diff --git a/POVME/POVME2_GUI.py b/POVME/POVME2_GUI.py index 58cddff..e3c1760 100644 --- a/POVME/POVME2_GUI.py +++ b/POVME/POVME2_GUI.py @@ -1,6 +1,6 @@ #!/usr/bin/python -from Tkinter import * +from tkinter import * #------------------------------------------------------------------------------# # # # POVME2_GUI # @@ -12,7 +12,7 @@ def __init__(self,Master=None,**kw): #Your code here # - apply(Frame.__init__,(self,Master),kw) + Frame.__init__(*(self,Master), **kw) self.__Frame2 = Frame(self) self.__Frame2.pack(side='top') self.__Label1 = Label(self.__Frame2,background='#000000' @@ -828,8 +828,8 @@ def is_int(self, str): except ValueError: return False -import tkMessageBox -import tkFileDialog +import tkinter.messagebox +import tkinter.filedialog import os #import shutil import sys diff --git a/POVME/POVME3.py b/POVME/POVME3.py index 0b46f09..d231625 100755 --- a/POVME/POVME3.py +++ b/POVME/POVME3.py @@ -21,13 +21,14 @@ import POVME.packages.binana.peel as peel import multiprocessing import platform +from functools import reduce #from guppy import hpy #hp=hpy() -try: from cStringIO import StringIO -except: from StringIO import StringIO +try: from io import StringIO +except: from io import StringIO from scipy.spatial.distance import cdist from scipy.spatial.distance import pdist @@ -89,7 +90,7 @@ def log(astr, parameters): ''' # Print the output to the screen. - print astr + print(astr) # Save it to the output file as well. try: @@ -135,7 +136,7 @@ def __init__(self, inputs, num_processors, task_class): self.results = [] if num_processors != 1 and (platform.system().upper()[:3] == "WIN" or "NT" in platform.system().upper()): # If it's windows, you can only use one processor. - print "WARNING: Use of multiple processors is not supported in Windows. Proceeding with one processor..." + print("WARNING: Use of multiple processors is not supported in Windows. Proceeding with one processor...") num_processors = 1 if num_processors == 1: # so just running on 1 processor, perhaps under windows @@ -157,7 +158,7 @@ def __init__(self, inputs, num_processors, task_class): # reduce the number of processors if too many have been specified if len(inputs) < num_processors: - print 'Too many processors requested (%i requested, vs %i frames to analyze). Lowering number requested.' %(num_processors, len(inputs)) + print('Too many processors requested (%i requested, vs %i frames to analyze). Lowering number requested.' %(num_processors, len(inputs))) num_processors = len(inputs) if len(inputs) == 0: # if there are no inputs, there's nothing to do. @@ -849,6 +850,7 @@ def determineFirstConvexHull(index_and_pdbs,parameters): hydros = this_pdb.selections.select_atoms({'element_stripped':['H']}) not_hydros = this_pdb.selections.invert_selection(hydros) not_hydros_coors = this_pdb.information.get_coordinates()[not_hydros] + break akl_toussaint_pts = convex_hull_3d.akl_toussaint(not_hydros_coors) # quickly reduces input size @@ -878,9 +880,9 @@ def value_func(self, item, results_queue, color = False): results_queue -- A multiprocessing.Queue() object for storing the calculation output """ - print '---------------------------------' - print 'STARTING CALC VOLUME'#,hp.heap() - print '---------------------------------' + print('---------------------------------') + print('STARTING CALC VOLUME')#,hp.heap() + print('---------------------------------') frame_indx = item[0] @@ -1140,7 +1142,7 @@ def value_func(self, item, results_queue, color = False): extra_data_to_add['CalculateSurfaceArea'] = surfA #print "Surface Area for frame %r: %r" %(frame_indx, len(surfacePointsSet.intersection(adjacentPointsSet))) #if parameters[SaveIndividualPocketVolumes] == True: - for color in coloredMaps.keys(): + for color in list(coloredMaps.keys()): #First make a copy of coloredMaps[color] that only contains the points over the intensity threshold #print color, coloredMaps[color] #log('AAAAA' + color + str(frame_indx), parameters) @@ -1188,9 +1190,9 @@ def value_func(self, item, results_queue, color = False): #else: # log("\tFrame " + str(frame_indx) + ": " + repr(volume) + " A^3", parameters) self.results.append((frame_indx, volume, extra_data_to_add)) - print '---------------------------------' - print 'FINISHING CALC VOLUME'#,hp.heap() - print '---------------------------------' + print('---------------------------------') + print('FINISHING CALC VOLUME')#,hp.heap() + print('---------------------------------') #if len(extra_data_to_add.keys()) != 0: #else: self.results.append((frame_indx, volume)) @@ -1219,8 +1221,8 @@ def value_func(self, item, results_queue): pdb.fileio.load_pym_into(pym_filename) ligand_atoms = pdb.select_atoms({'resname_stripped':parameters[DefinePocketByLigand]}) - print parameters[DefinePocketByLigand] - print ligand_atoms + print(parameters[DefinePocketByLigand]) + print(ligand_atoms) ligand_coords = pdb.get_coordinates()[ligand_atoms].round() ligand_coords_set = set([tuple(row) for row in ligand_coords]) self.results.append(ligand_coords_set) @@ -1597,7 +1599,7 @@ def __init__ (self, FileName): # has more than 2 members, python will crash. However, each entity in self.entities should have only 2 members # due to the processing code above. for parameter,values in self.entities: - print parameter, values + print(parameter, values) #if unexpected config keyword in config file, throw this exception if parameter not in all_parameters: raise Exception('%s is not a valid parameter. Valid parameters are: %r' %(parameter,all_parameters)) @@ -1683,13 +1685,13 @@ def load_multi_frame_pdb(self, filename, parameters): log("", parameters) log("Reading frames from " + filename, parameters) - f = open(filename, 'rb') + f = open(filename, 'r') while True: if parameters[NumFrames] != -1: if len(pdb_strings) >= parameters[NumFrames]: break - line = f.readline() + line = str(f.readline()) if len(line) == 0: pdb_strings.append(growing_string) @@ -1717,18 +1719,18 @@ def __init__(self, argv): argv -- A list of the command-line arguments. ''' - print '---------------------------------' - print 'START'#,hp.heap() - print '---------------------------------' + print('---------------------------------') + print('START')#,hp.heap() + print('---------------------------------') start_time = time.time() # Load the configuration file if len(argv) == 1: - print "\nPOVME " + version - print "\nPlease specify the input file from the command line!\n\nExample: python POVME.py input_file.ini" + print("\nPOVME " + version) + print("\nPlease specify the input file from the command line!\n\nExample: python POVME.py input_file.ini") self.reference({}) - print + print() sys.exit() config = ConfigFile(argv[1]) @@ -1768,7 +1770,7 @@ def __init__(self, argv): # print out parameters #consider this section for deletion log("Parameters:", parameters) - for i in parameters.keys(): + for i in list(parameters.keys()): if i == 'NumFrames' and parameters[NumFrames] == -1: continue # So only show this parameter if it's value is not the default. @@ -1779,9 +1781,9 @@ def __init__(self, argv): if parameters[i] != "": log("\t" + str(i) + ": " + str(parameters[i]), parameters) #this section ^ total garbage - print '---------------------------------' - print 'PARAMETERS DEFINED'#,hp.heap() - print '---------------------------------' + print('---------------------------------') + print('PARAMETERS DEFINED')#,hp.heap() + print('---------------------------------') pts = None @@ -1789,14 +1791,14 @@ def __init__(self, argv): # load the points in they aren't already present - print '---------------------------------' - print 'ABOUT TO LOAD RECEPTORS'#,hp.heap() - print '---------------------------------' + print('---------------------------------') + print('ABOUT TO LOAD RECEPTORS')#,hp.heap() + print('---------------------------------') # load the PDB frames index_and_pdbs = self.load_multi_frame_pdb(parameters[PDBFileName], parameters) - print '---------------------------------' - print 'RECEPTORS LOADED'#,hp.heap() - print '---------------------------------' + print('---------------------------------') + print('RECEPTORS LOADED')#,hp.heap() + print('---------------------------------') # calculate all the volumes log("", parameters) @@ -1968,9 +1970,9 @@ def __init__(self, argv): log("Calculating the pocket volume of each frame", parameters) tmp = Multithreading([(index, pdb_object, parameters) for index, pdb_object in index_and_pdbs], parameters[NumProcessors], MultithreadingCalcVolumeTask) - print '---------------------------------' - print 'VOLUMES CALCULATED'#,hp.heap() - print '---------------------------------' + print('---------------------------------') + print('VOLUMES CALCULATED')#,hp.heap() + print('---------------------------------') # delete the temp swap directory if necessary @@ -2015,7 +2017,7 @@ def __init__(self, argv): if parameters[CompressOutput] == True: traj_file = gzip.open(parameters[OutputFilenamePrefix] + "volume_trajectory.pdb.gz", 'wb') else: traj_file = open(parameters[OutputFilenamePrefix] + "volume_trajectory.pdb", 'w') - for frame_index in range(1,len(volume_dic.keys())+1): + for frame_index in range(1,len(list(volume_dic.keys()))+1): if parameters[CompressOutput] == True: frame_file = gzip.open(parameters[OutputFrameFilenamePrefix] + "frame_" + str(frame_index) + ".pdb.gz", 'rb') else: frame_file = open(parameters[OutputFrameFilenamePrefix] + "frame_" + str(frame_index) + ".pdb", 'r') @@ -2028,12 +2030,12 @@ def __init__(self, argv): traj_file.close() #if parameters[SaveColoredMap] == True: - colors = tmp.results[0][2]['SaveColoredMap'].keys() + colors = list(tmp.results[0][2]['SaveColoredMap'].keys()) for color in colors: if parameters[CompressOutput] == True: traj_file = gzip.open(parameters[OutputFilenamePrefix] + color + "_trajectory.pdb.gz", 'wb') else: traj_file = open(parameters[OutputFilenamePrefix] + color + "_volume_trajectory.pdb", 'w') - for frame_index in range(1,len(volume_dic.keys())+1): + for frame_index in range(1,len(list(volume_dic.keys()))+1): if parameters[CompressOutput] == True: frame_file = gzip.open(parameters[OutputFrameFilenamePrefix] + "frame_" + str(frame_index) + "_" + color + ".pdb.gz", 'rb') else: frame_file = open(parameters[OutputFrameFilenamePrefix] + "frame_" + str(frame_index) + "_" + color + ".pdb", 'r') @@ -2067,9 +2069,9 @@ def __init__(self, argv): - print '---------------------------------' - print 'ABOUT TO CALCULATE OCCUPANCY AVERAGE'#,hp.heap() - print '---------------------------------' + print('---------------------------------') + print('ABOUT TO CALCULATE OCCUPANCY AVERAGE')#,hp.heap() + print('---------------------------------') # Generate the frame-averages volumetric density map #if parameters[SaveVolumetricDensityDX] == True or parameters[SaveVolumetricDensityNpy] == True: unique_points = {} @@ -2127,22 +2129,22 @@ def __init__(self, argv): - print '---------------------------------' - print 'CALCULATED OCCUPANCY AVERAGE'#,hp.heap() - print '---------------------------------' + print('---------------------------------') + print('CALCULATED OCCUPANCY AVERAGE')#,hp.heap() + print('---------------------------------') #if parameters[SaveColoredMap] == True: - print '---------------------------------' - print 'ABOUT TO CALCULATE COLOR MAPS'#,hp.heap() - print '---------------------------------' + print('---------------------------------') + print('ABOUT TO CALCULATE COLOR MAPS')#,hp.heap() + print('---------------------------------') #print 'Saving Colored Maps!' #start = time.time() - colors = tmp.results[0][2]['SaveColoredMap'].keys() + colors = list(tmp.results[0][2]['SaveColoredMap'].keys()) for color in colors: overall_min = numpy.ones(3) * 1e100 overall_max = numpy.ones(3) * -1e100 @@ -2197,9 +2199,9 @@ def __init__(self, argv): #if parameters[SaveVolumetricDensityNpy] == True: numpy.save(colorParams['OutputFrameFilenamePrefix']+'volumetric_density.npy', all_pts) #print 'time to save map for %s: %s' %(color, str(time.time()-start3)) - print '---------------------------------' - print 'CALCULATED COLOR MAPS'#,hp.heap() - print '---------------------------------' + print('---------------------------------') + print('CALCULATED COLOR MAPS')#,hp.heap() + print('---------------------------------') if __name__ == "__main__": dorun = runit(sys.argv) diff --git a/POVME/POVME_pocket_id.py b/POVME/POVME_pocket_id.py index 6c40ba7..785611e 100644 --- a/POVME/POVME_pocket_id.py +++ b/POVME/POVME_pocket_id.py @@ -173,7 +173,7 @@ def select_atoms(self, selection_criteria): try: selection = numpy.ones(len(self.__parent_molecule.get_atom_information()), dtype=bool) # start assuming everything is selected - for key in selection_criteria.keys(): + for key in list(selection_criteria.keys()): vals = selection_criteria[key] @@ -195,8 +195,8 @@ def select_atoms(self, selection_criteria): # now get the indices of the selection return numpy.nonzero(selection)[0] except: - print "ERROR: Could not make the selection. Existing fields:" - print "\t" + ", ".join(self.__parent_molecule.get_atom_information().dtype.names) + print("ERROR: Could not make the selection. Existing fields:") + print("\t" + ", ".join(self.__parent_molecule.get_atom_information().dtype.names)) sys.exit(0) def invert_selection(self, selection): @@ -611,7 +611,7 @@ def runit(self, running, mutex, results_queue, items): results_queue.put(self.results) def value_func(self, item, results_queue): # this is the function that changes through inheritance - print item # here's where you do something + print(item) # here's where you do something self.results.append(item) # here save the results for later compilation # You'll also need a class representing a box of points, with associated definitions @@ -638,7 +638,7 @@ def __init__(self, box, reso): max_z = self.__snap_float(box[1][2], reso) + 1.1 * reso x, y, z = numpy.mgrid[min_x:max_x:reso, min_y:max_y:reso, min_z:max_z:reso] - self.points = numpy.array(zip(x.ravel(), y.ravel(), z.ravel())) + self.points = numpy.array(list(zip(x.ravel(), y.ravel(), z.ravel()))) def __snap_float(self, val, reso): """Snaps an arbitrary point to the nearest grid point. @@ -777,7 +777,7 @@ def filter_isolated_points_until_no_change(self, reso, number_of_neighbors): # calculate the pairwise distances between all box points box_of_pts_distance_tree = spatial.KDTree(self.points) # note, in newer versions of scipy use cKDTree - print self.points + print(self.points) self.dist_matrix = box_of_pts_distance_tree.sparse_distance_matrix(box_of_pts_distance_tree, reso * numpy.sqrt(3.0) * 1.1).todense() # so kiddy-corner counted as a neighbor # note that the diagnol of self.dist_matrix is zero, as expected, but ones with dist > reso * numpy.sqrt(3.0) * 1.1 are also 0. Pretty convenient. @@ -941,7 +941,7 @@ def numpy_to_pdb(self, narray, letter, resname=""): help_lines.append('python pocket_id.py --filename rel1_example.pdb --pocket_detection_resolution 4.0 --pocket_measuring_resolution 1.0 --clashing_cutoff 3.0 --number_of_neighbors 4 --processors 1 --number_of_spheres 5 --sphere_padding 5.0 ') help_lines.append('') -def printit(text): print textwrap.fill(text, initial_indent='', subsequent_indent=' ') +def printit(text): print(textwrap.fill(text, initial_indent='', subsequent_indent=' ')) for line in help_lines: printit(line) if len(sys.argv[1:]) == 0: sys.exit(0) @@ -962,17 +962,17 @@ def printit(text): print textwrap.fill(text, initial_indent='', subsequent_inden for item in getopt.getopt(sys.argv[1:], '', [ 'filename=', 'pocket_detection_resolution=', 'pocket_measuring_resolution=', 'clashing_cutoff=', 'number_of_neighbors=', 'processors=', 'number_of_spheres=', 'sphere_padding=' ])[0]: params[item[0].replace('--','')] = item[1] if params['filename'] == '': - print "ERROR: Must specify the --filename parameter!" - print + print("ERROR: Must specify the --filename parameter!") + print() sys.exit(0) for key in ['number_of_neighbors', 'processors', 'number_of_spheres']: params[key] = int(params[key]) for key in ['pocket_detection_resolution', 'pocket_measuring_resolution', 'clashing_cutoff', 'sphere_padding']: params[key] = float(params[key]) -print 'Specified command-line arguments:' -print -for key in params: print " --" + key + ': ' + str(params[key]) -print +print('Specified command-line arguments:') +print() +for key in params: print(" --" + key + ': ' + str(params[key])) +print() # Step 1: Load in the protein @@ -982,13 +982,13 @@ def printit(text): print textwrap.fill(text, initial_indent='', subsequent_inden # Step 2: Get rid of hydogen atoms. They just slow stuff down. -print "Step 2. Removing hydrogen atoms..." +print("Step 2. Removing hydrogen atoms...") sel = molecule.selections.select_atoms({'element_stripped':'H'}) sel = molecule.selections.invert_selection(sel) molecule = molecule.selections.get_molecule_from_selection(sel) # Step 3: Calculate the convex hull of the protein alpha carbons. -print "Step 3. Calculating the convex hull of the PDB file..." +print("Step 3. Calculating the convex hull of the PDB file...") molecule_alpha_carbons = molecule.selections.get_molecule_from_selection(molecule.selections.select_atoms({'name_stripped':'CA'})) # Get a version of the protein with just the alpha carbons. In my experience, that's better for convex hull identification. Otherwise the program identifies shallow contors in the protein surface as pockets. convex_hull_3d = ConvexHull(molecule_alpha_carbons.get_coordinates()) @@ -1015,7 +1015,7 @@ def printit(text): print textwrap.fill(text, initial_indent='', subsequent_inden # Step 7. Now surround each of these points with higher density points that in the same regions. This is for getting a more detailed view of the identified pockets. if params['pocket_measuring_resolution'] != params['pocket_detection_resolution']: printit("Step 7. Flooding the identified pockets with points spaced " + str(params['pocket_measuring_resolution']) + " A apart for a more detailed measurement of the pocket volume...") - print "\tAdding points..." + print("\tAdding points...") box_pts.expand_around_existing_points(params['pocket_detection_resolution']/params['pocket_measuring_resolution'], params['pocket_measuring_resolution']) printit("\tRemoving points that fall outside the convex hull...") box_pts.remove_points_outside_convex_hull(convex_hull_3d) @@ -1055,14 +1055,14 @@ def printit(text): print textwrap.fill(text, initial_indent='', subsequent_inden f.write("REMARK CHAIN " + let_ids[cluster_num] + ": PointsInclusionSphere " + str(numpy.round(cluster_center[0],2)) + ' ' + str(numpy.round(cluster_center[1],2)) + ' ' + str(numpy.round(cluster_center[2],2)) + ' ' + str(numpy.round(cluster_radius + params['sphere_padding'],2)) + "\n") pts_string = pts_string + write_some_pdbs.numpy_to_pdb(cluster_pts, let_ids[cluster_num]) except: - print + print() printit("There was an error, but I don't think it was catastrophic. Could be that one of the pocket clusters was empty.") - print + print() f.write(pts_string) f.close() -print +print() printit("Done. See the pocket{n}.pdb files. Using a visualization program like VMD, identify which of these files includes the pocket you wish to measure. POVME Pocket ID has divided each pocket volume into " + str(params['number_of_spheres']) + " sections (i.e., PDB chains). In some cases, the pocket you're interested in might be included in a larger identified pocket, so feel free to use only certain sections of a given pocket as well.") printit("The POVME PointsInclusionSphere commands are located in the header of each pocket{n}.pdb file. A text editor can be used to copy and paste these commands into a POVME input file.") -print +print() diff --git a/POVME/examples/analysis_workflow_example/3-post_analysis/analyzeClusterMembershipInGroups.py b/POVME/examples/analysis_workflow_example/3-post_analysis/analyzeClusterMembershipInGroups.py index 762ed8a..c1da679 100644 --- a/POVME/examples/analysis_workflow_example/3-post_analysis/analyzeClusterMembershipInGroups.py +++ b/POVME/examples/analysis_workflow_example/3-post_analysis/analyzeClusterMembershipInGroups.py @@ -3,12 +3,12 @@ import re data = [i.split() for i in open('cluster_members.csv').readlines()] -print [len(i) for i in data] +print([len(i) for i in data]) nClusters = len(data) nCols = 3 nRows = (nClusters+(nCols-1))/nCols -print nClusters, nRows, nCols +print(nClusters, nRows, nCols) def getGroupPrefix(runPrefix): groupPrefix = runPrefix.split('run')[0].strip('_') @@ -23,7 +23,7 @@ def getGroupPrefix(runPrefix): #print member, result prefix = result[0][0].strip('_') groupPrefix = getGroupPrefix(prefix) - if not groupPrefix in groupPrefix2prefixes2frames.keys(): + if not groupPrefix in list(groupPrefix2prefixes2frames.keys()): groupPrefix2prefixes2frames[groupPrefix] = {} groupPrefix2prefixes2frames[groupPrefix][prefix] = [] frame = int(result[0][1]) @@ -31,7 +31,7 @@ def getGroupPrefix(runPrefix): groupPrefix2prefixes2frames[groupPrefix][prefix] += [frame] #print prefix2frames -prefixes = prefix2frames.keys() +prefixes = list(prefix2frames.keys()) prefixes.sort() nPrefixes = len(prefixes) groupPrefixes = list(set([getGroupPrefix(i) for i in prefixes])) @@ -49,7 +49,7 @@ def getGroupPrefix(runPrefix): frames = prefix2frames[prefix] frames.sort() #if prefix in prefixAndFrame2Col.keys(): - if groupPrefix in groupPrefixColsTaken.keys(): + if groupPrefix in list(groupPrefixColsTaken.keys()): #Note that frame numbering starts at 1 so off-by-1 won't be a problem here offset = max(groupPrefixColsTaken[groupPrefix]) else: @@ -60,8 +60,8 @@ def getGroupPrefix(runPrefix): #memberships = np.zeros((nClusters, nPrefixes, max([len(i) for i in prefix2frames.values()]))) #memberships = np.zeros((nClusters, nGroupPrefixes, max([len(i) for i in prefix2frames.values()]))) -memberships = np.zeros((nClusters, nGroupPrefixes, max([max(i) for i in groupPrefixColsTaken.values()]))) -print [(groupPrefix, max(i)) for groupPrefix, i in zip(groupPrefixColsTaken.keys(), groupPrefixColsTaken.values())] +memberships = np.zeros((nClusters, nGroupPrefixes, max([max(i) for i in list(groupPrefixColsTaken.values())]))) +print([(groupPrefix, max(i)) for groupPrefix, i in zip(list(groupPrefixColsTaken.keys()), list(groupPrefixColsTaken.values()))]) #1/0 memberships -= 1 for clusterIndex, cluster in enumerate(data): @@ -74,7 +74,7 @@ def getGroupPrefix(runPrefix): col = prefixAndFrame2Col[prefix][frame] #print member if sum(memberships[:,row,col]) > 0: - print memberships[:,row,col] + print(memberships[:,row,col]) 1/0 memberships[:,row,col] = 0 memberships[clusterIndex,row,col] = 1 @@ -87,7 +87,7 @@ def getGroupPrefix(runPrefix): aspect='auto') #pylab.yticks(range(len(prefixes)), [[]*4+[prefix] for i, prefix in enumerate(prefixes) if i%5==0]) #pylab.yticks(range(0,len(prefixes),1), prefixes ) - pylab.yticks(range(0,len(groupPrefixes),1), groupPrefixes ) + pylab.yticks(list(range(0,len(groupPrefixes),1)), groupPrefixes ) pylab.xlabel('Frame') pylab.title('Cluster %i' %(clusterIndex)) @@ -115,7 +115,7 @@ def getGroupPrefix(runPrefix): transitions = dict(((groupPrefix,np.zeros((nClusters, nClusters))) for groupPrefix in groupPrefixes)) for simulationIndex, groupPrefix in enumerate(groupPrefixes): simulationIndex = groupPrefixes.index(groupPrefix) - for prefix in groupPrefix2prefixes2frames[groupPrefix].keys(): + for prefix in list(groupPrefix2prefixes2frames[groupPrefix].keys()): currentCluster = None sliceStartCol = min(prefixAndFrame2Col[prefix].values()) sliceEndCol = max(prefixAndFrame2Col[prefix].values()) @@ -126,7 +126,7 @@ def getGroupPrefix(runPrefix): if len(nonzeros[0]) == 0: nextCluster = None elif len(nonzeros[0]) > 1: - print nextCluster + print(nextCluster) 1/0 else: nextCluster = nonzeros[0][0] @@ -211,9 +211,9 @@ def getGroupPrefix(runPrefix): # nodes nFramesPerClusterThisSim = [np.sum(memberships[clusterIndex,simulationIndex,:]==1) for clusterIndex in range(nClusters)] - print nFramesPerClusterThisSim + print(nFramesPerClusterThisSim) nodeSizes = [150. * float(i)/(np.mean(nFramesPerClusterAllSims)/nGroupPrefixes) for i in nFramesPerClusterThisSim] - print nodeSizes + print(nodeSizes) nx.draw_networkx_nodes(G, pos, node_size=nodeSizes) diff --git a/POVME/examples/analysis_workflow_example/3-post_analysis/analyzeClusterMembershipInGroups_HSP90.py b/POVME/examples/analysis_workflow_example/3-post_analysis/analyzeClusterMembershipInGroups_HSP90.py index 3d63c40..d746578 100644 --- a/POVME/examples/analysis_workflow_example/3-post_analysis/analyzeClusterMembershipInGroups_HSP90.py +++ b/POVME/examples/analysis_workflow_example/3-post_analysis/analyzeClusterMembershipInGroups_HSP90.py @@ -29,12 +29,12 @@ def fixPdbSdfFormatting(data): data = [i.split() for i in open('cluster_members.csv').readlines()] -print [len(i) for i in data] +print([len(i) for i in data]) nClusters = len(data) nCols = 3 nRows = (nClusters+(nCols-1))/nCols -print nClusters, nRows, nCols +print(nClusters, nRows, nCols) def getGroupPrefix(runPrefix): groupPrefix = runPrefix.split('run')[0].strip('_') @@ -49,7 +49,7 @@ def getGroupPrefix(runPrefix): #print member, result prefix = result[0][0].strip('_') groupPrefix = getGroupPrefix(prefix) - if not groupPrefix in groupPrefix2prefixes2frames.keys(): + if not groupPrefix in list(groupPrefix2prefixes2frames.keys()): groupPrefix2prefixes2frames[groupPrefix] = {} groupPrefix2prefixes2frames[groupPrefix][prefix] = [] frame = int(result[0][1]) @@ -57,7 +57,7 @@ def getGroupPrefix(runPrefix): groupPrefix2prefixes2frames[groupPrefix][prefix] += [frame] #print prefix2frames -prefixes = prefix2frames.keys() +prefixes = list(prefix2frames.keys()) prefixes.sort() nPrefixes = len(prefixes) groupPrefixes = list(set([getGroupPrefix(i) for i in prefixes])) @@ -75,7 +75,7 @@ def getGroupPrefix(runPrefix): frames = prefix2frames[prefix] frames.sort() #if prefix in prefixAndFrame2Col.keys(): - if groupPrefix in groupPrefixColsTaken.keys(): + if groupPrefix in list(groupPrefixColsTaken.keys()): #Note that frame numbering starts at 1 so off-by-1 won't be a problem here offset = max(groupPrefixColsTaken[groupPrefix]) else: @@ -86,8 +86,8 @@ def getGroupPrefix(runPrefix): #memberships = np.zeros((nClusters, nPrefixes, max([len(i) for i in prefix2frames.values()]))) #memberships = np.zeros((nClusters, nGroupPrefixes, max([len(i) for i in prefix2frames.values()]))) -memberships = np.zeros((nClusters, nGroupPrefixes, max([max(i) for i in groupPrefixColsTaken.values()]))) -print [(groupPrefix, max(i)) for groupPrefix, i in zip(groupPrefixColsTaken.keys(), groupPrefixColsTaken.values())] +memberships = np.zeros((nClusters, nGroupPrefixes, max([max(i) for i in list(groupPrefixColsTaken.values())]))) +print([(groupPrefix, max(i)) for groupPrefix, i in zip(list(groupPrefixColsTaken.keys()), list(groupPrefixColsTaken.values()))]) #1/0 memberships -= 1 for clusterIndex, cluster in enumerate(data): @@ -100,7 +100,7 @@ def getGroupPrefix(runPrefix): col = prefixAndFrame2Col[prefix][frame] #print member if sum(memberships[:,row,col]) > 0: - print memberships[:,row,col] + print(memberships[:,row,col]) 1/0 memberships[:,row,col] = 0 memberships[clusterIndex,row,col] = 1 @@ -113,7 +113,7 @@ def getGroupPrefix(runPrefix): aspect='auto') #pylab.yticks(range(len(prefixes)), [[]*4+[prefix] for i, prefix in enumerate(prefixes) if i%5==0]) #pylab.yticks(range(0,len(prefixes),1), prefixes ) - pylab.yticks(range(0,len(groupPrefixes),1), groupPrefixes ) + pylab.yticks(list(range(0,len(groupPrefixes),1)), groupPrefixes ) pylab.xlabel('Frame') pylab.title('Cluster %i' %(clusterIndex)) @@ -141,7 +141,7 @@ def getGroupPrefix(runPrefix): transitions = dict(((groupPrefix,np.zeros((nClusters, nClusters))) for groupPrefix in groupPrefixes)) for simulationIndex, groupPrefix in enumerate(groupPrefixes): simulationIndex = groupPrefixes.index(groupPrefix) - for prefix in groupPrefix2prefixes2frames[groupPrefix].keys(): + for prefix in list(groupPrefix2prefixes2frames[groupPrefix].keys()): currentCluster = None sliceStartCol = min(prefixAndFrame2Col[prefix].values()) sliceEndCol = max(prefixAndFrame2Col[prefix].values()) @@ -152,7 +152,7 @@ def getGroupPrefix(runPrefix): if len(nonzeros[0]) == 0: nextCluster = None elif len(nonzeros[0]) > 1: - print nextCluster + print(nextCluster) 1/0 else: nextCluster = nonzeros[0][0] @@ -237,9 +237,9 @@ def getGroupPrefix(runPrefix): # nodes nFramesPerClusterThisSim = [np.sum(memberships[clusterIndex,simulationIndex,:]==1) for clusterIndex in range(nClusters)] - print nFramesPerClusterThisSim + print(nFramesPerClusterThisSim) nodeSizes = [150. * float(i)/(np.mean(nFramesPerClusterAllSims)/nGroupPrefixes) for i in nFramesPerClusterThisSim] - print nodeSizes + print(nodeSizes) nx.draw_networkx_nodes(G, pos, node_size=nodeSizes) @@ -285,7 +285,7 @@ def getGroupPrefix(runPrefix): prefix2indices[prefix] = prefix2indices.get(prefix,[]) + [int(index)] index2prefix[index] = prefix -sortedPrefixes = prefix2indices.keys() +sortedPrefixes = list(prefix2indices.keys()) sortedPrefixes.sort() groupOverlapSimilarities = np.zeros((nGroupPrefixes, nGroupPrefixes)) tanimoto = np.load('tanimoto_matrix.npy') @@ -368,17 +368,17 @@ def getGroupPrefix(runPrefix): } pdb2LigMol = {} -import urllib2 -sortedPdbList = pdb2Lig.keys() +import urllib.request, urllib.error, urllib.parse +sortedPdbList = list(pdb2Lig.keys()) sortedPdbList.sort() for pdb in sortedPdbList: - print pdb, pdb2Lig[pdb] + print(pdb, pdb2Lig[pdb]) if pdb2Lig[pdb] == 'NOLIG': pdb2LigMol[pdb] = Chem.Mol() continue url = 'http://www.rcsb.org/pdb/download/downloadLigandFiles.do?ligandIdList=%s&structIdList=%s&instanceType=all&excludeUnobserved=false&includeHydrogens=false' %(pdb2Lig[pdb],pdb) #print url - response = urllib2.urlopen(url) + response = urllib.request.urlopen(url) #print "Response received" import time time.sleep(0.5) @@ -408,7 +408,7 @@ def getGroupPrefix(runPrefix): legends = [] molList = [] -sortedPdbList2 = pdb2LigMol.keys() +sortedPdbList2 = list(pdb2LigMol.keys()) sortedPdbList2.sort() for pdb in sortedPdbList2: legends.append(pdb) @@ -469,20 +469,20 @@ def getGroupPrefix(runPrefix): import random import scipy.stats -print "Calculating Rank Correlations" +print("Calculating Rank Correlations") actualTau = scipy.stats.kendalltau(flatGroupOverlapSimilarities, flatMolSimilarities) -print "Actual Kendall Tau:", actualTau +print("Actual Kendall Tau:", actualTau) actualRho = scipy.stats.spearmanr(flatGroupOverlapSimilarities, flatMolSimilarities) -print "Actual Spearman's Rho:", actualRho +print("Actual Spearman's Rho:", actualRho) nResamplings = 10000 bootstrapRhos = [] bootstrapTaus = [] #flatGroupOverlapSimilarities = np.random.random(flatGroupOverlapSimilarities.shape) #flatMolSimilarities = np.random.random(flatMolSimilarities.shape) for i in range(nResamplings): - newOrder = range(len(flatMolSimilarities)) + newOrder = list(range(len(flatMolSimilarities))) random.shuffle(newOrder) scrambledMolSimilarities = [flatMolSimilarities[i] for i in newOrder] scrambledRho = scipy.stats.spearmanr(flatGroupOverlapSimilarities, diff --git a/POVME/packages/binana/atom_type_feature_mapping/peel.py b/POVME/packages/binana/atom_type_feature_mapping/peel.py index 7cb19ad..5ae187b 100644 --- a/POVME/packages/binana/atom_type_feature_mapping/peel.py +++ b/POVME/packages/binana/atom_type_feature_mapping/peel.py @@ -156,7 +156,7 @@ def copy_of(self): return point([self.x, self.y, self.z]) def print_coords(self): - print str(self.x)+"\t"+str(self.y)+"\t"+str(self.z) + print(str(self.x)+"\t"+str(self.y)+"\t"+str(self.z)) def coords(self): return [self.x,self.y,self.z] @@ -417,7 +417,7 @@ def LoadPDB(self, FileName, min_x=-9999.99, max_x=9999.99, min_y=-9999.99, max_y if key in atom_already_loaded and TempAtom.residue.strip() in self.protein_resnames: # so this is a protein atom that has already been loaded once self.printout("Warning: Duplicate protein atom detected: \"" + TempAtom.line.strip() + "\". Not loading this duplicate.") - print "" + print("") if not key in atom_already_loaded or not TempAtom.residue.strip() in self.protein_resnames: # so either the atom hasn't been loaded, or else it's a non-protein atom # so note that non-protein atoms can have redundant names, but protein atoms cannot. @@ -437,7 +437,7 @@ def LoadPDB(self, FileName, min_x=-9999.99, max_x=9999.99, min_y=-9999.99, max_y def printout(self, thestring): lines = textwrap.wrap(thestring, 80) for line in lines: - print line + print(line) def SavePDB(self, filename): f = open(filename, 'w') @@ -460,7 +460,7 @@ def AddNewAtom(self, atom): # first get available index t = 1 - while t in self.AllAtoms.keys(): + while t in list(self.AllAtoms.keys()): t = t + 1 # now add atom @@ -525,136 +525,136 @@ def CheckProteinFormat_process_residue(self, residue, last_key): if not "N" in residue: self.printout('Warning: There is no atom named "N" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine secondary structure. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "C" in residue: self.printout('Warning: There is no atom named "C" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine secondary structure. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CA" in residue: self.printout('Warning: There is no atom named "CA" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine secondary structure. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "GLU" or real_resname == "GLH" or real_resname == "GLX": if not "OE1" in residue: self.printout('Warning: There is no atom named "OE1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "OE2" in residue: self.printout('Warning: There is no atom named "OE2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "ASP" or real_resname == "ASH" or real_resname == "ASX": if not "OD1" in residue: self.printout('Warning: There is no atom named "OD1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "OD2" in residue: self.printout('Warning: There is no atom named "OD2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "LYS" or real_resname == "LYN": if not "NZ" in residue: self.printout('Warning: There is no atom named "NZ" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-cation and salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "ARG": if not "NH1" in residue: self.printout('Warning: There is no atom named "NH1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-cation and salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "NH2" in residue: self.printout('Warning: There is no atom named "NH2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-cation and salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "HIS" or real_resname == "HID" or real_resname == "HIE" or real_resname == "HIP": if not "NE2" in residue: self.printout('Warning: There is no atom named "NE2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-cation and salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "ND1" in residue: self.printout('Warning: There is no atom named "ND1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-cation and salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "PHE": if not "CG" in residue: self.printout('Warning: There is no atom named "CG" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CD1" in residue: self.printout('Warning: There is no atom named "CD1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CD2" in residue: self.printout('Warning: There is no atom named "CD2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CE1" in residue: self.printout('Warning: There is no atom named "CE1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CE2" in residue: self.printout('Warning: There is no atom named "CE2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CZ" in residue: self.printout('Warning: There is no atom named "CZ" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "TYR": if not "CG" in residue: self.printout('Warning: There is no atom named "CG" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CD1" in residue: self.printout('Warning: There is no atom named "CD1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CD2" in residue: self.printout('Warning: There is no atom named "CD2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CE1" in residue: self.printout('Warning: There is no atom named "CE1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CE2" in residue: self.printout('Warning: There is no atom named "CE2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CZ" in residue: self.printout('Warning: There is no atom named "CZ" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "TRP": if not "CG" in residue: self.printout('Warning: There is no atom named "CG" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CD1" in residue: self.printout('Warning: There is no atom named "CD1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CD2" in residue: self.printout('Warning: There is no atom named "CD2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "NE1" in residue: self.printout('Warning: There is no atom named "NE1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CE2" in residue: self.printout('Warning: There is no atom named "CE2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CE3" in residue: self.printout('Warning: There is no atom named "CE3" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CZ2" in residue: self.printout('Warning: There is no atom named "CZ2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CZ3" in residue: self.printout('Warning: There is no atom named "CZ3" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CH2" in residue: self.printout('Warning: There is no atom named "CH2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "HIS" or real_resname == "HID" or real_resname == "HIE" or real_resname == "HIP": if not "CG" in residue: self.printout('Warning: There is no atom named "CG" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "ND1" in residue: self.printout('Warning: There is no atom named "ND1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CD2" in residue: self.printout('Warning: There is no atom named "CD2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CE1" in residue: self.printout('Warning: There is no atom named "CE1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "NE2" in residue: self.printout('Warning: There is no atom named "NE2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") # Functions to determine the bond connectivity based on distance @@ -1864,7 +1864,7 @@ def generateTranslations(self,ligandMap,resolution,number): def generateRotations(self,number,nsteps): - if number in self.pointDict.keys(): + if number in list(self.pointDict.keys()): spherePoints = self.pointDict[number] else: @@ -1926,7 +1926,7 @@ def interpolation_rotate_inplace(self, quaternion): zpsi = 57.29578 * numpy.arctan2((w*y - x*z),(x*y + w*z)) #rotatedArrays = copy.deepcopy(ligandMaps) - for feature in rotatedArrays.keys(): + for feature in list(rotatedArrays.keys()): self.data = sni.rotate(self.data,zphi,axes=(0,1), reshape=False) self.data = sni.rotate(self.data,xtheta,axes=(1,2), reshape=False) self.data = sni.rotate(self.data,zpsi,axes=(0,1), reshape=False) @@ -2496,14 +2496,14 @@ def dockOne(self,receptorMaps, ligandMaps,translation_list,spherePoints): c=0 for [w,x,y,z] in spherePoints: c += 1 - print "Processing rotation %i of %i" %(c, len(spherePoints)) + print("Processing rotation %i of %i" %(c, len(spherePoints))) #Quaternions to Euler angles: #180/3.1415926 #zphi = 57.29578 * numpy.arctan2((w*y + x*z),-(x*y - w*z)) #xtheta = 57.29578 * numpy.arccos(-w**2 - x**2 + y**2 + z**2) #zpsi = 57.29578 * numpy.arctan2((w*y - x*z),(x*y + w*z)) rotatedArrays = copy.deepcopy(ligandMaps) - for feature in rotatedArrays.keys(): + for feature in list(rotatedArrays.keys()): rotatedArrays[feature].interpolation_rotate_inplace([w,x,y,z]) #print zphi, xtheta, zpsi #for feature in rotatedArrays.keys(): @@ -2519,7 +2519,7 @@ def dockOne(self,receptorMaps, ligandMaps,translation_list,spherePoints): #shiftedArray = sni.shift(receptorMap,[X,Y,Z]) shiftedArrays = copy.deepcopy(rotatedArrays) - for feature in shiftedArrays.keys(): + for feature in list(shiftedArrays.keys()): shiftedArrays[feature].translate_inplace([X,Y,Z]) #shiftedArrays[feature].borders = [shiftedArrays[feature].borders[0]+X, # shiftedArrays[feature].borders[1]+X, @@ -2544,19 +2544,19 @@ def dockOne(self,receptorMaps, ligandMaps,translation_list,spherePoints): successfulDockings.append([[X,Y,Z],[w,x,y,z],scores]) #print [[X,Y,Z],[w,x,y,z],scores] successfulDockings.sort(key=lambda x: sum(x[2]), reverse = True) - print "Docking complete!" + print("Docking complete!") return successfulDockings def dockPeel(self,receptorMaps, ligandPeel, translation_list,spherePoints): - resolution = receptorMaps[receptorMaps.keys()[0]].getReso() + resolution = receptorMaps[list(receptorMaps.keys())[0]].getReso() #successfulDockings = numpy.array(['Translation Steps','Rotation Quaternion','Score'],dtype='string_') successfulDockings=[] c=0 for [w,x,y,z] in spherePoints: c += 1 - print "Processing rotation %i of %i: %s" %(c, len(spherePoints), str([w,x,y,z])) + print("Processing rotation %i of %i: %s" %(c, len(spherePoints), str([w,x,y,z]))) #Quaternions to Euler angles: #180/3.1415926 #zphi = 57.29578 * numpy.arctan2((w*y + x*z),-(x*y - w*z)) @@ -2627,7 +2627,7 @@ def dockPeel(self,receptorMaps, ligandPeel, translation_list,spherePoints): #shiftedMaps = copy.deepcopy(rotatedMaps) - for feature in shiftedMaps.keys(): + for feature in list(shiftedMaps.keys()): shiftedMaps[feature].translate_inplace([dXAngstroms,dYAngstroms,dZAngstroms]) #shiftedMaps[feature].translate_inplace([X,Y,Z]) #shiftedMaps[feature].borders = [shiftedMaps[feature].borders[0]+X, @@ -2651,12 +2651,12 @@ def dockPeel(self,receptorMaps, ligandPeel, translation_list,spherePoints): successfulDockings.append([[absXAngstroms,absYAngstroms,absZAngstroms],[w,x,y,z],scores]) #print [[X,Y,Z],[w,x,y,z],scores] successfulDockings.sort(key=lambda x: sum(x[2]), reverse = True) - print "Docking complete!" + print("Docking complete!") return successfulDockings def printLastScores(self): if self.lastScores != None: - print '\n'.join(['%.5e\t%s'%(score, func) for func, score in zip(self.lastStringScoreFuncs, self.lastScores)]) + print('\n'.join(['%.5e\t%s'%(score, func) for func, score in zip(self.lastStringScoreFuncs, self.lastScores)])) @@ -2671,7 +2671,7 @@ class peel: # return '_'.join(list) def hashtable_entry_add_one(self, hashtable, key, toadd = 1): # note that dictionaries (hashtables) are passed by reference in python - if hashtable.has_key(key): + if key in hashtable: hashtable[key] = hashtable[key] + toadd else: hashtable[key] = toadd @@ -2882,49 +2882,49 @@ def create_feature_maps(self, gridBorders, gridReso, features = ['occupancy','ad start = time.time() self.color_map_by_occupancy(featureMaps[feature]) end = time.time() - print 'time to create occupancy map:', end-start + print('time to create occupancy map:', end-start) if feature == 'adjacency': featureMaps[feature] = featureMap(gridBorders, gridReso, boolean=True) start = time.time() self.color_map_by_adjacency(featureMaps[feature]) end = time.time() - print 'time to create adjacency map:', end-start + print('time to create adjacency map:', end-start) if feature == 'hbondAcceptor': featureMaps[feature] = featureMap(gridBorders, gridReso, boolean=False) start = time.time() self.color_map_by_hbondAcceptor(featureMaps[feature]) end = time.time() - print 'time to create hydrogen bond acceptor map:', end-start + print('time to create hydrogen bond acceptor map:', end-start) if feature == 'hbondDonor': featureMaps[feature] = featureMap(gridBorders, gridReso, boolean=False) start = time.time() self.color_map_by_hbondDonor(featureMaps[feature]) end = time.time() - print 'time to create hydrogen bond donor map:', end-start + print('time to create hydrogen bond donor map:', end-start) if feature == 'aromatic': featureMaps[feature] = featureMap(gridBorders, gridReso, boolean=False) start = time.time() self.color_map_by_aromatic(featureMaps[feature]) end = time.time() - print 'time to create aromatic map:', end-start + print('time to create aromatic map:', end-start) if feature == 'hydrophobic': featureMaps[feature] = featureMap(gridBorders, gridReso, boolean=False) start = time.time() self.color_map_by_hydrophobic(featureMaps[feature]) end = time.time() - print 'time to create hydrophobic map:', end-start + print('time to create hydrophobic map:', end-start) if feature == 'hydrophilic': featureMaps[feature] = featureMap(gridBorders, gridReso, boolean=False) start = time.time() self.color_map_by_hydrophilic(featureMaps[feature]) end = time.time() - print 'time to create hydrophilic map:', end-start + print('time to create hydrophilic map:', end-start) if feature == 'hydrophobicity': featureMaps[feature] = featureMap(gridBorders, gridReso, boolean=False) start = time.time() self.color_map_by_hydrophobicity(featureMaps[feature]) end = time.time() - print 'time to create hydrophobicity map:', end-start + print('time to create hydrophobicity map:', end-start) #print 'CFM', numpy.nonzero(featureMaps[0].data) return featureMaps @@ -2936,7 +2936,7 @@ def create_atom_map(self, gridBorders, gridReso = 1.0): start = time.time() self.color_map_by_atomDictionary(atomMaps[category], category) end = time.time() - print 'time to create atom category ' + category + ' map:', end-start + print('time to create atom category ' + category + ' map:', end-start) return atomMaps @@ -2998,7 +2998,7 @@ def color_povme_map(self, povmeMatrix, gridReso, features = ['hbondAcceptor','hb #Turning into a set so the hash search will be fast #povmeSet = set([ tuple(i) for i in povmeList]) - for feature in colorMaps.keys(): + for feature in list(colorMaps.keys()): completePointList = colorMaps[feature].toPovmeList() #Only return points that were available in the POVME list beforehand #THIS COULD BE IMPROVED @@ -3093,11 +3093,11 @@ def characterize_ligand_occupancies(self): for this_atom in self.receptor.AllAtoms: this_element = self.receptor.AllAtoms[this_atom].element coordinates_pt = self.receptor.AllAtoms[this_atom].coordinates - if this_element in radii.keys(): + if this_element in list(radii.keys()): #print self.receptor.AllAtoms[this_atom].coordinates, radii[this_element] self.features['occupancies'][this_atom] = {'coordinates':coordinates_pt, 'radius':radii[this_element]} else: - print "WARNING: Atom type %s is not C, H, O, N P, S, or F. Assuming atomic radius of 2 angstroms" %(this_element) + print("WARNING: Atom type %s is not C, H, O, N P, S, or F. Assuming atomic radius of 2 angstroms" %(this_element)) self.features['occupancies'][this_atom] = {'coordinates':coordinates_pt, 'radius': 2.0} @@ -3172,7 +3172,7 @@ def characterize_hbond_donors(self): #print self.receptor.selections.select_atoms({'element':['O','N']}) #for receptor_atom_index in self.receptor.selections.select_atoms({'element':['O','N']}): #self.receptor.create_bonds_by_distance()\ - print self.receptor.get_bonds() + print(self.receptor.get_bonds()) for receptor_atom_index in self.receptor.selections.select_atoms({'element_stripped':['O','N']}): #print "BBB", receptor_atom_index, self.receptor.information.get_atom_information()[receptor_atom_index] @@ -3400,10 +3400,10 @@ def characterize_occupancies(self): this_element = this_atom_info['element_stripped'] receptor_atom_index = self.receptor.selections.select_atoms({'serial':this_serial}) coordinates_pt = point(self.receptor.get_coordinates()[receptor_atom_index][0]) - if this_element in radii.keys(): + if this_element in list(radii.keys()): self.features['occupancies'][this_serial] = {'coordinates': coordinates_pt, 'radius':radii[this_element]} else: - print "WARNING: Atom type %s is not C, H, O, N P, S, or F. Assuming atomic radius of 2 angstroms" %(this_element) + print("WARNING: Atom type %s is not C, H, O, N P, S, or F. Assuming atomic radius of 2 angstroms" %(this_element)) self.features['occupancies'][this_atom_info['serial']] = {'coordinates':coordinates_pt, 'radius':2.0} def create_atom_dictionary(self): @@ -3550,16 +3550,16 @@ def write_vmd_script(self, vmdScriptName, parameters): def rotate(self, quaternion, center='average'): if center == 'average': coords = [] - for feature in self.features.keys(): - for key in self.features[feature].keys(): + for feature in list(self.features.keys()): + for key in list(self.features[feature].keys()): coords.append(self.features[feature][key]['coordinates'].coords()) coords = numpy.array(coords) center = numpy.array([numpy.mean(coords[:,0]), numpy.mean(coords[:,1]), numpy.mean(coords[:,2])]) #Move whole thing to be vcentered around 0,0,0 self.translate(-1.0*center) - for feature in self.features.keys(): - for index in self.features[feature].keys(): + for feature in list(self.features.keys()): + for index in list(self.features[feature].keys()): oldCoordsList = self.features[feature][index]['coordinates'].coords() oldMagnitude = self.features[feature][index]['coordinates'].magnitude() #rotation = self.functions.axisangle_to_q(quaternion[1:], numpy.arcsin(quaternion[0])*2) @@ -3577,8 +3577,8 @@ def rotate(self, quaternion, center='average'): def translate(self, vector): - for feature in self.features.keys(): - for key in self.features[feature].keys(): + for feature in list(self.features.keys()): + for key in list(self.features[feature].keys()): oldCoords = self.features[feature][key]['coordinates'].coords() newCoords = oldCoords + numpy.array(vector) self.features[feature][key]['coordinates'] = point(newCoords) @@ -3674,7 +3674,7 @@ def __init__(self, receptor, parameters, isLigand=False): self.atom_dictionary = {} self.create_atom_dictionary() - print "Peeled!" + print("Peeled!") class command_line_parameters: @@ -3717,7 +3717,7 @@ def __init__(self, parameters): if item[:1] == '-': # so it's a parameter key value key = item.replace('-','') value = self.is_num(parameters[index+1]) - if key in self.params.keys(): + if key in list(self.params.keys()): self.params[key] = value parameters[index] = "" parameters[index + 1] = "" @@ -3832,45 +3832,45 @@ def intro(): wrapped.extend(textwrap.wrap(line, 80)) - print " ..I?+?. " - print " ..$7$7. " - print " ..$$Z, " - print " ..I$$O?. " - print " :??7$$$. " - print " .=????7III " - print " ..I?????I???.. " - print " ...???????I????. " - print " ..?+??????I????? " - print " .??I??????II????+. " - print " ~?II??????II+???=+.. " - print " .??I+??????II????+=+. " - print " .+?I,???????I?????+~:, " - print " .+I?~???????+I????++~~:~.. " - print " .+??==???????=+?+++++:~~:~~:..... " - print " .++?+.???????+~+?+++++,:~:~~~,:,:::,........ ....... " - print " .?=++=~++??+++:=??++++++~::,:~~::::~~:~=~~~~~~~~~?+=.. " - print " :+====?+++++++.=??++++++????=~~=~~::,:,,,,:::~==++= " - print " .+==~=+++++++++,=I?+++++++..:?77I????????????I7?... " - print " .:====~??+++++?++:I?+++++++~. .................. " - print " ..++=~=:+?++++++++??I?++++++??.. " - print " ..?~==~=~.??++++++++?7??++++++++,. " - print " ~=====~,.=?++++++++??7?+++++++++~ " - print " .==~~:==...=?+?+++++???7??+++++++?. " - print " .?===~=:~ ..??++?+++???7?I?++?++?,. " - print " .?=~=~~:=.. .7???++?+??7$7I?++III,. " - print " .==~~~:~:.. ..,777I???7$ODDMDNM, " - print " .,~~~~~=::. .~$II7ZOONMN. " - print " ..:=~~~=:?. .......,=I7I. " - print " ..=+=~==::. . .... " - print " ..?+===~~=. " - print " ~+==~~=~. " - print " .+?==~=:. " - print " ..I7II++. " - print " .=I$$$. " - print " .... " + print(" ..I?+?. ") + print(" ..$7$7. ") + print(" ..$$Z, ") + print(" ..I$$O?. ") + print(" :??7$$$. ") + print(" .=????7III ") + print(" ..I?????I???.. ") + print(" ...???????I????. ") + print(" ..?+??????I????? ") + print(" .??I??????II????+. ") + print(" ~?II??????II+???=+.. ") + print(" .??I+??????II????+=+. ") + print(" .+?I,???????I?????+~:, ") + print(" .+I?~???????+I????++~~:~.. ") + print(" .+??==???????=+?+++++:~~:~~:..... ") + print(" .++?+.???????+~+?+++++,:~:~~~,:,:::,........ ....... ") + print(" .?=++=~++??+++:=??++++++~::,:~~::::~~:~=~~~~~~~~~?+=.. ") + print(" :+====?+++++++.=??++++++????=~~=~~::,:,,,,:::~==++= ") + print(" .+==~=+++++++++,=I?+++++++..:?77I????????????I7?... ") + print(" .:====~??+++++?++:I?+++++++~. .................. ") + print(" ..++=~=:+?++++++++??I?++++++??.. ") + print(" ..?~==~=~.??++++++++?7??++++++++,. ") + print(" ~=====~,.=?++++++++??7?+++++++++~ ") + print(" .==~~:==...=?+?+++++???7??+++++++?. ") + print(" .?===~=:~ ..??++?+++???7?I?++?++?,. ") + print(" .?=~=~~:=.. .7???++?+??7$7I?++III,. ") + print(" .==~~~:~:.. ..,777I???7$ODDMDNM, ") + print(" .,~~~~~=::. .~$II7ZOONMN. ") + print(" ..:=~~~=:?. .......,=I7I. ") + print(" ..=+=~==::. . .... ") + print(" ..?+===~~=. ") + print(" ~+==~~=~. ") + print(" .+?==~=:. ") + print(" ..I7II++. ") + print(" .=I$$$. ") + print(" .... ") for i in wrapped: - print i + print(i) if __name__=='__main__': intro() @@ -3878,12 +3878,12 @@ def intro(): cmd_params = command_line_parameters(sys.argv[:]) if cmd_params.okay_to_proceed() == False: - print "Error: You need to specify the ligand and receptor PDBQT files to analyze using\nthe -receptor and -ligand tags from the command line.\n" + print("Error: You need to specify the ligand and receptor PDBQT files to analyze using\nthe -receptor and -ligand tags from the command line.\n") sys.exit(0) if cmd_params.error != "": - print "Warning: The following command-line parameters were not recognized:" - print " " + cmd_params.error + "\n" + print("Warning: The following command-line parameters were not recognized:") + print(" " + cmd_params.error + "\n") #lig = cmd_params.params['ligand'] rec = cmd_params.params['receptor'] @@ -3901,5 +3901,5 @@ def intro(): my_peel.receptor.fileio.save_pdb('receptor.pdb') my_peel.write_vmd_script('visualize.vmd', parameters) - print "Done!" + print("Done!") diff --git a/POVME/packages/binana/binana.py b/POVME/packages/binana/binana.py index ee4c689..bdc8603 100644 --- a/POVME/packages/binana/binana.py +++ b/POVME/packages/binana/binana.py @@ -21,7 +21,7 @@ def copy_of(self): return point(self.x, self.y, self.z) def print_coors(self): - print str(self.x)+"\t"+str(self.y)+"\t"+str(self.z) + print(str(self.x)+"\t"+str(self.y)+"\t"+str(self.z)) def snap(self,reso): # snap the point to a grid self.x = round(self.x / reso) * reso @@ -215,7 +215,7 @@ def LoadPDB(self, FileName, min_x=-9999.99, max_x=9999.99, min_y=-9999.99, max_y if line[:3] == "END": t = textwrap.wrap("WARNING: END or ENDMDL term found in " + FileName + ". Everything after the first instance of this term will be ignored. If any of your PDBQT files have multiple frames/poses, please partition them into separate files using vina_split and feed each of the the single-frame files into binana separately.", 80) - print "\n".join(t) + "\n" + print("\n".join(t) + "\n") break if "between atoms" in line and " A " in line: @@ -240,7 +240,7 @@ def LoadPDB(self, FileName, min_x=-9999.99, max_x=9999.99, min_y=-9999.99, max_y if key in atom_already_loaded and TempAtom.residue.strip() in self.protein_resnames: # so this is a protein atom that has already been loaded once self.printout("Warning: Duplicate protein atom detected: \"" + TempAtom.line.strip() + "\". Not loading this duplicate.") - print "" + print("") if not key in atom_already_loaded or not TempAtom.residue.strip() in self.protein_resnames: # so either the atom hasn't been loaded, or else it's a non-protein atom # so note that non-protein atoms can have redundant names, but protein atoms cannot. @@ -260,7 +260,7 @@ def LoadPDB(self, FileName, min_x=-9999.99, max_x=9999.99, min_y=-9999.99, max_y def printout(self, thestring): lines = textwrap.wrap(thestring, 80) for line in lines: - print line + print(line) def SavePDB(self, filename): f = open(filename, 'w') @@ -283,7 +283,7 @@ def AddNewAtom(self, atom): # first get available index t = 1 - while t in self.AllAtoms.keys(): + while t in list(self.AllAtoms.keys()): t = t + 1 # now add atom @@ -348,136 +348,136 @@ def CheckProteinFormat_process_residue(self, residue, last_key): if not "N" in residue: self.printout('Warning: There is no atom named "N" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine secondary structure. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "C" in residue: self.printout('Warning: There is no atom named "C" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine secondary structure. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CA" in residue: self.printout('Warning: There is no atom named "CA" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine secondary structure. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "GLU" or real_resname == "GLH" or real_resname == "GLX": if not "OE1" in residue: self.printout('Warning: There is no atom named "OE1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "OE2" in residue: self.printout('Warning: There is no atom named "OE2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "ASP" or real_resname == "ASH" or real_resname == "ASX": if not "OD1" in residue: self.printout('Warning: There is no atom named "OD1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "OD2" in residue: self.printout('Warning: There is no atom named "OD2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "LYS" or real_resname == "LYN": if not "NZ" in residue: self.printout('Warning: There is no atom named "NZ" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-cation and salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "ARG": if not "NH1" in residue: self.printout('Warning: There is no atom named "NH1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-cation and salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "NH2" in residue: self.printout('Warning: There is no atom named "NH2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-cation and salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "HIS" or real_resname == "HID" or real_resname == "HIE" or real_resname == "HIP": if not "NE2" in residue: self.printout('Warning: There is no atom named "NE2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-cation and salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "ND1" in residue: self.printout('Warning: There is no atom named "ND1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-cation and salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "PHE": if not "CG" in residue: self.printout('Warning: There is no atom named "CG" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CD1" in residue: self.printout('Warning: There is no atom named "CD1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CD2" in residue: self.printout('Warning: There is no atom named "CD2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CE1" in residue: self.printout('Warning: There is no atom named "CE1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CE2" in residue: self.printout('Warning: There is no atom named "CE2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CZ" in residue: self.printout('Warning: There is no atom named "CZ" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "TYR": if not "CG" in residue: self.printout('Warning: There is no atom named "CG" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CD1" in residue: self.printout('Warning: There is no atom named "CD1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CD2" in residue: self.printout('Warning: There is no atom named "CD2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CE1" in residue: self.printout('Warning: There is no atom named "CE1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CE2" in residue: self.printout('Warning: There is no atom named "CE2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CZ" in residue: self.printout('Warning: There is no atom named "CZ" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "TRP": if not "CG" in residue: self.printout('Warning: There is no atom named "CG" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CD1" in residue: self.printout('Warning: There is no atom named "CD1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CD2" in residue: self.printout('Warning: There is no atom named "CD2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "NE1" in residue: self.printout('Warning: There is no atom named "NE1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CE2" in residue: self.printout('Warning: There is no atom named "CE2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CE3" in residue: self.printout('Warning: There is no atom named "CE3" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CZ2" in residue: self.printout('Warning: There is no atom named "CZ2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CZ3" in residue: self.printout('Warning: There is no atom named "CZ3" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CH2" in residue: self.printout('Warning: There is no atom named "CH2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "HIS" or real_resname == "HID" or real_resname == "HIE" or real_resname == "HIP": if not "CG" in residue: self.printout('Warning: There is no atom named "CG" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "ND1" in residue: self.printout('Warning: There is no atom named "ND1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CD2" in residue: self.printout('Warning: There is no atom named "CD2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CE1" in residue: self.printout('Warning: There is no atom named "CE1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "NE2" in residue: self.printout('Warning: There is no atom named "NE2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") # Functions to determine the bond connectivity based on distance @@ -1509,7 +1509,7 @@ def list_alphebetize_and_combine(self, list): return '_'.join(list) def hashtable_entry_add_one(self, hashtable, key, toadd = 1): # note that dictionaries (hashtables) are passed by reference in python - if hashtable.has_key(key): + if key in hashtable: hashtable[key] = hashtable[key] + toadd else: hashtable[key] = toadd @@ -1794,7 +1794,7 @@ def __init__(self, ligand_pdbqt_filename, receptor_pdbqt_filename, parameters): output = output + preface + "Command-line parameters used:" + "\n" output = output + preface + " Parameter | Value " + "\n" output = output + preface + " -------------------------------------|----------------------------" + "\n" - for key in parameters.params.keys(): + for key in list(parameters.params.keys()): value = str(parameters.params[key]) output = output + preface + " " + self.center(key,37) + "| " + self.center(value,27) + "\n" @@ -1950,7 +1950,7 @@ def __init__(self, ligand_pdbqt_filename, receptor_pdbqt_filename, parameters): f.close() if parameters.params['output_file'] == "" and parameters.params['output_dir'] == "": # so you're not outputing to either a file or a directory - print output.replace("REMARK ","") + print(output.replace("REMARK ","")) if parameters.params['output_file'] != "": # so it's writing to a single file. @@ -2295,7 +2295,7 @@ def __init__(self, parameters): if item[:1] == '-': # so it's a parameter key value key = item.replace('-','') value = self.is_num(parameters[index+1]) - if key in self.params.keys(): + if key in list(self.params.keys()): self.params[key] = value parameters[index] = "" parameters[index + 1] = "" @@ -2408,39 +2408,39 @@ def intro(): else: wrapped.extend(textwrap.wrap(line, 80)) - print "" - print " |[]{};" - print " .|[]{}" - print " .| {}" - print " | }" - print " | }" - print " | }" - print " .| };" - print " .| :'\"" - print " +. \"" - print " =+ \"/" - print " _= \"/" - print " -_ \"/" - print " ,- \"/" - print " <> \"/" - print " |\ \"" - print " :'\"/ '\"" - print " .|[]{}; :'" - print " ,-_=+.|[]{};:'\"/|\<>,-_=+ :'" - print " |\<> ;:" - print " /| {};" - print " /| ]{}" - print " /| []" - print " |\ .|[" - print " \< =+." - print " >, -_=" - print " ,-_= <>,-" - print " =+.|[] \"/|\<" - print " ]{};:'\"/|\ []{};:'\"" - print " \<>,-_=+.|" + print("") + print(" |[]{};") + print(" .|[]{}") + print(" .| {}") + print(" | }") + print(" | }") + print(" | }") + print(" .| };") + print(" .| :'\"") + print(" +. \"") + print(" =+ \"/") + print(" _= \"/") + print(" -_ \"/") + print(" ,- \"/") + print(" <> \"/") + print(" |\ \"") + print(" :'\"/ '\"") + print(" .|[]{}; :'") + print(" ,-_=+.|[]{};:'\"/|\<>,-_=+ :'") + print(" |\<> ;:") + print(" /| {};") + print(" /| ]{}") + print(" /| []") + print(" |\ .|[") + print(" \< =+.") + print(" >, -_=") + print(" ,-_= <>,-") + print(" =+.|[] \"/|\<") + print(" ]{};:'\"/|\ []{};:'\"") + print(" \<>,-_=+.|") for i in wrapped: - print i + print(i) intro() @@ -2448,12 +2448,12 @@ def intro(): cmd_params = command_line_parameters(sys.argv[:]) if cmd_params.okay_to_proceed() == False: - print "Error: You need to specify the ligand and receptor PDBQT files to analyze using\nthe -receptor and -ligand tags from the command line.\n" + print("Error: You need to specify the ligand and receptor PDBQT files to analyze using\nthe -receptor and -ligand tags from the command line.\n") sys.exit(0) if cmd_params.error != "": - print "Warning: The following command-line parameters were not recognized:" - print " " + cmd_params.error + "\n" + print("Warning: The following command-line parameters were not recognized:") + print(" " + cmd_params.error + "\n") lig = cmd_params.params['ligand'] rec = cmd_params.params['receptor'] diff --git a/POVME/packages/binana/peel.py b/POVME/packages/binana/peel.py index 6d23326..56807d8 100644 --- a/POVME/packages/binana/peel.py +++ b/POVME/packages/binana/peel.py @@ -162,7 +162,7 @@ def copy_of(self): return point([self.x, self.y, self.z]) def print_coords(self): - print str(self.x)+"\t"+str(self.y)+"\t"+str(self.z) + print(str(self.x)+"\t"+str(self.y)+"\t"+str(self.z)) def coords(self): return [self.x,self.y,self.z] @@ -421,7 +421,7 @@ def LoadPDB(self, FileName, min_x=-9999.99, max_x=9999.99, min_y=-9999.99, max_y if key in atom_already_loaded and TempAtom.residue.strip() in self.protein_resnames: # so this is a protein atom that has already been loaded once self.printout("Warning: Duplicate protein atom detected: \"" + TempAtom.line.strip() + "\". Not loading this duplicate.") - print "" + print("") if not key in atom_already_loaded or not TempAtom.residue.strip() in self.protein_resnames: # so either the atom hasn't been loaded, or else it's a non-protein atom # so note that non-protein atoms can have redundant names, but protein atoms cannot. @@ -441,7 +441,7 @@ def LoadPDB(self, FileName, min_x=-9999.99, max_x=9999.99, min_y=-9999.99, max_y def printout(self, thestring): lines = textwrap.wrap(thestring, 80) for line in lines: - print line + print(line) def SavePDB(self, filename): f = open(filename, 'w') @@ -464,7 +464,7 @@ def AddNewAtom(self, atom): # first get available index t = 1 - while t in self.AllAtoms.keys(): + while t in list(self.AllAtoms.keys()): t = t + 1 # now add atom @@ -529,136 +529,136 @@ def CheckProteinFormat_process_residue(self, residue, last_key): if not "N" in residue: self.printout('Warning: There is no atom named "N" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine secondary structure. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "C" in residue: self.printout('Warning: There is no atom named "C" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine secondary structure. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CA" in residue: self.printout('Warning: There is no atom named "CA" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine secondary structure. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "GLU" or real_resname == "GLH" or real_resname == "GLX": if not "OE1" in residue: self.printout('Warning: There is no atom named "OE1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "OE2" in residue: self.printout('Warning: There is no atom named "OE2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "ASP" or real_resname == "ASH" or real_resname == "ASX": if not "OD1" in residue: self.printout('Warning: There is no atom named "OD1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "OD2" in residue: self.printout('Warning: There is no atom named "OD2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "LYS" or real_resname == "LYN": if not "NZ" in residue: self.printout('Warning: There is no atom named "NZ" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-cation and salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "ARG": if not "NH1" in residue: self.printout('Warning: There is no atom named "NH1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-cation and salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "NH2" in residue: self.printout('Warning: There is no atom named "NH2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-cation and salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "HIS" or real_resname == "HID" or real_resname == "HIE" or real_resname == "HIP": if not "NE2" in residue: self.printout('Warning: There is no atom named "NE2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-cation and salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "ND1" in residue: self.printout('Warning: There is no atom named "ND1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-cation and salt-bridge interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "PHE": if not "CG" in residue: self.printout('Warning: There is no atom named "CG" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CD1" in residue: self.printout('Warning: There is no atom named "CD1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CD2" in residue: self.printout('Warning: There is no atom named "CD2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CE1" in residue: self.printout('Warning: There is no atom named "CE1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CE2" in residue: self.printout('Warning: There is no atom named "CE2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CZ" in residue: self.printout('Warning: There is no atom named "CZ" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "TYR": if not "CG" in residue: self.printout('Warning: There is no atom named "CG" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CD1" in residue: self.printout('Warning: There is no atom named "CD1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CD2" in residue: self.printout('Warning: There is no atom named "CD2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CE1" in residue: self.printout('Warning: There is no atom named "CE1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CE2" in residue: self.printout('Warning: There is no atom named "CE2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CZ" in residue: self.printout('Warning: There is no atom named "CZ" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "TRP": if not "CG" in residue: self.printout('Warning: There is no atom named "CG" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CD1" in residue: self.printout('Warning: There is no atom named "CD1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CD2" in residue: self.printout('Warning: There is no atom named "CD2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "NE1" in residue: self.printout('Warning: There is no atom named "NE1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CE2" in residue: self.printout('Warning: There is no atom named "CE2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CE3" in residue: self.printout('Warning: There is no atom named "CE3" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CZ2" in residue: self.printout('Warning: There is no atom named "CZ2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CZ3" in residue: self.printout('Warning: There is no atom named "CZ3" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CH2" in residue: self.printout('Warning: There is no atom named "CH2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if real_resname == "HIS" or real_resname == "HID" or real_resname == "HIE" or real_resname == "HIP": if not "CG" in residue: self.printout('Warning: There is no atom named "CG" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "ND1" in residue: self.printout('Warning: There is no atom named "ND1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CD2" in residue: self.printout('Warning: There is no atom named "CD2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "CE1" in residue: self.printout('Warning: There is no atom named "CE1" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") if not "NE2" in residue: self.printout('Warning: There is no atom named "NE2" in the protein residue ' + last_key + '. Please use standard naming conventions for all protein residues. This atom is needed to determine pi-pi and pi-cation interactions. If this residue is far from the active site, this warning may not affect the NNScore.') - print "" + print("") # Functions to determine the bond connectivity based on distance @@ -1890,7 +1890,7 @@ def fromOffGridPts(cls,offGridPts, gridReso, skinDistance = 1., justCoords = Fal newWay = True if newWay: coord2GridIndex = thisMap.generate_coord_to_grid_index_dict() - gridPts = np.array(coord2GridIndex.keys()) + gridPts = np.array(list(coord2GridIndex.keys())) allDists = ssd.cdist(offGridPts[:,:3],gridPts[:,:3]) globalMaxDist = np.amax(allDists) for index, offGridPt in enumerate(offGridPts): @@ -2058,7 +2058,7 @@ def generateTranslations(self,ligandMap,resolution,number): def generateRotations(self,number,nsteps): - if number in self.pointDict.keys(): + if number in list(self.pointDict.keys()): spherePoints = self.pointDict[number] else: @@ -2153,7 +2153,7 @@ def interpolation_rotate_inplace(self, quaternion): zpsi = 57.29578 * np.arctan2((w*y - x*z),(x*y + w*z)) #rotatedArrays = copy.deepcopy(ligandMaps) - for feature in rotatedArrays.keys(): + for feature in list(rotatedArrays.keys()): self.data = sni.rotate(self.data,zphi,axes=(0,1), reshape=False) self.data = sni.rotate(self.data,xtheta,axes=(1,2), reshape=False) self.data = sni.rotate(self.data,zpsi,axes=(0,1), reshape=False) @@ -2620,7 +2620,7 @@ def __iadd__(self, other): tempOtherBitVector = np.zeros((other.getNumFeatureMaps(),self.getnVecPos()),dtype=np.bool) - for frame in xrange(other.getNumFeatureMaps()): + for frame in range(other.getNumFeatureMaps()): for coord in self.getCoord2BitVecPos(): if coord not in other.getCoord2BitVecPos(): continue @@ -2650,13 +2650,13 @@ def getBitVector(self): return self.bit_vectors def makeBitVector(self,num_feature_maps, nVectPos): - print "Starting BitVector construction" + print("Starting BitVector construction") this_vec_pos_matrix = np.zeros((num_feature_maps, nVectPos), dtype=np.bool) for f1 in range(num_feature_maps): for coord in np.load(self.filenames[f1]): this_vec_pos_matrix[f1,self.getCoord2BitVecPos()[tuple(coord)]] = 1 self.setBitVector(this_vec_pos_matrix) - print "Finished that too." + print("Finished that too.") def setCoord2BitVecPos(self, coord2BitVecPos): self.coord2vectPos = coord2BitVecPos @@ -2665,18 +2665,18 @@ def getCoord2BitVecPos(self): return self.coord2vectPos def makeCoord2BitVecPos(self, filenames=[], num_frames=0): - print "Beginning Coord2BitVecPos" + print("Beginning Coord2BitVecPos") allPointsSet = set() for f1 in range(num_frames): for coord in np.load(filenames[f1]): allPointsSet.add(tuple(map(int,coord))) self.setCoord2BitVecPos(OrderedDict((coord, i) for i, coord in enumerate(allPointsSet))) self.setnVecPos(len(allPointsSet)) - print "Finished Coord2BitVecPos" + print("Finished Coord2BitVecPos") def allPointsSetfromCoord2BVP(self): allPointsSet = set() - for coord in self.getCoord2BitVecPos().iterkeys(): + for coord in self.getCoord2BitVecPos().keys(): allPointsSet.add( coord ) return allPointsSet @@ -2712,8 +2712,8 @@ def addFeature(self, coord): def getFeatureMap(self, index): tempBitVector = self.getBitVector()[index] - print tempBitVector - myArray = np.array([coord for coord in self.getCoord2BitVecPos().keys() if tempBitVector[self.getCoord2BitVecPos()[coord]]]) + print(tempBitVector) + myArray = np.array([coord for coord in list(self.getCoord2BitVecPos().keys()) if tempBitVector[self.getCoord2BitVecPos()[coord]]]) return featureMap.fromPovmeList(myArray, 1) @classmethod @@ -2737,21 +2737,21 @@ def fromNumpyCoordFiles(self, fileList): return thisFME def saveToNPZ(self,outfile): - print "Saving file to %s" %outfile + print("Saving file to %s" %outfile) np.savez(outfile, self.getBitVector(), self.getCoord2BitVecPos()) - print "Finished saving to file" + print("Finished saving to file") def loadFromNPZ(self, infile): - print "Loading NPZ file" + print("Loading NPZ file") tempfile = np.load(infile) - print tempfile + print(tempfile) self.setBitVector(tempfile['arr_0']) self.setCoord2BitVecPos(tempfile['arr_1'].item()) self.setNumFeatureMaps(len(self.getBitVector())) self.setnVecPos(len(self.getCoord2BitVecPos())) - print len(self.getCoord2BitVecPos()) - print "Finished loading NPZ file" + print(len(self.getCoord2BitVecPos())) + print("Finished loading NPZ file") class algebra: @@ -2967,14 +2967,14 @@ def dockOne(self,receptorMaps, ligandMaps,translation_list,spherePoints): c=0 for [w,x,y,z] in spherePoints: c += 1 - print "Processing rotation %i of %i" %(c, len(spherePoints)) + print("Processing rotation %i of %i" %(c, len(spherePoints))) #Quaternions to Euler angles: #180/3.1415926 #zphi = 57.29578 * np.arctan2((w*y + x*z),-(x*y - w*z)) #xtheta = 57.29578 * np.arccos(-w**2 - x**2 + y**2 + z**2) #zpsi = 57.29578 * np.arctan2((w*y - x*z),(x*y + w*z)) rotatedArrays = copy.deepcopy(ligandMaps) - for feature in rotatedArrays.keys(): + for feature in list(rotatedArrays.keys()): rotatedArrays[feature].interpolation_rotate_inplace([w,x,y,z]) #print zphi, xtheta, zpsi #for feature in rotatedArrays.keys(): @@ -2990,7 +2990,7 @@ def dockOne(self,receptorMaps, ligandMaps,translation_list,spherePoints): #shiftedArray = sni.shift(receptorMap,[X,Y,Z]) shiftedArrays = copy.deepcopy(rotatedArrays) - for feature in shiftedArrays.keys(): + for feature in list(shiftedArrays.keys()): shiftedArrays[feature].translate_inplace([X,Y,Z]) #shiftedArrays[feature].borders = [shiftedArrays[feature].borders[0]+X, # shiftedArrays[feature].borders[1]+X, @@ -3015,19 +3015,19 @@ def dockOne(self,receptorMaps, ligandMaps,translation_list,spherePoints): successfulDockings.append([[X,Y,Z],[w,x,y,z],scores]) #print [[X,Y,Z],[w,x,y,z],scores] successfulDockings.sort(key=lambda x: sum(x[2]), reverse = True) - print "Docking complete!" + print("Docking complete!") return successfulDockings def dockPeel(self,receptorMaps, ligandPeel, translation_list,spherePoints): - resolution = receptorMaps[receptorMaps.keys()[0]].getReso() + resolution = receptorMaps[list(receptorMaps.keys())[0]].getReso() #successfulDockings = np.array(['Translation Steps','Rotation Quaternion','Score'],dtype='string_') successfulDockings=[] c=0 for [w,x,y,z] in spherePoints: c += 1 - print "Processing rotation %i of %i: %s" %(c, len(spherePoints), str([w,x,y,z])) + print("Processing rotation %i of %i: %s" %(c, len(spherePoints), str([w,x,y,z]))) #Quaternions to Euler angles: #180/3.1415926 #zphi = 57.29578 * np.arctan2((w*y + x*z),-(x*y - w*z)) @@ -3098,7 +3098,7 @@ def dockPeel(self,receptorMaps, ligandPeel, translation_list,spherePoints): #shiftedMaps = copy.deepcopy(rotatedMaps) - for feature in shiftedMaps.keys(): + for feature in list(shiftedMaps.keys()): shiftedMaps[feature].translate_inplace([dXAngstroms,dYAngstroms,dZAngstroms]) #shiftedMaps[feature].translate_inplace([X,Y,Z]) #shiftedMaps[feature].borders = [shiftedMaps[feature].borders[0]+X, @@ -3122,12 +3122,12 @@ def dockPeel(self,receptorMaps, ligandPeel, translation_list,spherePoints): successfulDockings.append([[absXAngstroms,absYAngstroms,absZAngstroms],[w,x,y,z],scores]) #print [[X,Y,Z],[w,x,y,z],scores] successfulDockings.sort(key=lambda x: sum(x[2]), reverse = True) - print "Docking complete!" + print("Docking complete!") return successfulDockings def printLastScores(self): if self.lastScores != None: - print '\n'.join(['%.5e\t%s'%(score, func) for func, score in zip(self.lastStringScoreFuncs, self.lastScores)]) + print('\n'.join(['%.5e\t%s'%(score, func) for func, score in zip(self.lastStringScoreFuncs, self.lastScores)])) @@ -3142,7 +3142,7 @@ class peel: # return '_'.join(list) def hashtable_entry_add_one(self, hashtable, key, toadd = 1): # note that dictionaries (hashtables) are passed by reference in python - if hashtable.has_key(key): + if key in hashtable: hashtable[key] = hashtable[key] + toadd else: hashtable[key] = toadd @@ -3448,7 +3448,7 @@ def color_povme_map(self, povmeMatrix, gridReso, features = ['hbondAcceptor','hb #Turning into a set so the hash search will be fast #povmeSet = set([ tuple(i) for i in povmeList]) - for feature in colorMaps.keys(): + for feature in list(colorMaps.keys()): completePointList = colorMaps[feature].toPovmeList() #Only return points that were available in the POVME list beforehand #THIS COULD BE IMPROVED @@ -3543,11 +3543,11 @@ def characterize_ligand_occupancies(self): for this_atom in self.receptor.AllAtoms: this_element = self.receptor.AllAtoms[this_atom].element coordinates_pt = self.receptor.AllAtoms[this_atom].coordinates - if this_element in radii.keys(): + if this_element in list(radii.keys()): #print self.receptor.AllAtoms[this_atom].coordinates, radii[this_element] self.features['occupancies'][this_atom] = {'coordinates':coordinates_pt, 'radius':radii[this_element]} else: - print "WARNING: Atom type %s is not C, H, O, N P, S, or F. Assuming atomic radius of 2 angstroms" %(this_element) + print("WARNING: Atom type %s is not C, H, O, N P, S, or F. Assuming atomic radius of 2 angstroms" %(this_element)) self.features['occupancies'][this_atom] = {'coordinates':coordinates_pt, 'radius': 2.0} @@ -3865,10 +3865,10 @@ def characterize_occupancies(self): this_element = this_atom_info['element_stripped'] receptor_atom_index = self.receptor.selections.select_atoms({'serial':this_serial}) coordinates_pt = point(self.receptor.get_coordinates()[receptor_atom_index][0]) - if this_element in radii.keys(): + if this_element in list(radii.keys()): self.features['occupancies'][this_serial] = {'coordinates': coordinates_pt, 'radius':radii[this_element]} else: - print "WARNING: Atom type %s is not C, H, O, N P, S, or F. Assuming atomic radius of 2 angstroms" %(this_element) + print("WARNING: Atom type %s is not C, H, O, N P, S, or F. Assuming atomic radius of 2 angstroms" %(this_element)) self.features['occupancies'][this_atom_info['serial']] = {'coordinates':coordinates_pt, 'radius':2.0} @@ -3985,16 +3985,16 @@ def write_vmd_script(self, vmdScriptName, parameters): def rotate(self, quaternion, center='average'): if center == 'average': coords = [] - for feature in self.features.keys(): - for key in self.features[feature].keys(): + for feature in list(self.features.keys()): + for key in list(self.features[feature].keys()): coords.append(self.features[feature][key]['coordinates'].coords()) coords = np.array(coords) center = np.array([np.mean(coords[:,0]), np.mean(coords[:,1]), np.mean(coords[:,2])]) #Move whole thing to be vcentered around 0,0,0 self.translate(-1.0*center) - for feature in self.features.keys(): - for index in self.features[feature].keys(): + for feature in list(self.features.keys()): + for index in list(self.features[feature].keys()): oldCoordsList = self.features[feature][index]['coordinates'].coords() oldMagnitude = self.features[feature][index]['coordinates'].magnitude() #rotation = self.functions.axisangle_to_q(quaternion[1:], np.arcsin(quaternion[0])*2) @@ -4012,8 +4012,8 @@ def rotate(self, quaternion, center='average'): def translate(self, vector): - for feature in self.features.keys(): - for key in self.features[feature].keys(): + for feature in list(self.features.keys()): + for key in list(self.features[feature].keys()): oldCoords = self.features[feature][key]['coordinates'].coords() newCoords = oldCoords + np.array(vector) self.features[feature][key]['coordinates'] = point(newCoords) @@ -4088,44 +4088,44 @@ def intro(): - print " ..I?+?. " - print " ..$7$7. " - print " ..$$Z, " - print " ..I$$O?. " - print " :??7$$$. " - print " .=????7III " - print " ..I?????I???.. " - print " ...???????I????. " - print " ..?+??????I????? " - print " .??I??????II????+. " - print " ~?II??????II+???=+.. " - print " .??I+??????II????+=+. " - print " .+?I,???????I?????+~:, " - print " .+I?~???????+I????++~~:~.. " - print " .+??==???????=+?+++++:~~:~~:..... " - print " .++?+.???????+~+?+++++,:~:~~~,:,:::,........ ....... " - print " .?=++=~++??+++:=??++++++~::,:~~::::~~:~=~~~~~~~~~?+=.. " - print " :+====?+++++++.=??++++++????=~~=~~::,:,,,,:::~==++= " - print " .+==~=+++++++++,=I?+++++++..:?77I????????????I7?... " - print " .:====~??+++++?++:I?+++++++~. .................. " - print " ..++=~=:+?++++++++??I?++++++??.. " - print " ..?~==~=~.??++++++++?7??++++++++,. " - print " ~=====~,.=?++++++++??7?+++++++++~ " - print " .==~~:==...=?+?+++++???7??+++++++?. " - print " .?===~=:~ ..??++?+++???7?I?++?++?,. " - print " .?=~=~~:=.. .7???++?+??7$7I?++III,. " - print " .==~~~:~:.. ..,777I???7$ODDMDNM, " - print " .,~~~~~=::. .~$II7ZOONMN. " - print " ..:=~~~=:?. .......,=I7I. " - print " ..=+=~==::. . .... " - print " ..?+===~~=. " - print " ~+==~~=~. " - print " .+?==~=:. " - print " ..I7II++. " - print " .=I$$$. " - print " .... " - print - print "Thanks for using peel.py. We are phasing out the command-line functionality for this program. Please see the examples for how peel.py can be imported and used in a variety of workflows." + print(" ..I?+?. ") + print(" ..$7$7. ") + print(" ..$$Z, ") + print(" ..I$$O?. ") + print(" :??7$$$. ") + print(" .=????7III ") + print(" ..I?????I???.. ") + print(" ...???????I????. ") + print(" ..?+??????I????? ") + print(" .??I??????II????+. ") + print(" ~?II??????II+???=+.. ") + print(" .??I+??????II????+=+. ") + print(" .+?I,???????I?????+~:, ") + print(" .+I?~???????+I????++~~:~.. ") + print(" .+??==???????=+?+++++:~~:~~:..... ") + print(" .++?+.???????+~+?+++++,:~:~~~,:,:::,........ ....... ") + print(" .?=++=~++??+++:=??++++++~::,:~~::::~~:~=~~~~~~~~~?+=.. ") + print(" :+====?+++++++.=??++++++????=~~=~~::,:,,,,:::~==++= ") + print(" .+==~=+++++++++,=I?+++++++..:?77I????????????I7?... ") + print(" .:====~??+++++?++:I?+++++++~. .................. ") + print(" ..++=~=:+?++++++++??I?++++++??.. ") + print(" ..?~==~=~.??++++++++?7??++++++++,. ") + print(" ~=====~,.=?++++++++??7?+++++++++~ ") + print(" .==~~:==...=?+?+++++???7??+++++++?. ") + print(" .?===~=:~ ..??++?+++???7?I?++?++?,. ") + print(" .?=~=~~:=.. .7???++?+??7$7I?++III,. ") + print(" .==~~~:~:.. ..,777I???7$ODDMDNM, ") + print(" .,~~~~~=::. .~$II7ZOONMN. ") + print(" ..:=~~~=:?. .......,=I7I. ") + print(" ..=+=~==::. . .... ") + print(" ..?+===~~=. ") + print(" ~+==~~=~. ") + print(" .+?==~=:. ") + print(" ..I7II++. ") + print(" .=I$$$. ") + print(" .... ") + print() + print("Thanks for using peel.py. We are phasing out the command-line functionality for this program. Please see the examples for how peel.py can be imported and used in a variety of workflows.") if __name__=='__main__': diff --git a/POVME/packages/binana/tests/algebra_basic/testBasicFmaps.py b/POVME/packages/binana/tests/algebra_basic/testBasicFmaps.py index ccbff8e..2dbcd19 100644 --- a/POVME/packages/binana/tests/algebra_basic/testBasicFmaps.py +++ b/POVME/packages/binana/tests/algebra_basic/testBasicFmaps.py @@ -11,27 +11,27 @@ one_point_fmaps_1 = my_peel.create_feature_maps([0,0,0,0,0,0], 1, features) one_point_fmaps_2 = my_peel.create_feature_maps([0,0,0,0,0,0], 1, features) -print -print '======Beginning scoring ======' +print() +print('======Beginning scoring ======') for i in range(len(features)): #So the point of featuremap_1 for aromatic will be set to 0, hBondDonor 2, etc... one_point_fmaps_1[features[i]].setData(numpy.array([[[2*i]]])) #So the point of featuremap_2 for aromatic will be set to 1, hBondDonor 3, etc... one_point_fmaps_2[features[i]].setData(numpy.array([[[(2*i)+1]]])) - print 'Setting %s to be %i for featuremap_A and %i for featuremap_B' %(features[i], i*2, (i*2)+1) + print('Setting %s to be %i for featuremap_A and %i for featuremap_B' %(features[i], i*2, (i*2)+1)) my_algebra = peel.algebra() my_score_funcs = ['hbondAcceptor_A * hbondDonor_B', 'hbondAcceptor_B * hbondDonor_A'] my_algebra.setScoreFuncs(my_score_funcs) my_score_maps, my_scores = my_algebra.scoreAll(one_point_fmaps_1, one_point_fmaps_2) -print '\n'.join(['%.5e\t%s'%(score, func) for func, score in zip(my_score_funcs, my_scores)]) +print('\n'.join(['%.5e\t%s'%(score, func) for func, score in zip(my_score_funcs, my_scores)])) -print -print 'Now trying out meaner score functions' -print +print() +print('Now trying out meaner score functions') +print() mean_score_funcs = ['-2 * hydrophobic_A * hydrophobic_B', 'hbondAcceptor_A * numpy.sqrt(hbondDonor_B)', @@ -45,14 +45,14 @@ my_algebra.setScoreFuncs(mean_score_funcs) my_score_maps, my_scores = my_algebra.scoreAll(one_point_fmaps_1, one_point_fmaps_2) -print '\n'.join(['%.5e\t%s'%(score, func) for func, score in zip(mean_score_funcs, my_scores)]) +print('\n'.join(['%.5e\t%s'%(score, func) for func, score in zip(mean_score_funcs, my_scores)])) -print -print 'Now trying out previously buggy score functions' -print +print() +print('Now trying out previously buggy score functions') +print() buggy_score_funcs = ['hbondAcceptor_A * hbondDonor_B', 'hbondAcceptor_B * hbondDonor_A','-(hbondDonor_A * hbondDonor_B)'] my_algebra.setScoreFuncs(buggy_score_funcs) my_score_maps, my_scores = my_algebra.scoreAll(one_point_fmaps_1, one_point_fmaps_2) -print '\n'.join(['%.5e\t%s'%(score, func) for func, score in zip(buggy_score_funcs, my_scores)]) +print('\n'.join(['%.5e\t%s'%(score, func) for func, score in zip(buggy_score_funcs, my_scores)])) diff --git a/POVME/packages/binana/tests/algebra_dock_basic/testBasicFmaps.py b/POVME/packages/binana/tests/algebra_dock_basic/testBasicFmaps.py index 8f46562..efad9e2 100644 --- a/POVME/packages/binana/tests/algebra_dock_basic/testBasicFmaps.py +++ b/POVME/packages/binana/tests/algebra_dock_basic/testBasicFmaps.py @@ -11,27 +11,27 @@ one_point_fmaps_1 = my_peel.create_feature_maps([0,3,0,3,0,3], 1, features) one_point_fmaps_2 = my_peel.create_feature_maps([0,3,0,3,0,3], 1, features) -print -print '======Beginning scoring ======' +print() +print('======Beginning scoring ======') for i in range(len(features)): #So the point of featuremap_1 for aromatic will be set to 0, hBondDonor 2, etc... one_point_fmaps_1[features[i]].setData(numpy.array([[[0,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,0]],[[2*i,0,0],[0,0,0],[0,0,0]]])) #So the point of featuremap_2 for aromatic will be set to 1, hBondDonor 3, etc... one_point_fmaps_2[features[i]].setData(numpy.array([[[0,0,0],[0,0,0],[0,0,(2*i)+1]],[[0,0,0],[0,0,0],[0,0,0]],[[0,0,0],[0,0,0],[0,0,0]]])) - print 'Setting %s to be %i for featuremap_A and %i for featuremap_B' %(features[i], i*2, (i*2)+1) + print('Setting %s to be %i for featuremap_A and %i for featuremap_B' %(features[i], i*2, (i*2)+1)) my_algebra = peel.algebra() my_score_funcs = ['hbondAcceptor_A * hbondDonor_B', 'hbondAcceptor_B * hbondDonor_A'] my_algebra.setScoreFuncs(my_score_funcs) my_score_maps, my_scores = my_algebra.scoreAll(one_point_fmaps_1, one_point_fmaps_2) -print '\n'.join(['%.5e\t%s'%(score, func) for func, score in zip(my_score_funcs, my_scores)]) +print('\n'.join(['%.5e\t%s'%(score, func) for func, score in zip(my_score_funcs, my_scores)])) -print -print 'Now trying out meaner score functions' -print +print() +print('Now trying out meaner score functions') +print() mean_score_funcs = ['-2 * hydrophobic_A * hydrophobic_B', 'hbondAcceptor_A * numpy.sqrt(hbondDonor_B)', @@ -45,11 +45,11 @@ my_algebra.setScoreFuncs(mean_score_funcs) my_score_maps, my_scores = my_algebra.scoreAll(one_point_fmaps_1, one_point_fmaps_2) -print '\n'.join(['%.5e\t%s'%(score, func) for func, score in zip(mean_score_funcs, my_scores)]) +print('\n'.join(['%.5e\t%s'%(score, func) for func, score in zip(mean_score_funcs, my_scores)])) -print -print 'Now trying out previously buggy score functions' -print +print() +print('Now trying out previously buggy score functions') +print() buggy_score_funcs = ['hbondAcceptor_A * hbondDonor_B', 'hbondAcceptor_B * hbondDonor_A', @@ -57,4 +57,4 @@ my_algebra.setScoreFuncs(buggy_score_funcs) my_score_maps, my_scores = my_algebra.scoreAll(one_point_fmaps_1, one_point_fmaps_2) -print '\n'.join(['%.5e\t%s'%(score, func) for func, score in zip(buggy_score_funcs, my_scores)]) +print('\n'.join(['%.5e\t%s'%(score, func) for func, score in zip(buggy_score_funcs, my_scores)])) diff --git a/POVME/packages/binana/tests/algebra_dock_complex/exampleDock.py b/POVME/packages/binana/tests/algebra_dock_complex/exampleDock.py index 32e2a65..65c6613 100644 --- a/POVME/packages/binana/tests/algebra_dock_complex/exampleDock.py +++ b/POVME/packages/binana/tests/algebra_dock_complex/exampleDock.py @@ -5,7 +5,7 @@ import sys import os import scipy.ndimage.interpolation as sni -import cPickle +import pickle import csv @@ -72,7 +72,7 @@ def profiled_func(*args, **kwargs): spherePoints = numpy.genfromtxt(outputFile + '.out',skip_header=3, skip_footer=0, usecols=(4,5,6,7), comments='}') #spherePoints = [[0,1,0,0]] -print spherePoints +print(spherePoints) @@ -92,7 +92,7 @@ def profiled_func(*args, **kwargs): # y.append(n) #for n in numpy.arange(0,receptorDim[2]-ligandDim[2],cubeLength): # z.append(n) -translation_list = list(itertools.product(range(-8,9,2),range(-8,9,2),range(-8,9,2))) +translation_list = list(itertools.product(list(range(-8,9,2)),list(range(-8,9,2)),list(range(-8,9,2)))) #print translation_list my_score_functions = ['hydrophobic_A * hydrophobic_B', 'hydrophilic_A * hydrophilic_B', @@ -129,7 +129,7 @@ def do_docking(): a=do_docking() with open('results_%s.cPickle' %(ligandName), 'w') as fo: - cPickle.dump(a, fo) + pickle.dump(a, fo) diff --git a/POVME/packages/binana/tests/algebra_dock_complex/howDifferent.py b/POVME/packages/binana/tests/algebra_dock_complex/howDifferent.py index 2d5d30f..16323ed 100644 --- a/POVME/packages/binana/tests/algebra_dock_complex/howDifferent.py +++ b/POVME/packages/binana/tests/algebra_dock_complex/howDifferent.py @@ -1,4 +1,4 @@ -import cPickle +import pickle import numpy ### This is a very rudimentary script to kind of help with debugging this horrible test case orig = numpy.load(open('results_2QO8-results_11032.pdb.cPickle.orig')) @@ -8,4 +8,4 @@ for i,j in zip(orig,new): if i != j: diff= numpy.array(i[2])-numpy.array(j[2]) - print diff + print(diff) diff --git a/POVME/packages/binana/tests/algebra_func_input/funcInputTest.py b/POVME/packages/binana/tests/algebra_func_input/funcInputTest.py index 0b57f41..c93b8d3 100644 --- a/POVME/packages/binana/tests/algebra_func_input/funcInputTest.py +++ b/POVME/packages/binana/tests/algebra_func_input/funcInputTest.py @@ -25,26 +25,26 @@ my_algebra = peel.algebra() -print -print -print 'The scoring function components are originally:' -print '\n'.join(my_algebra.getScoreFuncs()) -print -print "However, I'd prefer them to be" +print() +print() +print('The scoring function components are originally:') +print('\n'.join(my_algebra.getScoreFuncs())) +print() +print("However, I'd prefer them to be") my_score_funcs = ['-2 * hydrophobic_A * hydrophobic_B', 'hbondAcceptor_A * numpy.sqrt(hbondDonor_B)', 'numpy.sqrt(hbondDonor_A) * hbondAcceptor_B', '-aromatic_A - aromatic_B', '0.0001 * numpy.exp( hydrophobicity_A * hydrophobicity_B )'] -print '\n'.join(my_score_funcs) +print('\n'.join(my_score_funcs)) my_algebra.setScoreFuncs(my_score_funcs) my_score_maps, my_scores = my_algebra.scoreAll(fmaps_1, fmaps_2) -print 'The scores for each term are' -print '\n'.join(['%.5e\t%s'%(score, func) for func, score in zip(my_score_funcs, my_scores)]) +print('The scores for each term are') +print('\n'.join(['%.5e\t%s'%(score, func) for func, score in zip(my_score_funcs, my_scores)])) my_score_maps[0].write_dx_file('term1.dx') my_score_maps[1].write_dx_file('term2.dx') diff --git a/POVME/packages/binana/tests/algebra_peel_dock/howDifferent.py b/POVME/packages/binana/tests/algebra_peel_dock/howDifferent.py index b6aa7cc..84ee678 100644 --- a/POVME/packages/binana/tests/algebra_peel_dock/howDifferent.py +++ b/POVME/packages/binana/tests/algebra_peel_dock/howDifferent.py @@ -1,4 +1,4 @@ -import cPickle +import pickle import numpy ### This is a very rudimentary script to kind of help with debugging this horrible test case orig = numpy.load(open('results_2B52-results_5645.pdb.cPickle.orig')) @@ -8,4 +8,4 @@ for i,j in zip(orig,new): if i != j: diff= numpy.array(i[2])-numpy.array(j[2]) - print diff + print(diff) diff --git a/POVME/packages/binana/tests/algebra_peel_dock/peelDock.py b/POVME/packages/binana/tests/algebra_peel_dock/peelDock.py index 4383216..3eb7758 100644 --- a/POVME/packages/binana/tests/algebra_peel_dock/peelDock.py +++ b/POVME/packages/binana/tests/algebra_peel_dock/peelDock.py @@ -5,7 +5,7 @@ import sys import os import scipy.ndimage.interpolation as sni -import cPickle +import pickle import csv features = ['aromatic','hbondAcceptor','hbondDonor','hydrophilic','hydrophobic','occupancy','adjacency'] @@ -54,7 +54,7 @@ comments='}') spherePoints[0,:] = numpy.array([0.,1.,0.,0.]) #spherePoints = [[0,1,0,0]] -print spherePoints +print(spherePoints) @@ -74,7 +74,7 @@ # y.append(n) #for n in numpy.arange(0,receptorDim[2]-ligandDim[2],cubeLength): # z.append(n) -translation_list = list(itertools.product(range(-8,9,2),range(-8,9,2),range(-8,9,2))) +translation_list = list(itertools.product(list(range(-8,9,2)),list(range(-8,9,2)),list(range(-8,9,2)))) #print translation_list my_score_functions = ['hydrophobic_A * hydrophobic_B', 'hydrophilic_A * hydrophilic_B', @@ -95,7 +95,7 @@ a = my_algebra.dockPeel(receptorData, ligandPeel, translation_list, spherePoints) with open('%s/results_%s.cPickle' %(outputDir, ligandName), 'w') as fo: - cPickle.dump(a, fo) + pickle.dump(a, fo) diff --git a/POVME/packages/binana/tests/peel_2gfc_basic/2gfcTest.py b/POVME/packages/binana/tests/peel_2gfc_basic/2gfcTest.py index 3864288..be0b0a6 100644 --- a/POVME/packages/binana/tests/peel_2gfc_basic/2gfcTest.py +++ b/POVME/packages/binana/tests/peel_2gfc_basic/2gfcTest.py @@ -28,4 +28,4 @@ #my_feature_maps['hydrophobicity'].write_dx_file('HPBTY.dx') -print "Done!" +print("Done!") diff --git a/POVME/packages/binana/tests/peel_arg_basic/argTest.py b/POVME/packages/binana/tests/peel_arg_basic/argTest.py index 70774e0..049d261 100644 --- a/POVME/packages/binana/tests/peel_arg_basic/argTest.py +++ b/POVME/packages/binana/tests/peel_arg_basic/argTest.py @@ -34,4 +34,4 @@ #HBAPoints = numpy.transpose(numpy.nonzero(HBAMap)) #print HBAPoints -print "Done!" +print("Done!") diff --git a/POVME/packages/binana/tests/peel_dock_parameter_optimization/analyzeAll_customDir.py b/POVME/packages/binana/tests/peel_dock_parameter_optimization/analyzeAll_customDir.py index 78dcb07..828ce25 100644 --- a/POVME/packages/binana/tests/peel_dock_parameter_optimization/analyzeAll_customDir.py +++ b/POVME/packages/binana/tests/peel_dock_parameter_optimization/analyzeAll_customDir.py @@ -1,4 +1,4 @@ -import cPickle +import pickle import sys import numpy import glob @@ -6,7 +6,7 @@ import copy import sys import threading -import Queue +import queue import time ligands = [] @@ -22,17 +22,17 @@ def loadPickle(this_q, this_filename): fo = gzip.open(this_filename,'rb') #this_scoreList = cPickle.load(fo) data = fo.read() - this_scoreList = cPickle.loads(data) + this_scoreList = pickle.loads(data) fo.close() this_q.put((filePrefix, this_scoreList)) #this_scoreList2 = copy.deepcopy(this_scoreList) #this_q.put((filePrefix, this_scoreList, this_scoreList2)) -q = Queue.Queue() +q = queue.Queue() threadList = [] for filename in glob.glob('%s/results*' %(resultsDir))[:30]: #for filename in glob.glob('%s/results*' %(resultsDir))[:200]: - print filename + print(filename) #filePrefix = filename.replace(resultsDir,'').replace('.cPickle','') #ligands.append(filePrefix) @@ -48,7 +48,7 @@ def loadPickle(this_q, this_filename): while sum([i.is_alive() for i in threadList]) != 0: time.sleep(1) c += 1 - print 'waiting for threads %i sec:' %(c), [i.is_alive() for i in threadList] + print('waiting for threads %i sec:' %(c), [i.is_alive() for i in threadList]) while not q.empty(): prefix, scoreList = q.get() ligands.append(prefix) @@ -86,7 +86,7 @@ def loadPickle(this_q, this_filename): for ligand in ligands: #minRotation[ligand] = sorted(list(rotations[ligand]), key=lambda x:abs(x[0]))[0] minRotation[ligand] = sorted(list(rotations[ligand]), key=lambda x:abs(x[0]))[-1] -print minRotation +print(minRotation) ##Get normalization factors @@ -109,7 +109,7 @@ def loadPickle(this_q, this_filename): ligandMeans[ligand] = numpy.array(ligandMeans[ligand]) #Avoid dividing by 0 ligandMeans[ligand][ligandMeans[ligand] == 0.0] = 1. -print ligandMeans +print(ligandMeans) ###This comes in handy when scoring later template_scoreListDict = {} @@ -177,9 +177,9 @@ def scoreAll(factors): def rankFactors(factors): #This function takes a list of weighting factors and returns the rank that 0,0,0 gets when using them as multipliers on the score terms #this_bestScoreTransList = getBestTranslations(factors) - print factors + print(factors) this_scoreListDict = scoreAll(factors) - print 'scored!' + print('scored!') ranks = [] for ligand in ligands: if 1: @@ -207,7 +207,7 @@ def rankFactors(factors): rank = numpy.count_nonzero(this_scoreListDict[ligand][:,7]>tripleZScore) ranks.append(rank) break - print sum(ranks) + print(sum(ranks)) return sum(ranks) #for i, row in enumerate(this_bestScoreTransList): # if (row[:3] == numpy.array([0,0,0])).all(): @@ -228,7 +228,7 @@ def scoreFactors(factors): ''' def print_parameters(x): - print x + print(x) import scipy.optimize @@ -280,7 +280,7 @@ def print_parameters(x): (-200,200)) ) -print 'OPTIMIZATION STATS:', my_optimization +print('OPTIMIZATION STATS:', my_optimization) optimizedFactors = my_optimization.x ''' @@ -290,8 +290,8 @@ def print_parameters(x): ''' optimizedFactors = numpy.array([ 6.27265804e-01, 4.54168056e+00, 5.46248338e+00, -1.87883923e+00, 1.44989168e+00, 3.79782140e-01, 5.51136641e-04, -2.47446270e-03, 1.14398554e+00, 2.64094296e-03, -2.12394170e-03, -2.48873856e-03, -9.11841469e-04, 7.13814468e-01, -1.06753076e+00, 2.37556547e+00, 1.97917698e+00, -2.62286481e+00]) ''' -print 'OPTIMIZATION FINISHED!!!!!!' -print optimizedFactors +print('OPTIMIZATION FINISHED!!!!!!') +print(optimizedFactors) #bestScoreTransList = getBestTranslations(my_optimization.x) @@ -324,7 +324,7 @@ def print_parameters(x): #for ligand in ligands: for row in finalScoreList: - if row[0] == 0 and row[1] == 0 and row[2] == 0 and tuple(row[3:7]) in minRotation.values(): + if row[0] == 0 and row[1] == 0 and row[2] == 0 and tuple(row[3:7]) in list(minRotation.values()): pylab.scatter([0],[row[7]], color='r', s=100) h, xedges, yedges = numpy.histogram2d(distScoreList[:,0], distScoreList[:,1], bins=50) diff --git a/POVME/packages/binana/tests/peel_dock_parameter_optimization/parameterTest.py b/POVME/packages/binana/tests/peel_dock_parameter_optimization/parameterTest.py index 27b4806..c39dec3 100644 --- a/POVME/packages/binana/tests/peel_dock_parameter_optimization/parameterTest.py +++ b/POVME/packages/binana/tests/peel_dock_parameter_optimization/parameterTest.py @@ -9,7 +9,7 @@ # It returns the sum of the ranks of the correct placements. The best combination of parameters would minimize the sum of the correct ranks (for instance, the correct placements should all be in 1st place given a perfect scoring function). import copy -import cPickle +import pickle import os import os.path import glob @@ -51,7 +51,7 @@ numpy.arange(-8./gridResolution,8.001/gridResolution,2./gridResolution), numpy.arange(-8./gridResolution,8.001/gridResolution,2./gridResolution))) -print docking_translation_list[0] +print(docking_translation_list[0]) my_score_functions = ['hydrophobic_A * hydrophobic_B', 'hydrophilic_A * hydrophilic_B', 'hydrophilic_A * hydrophobic_B', @@ -119,14 +119,14 @@ # Now save the featureMaps for this protein #with gzip.open('%s/%s_featureMaps.cPickle.gz' %(proteinFmOutputDir, proteinPdbPrefix),'wb') as my_file: my_file = gzip.open('%s/%s_featureMaps.cPickle.gz' %(proteinFmOutputDir, proteinPdbPrefix),'wb') - cPickle.dump(protein_feature_maps, my_file, protocol=2) + pickle.dump(protein_feature_maps, my_file, protocol=2) my_file.close() else: #If the job is marked as started, let's see if it's finished. If so, load that receptor map if os.path.exists('%s/%s_featureMaps.cPickle.gz' %(proteinFmOutputDir, proteinPdbPrefix)): #with gzip.open('%s/%s_featureMaps.cPickle.gz' %(proteinFmOutputDir, proteinPdbPrefix),'rb') as my_file: my_file = gzip.open('%s/%s_featureMaps.cPickle.gz' %(proteinFmOutputDir, proteinPdbPrefix),'rb') - protein_feature_maps = cPickle.load(my_file) + protein_feature_maps = pickle.load(my_file) my_file.close() #Otherwise, there's probably another process working on making the feature map for this protein. #Skip it and go onto the next @@ -148,7 +148,7 @@ #with gzip.open('%s/results_%s.cPickle.gz' %(dockingResultsOutputDir, ligandPrefix), 'wb') as my_file: my_file = gzip.open('%s/results_%s.cPickle.gz' %(dockingResultsOutputDir, ligandPrefix), 'wb') - cPickle.dump(results, my_file, protocol=2) + pickle.dump(results, my_file, protocol=2) my_file.close() #else: # #with gzip.open('%s/results_%s.cPickle.gz' %(dockingResultsOutputDir, ligandPrefix), 'rb') as my_file: @@ -170,9 +170,9 @@ def scoreAll(factors): def rankFactors(factors): #This function takes a list of weighting factors and returns the rank that 0,0,0 gets when using them as multipliers on the score terms - print factors + print(factors) this_scoreListDict = scoreAll(factors) - print 'scored!' + print('scored!') ranks = [] for ligand in ligands: for i, row in enumerate(this_scoreListDict[ligand]): @@ -182,7 +182,7 @@ def rankFactors(factors): #print row ranks.append(i) break - print sum(ranks) + print(sum(ranks)) return sum(ranks) ligands = [] @@ -192,12 +192,12 @@ def rankFactors(factors): os.system('touch %s' %(analysisStartedFlagFilename)) allScoreListDict = {} for filename in glob.glob('%s/results*' %(analysisOutputDir)): - print filename + print(filename) filePrefix = filename.replace(analysisOutputDir,'').replace('.cPickle','') ligands.append(filePrefix) #with gzip.open(filename, 'rb') as my_file: my_file = gzip.open(filename,'rb') - scoreList = cPickle.load(my_file) + scoreList = pickle.load(my_file) my_file.close() allScoreListDict[filePrefix] = copy.deepcopy(scoreList) @@ -262,11 +262,11 @@ def rankFactors(factors): (-20,20)) ) - print 'OPTIMIZATION STATS:', my_optimization + print('OPTIMIZATION STATS:', my_optimization) optimizedFactors = my_optimization.x #with gzip.open('%s/optimization_results.cPickle.gz') as my_file: my_file = gzip.open('%s/optimization_results.cPickle.gz', 'wb') - cPickle.dump(my_optimization, my_file, protocol=2) + pickle.dump(my_optimization, my_file, protocol=2) my_file.close() @@ -281,7 +281,7 @@ def rankFactors(factors): #for ligand in ligands: for row in finalScoreList: - if row[0] == 0 and row[1] == 0 and row[2] == 0 and tuple(row[3:7]) in minRotation.values(): + if row[0] == 0 and row[1] == 0 and row[2] == 0 and tuple(row[3:7]) in list(minRotation.values()): pylab.scatter([0],[row[7]], color='r', s=100) h, xedges, yedges = numpy.histogram2d(distScoreList[:,0], distScoreList[:,1], bins=50) diff --git a/POVME/packages/binana/tests/peel_lig_basic/ligTest.py b/POVME/packages/binana/tests/peel_lig_basic/ligTest.py index e5cb13c..f60fd86 100644 --- a/POVME/packages/binana/tests/peel_lig_basic/ligTest.py +++ b/POVME/packages/binana/tests/peel_lig_basic/ligTest.py @@ -34,4 +34,4 @@ #HBAPoints = numpy.transpose(numpy.nonzero(HBAMap)) #print HBAPoints -print "Done!" +print("Done!") diff --git a/POVME/packages/binana/tests/peel_povme_conversion/conversionTest.py b/POVME/packages/binana/tests/peel_povme_conversion/conversionTest.py index 5963ae8..3d264b1 100644 --- a/POVME/packages/binana/tests/peel_povme_conversion/conversionTest.py +++ b/POVME/packages/binana/tests/peel_povme_conversion/conversionTest.py @@ -57,8 +57,8 @@ dxFile_povme2 = open('test2_volumetric_density.dx').read() if dxFile_povme1 != dxFile_peel: - print "dxFile_povme1 differs from dxFile_peel" + print("dxFile_povme1 differs from dxFile_peel") if dxFile_povme2 != dxFile_peel: - print "dxFile_povme2 differs from dxFile_peel" + print("dxFile_povme2 differs from dxFile_peel") if dxFile_povme1 != dxFile_povme2: - print "dxFile_povme1 differs from dxFile_povme2" + print("dxFile_povme1 differs from dxFile_povme2") diff --git a/POVME/packages/binana/tests/peel_receptor_basic/receptorLigandTest.py b/POVME/packages/binana/tests/peel_receptor_basic/receptorLigandTest.py index 13731a7..a17ebfb 100644 --- a/POVME/packages/binana/tests/peel_receptor_basic/receptorLigandTest.py +++ b/POVME/packages/binana/tests/peel_receptor_basic/receptorLigandTest.py @@ -34,4 +34,4 @@ my_ligand_feature_maps['aromatic'].write_dx_file('LIG_ARO.dx') my_ligand_feature_maps['hydrophobicity'].write_dx_file('LIG_HPBTY.dx') -print "Done!" +print("Done!") diff --git a/POVME/packages/binana/tests/peel_trp_basic/trpTest.py b/POVME/packages/binana/tests/peel_trp_basic/trpTest.py index 193ad62..570dcae 100644 --- a/POVME/packages/binana/tests/peel_trp_basic/trpTest.py +++ b/POVME/packages/binana/tests/peel_trp_basic/trpTest.py @@ -12,4 +12,4 @@ my_feature_maps['hbondDonor'].write_pdb('HBD.pdb') my_feature_maps['aromatic'].write_pdb('ARO.pdb') -print "Done!" +print("Done!") diff --git a/POVME/packages/binana/tests/runRegTests.py b/POVME/packages/binana/tests/runRegTests.py index c29c3e8..ecfc609 100644 --- a/POVME/packages/binana/tests/runRegTests.py +++ b/POVME/packages/binana/tests/runRegTests.py @@ -46,7 +46,7 @@ def compareFile(origFile, args): origFileData = remove_regex_lines(origFileData) newFile = origFile.replace('.orig','') if not os.path.exists(newFile): - print 'File %s does not exist - Unable to perform file comparison' %(newFile) + print('File %s does not exist - Unable to perform file comparison' %(newFile)) passed = False return passed newFileData = open(newFile).readlines() @@ -57,15 +57,15 @@ def compareFile(origFile, args): if newFileData == origFileData: #passedFiles.append(origFile) passed = True - print "Files %s and %s match!" %(newFile, origFile) + print("Files %s and %s match!" %(newFile, origFile)) else: #failedFiles.append(origFile) passed = False - print 'File %s DOES NOT MATCH' %(origFile) + print('File %s DOES NOT MATCH' %(origFile)) if args.compare == True: validChoice = False while validChoice == False: - choice = raw_input('Files %s and %s differ. View differences (y,n,v)? ' %(newFile, origFile)) + choice = input('Files %s and %s differ. View differences (y,n,v)? ' %(newFile, origFile)) if choice == 'y': ignoreStr = ' '.join(['-I %s' %(i) for i in regexes_to_ignore]) os.system('diff %s %s %s | less' %(ignoreStr, newFile, origFile)) @@ -89,14 +89,14 @@ def runTests(args): failedFiles = [] with Chdir(directory): - print + print() origFiles = glob.glob('*orig') if args.remove_old == True: files_to_remove = [i.replace('.orig','') for i in origFiles] for file_to_remove in files_to_remove: - print 'Removing', file_to_remove + print('Removing', file_to_remove) os.system('rm %s' %(file_to_remove)) - print "RUNNING TEST %s" %(linesp) + print("RUNNING TEST %s" %(linesp)) #os.system('%s python %s > output' %(arunPath,script)) #print '%s python %s/%s' %(arunPath, directory, script) start = time.time() @@ -106,18 +106,18 @@ def runTests(args): cwd = directory, shell=True) out, error = p.communicate() - print 'Test ran in %s seconds' %(time.time()-start) + print('Test ran in %s seconds' %(time.time()-start)) #print out, error results[title]['testPassed'] = True if p.returncode == 0: #if error == '': - print "Exit status: Completed" + print("Exit status: Completed") results[title]['exit_status'] = True else: - print "Exit status: Failed" - print 'error %s' %(error) + print("Exit status: Failed") + print('error %s' %(error)) results[title]['exit_status'] = False results[title]['testPassed'] = False @@ -135,23 +135,23 @@ def runTests(args): nPassed = 0 nFailed = 0 - print - print '===============' - print "RESULTS SUMMARY" - print '===============' + print() + print('===============') + print("RESULTS SUMMARY") + print('===============') for test in regTests: - print "----Test %s Exit Status = %s ----" %(test[0], results[test[0]]['exit_status']) - print "%i file comparisons succeeded: %s" %(len(results[test[0]]['passedFiles']), - results[test[0]]['passedFiles']) - print "%i file comparisons failed: %s" %(len(results[test[0]]['failedFiles']), results[test[0]]['failedFiles']) + print("----Test %s Exit Status = %s ----" %(test[0], results[test[0]]['exit_status'])) + print("%i file comparisons succeeded: %s" %(len(results[test[0]]['passedFiles']), + results[test[0]]['passedFiles'])) + print("%i file comparisons failed: %s" %(len(results[test[0]]['failedFiles']), results[test[0]]['failedFiles'])) if results[test[0]]['testPassed'] == True: nPassed += 1 else: nFailed += 1 - print - print '%i tests passed, %i tests failed' %(nPassed, nFailed) + print() + print('%i tests passed, %i tests failed' %(nPassed, nFailed)) if nFailed > 0: - print "TEST SUITE FAILED" + print("TEST SUITE FAILED") diff --git a/POVME/packages/clustering/binding_site_overlap.py b/POVME/packages/clustering/binding_site_overlap.py index 4a0ed9c..6e41314 100755 --- a/POVME/packages/clustering/binding_site_overlap.py +++ b/POVME/packages/clustering/binding_site_overlap.py @@ -43,7 +43,7 @@ def read_traj(self,traj_file, color): sortedFramesAndNames = [(int(re.findall('frame_([0-9]+).npy',name)[0]), name) for name in traj_file] sortedFramesAndNames.sort(key=lambda x:x[0]) sortedNames = [i[1] for i in sortedFramesAndNames] - print sortedNames + print(sortedNames) self.frames = len(sortedNames) for index, fileName in enumerate(sortedNames): self.volumetric_filename.append(fileName) @@ -99,14 +99,14 @@ def number_overlap(self,frame1,frame2): setFrame2 = self.coordinates[frame2] if not isinstance(setFrame1,set) or not isinstance(setFrame2,set): - print "Coordinates must be contained in a set object" + print("Coordinates must be contained in a set object") sys.exit(1) num_overlap_points = len(setFrame1.intersection(setFrame2)) '''Test here for error values ''' if num_overlap_points > min(len(setFrame1),len(setFrame2)): - print 'invalid overlap value' + print('invalid overlap value') return num_overlap_points # need to calculate the volume that is overlapped @@ -152,7 +152,7 @@ class main(): def __init__(self,argv): if len(argv) == 1: - print "Cannot run binding_site_overlap.py: Need to specify .npy files to be read" + print("Cannot run binding_site_overlap.py: Need to specify .npy files to be read") sys.exit(1) parser = OptionParser() @@ -185,7 +185,7 @@ def __init__(self,argv): hbondDon_overlap = Overlap(file_input.hbondDonor_coordinates) num_frames = len(file_input.coordinates) - print "The number of frames found was: {0}".format(num_frames) + print("The number of frames found was: {0}".format(num_frames)) '''Make a matrix of number of overlapping coordinates first''' @@ -236,7 +236,7 @@ def __init__(self,argv): '''Record the overlap_matrix in a csv file''' - print "Starting Tanimoto calculations" + print("Starting Tanimoto calculations") tanimoto_matrix = numpy.empty([file_input.frames,file_input.frames],dtype=float) @@ -266,18 +266,18 @@ def __init__(self,argv): colored_tanimoto_matrix[f1,f2] = average_similarity colored_tanimoto_matrix[f2,f1] = average_similarity - print "Overlap Matrix for Tanimoto calculation" - print tanimoto_matrix + print("Overlap Matrix for Tanimoto calculation") + print(tanimoto_matrix) if (options.color): - print "Aromatic" - print aromatic_tanimoto_matrix - print "Hydrogen Bond Acceptor" - print hbondAcc_tanimoto_matrix - print "Hydrogen Bond Donor" - print hbondDon_tanimoto_matrix + print("Aromatic") + print(aromatic_tanimoto_matrix) + print("Hydrogen Bond Acceptor") + print(hbondAcc_tanimoto_matrix) + print("Hydrogen Bond Donor") + print(hbondDon_tanimoto_matrix) - print "\n" + print("\n") if (options.csv): numpy.savetxt(os.getcwd()+'/POVME_Tanimoto_matrix.csv', tanimoto_matrix, delimiter=',') @@ -295,7 +295,7 @@ def __init__(self,argv): numpy.save('hbondDon_tanimoto_matrix.npy', hbondDon_tanimoto_matrix) - print "Starting Tversky calculations" + print("Starting Tversky calculations") tversky_matrix = numpy.empty([file_input.frames,file_input.frames],dtype=float) if (options.color): aromatic_tversky_matrix = numpy.empty([file_input.frames,file_input.frames],dtype=float) @@ -315,18 +315,18 @@ def __init__(self,argv): colored_tversky_matrix[f1,f2] = (hbondAcc_tversky_matrix[f1,f2] + hbondDon_tversky_matrix[f1,f2] + tversky_matrix[f1,f2] + aromatic_tversky_matrix[f1,f2])/4 - print "Overlap Matrix for Tversky calculation" - print tversky_matrix + print("Overlap Matrix for Tversky calculation") + print(tversky_matrix) if (options.color): - print "Aromatic" - print aromatic_tversky_matrix - print "Hydrogen Bond Acceptor" - print hbondAcc_tversky_matrix - print "Hydrogen Bond Donor" - print hbondDon_tversky_matrix + print("Aromatic") + print(aromatic_tversky_matrix) + print("Hydrogen Bond Acceptor") + print(hbondAcc_tversky_matrix) + print("Hydrogen Bond Donor") + print(hbondDon_tversky_matrix) - print "\n" + print("\n") if (options.csv): numpy.savetxt(os.getcwd()+'/POVME_Tversky_matrix.csv',tversky_matrix,delimiter=',') diff --git a/POVME/packages/clustering/binding_site_overlap_no_color.py b/POVME/packages/clustering/binding_site_overlap_no_color.py index e43cf4a..9458812 100644 --- a/POVME/packages/clustering/binding_site_overlap_no_color.py +++ b/POVME/packages/clustering/binding_site_overlap_no_color.py @@ -91,14 +91,14 @@ def number_overlap(self,frame1,frame2): setFrame2 = self.coordinates[frame2] if not isinstance(setFrame1,set) or not isinstance(setFrame2,set): - print "Coordinates must be contained in a set object" + print("Coordinates must be contained in a set object") sys.exit(1) num_overlap_points = len(setFrame1.intersection(setFrame2)) '''Test here for error values ''' if num_overlap_points > min(len(setFrame1),len(setFrame2)): - print 'invalid overlap value' + print('invalid overlap value') return num_overlap_points # need to calculate the volume that is overlapped @@ -152,10 +152,10 @@ def __init__(self,argv): for arg in argv: if ('.npy' in arg) and ('frame' in arg): command_input['traj_file'].append(arg) - print command_input['traj_file'] + print(command_input['traj_file']) if command_input == []: - print "You need to specify .npy files to be read" + print("You need to specify .npy files to be read") sys.exit(1) file_input = Trajectory() @@ -164,11 +164,11 @@ def __init__(self,argv): overlap_value = Overlap(file_input.coordinates) num_frames = len(file_input.coordinates) - print "The number of frames found was: {0}".format(num_frames) + print("The number of frames found was: {0}".format(num_frames)) ''' TEST TEST TEST ''' for i in range(len(file_input.coordinates)): - print "The number of atoms in {0} is {1}".format(file_input.frameToFileName[i],len(file_input.coordinates[i])) + print("The number of atoms in {0} is {1}".format(file_input.frameToFileName[i],len(file_input.coordinates[i]))) #print overlap_value.volumes '''TESTING HERE''' @@ -190,9 +190,9 @@ def __init__(self,argv): #print os.getcwd() #numpy.savetxt(os.getcwd()+'/POVME_Schrodinger_matrix_'+command_input['output_name']+'.csv', overlap_matrix, delimiter =',') - print "Starting Tanimoto calculations" + print("Starting Tanimoto calculations") - print "Overlap Matrix for Tanimoto calculation" + print("Overlap Matrix for Tanimoto calculation") tanimoto_matrix = numpy.empty([file_input.frames,file_input.frames],dtype=float) for f1 in range(num_frames): @@ -201,11 +201,11 @@ def __init__(self,argv): tanimoto_matrix[f1,f2] = tanimoto_result tanimoto_matrix[f2,f1] = tanimoto_result - print tanimoto_matrix + print(tanimoto_matrix) #numpy.savetxt(os.getcwd()+'/POVME_Tanimoto_matrix_'+command_input['output_name']+'.csv', tanimoto_matrix, delimiter=',') numpy.save(os.getcwd()+'/POVME_Tanimoto_matrix_'+command_input['output_name']+'.npy',tanimoto_matrix) - print "Starting Tversky calculations" + print("Starting Tversky calculations") tversky_matrix = numpy.empty([file_input.frames,file_input.frames],dtype=float) for f1 in range(num_frames): @@ -213,7 +213,7 @@ def __init__(self,argv): #print 'length of frame 1 = {0}'.format(len(overlap_value.coordinates[f1])) tversky_matrix[f1,f2] = overlap_value.tversky_overlap(f1, f2) - print tversky_matrix + print(tversky_matrix) #numpy.savetxt(os.getcwd()+'/POVME_Tversky_matrix_'+command_input['output_name']+'.csv',tversky_matrix,delimiter=',') numpy.save(os.getcwd()+'/POVME_Tversky_matrix_'+command_input['output_name']+'.npy',tversky_matrix) @@ -221,7 +221,7 @@ def __init__(self,argv): ''' Saving which index refers to which frame file for use in clustering ''' frames_dict = file_input.frameToFileName - print frames_dict + print(frames_dict) with open('indexMapToFrames.csv','wb') as csvfile: fieldnames = ['index','frame'] diff --git a/POVME/packages/clustering/cluster.py b/POVME/packages/clustering/cluster.py index 77e6bde..c5590da 100755 --- a/POVME/packages/clustering/cluster.py +++ b/POVME/packages/clustering/cluster.py @@ -156,28 +156,28 @@ def check_commandline_inputs(self): if (self.indexToNpyFile == {}) and (self.prefixToTrajectory != {}): raise Exception("ERROR! Given pdb trajectory (-t/T) but not given index file (-i). Output will return matrix indices instead of frame numbers or cluster representative structures.") elif self.indexToNpyFile == {}: - print "Not given index file (-i). Clustering will return matrix indices, but not trajectory frame numbers or members/representatives." + print("Not given index file (-i). Clustering will return matrix indices, but not trajectory frame numbers or members/representatives.") elif (self.indexToNpyFile != {}) and(self.prefixToTrajectory == {}): - print "Given index file (-i) but not prefix-to-trajectory mapping (-t or -T). Clustering will return prefix and frame numbers of cluster members, but will not extract representatives." + print("Given index file (-i) but not prefix-to-trajectory mapping (-t or -T). Clustering will return prefix and frame numbers of cluster members, but will not extract representatives.") elif (self.indexToNpyFile != {}) and (self.prefixToTrajectory != {}): - print "Given index file (-i) and prefix-to-trajectory mapping (-t or -T). Clustering will return prefix and frame numbers of cluster members, and will extract representatives." + print("Given index file (-i) and prefix-to-trajectory mapping (-t or -T). Clustering will return prefix and frame numbers of cluster members, and will extract representatives.") def ensure_file_prefixes_map_to_trajectories(self): if (self.prefixToTrajectory == {}) or (self.indexToNpyFile == {}): - print "No -i and/or -t/T arguments given - Skipping file-prefix-to-trajectory mapping completeness test" + print("No -i and/or -t/T arguments given - Skipping file-prefix-to-trajectory mapping completeness test") return else: allPrefixesSet = set(self.indexToPrefix.values()) for prefix in allPrefixesSet: - if not(prefix in self.prefixToTrajectory.keys()): - raise Exception('File prefix %s not found in -t arguments (which are %r)' %(prefix, self.prefixToTrajectory.keys())) + if not(prefix in list(self.prefixToTrajectory.keys())): + raise Exception('File prefix %s not found in -t arguments (which are %r)' %(prefix, list(self.prefixToTrajectory.keys()))) return def ensure_trajectories_exist(self): if self.prefixToTrajectory == {}: - print "No -t/T arguments given. Skipping trajectory-file-existence check" + print("No -t/T arguments given. Skipping trajectory-file-existence check") else: - for trajectoryFile in self.prefixToTrajectory.values(): + for trajectoryFile in list(self.prefixToTrajectory.values()): if not(os.path.exists(trajectoryFile)): raise Exception("Trajectory file %s not found" %(trajectoryFile)) @@ -190,8 +190,8 @@ def kmeans_cluster(self,number_clusters): #frames,result = scipy.cluster.vq.kmeans2(self.whited_overlap_values, number_clusters) code, dist = scipy.cluster.vq.vq(self.whited_overlap_values,frames) - print "The clusters are {0}".format(code) - print code.shape + print("The clusters are {0}".format(code)) + print(code.shape) list_of_clusters = self.separate_clusters(code) #return code return list_of_clusters @@ -265,7 +265,7 @@ def separate_clusters(self,cluster_results): # print "cluster results: {0}".format(cluster_results) total_num_clusters = len(set(cluster_results)) - list_clusters = [list([]) for i in xrange(total_num_clusters)] + list_clusters = [list([]) for i in range(total_num_clusters)] for i in range(len(cluster_results)): # print "Cluster_res for {0} is {1}".format(i, cluster_results[i]) @@ -311,7 +311,7 @@ def find_centroids(self, list_of_clusters, outputPrefix): if (self.indexToFrame == {}) and (self.indexToNpyFile != {}): repsFileName = '%scluster_reps.csv' %(outputPrefix) membersFileName = '%scluster_members.csv' %(outputPrefix) - print "Unable to extract frame numbers from file names. Writing out npy file names to %s and %s" %(repsFileName, membersFileName) + print("Unable to extract frame numbers from file names. Writing out npy file names to %s and %s" %(repsFileName, membersFileName)) with open(repsFileName,'wb') as of: cluster_rep_file_names = [str(self.indexToNpyFile[i]) for i in centroid_list] of.write('\n'.join(cluster_rep_file_names)) @@ -322,7 +322,7 @@ def find_centroids(self, list_of_clusters, outputPrefix): of.write('\n') elif (self.indexToFrame == {}) and (self.indexToNpyFile == {}): - print "No matrix-index-to-trajectory-frame mapping given. Writing out matrix indices" + print("No matrix-index-to-trajectory-frame mapping given. Writing out matrix indices") with open('%scluster_reps.csv' %(outputPrefix),'wb') as of: of.write('\n'.join([str(i) for i in centroid_list])) with open('%scluster_members.csv' %(outputPrefix),'wb') as of: @@ -333,7 +333,7 @@ def find_centroids(self, list_of_clusters, outputPrefix): elif (self.indexToFrame != {}): repsFileName = '%scluster_reps.csv' %(outputPrefix) membersFileName = '%scluster_members.csv' %(outputPrefix) - print "Matrix-index-to-trajectory-frame mapping given. Writing out trajectory frames to %s and %s." %(repsFileName, membersFileName) + print("Matrix-index-to-trajectory-frame mapping given. Writing out trajectory frames to %s and %s." %(repsFileName, membersFileName)) with open(repsFileName,'wb') as of: cluster_rep_frame_nums = [str(self.indexToFrame[i]) for i in centroid_list] @@ -349,7 +349,7 @@ def find_centroids(self, list_of_clusters, outputPrefix): of.write('\n') if (self.indexToFrame != {}) and (self.prefixToTrajectory != {}): - print "Extracting trajectory frames" + print("Extracting trajectory frames") matrixIndex2Cluster = {} for index, centroid in enumerate(centroid_list): matrixIndex2Cluster[centroid] = index @@ -364,7 +364,7 @@ def outputAllFrames(self, list_of_clusters, outputPrefix): #print cluster #print indexToFrame.keys() for matrixInd in cluster: - if not(matrixInd in self.indexToFrame.keys()): + if not(matrixInd in list(self.indexToFrame.keys())): raise Exception('User requested all frame pdbs to be output to cluster directories, but the program is unable to map all overlap matrix indices to trajectory/frame combinations. Make sure that -t/-T and -i arguments cover all frames and prefixes. Index: %i Cluster: %i' %(matrixInd, clusterInd)) ## If all mappings exist, extract all relevant frames @@ -386,7 +386,7 @@ def extractFrames(self, matrixIndex2Cluster, outputPrefix, reps=False): frameNum = int(npyFileName.split('/')[-1].split('frame_')[-1].replace('.npy','')) prefixMatch = '' ## See if this prefix is in our dictionary or trajectories - for trajPrefix in self.prefixToTrajectory.keys(): + for trajPrefix in list(self.prefixToTrajectory.keys()): if trajPrefix == npyFilePrefix: if prefixMatch == '': prefixMatch = trajPrefix @@ -408,7 +408,7 @@ def extractFrames(self, matrixIndex2Cluster, outputPrefix, reps=False): else: outputFileName = '%sframe_%i.pdb' %(prefixMatch, frameNum) fullOutputFileName = outputDir + '/' + outputFileName - if not trajFileName in framesToExtract.keys(): + if not trajFileName in list(framesToExtract.keys()): framesToExtract[trajFileName] = {} framesToExtract[trajFileName][frameNum] = fullOutputFileName @@ -468,7 +468,7 @@ def extractFrame(self, matrixIndex, outputDir, rep=False): of.write(frameData) ''' def generate_difference_maps(self, list_of_clusters, clusterInd2CentFileName, outputPrefix): - print "Generating difference maps" + print("Generating difference maps") #nFrames = len(frame_assignments) nFrames = sum([len(i) for i in list_of_clusters]) #list_of_clusters = self.separate_clusters(frame_assignments) @@ -497,11 +497,11 @@ def generate_difference_maps(self, list_of_clusters, clusterInd2CentFileName, ou clusterCounts.append(thisClusterCounts) - allPoints = numpy.array(allFrameCounts.keys()) + allPoints = numpy.array(list(allFrameCounts.keys())) allFrameMap = peel.featureMap.fromPovmeList(allPoints, justCoords = True, skinDistance=2.) allFrameMap.data[:] = 0.0 - for point in allFrameCounts.keys(): + for point in list(allFrameCounts.keys()): thisIndex = allFrameMap.point_to_nearest_index(point) allFrameMap.data[thisIndex] = allFrameCounts[point] @@ -509,7 +509,7 @@ def generate_difference_maps(self, list_of_clusters, clusterInd2CentFileName, ou for thisClusterCounts in clusterCounts: thisClusterMap = peel.featureMap.fromPovmeList(allPoints, justCoords = True, skinDistance=2.) thisClusterMap.data[:] = 0.0 - for point in thisClusterCounts.keys(): + for point in list(thisClusterCounts.keys()): thisIndex = allFrameMap.point_to_nearest_index(point) thisClusterMap.data[thisIndex] = thisClusterCounts[point] @@ -763,7 +763,7 @@ def __init__(self,argv): # Print message and exit out of program if missing essential files if args.m == '': - print "Cannot run cluster.py: Need an overlap file from binding_site_overlap.py in order to cluster \n" + print("Cannot run cluster.py: Need an overlap file from binding_site_overlap.py in order to cluster \n") #print_help() sys.exit(1) @@ -828,25 +828,25 @@ def __init__(self,argv): argsNsp = args.N.split(':') if len(argsNsp) == 1: maxKPClusters = int(argsNsp[0]) - userNClusters = range(1,maxKPClusters+1) - print "Computing Kelley penalty for nClusters from 1 to %i" %(maxKPClusters) + userNClusters = list(range(1,maxKPClusters+1)) + print("Computing Kelley penalty for nClusters from 1 to %i" %(maxKPClusters)) elif args.N.count(':') == 1: minKPClusters = int(argsNsp[0]) maxKPClusters = int(argsNsp[1]) - userNClusters = range(minKPClusters,maxKPClusters+1) - print "Computing Kelley penalty for nClusters from %i to %i" %(minKPClusters, maxKPClusters) + userNClusters = list(range(minKPClusters,maxKPClusters+1)) + print("Computing Kelley penalty for nClusters from %i to %i" %(minKPClusters, maxKPClusters)) elif args.N.count(':') == 2: minKPClusters = int(argsNsp[0]) maxKPClusters = int(argsNsp[1]) stride = int(argsNsp[2]) - userNClusters = range(minKPClusters,maxKPClusters+1,stride) - print "Computing Kelley penalty for nClusters from %i to %i, taking strides of %i" %(minKPClusters, maxKPClusters, stride) + userNClusters = list(range(minKPClusters,maxKPClusters+1,stride)) + print("Computing Kelley penalty for nClusters from %i to %i, taking strides of %i" %(minKPClusters, maxKPClusters, stride)) else: #maxKPClusters = clustering_obj.frames maxKPClusters = min(75, clustering_obj.frames) - userNClusters = range(1,maxKPClusters+1) - print "Computing Kelley penalty for nClusters from 1 to %i" %(maxKPClusters) + userNClusters = list(range(1,maxKPClusters+1)) + print("Computing Kelley penalty for nClusters from 1 to %i" %(maxKPClusters)) ## In order to achieve proper scaling, we must ALWAYS have 1 as a possible cluster number @@ -871,7 +871,7 @@ def __init__(self,argv): progressDecile = (10*index)/len(potentialNClusters) if progressDecile > lastProgressDecile: lastProgressDecile = progressDecile - print "Kelley penalty " + str(progressDecile*10) + "% computed" + print("Kelley penalty " + str(progressDecile*10) + "% computed") if args.kmeans == True: list_of_clusters = clustering_obj.kmeans_cluster(nClusters) else: @@ -925,7 +925,7 @@ def __init__(self,argv): optimal_nClusters = validNClusters[numpy.argsort(kPenalties)[0]] list_of_clusters = clustering_results[optimal_nClusters] #clusters = clustering_obj.separate_clusters(frame_assignments) - print "Done computing Kelley penalty. Optimal number of clusters is %i" %(optimal_nClusters) + print("Done computing Kelley penalty. Optimal number of clusters is %i" %(optimal_nClusters)) clusterInd2CentFileName = clustering_obj.find_centroids(list_of_clusters, args.o) diff --git a/POVME/packages/clustering/pocketPointsPca.py b/POVME/packages/clustering/pocketPointsPca.py index 6ee5103..822e76d 100755 --- a/POVME/packages/clustering/pocketPointsPca.py +++ b/POVME/packages/clustering/pocketPointsPca.py @@ -5,7 +5,7 @@ import numpy as np -import cPickle +import pickle import glob from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA as sklearnPCA @@ -36,7 +36,7 @@ '4R3M_every50ns':'JR9', #'4W7T':'3JC' } -sortedPdbs = pdb2Lig.keys() +sortedPdbs = list(pdb2Lig.keys()) sortedPdbs.sort() @@ -66,7 +66,7 @@ for line in index2frameData: index = int(line.split(',')[0]) prefix = line.split('/')[-1].split('_frame')[0] - print prefix + print(prefix) frame = int(line.split('/')[-1].split('_')[-1].replace('.npy','')) frameList.append(frame) prefix2indices[prefix] = prefix2indices.get(prefix,[]) + [int(index)] @@ -78,14 +78,14 @@ ## Load all relevant frames -print "Loading frames" +print("Loading frames") pointsSetList = [] frameStringList = [] allPointsSet = set() prefixList = [] for prefix in sortedPdbs: maxFrame = max(prefix2frames[prefix]) - framesToLoad = range(1,maxFrame,every) + framesToLoad = list(range(1,maxFrame,every)) for frame in framesToLoad: frameString = '%s_frame_%i' %(prefix, frame) frameFilename = '%s/%s/%s_frameInfo/%s.npy' %(analysisPath, @@ -99,7 +99,7 @@ allPointsSet = allPointsSet.union(pointsSet) -print "Vectorizing frames" +print("Vectorizing frames") coord2vectPos = dict([(coord, i) for i, coord in enumerate(allPointsSet)]) vectPos2Coord = dict([(i, coord) for i, coord in enumerate(allPointsSet)]) nVectPos = len(allPointsSet) @@ -109,9 +109,9 @@ for point in pointsSetList[f1]: vecPosMatrix[f1,coord2vectPos[point]] = 1 #print vecPosMatrix -print 'vecPosMatrix.shape is ', vecPosMatrix.shape +print('vecPosMatrix.shape is ', vecPosMatrix.shape) -print "Making X_std" +print("Making X_std") normalizeFeatures = 'Mean' if normalizeFeatures == 'MeanAndStd': @@ -119,10 +119,10 @@ elif normalizeFeatures == 'Mean': X_std = vecPosMatrix - np.mean(vecPosMatrix,0) -print "Making sklearn_pca" +print("Making sklearn_pca") nComponents = 10 sklearn_pca = sklearnPCA(n_components=nComponents) -print "Making Y_sklearn" +print("Making Y_sklearn") # An important note -- we get a hash value for the raw data here # as a unique identifier of this dataset. Then we save the initial @@ -135,18 +135,18 @@ #Y_sklearn = sklearn_pca.fit_transform(X_std) sklearn_pca.fit(X_std) with open(pca_result_hash,'wb') as of: - cPickle.dump(sklearn_pca, of) + pickle.dump(sklearn_pca, of) Y_sklearn = sklearn_pca.transform(X_std) #with open(pca_result_hash,'wb') as of: # cPickle.dump(Y_sklearn, of) else: #Y_sklearn = cPickle.load(open(pca_result_hash)) - sklearn_pca = cPickle.load(open(pca_result_hash)) + sklearn_pca = pickle.load(open(pca_result_hash)) Y_sklearn = sklearn_pca.transform(X_std) -print 'Y_sklearn.shape', Y_sklearn.shape +print('Y_sklearn.shape', Y_sklearn.shape) for col in range(Y_sklearn.shape[1]): - print col, np.mean(abs(Y_sklearn[:,col])) + print(col, np.mean(abs(Y_sklearn[:,col]))) twoD = True threeD = False @@ -181,7 +181,7 @@ import scipy.spatial.distance as ssd import itertools if twoD: - combos = list(itertools.combinations(range(4),2)) + combos = list(itertools.combinations(list(range(4)),2)) for index, (pc_x, pc_y) in enumerate(combos): xMin = min(Y_sklearn[:,pc_x]) xMax = max(Y_sklearn[:,pc_x]) @@ -258,11 +258,11 @@ hist2d, xEdges, yEdges = np.histogram2d(xs, ys, bins=[xBins, yBins]) import scipy.ndimage.filters hist2d = scipy.ndimage.filters.gaussian_filter(hist2d,3.5) - print xBins[:-1] - print - print yBins[:-1] - print - print hist2d + print(xBins[:-1]) + print() + print(yBins[:-1]) + print() + print(hist2d) #xBins += [xBins[-1]+(xRange/25)] #yBins += [yBins[-1]+(yRange/25)] contour = pylab.contour(xBins[:-1], @@ -386,9 +386,9 @@ if savePcDxFiles: loadAllScript = 'display rendermode GLSL\ndisplay projection Orthographic\n' - print 'Saving Principal Component DX files' + print('Saving Principal Component DX files') for pc_ind in range(nComponents): - print "Saving DX file for PC %i" %(pc_ind+1) + print("Saving DX file for PC %i" %(pc_ind+1)) pcPoints = np.zeros((vecPosMatrix.shape[1],4)) for vectPos in vectPos2Coord: coord = vectPos2Coord[vectPos] @@ -401,5 +401,5 @@ with open('loadAllPcs.vmd', 'wb') as of: of.write(loadAllScript) -print "Done!" +print("Done!") diff --git a/POVME/packages/in_progress/pocket_alignment_and_clustering/easyTestCase/makeTestCase.py b/POVME/packages/in_progress/pocket_alignment_and_clustering/easyTestCase/makeTestCase.py index 395ca42..f5551d6 100644 --- a/POVME/packages/in_progress/pocket_alignment_and_clustering/easyTestCase/makeTestCase.py +++ b/POVME/packages/in_progress/pocket_alignment_and_clustering/easyTestCase/makeTestCase.py @@ -36,7 +36,7 @@ familyMembership = [] #for index, family in enumerate(families.keys()): -for family in families.keys(): +for family in list(families.keys()): for replicate in range(families[family][0]): outPrefix = 'family%i_rep%02i' %(family, replicate) this_fm = peel.featureMap([-20,20,-20,20,-20,20],1) diff --git a/POVME/packages/in_progress/pocket_alignment_and_clustering/hardTestCase/makeTestCase.py b/POVME/packages/in_progress/pocket_alignment_and_clustering/hardTestCase/makeTestCase.py index 27edb18..3e60116 100644 --- a/POVME/packages/in_progress/pocket_alignment_and_clustering/hardTestCase/makeTestCase.py +++ b/POVME/packages/in_progress/pocket_alignment_and_clustering/hardTestCase/makeTestCase.py @@ -37,7 +37,7 @@ familyMembership = [] #for index, family in enumerate(families.keys()): -for family in families.keys(): +for family in list(families.keys()): for replicate in range(families[family][0]): outPrefix = 'family%i_rep%02i' %(family, replicate) this_fm = peel.featureMap([-20,20,-20,20,-20,20],1) diff --git a/POVME/packages/in_progress/pocket_alignment_and_clustering/mediumTestCase/makeTestCase.py b/POVME/packages/in_progress/pocket_alignment_and_clustering/mediumTestCase/makeTestCase.py index d8183ab..ea088c7 100644 --- a/POVME/packages/in_progress/pocket_alignment_and_clustering/mediumTestCase/makeTestCase.py +++ b/POVME/packages/in_progress/pocket_alignment_and_clustering/mediumTestCase/makeTestCase.py @@ -37,7 +37,7 @@ familyMembership = [] #for index, family in enumerate(families.keys()): -for family in families.keys(): +for family in list(families.keys()): for replicate in range(families[family][0]): outPrefix = 'family%i_rep%02i' %(family, replicate) this_fm = peel.featureMap([-20,20,-20,20,-20,20],1) diff --git a/POVME/packages/in_progress/pocket_alignment_and_clustering/scoreSolution.py b/POVME/packages/in_progress/pocket_alignment_and_clustering/scoreSolution.py index cee7d51..3284fad 100644 --- a/POVME/packages/in_progress/pocket_alignment_and_clustering/scoreSolution.py +++ b/POVME/packages/in_progress/pocket_alignment_and_clustering/scoreSolution.py @@ -5,7 +5,7 @@ import copy if not len(sys.argv) == 3: - print 'usage: python scoreSolution.py attemptFile keyFile' + print('usage: python scoreSolution.py attemptFile keyFile') sys.exit() @@ -24,7 +24,7 @@ def bootstrap_analysis(list1, list2): similarities = [] for i in range(nBootstraps): if i % 1000 == 0: - print 'bootstrap',i + print('bootstrap',i) newIndices = np.random.randint(0,len(list1),(len(list1))) list1Scramble = list1[newIndices] #list1Scramble = list(list1) @@ -47,7 +47,7 @@ def bootstrap_analysis(list1, list2): pylab.axvline(realSimilarity) betterThanPercent = 100*float(betterPop)/nBootstraps pylab.text(realSimilarity, 0.5*max(hist[0]),'%.1f' %(betterThanPercent)) - print 'Real similarity is better than %r percent of bootstrap permutations' %(betterThanPercent) + print('Real similarity is better than %r percent of bootstrap permutations' %(betterThanPercent)) @@ -105,11 +105,11 @@ def test_solution(groupList1, groupList2, plot = False): realSolutionGroups = np.array([int(i.split()[0]) for i in realSolution]) if len(attemptedSolution) != len(realSolution): - print 'error: Different number of classifications in the proposed solution and key file' + print('error: Different number of classifications in the proposed solution and key file') realScore = test_solution(attemptedSolutionGroups, realSolutionGroups) -print realScore +print(realScore) bootstrap_analysis(attemptedSolutionGroups, realSolutionGroups) pylab.show() diff --git a/POVME/packages/in_progress/shelby_PCA/cpp/npy_xyz.py b/POVME/packages/in_progress/shelby_PCA/cpp/npy_xyz.py index 5cc7436..5fac4b5 100644 --- a/POVME/packages/in_progress/shelby_PCA/cpp/npy_xyz.py +++ b/POVME/packages/in_progress/shelby_PCA/cpp/npy_xyz.py @@ -19,7 +19,7 @@ frame_coords_xyz_filename=str(sys.argv[x]) frame_coords_xyz_filename=frame_coords_xyz_filename[:-4].strip() frame_coords_xyz_filename=frame_coords_xyz_filename+'.xyz_arr' - print frame_coords_xyz_filename + print(frame_coords_xyz_filename) frame_pocket_coordinates=np.load(str(sys.argv[x])) frame_pocket_coordinates=set([tuple(i) for i in frame_pocket_coordinates]) @@ -27,28 +27,28 @@ frame_pocket_coordinates_list=list(frame_pocket_coordinates) frame_pocket_coordinates_string_list=[[str(i) for i in j] for j in frame_pocket_coordinates_list] write_frame_xyz=open(frame_coords_xyz_filename, 'w') - print >> write_frame_xyz, '\n'.join(['\t'.join(i) for i in frame_pocket_coordinates_string_list]) + print('\n'.join(['\t'.join(i) for i in frame_pocket_coordinates_string_list]), file=write_frame_xyz) coordinate_set=(frame_pocket_coordinates | coordinate_set) - print 'atoms in frame', x, len(frame_pocket_coordinates) + print('atoms in frame', x, len(frame_pocket_coordinates)) common_coordinate_set=(frame_pocket_coordinates - common_coordinate_set) -print 'total atoms', len(coordinate_set) +print('total atoms', len(coordinate_set)) total_atom_list=list(coordinate_set) total_atom_string_list=[[str(i) for i in j] for j in total_atom_list] write_file=open(nx3_filename, 'w') -print >> write_file, '\n'.join(['\t'.join(i) for i in total_atom_string_list]) +print('\n'.join(['\t'.join(i) for i in total_atom_string_list]), file=write_file) unique_coordinate_set=coordinate_set-common_coordinate_set -print 'unique atoms', len(unique_coordinate_set) +print('unique atoms', len(unique_coordinate_set)) unique_atom_list=list(unique_coordinate_set) unique_atom_string_list=[[str(i) for i in j] for j in unique_atom_list] write_file_2=open(unique_filename, 'w') -print >> write_file_2, '\n'.join(['\t'.join(i) for i in unique_atom_string_list]) +print('\n'.join(['\t'.join(i) for i in unique_atom_string_list]), file=write_file_2) diff --git a/POVME/packages/in_progress/shelby_PCA/python/POVME_PCA.py b/POVME/packages/in_progress/shelby_PCA/python/POVME_PCA.py index 0219060..7e8d9f4 100644 --- a/POVME/packages/in_progress/shelby_PCA/python/POVME_PCA.py +++ b/POVME/packages/in_progress/shelby_PCA/python/POVME_PCA.py @@ -37,11 +37,11 @@ frame_pocket_coordinates_string_list=[[str(i) for i in j] for j in frame_pocket_coordinates_list] coordinate_set=(frame_pocket_coordinates | coordinate_set) - print 'atoms in frame', x, len(frame_pocket_coordinates) + print('atoms in frame', x, len(frame_pocket_coordinates)) common_coordinate_set=(frame_pocket_coordinates - common_coordinate_set) -print 'Total number of points identified as part of the pocket: ', len(coordinate_set) +print('Total number of points identified as part of the pocket: ', len(coordinate_set)) total_atoms=len(coordinate_set) coordinates = np.array([list(i) for i in coordinate_set]) @@ -50,13 +50,13 @@ #this is required to build pdb's of these PCs downstream write_common_coordinate_filestream = open(nx3_filename, 'w') -print >> write_common_coordinate_filestream, total_atoms -print >> write_common_coordinate_filestream, 'Common points xyz file' +print(total_atoms, file=write_common_coordinate_filestream) +print('Common points xyz file', file=write_common_coordinate_filestream) -print coordinates[total_atoms-1,0],coordinates[total_atoms-1,1],coordinates[total_atoms-1,2] +print(coordinates[total_atoms-1,0],coordinates[total_atoms-1,1],coordinates[total_atoms-1,2]) for x in range(0,total_atoms): - print >> write_common_coordinate_filestream, 'O ', coordinates[x,0], coordinates[x,1], coordinates[x,2] + print('O ', coordinates[x,0], coordinates[x,1], coordinates[x,2], file=write_common_coordinate_filestream) #now that all the common points have been identified, pairwise distances can be #computed between all points in the data set to identify the resolution (in @@ -99,7 +99,7 @@ #compute the "average binary presence" of each point in the array, save #per-frame presence in the binary_frame_arrays data structure -print 'computing average and per-frame presences' +print('computing average and per-frame presences') for x in range(1,frame_count): @@ -126,7 +126,7 @@ #3D data structure from zero to one binary_frame_arrays[rel_frame_point_scaled[0],rel_frame_point_scaled[1],rel_frame_point_scaled[2],x]=1 -print 'converting data from 3D arrays to vectors' +print('converting data from 3D arrays to vectors') #loop responsible for transferring data from the 3D average presence array to a 1D array #This should reduce look-up time when computing the covariance matrix @@ -148,7 +148,7 @@ denominator = frame_count - 1 cov_mat=np.zeros((total_atoms+1,total_atoms+1)) -print 'computing covariance matrix' +print('computing covariance matrix') #This algorithm is take from (REF HERE) #As is, it takes ~2-3 minutes on a standard linux workstation @@ -173,9 +173,9 @@ cov_mat[i, j]=covariance_entry -print 'Covariance matrix computed' -print 'NumPy is now diagonalizing the covariance matrix, which is of dimenstion ', total_atoms -print 'Please be patient...' +print('Covariance matrix computed') +print('NumPy is now diagonalizing the covariance matrix, which is of dimenstion ', total_atoms) +print('Please be patient...') #Using eigh over eig dramatically improves performance: eigenvectors are now computed #in about 2 minutes because of the symmetry of the matrix, vs 1hr from straight schoolbook @@ -193,7 +193,7 @@ for count in range(0, 9): #it seems as if the eigenvalues are stored in increasing order; thus the index #must be reversed during look-up - print >> scree_plot_write_stream, eigenvalues[(total_atoms-count)]/normalization + print(eigenvalues[(total_atoms-count)]/normalization, file=scree_plot_write_stream) #print principal components as a vector, downstream tcl script turns this #into a .pdb file @@ -209,6 +209,6 @@ eigenvector_filename += str(x) write_file=open(eigenvector_filename, 'w') for y in range(0,total_atoms): - print >> write_file, np.real(eigenvectors[y,(total_atoms-x)]) + print(np.real(eigenvectors[y,(total_atoms-x)]), file=write_file) diff --git a/POVME/packages/in_progress/surf_area_calculation_comparison/comparePovmeToFpocket.py b/POVME/packages/in_progress/surf_area_calculation_comparison/comparePovmeToFpocket.py index 4c4b9e1..fa690f5 100644 --- a/POVME/packages/in_progress/surf_area_calculation_comparison/comparePovmeToFpocket.py +++ b/POVME/packages/in_progress/surf_area_calculation_comparison/comparePovmeToFpocket.py @@ -87,7 +87,7 @@ #mdpocketData = open('dpocket/%s%s/dpout_exp.txt' %(target, rotation)).readlines() if len(mdpocketData) == 1: # If there are no pockets detected - print "No data for %s %s. Skipping!" %(target, rotation) + print("No data for %s %s. Skipping!" %(target, rotation)) continue else: volumeIndex = mdpocketData[0].split().index('pock_vol') @@ -149,10 +149,10 @@ def analyze_difference(list1, list2, stdList1 = None, stdList2 = None, normalize povmeStdArray /= povmeNormConst mdpocketStdArray /= mdpocketNormConst - toPlot = zip(povmeVolumeArray,mdpocketVolumeArray, numpy.zeros((len(targets)))) + toPlot = list(zip(povmeVolumeArray,mdpocketVolumeArray, numpy.zeros((len(targets))))) toPlot = [i for t in toPlot for i in t] if stdList1 != None and stdList2 != None: - toPlotStds = zip(povmeStdArray,mdpocketStdArray, numpy.zeros((len(targets))) ) + toPlotStds = list(zip(povmeStdArray,mdpocketStdArray, numpy.zeros((len(targets))) )) toPlotStds = [i for t in toPlotStds for i in t] differences = [] @@ -197,7 +197,7 @@ def bootstrap_analysis_sum_difference(list1, list2): pylab.axvline(realDifference) betterThanPercent = 100*float(betterPop)/nBootstraps pylab.text(realDifference, 0.5*max(hist[0]),'%.1g' %(betterThanPercent)) - print 'Real difference is better than %r percent of bootstrap permutations' %(betterThanPercent) + print('Real difference is better than %r percent of bootstrap permutations' %(betterThanPercent)) def linear_regression(xData, yData, xErr = None, yErr = None, fit=True, plot=True): @@ -235,14 +235,14 @@ def subplotOrShow(subplotInd):#, title='', xLabel='', yLabel=''): else: pylab.show() -print 'ANALYZING POCKET VOLUMES' +print('ANALYZING POCKET VOLUMES') if allAsSubplots: pylab.subplot(331) toPlotVols, bar_toPlotVolStds, realDifferences = analyze_difference(povmeVolAvList, mdpocketVolAvList, stdList1=povmeVolStdList, stdList2=mdpocketVolStdList, normalize=normalize) #print len(toPlotVolStds) -pylab.bar(range(len(toPlotVols)), toPlotVols, color=toPlotColors,yerr=bar_toPlotVolStds) -pylab.xticks(range(len(toPlotVols)),toPlotLabels,rotation = 90) +pylab.bar(list(range(len(toPlotVols))), toPlotVols, color=toPlotColors,yerr=bar_toPlotVolStds) +pylab.xticks(list(range(len(toPlotVols))),toPlotLabels,rotation = 90) pylab.title('Volume Comparison') pylab.ylabel('Volume'+' (normalized)'*normalize) @@ -258,12 +258,12 @@ def subplotOrShow(subplotInd):#, title='', xLabel='', yLabel=''): if sum(mdpocketSAAvList) != 0: - print 'ANALYZING SURFACE AREAS' + print('ANALYZING SURFACE AREAS') subplotOrShow(334) toPlotSAs, bar_toPlotSAStds, realDifferences = analyze_difference(povmeSAAvList, mdpocketSAAvList,stdList1=povmeSAStdList, stdList2=mdpocketSAStdList, normalize=normalize) - pylab.bar(range(len(toPlotSAs)), toPlotSAs, color=toPlotColors, yerr=bar_toPlotSAStds) - pylab.xticks(range(len(toPlotSAs)),toPlotLabels,rotation = 90) + pylab.bar(list(range(len(toPlotSAs))), toPlotSAs, color=toPlotColors, yerr=bar_toPlotSAStds) + pylab.xticks(list(range(len(toPlotSAs))),toPlotLabels,rotation = 90) pylab.title('Surface Area Comparison') pylab.ylabel('Surf. Area'+' (normalized)'*normalize) @@ -278,11 +278,11 @@ def subplotOrShow(subplotInd):#, title='', xLabel='', yLabel=''): pylab.ylabel('frequency') -print 'ANALYZING POLARITY SCORES' +print('ANALYZING POLARITY SCORES') subplotOrShow(337) toPlotPols, bar_toPlotPolStds, realDifferences = analyze_difference(povmePolAvList, mdpocketPolAvList,stdList1=povmePolStdList, stdList2=mdpocketPolStdList, normalize=normalize) -pylab.bar(range(len(toPlotPols)), toPlotPols, color=toPlotColors, yerr=bar_toPlotPolStds) -pylab.xticks(range(len(toPlotPols)),toPlotLabels,rotation = 90) +pylab.bar(list(range(len(toPlotPols))), toPlotPols, color=toPlotColors, yerr=bar_toPlotPolStds) +pylab.xticks(list(range(len(toPlotPols))),toPlotLabels,rotation = 90) pylab.title('Polarity Comparison') pylab.ylabel('Polarity'+' (normalized)'*normalize) diff --git a/POVME/packages/in_progress/surf_area_calculation_comparison/makeRunScripts.py b/POVME/packages/in_progress/surf_area_calculation_comparison/makeRunScripts.py index b8d9467..2d00f09 100644 --- a/POVME/packages/in_progress/surf_area_calculation_comparison/makeRunScripts.py +++ b/POVME/packages/in_progress/surf_area_calculation_comparison/makeRunScripts.py @@ -40,7 +40,7 @@ pdbName = target.split('/')[-1] protID = pdbName.replace('.pdb','') if protName in bSiteRes: - print target, 'IN LIST UNDER TITLE', protName + print(target, 'IN LIST UNDER TITLE', protName) u = MDA.Universe(target) protein = u.selectAtoms('not resname LIG') bSiteResAtoms = u.selectAtoms(' or '.join(['(resnum %i and name CA)'%(i) for i in bSiteRes[protName]])) diff --git a/POVME/packages/in_progress/surf_area_calculation_comparison/rotateProteins.py b/POVME/packages/in_progress/surf_area_calculation_comparison/rotateProteins.py index fcc5d53..760045d 100644 --- a/POVME/packages/in_progress/surf_area_calculation_comparison/rotateProteins.py +++ b/POVME/packages/in_progress/surf_area_calculation_comparison/rotateProteins.py @@ -8,7 +8,7 @@ for target in targets: - print target + print(target) for rotation in range(5): u = MDA.Universe(target) atom1 = u.atoms[numpy.random.randint(0,len(u.atoms))] diff --git a/POVME/packages/pymolecule/pymolecule.py b/POVME/packages/pymolecule/pymolecule.py index f386093..3ac54f3 100644 --- a/POVME/packages/pymolecule/pymolecule.py +++ b/POVME/packages/pymolecule/pymolecule.py @@ -29,14 +29,14 @@ import scipy import copy import sys -import cPickle as pickle +import pickle as pickle import shutil import warnings warnings.filterwarnings("ignore", message="changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient.") version="2.0" -if __name__ == '__main__': print "\npymolecule " + version + "\n" +if __name__ == '__main__': print("\npymolecule " + version + "\n") class Information(): '''A class for storing and accessing information about the elements of a pymolecule.Molecule object''' @@ -355,7 +355,7 @@ def define_molecule_chain_residue_spherical_boundaries(self): '''Identifies spheres that bound (encompass) the entire molecule, the chains, and the residues. This information is stored in pymolecule.Molecule.information.hierarchy.''' # first, check to see if it's already been defined - if 'spheres' in self.__hierarchy.keys(): return + if 'spheres' in list(self.__hierarchy.keys()): return # set up the new structure self.__hierarchy['spheres'] = {} @@ -373,7 +373,7 @@ def define_molecule_chain_residue_spherical_boundaries(self): self.__hierarchy['spheres']['molecule']['radius'] = whole_mol_calc[1] # do calcs for the chains - self.__hierarchy['spheres']['chains']['keys'] = numpy.array(self.__hierarchy['chains']['indices'].keys()) #numpy string array e.g. ['a','b','c'] + self.__hierarchy['spheres']['chains']['keys'] = numpy.array(list(self.__hierarchy['chains']['indices'].keys())) #numpy string array e.g. ['a','b','c'] self.__hierarchy['spheres']['chains']['centers'] = numpy.empty((len(self.__hierarchy['spheres']['chains']['keys']),3)) self.__hierarchy['spheres']['chains']['radii'] = numpy.empty(len(self.__hierarchy['spheres']['chains']['keys'])) @@ -385,7 +385,7 @@ def define_molecule_chain_residue_spherical_boundaries(self): self.__hierarchy['spheres']['chains']['radii'][index] = asphere[1] # do calcs for the residues - self.__hierarchy['spheres']['residues']['keys'] = numpy.array(self.__hierarchy['residues']['indices'].keys()) + self.__hierarchy['spheres']['residues']['keys'] = numpy.array(list(self.__hierarchy['residues']['indices'].keys())) self.__hierarchy['spheres']['residues']['centers'] = numpy.empty((len(self.__hierarchy['spheres']['residues']['keys']),3)) self.__hierarchy['spheres']['residues']['radii'] = numpy.empty(len(self.__hierarchy['spheres']['residues']['keys'])) @@ -404,9 +404,9 @@ def serial_reindex(self): def resseq_reindex(self): '''Reindexes the resseq field of the atoms in the molecule, starting with 1''' - keys = numpy.core.defchararray.add(self.__atom_information['resname_stripped'], '-') - keys = numpy.core.defchararray.add(keys, numpy.array([str(t) for t in self.__atom_information['resseq']])) - keys = numpy.core.defchararray.add(keys, '-') + keys = numpy.core.defchararray.add(self.__atom_information['resname_stripped'], b'-') + keys = numpy.core.defchararray.add(keys, numpy.array([t for t in self.__atom_information['resseq']])) + keys = numpy.core.defchararray.add(keys, b'-') keys = numpy.core.defchararray.add(keys, self.__atom_information['chainid_stripped']) keys2 = numpy.insert(keys,0, '')[:-1] @@ -447,9 +447,9 @@ def load_pym_into(self, filename): self.__parent_molecule.set_atom_information(pickle.load(open(filename + 'atom_information', "rb" ))) self.__parent_molecule.set_coordinates(numpy.load(filename + "coordinates.npz")['arr_0']) # now look for other possible files (optional output) - if os.path.exists(filename + 'remarks'): self.__parent_molecule.set_remarks(pickle.load( open( filename + 'remarks', "rb" ) ) ) - if os.path.exists(filename + 'hierarchy'): self.__parent_molecule.set_hierarchy(pickle.load( open( filename + 'hierarchy', "rb" ) ) ) - if os.path.exists(filename + 'filename'): self.__parent_molecule.set_filename(pickle.load( open( filename + 'filename', "rb" ) ) ) + if os.path.exists(filename + 'remarks'): self.__parent_molecule.set_remarks(pickle.load( open( filename + 'remarks', "r" ) ) ) + if os.path.exists(filename + 'hierarchy'): self.__parent_molecule.set_hierarchy(pickle.load( open( filename + 'hierarchy', "r" ) ) ) + if os.path.exists(filename + 'filename'): self.__parent_molecule.set_filename(pickle.load( open( filename + 'filename', "r" ) ) ) if os.path.exists(filename + "bonds.npz"): # Some extra work here to load sparse bond matrix bonds_raw = numpy.load(filename + "bonds.npz") #['arr_0'] @@ -493,18 +493,19 @@ def load_pdb_into_using_file_object(self, file_obj, bonds_by_distance=True, seri source_data = numpy.genfromtxt(file_obj, dtype="S6,S5,S5,S5,S1,S4,S4,S8,S8,S8,S6,S6,S10,S2,S3", names=['record_name', 'serial', 'name', 'resname', 'chainid', 'resseq', 'empty', 'x', 'y', 'z', 'occupancy', 'tempfactor', 'empty2', 'element', 'charge'], delimiter=[6, 5, 5, 5, 1, 4, 4, 8, 8, 8, 6, 6, 10, 2, 3]) # get the remarks, if any. good to hold on to this because some of my programs might retain info via remarks - remark_indices = numpy.nonzero(source_data['record_name'] == "REMARK")[0] + remark_indices = numpy.nonzero(source_data['record_name'] == b"REMARK")[0] remarks = [] for index in remark_indices: astr = "" - for name in source_data.dtype.names[1:]: astr = astr + source_data[name][index] + for name in source_data.dtype.names[1:]: + astr = astr + source_data[name][index].decode("utf-8") remarks.append(astr.rstrip()) self.__parent_molecule.set_remarks(remarks) if source_data.ndim == 0: source_data = source_data.reshape(1, -1) # in case the pdb file has only one line # get the ones that are ATOM or HETATOM in the record_name - or_matrix = numpy.logical_or((source_data['record_name'] == "ATOM "), (source_data['record_name'] == "HETATM")) + or_matrix = numpy.logical_or((source_data['record_name'] == b"ATOM "), (source_data['record_name'] == b"HETATM")) indices_of_atom_or_hetatom = numpy.nonzero(or_matrix)[0] self.__parent_molecule.set_atom_information(source_data[indices_of_atom_or_hetatom]) @@ -547,7 +548,7 @@ def load_pdb_into_using_file_object(self, file_obj, bonds_by_distance=True, seri for f in fields_to_strip: self.__parent_molecule.set_atom_information(append_fields(self.__parent_molecule.get_atom_information(), f + '_stripped', data=numpy.core.defchararray.strip(self.__parent_molecule.get_atom_information()[f]))) # now, if there's conect data, load it. this part of the code is not that "numpyic" - conect_indices = numpy.nonzero(source_data['record_name'] == "CONECT")[0] + conect_indices = numpy.nonzero(source_data['record_name'] == b"CONECT")[0] if len(conect_indices) > 0: self.__parent_molecule.set_bonds(numpy.zeros((len(self.__parent_molecule.get_atom_information()), len(self.__parent_molecule.get_atom_information())))) @@ -563,7 +564,7 @@ def load_pdb_into_using_file_object(self, file_obj, bonds_by_distance=True, seri astr= astr.rstrip() indices = [] - for i in xrange(0, len(astr), 5): indices.append(serial_to_index[int(astr[i:i+5])]) + for i in range(0, len(astr), 5): indices.append(serial_to_index[int(astr[i:i+5])]) for partner_index in indices[1:]: self.__parent_molecule.add_bond(indices[0],partner_index) @@ -676,22 +677,22 @@ def save_pdb(self, filename="", serial_reindex=True, resseq_reindex=False, retur printout = numpy.core.defchararray.add(printout, atom_information['resname']) printout = numpy.core.defchararray.add(printout, atom_information['chainid']) printout = numpy.core.defchararray.add(printout, numpy.core.defchararray.rjust(atom_information['resseq'].astype('|S4'),4)) - printout = numpy.core.defchararray.add(printout, ' ') - printout = numpy.core.defchararray.add(printout, numpy.core.defchararray.rjust(numpy.array(["%.3f" % t for t in coordinates[:,0]]), 8)) - printout = numpy.core.defchararray.add(printout, numpy.core.defchararray.rjust(numpy.array(["%.3f" % t for t in coordinates[:,1]]), 8)) - printout = numpy.core.defchararray.add(printout, numpy.core.defchararray.rjust(numpy.array(["%.3f" % t for t in coordinates[:,2]]), 8)) - printout = numpy.core.defchararray.add(printout, numpy.core.defchararray.rjust(numpy.array(["%.2f" % t for t in atom_information['occupancy']]), 6)) - printout = numpy.core.defchararray.add(printout, numpy.core.defchararray.rjust(numpy.array(["%.2f" % t for t in atom_information['tempfactor']]), 6)) - printout = numpy.core.defchararray.add(printout, ' ') + printout = numpy.core.defchararray.add(printout, b' ') + printout = numpy.core.defchararray.add(printout, numpy.core.defchararray.rjust(numpy.array([b"%.3f" % t for t in coordinates[:,0]]), 8)) + printout = numpy.core.defchararray.add(printout, numpy.core.defchararray.rjust(numpy.array([b"%.3f" % t for t in coordinates[:,1]]), 8)) + printout = numpy.core.defchararray.add(printout, numpy.core.defchararray.rjust(numpy.array([b"%.3f" % t for t in coordinates[:,2]]), 8)) + printout = numpy.core.defchararray.add(printout, numpy.core.defchararray.rjust(numpy.array([b"%.2f" % t for t in atom_information['occupancy']]), 6)) + printout = numpy.core.defchararray.add(printout, numpy.core.defchararray.rjust(numpy.array([b"%.2f" % t for t in atom_information['tempfactor']]), 6)) + printout = numpy.core.defchararray.add(printout, b' ') printout = numpy.core.defchararray.add(printout, atom_information['element']) printout = numpy.core.defchararray.add(printout, atom_information['charge']) if return_text == False: - if printout[0][-1:] == "\n": afile.write("".join(printout) + "\n") - else: afile.write("\n".join(printout) + "\n") + if printout[0][-1:] == "\n": afile.write(str("".join([i.decode("utf-8") for i in printout]) + "\n")) + else: afile.write(str("\n".join([i.decode("utf-8") for i in printout]) + "\n")) else: - if printout[0][-1:] == "\n": return_string = return_string + ("".join(printout) + "\n") - else: return_string = return_string + ("\n".join(printout) + "\n") + if printout[0][-1:] == "\n": return_string = return_string + str("".join([i.decode("utf-8") for i in printout]) + "\n") + else: return_string = return_string + str("\n".join([i.decode("utf-8") for i in printout]) + "\n") # print out connect if not self.__parent_molecule.get_bonds() is None: @@ -705,7 +706,7 @@ def save_pdb(self, filename="", serial_reindex=True, resseq_reindex=False, retur if return_text == False: afile.close() else: return return_string - else: print "WARNING: Cannot save a Molecule with no atoms (file name \"" + filename + "\")" + else: print("WARNING: Cannot save a Molecule with no atoms (file name \"" + filename + "\")") class AtomsAndBonds(): '''A class for adding and deleting atoms and bonds''' @@ -733,7 +734,7 @@ def create_bonds_by_distance(self, remove_old_bond_data=True, delete_excessive_b if remove_old_bond_data == True or self.__parent_molecule.get_bonds() is None: self.__parent_molecule.set_bonds(numpy.zeros((len(self.__parent_molecule.information.get_atom_information()), len(self.__parent_molecule.information.get_atom_information())))) # get the longest bond length on record - max_bond_length = numpy.max([self.__parent_molecule.get_constants()['bond_length_dict'][key] for key in self.__parent_molecule.get_constants()['bond_length_dict'].keys()]) + max_bond_length = numpy.max([self.__parent_molecule.get_constants()['bond_length_dict'][key] for key in list(self.__parent_molecule.get_constants()['bond_length_dict'].keys())]) # which ones could possibly be bound (less than the max_bond_length) distances = scipy.spatial.distance.squareform(pdist(self.__parent_molecule.get_coordinates())) @@ -744,11 +745,11 @@ def create_bonds_by_distance(self, remove_old_bond_data=True, delete_excessive_b index2 = ones_to_consider[1][index] if index1 != index2: # so an atom is not bound to itself.__parent_molecule - key = self.__parent_molecule.get_atom_information()['element_stripped'][index1] +'-' + self.__parent_molecule.get_atom_information()['element_stripped'][index2] - + key = self.__parent_molecule.get_atom_information()['element_stripped'][index1].decode("utf-8") +'-' + self.__parent_molecule.get_atom_information()['element_stripped'][index2].decode("utf-8") + try: bond_dist = self.__parent_molecule.get_constants()['bond_length_dict'][key] except: - print "WARNING: Unknown bond distance between elements " + self.__parent_molecule.get_atom_information()['element_stripped'][index1] + ' and ' + self.__parent_molecule.get_atom_information()['element_stripped'][index2] + '. Assuming ' + str(max_bond_length) + '.' + print("WARNING: Unknown bond distance between elements " + str(self.__parent_molecule.get_atom_information()['element_stripped'][index1]) + ' and ' + str(self.__parent_molecule.get_atom_information()['element_stripped'][index2]) + '. Assuming ' + str(max_bond_length) + '.') bond_dist = max_bond_length if distances[index1][index2] < bond_dist * 1.2 and distances[index1][index2] > bond_dist * 0.5: # so they should be bonded @@ -844,7 +845,7 @@ def delete_bond(self, index1, index2): try: bonds[index1,index2] = 0 bonds[index2,index1] = 0 - except: print "Could not delete bond between " + str(index1) + " and " + str(index2) + "." + except: print("Could not delete bond between " + str(index1) + " and " + str(index2) + ".") def add_bond(self, index1, index2, order=1): '''Adds a bond. @@ -998,7 +999,7 @@ def select_atoms(self, selection_criteria): try: selection = numpy.ones(len(self.__parent_molecule.get_atom_information()), dtype=bool) # start assuming everything is selected - for key in selection_criteria.keys(): + for key in list(selection_criteria.keys()): vals = selection_criteria[key] @@ -1020,8 +1021,8 @@ def select_atoms(self, selection_criteria): # now get the indices of the selection return numpy.nonzero(selection)[0] except: - print "ERROR: Could not make the selection. Existing fields:" - print "\t" + ", ".join(self.__parent_molecule.get_atom_information().dtype.names) + print("ERROR: Could not make the selection. Existing fields:") + print("\t" + ", ".join(self.__parent_molecule.get_atom_information().dtype.names)) sys.exit(0) def select_atoms_in_bounding_box(self, bounding_box): @@ -1064,7 +1065,7 @@ def select_all_atoms_bound_to_selection(self, selection): ''' if self.__parent_molecule.information.get_bonds() is None: - print "You need to define the bonds to use select_all_atoms_bound_to_selection()." + print("You need to define the bonds to use select_all_atoms_bound_to_selection().") return bonds_to_consider = self.__parent_molecule.get_bonds()[selection] return numpy.unique(numpy.nonzero(bonds_to_consider)[1]) @@ -1087,12 +1088,12 @@ def select_branch(self, root_atom_index, directionality_atom_index): # had a branch-identification function. if self.__parent_molecule.get_bonds() is None: - print "To identify atoms in the same molecule as the atoms of a selection, you need to define the bonds." + print("To identify atoms in the same molecule as the atoms of a selection, you need to define the bonds.") return #Make sure atoms are neighboring if not directionality_atom_index in self.select_all_atoms_bound_to_selection(numpy.array([root_atom_index])): - print "The root and directionality atoms, with indices " + str(root_atom_index) + " and " + str(directionality_atom_index) + ", respectively, are not neighboring atoms." + print("The root and directionality atoms, with indices " + str(root_atom_index) + " and " + str(directionality_atom_index) + ", respectively, are not neighboring atoms.") return # first, set up the two indices need to manage the growing list of @@ -1135,7 +1136,7 @@ def select_atoms_from_same_molecule(self, selection): # note that bonds must be defined if self.__parent_molecule.get_bonds() is None: - print "To identify atoms in the same molecule as the atoms of a selection, you need to define the bonds." + print("To identify atoms in the same molecule as the atoms of a selection, you need to define the bonds.") return indices = [] @@ -1231,9 +1232,9 @@ def select_atoms_in_same_residue(self, selection): ''' # get string ids representing the residues of all atoms - keys = numpy.core.defchararray.add(self.__parent_molecule.get_atom_information()['resname_stripped'], '-') - keys = numpy.core.defchararray.add(keys, numpy.array([str(t) for t in self.__parent_molecule.get_atom_information()['resseq']])) - keys = numpy.core.defchararray.add(keys, '-') + keys = numpy.core.defchararray.add(self.__parent_molecule.get_atom_information()['resname_stripped'], b'-') + keys = numpy.core.defchararray.add(keys, numpy.array([bytes(t) for t in self.__parent_molecule.get_atom_information()['resseq']])) + keys = numpy.core.defchararray.add(keys, b'-') keys = numpy.core.defchararray.add(keys, self.__parent_molecule.get_atom_information()['chainid_stripped']) # get the unique keys of the selection @@ -1426,7 +1427,7 @@ def selections_of_chains(self): ''' - if not 'chains' in self.__parent_molecule.get_hierarchy().keys() : # so it hasn't already been calculated + if not 'chains' in list(self.__parent_molecule.get_hierarchy().keys()) : # so it hasn't already been calculated unique_chainids = numpy.unique(self.__parent_molecule.get_atom_information()['chainid_stripped']) self.__parent_molecule.get_hierarchy()['chains'] = {} @@ -1444,7 +1445,7 @@ def selections_of_residues(self): ''' - if not 'residues' in self.__parent_molecule.get_hierarchy().keys() : # so it hasn't already been calculated + if not 'residues' in list(self.__parent_molecule.get_hierarchy().keys()) : # so it hasn't already been calculated keys = numpy.core.defchararray.add(self.__parent_molecule.get_atom_information()['resname_stripped'], '-') keys = numpy.core.defchararray.add(keys, numpy.array([str(t) for t in self.__parent_molecule.get_atom_information()['resseq']])) @@ -1481,7 +1482,7 @@ def in_same_ring(self, index1, index2): paths = self.__ring_recursive_walk(index1, index2, [], 0) if len(paths) == 0: - print "No paths found between two indices" + print("No paths found between two indices") return False #Remove paths that do not start or end at the correct location @@ -1599,7 +1600,7 @@ def translate_molecule(self, delta): self.__parent_molecule.set_coordinates(self.__parent_molecule.get_coordinates() + delta) - if 'spheres' in self.__parent_molecule.get_hierarchy().keys(): + if 'spheres' in list(self.__parent_molecule.get_hierarchy().keys()): # so update location of hierarchical elements self.__parent_molecule.get_hierarchy()['spheres']['molecule']['center'] = self.__parent_molecule.get_hierarchy()['spheres']['molecule']['center'] + delta self.__parent_molecule.get_hierarchy()['spheres']['chains']['centers'] = self.__parent_molecule.get_hierarchy()['spheres']['chains']['centers'] + delta @@ -1759,7 +1760,7 @@ def get_angle_between_three_points(self, pt1, pt2, pt3): #Make sure vectors aren't <0,0,0> if vector1_mag < 1e-10 or vector2_mag < 1e-10: - print "One of vectors to determine angle is < 0, 0, 0 >...returning 0." + print("One of vectors to determine angle is < 0, 0, 0 >...returning 0.") return 0 vector1 = vector1 / vector1_mag @@ -2051,8 +2052,8 @@ def get_rmsd_equivalent_atoms_specified(self, other_mol, tethers): ''' if len(self.__parent_molecule.get_coordinates()) != len(other_mol.get_coordinates()): - print "Cannot calculate RMSD: number of atoms are not equal." - print "\t" + str(len(self.__parent_molecule.get_coordinates())) + " vs. " + str(len(other_mol.get_coordinates())) + " atoms." + print("Cannot calculate RMSD: number of atoms are not equal.") + print("\t" + str(len(self.__parent_molecule.get_coordinates())) + " vs. " + str(len(other_mol.get_coordinates())) + " atoms.") return 99999999.0 self_coors_in_order = self.__parent_molecule.get_coordinates()[tethers[0]] @@ -2119,17 +2120,17 @@ def load_from_mat(self, m): ''' #Make sure m is a 3x3 array if m.shape[0] != 3 or m.shape[1] != 3: - print "Could not load quaternion from matrix...size is not (3x3)" + print("Could not load quaternion from matrix...size is not (3x3)") return #Check that matrix is orthogonal. m_T = m_inv if not numpy.array_equal(numpy.transpose(m),numpy.linalg.inv(m)): - print "Load Quaternion error. Matrix is not orthogonal" + print("Load Quaternion error. Matrix is not orthogonal") return #Need to make sure that the matrix is special orthogonal if numpy.fabs(1-numpy.linalg.det(m)) > 0.000001: #Done for rounding errors - print "Load Quaternion error. Determinant is not 1" + print("Load Quaternion error. Determinant is not 1") return #First calculate the sum of the diagonal elements diff --git a/POVME/packages/pymolecule/test.py b/POVME/packages/pymolecule/test.py index 1c69550..be5a4e9 100644 --- a/POVME/packages/pymolecule/test.py +++ b/POVME/packages/pymolecule/test.py @@ -36,7 +36,7 @@ # You can also "save" to a string instead of to a file. Definitions used: # pymolecule.Molecule.fileio.save_pdb -print molecule.fileio.save_pdb('FILENAME DOES NOT MATTER', False, False, True)[:997] +print(molecule.fileio.save_pdb('FILENAME DOES NOT MATTER', False, False, True)[:997]) # Pymolecule can also save the data in the pym format, which is generally # faster than the PDB format. Definitions used:: @@ -177,7 +177,7 @@ # chain_selections is a dictionary, where the keys are the chainids and the values # are the corresponding selections. So, to save each chain to a separate file: -molecule_A = molecule.selections.get_molecule_from_selection(chain_selections['A']) +molecule_A = molecule.selections.get_molecule_from_selection(chain_selections[b'A']) molecule_A.fileio.save_pdb("./example_output/2HU4_chain_A.pdb") molecule_B = molecule.selections.get_molecule_from_selection(chain_selections['B']) molecule_B.fileio.save_pdb("./example_output/2HU4_chain_B.pdb") @@ -281,23 +281,23 @@ # pymolecule.Molecule.information.get_total_number_of_atoms # pymolecule.Molecule.information.get_total_number_of_heavy_atoms # pymolecule.Molecule.information.get_bounding_box -print "Center of mass:", molecule.information.get_center_of_mass() -print "Geometric center:", molecule.information.get_geometric_center() -print "Total mass:", molecule.information.get_total_mass() -print "Total number of atoms:", molecule.information.get_total_number_of_atoms() -print "Total number of heavy atoms:", molecule.information.get_total_number_of_heavy_atoms() -print "Bounding box:", molecule.information.get_bounding_box() +print("Center of mass:", molecule.information.get_center_of_mass()) +print("Geometric center:", molecule.information.get_geometric_center()) +print("Total mass:", molecule.information.get_total_mass()) +print("Total number of atoms:", molecule.information.get_total_number_of_atoms()) +print("Total number of heavy atoms:", molecule.information.get_total_number_of_heavy_atoms()) +print("Bounding box:", molecule.information.get_bounding_box()) # You can also get some information about what atoms are bonded to selected atoms. # For example, get the number of hydrogen atoms bonded to the 1st atom: # Definitions used: # pymolecule.Molecule.atoms_and_bonds.get_number_of_bond_partners_of_element -print "Number of hydrogen atoms bound to first atom:", molecule.atoms_and_bonds.get_number_of_bond_partners_of_element(0, "H") +print("Number of hydrogen atoms bound to first atom:", molecule.atoms_and_bonds.get_number_of_bond_partners_of_element(0, "H")) # You can also get the index of the first atom with a given element bound to # a specified atom. Definitions used: # pymolecule.Molecule.atoms_and_bonds.get_index_of_first_bond_partner_of_element -print "Index of the first hydrogen atom bound to first atom:", molecule.atoms_and_bonds.get_index_of_first_bond_partner_of_element(0, "H") +print("Index of the first hydrogen atom bound to first atom:", molecule.atoms_and_bonds.get_index_of_first_bond_partner_of_element(0, "H")) # Functions also exist for determining whether a given atom belongs to a protein, # DNA, or RNA molecule. Consider the 3943rd atom, which is known to belong to a @@ -305,9 +305,9 @@ # pymolecule.Molecule.information.belongs_to_protein # pymolecule.Molecule.information.belongs_to_dna # pymolecule.Molecule.information.belongs_to_rna -print "3943rd atom belongs to protein?", molecule.information.belongs_to_protein(3942) -print "3943rd atom belongs to DNA?", molecule.information.belongs_to_dna(3942) -print "3943rd atom belongs to RNA?", molecule.information.belongs_to_rna(3942) +print("3943rd atom belongs to protein?", molecule.information.belongs_to_protein(3942)) +print("3943rd atom belongs to DNA?", molecule.information.belongs_to_dna(3942)) +print("3943rd atom belongs to RNA?", molecule.information.belongs_to_rna(3942)) ########## Constructing Molecules Programatically ########## @@ -349,19 +349,19 @@ # 10 A cutoff. As above, if the third parameter is True, a simple pair-wise distance # comparison is performed. Definitions used: # pymolecule.Molecule.other_molecule.steric_clash_with_another_molecule -print "Clash according to steric_clash_with_another_molecule_atom_by_atom:", molecule_A.other_molecule.steric_clash_with_another_molecule(molecule_B, 10.0, True) +print("Clash according to steric_clash_with_another_molecule_atom_by_atom:", molecule_A.other_molecule.steric_clash_with_another_molecule(molecule_B, 10.0, True)) # If the third parameter is False (as above), the more sophisticated method for # identifying juxtaposed atoms is used. Definitions used: # pymolecule.Molecule.other_molecule.steric_clash_with_another_molecule -print "Clash according to steric_clash_with_another_molecule:", molecule_A.other_molecule.steric_clash_with_another_molecule(molecule_B, 10.0, False) +print("Clash according to steric_clash_with_another_molecule:", molecule_A.other_molecule.steric_clash_with_another_molecule(molecule_B, 10.0, False)) # PyMolecule can also be used to identify the minimum distance between two molecules. # The second parameter is like the third above, determining whether pair-wise or more # sophisticated methods are used to identify distances. Definitions used: # pymolecule.Molecule.other_molecule.get_distance_to_another_molecule -print 'Closest inter-chain distance according to pairwise comparison:', molecule_A.other_molecule.get_distance_to_another_molecule(molecule_B, True) -print 'Closest inter-chain distance according to sophisticated method:', molecule_A.other_molecule.get_distance_to_another_molecule(molecule_B, False) +print('Closest inter-chain distance according to pairwise comparison:', molecule_A.other_molecule.get_distance_to_another_molecule(molecule_B, True)) +print('Closest inter-chain distance according to sophisticated method:', molecule_A.other_molecule.get_distance_to_another_molecule(molecule_B, False)) #### I THINK THE ABOVE, THE BETTER METHOD MIGHT TAKE LONGER. WHY??? CHECK GENERALLY. # PyMolecule can calculate RMSD values. To demonstrate this, let's look at the first @@ -372,7 +372,7 @@ # The atoms of these two molecules are in the same order, so we can determine which # atoms are equivalent based on order alone. Definitions used: # pymolecule.Molecule.other_molecule.get_rmsd_order_dependent -print "RMSD between two chains, based on order: ", molecule_A_first_hundred.other_molecule.get_rmsd_order_dependent(molecule_B_first_hundred) +print("RMSD between two chains, based on order: ", molecule_A_first_hundred.other_molecule.get_rmsd_order_dependent(molecule_B_first_hundred)) # You can also specify which atoms are equivalent. This is accomplished using a tuple # of two numpy.array, where each array is comprised of the indecies of self and @@ -386,7 +386,7 @@ numpy.random.shuffle(mol1_index_in_order) numpy.random.shuffle(mol2_index_in_order) -print "RMSD between two chains, equiv atoms specified:", molecule_A_first_hundred.other_molecule.get_rmsd_equivalent_atoms_specified(molecule_B_first_hundred, (mol1_index_in_order, mol2_index_in_order)) +print("RMSD between two chains, equiv atoms specified:", molecule_A_first_hundred.other_molecule.get_rmsd_equivalent_atoms_specified(molecule_B_first_hundred, (mol1_index_in_order, mol2_index_in_order))) ##### YOU NEED ORDER INDEPENDENT ONE TOO!!!! WITH FINGERPRINTS???? ###### @@ -418,11 +418,11 @@ # For example, you can get the angle between three points. Definitions used: # pymolecule.Molecule.geometry.get_angle_between_three_points -print "Angle in radians between 1st, 2nd, and 3rd atoms:", molecule.geometry.get_angle_between_three_points(molecule.information.get_coordinates()[0], molecule.information.get_coordinates()[1], molecule.information.get_coordinates()[2]) +print("Angle in radians between 1st, 2nd, and 3rd atoms:", molecule.geometry.get_angle_between_three_points(molecule.information.get_coordinates()[0], molecule.information.get_coordinates()[1], molecule.information.get_coordinates()[2])) # You can also get the dihedral angle between four points. Definitions used: # pymolecule.Molecule.geometry.get_dihedral_angle -print "Dihedral angle in radians between 1st, 2nd, 3rd, and 4th atoms:", molecule.geometry.get_dihedral_angle(molecule.information.get_coordinates()[0], molecule.information.get_coordinates()[1], molecule.information.get_coordinates()[2], molecule.information.get_coordinates()[3]) +print("Dihedral angle in radians between 1st, 2nd, 3rd, and 4th atoms:", molecule.geometry.get_dihedral_angle(molecule.information.get_coordinates()[0], molecule.information.get_coordinates()[1], molecule.information.get_coordinates()[2], molecule.information.get_coordinates()[3])) # There's also a function to determine whether or not four points are in # a plane (within a given tolerance). For example, the 202nd, 203rd, 207th, @@ -431,4 +431,4 @@ # pymolecule.Molecule.geometry.is_planar # pymolecule.Molecule.geometry.get_planarity_deviation #four_atoms_from_TRP_sidechain_selection = numpy.array([201, 202, 206, 207]) -print "Four atoms in the same TRP sidechain are roughly planar?", molecule.geometry.is_planar(molecule.information.get_coordinates()[201], molecule.information.get_coordinates()[202], molecule.information.get_coordinates()[206], molecule.information.get_coordinates()[207], 0.2) +print("Four atoms in the same TRP sidechain are roughly planar?", molecule.geometry.is_planar(molecule.information.get_coordinates()[201], molecule.information.get_coordinates()[202], molecule.information.get_coordinates()[206], molecule.information.get_coordinates()[207], 0.2)) diff --git a/POVME/tests/runRegTests.py b/POVME/tests/runRegTests.py index cd8153c..26d3ed7 100644 --- a/POVME/tests/runRegTests.py +++ b/POVME/tests/runRegTests.py @@ -46,7 +46,7 @@ def compareFile(origFile, args): origFileData = remove_regex_lines(origFileData) newFile = origFile.replace('.orig','') if not os.path.exists(newFile): - print 'File %s does not exist - Unable to perform file comparison' %(newFile) + print('File %s does not exist - Unable to perform file comparison' %(newFile)) passed = False return passed newFileData = open(newFile).readlines() @@ -57,15 +57,15 @@ def compareFile(origFile, args): if newFileData == origFileData: #passedFiles.append(origFile) passed = True - print "Files %s and %s match!" %(newFile, origFile) + print("Files %s and %s match!" %(newFile, origFile)) else: #failedFiles.append(origFile) passed = False - print 'File %s DOES NOT MATCH' %(origFile) + print('File %s DOES NOT MATCH' %(origFile)) if args.compare == True: validChoice = False while validChoice == False: - choice = raw_input('Files %s and %s differ. View differences (y,n,v)? ' %(newFile, origFile)) + choice = input('Files %s and %s differ. View differences (y,n,v)? ' %(newFile, origFile)) if choice == 'y': ignoreStr = ' '.join(['-I %s' %(i) for i in regexes_to_ignore]) os.system('diff %s %s %s | less' %(ignoreStr, newFile, origFile)) @@ -89,16 +89,16 @@ def runTests(args): failedFiles = [] with Chdir(directory): - print + print() origFiles = glob.glob('*orig') if args.remove_old == True: files_to_remove = [i.replace('.orig','') for i in origFiles] for file_to_remove in files_to_remove: - print 'Removing', file_to_remove + print('Removing', file_to_remove) os.system('rm %s' %(file_to_remove)) - print "RUNNING TEST %s" %(linesp) + print("RUNNING TEST %s" %(linesp)) runCommand = '%s python %s > output' %(arunPath, script) - print "Run command: %s" %(runCommand) + print("Run command: %s" %(runCommand)) #os.system('%s python %s > output' %(arunPath,script)) #print '%s python %s/%s' %(arunPath, directory, script) start = time.time() @@ -108,16 +108,16 @@ def runTests(args): cwd = directory, shell=True) out, error = p.communicate() - print 'Test ran in %s seconds' %(time.time()-start) + print('Test ran in %s seconds' %(time.time()-start)) #print out, error results[title]['testPassed'] = True if p.returncode == 0: - print "Exit status: Completed" + print("Exit status: Completed") results[title]['exit_status'] = True else: - print "Exit status: Failed" - print 'error %s' %(error) + print("Exit status: Failed") + print('error %s' %(error)) results[title]['exit_status'] = False results[title]['testPassed'] = False @@ -135,23 +135,23 @@ def runTests(args): nPassed = 0 nFailed = 0 - print - print '===============' - print "RESULTS SUMMARY" - print '===============' + print() + print('===============') + print("RESULTS SUMMARY") + print('===============') for test in regTests: - print "----Test %s Exit Status = %s ----" %(test[0], results[test[0]]['exit_status']) - print "%i file comparisons succeeded: %s" %(len(results[test[0]]['passedFiles']), - results[test[0]]['passedFiles']) - print "%i file comparisons failed: %s" %(len(results[test[0]]['failedFiles']), results[test[0]]['failedFiles']) + print("----Test %s Exit Status = %s ----" %(test[0], results[test[0]]['exit_status'])) + print("%i file comparisons succeeded: %s" %(len(results[test[0]]['passedFiles']), + results[test[0]]['passedFiles'])) + print("%i file comparisons failed: %s" %(len(results[test[0]]['failedFiles']), results[test[0]]['failedFiles'])) if results[test[0]]['testPassed'] == True: nPassed += 1 else: nFailed += 1 - print - print '%i tests passed, %i tests failed' %(nPassed, nFailed) + print() + print('%i tests passed, %i tests failed' %(nPassed, nFailed)) if nFailed > 0: - print "TEST SUITE FAILED" + print("TEST SUITE FAILED") sys.exit(1)