Commit cfac8e18 authored by Somnath, Suhas's avatar Somnath, Suhas
Browse files

Removed many instances of python 2 print statements

parent 0bcd5e40
......@@ -580,8 +580,8 @@ class BELoopModel(Model):
warn('Error - could not reshape provided raw data chunk...')
return None
if verbose:
print 'Shape of N dimensional dataset:', fit_nd.shape
print 'Dimensions of order:', dim_names_orig
print('Shape of N dimensional dataset:', fit_nd.shape)
print('Dimensions of order:', dim_names_orig)
# order_dc_outside_nd = np.roll(range(fit_nd.ndim), -self._dc_offset_index)
# order_dc_offset_reverse = np.roll(range(fit_nd.ndim), self._dc_offset_index)
......@@ -594,13 +594,13 @@ class BELoopModel(Model):
fit_nd2 = np.transpose(fit_nd, tuple(order_dc_outside_nd))
dim_names_dc_out = dim_names_orig[order_dc_outside_nd]
if verbose:
print 'originally:', fit_nd.shape, ', after moving DC offset outside:', fit_nd2.shape
print 'new dim names:', dim_names_dc_out
print('originally:', fit_nd.shape, ', after moving DC offset outside:', fit_nd2.shape)
print('new dim names:', dim_names_dc_out)
# step 6: reshape the ND data to 2D arrays
loops_2d = np.reshape(fit_nd2, (fit_nd2.shape[0], -1))
if verbose:
print 'Loops ready to be projected of shape (Vdc, all other dims besides FORC):', loops_2d.shape
print('Loops ready to be projected of shape (Vdc, all other dims besides FORC):', loops_2d.shape)
return loops_2d, order_dc_offset_reverse, fit_nd2.shape
......@@ -628,15 +628,15 @@ class BELoopModel(Model):
Projected loops reshaped to the original chronological order in which the data was acquired
"""
if verbose:
print 'Projected loops of shape:', projected_loops_2d.shape, ', need to bring to:', nd_mat_shape_dc_first
print('Projected loops of shape:', projected_loops_2d.shape, ', need to bring to:', nd_mat_shape_dc_first)
# Step 9: Reshape back to same shape as fit_Nd2:
projected_loops_nd = np.reshape(projected_loops_2d, nd_mat_shape_dc_first)
if verbose:
print 'Projected loops reshaped to N dimensions :', projected_loops_nd.shape
print('Projected loops reshaped to N dimensions :', projected_loops_nd.shape)
# Step 10: Move Vdc back inwards. Only for projected loop
projected_loops_nd_2 = np.transpose(projected_loops_nd, order_dc_offset_reverse)
if verbose:
print 'Projected loops after moving DC offset inwards:', projected_loops_nd_2.shape
print('Projected loops after moving DC offset inwards:', projected_loops_nd_2.shape)
# step 11: reshape back to 2D
proj_loops_2d, success = reshape_from_Ndims(projected_loops_nd_2,
h5_pos=None,
......@@ -646,7 +646,7 @@ class BELoopModel(Model):
warn('unable to reshape projected loops')
return None
if verbose:
print 'loops shape after collapsing dimensions:', proj_loops_2d.shape
print('loops shape after collapsing dimensions:', proj_loops_2d.shape)
return proj_loops_2d
......@@ -671,7 +671,7 @@ class BELoopModel(Model):
Loop metrics reshaped to the original chronological order in which the data was acquired
"""
if verbose:
print 'Loop metrics of shape:', raw_results.shape
print('Loop metrics of shape:', raw_results.shape)
# Step 9: Reshape back to same shape as fit_Nd2:
if not self._met_all_but_forc_inds:
spec_inds = None
......@@ -681,7 +681,7 @@ class BELoopModel(Model):
loop_metrics_nd = np.reshape(raw_results, nd_mat_shape_dc_first[1:])
if verbose:
print 'Loop metrics reshaped to N dimensions :', loop_metrics_nd.shape
print('Loop metrics reshaped to N dimensions :', loop_metrics_nd.shape)
# step 11: reshape back to 2D
metrics_2d, success = reshape_from_Ndims(loop_metrics_nd,
......@@ -691,7 +691,7 @@ class BELoopModel(Model):
warn('unable to reshape ND results back to 2D')
return None
if verbose:
print 'metrics shape after collapsing dimensions:', metrics_2d.shape
print('metrics shape after collapsing dimensions:', metrics_2d.shape)
return metrics_2d
......
......@@ -3,6 +3,7 @@ import array
import StringIO
import logging
import re
# mfm 2013-05-21 do we need the numpy array stuff? The python array module
# allows us to store arrays easily and efficiently. How do we deal
# with arrays of complex data? We could use numpy arrays with custom dtypes
......@@ -23,7 +24,7 @@ verbose = False
treat_as_string_names = ['.*Name']
def get_from_file(f, stype):
#print "reading", stype, "size", struct.calcsize(stype)
# print("reading", stype, "size", struct.calcsize(stype))
src = f.read(struct.calcsize(stype))
assert(len(src) == struct.calcsize(stype))
d = struct.unpack(stype, src)
......@@ -103,7 +104,7 @@ def parse_dm_header(f, outdata=None):
start = f.tell()
ret = parse_dm_tag_root(f, outdata)
end = f.tell()
# print "fs", file_size, end - start, (end-start)%8
# print("fs", file_size, end - start, (end-start)%8)
# mfm 2013-07-11 the file_size value is not always
# end-start, sometimes there seems to be an extra 4 bytes,
# other times not. Let's just ignore it for the moment
......@@ -120,28 +121,28 @@ def parse_dm_tag_root(f, outdata=None):
put_into_file(f, "> b b l", is_dict, _open, num_tags)
if not is_dict:
if verbose:
print "list:", outdata
print("list:", outdata)
for subdata in outdata:
parse_dm_tag_entry(f, subdata, None)
else:
if verbose:
print "dict:", outdata
print("dict:", outdata)
for key in outdata:
if verbose:
print "Writing", key, outdata[key]
print("Writing", key, outdata[key])
assert(key is not None)
parse_dm_tag_entry(f, outdata[key], key)
else:
is_dict, _open, num_tags = get_from_file(f, "> b b l")
if verbose:
print "New tag root", is_dict, _open, num_tags
print("New tag root", is_dict, _open, num_tags)
if is_dict:
new_obj = {}
for i in range(num_tags):
name, data = parse_dm_tag_entry(f)
assert(name is not None)
if verbose:
print "Read name", name, "at", f.tell()
print("Read name", name, "at", f.tell())
new_obj[name] = data
else:
new_obj = []
......@@ -149,7 +150,7 @@ def parse_dm_tag_root(f, outdata=None):
name, data = parse_dm_tag_entry(f)
assert(name is None)
if verbose:
print "appending...", i, "at", f.tell()
print("appending...", i, "at", f.tell())
new_obj.append(data)
return new_obj
......@@ -206,7 +207,7 @@ def parse_dm_tag_data(f, outdata=None):
# ie can all numbers be doubles or ints, and we have lists
_, data_type = get_structdmtypes_for_python_typeorobject(outdata)
if verbose:
print "treating {} as {}".format(outdata, data_type)
print("treating {} as {}".format(outdata, data_type))
if not data_type:
raise Exception("Unsupported type: {}".format(type(outdata)))
_delim = "%%%%"
......@@ -349,7 +350,7 @@ def dm_read_string(f, outdata=None):
slen = get_from_file(f, ">L")
raws = get_from_file(f, ">" + str(slen) + "s")
if verbose:
print "Got String", unicode(raws, "utf_16_le"), "at", f.tell()
print("Got String", unicode(raws, "utf_16_le"), "at", f.tell())
return unicode(raws, "utf_16_le"), header_size
dm_types[get_dmtype_for_name('string')] = dm_read_string
......@@ -400,7 +401,7 @@ def dm_read_struct(f, outdata=None):
else:
types, header = dm_read_struct_types(f)
if verbose:
print "Found struct with types", types, "at", f.tell()
print("Found struct with types", types, "at", f.tell())
ret = []
for t in types:
......@@ -453,8 +454,8 @@ def dm_read_array(f, outdata=None):
types, struct_header = dm_read_struct_types(f)
alen = get_from_file(f, "> L")
if verbose:
print types
print "Array of structs! types %s, len %d" % (",".join(map(str, types)), alen), "at", f.tell()
print(types)
print("Array of structs! types %s, len %d" % (",".join(map(str, types)), alen), "at", f.tell())
ret = structarray([get_structchar_for_dmtype(d) for d in types])
ret.from_file(f, alen)
return ret, array_header + struct_header
......@@ -467,15 +468,15 @@ def dm_read_array(f, outdata=None):
ret = array.array(struct_char)
alen = get_from_file(f, "> L")
if verbose:
print "Array type %d len %d struct %c size %d" % (
dtype, alen, struct_char, struct.calcsize(struct_char)), "at", f.tell()
print("Array type %d len %d struct %c size %d" % (
dtype, alen, struct_char, struct.calcsize(struct_char)), "at", f.tell())
if alen:
# faster to read <1024f than <f 1024 times. probly
# stype = "<" + str(alen) + dm_simple_names[dtype][1]
# ret = get_from_file(f, stype)
read_array(f, ret, alen)
if verbose:
print "Done Array type %d len %d" % (dtype, alen), "at", f.tell()
print("Done Array type %d len %d" % (dtype, alen), "at", f.tell())
return ret, array_header
dm_types[get_dmtype_for_name('array')] = dm_read_array
......@@ -288,8 +288,8 @@ def normalizeBEresponse(spectrogram_mat, FFT_BE_wave, harmonic):
scaling_factor = np.fft.fftshift(np.fft.fft(BE_wave**2))/(2*np.exp(1j*3*np.pi*0.5))
elif harmonic == 3:
scaling_factor = np.fft.fftshift(np.fft.fft(BE_wave**3))/(4*np.exp(1j*np.pi))
elif harmonic>=4:
print "Warning these high harmonics are not supported in translator."
elif harmonic >= 4:
print("Warning these high harmonics are not supported in translator.")
# Generate transfer functions
F_AO_spectrogram = np.transpose(np.tile(FFT_BE_wave/scaling_factor, [spectrogram_mat.shape[1], 1]))
......@@ -1287,7 +1287,7 @@ class BEHistogram():
max_resp = []
min_resp = []
print 'Creating BEHistogram for Plot Group {}'.format(p_group.name)
print('Creating BEHistogram for Plot Group {}'.format(p_group.name))
udvs_lab = p_group.attrs['Name']
udvs_col = h5_udvs[im][h5_udvs[im].attrs[udvs_lab]]
actual_udvs_steps = np.where(np.isnan(udvs_col)==False)[0]
......@@ -1337,7 +1337,7 @@ class BEHistogram():
"""
free_mem = getAvailableMem()
if debug: print 'We have {} bytes of memory available'.format(free_mem)
if debug: print('We have {} bytes of memory available'.format(free_mem))
self.max_mem = min(max_mem_mb*1024**2,0.75*free_mem)
"""
......@@ -1372,17 +1372,17 @@ class BEHistogram():
self.N_bins = np.size(freqs_mat)
self.N_freqs = np.size(np.unique(freqs_mat))
# print 'There are {} total frequencies in this dataset'.format(self.N_bins)
# print('There are {} total frequencies in this dataset'.format(self.N_bins))
del freqs_mat, spec_ind_mat
self.N_pixels = np.shape(h5_main)[1]
# print 'There are {} pixels in this dataset'.format(self.N_pixels)
# print('There are {} pixels in this dataset'.format(self.N_pixels))
self.N_y_bins = np.int(np.min( (max_bins, np.rint(np.sqrt(self.N_pixels*self.N_spectral_steps)))))
# self.N_y_bins = np.min( (max_bins, np.rint(2*(self.N_pixels*self.N_spectral_steps)**(1.0/3.0))))
# print '{} bins will be used'.format(self.N_y_bins)
# print('{} bins will be used'.format(self.N_y_bins))
ds_hist = self.__datasetHist(h5_main, active_udvs_steps, x_hist,debug)
ds_hist = self.__datasetHist(h5_main, active_udvs_steps, x_hist, debug)
return ds_hist
......@@ -1557,9 +1557,9 @@ class BEHistogram():
loop over pixels
"""
for ichunk in range(len(pix_chunks)-1):
if debug: print 'pixel chunk',ichunk
if debug: print('pixel chunk', ichunk)
chunk = range(pix_chunks[ichunk],pix_chunks[ichunk+1])
chunk = range(pix_chunks[ichunk], pix_chunks[ichunk+1])
"""
Loop over active UDVS steps
......
......@@ -49,7 +49,7 @@ def buildHistogram(x_hist, data_mat, N_x_bins, N_y_bins, weighting_vec=1, min_re
min_resp = np.minb(y_hist)
if max_resp is None:
max_resp = np.max(y_hist)
if debug: print 'min_resp', min_resp, 'max_resp', max_resp
if debug: print('min_resp', min_resp, 'max_resp', max_resp)
y_hist = __scale_and_descritize(y_hist, N_y_bins, max_resp, min_resp, debug)
......@@ -57,8 +57,8 @@ def buildHistogram(x_hist, data_mat, N_x_bins, N_y_bins, weighting_vec=1, min_re
Combine x_hist and y_hist into one matrix
'''
if debug:
print np.shape(x_hist)
print np.shape(y_hist)
print(np.shape(x_hist))
print(np.shape(y_hist))
try:
group_idx = np.zeros((2, x_hist.size), dtype=np.int32)
......@@ -71,9 +71,9 @@ def buildHistogram(x_hist, data_mat, N_x_bins, N_y_bins, weighting_vec=1, min_re
Aggregate matrix for histogram of current chunk
'''
if debug:
print np.shape(group_idx)
print np.shape(weighting_vec)
print N_x_bins,N_y_bins
print(np.shape(group_idx))
print(np.shape(weighting_vec))
print(N_x_bins, N_y_bins)
try:
pixel_hist = aggregate_np(group_idx, weighting_vec, func='sum', size=(N_x_bins, N_y_bins), dtype=np.int32)
......@@ -108,6 +108,6 @@ def __scale_and_discretize(y_hist, N_y_bins, max_resp, min_resp, debug=False):
'''
y_hist = np.rint(y_hist * (N_y_bins - 1))
if debug:
print 'ymin', min(y_hist), 'ymax', max(y_hist)
print('ymin', min(y_hist), 'ymax', max(y_hist))
return y_hist
......@@ -62,14 +62,14 @@ def doSVD(h5_main, num_comps=None):
C.Smith -- We might need to put a lower limit on num_comps in the future. I don't
know enough about svd to be sure.
'''
print 'Performing SVD decomposition'
print('Performing SVD decomposition')
U, S, V = randomized_svd(func(h5_main), num_comps, n_iter=3)
svd_type = 'sklearn-randomized'
print 'SVD took {} seconds. Writing results to file.'.format((time.time() - t1))
print('SVD took {} seconds. Writing results to file.'.format((time.time() - t1)))
'''
Create datasets for V and S, deleting original arrays afterward to save
......@@ -249,7 +249,7 @@ def rebuild_svd(h5_main, components=None, cores=None, max_RAM_mb=1024):
# Ensuring that at least one core is available for use / 2 cores are available for other use
max_cores = max(1, cpu_count() - 2)
# print 'max_cores',max_cores
# print('max_cores',max_cores)
if cores is not None:
cores = min(round(abs(cores)), max_cores)
else:
......
......@@ -6,11 +6,12 @@ Created on Mar 14, 2016
import os
import datetime
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog='PySPM Versioner', description='Increments the version number for PySPM')
parser.add_argument('--manual',type=str,default=None)
parser.add_argument('--minor',default=False,action='store_true')
parser.add_argument('--major',default=False,action='store_true')
parser.add_argument('--manual', type=str, default=None)
parser.add_argument('--minor', default=False, action='store_true')
parser.add_argument('--major', default=False, action='store_true')
args = parser.parse_args()
new_minor = args.minor
new_major = args.major
......@@ -28,17 +29,17 @@ if __name__ == '__main__':
vc_time = 0
vm_time = 0
v_time = 0
dir_version = [0,0,0]
# print root, 'contains'
# print 'directories', dirs
# print 'files', files
dir_version = [0, 0, 0]
# print(root, 'contains')
# print('directories', dirs)
# print('files', files)
f_time = 0
for file in files:
if file.split('.')[1] == 'pyc':
continue
elif file == self_name:
continue
file_path = os.path.join(root,file)
file_path = os.path.join(root, file)
f_stats = os.stat(file_path)
if file == '__version__.py':
vc_time = f_stats[9]
......@@ -46,18 +47,18 @@ if __name__ == '__main__':
v_time = max([vc_time, vm_time])
fc_time = f_stats[9]
fm_time = f_stats[8]
f_time = max([fc_time,fm_time,f_time])
# print '{} was created {} and modified {}.'.format(file, fc_time, fm_time)
f_time = max([fc_time, fm_time, f_time])
# print('{} was created {} and modified {}.'.format(file, fc_time, fm_time)
if v_time == 0:
# print 'No version file found. Will create new at version 0.0.1'
v_file = open(os.path.join(root,'__version__.py'),'w')
# print('No version file found. Will create new at version 0.0.1')
v_file = open(os.path.join(root, '__version__.py'), 'w')
new_version = True
elif root == main_dir:
continue
else:
# print 'Version file found. Reading old version number.'
v_file = open(os.path.join(root,'__version__.py'),'r+')
# print('Version file found. Reading old version number.'))
v_file = open(os.path.join(root, '__version__.py'), 'r+')
for iline, line in enumerate(v_file.readlines()):
line = line.split()
if line == []:
......@@ -73,36 +74,36 @@ if __name__ == '__main__':
new_version = f_time < v_time
if dir_version == [0,0,0]:
# print 'Blank version file.'
if dir_version == [0, 0, 0]:
# print('Blank version file.')
new_version = True
# print 'Old version was {}.{}.{}'.format(*dir_version)
# print('Old version was {}.{}.{}'.format(*dir_version))
if new_version:
print 'Files have been modified since last version.'
print('Files have been modified since last version.')
new_main_version = True
dir_version[2]+=1
dir_version[2] += 1
if new_minor:
dir_version[1]+= 1
dir_version[1] += 1
dir_version[2] = 0
if new_major:
dir_version[0]+= 1
dir_version[0] += 1
dir_version[1] = 0
dir_version[2] = 0
v_file.seek(0)
v_file.write('major\t=\t{}\n'.format(dir_version[0]))
v_file.write('minor\t=\t{}\n'.format(dir_version[1]))
v_file.write('micro\t=\t{}\n'.format(dir_version[2]))
print 'New version is {}.{}.{}'.format(*dir_version)
print('New version is {}.{}.{}'.format(*dir_version))
v_file.close()
if new_main_version:
mv_file = open(os.path.join(main_dir,'__version__.py'),'r+')
mv_file = open(os.path.join(main_dir, '__version__.py'), 'r+')
mv_version = '0.0.1'
ver_date = datetime.datetime.now()
mv_date = '{}/{}/{}'.format(ver_date.month,ver_date.day,ver_date.year)
mv_date = '{}/{}/{}'.format(ver_date.month, ver_date.day, ver_date.year)
for line in mv_file.readlines():
print line
print(line)
if line.strip() == '':
continue
field, value = line.split('=')
......@@ -113,29 +114,29 @@ if __name__ == '__main__':
elif field == 'time':
mv_time = value.strip['\'']
mv_major,mv_minor,mv_micro = mv_version.split('.')
mv_major, mv_minor, mv_micro = mv_version.split('.')
mv_micro = str(int(mv_micro)+1)
if new_minor:
mv_minor+= 1
mv_minor += 1
mv_micro = 0
if new_major:
mv_major+= 1
mv_major += 1
mv_minor = 0
mv_micro = 0
if args.manual:
mv_version = args.manual
else:
mv_version = '.'.join([mv_major,mv_minor,mv_micro])
mv_time = '{}:{}:{}'.format(ver_date.hour,ver_date.minute,ver_date.second)
mv_version = '.'.join([mv_major, mv_minor, mv_micro])
mv_time = '{}:{}:{}'.format(ver_date.hour, ver_date.minute, ver_date.second)
mv_file.seek(0)
mv_file.truncate()
mv_file.write('version = {} \n'.format(mv_version))
mv_file.write('date = {} \n'.format(mv_date))
mv_file.write('time = {} \n'.format(mv_time))
print 'New main version is {}'.format(mv_version)
print 'Vesion date is {}'.format(mv_date)
print('New main version is {}'.format(mv_version))
print('Vesion date is {}'.format(mv_date))
pass
\ No newline at end of file
......@@ -437,7 +437,7 @@ def plot_loops(excit_wfm, datasets, line_colors=[], dataset_names=[], evenly_spa
for dataset, col_val in zip(datasets, line_colors):
axes_lin[count].plot(excit_wfm[l_resp_ind:r_resp_ind], dataset[posn, l_resp_ind:r_resp_ind], color=col_val)
if h5_pos is not None:
# print 'Row ' + str(h5_pos[posn,1]) + ' Col ' + str(h5_pos[posn,0])
# print('Row ' + str(h5_pos[posn,1]) + ' Col ' + str(h5_pos[posn,0]))
axes_lin[count].set_title('Row ' + str(h5_pos[posn, 1]) + ' Col ' + str(h5_pos[posn, 0]), fontsize=12)
else:
axes_lin[count].set_title(subtitles + ' ' + str(posn), fontsize=12)
......@@ -1005,10 +1005,10 @@ def plot_cluster_dendrogram(label_mat, e_vals, num_comp, num_cluster, mode='Full
mode = 'Full'
if mode == 'Full':
print 'Creating full dendrogram from clusters'
print('Creating full dendrogram from clusters')
mode = None
elif mode == 'Truncated':
print 'Creating truncated dendrogram from clusters. Will stop at {}.'.format(last)
print('Creating truncated dendrogram from clusters. Will stop at {}.'.format(last))
mode = 'lastp'
else:
raise ValueError('Error: Unknown mode requested for plotting dendrograms. mode={}'.format(mode))
......@@ -1127,8 +1127,8 @@ def plot_2d_spectrogram(mean_spectrogram, freq, title, cmap=None, figure_path=No
freq *= 1E-3 # to kHz
fig, ax = plt.subplots(nrows=2, ncols=1, sharex=True)
# print mean_spectrogram.shape
# print freq.shape
# print(mean_spectrogram.shape)
# print(freq.shape)
ax[0].imshow(np.abs(mean_spectrogram), interpolation='nearest', cmap=col_map,
extent=[freq[0], freq[-1], mean_spectrogram.shape[0], 0], **kwargs)
ax[0].set_title('Amplitude')
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment