From 69bd08be32c48946441a7589d10b7223e7e583a4 Mon Sep 17 00:00:00 2001 From: shadow_walker Date: Thu, 12 Jul 2018 18:48:31 -0500 Subject: [PATCH] futurize fixes: lib2to3.fixes.fix_dict cmd: find . -name '*.py' | xargs futurize -w -n --no-diff -j6 -f lib2to3.fixes.fix_dict --- broken/e2avg_ffts.py | 2 +- broken/e2plotFSC.py | 2 +- broken/e2preferences.py | 2 +- broken/e2remoted.py | 2 +- broken/e2scp.py | 2 +- doc/modular_class_html/docgen.py | 16 +-- examples/e2extractctf.py | 2 +- examples/e2melonball.py | 2 +- examples/e2plot_de_motion.py | 2 +- examples/e2plotfig.py | 2 +- examples/e2simmxptclqual.py | 2 +- examples/e2spt_eval_orient.py | 2 +- examples/e2spt_extract_align.py | 2 +- examples/e2spt_group.py | 2 +- examples/e2spt_radialdensityplot.py | 2 +- examples/e2spt_reconfromtilts.py | 4 +- examples/e2spt_transform.py | 2 +- examples/e2starfiletoboxfile.py | 2 +- examples/e2starfiletolstfile.py | 2 +- examples/e2tomogram_old.py | 4 +- examples/extractfsc.py | 2 +- examples/extractptclfromseg.py | 2 +- examples/mergeproject.py | 10 +- examples/mergeproject2.py | 2 +- examples/movie_analyzer.py | 36 +++---- examples/movie_ccf.py | 4 +- examples/prepare_eulerxplor_from_spt.py | 2 +- libpyEM/Anneal.py | 4 +- libpyEM/EMAN2.py | 4 +- libpyEM/EMAN2PAR.py | 12 +-- libpyEM/EMAN2_utils.py | 2 +- libpyEM/EMAN2db.py | 24 ++--- libpyEM/EMAN2jsondb.py | 12 +-- libpyEM/qtgui/emboxerbase.py | 22 ++--- libpyEM/qtgui/embrowser.py | 10 +- libpyEM/qtgui/emdatastorage.py | 36 +++---- libpyEM/qtgui/emform.py | 26 ++--- libpyEM/qtgui/emhist.py | 18 ++-- libpyEM/qtgui/emimage.py | 6 +- libpyEM/qtgui/emimage2d.py | 10 +- libpyEM/qtgui/emimage3dsym.py | 4 +- libpyEM/qtgui/emimagemx.py | 10 +- libpyEM/qtgui/emimageutil.py | 4 +- libpyEM/qtgui/emplot2d.py | 24 ++--- libpyEM/qtgui/emplot3d.py | 20 ++-- libpyEM/qtgui/emrctboxergui.py | 2 +- libpyEM/qtgui/emselector.py | 12 +-- libpyEM/qtgui/emsprworkflow.py | 110 ++++++++++----------- libpyEM/qtgui/emtprworkflow.py | 20 ++-- programs/e2RCTboxer.py | 2 +- programs/e2a2d_average.py | 2 +- programs/e2a2d_stat.py | 12 +-- programs/e2bdb.py | 18 ++-- programs/e2boxer_old.py | 12 +-- programs/e2classify.py | 2 +- programs/e2classifytree.py | 2 +- programs/e2classvsproj.py | 2 +- programs/e2ctffind3util.py | 2 +- programs/e2ddd_movie.py | 4 +- programs/e2emx.py | 10 +- programs/e2eulerxplor.py | 4 +- programs/e2evalrefine.py | 2 +- programs/e2filtertool.py | 2 +- programs/e2helixboxer.py | 8 +- programs/e2help.py | 8 +- programs/e2history.py | 2 +- programs/e2iminfo.py | 2 +- programs/e2import.py | 2 +- programs/e2maskbyclass.py | 2 +- programs/e2motion.py | 4 +- programs/e2parallel.py | 6 +- programs/e2pathwalker.py | 18 ++-- programs/e2pdb2mrc.py | 4 +- programs/e2plotEulers.py | 2 +- programs/e2proc2d.py | 6 +- programs/e2proc2dpar.py | 6 +- programs/e2proc3d.py | 6 +- programs/e2project3d.py | 2 +- programs/e2projectmanager.py | 12 +-- programs/e2projectupdate21.py | 4 +- programs/e2refinemultinoali.py | 2 +- programs/e2refinetorelion2d.py | 2 +- programs/e2refinetorelion3d.py | 2 +- programs/e2simmx.py | 10 +- programs/e2spt_average.py | 6 +- programs/e2spt_average_multi.py | 6 +- programs/e2spt_boxer.py | 8 +- programs/e2spt_boxer22.py | 8 +- programs/e2spt_classaverage.py | 10 +- programs/e2spt_ctf_old.py | 6 +- programs/e2spt_eval.py | 2 +- programs/e2spt_extract.py | 2 +- programs/e2spt_hac.py | 10 +- programs/e2spt_refine.py | 2 +- programs/e2spt_refinemulti.py | 4 +- programs/e2spt_sgd.py | 2 +- programs/e2spt_simulation.py | 2 +- programs/e2spt_stat.py | 6 +- programs/e2spt_tempmatch.py | 2 +- programs/e2spt_tiltrefine.py | 4 +- programs/e2tilefile.py | 2 +- programs/e2tiltseries.py | 2 +- programs/e2tomo_eval.py | 6 +- pyemtbx/boxertools.py | 2 +- rt/pyem/test_emdata.py | 4 +- sparx/bin/sxgui.py | 12 +-- sparx/bin/sxgui_meridien.py | 4 +- sparx/bin/sxhelixboxer.py | 8 +- sparx/bin/sxrelion2sphire.py | 6 +- sparx/bin/sxsort3d_depth.py | 6 +- sparx/bin/sxsort3d_new.py | 4 +- sparx/doc/Tutorial/scripts/gfm_to_latex.py | 4 +- sparx/libpy/applications.py | 2 +- sparx/libpy/statistics.py | 2 +- sparx/libpy/utilities.py | 4 +- sparx/templates/sxgui_template.py | 12 +-- sparx/templates/wikiparser.py | 16 +-- 117 files changed, 435 insertions(+), 435 deletions(-) diff --git a/broken/e2avg_ffts.py b/broken/e2avg_ffts.py index 28dc38ef28..270a8bbfe8 100644 --- a/broken/e2avg_ffts.py +++ b/broken/e2avg_ffts.py @@ -53,7 +53,7 @@ def avg_this_pixel (filename, imagedict, thr, i,j,k): # suma2=0. num=0 numth=0 - for filename in imagedict.keys(): + for filename in list(imagedict.keys()): # print filename, i,j,k re= imagedict[filename].get_value_at(i,j,k) im= imagedict[filename].get_value_at(i+1,j,k) diff --git a/broken/e2plotFSC.py b/broken/e2plotFSC.py index 7d472d4d58..c56ee4e453 100644 --- a/broken/e2plotFSC.py +++ b/broken/e2plotFSC.py @@ -75,7 +75,7 @@ def main(): print("Rubbish!!!, no FSC curves found!!!") return db = db_open_dict(db_name,ro=True) - keys = db.keys() + keys = list(db.keys()) # Load desired FSC curves res = [] diff --git a/broken/e2preferences.py b/broken/e2preferences.py index e8ff65ae85..a6dd916359 100644 --- a/broken/e2preferences.py +++ b/broken/e2preferences.py @@ -106,7 +106,7 @@ def write_db_entries(self,params): HOMEDB.open_dict("e2tomoboxer_preferences") db_tomo = HOMEDB.e2tomoboxer_preferences tmp_db = None - for key,value in params.items(): + for key,value in list(params.items()): if key in self.__tomoboxer_entries: tmp_db = db_tomo elif key in self.__display_entries: diff --git a/broken/e2remoted.py b/broken/e2remoted.py index 3276e7d565..5e24f9a33f 100644 --- a/broken/e2remoted.py +++ b/broken/e2remoted.py @@ -181,7 +181,7 @@ def recv_file(stdin,path): def send_bdb(stdout,path): "Sends a BDB to stdout as a set of compressed pickled key/value pairs, terminated by a None key" db=db_open_dict(path) - keys=db.keys() + keys=list(db.keys()) for k in keys: write_obj(stdout,k) write_obj(stdout,db[k]) diff --git a/broken/e2scp.py b/broken/e2scp.py index 978070bbbe..c9161ea8d2 100644 --- a/broken/e2scp.py +++ b/broken/e2scp.py @@ -212,7 +212,7 @@ def recv_file(stdin,path): def send_bdb(stdout,path): "Sends a BDB to stdout as a set of compressed pickled key/value pairs, terminated by a None key" db=db_open_dict(path) - keys=db.keys() + keys=list(db.keys()) for k in keys: write_obj(stdout,k) write_obj(stdout,db[k]) diff --git a/doc/modular_class_html/docgen.py b/doc/modular_class_html/docgen.py index 954198cf6e..e7c8354df1 100755 --- a/doc/modular_class_html/docgen.py +++ b/doc/modular_class_html/docgen.py @@ -71,7 +71,7 @@ def write_processor(processorname, output, bgcolor): typedict = processor.get_param_types() output.write(" ") - typekeys = typedict.keys() + typekeys = list(typedict.keys()) for typekey in typekeys: output.write(typedict.get_type(typekey).lower() + " ") @@ -91,7 +91,7 @@ def write_cmp(cmp_name, output, bgcolor): typedict = cmp.get_param_types() output.write(" ") - typekeys = typedict.keys() + typekeys = list(typedict.keys()) for typekey in typekeys: output.write(typedict.get_type(typekey).lower() + " ") @@ -111,7 +111,7 @@ def write_aligner(aligner_name, output, bgcolor): typedict = align.get_param_types() output.write(" ") - typekeys = typedict.keys() + typekeys = list(typedict.keys()) for typekey in typekeys: output.write(typedict.get_type(typekey).lower() + " ") @@ -131,7 +131,7 @@ def write_projector(projector_name, output, bgcolor): typedict = project.get_param_types() output.write(" ") - typekeys = typedict.keys() + typekeys = list(typedict.keys()) for typekey in typekeys: output.write(typedict.get_type(typekey).lower() + " ") @@ -151,7 +151,7 @@ def write_reconstructor(reconstructor_name, output, bgcolor): typedict = reconstruct.get_param_types() output.write(" ") - typekeys = typedict.keys() + typekeys = list(typedict.keys()) for typekey in typekeys: output.write(typedict.get_type(typekey).lower() + " ") @@ -171,7 +171,7 @@ def write_averager(averager_name, output, bgcolor): typedict = average.get_param_types() output.write(" ") - typekeys = typedict.keys() + typekeys = list(typedict.keys()) for typekey in typekeys: output.write(typedict.get_type(typekey).lower() + " ") @@ -191,7 +191,7 @@ def write_analyzer(analyzer_name, output, bgcolor): typedict = analyze.get_param_types() output.write(" ") - typekeys = typedict.keys() + typekeys = list(typedict.keys()) for typekey in typekeys: output.write(typedict.get_type(typekey).lower() + " ") @@ -356,7 +356,7 @@ def write_group_processors(): gout = open("processor_groups.html", "wb") write_header(gout, 'Processor Group') processorgroups = group_processors() - groupnames = processorgroups.keys() + groupnames = list(processorgroups.keys()) bgcolor1 = 'f0f0fa' bgcolor2 = 'fafaf0' bgcolor = bgcolor1 diff --git a/examples/e2extractctf.py b/examples/e2extractctf.py index f1070554df..996d94ecf4 100755 --- a/examples/e2extractctf.py +++ b/examples/e2extractctf.py @@ -8,7 +8,7 @@ db=db_open_dict("bdb:e2ctf.parms",True) out=open("ctf_parms.txt","w") -for k in db.keys(): +for k in list(db.keys()): ctf=EMAN2Ctf() ctf.from_string(db[k][0]) out.write( "%s,%1.3f,%1.1f\n"%(k,ctf.defocus,ctf.bfactor)) diff --git a/examples/e2melonball.py b/examples/e2melonball.py index 5deddc0782..e90b5bcf3c 100755 --- a/examples/e2melonball.py +++ b/examples/e2melonball.py @@ -402,7 +402,7 @@ def getptcltransforms(options): ptclts = {} - keys = jsonfileopen.keys() + keys = list(jsonfileopen.keys()) keys.sort() #n = len(keys) for j in xrange(0,n): diff --git a/examples/e2plot_de_motion.py b/examples/e2plot_de_motion.py index 39f738791b..e21e69e512 100644 --- a/examples/e2plot_de_motion.py +++ b/examples/e2plot_de_motion.py @@ -231,7 +231,7 @@ def main(): print("\n(DE_translation_plotter)(main) ids before are {} type={} ".format( ids, type(ids) )) print("\ndatadict is {}".format(datadict)) - datadictsorted = sorted(datadict.items(), key=lambda e: e[1][0]) + datadictsorted = sorted(list(datadict.items()), key=lambda e: e[1][0]) if options.verbose > 9: print("\n(DE_translation_plotter)(main) datadictsorted is {}".format(datadictsorted)) diff --git a/examples/e2plotfig.py b/examples/e2plotfig.py index 67604fe93f..0e9ea57063 100644 --- a/examples/e2plotfig.py +++ b/examples/e2plotfig.py @@ -349,7 +349,7 @@ def plotdata( options, data ): #import string #markers=string.printable - markers = matplotlib.markers.MarkerStyle.markers.keys() + markers = list(matplotlib.markers.MarkerStyle.markers.keys()) marker='' diff --git a/examples/e2simmxptclqual.py b/examples/e2simmxptclqual.py index 15cbfb71cf..6d1d440d7f 100755 --- a/examples/e2simmxptclqual.py +++ b/examples/e2simmxptclqual.py @@ -96,7 +96,7 @@ def main(): except: bvecs[N]=im # normalize all vector sums - for im in bvecs.values(): + for im in list(bvecs.values()): im.process_inplace("normalize.unitlen") # Make an output image of vectors diff --git a/examples/e2spt_eval_orient.py b/examples/e2spt_eval_orient.py index 7fbc9d9be1..c41f31152e 100755 --- a/examples/e2spt_eval_orient.py +++ b/examples/e2spt_eval_orient.py @@ -62,7 +62,7 @@ def main(): out=open(options.output,"w") alts=[ [] for i in xrange(18)] - for k in db.keys(): + for k in list(db.keys()): xf=db[k][0].inverse() xfd=xf.get_params("eman") out.write("%1.3f,\t%1.3f,\t%1.3f,\t%1.3g\n"%(xfd["az"],xfd["alt"],xfd["phi"],float(db[k][1]))) diff --git a/examples/e2spt_extract_align.py b/examples/e2spt_extract_align.py index 14009ef8d1..bf0035e70d 100755 --- a/examples/e2spt_extract_align.py +++ b/examples/e2spt_extract_align.py @@ -115,7 +115,7 @@ def main(): print("Line of coordinates to add",line) tomograms[tomogram].append(line) - for tomogram in tomograms.keys(): + for tomogram in list(tomograms.keys()): #coordsfile = options.path + '/' + options.input.replace('.hdf','_coords.txt') coordsfile = options.path + '/' + tomogram.split('.')[0] + '_coords.txt' diff --git a/examples/e2spt_group.py b/examples/e2spt_group.py index b347c26f85..92c56ce7a0 100755 --- a/examples/e2spt_group.py +++ b/examples/e2spt_group.py @@ -176,7 +176,7 @@ def main(): dataset.update({i:scores[i]}) #x.append(i) - dataset = sorted( dataset.items(), key=itemgetter(1), reverse=True ) + dataset = sorted( list(dataset.items()), key=itemgetter(1), reverse=True ) if options.normalizeplot: #for s in scores: diff --git a/examples/e2spt_radialdensityplot.py b/examples/e2spt_radialdensityplot.py index 9acbe1999b..97ed1b9f1a 100755 --- a/examples/e2spt_radialdensityplot.py +++ b/examples/e2spt_radialdensityplot.py @@ -203,7 +203,7 @@ def main(): cc=0 for ele in finalvalues: - thisfile = ele.keys()[0] + thisfile = list(ele.keys())[0] key = thisfile n = EMUtil.get_image_count(thisfile) diff --git a/examples/e2spt_reconfromtilts.py b/examples/e2spt_reconfromtilts.py index b45ed23f52..1b553b83bc 100755 --- a/examples/e2spt_reconfromtilts.py +++ b/examples/e2spt_reconfromtilts.py @@ -21,7 +21,7 @@ def main(): sptpath=os.path.dirname(options.json) js=js_open_dict(options.json) - print("Read alignment of {:d} 3D particles.".format(len(js.keys()))) + print("Read alignment of {:d} 3D particles.".format(len(list(js.keys())))) ks=[eval(str(s)) for s in sorted(js.keys())] ### lists in dictionaries in dictionaries..... @@ -48,7 +48,7 @@ def main(): lst=[LSXFile(m, False) for m in lname] - pnames=ptclnames.keys() + pnames=list(ptclnames.keys()) for pname in pnames: modelids=sorted(ptclnames[pname].keys()) num=EMUtil.get_image_count(pname) diff --git a/examples/e2spt_transform.py b/examples/e2spt_transform.py index 1c548aab3a..05aee984e6 100644 --- a/examples/e2spt_transform.py +++ b/examples/e2spt_transform.py @@ -116,7 +116,7 @@ def main(): n = int(nt) print("\nWARNING: more particles/coordinates n={} than transform parameters nt={}".format(n,nt)) - keys = jsonfileopen.keys() + keys = list(jsonfileopen.keys()) keys.sort() for j in range(n): label = keys[j] diff --git a/examples/e2starfiletoboxfile.py b/examples/e2starfiletoboxfile.py index a99e3dbbbf..7e4baf0d5a 100755 --- a/examples/e2starfiletoboxfile.py +++ b/examples/e2starfiletoboxfile.py @@ -42,7 +42,7 @@ def main(): logger = E2init(sys.argv) - hdr = starf.keys() + hdr = list(starf.keys()) # resolve correct micrograph dictionary key diff --git a/examples/e2starfiletolstfile.py b/examples/e2starfiletolstfile.py index 650c8739e9..dc312f5f9d 100755 --- a/examples/e2starfiletolstfile.py +++ b/examples/e2starfiletolstfile.py @@ -48,7 +48,7 @@ # in the below line, -1 tells it to append the line, the next value is the image number in that image, and the final value is the image name -for i in range(len(starf[starf.keys()[0]])): +for i in range(len(starf[list(starf.keys())[0]])): if options.path: filepath1=starf['rlnImageName'][i].split("@")[1].replace(".mrcs",".hdf").split("/") filepath = options.path + "/" + filepath1[len(filepath1)-1] diff --git a/examples/e2tomogram_old.py b/examples/e2tomogram_old.py index bec100c934..1221279233 100755 --- a/examples/e2tomogram_old.py +++ b/examples/e2tomogram_old.py @@ -112,7 +112,7 @@ def mode(vals): try: d[i]=d[i]+1 except: d[i]=1 - cnt=[(i[1],i[0]) for i in d.items()] + cnt=[(i[1],i[0]) for i in list(d.items())] cnt.sort() @@ -209,7 +209,7 @@ def main(): if options.mode=="modeshift" : dct=matrixalign(im1,im2,options.box,options.box+options.maxshift,debug=i[0]==63) - vec=dct.values() + vec=list(dct.values()) vec.sort() # sort in order of peak height vec2=vec[-len(vec)/4:] # take the 25% strongest correlation peaks diff --git a/examples/extractfsc.py b/examples/extractfsc.py index f9a555f24f..d1f9db1943 100755 --- a/examples/extractfsc.py +++ b/examples/extractfsc.py @@ -42,7 +42,7 @@ db=db_open_dict("bdb:%s#convergence.results"%sys.argv[1],ro=True) -for k in db.keys(): +for k in list(db.keys()): curve=db[k] out=open("fsc_%s_%s.txt"%(sys.argv[1].rsplit("_",1)[-1],k),"w") for i in xrange(len(curve[0])): out.write("%1.5f\t%1.4f\n"%(curve[0][i],curve[1][i])) diff --git a/examples/extractptclfromseg.py b/examples/extractptclfromseg.py index accd1b2639..6d8e395a8b 100755 --- a/examples/extractptclfromseg.py +++ b/examples/extractptclfromseg.py @@ -226,7 +226,7 @@ def main(): jsname=info_name(tomoname) js=js_open_dict(jsname) if "class_list" in js: - clst=[int(k) for k in js["class_list"].keys()] + clst=[int(k) for k in list(js["class_list"].keys())] for ii in range(100): if ii not in clst: mytag=ii diff --git a/examples/mergeproject.py b/examples/mergeproject.py index d7919233af..5ac35e61d5 100755 --- a/examples/mergeproject.py +++ b/examples/mergeproject.py @@ -68,7 +68,7 @@ # filter out images with low quality if requested if minq>0 : src2=db_open_dict("bdb:%s#e2ctf.parms"%source,ro=True) - for k in src2.keys(): + for k in list(src2.keys()): if src2[k][3]0 : src2=db_open_dict("bdb:%s#e2ctf.parms"%source,ro=True) goodkeys=[] - for k in src2.keys(): + for k in list(src2.keys()): if src2[k][3]1 : print("Data translate ",k,i) # try: if isinstance(i,list) and len(i)>0 and i[0]=="cache" : @@ -2192,13 +2192,13 @@ def run(self,dieifidle=86400,dieifnoserver=86400,onejob=False): retry=True continue - for k,v in ret.items(): + for k,v in list(ret.items()): signal.alarm(120) try: sendobj(sockf,k) sendobj(sockf,v) except : - print("ERROR (retrying ",task.taskid,") on : ",k, " in ",ret.items()) + print("ERROR (retrying ",task.taskid,") on : ",k, " in ",list(ret.items())) if isinstance(v,EMData) : v.write_image("error.hdf",-1) time.sleep(3) retry=True diff --git a/libpyEM/EMAN2_utils.py b/libpyEM/EMAN2_utils.py index 99b8dc3c90..ea044b10e1 100644 --- a/libpyEM/EMAN2_utils.py +++ b/libpyEM/EMAN2_utils.py @@ -12,7 +12,7 @@ from scipy.interpolate import interp1d amino_dict= {0: 'ALA', 1: 'ARG', 2: 'ASN', 3: 'ASP', 4: 'CYS', 5: 'GLU', 6: 'GLN', 7: 'GLY', 8: 'HIS', 9: 'ILE', 10: 'LEU', 11: 'LYS', 12: 'MET', 13: 'PHE', 14: 'PRO', 15: 'SER', 16: 'THR', 17: 'TRP', 18: 'TYR', 19: 'VAL', 20: 'ASX', 21:'GLX'} -amino_dict.update(dict((v, k) for k, v in amino_dict.iteritems())) +amino_dict.update(dict((v, k) for k, v in amino_dict.items())) amino_dict.update({'A': 0, 'C': 4, 'E': 5, 'D': 3, 'G': 7, 'F': 13, 'I': 9, 'H': 8, 'K': 11, 'M': 12, 'L': 10, 'N': 2, 'Q': 6, 'P': 14, 'S': 15, 'R': 1, 'T': 16, 'W': 17, 'V': 19, 'Y': 18, 'X':20}) def pdb2numpy(fname, readres=False, readocc=False, readbfac=False): diff --git a/libpyEM/EMAN2db.py b/libpyEM/EMAN2db.py index c312c13778..24adb568dd 100755 --- a/libpyEM/EMAN2db.py +++ b/libpyEM/EMAN2db.py @@ -90,13 +90,13 @@ def DB_cleanup(signum=None,stack=None): try: nopen=len([i for i in DBDict.alldicts if i.bdb!=None]) except: nopen=0 print("Program interrupted (%d), closing %d databases, please wait (%d)"%(signum,nopen,os.getpid())) - for i in DBDict.alldicts.keys(): print(i.name) + for i in list(DBDict.alldicts.keys()): print(i.name) if stack!=None : traceback.print_stack(stack) - for d in DBDict.alldicts.keys(): + for d in list(DBDict.alldicts.keys()): d.forceclose() d.lock.acquire(False) # prevents reopening - for e in EMAN2DB.opendbs.values(): e.close() - for d in DBDict.alldicts.keys(): + for e in list(EMAN2DB.opendbs.values()): e.close() + for d in list(DBDict.alldicts.keys()): try : d.lock.release() # This will (intentionally) allow the threads to fail, since the environment is now closed except : pass if signum in (2,15) : @@ -123,7 +123,7 @@ def parallel_process_exit(): if os.access('EMAN2DB',os.R_OK): # Kill any running process from e2paralle.py running on localhost. If none are running nothing happens from EMAN2PAR import EMLocalTaskHandler - for proc in EMLocalTaskHandler.allrunning.values(): + for proc in list(EMLocalTaskHandler.allrunning.values()): proc.terminate() os.kill(proc.pid,signal.SIGKILL) @@ -691,7 +691,7 @@ def add_task(self,task): task.queuetime=time.time() # map data file specifiers to ids - for j,k in task.data.items(): + for j,k in list(task.data.items()): try: if k[0]!="cache" : continue except: continue @@ -969,7 +969,7 @@ def close(self): def __del__(self): if not self.dbenv: return - for i in self.dicts.keys() : self.close_dict(i) + for i in list(self.dicts.keys()) : self.close_dict(i) self.close() def __getitem__(self,key): @@ -1076,7 +1076,7 @@ def updateold(self,lfile,ro=False): print("Error 2 updating %s. Please contact sludtke@bcm.edu."%lfile) os._exit(1) - for k in tmpdb.keys(): + for k in list(tmpdb.keys()): self.bdb[k]=tmpdb[k] tmpdb.close() @@ -1413,7 +1413,7 @@ def item_type(self,key): def keys(self): self.realopen(self.rohint) - try: return [loads(x) for x in self.bdb.keys() if x[0]=='\x80'] + try: return [loads(x) for x in list(self.bdb.keys()) if x[0]=='\x80'] except: traceback.print_exc() print("This is a serious error, which should never occur during normal usage.\n Please report it (with the error text above) to sludtke@bcm.edu. Please also read the database warning page in the Wiki.") @@ -1421,11 +1421,11 @@ def keys(self): def values(self): self.realopen(self.rohint) - return [self[k] for k in self.keys()] + return [self[k] for k in list(self.keys())] def items(self): self.realopen(self.rohint) - return [(k,self[k]) for k in self.keys()] + return [(k,self[k]) for k in list(self.keys())] def has_key(self,key): self.realopen(self.rohint) @@ -1598,7 +1598,7 @@ def set_header(self,key,val,txn=None): def update(self,dict): self.realopen() - for i,j in dict.items(): self[i]=j + for i,j in list(dict.items()): self[i]=j #def DB_cleanup(): diff --git a/libpyEM/EMAN2jsondb.py b/libpyEM/EMAN2jsondb.py index e73ac21eb3..67191933e1 100755 --- a/libpyEM/EMAN2jsondb.py +++ b/libpyEM/EMAN2jsondb.py @@ -154,7 +154,7 @@ def emdata_from_jsondict(dct): try: del dct[k] except: pass - for k in dct.keys(): + for k in list(dct.keys()): ret[k]=dct[k] ret.update() @@ -358,7 +358,7 @@ def add_task(self,task): task.queuetime=time.time() # map data file specifiers to ids - for j,k in task.data.items(): + for j,k in list(task.data.items()): try: if k[0]!="cache" : continue except: continue @@ -756,15 +756,15 @@ def __contains__(self,key): def keys(self): self.sync() - return self.data.keys() + return list(self.data.keys()) def values(self): self.sync() - return [self.get(key) for key in self.data.keys()] # to make sure images are read + return [self.get(key) for key in list(self.data.keys())] # to make sure images are read def items(self): self.sync() - return [(key,self.get(key)) for key in self.data.keys()] + return [(key,self.get(key)) for key in list(self.data.keys())] def has_key(self,key): self.sync() @@ -775,7 +775,7 @@ def update(self,newdict): """Equivalent to dictionary update(). Performs JSON file update all at once, so substantially better performance than many individual changes.""" - for k in newdict.keys(): self.setval(k,newdict[k],deferupdate=True) + for k in list(newdict.keys()): self.setval(k,newdict[k],deferupdate=True) self.sync() def setdefault(self,key,dfl,noupdate=False): diff --git a/libpyEM/qtgui/emboxerbase.py b/libpyEM/qtgui/emboxerbase.py index c32c7e01ce..ba46be1ef9 100644 --- a/libpyEM/qtgui/emboxerbase.py +++ b/libpyEM/qtgui/emboxerbase.py @@ -982,12 +982,12 @@ def boxes_erased(self,rm_boxes): @param rm_boxes a list of EMBox objects ''' name_box_map = {} - for name,handler in self.mouse_handlers.items(): + for name,handler in list(self.mouse_handlers.items()): name_box_map[name] = handler.get_unique_box_types() rm_box_map = {} for box in rm_boxes: - for name,box_types in name_box_map.items(): + for name,box_types in list(name_box_map.items()): if box.type in box_types: if name in rm_box_map: rm_box_map[name].append(box) @@ -995,7 +995,7 @@ def boxes_erased(self,rm_boxes): rm_box_map[name] = [box] - for name,boxes in rm_box_map.items(): + for name,boxes in list(rm_box_map.items()): self.mouse_handlers[name].boxes_erased(boxes) def mouse_down(self,event) : @@ -1912,7 +1912,7 @@ def set_main_2d_mouse_mode(self,mode): self.main_2d_window.add_eraser_shape("None",None) self.main_2d_window.updateGL() - for mouse_handler in self.signal_slot_handlers.values(): + for mouse_handler in list(self.signal_slot_handlers.values()): mouse_handler.set_mouse_mode(mode) @@ -1920,7 +1920,7 @@ def set_inspector_tool_mode(self,mode): self.current_tool = mode self.inspector.set_tool_mode(mode) - for mouse_handler in self.signal_slot_handlers.values(): + for mouse_handler in list(self.signal_slot_handlers.values()): mouse_handler.set_mouse_mode(mode) @@ -1973,7 +1973,7 @@ def __init_thumbs_window(self,redo_thumbs=False): self.thumbs_window.set_mouse_mode("App") self.thumbs_window.setWindowTitle("Thumbnails") self.signal_slot_handlers["thumbs_window"] = ThumbsEventHandler(self,self.thumbs_window) - for tool in self.tools.values(): + for tool in list(self.tools.values()): self.signal_slot_handlers["thumbs_window"].add_mouse_handler(tool) get_application().setOverrideCursor(QtCore.Qt.ArrowCursor) @@ -2005,7 +2005,7 @@ def __init_particles_window(self): self.particles_window.set_mouse_mode("App") self.particles_window.setWindowTitle("Particles") self.signal_slot_handlers["particles_window"] = ParticlesWindowEventHandler(self,self.particles_window) - for tool in self.tools.values(): + for tool in list(self.tools.values()): self.signal_slot_handlers["particles_window"].add_mouse_handler(tool) def particles_window_closed(self): @@ -2123,7 +2123,7 @@ def set_current_file(self,file_name): self.load_default_status_msg() - for name, mouse_handler in self.tools.items(): + for name, mouse_handler in list(self.tools.items()): mouse_handler.set_current_file(file_name,name==self.current_tool) get_application().setOverrideCursor(QtCore.Qt.ArrowCursor) @@ -2137,7 +2137,7 @@ def __init_main_2d_window(self): self.main_2d_window.set_mouse_mode(0) self.signal_slot_handlers["2d_window"] = Main2DWindowEventHandler(self,self.main_2d_window) - for tool in self.tools.values(): + for tool in list(self.tools.values()): self.signal_slot_handlers["2d_window"].add_mouse_handler(tool) get_application().show_specific(self.main_2d_window) @@ -2159,7 +2159,7 @@ def add_tool(self,event_tool_class,**kargs): if self.current_tool == None: self.current_tool = name self.tools[name] = event_tool - for mouse_handler in self.signal_slot_handlers.values(): + for mouse_handler in list(self.signal_slot_handlers.values()): mouse_handler.add_mouse_handler(event_tool) self.inspector.add_mouse_tool(event_tool) @@ -2460,7 +2460,7 @@ def get_display_tab(self): viewhbl2 = QtGui.QHBoxLayout() self.boxformats = QtGui.QComboBox(self) - for val in EMBoxerInspector.PTCL_SHAPE_MAP.keys(): + for val in list(EMBoxerInspector.PTCL_SHAPE_MAP.keys()): self.boxformats.addItem(val) viewhbl2.addWidget(self.boxformats) diff --git a/libpyEM/qtgui/embrowser.py b/libpyEM/qtgui/embrowser.py index e8df337b06..1410fde669 100644 --- a/libpyEM/qtgui/embrowser.py +++ b/libpyEM/qtgui/embrowser.py @@ -889,7 +889,7 @@ def __init__(self, path) : EMFileType.__init__(self, path) # the current path this FileType is representing self.js = js_open_dict(path) - self.keys = self.js.keys() + self.keys = list(self.js.keys()) self.dim = (0, 0, 0) def __del__(self) : @@ -937,7 +937,7 @@ def __init__(self, path) : self.nimg = len(self.bdb) - if self.nimg == 0 : self.keys = self.bdb.keys() + if self.nimg == 0 : self.keys = list(self.bdb.keys()) else : self.keys = None if self.nimg > 0 : @@ -2332,7 +2332,7 @@ def display(self, target) : if target.nimg == 0 : self.wimnum.hide() - k = self.bdb.keys() + k = list(self.bdb.keys()) k.sort() self.wimlist.addItems(k) self.wimlist.show() @@ -2517,7 +2517,7 @@ def display(self, target) : # Set up image selectors for stacks - k = self.js.keys() + k = list(self.js.keys()) k.sort() self.wkeylist.addItems(k) self.wkeylist.show() @@ -2594,7 +2594,7 @@ def addTreeItem(self, trg, parent = None) : elif isinstance(trg, EMAN2Ctf) : itms.append(QtGui.QTreeWidgetItem(QtCore.QStringList(("EMAN2Ctf", "")))) subitms = [] - for k, v in trg.to_dict().items() : + for k, v in list(trg.to_dict().items()) : if isinstance(v, (list, tuple)) : v = ["%1.3g"%i for i in v] subitms.append(QtGui.QTreeWidgetItem(QtCore.QStringList((str(k), ", ".join(v))))) diff --git a/libpyEM/qtgui/emdatastorage.py b/libpyEM/qtgui/emdatastorage.py index 63c32e17de..22e75cdb85 100644 --- a/libpyEM/qtgui/emdatastorage.py +++ b/libpyEM/qtgui/emdatastorage.py @@ -399,10 +399,10 @@ def validate(self): if self.defaultunits != None: a=[] - for q in valid_properties.values(): + for q in list(valid_properties.values()): # ian - a.extend(q[1].keys()) - a.extend(q[2].keys()) + a.extend(list(q[1].keys())) + a.extend(list(q[2].keys())) if not str(self.defaultunits) in a and str(self.defaultunits) != '': #raise ValueError,"Invalid defaultunits; not in valid_properties" print("Warning: Invalid defaultunits; not in valid_properties") @@ -498,7 +498,7 @@ def __str__(self): def stringparams(self): """returns the params for this recorddef as an indented printable string""" r=["{"] - for k,v in self.params.items(): + for k,v in list(self.params.items()): r.append("\n\t%s: %s"%(k,str(v))) return "".join(r)+" }\n" @@ -530,7 +530,7 @@ def keys(self): def findparams(self): """This will update the list of params by parsing the views""" t,d=parseparmvalues(self.mainview) - for i in self.views.values(): + for i in list(self.views.values()): t2,d2=parseparmvalues(i) for j in t2: # ian: fix for: empty default value in a view unsets default value specified in mainview @@ -551,7 +551,7 @@ def items_dict(self): def fromdict(self,d): - for k,v in d.items(): + for k,v in list(d.items()): self.__setattr__(k,v) self.validate() @@ -589,7 +589,7 @@ def validate(self): if "recname" not in dict(self.views): print("Warning: recname view strongly suggested") - for k,v in self.views.items(): + for k,v in list(self.views.items()): if not isinstance(k,str) or not isinstance(v,str): raise ValueError("Views names must be strings; view defs may be unicode") @@ -774,10 +774,10 @@ def validate_param(self, value, pd): if pd.defaultunits != None: defaultunits=pd.defaultunits - if units in valid_properties[pd.property][1].keys(): + if units in list(valid_properties[pd.property][1].keys()): pass - elif units in valid_properties[pd.property][2].keys(): + elif units in list(valid_properties[pd.property][2].keys()): units=valid_properties[pd.property][2][units] elif units == "": @@ -812,9 +812,9 @@ def validate_param(self, value, pd): def validate_params(self): - if self.__params.keys(): - pds=self.__context.db.getparamdefs(self.__params.keys()) - for i,pd in pds.items(): + if list(self.__params.keys()): + pds=self.__context.db.getparamdefs(list(self.__params.keys())) + for i,pd in list(pds.items()): self.validate_param(self[i],pd) @@ -823,7 +823,7 @@ def changedparams(self): print("===== changed params =====") cp = set() - for k in self.keys(): + for k in list(self.keys()): if k not in (self.param_special-set(["comments"])) and self[k] != self.__oparams.get(k,None): if k == "comments": @@ -889,7 +889,7 @@ def __setstate__(self,dict): def __unicode__(self): "A string representation of the record" ret=["%s (%s)\n"%(str(self.recid),self.rectype)] - for i,j in self.items(): + for i,j in list(self.items()): ret.append(u"%12s: %s\n"%(str(i),unicode(j))) return u"".join(ret) @@ -973,7 +973,7 @@ def keys(self): return tuple(self.__params.keys())+tuple(self.param_special) def has_key(self,key): - if str(key).strip().lower() in self.keys(): return True + if str(key).strip().lower() in list(self.keys()): return True return False def get(self, key, default=None): @@ -998,13 +998,13 @@ def addcomment(self, value): self.__comments.append((self.__context.user,time.strftime("%Y/%m/%d %H:%M:%S"),value)) # store the comment string itself # now update the values of any embedded params - for i,j in d.items(): + for i,j in list(d.items()): self.__setitem__(i,j) def getparamkeys(self): """Returns parameter keys without special values like owner, creator, etc.""" - return self.__params.keys() + return list(self.__params.keys()) # ian: hard coded groups here need to be in sync with the various check*ctx methods. @@ -1055,7 +1055,7 @@ def fromdict(self,d): if "comments" in d: self.__comments=d["comments"] del d["comments"] - for k,v in d.items(): + for k,v in list(d.items()): #print "setting %s = %s"%(k,v) self[k]=v # generally there will be no context set at this point; validation is short form diff --git a/libpyEM/qtgui/emform.py b/libpyEM/qtgui/emform.py index c9df76ea63..4b8223c446 100644 --- a/libpyEM/qtgui/emform.py +++ b/libpyEM/qtgui/emform.py @@ -303,7 +303,7 @@ def time_out(self): stime=time.time() self.busy = 1 - for key,value in self.animated_columns.items(): + for key,value in list(self.animated_columns.items()): if value == -1: for i in xrange(0,self.columnCount()): if (str(self.horizontalHeaderItem(i).text())) == key: @@ -317,7 +317,7 @@ def time_out(self): return - for key,value in self.animated_columns.items(): + for key,value in list(self.animated_columns.items()): cd = self.column_data[value-1] for i in xrange(0,len(self.listed_names)): @@ -337,7 +337,7 @@ def convert_text(self,name): Sometimes the first column displays a shortened version of the name of a file on disk, but it occurs that you want to recall the full name. This function does that ''' - for key,value in self.name_conversions.items(): + for key,value in list(self.name_conversions.items()): if value == name: return key return None @@ -367,7 +367,7 @@ def add_context_menu_data(self,context_menu_data): for these "action-functions" ''' self.context_menu_refs.append(context_menu_data) - for key,value in context_menu_data.items(): + for key,value in list(context_menu_data.items()): self.add_context_menu_action(key,value) def add_column_data(self,column_data): @@ -379,7 +379,7 @@ def add_column_data(self,column_data): self.column_data.append(column_data) else: self.column_data_refs.append(column_data) - for key,value in column_data.column_data.items(): + for key,value in list(column_data.column_data.items()): self.column_data.append(EMFileTable.EMColumnData(key,value,"")) def remove_column_data(self,column_data_name): ''' @@ -551,7 +551,7 @@ def contextMenuEvent(self,event): ''' menu = QtGui.QMenu() cmenu = self.context_menu_data - for k in cmenu.keys(): + for k in list(cmenu.keys()): menu.addAction(k) menu.triggered[QAction].connect(self.menu_action_triggered) menu.exec_(event.globalPos()) @@ -952,7 +952,7 @@ def __init__(self,dumped_dict={},name="strategy",desc_short="Strategy",desc_long self.strategy_output = {} self.current_strategy = None - for key in self.dumped_dict.keys(): + for key in list(self.dumped_dict.keys()): self.strategy_widget[key] = None self.current_widget = None @@ -973,7 +973,7 @@ def build_widgets(self): self.main_combo = QtGui.QComboBox() start_idx = None - dumped_dict_keys = self.dumped_dict.keys() + dumped_dict_keys = list(self.dumped_dict.keys()) dumped_dict_keys.sort() for i,key in enumerate(dumped_dict_keys): if key == self.defaultunits: @@ -1067,7 +1067,7 @@ def write_data(self,dict): result = self.current_strategy - for key,val in d.items(): + for key,val in list(d.items()): if isinstance(val,str): if len(val) > 0: result += ":"+key+"="+val @@ -1621,7 +1621,7 @@ def __call__(self,param,layout,target): hbl.setMargin(0) hbl.setSpacing(2) - keys = param.choices.keys() + keys = list(param.choices.keys()) keys.sort() # yes this is somewhat restrictive but it was my only way around something # label = QtGui.QLabel(param.desc_short+":",target) # label.setToolTip(param.desc_long) @@ -1830,7 +1830,7 @@ def write_data(self,dict): # get value1 idx1 = self.combo1.currentIndex() - keys = self.param.choices.keys() + keys = list(self.param.choices.keys()) keys.sort() # because it was sorted above value1 = keys[idx1] # this preserves the type - overkill, well, foolproof, yes a bit more so @@ -1873,7 +1873,7 @@ def table_item_double_clicked(self,item): def contextMenuEvent(self,event): if hasattr(self.table_widget,"context_menu"): menu = QtGui.QMenu() - for k in self.table_widget.context_menu.keys(): + for k in list(self.table_widget.context_menu.keys()): menu.addAction(k) menu.triggered[QAction].connect(self.menu_action_triggered) menu.exec_(event.globalPos()) @@ -1948,7 +1948,7 @@ def __init__(self,dict,combo1,combo2): def combo1_index_changed(self,i): - keys = self.dict.keys() + keys = list(self.dict.keys()) keys.sort() # because the keys are sorted in the display key = keys[i] values = self.dict[key] diff --git a/libpyEM/qtgui/emhist.py b/libpyEM/qtgui/emhist.py index cc247d59dc..068e377e78 100755 --- a/libpyEM/qtgui/emhist.py +++ b/libpyEM/qtgui/emhist.py @@ -440,7 +440,7 @@ def render(self): GL.glPushMatrix() # overcome depth issues glTranslate(0,0,5) - for k,s in self.shapes.items(): + for k,s in list(self.shapes.items()): s.draw(self.scr2plot) GL.glPopMatrix() if render: @@ -464,7 +464,7 @@ def render(self): elif self.alignment == "edge": histalign = "left" - for k in self.axes.keys(): + for k in list(self.axes.keys()): if not self.visibility[k]: continue dcurr = self.data[k][self.axes[k][0]] @@ -479,7 +479,7 @@ def render(self): self.bins[k] = np.cumsum(self.bins[k]) if self.normed: self.bins[k] /= np.sum(self.bins[k]) - self.bins[k] /= len(self.axes.keys()) + self.bins[k] /= len(list(self.axes.keys())) if self.histtype == "bar": if self.stacked and len(usedkeys) > 0: @@ -724,7 +724,7 @@ def getTotals(self,bins=[],keys=[]): def getBinCount(self,n,keys=[]): if len(keys) == 0: - return sum([self.bins[k][n] for k in self.bins.keys()]) + return sum([self.bins[k][n] for k in list(self.bins.keys())]) else: return sum([self.bins[k][n] for k in keys]) @@ -787,7 +787,7 @@ def autoscale(self,force=False,xmin=1.0e38,xmax=-1.0e38,ymin = 0,ymax = -1e38): "This autoscales, but only axes which currently have invalid settings" if force or self.xlimits==None or self.xlimits[1]<=self.xlimits[0] : - for k in self.axes.keys(): + for k in list(self.axes.keys()): if not self.visibility[k]: continue xmin=min(xmin,min(self.data[k][self.axes[k][0]])) xmax=max(xmax,max(self.data[k][self.axes[k][0]])) @@ -802,7 +802,7 @@ def autoscale(self,force=False,xmin=1.0e38,xmax=-1.0e38,ymin = 0,ymax = -1e38): ymax = max(ymax,max(counts)) ymin = min(ymin,min(counts)) else: - for k in self.bins.keys(): + for k in list(self.bins.keys()): #print(self.bins[k]) ymax = max(ymax,max(self.bins[k])) ymin = min(ymin,min(self.bins[k])) @@ -1118,13 +1118,13 @@ def selSlide(self,val): self.datachange() def selAll(self): - for k in self.target().visibility.keys() : self.target().visibility[k]=True + for k in list(self.target().visibility.keys()) : self.target().visibility[k]=True self.target().full_refresh() self.target().updateGL() self.datachange() def selNone(self): - for k in self.target().visibility.keys() : self.target().visibility[k]=False + for k in list(self.target().visibility.keys()) : self.target().visibility[k]=False self.target().full_refresh() self.target().updateGL() self.datachange() @@ -1304,7 +1304,7 @@ def autoScale(self): def datachange(self): self.setlist.clear() flags= Qt.ItemFlags(Qt.ItemIsSelectable)|Qt.ItemFlags(Qt.ItemIsEnabled)|Qt.ItemFlags(Qt.ItemIsUserCheckable)|Qt.ItemFlags(Qt.ItemIsDragEnabled) - keys=self.target().data.keys() + keys=list(self.target().data.keys()) visible = self.target().visibility keys.sort() parms = self.target().pparm # get the colors from this diff --git a/libpyEM/qtgui/emimage.py b/libpyEM/qtgui/emimage.py index 9a646d7328..9f08cbb479 100644 --- a/libpyEM/qtgui/emimage.py +++ b/libpyEM/qtgui/emimage.py @@ -46,7 +46,7 @@ def image_update(): from .emimage2d import EMImage2DWidget from .emimagemx import EMImageMXWidget from .emimage3d import EMImage3DWidget - for i in EMImage2DWidget.allim.keys(): + for i in list(EMImage2DWidget.allim.keys()): try: if i.isVisible() and i.data["changecount"] !=i.image_change_count: i.force_fft_redo() @@ -54,14 +54,14 @@ def image_update(): i.updateGL() except: pass - for i in EMImageMXWidget.allim.keys(): + for i in list(EMImageMXWidget.allim.keys()): try: if i.isVisible() and i.data[0]["changecount"]!=i.image_change_count: i.force_display_update() i.updateGL() except: pass - for i in EMImage3DWidget.allim.keys(): + for i in list(EMImage3DWidget.allim.keys()): try: if i.isVisible() and i.data["changecount"]!=i.image_change_count: i.updateGL() diff --git a/libpyEM/qtgui/emimage2d.py b/libpyEM/qtgui/emimage2d.py index 19f4f6e1c8..893b80f700 100644 --- a/libpyEM/qtgui/emimage2d.py +++ b/libpyEM/qtgui/emimage2d.py @@ -1293,7 +1293,7 @@ def setup_shapes(self): alpha = 1.0 if len(self.shapes) > 0: - for k in self.shapes.keys(): + for k in list(self.shapes.keys()): shape = self.shapes[k] if not isinstance(shape,EMShape) : continue glLineWidth(2) @@ -1312,7 +1312,7 @@ def setup_shapes(self): GL.glBlendFunc(GL.GL_SRC_ALPHA,GL.GL_ONE_MINUS_SRC_ALPHA); glPointSize(2) - for k,s in self.shapes.items(): + for k,s in list(self.shapes.items()): ### handle boxes for 3D images if s.shape[0] == "ellipse": mxlen=11 @@ -1397,7 +1397,7 @@ def setup_shapes(self): # We do the scr* shapes last since they mess up the matrix - for k,s in self.shapes.items(): + for k,s in list(self.shapes.items()): try: if s.shape[0][:3]=="scr": # print "shape",s.shape @@ -1475,7 +1475,7 @@ def animation_done_event(self,animation): self.set_line_animation(*animation.get_end()) def set_animation_increment(self,increment): - for shape in self.shapes.items(): + for shape in list(self.shapes.items()): shape[1].set_blend(increment) self.shapechange = True @@ -1486,7 +1486,7 @@ def set_line_animation(self,x,y): def update_blend(self): ret = False - for shape in self.shapes.items(): + for shape in list(self.shapes.items()): s = shape[1] if s.isanimated: v = s.incblend() diff --git a/libpyEM/qtgui/emimage3dsym.py b/libpyEM/qtgui/emimage3dsym.py index 95ce8a8da8..dfcbe0dc51 100644 --- a/libpyEM/qtgui/emimage3dsym.py +++ b/libpyEM/qtgui/emimage3dsym.py @@ -205,7 +205,7 @@ def set_data(self,data): # get the first header and get any items that can be cast to a float header = self.data[0].get_attr_dict() self.score_options = [] - for key,value in header.items(): + for key,value in list(header.items()): try: # make sure we can cast the value to a float, that way in can become the height of the cylinder float(value) @@ -1813,7 +1813,7 @@ def get_display_tab(self): # self.glbrightness.setValue(0.0) # self.display_tab.vbl.addWidget(self.glbrightness) - keys = self.target().colors.keys() + keys = list(self.target().colors.keys()) keys.sort() self.arc_color = self.__get_combo(keys,self.target().arc_color) hbl1 = QtGui.QHBoxLayout() diff --git a/libpyEM/qtgui/emimagemx.py b/libpyEM/qtgui/emimagemx.py index 7ad00108cd..7fb0b46604 100644 --- a/libpyEM/qtgui/emimagemx.py +++ b/libpyEM/qtgui/emimagemx.py @@ -1546,7 +1546,7 @@ def scr_to_img(self,vec): if self.max_idx == 0: return # there is no data absloc=((vec[0]),(self.height()-(vec[1]))) - for item in self.coords.items(): + for item in list(self.coords.items()): index = item[0]+self.img_num_offset if index != 0: index %= self.max_idx data = item[1] @@ -2930,7 +2930,7 @@ def get_image_header_keys(self): Gets the keys in the header of the first image ''' if self.header_keys == None: - self.header_keys = self.get_image_header(self.cache_start).keys() + self.header_keys = list(self.get_image_header(self.cache_start).keys()) return self.header_keys def refocus_cache(self,new_focus): @@ -3138,14 +3138,14 @@ def get_image_header_keys(self): for i in self.images: try: if self.images[i] != None: - self.keys = self.images[i].get_attr_dict().keys() + self.keys = list(self.images[i].get_attr_dict().keys()) break except: pass elif self.mode == EMDataListCache.LIST_MODE: for i in self.images: try: - self.keys = i.get_attr_dict().keys() + self.keys = list(i.get_attr_dict().keys()) break except: pass @@ -3335,7 +3335,7 @@ def get_image_header(self,idx): def get_image_header_keys(self): if self.keys == None: - self.keys = self[0].get_attr_dict().keys() + self.keys = list(self[0].get_attr_dict().keys()) return self.keys diff --git a/libpyEM/qtgui/emimageutil.py b/libpyEM/qtgui/emimageutil.py index 305f3ee9c1..3b198408f3 100644 --- a/libpyEM/qtgui/emimageutil.py +++ b/libpyEM/qtgui/emimageutil.py @@ -590,8 +590,8 @@ def __new__(cls,parent,metadata): ''' if not isinstance(metadata,dict): raise - left = [str(k) for k in metadata.keys()] - right = [str(v) for v in metadata.values()] + left = [str(k) for k in list(metadata.keys())] + right = [str(v) for v in list(metadata.values())] from .emform import EMParamTable, ParamDef,EMFormWidget diff --git a/libpyEM/qtgui/emplot2d.py b/libpyEM/qtgui/emplot2d.py index cee778a7a1..d8e4d3d37d 100644 --- a/libpyEM/qtgui/emplot2d.py +++ b/libpyEM/qtgui/emplot2d.py @@ -507,7 +507,7 @@ def render(self): GL.glPushMatrix() # overcome depth issues glTranslate(0,0,5) - for k,s in self.shapes.items(): + for k,s in list(self.shapes.items()): # print k,s s.draw(self.scr2plot) @@ -523,7 +523,7 @@ def render(self): ax.tick_params(axis='y', labelsize="x-large") canvas=FigureCanvasAgg(fig) - for i in self.axes.keys(): + for i in list(self.axes.keys()): if not self.visibility[i]: continue j=self.axes[i] # print j @@ -736,7 +736,7 @@ def update_selected(self,evc,lc): j=0 # we find the first displayed axis in the list - for ak in self.axes.keys(): + for ak in list(self.axes.keys()): if not self.visibility[ak]: continue j=self.axes[ak] break @@ -885,7 +885,7 @@ def autoscale(self,force=False): if force or self.xlimits==None or self.xlimits[1]<=self.xlimits[0] : xmin=1.0e38 xmax=-1.0e38 - for k in self.axes.keys(): + for k in list(self.axes.keys()): if not self.visibility[k]: continue xmin=min(xmin,min(self.data[k][self.axes[k][0]])) xmax=max(xmax,max(self.data[k][self.axes[k][0]])) @@ -898,7 +898,7 @@ def autoscale(self,force=False): if force or self.ylimits==None or self.ylimits[1]<=self.ylimits[0] : ymin=1.0e38 ymax=-1.0e38 - for k in self.axes.keys(): + for k in list(self.axes.keys()): if not self.visibility[k]: continue ymin=min(ymin,min(self.data[k][self.axes[k][1]])) ymax=max(ymax,max(self.data[k][self.axes[k][1]])) @@ -911,7 +911,7 @@ def autoscale(self,force=False): if force or self.climits==None or self.climits[1]<=self.climits[0] : cmin=1.0e38 cmax=-1.0e38 - for k in self.axes.keys(): + for k in list(self.axes.keys()): if not self.visibility[k]: continue cmin=min(cmin,min(self.data[k][self.axes[k][2]])) cmax=max(cmax,max(self.data[k][self.axes[k][2]])) @@ -920,7 +920,7 @@ def autoscale(self,force=False): if force or self.slimits==None or self.slimits[1]<=self.slimits[0] : smin=1.0e38 smax=-1.0e38 - for k in self.axes.keys(): + for k in list(self.axes.keys()): if not self.visibility[k]: continue smin=min(smin,min(self.data[k][self.axes[k][3]])) smax=max(smax,max(self.data[k][self.axes[k][3]])) @@ -1310,7 +1310,7 @@ def render(self): GL.glPushMatrix() # overcome depth issues glTranslate(0,0,5) - for k,s in self.shapes.items(): + for k,s in list(self.shapes.items()): # print k,s s.draw(self.scr2plot) @@ -1327,7 +1327,7 @@ def render(self): if not self.xticklabels: ax.set_xticklabels([]) canvas=FigureCanvasAgg(fig) - for i in self.axes.keys(): + for i in list(self.axes.keys()): if not self.visibility[i]: continue j=self.axes[i] theta=self.data[i][self.axes[i][0]] @@ -2583,13 +2583,13 @@ def newAlpha(self,val): self.target().updateGL() def selAll(self): - for k in self.target().visibility.keys() : self.target().visibility[k]=True + for k in list(self.target().visibility.keys()) : self.target().visibility[k]=True self.target().full_refresh() self.target().updateGL() self.datachange() def selNone(self): - for k in self.target().visibility.keys() : self.target().visibility[k]=False + for k in list(self.target().visibility.keys()) : self.target().visibility[k]=False self.target().full_refresh() self.target().updateGL() self.datachange() @@ -2948,7 +2948,7 @@ def datachange(self): flags= Qt.ItemFlags(Qt.ItemIsSelectable)|Qt.ItemFlags(Qt.ItemIsEnabled)|Qt.ItemFlags(Qt.ItemIsUserCheckable)|Qt.ItemFlags(Qt.ItemIsDragEnabled) - keys=self.target().data.keys() + keys=list(self.target().data.keys()) visible = self.target().visibility keys.sort() parms = self.target().pparm # get the colors from this diff --git a/libpyEM/qtgui/emplot3d.py b/libpyEM/qtgui/emplot3d.py index b7000ed71b..3b0eaff608 100644 --- a/libpyEM/qtgui/emplot3d.py +++ b/libpyEM/qtgui/emplot3d.py @@ -546,7 +546,7 @@ def render(self): ax.tick_params(axis='z', labelsize="x-large") canvas=FigureCanvasAgg(fig) - for i in self.axes.keys(): + for i in list(self.axes.keys()): if not self.visibility[i]: continue j=self.axes[i] # print j @@ -763,7 +763,7 @@ def update_selected(self,evc,lc): j=0 # we find the first displayed axis in the list - for ak in self.axes.keys(): + for ak in list(self.axes.keys()): if not self.visibility[ak]: continue j=self.axes[ak] break @@ -940,7 +940,7 @@ def autoscale(self,force=False): if force or self.xlimits==None or self.xlimits[1]<=self.xlimits[0] : xmin=1.0e38 xmax=-1.0e38 - for k in self.axes.keys(): + for k in list(self.axes.keys()): if not self.visibility[k]: continue if self.axes[k][0]>=0: xmin=min(xmin,min(self.data[k][self.axes[k][0]])) @@ -957,7 +957,7 @@ def autoscale(self,force=False): if force or self.ylimits==None or self.ylimits[1]<=self.ylimits[0] : ymin=1.0e38 ymax=-1.0e38 - for k in self.axes.keys(): + for k in list(self.axes.keys()): if not self.visibility[k]: continue ymin=min(ymin,min(self.data[k][self.axes[k][1]])) ymax=max(ymax,max(self.data[k][self.axes[k][1]])) @@ -970,7 +970,7 @@ def autoscale(self,force=False): if force or self.zlimits==None or self.zlimits[1]<=self.zlimits[0] : zmin=1.0e38 zmax=-1.0e38 - for k in self.axes.keys(): + for k in list(self.axes.keys()): if not self.visibility[k]: continue zmin=min(zmin,min(self.data[k][self.axes[k][2]])) zmax=max(zmax,max(self.data[k][self.axes[k][2]])) @@ -983,7 +983,7 @@ def autoscale(self,force=False): if force or self.climits==None or self.climits[1]<=self.climits[0] : cmin=1.0e38 cmax=-1.0e38 - for k in self.axes.keys(): + for k in list(self.axes.keys()): if not self.visibility[k]: continue cmin=min(cmin,min(self.data[k][self.axes[k][3]])) cmax=max(cmax,max(self.data[k][self.axes[k][3]])) @@ -992,7 +992,7 @@ def autoscale(self,force=False): if force or self.slimits==None or self.slimits[1]<=self.slimits[0] : smin=1.0e38 smax=-1.0e38 - for k in self.axes.keys(): + for k in list(self.axes.keys()): if not self.visibility[k]: continue smin=min(smin,min(self.data[k][self.axes[k][4]])) smax=max(smax,max(self.data[k][self.axes[k][4]])) @@ -2133,13 +2133,13 @@ def newAlpha(self,val): self.target().updateGL() def selAll(self): - for k in self.target().visibility.keys() : self.target().visibility[k]=True + for k in list(self.target().visibility.keys()) : self.target().visibility[k]=True self.target().full_refresh() self.target().updateGL() self.datachange() def selNone(self): - for k in self.target().visibility.keys() : self.target().visibility[k]=False + for k in list(self.target().visibility.keys()) : self.target().visibility[k]=False self.target().full_refresh() self.target().updateGL() self.datachange() @@ -2510,7 +2510,7 @@ def datachange(self): flags= Qt.ItemFlags(Qt.ItemIsSelectable)|Qt.ItemFlags(Qt.ItemIsEnabled)|Qt.ItemFlags(Qt.ItemIsUserCheckable)|Qt.ItemFlags(Qt.ItemIsDragEnabled) - keys=self.target().data.keys() + keys=list(self.target().data.keys()) visible = self.target().visibility keys.sort() parms = self.target().pparm # get the colors from this diff --git a/libpyEM/qtgui/emrctboxergui.py b/libpyEM/qtgui/emrctboxergui.py index 97ef495f23..7d64fcdf04 100644 --- a/libpyEM/qtgui/emrctboxergui.py +++ b/libpyEM/qtgui/emrctboxergui.py @@ -147,7 +147,7 @@ def get_processor_tab(self): hbl.addWidget(flabel) self.processor_combobox = QtGui.QComboBox() proc_data = dump_processors_list() - for key in proc_data.keys(): + for key in list(proc_data.keys()): if len(key) >= 5 and key[:7] == "filter.": #print key self.processor_combobox.addItem(key) diff --git a/libpyEM/qtgui/emselector.py b/libpyEM/qtgui/emselector.py index 25b1d8d608..6bb5c8c067 100644 --- a/libpyEM/qtgui/emselector.py +++ b/libpyEM/qtgui/emselector.py @@ -745,7 +745,7 @@ def __del__(self): pass def closeEvent(self,event): - for delegate in self.action_delegates.values(): + for delegate in list(self.action_delegates.values()): delegate.closeEvent(event) EMBrowserType.closeEvent(self, event) @@ -1343,7 +1343,7 @@ def __get_file_metadata_items(self,url): return_items = [EM2DMetaImageItem(self,str(i),url,i) for i in xrange(0,EMUtil.get_image_count(url))] else: d = e.get_attr_dict() - keys = d.keys() + keys = list(d.keys()) keys.sort() #alphabetical order return_items = [EMDataHeaderItem(self,str(k)+" : "+str(d[k]),url,k,d[k]) for k in keys] @@ -1367,7 +1367,7 @@ def __get_metadata_items(self,url): d = e.get_attr_dict() if len(vals) == val_idx: - keys = d.keys() + keys = list(d.keys()) keys.sort() #alphabetical order return_items = [EMDataHeaderItem(self,str(k)+" : "+str(d[k]),url,k,d[k]) for k in keys] elif len(vals) == val_idx+1: @@ -1917,7 +1917,7 @@ def __get_bdb_image_items(self,url): if d["nz"] > 1: return_items = [EM3DMetaImageItem(self,str(i),url,i) for i in xrange(0,n)] else: return_items = [EM2DMetaImageItem(self,str(i),url,i) for i in xrange(0,n)] else: - keys = d.keys() + keys = list(d.keys()) keys.sort() #alphabetical order return_items = [EMDataHeaderItem(self,str(k)+" : "+str(d[k]),url,k,d[k]) for k in keys] else: @@ -1929,7 +1929,7 @@ def __get_bdb_image_items(self,url): d = db.get_header(0) if len(vals) == val_idx: - keys = d.keys() + keys = list(d.keys()) keys.sort() #alphabetical order return_items = [EMDataHeaderItem(self,str(k)+" : "+str(d[k]),url,k,d[k]) for k in keys] elif len(vals) == val_idx+1: @@ -1956,7 +1956,7 @@ def __get_bdb_type_items(self,url): for db_key in vals[2:]:db = db[db_key] try: - for k,val in db.items(): + for k,val in list(db.items()): if isinstance(val,dict): return_items.append(EMBDBDictItem(self,str(k),url,str(k))) else: diff --git a/libpyEM/qtgui/emsprworkflow.py b/libpyEM/qtgui/emsprworkflow.py index e3f7b125e5..c18c8bd11f 100644 --- a/libpyEM/qtgui/emsprworkflow.py +++ b/libpyEM/qtgui/emsprworkflow.py @@ -135,7 +135,7 @@ def on_display_file(self,filename): self.display_file.emit(filename) def on_form_ok(self,params): - for k,v in params.items(): + for k,v in list(params.items()): self.write_db_entry(k,v) self.disconnect_form() @@ -183,7 +183,7 @@ def write_db_entries(self,dictionary): else: db = None project_db = db_open_dict("bdb:project") - for k,v in dictionary.items(): + for k,v in list(dictionary.items()): if k == "blurb": continue if k in self.project_db_entries: project_db[k] = v @@ -423,19 +423,19 @@ def check_sym(self,params,options): return error_message def get_cmps_list(self): - return dump_cmps_list().keys() + return list(dump_cmps_list().keys()) def get_aligners_list(self): - return dump_aligners_list().keys() + return list(dump_aligners_list().keys()) def get_projectors_list(self): - return dump_projectors_list().keys() + return list(dump_projectors_list().keys()) def get_orientgens_list(self): - return dump_orientgens_list().keys() + return list(dump_orientgens_list().keys()) def get_averagers_list(self): - return dump_averagers_list().keys() + return list(dump_averagers_list().keys()) # cmps.append("None") I think this is necessary @@ -546,7 +546,7 @@ def keys(self): @return the keys of the data dictionary ''' dict = self.get_data_dict() - return dict.keys() + return list(dict.keys()) def get_names(self,filt=original_data): ''' @@ -555,8 +555,8 @@ def get_names(self,filt=original_data): ''' dict = self.get_data_dict() ret = [] - for tag,dict2 in dict.items(): - for key,name in dict2.items(): + for tag,dict2 in list(dict.items()): + for key,name in list(dict2.items()): if key == filt: ret.append(name) return ret @@ -690,8 +690,8 @@ def __remove_dict_if_files_lost(self): project_db = db_open_dict(self.db_name) dict = project_db.get(self.data_dict_name,dfl={}) rem = [] - for name, map in dict.items(): - for key,image_name in map.items(): + for name, map in list(dict.items()): + for key,image_name in list(map.items()): try: if not file_exists(image_name) and not os.path.isdir(image_name[:image_name.rindex("/")]): map.pop(key) @@ -733,7 +733,7 @@ def __recover_missing_key_dict(self): project_db = db_open_dict(self.db_name) dict = project_db.get(self.data_dict_name,dfl={}) update = False - for tag,dict2 in dict.items(): + for tag,dict2 in list(dict.items()): if EMProjectDataDict.original_data not in dict2: if file_exists(tag): dict2[EMProjectDataDict.original_data] = tag @@ -827,7 +827,7 @@ def get_raw_data_table(self): data_dict = EMProjectDataDict(self.project_list) self.project_data_at_init = data_dict.get_data_dict() # so if the user hits cancel this can be reset print(self.project_data_at_init) - project_names = data_dict.keys() + project_names = list(data_dict.keys()) from .emform import EM2DFileTable,EMFileTable table = EM2DFileTable(project_names,desc_short="Raw Data Files",desc_long="") @@ -866,7 +866,7 @@ def __init__(self,project_list=spr_raw_data_dict,remove_only=False,using_file_ta if not remove_only: self.context_menu["Add"] = EMRawDataReportTask.ProjectListContextMenu.AddFilesToProjectViaContext(self.project_list) def items(self): - return self.context_menu.items() + return list(self.context_menu.items()) class RemoveFilesFromProject: @@ -881,7 +881,7 @@ def __call__(self,names,table_widget): text_entries = [table_widget.convert_text(str(i.text())) for i in entries] data_dict = EMProjectDataDict(self.project_list) - project_names = data_dict.keys() + project_names = list(data_dict.keys()) full_names = [table_widget.convert_text(name) for name in names] db_full_names = [table_widget.convert_text(name) for name in names] @@ -914,7 +914,7 @@ def __init__(self,project_list): def __call__(self,list_of_names,table_widget): data_dict = EMProjectDataDict(self.project_list) - project_names = data_dict.keys() + project_names = list(data_dict.keys()) for name in list_of_names: if not file_exists(name) and not os.path.isdir(name[:name.rfind("/")]): @@ -1018,7 +1018,7 @@ def validate_file_name(self,list_of_names): else: raise RuntimeError("Files needs to be a list") data_dict = EMProjectDataDict(self.project_list) - project_names = data_dict.keys() + project_names = list(data_dict.keys()) for name in list_of_names: if not file_exists(name) and not os.path.isdir(name[:name.rfind("/")]): #See if its a dir, which is ok: @@ -1193,7 +1193,7 @@ def check_params(self,params): error_message.append("File %s is not a valid EM image." %name) data_dict = EMProjectDataDict(spr_raw_data_dict) - project_names = data_dict.keys() + project_names = list(data_dict.keys()) if params["project_associate"]: for name in self.output_names: # this will change one day - the imported name will be altered @@ -1359,7 +1359,7 @@ def __init__(self,validator=None): self.context_menu["Add"] = ParticleWorkFlowTask.AddDataToTable(validator) def items(self): - return self.context_menu.items() + return list(self.context_menu.items()) class RemoveDataFromTable: @@ -1673,8 +1673,8 @@ def on_form_ok(self,params): return else: data_dict = EMProjectDataDict(spr_ptcls_dict) - print(params["name_map"].values()) - data_dict.add_names(params["name_map"].values(),use_file_tag=True) + print(list(params["name_map"].values())) + data_dict.add_names(list(params["name_map"].values()),use_file_tag=True) self.task_idle.emit() self.form.close() @@ -1690,7 +1690,7 @@ def import_data(self,params): get_application().processEvents() - for infile,output in params["name_map"].items(): + for infile,output in list(params["name_map"].items()): #if len(input) > 3 and infile[:4] == "bdb:": #i += 1 #progress.setValue(i) @@ -1734,7 +1734,7 @@ def __init__(self,project_list): self.context_menu["Add"] = EMParticleImportTask.ContextMenu.AddFilesViaContext(self.project_list) def items(self): - return self.context_menu.items() + return list(self.context_menu.items()) class RemoveFiles: @@ -1851,7 +1851,7 @@ def on_form_ok(self,params): # from e2boxer import merge_boxes_as_manual_to_db # merge_boxes_as_manual_to_db(params["coordfiles"]) pdb=db_open_dict("bdb:.#project") - img_list=pdb.get("global.spr_raw_data_dict",dfl={}).keys() + img_list=list(pdb.get("global.spr_raw_data_dict",dfl={}).keys()) if len(img_list)==0 : print("No image files in project !!!") return @@ -2051,7 +2051,7 @@ def __get_e2boxer_data(self,project_names): box_maps = {} if db_check_dict(db_name): e2boxer_db = db_open_dict(db_name,ro=True) - for name in e2boxer_db.keys(): + for name in list(e2boxer_db.keys()): d = e2boxer_db[name] if not isinstance(d,dict): continue if "e2boxer_image_name" not in d: # this is the test, if something else has this key then we're screwed. @@ -2158,7 +2158,7 @@ def get_params(self): data_dict = EMProjectDataDict(project_list) self.project_data_at_init = data_dict.get_data_dict() # so if the user hits cancel this can be reset - project_names = data_dict.keys() + project_names = list(data_dict.keys()) culled_names = [] for name in project_names: @@ -2250,7 +2250,7 @@ def on_form_ok(self,params): else: self.write_db_entries(params) # will only write filenames options = EmptyObject() - for k,v in params.items(): + for k,v in list(params.items()): setattr(options,k,v) options.autoboxer = params["autoboxer"][0] @@ -2355,7 +2355,7 @@ def recover_old_boxer_database(): if db_check_dict(old_boxer_database): recovery_items = [] db = db_open_dict(old_boxer_database) - for key,value in db.items(): + for key,value in list(db.items()): if isinstance(key,str) and len(key) > 2 and key[-3:] == "_DD": if isinstance(value,dict): if "reference_boxes" in value or "auto_boxes" in value or "manual_boxes" in value: @@ -2444,7 +2444,7 @@ def on_form_ok(self,params): else: self.write_db_entries(params) options = EmptyObject() - for key in params.keys(): + for key in list(params.keys()): setattr(options,key,params[key]) options.boxsize = params["interface_boxsize"] options.running_mode = "gui" @@ -2565,7 +2565,7 @@ def on_form_ok(self,params): else: self.write_db_entries(params) options = EmptyObject() - for k,v in params.items(): + for k,v in list(params.items()): setattr(options,k,v) options.boxsize = params["output_boxsize"] @@ -2609,11 +2609,11 @@ def get_e2boxer_boxes_table(self,project_check=True): if project_check: project_db = db_open_dict("bdb:project") project_data = project_db.get(spr_raw_data_dict,dfl={}) - project_names = project_data.keys() + project_names = list(project_data.keys()) if db_check_dict(db_name): e2boxer_db = db_open_dict(db_name,ro=True) - for name in e2boxer_db.keys(): + for name in list(e2boxer_db.keys()): d = e2boxer_db[name] if not isinstance(d,dict): continue if "e2boxer_image_name" not in d: # this is the test, if something else has this key then we're screwed. @@ -2819,7 +2819,7 @@ def get_names_with_ctf_params(self): parms_db = db_open_dict("bdb:e2ctf.parms",ro=True) ret = [] - for key,data in parms_db.items(): + for key,data in list(parms_db.items()): if data == None: print("error?",key) continue @@ -3307,7 +3307,7 @@ def get_ctf_options(self,params): return options def on_form_ok(self,params): - for k,v in params.items(): + for k,v in list(params.items()): self.write_db_entry(k,v) options = self.get_ctf_options(params) @@ -3383,7 +3383,7 @@ def get_default_ctf_options(self,params): def on_form_ok(self,params): - for k,v in params.items(): + for k,v in list(params.items()): self.write_db_entry(k,v) options = self.get_default_ctf_options(params) @@ -3481,8 +3481,8 @@ def get_particle_options(self): filter_opts = {} # key is the filter type, value is the number of images with this filter type main_dict = data_dict.get_data_dict() - for name,d in main_dict.items(): - for filt,ptcl_name in d.items(): + for name,d in list(main_dict.items()): + for filt,ptcl_name in list(d.items()): if self.bdb_only != False and ( len(ptcl_name) > 3 and ptcl_name[:4] != "bdb:"): continue name_map[ptcl_name] = name @@ -3496,7 +3496,7 @@ def get_particle_options(self): stacks_map[filt] = [ptcl_name] choices = [] - for filt,num in filter_opts.items(): + for filt,num in list(filter_opts.items()): name = filt+" ("+str(num)+")" choices.append( name ) stacks_name_map[name] = filt @@ -3637,7 +3637,7 @@ def on_form_ok(self,params): choice = params["particle_set_choice"] name_map = {} - for filt_name, particles in self.particles_map.items(): + for filt_name, particles in list(self.particles_map.items()): for name in particles: if name in self.name_map: name_map[name] = base_name(self.name_map[name]) @@ -3712,7 +3712,7 @@ def execute(self,params): for name in params["filenames"]: root_name = self.data_name_map[name] dict = project_data[root_name] - for filt,name in dict.items(): + for filt,name in list(dict.items()): # f = "_"+filt.split()[0].lower() # This produces redundant names sometimes f ="_"+filt.lower().replace(" ","_") # This doesn't @@ -3722,7 +3722,7 @@ def execute(self,params): if f in output_stacks: output_stacks[f].append(name) else: output_stacks[f] = [name] - for f in output_stacks.keys(): + for f in list(output_stacks.keys()): test_stack_name = "bdb:sets#"+base_stack_root+f if file_exists(test_stack_name): EMErrorMessageDisplay.run("The %s stack already exists. Remove it, or try a different name" %test_stack_name) @@ -3734,13 +3734,13 @@ def execute(self,params): progress.show() n=-1 print(output_stacks) - for key,filenames in output_stacks.items(): + for key,filenames in list(output_stacks.items()): n+=1 if len(filenames) == 0: print("Warning, there were no files in the list") continue if len(filenames[0]) > 3 and filenames[0][:4] == "bdb:": - success,cmd = self.make_v_stack(filenames,base_stack_root+key,"sets",params["exclude_bad"],progress,n,len(output_stacks.items())) + success,cmd = self.make_v_stack(filenames,base_stack_root+key,"sets",params["exclude_bad"],progress,n,len(list(output_stacks.items()))) else: EMErrorMessageDisplay.run("The generation of stacks for flat (non database) files is currently disabled. A particle set (%s) is being ignored" %stack_type_map[key], "Warning") @@ -3859,7 +3859,7 @@ def __init__(self): def get_project_particle_table(self): data_dict = EMProjectDataDict(spr_sets_dict) stack_data = data_dict.get_data_dict() - stack_names = stack_data.keys() + stack_names = list(stack_data.keys()) self.stack_data_at_init = stack_data # so if the user hits cancel this can be reset @@ -3879,8 +3879,8 @@ def get_project_particle_table(self): if len(stack_names) != 0: filt_options = [] - for key,value in stack_data.items(): - for filt,name in value.items(): + for key,value in list(stack_data.items()): + for filt,name in list(value.items()): if filt not in filt_options: filt_options.append(filt) @@ -4474,7 +4474,7 @@ def get_reference_free_class_averages_table(self): data_dict = EMProjectDataDict(spr_rfca_dict) data = data_dict.get_data_dict() self.project_data_at_init = data # so if the user hits cancel this can be reset - names = data.keys() + names = list(data.keys()) from .emform import EM2DStackTable,EMFileTable,int_lt table = EM2DStackTable(names,desc_short="Class Averages",desc_long="") context_menu_data = EMRawDataReportTask.ProjectListContextMenu(spr_rfca_dict) @@ -4606,7 +4606,7 @@ def get_initial_models_table(self, makebutton=1): data_dict = EMProjectDataDict(spr_init_models_dict) init_model_data = data_dict.get_data_dict() self.project_data_at_init = init_model_data # so if the user hits cancel this can be reset - init_model_names = init_model_data.keys() + init_model_names = list(init_model_data.keys()) from .emform import EM3DFileTable,EMFileTable,float_lt table = EM3DFileTable(init_model_names,name="model",desc_short="Initial Models",desc_long="") @@ -4979,7 +4979,7 @@ def get_postprocess_filt_options(self): if E2Make3DTools.preprocessor_cache == None: a = dump_processors_list() l = ["None"] - for key in a.keys(): + for key in list(a.keys()): if len(key) > 5 and key[:6] == "filter": vals = key.split(".") if len(vals) > 1: @@ -5804,7 +5804,7 @@ def get_ref_table(self): data_dict = EMProjectDataDict(spr_freealign_dirs_dict) init_model_data = data_dict.get_data_dict() self.project_data_at_init = init_model_data # so if the user hits cancel this can be reset - init_model_names = init_model_data.keys() + init_model_names = list(init_model_data.keys()) from .emform import EM3DFileTable,EMFileTable,float_lt table = EM3DFileTable(init_model_names,name="dirs",desc_short="FreAlign Dirs",desc_long="") @@ -5856,7 +5856,7 @@ def get_ref_table(self): data_dict = EMProjectDataDict(spr_freealign_dirs_dict) init_model_data = data_dict.get_data_dict() self.project_data_at_init = init_model_data # so if the user hits cancel this can be reset - init_model_names = init_model_data.keys() + init_model_names = list(init_model_data.keys()) from .emform import EM3DFileTable,EMFileTable,float_lt table = EM3DFileTable(init_model_names,name="dirs",desc_short="FreAlign Dirs",desc_long="") @@ -5922,7 +5922,7 @@ def get_ref_table(self): data_dict = EMProjectDataDict(spr_freealign_models_dict) init_model_data = data_dict.get_data_dict() self.project_data_at_init = init_model_data # so if the user hits cancel this can be reset - init_model_names = init_model_data.keys() + init_model_names = list(init_model_data.keys()) from .emform import EM3DFileTable,EMFileTable,float_lt table = EM3DFileTable(init_model_names,name="model",desc_short="Starting Models",desc_long="") @@ -6066,7 +6066,7 @@ def on_form_ok(self,params): data_dict = EMProjectDataDict(self.filt_name) db_map = data_dict.get_data_dict() - ptcl_keys = db_map.keys() + ptcl_keys = list(db_map.keys()) if usefilt_choice != "None": usefilt_name = self.particles_name_map[usefilt_choice] @@ -6228,7 +6228,7 @@ def get_resolution_table(self): db_name = "bdb:"+dir+"#convergence.results" if db_check_dict(db_name): db = db_open_dict(db_name,ro=True) - keys = db.keys() + keys = list(db.keys()) if len(keys) > 0: available_dirs.append(dir) diff --git a/libpyEM/qtgui/emtprworkflow.py b/libpyEM/qtgui/emtprworkflow.py index e483fb4032..35892edaae 100644 --- a/libpyEM/qtgui/emtprworkflow.py +++ b/libpyEM/qtgui/emtprworkflow.py @@ -141,7 +141,7 @@ def get_postprocess_filt_options(self): if E2TomoFilterParticlesTask.preprocessor_cache == None: a = dump_processors_list() l = ["None"] - for key in a.keys(): + for key in list(a.keys()): if len(key) > 5 and key[:6] == "filter": vals = key.split(".") if len(vals) > 1: @@ -233,8 +233,8 @@ def get_previous_filtered_set_names(self): # db_map = project_db.get(name) previous_sets = [] - for root_name,dict in db_map.items(): - for filt,name in dict.items(): + for root_name,dict in list(db_map.items()): + for filt,name in list(dict.items()): if previous_sets.count(filt) == 0: previous_sets.append(filt) @@ -359,7 +359,7 @@ def get_raw_data_table(self): ''' data_dict = EMProjectDataDict(self.project_list) project_data = data_dict.get_data_dict() - project_names = project_data.keys() + project_names = list(project_data.keys()) self.project_data_at_init = project_data # so if the user hits cancel this can be reset from .emform import EMTomographicFileTable,EMFileTable @@ -383,7 +383,7 @@ def get_raw_data_table(self): ''' data_dict = EMProjectDataDict(self.project_list) project_data = data_dict.get_data_dict() - project_names = project_data.keys() + project_names = list(project_data.keys()) self.project_data_at_init = project_data # so if the user hits cancel this can be reset from .emform import EMTomographicFileTable,EMFileTable @@ -451,7 +451,7 @@ def get_params(self): proc_data = dump_processors_list() masks = {} - for key in proc_data.keys(): + for key in list(proc_data.keys()): if len(key) >= 5 and key[:5] == "mask.": masks[key] = proc_data[key] masks["None"] = ["Choose this to stop masking from occuring"] @@ -460,7 +460,7 @@ def get_params(self): params.append([pmask, pmaskparams]) filters = {} - for key in proc_data.keys(): + for key in list(proc_data.keys()): if len(key) >= 7 and key[:7] == "filter.": filters[key] = proc_data[key] filters["None"] = ["Choose this to stop filtering from occuring"] @@ -470,7 +470,7 @@ def get_params(self): ali_data = dump_aligners_list() caligners = {} - for key in ali_data.keys(): + for key in list(ali_data.keys()): if len(key) >= 19 and key[:19] == "rotate_translate_3d": caligners[key] = ali_data[key] pali = ParamDef("aligner3D",vartype="string",desc_short="Aligner3D",desc_long="The 3D course aligner",property=None,defaultunits=db.get("aligner3D",dfl="rotate_translate_3d"),choices=caligners) @@ -478,7 +478,7 @@ def get_params(self): params.append([pali, paliparams]) craligners = {} - for key in ali_data.keys(): + for key in list(ali_data.keys()): if len(key) >= 9 and key[:9] == "refine_3d": craligners[key] = ali_data[key] prali = ParamDef("raligner3D",vartype="string",desc_short="RAligner3D",desc_long="The 3D refine aligner",property=None,defaultunits=db.get("raligner3D",dfl="refine_3d_grid"),choices=craligners) @@ -585,7 +585,7 @@ def get_raw_data_table(self): ''' data_dict = EMProjectDataDict(self.project_list) project_data = data_dict.get_data_dict() - project_names = project_data.keys() + project_names = list(project_data.keys()) self.project_data_at_init = project_data # so if the user hits cancel this can be reset from .emform import EMTomographicFileTable,EMFileTable diff --git a/programs/e2RCTboxer.py b/programs/e2RCTboxer.py index c7a5ce5d2c..1d649ea3b9 100755 --- a/programs/e2RCTboxer.py +++ b/programs/e2RCTboxer.py @@ -540,7 +540,7 @@ def close_db(self): def load_boxes_from_db(self): #data = self.db[self.entry] - if not "boxes_rct" in self.db.keys(): + if not "boxes_rct" in list(self.db.keys()): pass#data = self.db[os.path.basename(self.entry)] # Backward compability else: for box in self.db["boxes_rct"]: diff --git a/programs/e2a2d_average.py b/programs/e2a2d_average.py index 0b0e53bc29..6755525ef1 100644 --- a/programs/e2a2d_average.py +++ b/programs/e2a2d_average.py @@ -66,7 +66,7 @@ def main(): try: os.unlink("{}/avg_bandali_{:02d}.hdf".format(options.path,options.iter)) except: pass - sortangs=[(v["score"],v["xform.align2d"],eval(k)) for k,v in angs.items()] # the eval() here is poor programming practice, but is the easiest way :^( + sortangs=[(v["score"],v["xform.align2d"],eval(k)) for k,v in list(angs.items())] # the eval() here is poor programming practice, but is the easiest way :^( N=len(sortangs) # make a quick alignment reference diff --git a/programs/e2a2d_stat.py b/programs/e2a2d_stat.py index 647440f7df..3927dfe53b 100644 --- a/programs/e2a2d_stat.py +++ b/programs/e2a2d_stat.py @@ -72,7 +72,7 @@ def main(): t0=time.time() t1=t0 - N=len(angs.keys()) + N=len(list(angs.keys())) for n,i in enumerate(angs.keys()): if options.verbose==1 and time.time()-t1>1: t1=time.time() @@ -110,7 +110,7 @@ def main(): t0=time.time() t1=t0 - N=len(angs.keys()) + N=len(list(angs.keys())) out=open("{}/particle_multicmp_{:02d}.txt".format(options.path,options.iter),"w") for n,i in enumerate(angs.keys()): if options.verbose==1 and time.time()-t1>1: @@ -140,14 +140,14 @@ def main(): out.write("\n") if options.mode=="score": - if options.cmp[0]!=None : data=[angs[a]["score.alt"] for a in angs.keys()] - else : data=[angs[a][options.mode] for a in angs.keys()] + if options.cmp[0]!=None : data=[angs[a]["score.alt"] for a in list(angs.keys())] + else : data=[angs[a][options.mode] for a in list(angs.keys())] else: - data=[angs[a]["xform.align2d"].get_params("2d")[options.mode] for a in angs.keys()] + data=[angs[a]["xform.align2d"].get_params("2d")[options.mode] for a in list(angs.keys())] if options.extract: out=open("{}/particle_parms_{:02d}.txt".format(options.path,options.iter),"w") - k=angs.keys() + k=list(angs.keys()) k.sort(key=lambda i:int(eval(i)[1])) for i in k: itm=angs[i] diff --git a/programs/e2bdb.py b/programs/e2bdb.py index 106ec8c39e..d05cf780d9 100755 --- a/programs/e2bdb.py +++ b/programs/e2bdb.py @@ -138,7 +138,7 @@ def main(): continue indb=db_open_dict(path,True) - for k in indb.keys(): + for k in list(indb.keys()): outdb[k]=indb[k] print("Merging complete") @@ -291,7 +291,7 @@ def main(): dct=db_open_dict(path+db,ro=True) #### Dump - keys=dct.keys() + keys=list(dct.keys()) keys.sort() for k in keys: v=dct[k] @@ -315,7 +315,7 @@ def main(): dct=db_open_dict(path+db,ro=True) #### Dump - keys=dct.keys() + keys=list(dct.keys()) keys.sort() if len(options.step)==3 : keys=keys[:options.step[2]] for k in keys[options.step[0]::options.step[1]]: @@ -325,7 +325,7 @@ def main(): for i in v: print("\n\t%s"%str(i), end=' ') print("") elif isinstance(v,dict) : - ks2=v.keys() + ks2=list(v.keys()) ks2.sort() kc=0 for i in ks2: @@ -341,7 +341,7 @@ def main(): for db in dbs: print("##### CTF -> ",db) dct=db_open_dict(path+db,ro=True) - keys=dct.keys() + keys=list(dct.keys()) if len(options.step)==3 : keys=keys[:options.step[2]] defocus=set() for k in keys[options.step[0]::options.step[1]]: @@ -367,7 +367,7 @@ def main(): dct=db_open_dict(path+db,ro=True) #### Dump - keys=dct.keys() + keys=list(dct.keys()) if len(options.step)==3 : keys=keys[:options.step[2]] keys.sort() for k in keys[options.step[0]::options.step[1]]: @@ -377,7 +377,7 @@ def main(): for i in v: print("\n\t%s"%str(i), end=' ') print("") elif isinstance(v,dict) : - ks2=v.keys() + ks2=list(v.keys()) ks2.sort() for i in ks2: print("\n\t%s : %s"%(i,v[i]), end=' ') @@ -428,7 +428,7 @@ def main(): for db in dbs: dct=db_open_dict(path+db,ro=True) dct.realopen() - keys=dct.bdb.keys() + keys=list(dct.bdb.keys()) allkvp={} for k in keys: s1,s2=k.split("\x80",1) # start of a pickled string. @@ -439,7 +439,7 @@ def main(): if v in st : print("Error: value %d seen multiple times in %s (%s,%s)"%(v,db,s1,s2)) st.add(v) print("%s : "%db, end=' ') - for i in allkvp.keys(): + for i in list(allkvp.keys()): if options.verbose>0 : print("%s %d/%d\t"%(i,len(allkvp[i]),int(max(allkvp[i]))+1), end=' ') if len(allkvp[i])!=int(max(allkvp[i])+1) : print("\nMismatch found in %s. Could be normal if file has been rewritten multiple times, but is unusual"%db) if options.verbose>0 : print("") diff --git a/programs/e2boxer_old.py b/programs/e2boxer_old.py index e36bb3c843..80edeea017 100755 --- a/programs/e2boxer_old.py +++ b/programs/e2boxer_old.py @@ -52,9 +52,9 @@ def e2boxer_check(options,args): db = js_open_dict("e2boxercache/swarm.json") if options.autoboxer not in db: s = "There is no autoboxing information present for %s." %options.autoboxer - if len(db.keys()) > 0: + if len(list(db.keys())) > 0: s+= ("Choose from") - for k in db.keys(): + for k in list(db.keys()): try: s+=" "+str(k)+";" except: pass error_message.append(s) @@ -1096,7 +1096,7 @@ def get_proximal_boxes(self,boxes): nearness_sq = self.proximity_threshold**2 # avoid use of sqrt - if isinstance(boxes,dict): keys = boxes.keys() + if isinstance(boxes,dict): keys = list(boxes.keys()) elif isinstance(boxes,list): keys = [i for i in range(len(boxes))] for i,key in enumerate(keys): @@ -2491,7 +2491,7 @@ def calc_ctf(self): #print "calc_ctf image_name: ", image_name if image_name in gbdb: olddict=gbdb[image_name] - gbdb[image_name] = dict((olddict).items() + ctfdict.items() ) # merge the two dictionaries with conflict resolution resolved in favorr of the latest ctf parameters + gbdb[image_name] = dict(list((olddict).items()) + list(ctfdict.items()) ) # merge the two dictionaries with conflict resolution resolved in favorr of the latest ctf parameters else: gbdb[image_name]=ctfdict @@ -2597,7 +2597,7 @@ def calc_ctf_cter(self): #print "calc_ctf image_name: ", image_name if image_name in gbdb: olddict=gbdb[image_name] - gbdb[image_name] = dict((olddict).items() + ctfdict.items() ) # merge the two dictionaries with conflict resolution resolved in favorr of the latest ctf parameters + gbdb[image_name] = dict(list((olddict).items()) + list(ctfdict.items()) ) # merge the two dictionaries with conflict resolution resolved in favorr of the latest ctf parameters else: gbdb[image_name]=ctfdict @@ -2810,7 +2810,7 @@ def auto_box(self, imgname, parameter_update=True, force_remove_auto_boxes=False if imgname in gbdb: oldautoboxdict = gbdb[imgname] - gbdb[imgname] = dict(oldautoboxdict.items() + autoboxdict.items()) # resolve conflicts in favor of new autoboxdict + gbdb[imgname] = dict(list(oldautoboxdict.items()) + list(autoboxdict.items())) # resolve conflicts in favor of new autoboxdict else: gbdb[imgname] = autoboxdict ####################################################### diff --git a/programs/e2classify.py b/programs/e2classify.py index 719a51db71..2f5b3c6906 100755 --- a/programs/e2classify.py +++ b/programs/e2classify.py @@ -127,7 +127,7 @@ def main(): except: bvecs[N]=im # normalize all vector sums - for im in bvecs.values(): + for im in list(bvecs.values()): im.process_inplace("normalize.unitlen") ## Make an output image of vectors diff --git a/programs/e2classifytree.py b/programs/e2classifytree.py index a0a2e51d8e..1250cd887b 100755 --- a/programs/e2classifytree.py +++ b/programs/e2classifytree.py @@ -259,7 +259,7 @@ def buildtree(projs,par,nodes,incomplete,verbose): alipm=[a[x,y] for a in pms] alidict={"type":"2d"} - for i,a in simxorder.items(): + for i,a in list(simxorder.items()): alidict[a]=float(alipm[i]) alidict["mirror"]=int(alidict["mirror"]) #print x,y,alipm,alidict diff --git a/programs/e2classvsproj.py b/programs/e2classvsproj.py index a60203b003..bb0e2f35e8 100755 --- a/programs/e2classvsproj.py +++ b/programs/e2classvsproj.py @@ -152,7 +152,7 @@ def main(): ali.write_image(args[2],i*2) proj.write_image(args[2],i*2+1) if options.savesim: - for prj in pps.keys(): + for prj in list(pps.keys()): xf=projs[prj]["xform.projection"] out.write("{}\t{}\t{}\t{}\t{}\n".format(i,prj,xf.get_rotation("eman")["alt"],xf.get_rotation("eman")["az"],pps[prj])) diff --git a/programs/e2ctffind3util.py b/programs/e2ctffind3util.py index 8dd6e45423..12a37ff866 100755 --- a/programs/e2ctffind3util.py +++ b/programs/e2ctffind3util.py @@ -169,7 +169,7 @@ def import_ctf(voltage, cs, ac, apix, verbose, version): if not os.path.exists(os.getcwd() + "/info"): os.mkdir(os.getcwd() + "/info") jdb = js_open_dict(os.getcwd() + "/info/" + base_name(filename) + "_info.json") - if "ctf" in jdb.keys(): + if "ctf" in list(jdb.keys()): jdb.delete('ctf') ctf = EMAN2Ctf() ctf.from_dict({"defocus":e2defocus,"dfang":e2dfang,"dfdiff":e2dfdiff,"voltage":voltage,"cs":cs,"ampcont":ac,"apix":apix}) diff --git a/programs/e2ddd_movie.py b/programs/e2ddd_movie.py index c4074f383d..ef611a9833 100755 --- a/programs/e2ddd_movie.py +++ b/programs/e2ddd_movie.py @@ -651,7 +651,7 @@ def process_movie(options,fsp,dark,gain,first,flast,step,idx): print() avgr=Averagers.get("minmax",{"max":0}) - avgr.add_image_list(csum2.values()) + avgr.add_image_list(list(csum2.values())) csum=avgr.finish() ##### @@ -668,7 +668,7 @@ def process_movie(options,fsp,dark,gain,first,flast,step,idx): if options.debug and options.verbose == 9: print("PEAK LOCATIONS:") - for l in peak_locs.keys(): + for l in list(peak_locs.keys()): print(peak_locs[l]) # if options.ccweight: diff --git a/programs/e2emx.py b/programs/e2emx.py index 5ea92616a4..bf25da2711 100755 --- a/programs/e2emx.py +++ b/programs/e2emx.py @@ -289,7 +289,7 @@ elif item2.tag == "transformationMatrix": t = Transform([float(item2.find('t11').text),float(item2.find('t12').text),float(item2.find('t13').text),float(item2.find('t14').text),float(item2.find('t21').text),float(item2.find('t22').text),float(item2.find('t23').text),float(item2.find('t24').text),float(item2.find('t31').text),float(item2.find('t32').text),float(item2.find('t33').text),float(item2.find('t34').text)]) - if item.find('micrograph').get('fileName') in transform_dict.keys(): + if item.find('micrograph').get('fileName') in list(transform_dict.keys()): transform_dict[item.find('micrograph').get('fileName')].append(t) else: transform_dict[item.find('micrograph').get('fileName')] = [t] @@ -305,7 +305,7 @@ if particle_micrograph_filename != last_part_filename: micro_dict[particle_micrograph_filename]['first_index'] = int(particle) - 1 last_part_filename = particle_micrograph_filename - if 'last_index' not in micro_dict[particle_micrograph_filename].keys(): + if 'last_index' not in list(micro_dict[particle_micrograph_filename].keys()): micro_dict[particle_micrograph_filename]['last_index'] = int(particle)-1 else: micro_dict[particle_micrograph_filename]['last_index'] = int(particle)-1 @@ -340,18 +340,18 @@ if options.verbose>0 : print("Computing particle SNRs") if not os.path.exists("particles"): os.mkdir("particles") - for item in micro_dict.keys(): + for item in list(micro_dict.keys()): print("e2proc2d.py {} particles/{}_ptcls.hdf --threed2twod --first {} --last {}".format(micro_dict[item]['stack'],base_name(item),micro_dict[item]['first_index'],micro_dict[item]['last_index'])) launch_childprocess("e2proc2d.py {} particles/{}_ptcls.hdf --threed2twod --first {} --last {}".format(micro_dict[item]['stack'],base_name(item),micro_dict[item]['first_index'],micro_dict[item]['last_index'])) launch_childprocess("e2ctf.py particles/{}_ptcls.hdf --voltage {} --cs {} --ac {} --apix {} --autofit --zerook --storeparm --astigmatism {} -v {}".format(base_name(item),micro_dict[item]['voltage'],micro_dict[item]['cs'],micro_dict[item]['ampcont'],micro_dict[item]['apix_x'],dfopt,options.verbose-1)) if twod_xform: - for micrograph_xform in transform_dict.keys(): + for micrograph_xform in list(transform_dict.keys()): temp_images = EMData.read_images("particles/" + base_name(micrograph_xform) + "_ptcls.hdf") for i in range(len(transform_dict[micrograph_xform])): temp_images[i]['xform.projection'] = transform_dict[micrograph_xform][i] temp_images[i].write_image("particles/" + base_name(micrograph_xform) + "_ptcls.hdf",i) elif threed_xform: - for micrograph_xform in transform_dict.keys(): + for micrograph_xform in list(transform_dict.keys()): temp_images = EMData.read_images("particles/" + base_name(micrograph_xform) + "_ptcls.hdf") for i in range(len(transform_dict[micrograph_xform])): temp_images[i]['xform.align3d'] = transform_dict[micrograph_xform][i] diff --git a/programs/e2eulerxplor.py b/programs/e2eulerxplor.py index 0d42a8fd19..efc5154e60 100755 --- a/programs/e2eulerxplor.py +++ b/programs/e2eulerxplor.py @@ -266,7 +266,7 @@ def __init__(self, gl_widget=None, auto=True,sparse_mode=False, file_name = "", # this object will have if self.au_data != None: - combo_entries = self.au_data.keys() + combo_entries = list(self.au_data.keys()) combo_entries.sort() combo_entries.reverse() @@ -722,7 +722,7 @@ def add_au_table(self): self.au_tab.vbl = QtGui.QVBoxLayout(self.au_tab) self.au_data = self.target().au_data - combo_entries = self.au_data.keys() + combo_entries = list(self.au_data.keys()) combo_entries.sort() combo_entries.reverse() self.combo = QtGui.QComboBox(self) diff --git a/programs/e2evalrefine.py b/programs/e2evalrefine.py index 1b472bcb58..b350dddd9f 100755 --- a/programs/e2evalrefine.py +++ b/programs/e2evalrefine.py @@ -466,7 +466,7 @@ def main(): # Create Thread objects jsd=Queue.Queue(0) - thrds=[threading.Thread(target=pqual,args=(i,classptcls[i],jsd,options.includeprojs,options.verbose)) for i in classptcls.keys()] + thrds=[threading.Thread(target=pqual,args=(i,classptcls[i],jsd,options.includeprojs,options.verbose)) for i in list(classptcls.keys())] result={} thrtolaunch=0 diff --git a/programs/e2filtertool.py b/programs/e2filtertool.py index acb8281697..e8c2aa66aa 100755 --- a/programs/e2filtertool.py +++ b/programs/e2filtertool.py @@ -101,7 +101,7 @@ class EMProcessorWidget(QtGui.QWidget): plist=dump_processors_list() # Sorted list of the stuff before the first '.' - cats=set([i.split(".")[0] for i in plist.keys()]) + cats=set([i.split(".")[0] for i in list(plist.keys())]) cats=list(cats) cats.sort() diff --git a/programs/e2helixboxer.py b/programs/e2helixboxer.py index 5c0e0b3994..898c74eb9d 100755 --- a/programs/e2helixboxer.py +++ b/programs/e2helixboxer.py @@ -450,7 +450,7 @@ def save_particle_coords(helix_particle_coords_dict, output_filepath, micrograph out_file.write("#micrograph: " + micrograph_filepath + "\n") out_file.write("#particle length: " + str(ptcl_length) + "\n") out_file.write("#particle width: " + str(ptcl_width) + "\n") - for helix_coords in helix_particle_coords_dict.keys(): + for helix_coords in list(helix_particle_coords_dict.keys()): out_file.write("#helix: " + str(list(helix_coords[0:2])) + "," + str(list(helix_coords[2:4])) + "," + str(helix_coords[4]) + "\n") particle_list = helix_particle_coords_dict[tuple(helix_coords)] for ptcl_center in particle_list: @@ -906,7 +906,7 @@ def save(self): if self.helices_groupbox.isChecked(): if self.helices_coords_groupbox.isChecked(): path = str( self.helices_coords_line_edit.text() ) - save_helix_coords(helices_dict.keys(), path) + save_helix_coords(list(helices_dict.keys()), path) if self.helices_images_groupbox.isChecked(): helix_filepath = str(self.helices_images_line_edit.text()) i = 0 @@ -1203,7 +1203,7 @@ def load_micrograph(self, micrograph_emdata): width = self.box_width if self.helices_dict: - first_coords = self.helices_dict.keys()[0] + first_coords = list(self.helices_dict.keys())[0] width = first_coords[4] self.box_width_spinbox.setValue(width) def main_image_closed(self): @@ -1276,7 +1276,7 @@ def width_changed(self, width): #TODO: this is similar to part of self.mouse_up ==> make both methods call a function with common code shapes = self.main_image.get_shapes() #an EMShapeDict of EMShapes newcoords=[] - for box_key in shapes.keys(): + for box_key in list(shapes.keys()): shape=shapes.get(box_key) shape[9]=width newcoords.append(shape[4:9]) diff --git a/programs/e2help.py b/programs/e2help.py index 2b9f1bad60..6a35464b70 100755 --- a/programs/e2help.py +++ b/programs/e2help.py @@ -143,16 +143,16 @@ def main(): if l: if options.verbose>0: - if len(args)>1 : k=[i for i in l.keys() if args[1] in i] - else: k=l.keys() + if len(args)>1 : k=[i for i in list(l.keys()) if args[1] in i] + else: k=list(l.keys()) k.sort() for i in k: print("%s : %s"%(i, l[i][0])) for j in range(1,len(l[i]),3): print("\t%s(%s) - %s"%(l[i][j],l[i][j+1],l[i][j+2])) else : - if len(args)>1 : k=[i for i in l.keys() if args[1] in i] - else: k=l.keys() + if len(args)>1 : k=[i for i in list(l.keys()) if args[1] in i] + else: k=list(l.keys()) if len(k)==0 : print("Empty list - no items met search criteria") sys.exit(0) diff --git a/programs/e2history.py b/programs/e2history.py index 0bb07d946d..fce4e71d12 100755 --- a/programs/e2history.py +++ b/programs/e2history.py @@ -217,7 +217,7 @@ def print_to_std_out(all): except: print("Entry ",i," missing") try : ah.setdefault(h["path"],[]).append(h) except: continue - for k in ah.keys(): + for k in list(ah.keys()): print("---------- ",k) for i in ah[k]: if "end" in i : print(local_datetime(i["start"]),"\t ",time_diff(i["end"]-i["start"]),"\t"," ".join(i["args"])) diff --git a/programs/e2iminfo.py b/programs/e2iminfo.py index 014f77ca8d..b6d6690928 100755 --- a/programs/e2iminfo.py +++ b/programs/e2iminfo.py @@ -182,7 +182,7 @@ def main(): if options.header : # d=EMData(imagefile,i, True) #Jesus print("") - keys=d.get_attr_dict().keys() + keys=list(d.get_attr_dict().keys()) keys.sort() for k in keys: print("\t%s: %s"%(k,str(d[k]))) diff --git a/programs/e2import.py b/programs/e2import.py index 59986c5888..cf13d5cbf9 100755 --- a/programs/e2import.py +++ b/programs/e2import.py @@ -253,7 +253,7 @@ def main(): for filename in starfs: print(("Importing from {}.star".format(base_name(filename,nodir=True)))) sf = StarFile(filename) - hdr = sf.keys() + hdr = list(sf.keys()) if len(hdr) < 3: print(("Could not parse {}".format(filename))) continue diff --git a/programs/e2maskbyclass.py b/programs/e2maskbyclass.py index 363868db47..1d0502f318 100755 --- a/programs/e2maskbyclass.py +++ b/programs/e2maskbyclass.py @@ -127,7 +127,7 @@ def main(): print("ERROR: This program is meant to be used with full resolution phase flipped particles (__ctf_flip_fullres). ",fsp," does not appear to be this type of file. You can override this behavior with --nofullresok") if options.verbose: - print(sum([i.count(-1) for i in ptcls.values()])," missing particles in classes. They will be unmasked") + print(sum([i.count(-1) for i in list(ptcls.values())])," missing particles in classes. They will be unmasked") # import pprint # pprint.pprint(ptcls) diff --git a/programs/e2motion.py b/programs/e2motion.py index 5d1b681dff..ac302a2d0f 100755 --- a/programs/e2motion.py +++ b/programs/e2motion.py @@ -95,7 +95,7 @@ def main(): parms=js_open_dict("{}/0_a2d_parms.json".format(options.path)) if options.iter not in parms : - try: options.iter=max([int(i) for i in parms.keys()]) + try: options.iter=max([int(i) for i in list(parms.keys())]) except: options.iter=0 print("Iteration: ",options.iter) @@ -465,7 +465,7 @@ def newIter(self,x=0): try: dct=js_open_dict("{}/particle_parms_{:02d}.json".format(self.path,itr)) - self.particles=[(j["score"],j["xform.align2d"],eval(i)[0],int(eval(i)[1])) for i,j in dct.items()] + self.particles=[(j["score"],j["xform.align2d"],eval(i)[0],int(eval(i)[1])) for i,j in list(dct.items())] self.particles.sort() if len(self.particles)==0 : raise Exception except: diff --git a/programs/e2parallel.py b/programs/e2parallel.py index 619391dc07..64bfc5e285 100755 --- a/programs/e2parallel.py +++ b/programs/e2parallel.py @@ -207,7 +207,7 @@ def precache(files): def rerunall(): """Requeues all active (incomplete) tasks""" q=EMTaskQueue() - e=q.active.keys() + e=list(q.active.keys()) e=[i for i in e if isinstance(i,int) and q.active[i]!=None] for i in e: q.task_rerun(i) @@ -217,7 +217,7 @@ def rerunall(): def killall(): """Requeues all active (incomplete) tasks""" q=EMTaskQueue() - e=q.active.keys() + e=list(q.active.keys()) e=[i for i in e if isinstance(i,int) and q.active[i]!=None] for i in e: q.task_aborted(i) @@ -334,7 +334,7 @@ def __init__(self,target): def load(self): """Updates the cached display from source""" - keys=self.target.keys() + keys=list(self.target.keys()) keys.sort() keys=keys[:-2] self.nrows=len(keys) diff --git a/programs/e2pathwalker.py b/programs/e2pathwalker.py index 944eafc10d..8c95e5501b 100755 --- a/programs/e2pathwalker.py +++ b/programs/e2pathwalker.py @@ -165,7 +165,7 @@ def write_pdbs(filename, paths, points=None, bfactors=None, tree=None): if tree: connected = [] count = 0 - for k,v in tree.items(): + for k,v in list(tree.items()): for v2 in v: if (k,v2) in connected or (v2,k) in connected: continue @@ -235,7 +235,7 @@ def __init__(self, filename=None, outfile=None, start=None, end=None, edgefile=N if self.average < self.dmin: self.dmin = self.average - for i in self.points.keys(): + for i in list(self.points.keys()): self.itree[i] = set() @@ -243,8 +243,8 @@ def __init__(self, filename=None, outfile=None, start=None, end=None, edgefile=N #print d,w #exit() - for count1, point1 in self.points.items(): - for count2, point2 in self.points.items(): + for count1, point1 in list(self.points.items()): + for count2, point2 in list(self.points.items()): #print count1,count2, d, w = self.calcweight(point1, point2) self.distances[(count1, count2)] = d @@ -275,7 +275,7 @@ def __init__(self, filename=None, outfile=None, start=None, end=None, edgefile=N self.points[id2]=[0,0,0] self.itree[id1]=set() self.itree[id2]=set() - for ct, pt in self.points.items(): + for ct, pt in list(self.points.items()): self.distances[(id1,ct)]=.1 self.distances[(id2,ct)]=.1 self.weighted[(id1,ct)]=0 @@ -299,7 +299,7 @@ def __init__(self, filename=None, outfile=None, start=None, end=None, edgefile=N idn=max(self.points)+1 self.points[idn]=[-1,-1,-1] self.itree[idn]=set() - for ct, pt in self.points.items(): + for ct, pt in list(self.points.items()): self.distances[(idn,ct)]=.1 self.distances[(ct,idn)]=.1 self.weighted[(idn,ct)]=0 @@ -757,14 +757,14 @@ def calcweight(self, point1, point2): def find_endpoints(self): """Return list of points that have != 2 connections as possible termini; note: circular paths may have 2 links...""" - return [k for k,v in self.itree.items() if len(self.itree.get(k)) == 1] + return [k for k,v in list(self.itree.items()) if len(self.itree.get(k)) == 1] def find_branches(self): """Return points with > 2 connections""" - return [k for k,v in self.itree.items() if len(self.itree.get(k)) > 2] + return [k for k,v in list(self.itree.items()) if len(self.itree.get(k)) > 2] @@ -923,7 +923,7 @@ def run(self): for pos in common: distances[pos] = distance(self.pdb1[pos], self.pdb2[pos]) - rmsd = math.sqrt(sum((i**2 for i in distances.values())) / len(distances)) + rmsd = math.sqrt(sum((i**2 for i in list(distances.values()))) / len(distances)) print("Total RMSD:", rmsd) diff --git a/programs/e2pdb2mrc.py b/programs/e2pdb2mrc.py index 46301d8301..665c52d663 100755 --- a/programs/e2pdb2mrc.py +++ b/programs/e2pdb2mrc.py @@ -153,7 +153,7 @@ def main(): rz = float(line[30:40]) t = float(line[40:55]) row = np.array([rx,ry,rz,t]) - if tfid in tfs.keys(): + if tfid in list(tfs.keys()): tfs[tfid][rowid] = row else: tfs[tfid] = np.zeros((3,4)) @@ -285,7 +285,7 @@ def main(): p = np.asmatrix(pa.get_points()).T p = p.reshape(p.shape[0]/3,3) points = [] - for tfid in tfs.keys(): + for tfid in list(tfs.keys()): m = np.asmatrix(tfs[tfid]) # transformation matrix tfd = np.dot(p,m[:,:3].T)+m[:,3].T bfs = np.asmatrix(np.ones(tfd.shape[0])).T # should probably fill with real bfactors diff --git a/programs/e2plotEulers.py b/programs/e2plotEulers.py index 01ae8818f5..b837130888 100755 --- a/programs/e2plotEulers.py +++ b/programs/e2plotEulers.py @@ -83,7 +83,7 @@ def main(): theta = [] r = [] size = [] - for euler, count in eulerhash.items(): + for euler, count in list(eulerhash.items()): eulers = euler.split() theta.append(float(eulers[0])) r.append(float(eulers[1])) diff --git a/programs/e2proc2d.py b/programs/e2proc2d.py index d5132db55b..00ca08e192 100755 --- a/programs/e2proc2d.py +++ b/programs/e2proc2d.py @@ -268,7 +268,7 @@ def main(): options.outmode = "int8" if options.outmode not in file_mode_map : - print("Invalid output mode, please specify one of :\n",str(file_mode_map.keys()).translate(None,'"[]')) + print("Invalid output mode, please specify one of :\n",str(list(file_mode_map.keys())).translate(None,'"[]')) sys.exit(1) no_2d_3d_options = (not (options.threed2threed or options.threed2twod or options.twod2threed)) @@ -650,7 +650,7 @@ def main(): # Parse the options to convert the image file name to EMData object # (for both plain image file and bdb file) - for key in param_dict.keys(): + for key in list(param_dict.keys()): #print str(param_dict[key]) if str(param_dict[key]).find('bdb:') != -1 or not str(param_dict[key]).isdigit(): @@ -1158,7 +1158,7 @@ def main(): options.twod2threed = opt2to3 if options.extractboxes: - for k in boxes.keys(): + for k in list(boxes.keys()): out=open(k+".box","w") for c in boxes[k]: out.write("{:1d}\t{:1d}\t{:1d}\t{:1d}\n".format(int(c[0]-boxsize/2),int(c[1]-boxsize/2),int(boxsize),int(boxsize))) diff --git a/programs/e2proc2dpar.py b/programs/e2proc2dpar.py index f39ad2485b..3eabb81fbd 100644 --- a/programs/e2proc2dpar.py +++ b/programs/e2proc2dpar.py @@ -106,7 +106,7 @@ def main(): logid = E2init(sys.argv,options.ppid) if options.outmode not in file_mode_map : - print("Invalid output mode, please specify one of :\n",str(file_mode_map.keys()).translate(None,'"[]')) + print("Invalid output mode, please specify one of :\n",str(list(file_mode_map.keys())).translate(None,'"[]')) sys.exit(1) N=EMUtil.get_image_count(args[0]) @@ -134,7 +134,7 @@ def main(): # return is [N,dict] a dict of image# keyed processed images while not jsd.empty(): rd=jsd.get() - for k in rd[1].keys(): + for k in list(rd[1].keys()): writeimage(rd[1][k],args[1],k,options) thrds[rd[0]].join() @@ -183,7 +183,7 @@ def procfn(jsd,args,options,thrn,n0,n1): # Parse the options to convert the image file name to EMData object # (for both plain image file and bdb file) - for key in param_dict.keys(): + for key in list(param_dict.keys()): #print str(param_dict[key]) if str(param_dict[key]).find('bdb:') != -1 or not str(param_dict[key]).isdigit(): diff --git a/programs/e2proc3d.py b/programs/e2proc3d.py index 10e635bfd5..85f6912806 100755 --- a/programs/e2proc3d.py +++ b/programs/e2proc3d.py @@ -174,7 +174,7 @@ def main(): options.outmode="int8" if options.outmode not in file_mode_map : - print("Invalid output mode, please specify one of :\n",str(file_mode_map.keys()).translate(None,'"[]')) + print("Invalid output mode, please specify one of :\n",str(list(file_mode_map.keys())).translate(None,'"[]')) sys.exit(1) infile = args[0] @@ -461,7 +461,7 @@ def main(): if not param_dict : param_dict={} #Parse the options to convert the image file name to EMData object(for both plain image file and bdb file) - for key in param_dict.keys(): + for key in list(param_dict.keys()): if str(param_dict[key]).find('bdb:')!=-1 or not str(param_dict[key]).isdigit(): try: if os.path.is_file(param_dict[key]) : @@ -556,7 +556,7 @@ def main(): if not param_dict : param_dict={} #Parse the options to convert the image file name to EMData object(for both plain image file and bdb file) - for key in param_dict.keys(): + for key in list(param_dict.keys()): if str(param_dict[key]).find('bdb:')!=-1 or not str(param_dict[key]).isdigit(): try: param_dict[key] = EMData(param_dict[key]) diff --git a/programs/e2project3d.py b/programs/e2project3d.py index aa86645e6c..724a5d46b9 100755 --- a/programs/e2project3d.py +++ b/programs/e2project3d.py @@ -168,7 +168,7 @@ def execute(self): raise NotImplementedError("The parallelism option you specified (%s) is not suppored" %self.options.parallel ) def __write_output_data(self,rslts): - for idx,image in rslts.items(): + for idx,image in list(rslts.items()): if not isinstance(image,EMData): continue # this is here because we get the dimensions of the database as a key (e.g. '40x40x1'). image["model_id"]=self.modeln if self.options.append : image.write_image(self.options.outfile,-1) diff --git a/programs/e2projectmanager.py b/programs/e2projectmanager.py index 7e59ad3688..00afaa43a8 100755 --- a/programs/e2projectmanager.py +++ b/programs/e2projectmanager.py @@ -1096,7 +1096,7 @@ def _helpchange(self, idx): helpdict = self.helptopics[idx][1] helpdoc = "

Listed below is a list of EMAN2 %s


"%self.helptopics[idx][0] - keys = helpdict.keys() + keys = list(helpdict.keys()) keys.sort() for key in keys: helpdoc += "%s"%(key) @@ -1517,7 +1517,7 @@ def update_list(self): #self.list_widget.clear() listitems = self.getListItems() for t in self.tasks: - if t[1] in listitems.keys(): + if t[1] in list(listitems.keys()): listitems[t[1]].setText("%s %s (%s) %s"%(t[2][5:16],t[3][:4],t[1],t[4])) del(listitems[t[1]]) continue @@ -1527,7 +1527,7 @@ def update_list(self): listwigetitem.setProgramName(t[4]) self.list_widget.addItem(listwigetitem) # Remove items that have stopped running - for item in listitems.values(): + for item in list(listitems.values()): self.list_widget.takeItem(self.list_widget.row(item)) def getListItems(self): @@ -1779,7 +1779,7 @@ def getChoices(self, option): choices = eval(option['choicelist']) # If it is a dict, get the keys if type(choices) == type({}): - choices = choices.keys() + choices = list(choices.keys()) return choices def getPositional(self, option): @@ -1851,7 +1851,7 @@ def updateGUIFromCmd(self, cmd): posargs = [] # now do the widgets which are not listed in the above list - for name,widget in widgethash.iteritems(): + for name,widget in widgethash.items(): if isinstance(widget, PMHeaderWidget): continue if isinstance(widget, PMBoolWidget): @@ -1903,7 +1903,7 @@ def getErrorMessage(self): """ Check for any error messages """ errormsg = "" self.errorstate = False - for widget in self.widgethash.values(): + for widget in list(self.widgethash.values()): if widget.getErrorMessage(): self.errorstate = True errormsg += (widget.getErrorMessage()+"
") diff --git a/programs/e2projectupdate21.py b/programs/e2projectupdate21.py index b815dc2bc0..eb3889a036 100755 --- a/programs/e2projectupdate21.py +++ b/programs/e2projectupdate21.py @@ -125,7 +125,7 @@ def main(): ctf=db_open_dict("bdb:.#e2ctf.parms",ro=True) ctfbg=db_open_dict("bdb:.#e2ctf.bg2d",ro=True) ctffg=db_open_dict("bdb:.#e2ctf.im2d",ro=True) - for k in ctf.keys(): + for k in list(ctf.keys()): try: if options.verbose>1 : print("\t",k) js=js_open_dict("{}/{}".format(dest,info_name("bdb:particles#"+k))) @@ -149,7 +149,7 @@ def main(): if options.verbose : print("Converting Boxes") boxes=db_open_dict("bdb:e2boxercache#boxes",ro=True) try: - for k in boxes.keys(): + for k in list(boxes.keys()): try: if options.verbose>1 : print("\t",k) js=js_open_dict("{}/{}".format(dest,info_name(k))) diff --git a/programs/e2refinemultinoali.py b/programs/e2refinemultinoali.py index b2c635f514..1182da3185 100755 --- a/programs/e2refinemultinoali.py +++ b/programs/e2refinemultinoali.py @@ -252,7 +252,7 @@ def main(): output_3d.append({}) output_cls.append({}) ### even/odd loop - for eoid,eo in input_eo_order.items(): + for eoid,eo in list(input_eo_order.items()): if it>0: inputmodel=[output_3d[-2][eo][m] for m in models] diff --git a/programs/e2refinetorelion2d.py b/programs/e2refinetorelion2d.py index f3bf7867e7..69734a6ce7 100755 --- a/programs/e2refinetorelion2d.py +++ b/programs/e2refinetorelion2d.py @@ -107,7 +107,7 @@ verbosity=str(options.verbosity) header= EMData(set_name,0,True) -h_keys=header.get_attr_dict().keys() +h_keys=list(header.get_attr_dict().keys()) nx,ny,nz=header['nx'],header['ny'],header['nz'] num_images = EMUtil.get_image_count(set_name) mrc = False diff --git a/programs/e2refinetorelion3d.py b/programs/e2refinetorelion3d.py index a7ff447e26..33b01a9349 100755 --- a/programs/e2refinetorelion3d.py +++ b/programs/e2refinetorelion3d.py @@ -133,7 +133,7 @@ s1 = "e2proc3d.py " + refmap + " " + E2RLN + "/3DRefMap.mrc --process=normalize.edgemean --verbose="+str(options.verbose) call(s1, shell=True) header = EMData(set_name,0,True) -h_keys = header.get_attr_dict().keys() +h_keys = list(header.get_attr_dict().keys()) nx,ny,nz=header['nx'],header['ny'],header['nz'] num_images = EMUtil.get_image_count(set_name) mrc = False diff --git a/programs/e2simmx.py b/programs/e2simmx.py index 7fa1c3e8fe..b2a260c662 100755 --- a/programs/e2simmx.py +++ b/programs/e2simmx.py @@ -445,7 +445,7 @@ def __cmp_one_to_many(self,ptcl,refs,mask,partial=None,progress_callback=None,cb data = {} cbli=0 - for ref_idx,ref in refs.items(): + for ref_idx,ref in list(refs.items()): if not progress_callback(int(100*(cbi+cbli/float(len(refs)))/cbn)) : break cbli+=1 if partial!=None : @@ -514,7 +514,7 @@ def execute(self,progress_callback=None): min_ptcl_idx = None n = float(len(ptcls)) i = 0 - for ptcl_idx,ptcl in ptcls.items(): + for ptcl_idx,ptcl in list(ptcls.items()): if min_ptcl_idx == None or ptcl_idx < min_ptcl_idx: min_ptcl_idx = ptcl_idx @@ -540,12 +540,12 @@ def execute(self,progress_callback=None): result_data.append(e) min_ref_idx = None - for ref_idx in refs.keys(): + for ref_idx in list(refs.keys()): if min_ref_idx == None or ref_idx < min_ref_idx: min_ref_idx = ref_idx - for r,dd in sim_data.items(): - for c,data in dd.items(): + for r,dd in list(sim_data.items()): + for c,data in list(dd.items()): comp = data[0] rc = c-min_ref_idx # this was a solution to a bug rr = r-min_ptcl_idx # this was a solution to a bug diff --git a/programs/e2spt_average.py b/programs/e2spt_average.py index f892310cac..be017e5d15 100755 --- a/programs/e2spt_average.py +++ b/programs/e2spt_average.py @@ -123,13 +123,13 @@ def main(): avg[1]=Averagers.get("mean.tomo",{"thresh_sigma":options.wedgesigma}) # filter the list of particles to include - keys=angs.keys() + keys=list(angs.keys()) if options.listfile!=None : keys=[i for i in keys if eval(i)[1] in plist] - if options.verbose : print("{}/{} particles based on list file".format(len(keys),len(angs.keys()))) + if options.verbose : print("{}/{} particles based on list file".format(len(keys),len(list(angs.keys())))) keys=[k for k in keys if angs[k]["score"]<=options.simthr and inrange(options.minalt,angs[k]["xform.align3d"].get_params("eman")["alt"],options.maxalt)] - if options.verbose : print("{}/{} particles after filters".format(len(keys),len(angs.keys()))) + if options.verbose : print("{}/{} particles after filters".format(len(keys),len(list(angs.keys())))) # Rotation and insertion are slow, so we do it with threads. diff --git a/programs/e2spt_average_multi.py b/programs/e2spt_average_multi.py index cbc9135fc2..590b260bfa 100755 --- a/programs/e2spt_average_multi.py +++ b/programs/e2spt_average_multi.py @@ -130,13 +130,13 @@ def main(): avgs=[Averagers.get("mean.tomo",{"thresh_sigma":options.wedgesigma}) for i in xrange(n)] # filter the list of particles to include - keys=angs.keys() + keys=list(angs.keys()) if options.listfile!=None : keys=[i for i in keys if eval(i)[1] in plist] - if options.verbose : print("{}/{} particles based on list file".format(len(keys),len(angs.keys()))) + if options.verbose : print("{}/{} particles based on list file".format(len(keys),len(list(angs.keys())))) keys=[k for k in keys if angs[k]["score"]<=options.simthr and inrange(options.minalt,angs[k]["xform.align3d"].get_params("eman")["alt"],options.maxalt)] - if options.verbose : print("{}/{} particles after filters".format(len(keys),len(angs.keys()))) + if options.verbose : print("{}/{} particles after filters".format(len(keys),len(list(angs.keys())))) if options.shrinkcompare>1 : diff --git a/programs/e2spt_boxer.py b/programs/e2spt_boxer.py index 47594b0627..e9f1b987a9 100755 --- a/programs/e2spt_boxer.py +++ b/programs/e2spt_boxer.py @@ -367,7 +367,7 @@ def __init__(self,application,options,datafile=None): bdf[j]=b[j] - if bdf[5] not in self.sets.keys(): + if bdf[5] not in list(self.sets.keys()): clsi=int(bdf[5]) self.sets[clsi]="particles_{:02d}".format(clsi) @@ -377,7 +377,7 @@ def __init__(self,application,options,datafile=None): info.close() if len(self.sets)==0: self.new_set("particles_00") - self.sets_visible[self.sets.keys()[0]]=0 + self.sets_visible[list(self.sets.keys())[0]]=0 self.currentset=sorted(self.sets.keys())[0] self.setspanel.update_sets() @@ -1433,7 +1433,7 @@ def new_set(self, name): def save_set(self): - self.save_boxes(self.sets_visible.keys()) + self.save_boxes(list(self.sets_visible.keys())) return @@ -1452,7 +1452,7 @@ def closeEvent(self,event): info=js_open_dict(self.jsonfile) info["boxes_3d"]=self.boxes clslst={} - for key in self.sets.keys(): + for key in list(self.sets.keys()): clslst[int(key)]={ "name":self.sets[key], "boxsize":self.boxsize[key], diff --git a/programs/e2spt_boxer22.py b/programs/e2spt_boxer22.py index 9fc6b2ac42..a58497543c 100755 --- a/programs/e2spt_boxer22.py +++ b/programs/e2spt_boxer22.py @@ -321,7 +321,7 @@ def __init__(self,application,options,datafile=None): bdf[j]=b[j] - if bdf[5] not in self.sets.keys(): + if bdf[5] not in list(self.sets.keys()): clsi=int(bdf[5]) self.sets[clsi]="particles_{:02d}".format(clsi) @@ -331,7 +331,7 @@ def __init__(self,application,options,datafile=None): info.close() if len(self.sets)==0: self.new_set("particles_00") - self.sets_visible[self.sets.keys()[0]]=0 + self.sets_visible[list(self.sets.keys())[0]]=0 self.currentset=sorted(self.sets.keys())[0] self.setspanel.update_sets() @@ -1325,7 +1325,7 @@ def new_set(self, name): def save_set(self): - self.save_boxes(self.sets_visible.keys()) + self.save_boxes(list(self.sets_visible.keys())) return @@ -1343,7 +1343,7 @@ def SaveJson(self): info=js_open_dict(self.jsonfile) info["boxes_3d"]=self.boxes clslst={} - for key in self.sets.keys(): + for key in list(self.sets.keys()): clslst[int(key)]={ "name":self.sets[key], "boxsize":self.boxsize[key], diff --git a/programs/e2spt_classaverage.py b/programs/e2spt_classaverage.py index 4b2e9bdb2e..86809ed5af 100755 --- a/programs/e2spt_classaverage.py +++ b/programs/e2spt_classaverage.py @@ -556,7 +556,7 @@ def main(): resumeDict = js_open_dict( options.resume ) #print "Resume dict is", resumeDict - for key in resumeDict.keys(): + for key in list(resumeDict.keys()): #print "\n\nKKKKKKey is", key keyint = int ( key.split('_')[-1] ) @@ -598,7 +598,7 @@ def main(): if options.inputaliparams: try: inputalidict = js_open_dict( options.inputaliparams ) - numdigits = len( inputalidict.keys()[0].split('_')[-1] ) #keys are of the form 'subtomo_XXX'; we determine how many XXX the keys have + numdigits = len( list(inputalidict.keys())[0].split('_')[-1] ) #keys are of the form 'subtomo_XXX'; we determine how many XXX the keys have except: print("ERROR: Something is wrong with the json file provided". options.inputaliparams) sys.exit(1) @@ -1048,13 +1048,13 @@ def main(): tomoID = "subtomo_" + str(ptclnum).zfill( len(str( len(ptclnums) )) ) - if tomoID not in resumeDict.keys(): + if tomoID not in list(resumeDict.keys()): print("ERROR: This key is not in the file provided for --resume", tomoID) sys.exit() - if len(resumeDict.keys()) > 0: - keys = resumeDict.keys() + if len(list(resumeDict.keys())) > 0: + keys = list(resumeDict.keys()) for key in keys: if type(resumeDict[key]) is not list: diff --git a/programs/e2spt_ctf_old.py b/programs/e2spt_ctf_old.py index 830a3d0303..b655a40113 100755 --- a/programs/e2spt_ctf_old.py +++ b/programs/e2spt_ctf_old.py @@ -600,7 +600,7 @@ def main(): ''' #Once the images are organized, proceed to CTF correct them. Loop over all images. ''' - for imagestem in imagefilenames.keys(): + for imagestem in list(imagefilenames.keys()): print("\nWorking on image",pp,imagefilenames[imagestem]) ctf=None @@ -1491,7 +1491,7 @@ def ctfparamparser( pline ): params = {'ampcont':ampcont,'apix':apix,'bfactor':bfactor,'cs':cs,'defocus':defocus,'voltage':voltage} print("\n(e2spt_ctf.py)(ctfparamparser) The parsed parameters are") - for key in params.keys(): + for key in list(params.keys()): print(key + '=' + params[key]) ctf = EMAN2Ctf() @@ -2231,7 +2231,7 @@ def sptctffit( options, apix, imagefilenames, angles, icethickness ): angerrors = collections.OrderedDict(sorted(angerrors.items())) if angerrors: - avgangerror = sum( [ math.sqrt(angerrors[a]*angerrors[a]) for a in angerrors.keys() ] ) /len( angerrors ) + avgangerror = sum( [ math.sqrt(angerrors[a]*angerrors[a]) for a in list(angerrors.keys()) ] ) /len( angerrors ) a=open(options.path + '/angular_error_avg.txt','w') a.writelines([str(avgangerror)+'\n']) diff --git a/programs/e2spt_eval.py b/programs/e2spt_eval.py index d4ad657ed1..ed23a100f7 100755 --- a/programs/e2spt_eval.py +++ b/programs/e2spt_eval.py @@ -113,7 +113,7 @@ def update_files(self): js=js_open_dict(jsfile) dic.update(js.data) - for k in js.keys(): + for k in list(js.keys()): if str(k) not in self.paramlst: self.paramlst[str(k)]=True diff --git a/programs/e2spt_extract.py b/programs/e2spt_extract.py index d24de4a66c..71b7a76d9f 100755 --- a/programs/e2spt_extract.py +++ b/programs/e2spt_extract.py @@ -78,7 +78,7 @@ def main(): if "class_list" in js and "boxes_3d" in js: clslst=js["class_list"] boxes=js["boxes_3d"] - for ky in clslst.keys(): + for ky in list(clslst.keys()): val=clslst[ky] if options.label: if str(val["name"])!=options.label: diff --git a/programs/e2spt_hac.py b/programs/e2spt_hac.py index ccb7c291ac..9c125ba233 100755 --- a/programs/e2spt_hac.py +++ b/programs/e2spt_hac.py @@ -700,9 +700,9 @@ def allvsall(options,preproc): #print "Old tagas are:\n", oldtags nnn = 0 - for refkey,refvalue in newptcls.iteritems(): + for refkey,refvalue in newptcls.items(): ptcl1 = nnn - for particlekey,particlevalue in oldptcls.iteritems(): + for particlekey,particlevalue in oldptcls.items(): ptcl2 = oldtags[particlekey] @@ -1325,7 +1325,7 @@ def allvsall(options,preproc): if options.verbose > 2: print("These were the particles in iteration", k) - for particlekey,particlevalue in newptcls.iteritems(): + for particlekey,particlevalue in newptcls.items(): if options.verbose > 2: print(particlekey) @@ -1337,7 +1337,7 @@ def allvsall(options,preproc): if options.verbose > 1: print("This particle from newptcls was averaged", particlekey) - for particlekey,particlevalue in oldptcls.iteritems(): + for particlekey,particlevalue in oldptcls.items(): if particlekey not in used: surviving_oldptcls.update({particlekey:particlevalue}) else: @@ -1365,7 +1365,7 @@ def allvsall(options,preproc): #a.write_image(oldptclstack.hdf,0) # gg=0 - for particlekey,particlevalue in oldptcls.iteritems(): + for particlekey,particlevalue in oldptcls.items(): allptclsRound.update({ particlekey: [particlevalue,allptclsMatrix[k][particlekey][-1]]}) particlevalue.write_image(options.path + '/oldptclstack.hdf',gg) gg+=1 diff --git a/programs/e2spt_refine.py b/programs/e2spt_refine.py index 2ce8c390c5..c5cebe45a8 100755 --- a/programs/e2spt_refine.py +++ b/programs/e2spt_refine.py @@ -94,7 +94,7 @@ def main(): js=js_open_dict(os.path.join(options.path, "particle_parms_{:02d}.json".format(itr))) score=[] - for k in js.keys(): + for k in list(js.keys()): score.append(float(js[k]["score"])) s="" diff --git a/programs/e2spt_refinemulti.py b/programs/e2spt_refinemulti.py index 7d92e0033d..874bb93907 100755 --- a/programs/e2spt_refinemulti.py +++ b/programs/e2spt_refinemulti.py @@ -939,7 +939,7 @@ def main(): newreffiles.update({ reftag: newreffile } ) else: print("there is no avg in avgs with refindx or reftag %d " %( int(refindx) )) - print("avgs.keys() are", avgs.keys()) + print("avgs.keys() are", list(avgs.keys())) reffilesrefine = newreffiles @@ -1260,7 +1260,7 @@ def main(): kkk = 0 - classes_sorted = sorted( classes.items(), key=itemgetter(0)) + classes_sorted = sorted( list(classes.items()), key=itemgetter(0)) print("\n\nclasses sorted are", classes_sorted) for klass in classes_sorted: diff --git a/programs/e2spt_sgd.py b/programs/e2spt_sgd.py index 73d78ced66..da500006b1 100755 --- a/programs/e2spt_sgd.py +++ b/programs/e2spt_sgd.py @@ -145,7 +145,7 @@ def main(): angs[(fsp,n)]=d avgr=Averagers.get("mean.tomo") #print(angs) - for ks in angs.keys(): + for ks in list(angs.keys()): d=angs[ks] jspm[ks]=d p=EMData(str(ks[0]), int(ks[1])) diff --git a/programs/e2spt_simulation.py b/programs/e2spt_simulation.py index a718e765b4..da0816688f 100755 --- a/programs/e2spt_simulation.py +++ b/programs/e2spt_simulation.py @@ -809,7 +809,7 @@ def subtomosim(options,ptcls,outname,dimension): finaloutname = outname for result in results: - key = result.keys()[0] + key = list(result.keys())[0] #if options.path not in outname: # finaloutname = options.path + '/' + outname diff --git a/programs/e2spt_stat.py b/programs/e2spt_stat.py index 54a0be4e4e..d8590b5272 100755 --- a/programs/e2spt_stat.py +++ b/programs/e2spt_stat.py @@ -55,16 +55,16 @@ def main(): angs=js_open_dict("{}/particle_parms_{:02d}.json".format(options.path,options.iter)) if options.mode in ("score","coverage"): - data=[angs[a][options.mode] for a in angs.keys()] + data=[angs[a][options.mode] for a in list(angs.keys())] else: - data=[angs[a]["xform.align3d"].get_params("eman")[options.mode] for a in angs.keys()] + data=[angs[a]["xform.align3d"].get_params("eman")[options.mode] for a in list(angs.keys())] if options.extract: out=open("{}/particle_parms_{:02d}.txt".format(options.path,options.iter),"w") out.write("# num; score; ref coverage; az; alt; phi\n") - k=angs.keys() + k=list(angs.keys()) k.sort(key=lambda i:int(eval(i)[1])) for i in k: itm=angs[i] diff --git a/programs/e2spt_tempmatch.py b/programs/e2spt_tempmatch.py index aa7b8391ea..dc09239796 100755 --- a/programs/e2spt_tempmatch.py +++ b/programs/e2spt_tempmatch.py @@ -108,7 +108,7 @@ def main(): n=min(options.nptcl, len(pts)) if "class_list" in js: clst=js['class_list'] - try: kid=max([int(k) for k in clst.keys()])+1 + try: kid=max([int(k) for k in list(clst.keys())])+1 except: kid=0 # In case someone manually edited the info file. Unlikely. else: clst={} diff --git a/programs/e2spt_tiltrefine.py b/programs/e2spt_tiltrefine.py index 880cf426ea..0faea26ffa 100755 --- a/programs/e2spt_tiltrefine.py +++ b/programs/e2spt_tiltrefine.py @@ -110,7 +110,7 @@ def main(): else: js=js_open_dict(path+"/particle_parms_{:02d}.json".format(itr)) - k=js.keys()[0] + k=list(js.keys())[0] src=eval(k)[0] e=EMData(src, 0,True) bxsz=e["nx"] @@ -132,7 +132,7 @@ def main(): except:pass lst=[LSXFile(m, False) for m in lname] - n3d=len(js.keys()) + n3d=len(list(js.keys())) for ii in range(n3d): e=EMData(src, ii, True) fname=e["class_ptcl_src"] diff --git a/programs/e2tilefile.py b/programs/e2tilefile.py index 5d60200aff..d63838abda 100755 --- a/programs/e2tilefile.py +++ b/programs/e2tilefile.py @@ -76,7 +76,7 @@ def main(): if options.dump: td=tile_list(args[0]) print(td) - k=td.keys() + k=list(td.keys()) k.sort() for i in k: print(i,td[i]) diff --git a/programs/e2tiltseries.py b/programs/e2tiltseries.py index 94c6672e6a..73f01e5d27 100644 --- a/programs/e2tiltseries.py +++ b/programs/e2tiltseries.py @@ -111,7 +111,7 @@ def main(): tlt_assoc[ang] = arg db.close() - ordered_angles = sorted([float(a) for a in tlt_assoc.keys()]) + ordered_angles = sorted([float(a) for a in list(tlt_assoc.keys())]) sorted_args = [tlt_assoc[a] for a in ordered_angles] # order args according to tilt angle parameter for angle,infile in zip(ordered_angles,sorted_args): diff --git a/programs/e2tomo_eval.py b/programs/e2tomo_eval.py index c8b9320e03..5548c80487 100755 --- a/programs/e2tomo_eval.py +++ b/programs/e2tomo_eval.py @@ -191,7 +191,7 @@ def update_files(self): if nbox>0 and "class_list" in js: cls=js["class_list"] - for k in cls.keys(): + for k in list(cls.keys()): vname=str(cls[k]["name"]) n=np.sum([b[-1]==int(k) for b in boxes]) @@ -216,7 +216,7 @@ def update_files(self): #### update particle type list self.setspanel.clear() - for k in self.ptclcls.keys(): + for k in list(self.ptclcls.keys()): v=self.ptclcls[k] kname=" {}\t: {}".format(k, v[1]) item=QtGui.QListWidgetItem(kname) @@ -237,7 +237,7 @@ def update_list(self): self.imglst.setItem(i,0,it) self.imglst.setItem(i,1,QtGui.QTableWidgetItem(str(info["basename"]))) nbox=0 - for kname in info["boxcls"].keys(): + for kname in list(info["boxcls"].keys()): if self.ptclcls[kname][0]==1: nbox+=info["boxcls"][kname] it=QtGui.QTableWidgetItem() diff --git a/pyemtbx/boxertools.py b/pyemtbx/boxertools.py index ebc3e3c601..31e130ce1e 100644 --- a/pyemtbx/boxertools.py +++ b/pyemtbx/boxertools.py @@ -2992,7 +2992,7 @@ def __init__(self,parent,dict=None): if not(dict is None): # assume the dictionary uses variable names as keys, so we loop over all # keys - for key in dict.keys(): + for key in list(dict.keys()): try: # and set our contents according to the dict self.__dict__[key] = dict[key] diff --git a/rt/pyem/test_emdata.py b/rt/pyem/test_emdata.py index ca71c4b166..5a460c6344 100755 --- a/rt/pyem/test_emdata.py +++ b/rt/pyem/test_emdata.py @@ -151,7 +151,7 @@ def test_copy_head(self): self.assertEqual(dict1['nx'], dict2['nx']) self.assertEqual(dict1['ny'], dict2['ny']) self.assertEqual(dict1['nz'], dict2['nz']) - self.assertEqual(dict1.keys(), dict2.keys()) + self.assertEqual(list(dict1.keys()), list(dict2.keys())) def test_copy_fft(self): """test copy() on fft ...............................""" @@ -2255,7 +2255,7 @@ def test_get_attr_dict(self): cur_attrlist = [] for mydict in (d0, d1, d2): - for mykey in mydict.keys(): + for mykey in list(mydict.keys()): if (not ("MRC" in mykey)): cur_attrlist.append(mykey + "=" + str(mydict[mykey])+"\n") diff --git a/sparx/bin/sxgui.py b/sparx/bin/sxgui.py index e6c03f4233..97099c6add 100755 --- a/sparx/bin/sxgui.py +++ b/sparx/bin/sxgui.py @@ -1018,7 +1018,7 @@ def read_params(self, file_path_in): QMessageBox.warning(self, "Invalid Parameter File Format", "Command token entry should have \"%s\" closing key base name in line (%s) of file (%s). The format of this file might be corrupted. Please save the paramater file again." % (target_operator, line_in, file_path_in)) key_base = label_in[0:item_tail] # Get corresponding cmd_token - if key_base not in self.sxcmd.token_dict.keys(): + if key_base not in list(self.sxcmd.token_dict.keys()): QMessageBox.warning(self, "Invalid Parameter File Format", "Invalid base name of command token \"%s\" is found in line (%s) of file (%s). This parameter file might be incompatible with the current version. Please save the paramater file again." % (key_base, line_in, file_path_in)) cmd_token = self.sxcmd.token_dict[key_base] if not cmd_token.is_locked: @@ -1628,7 +1628,7 @@ def __init__(self, name, parent=None): custom_style = "QPushButton {color:gray; }" if cmd_token.restore: btn_name = "YES" - if cmd_token.type in parent.sxconst_set.dict.keys(): + if cmd_token.type in list(parent.sxconst_set.dict.keys()): custom_style = "QPushButton {color:green; }" cmd_token_restore_tooltip = const_cmd_token_restore_tooltip elif cmd_token.is_required: @@ -1663,7 +1663,7 @@ def __init__(self, name, parent=None): btn_name = "%s" % cmd_token.restore custom_style = "QPushButton {color:gray; }" is_btn_enable = True - if cmd_token.type in parent.sxconst_set.dict.keys(): + if cmd_token.type in list(parent.sxconst_set.dict.keys()): custom_style = "QPushButton {color:green; }" cmd_token_restore_tooltip = const_cmd_token_restore_tooltip elif cmd_token.is_required: @@ -2870,14 +2870,14 @@ def register_const_set(self): for sxcmd in sxcmd_category.cmd_list: # Loop through all command tokens of this command for cmd_token in sxcmd.token_list: - if not cmd_token.is_locked and cmd_token.type in self.sxconst_set.dict.keys(): + if not cmd_token.is_locked and cmd_token.type in list(self.sxconst_set.dict.keys()): sxconst = self.sxconst_set.dict[cmd_token.type] cmd_token.restore = sxconst.register cmd_token.restore_widget.setText("%s" % cmd_token.restore) cmd_token.widget.setText(cmd_token.restore) # print "MRK_DEBUG: %s, %s, %s, %s, %s, %s" % (sxcmd.name, sxcmd.subname, cmd_token.key_base, cmd_token.type, cmd_token.default, cmd_token.restore) elif cmd_token.type == "abs_freq": - assert("apix" in self.sxconst_set.dict.keys()) + assert("apix" in list(self.sxconst_set.dict.keys())) ### print("MRK_DEBUG: ----- register_const_set() ----- ") ### print("MRK_DEBUG: cmd_token.type = {}".format(cmd_token.type)) ### sxconst_apix = self.sxconst_set.dict["apix"] @@ -2946,7 +2946,7 @@ def read_consts(self, file_path_in): QMessageBox.warning(self, "Invalid Project Settings File Format", "Project settings entry should have \"%s\" closing entry key in line (%s) The format of this file might be corrupted. Please save the project settings file again." % (target_operator, line_in)) key = label_in[0:item_tail] # Get corresponding sxconst - if key not in self.sxconst_set.dict.keys(): + if key not in list(self.sxconst_set.dict.keys()): QMessageBox.warning(self, "Invalid Project Settings File Format", "Invalid entry key for project settings \"%s\" is found in line (%s). This project settings file might be incompatible with the current version. Please save the project settings file again." % (key, line_in)) sxconst = self.sxconst_set.dict[key] sxconst.widget.setText(val_str_in) diff --git a/sparx/bin/sxgui_meridien.py b/sparx/bin/sxgui_meridien.py index 176a1e330a..8a889834f3 100644 --- a/sparx/bin/sxgui_meridien.py +++ b/sparx/bin/sxgui_meridien.py @@ -465,7 +465,7 @@ def _event_select_deselect_all(self, root_tree_item): :return: ''' - if root_tree_item in self.root_items_path_dictionary.values(): + if root_tree_item in list(self.root_items_path_dictionary.values()): number_of_runs = root_tree_item.childCount() for i in range(number_of_runs): child_run = root_tree_item.child(i) @@ -477,7 +477,7 @@ def _get_checked_items(self): :return: List of checked QItemWidget """ checked_runs = [] - for root in self.root_items_path_dictionary.values(): + for root in list(self.root_items_path_dictionary.values()): number_of_runs = root.childCount() for i in range(number_of_runs): diff --git a/sparx/bin/sxhelixboxer.py b/sparx/bin/sxhelixboxer.py index de6520e98b..25817e46b3 100755 --- a/sparx/bin/sxhelixboxer.py +++ b/sparx/bin/sxhelixboxer.py @@ -482,7 +482,7 @@ def save_particle_coords(helix_particle_coords_dict, output_filepath, micrograph out_file.write("#micrograph: " + micrograph_filepath + "\n") out_file.write("#segment length: " + str(ptcl_length) + "\n") out_file.write("#segment width: " + str(ptcl_width) + "\n") - for helix_coords in helix_particle_coords_dict.keys(): + for helix_coords in list(helix_particle_coords_dict.keys()): out_file.write("#helix: " + str(tuple(helix_coords[0:2])) + "," + str(tuple(helix_coords[2:4])) + "," + str(helix_coords[4]) + "\n") particle_list = helix_particle_coords_dict[helix_coords] for ptcl_center in particle_list: @@ -969,7 +969,7 @@ def save(self): if self.helices_groupbox.isChecked(): if self.helices_coords_groupbox.isChecked(): path = str( self.helices_coords_line_edit.text() ) - save_helix_coords(helices_dict.keys(), path) + save_helix_coords(list(helices_dict.keys()), path) if self.helices_images_groupbox.isChecked(): helix_filepath = str(self.helices_images_line_edit.text()) i = 0 @@ -1505,7 +1505,7 @@ def load_micrograph(self, micrograph_emdata): width = self.box_width if self.helices_dict: - first_coords = self.helices_dict.keys()[0] + first_coords = list(self.helices_dict.keys())[0] width = first_coords[4] self.box_width_spinbox.setValue(width) def main_image_closed(self): @@ -1594,7 +1594,7 @@ def width_changed(self, width): #resize current boxes #TODO: this is similar to part of self.mouse_up ==> make both methods call a function with common code shapes = self.main_image.get_shapes() #an EMShapeDict of EMShapes - for box_key in shapes.keys(): + for box_key in list(shapes.keys()): old_emshape = shapes.get(box_key) old_coords = old_emshape.getShape()[4:9] new_coords = (old_coords[0], old_coords[1], old_coords[2], old_coords[3], width) diff --git a/sparx/bin/sxrelion2sphire.py b/sparx/bin/sxrelion2sphire.py index dc805c3352..43c664b980 100755 --- a/sparx/bin/sxrelion2sphire.py +++ b/sparx/bin/sxrelion2sphire.py @@ -342,7 +342,7 @@ def main(): relion_key = str_line.split(' ')[0] assert relion_key.find('_rln') != -1, '# Logical Error: The string %s must contain _rln at this point of code.' % (str_line) - if relion_key in relion_dict.keys(): + if relion_key in list(relion_dict.keys()): relion_dict[relion_key][idx_col] = int(i_relion_item_col) print(relion_dict[relion_key][idx_title] % (relion_dict[relion_key][idx_col], relion_key)) @@ -353,7 +353,7 @@ def main(): if i_relion_particle == 0: print('# ') print('# Checking RELION STAR file contents ...') - for category_key in relion_category_dict.keys(): + for category_key in list(relion_category_dict.keys()): for key in relion_category_dict[category_key][idx_required_key_list]: if relion_dict[key][idx_col] < 0: print('# %s entry for %s is not found' % (key, relion_category_dict[category_key][idx_relion_process])) @@ -370,7 +370,7 @@ def main(): is_success = False break; - for category_key in relion_category_dict.keys(): + for category_key in list(relion_category_dict.keys()): if relion_category_dict[category_key][idx_is_category_found] == True: print('# ') print('# Parameters associated with %s will be extracted.' % (relion_category_dict[category_key][idx_relion_process])) diff --git a/sparx/bin/sxsort3d_depth.py b/sparx/bin/sxsort3d_depth.py index 61de2da72e..08ddf3b28f 100755 --- a/sparx/bin/sxsort3d_depth.py +++ b/sparx/bin/sxsort3d_depth.py @@ -2160,13 +2160,13 @@ def copy_oldparamstructure_from_meridien_MPI(selected_iteration, log_main): for im in xrange(len(tchunk)): all_smearing[im] = smearing_dict[tchunk[im]] write_text_file(all_smearing, os.path.join(Tracker["constants"]["masterdir"], "all_smearing.txt")) full_dict_list = [ None for im in xrange(Tracker["constants"]["total_stack"])] - for key, value in local_dict.iteritems():full_dict_list[key] = value + for key, value in local_dict.items():full_dict_list[key] = value mpi_barrier(MPI_COMM_WORLD) for icpu in xrange(Blockdata["nproc"]): if Blockdata["myid"] == icpu and Blockdata["myid"] != Blockdata["main_node"]: wrap_mpi_send(local_dict, Blockdata["main_node"], MPI_COMM_WORLD) elif Blockdata["myid"] != icpu and Blockdata["myid"] == Blockdata["main_node"]: local_dict = wrap_mpi_recv(icpu, MPI_COMM_WORLD) - for key, value in local_dict.iteritems(): + for key, value in local_dict.items(): full_dict_list[key] = value else: pass mpi_barrier(MPI_COMM_WORLD) @@ -5748,7 +5748,7 @@ def copy_results(log_file, all_gen_stat_list): log_file.add( '{:^8} {:>8} {:^24} {:>15} {:^22} {:^5} {:^15} {:^20} '.format('Group ID', ' size','determined in generation', 'reproducibility', 'random reproducibility', ' std ', ' selection file', ' map file ')) clusters = [] NACC = 0 - for ig1, value in Tracker["generation"].items(): + for ig1, value in list(Tracker["generation"].items()): ig = atoi('%s'%ig1) for ic in xrange(value): cluster_file = os.path.join(Tracker["constants"]["masterdir"], "generation_%03d"%ig, "Cluster_%03d.txt"%ic) diff --git a/sparx/bin/sxsort3d_new.py b/sparx/bin/sxsort3d_new.py index 48e0b6bec4..f68af09aa7 100755 --- a/sparx/bin/sxsort3d_new.py +++ b/sparx/bin/sxsort3d_new.py @@ -1255,12 +1255,12 @@ def copy_oldparamstructure_from_meridien_MPI(selected_iteration, log): if Blockdata["myid"] == Blockdata["main_node"]: full_dict_list = [ None for im in xrange(Tracker["constants"]["total_stack"])] - for key, value in local_dict.iteritems():full_dict_list[key] = value + for key, value in local_dict.items():full_dict_list[key] = value for icpu in xrange(Blockdata["nproc"]): if Blockdata["myid"] == icpu and Blockdata["myid"] != Blockdata["main_node"]: wrap_mpi_send(local_dict, Blockdata["main_node"], MPI_COMM_WORLD) elif Blockdata["myid"] != icpu and Blockdata["myid"] == Blockdata["main_node"]: local_dict = wrap_mpi_recv(icpu, MPI_COMM_WORLD) - for key, value in local_dict.iteritems(): + for key, value in local_dict.items(): full_dict_list[key] = value else: pass mpi_barrier(MPI_COMM_WORLD) diff --git a/sparx/doc/Tutorial/scripts/gfm_to_latex.py b/sparx/doc/Tutorial/scripts/gfm_to_latex.py index a731131717..f5791a792e 100644 --- a/sparx/doc/Tutorial/scripts/gfm_to_latex.py +++ b/sparx/doc/Tutorial/scripts/gfm_to_latex.py @@ -40,7 +40,7 @@ def load_lines(input_file): def replace_tags(lines, replace_dict): sanity_list = [] typo_list = [] - for key, value in replace_dict.iteritems(): + for key, value in replace_dict.items(): if 'END|||' in key: sanity_list.append(key) typo_list.append(key) @@ -58,7 +58,7 @@ def replace_tags(lines, replace_dict): print('line:', idx, ' Tag typo for:', name) print(line) - for key, value in replace_dict.iteritems(): + for key, value in replace_dict.items(): if not key in lines: print(key, 'not found') lines = lines.replace(key, value) diff --git a/sparx/libpy/applications.py b/sparx/libpy/applications.py index de27049a83..ff9d6efc9c 100644 --- a/sparx/libpy/applications.py +++ b/sparx/libpy/applications.py @@ -17826,7 +17826,7 @@ def HAC_averages(stack, dendoname, avename, K): print('Impossible to read dendogram structure.') sys.exit() - list_k = Dendo.keys() + list_k = list(Dendo.keys()) if K not in list_k: print('Dendogram does not contain the draw for K=%d' % K) sys.exit() diff --git a/sparx/libpy/statistics.py b/sparx/libpy/statistics.py index a1c95c41a8..29d0d207be 100755 --- a/sparx/libpy/statistics.py +++ b/sparx/libpy/statistics.py @@ -7555,7 +7555,7 @@ def fullyflatten(self, *args): """ flattened_items = [] if len(args) == 0: collection = self.__items - else: collection = args[0].items() + else: collection = list(args[0].items()) for item in collection: if isinstance(item, py_Cluster): diff --git a/sparx/libpy/utilities.py b/sparx/libpy/utilities.py index a4bf15cd65..9ae0275475 100644 --- a/sparx/libpy/utilities.py +++ b/sparx/libpy/utilities.py @@ -5610,7 +5610,7 @@ def store_value_of_simple_vars_in_json_file(filename, local_vars, exclude_list_o allowed_types = [type(None), bool, int, int, float, complex, str, bytes] - local_vars_keys = local_vars.keys() + local_vars_keys = list(local_vars.keys()) my_vars = dict() for key in set(local_vars_keys) - set(exclude_list_of_vars): @@ -5839,7 +5839,7 @@ def convert_json_fromunicode(data): if isinstance(data, str): return str(data) elif isinstance(data, collections.Mapping): - return dict(map(convert_json_fromunicode, data.iteritems())) + return dict(map(convert_json_fromunicode, iter(data.items()))) elif isinstance(data, collections.Iterable): return type(data)(map(convert_json_fromunicode, data)) else: diff --git a/sparx/templates/sxgui_template.py b/sparx/templates/sxgui_template.py index 59b1253ef8..ae39c07ea8 100755 --- a/sparx/templates/sxgui_template.py +++ b/sparx/templates/sxgui_template.py @@ -1018,7 +1018,7 @@ def read_params(self, file_path_in): QMessageBox.warning(self, "Invalid Parameter File Format", "Command token entry should have \"%s\" closing key base name in line (%s) of file (%s). The format of this file might be corrupted. Please save the paramater file again." % (target_operator, line_in, file_path_in)) key_base = label_in[0:item_tail] # Get corresponding cmd_token - if key_base not in self.sxcmd.token_dict.keys(): + if key_base not in list(self.sxcmd.token_dict.keys()): QMessageBox.warning(self, "Invalid Parameter File Format", "Invalid base name of command token \"%s\" is found in line (%s) of file (%s). This parameter file might be incompatible with the current version. Please save the paramater file again." % (key_base, line_in, file_path_in)) cmd_token = self.sxcmd.token_dict[key_base] if not cmd_token.is_locked: @@ -1628,7 +1628,7 @@ def __init__(self, name, parent=None): custom_style = "QPushButton {color:gray; }" if cmd_token.restore: btn_name = "YES" - if cmd_token.type in parent.sxconst_set.dict.keys(): + if cmd_token.type in list(parent.sxconst_set.dict.keys()): custom_style = "QPushButton {color:green; }" cmd_token_restore_tooltip = const_cmd_token_restore_tooltip elif cmd_token.is_required: @@ -1663,7 +1663,7 @@ def __init__(self, name, parent=None): btn_name = "%s" % cmd_token.restore custom_style = "QPushButton {color:gray; }" is_btn_enable = True - if cmd_token.type in parent.sxconst_set.dict.keys(): + if cmd_token.type in list(parent.sxconst_set.dict.keys()): custom_style = "QPushButton {color:green; }" cmd_token_restore_tooltip = const_cmd_token_restore_tooltip elif cmd_token.is_required: @@ -2870,14 +2870,14 @@ def register_const_set(self): for sxcmd in sxcmd_category.cmd_list: # Loop through all command tokens of this command for cmd_token in sxcmd.token_list: - if not cmd_token.is_locked and cmd_token.type in self.sxconst_set.dict.keys(): + if not cmd_token.is_locked and cmd_token.type in list(self.sxconst_set.dict.keys()): sxconst = self.sxconst_set.dict[cmd_token.type] cmd_token.restore = sxconst.register cmd_token.restore_widget.setText("%s" % cmd_token.restore) cmd_token.widget.setText(cmd_token.restore) # print "MRK_DEBUG: %s, %s, %s, %s, %s, %s" % (sxcmd.name, sxcmd.subname, cmd_token.key_base, cmd_token.type, cmd_token.default, cmd_token.restore) elif cmd_token.type == "abs_freq": - assert("apix" in self.sxconst_set.dict.keys()) + assert("apix" in list(self.sxconst_set.dict.keys())) ### print("MRK_DEBUG: ----- register_const_set() ----- ") ### print("MRK_DEBUG: cmd_token.type = {}".format(cmd_token.type)) ### sxconst_apix = self.sxconst_set.dict["apix"] @@ -2946,7 +2946,7 @@ def read_consts(self, file_path_in): QMessageBox.warning(self, "Invalid Project Settings File Format", "Project settings entry should have \"%s\" closing entry key in line (%s) The format of this file might be corrupted. Please save the project settings file again." % (target_operator, line_in)) key = label_in[0:item_tail] # Get corresponding sxconst - if key not in self.sxconst_set.dict.keys(): + if key not in list(self.sxconst_set.dict.keys()): QMessageBox.warning(self, "Invalid Project Settings File Format", "Invalid entry key for project settings \"%s\" is found in line (%s). This project settings file might be incompatible with the current version. Please save the project settings file again." % (key, line_in)) sxconst = self.sxconst_set.dict[key] sxconst.widget.setText(val_str_in) diff --git a/sparx/templates/wikiparser.py b/sparx/templates/wikiparser.py index 7d97221ed4..d33aba592a 100755 --- a/sparx/templates/wikiparser.py +++ b/sparx/templates/wikiparser.py @@ -541,7 +541,7 @@ def construct_token_list_from_MoinMoinWiki(sxcmd_config): token.key_prefix = key[0:len(key) - len(token.key_base)] # Try to set the special type base on the keyword dictionary best_keyword_map = SXkeyword_map(99, "") - for keyword in keyword_dict.keys(): + for keyword in list(keyword_dict.keys()): if key.find(keyword) != -1: # command token contains keyword keyword_map = keyword_dict[keyword] @@ -577,7 +577,7 @@ def construct_token_list_from_MoinMoinWiki(sxcmd_config): continue line_buffer = line_buffer[item_tail + len(target_operator):].strip() # Get the rest of line # check consistency between 'usage in command line' and this - if key_base not in sxcmd.token_dict.keys(): ERROR("Wiki Format Error: Key base (%s) is missing from 'usage in command line' in '= Usage ='." % key_base, "%s in %s" % (__name__, os.path.basename(__file__))) + if key_base not in list(sxcmd.token_dict.keys()): ERROR("Wiki Format Error: Key base (%s) is missing from 'usage in command line' in '= Usage ='." % key_base, "%s in %s" % (__name__, os.path.basename(__file__))) # Get the reference to the command token object associated with this key base name token = sxcmd.token_dict[key_base] if token.key_base != key_base: ERROR("Logical Error: Registered command token with wrong key base name into the dictionary.", "%s in %s" % (__name__, os.path.basename(__file__))) @@ -934,7 +934,7 @@ def construct_token_list_from_DokuWiki(sxcmd_config): token.key_prefix = key[0:len(key) - len(token.key_base)] # Try to set the special type base on the keyword dictionary best_keyword_map = SXkeyword_map(99, "") - for keyword in keyword_dict.keys(): + for keyword in list(keyword_dict.keys()): if key.find(keyword) != -1: # command token contains keyword keyword_map = keyword_dict[keyword] @@ -1042,7 +1042,7 @@ def construct_token_list_from_DokuWiki(sxcmd_config): if current_state != state_done: ERROR("Wiki Format Error: parser could not extract all information necessary (current state %d). Please check if the Wiki format has all required sections." % (current_state), "%s in %s" % (__name__, os.path.basename(__file__))) - for sxcmd_token_key_base in sxcmd.token_dict.keys(): + for sxcmd_token_key_base in list(sxcmd.token_dict.keys()): # Make sure there are no extra arguments or options in command token dictionary compared with command token list. is_found = False for sxcmd_token in sxcmd.token_list: @@ -1060,7 +1060,7 @@ def construct_token_list_from_DokuWiki(sxcmd_config): for sxcmd_token in sxcmd.token_list: # Make sure there are no extra arguments or options in command token list compared with command token dictionary. - if sxcmd_token.key_base not in sxcmd.token_dict.keys(): ERROR("Logical Error: Registered key base name in the command token list is not registered as key base name in the command token dictionary.", "%s in %s" % (__name__, os.path.basename(__file__))) + if sxcmd_token.key_base not in list(sxcmd.token_dict.keys()): ERROR("Logical Error: Registered key base name in the command token list is not registered as key base name in the command token dictionary.", "%s in %s" % (__name__, os.path.basename(__file__))) # Make sure there are no extra arguments or options in command token list compared with usage token list extracted from "usage in command line" of "====== Usage ======". is_found = False for usage_token in usage_token_list: @@ -1071,7 +1071,7 @@ def construct_token_list_from_DokuWiki(sxcmd_config): for usage_token in usage_token_list: # Make sure there are no extra arguments or options in usage token list extracted from "usage in command line" of "====== Usage ======" compared with command token dictionary. - if usage_token.key_base not in sxcmd.token_dict.keys(): ERROR("Wiki Format Error: An extra argument or option (%s) is found in 'usage in command line' of '====== Usage ======' compared with the command token dictionary extracted from '===== Input =====' ." % usage_token.key_base, "%s in %s" % (__name__, os.path.basename(__file__))) + if usage_token.key_base not in list(sxcmd.token_dict.keys()): ERROR("Wiki Format Error: An extra argument or option (%s) is found in 'usage in command line' of '====== Usage ======' compared with the command token dictionary extracted from '===== Input =====' ." % usage_token.key_base, "%s in %s" % (__name__, os.path.basename(__file__))) # Make sure there are no extra arguments or options in usage token list extracted from "usage in command line" of "====== Usage ======" compared with command token list. is_found = False for sxcmd_token in sxcmd.token_list: @@ -1141,7 +1141,7 @@ def apply_sxsubcmd_config(sxsubcmd_config, sxcmd): # Using the first entry in token edit list as command mode token of this subset, # get mode token from sxcmd (having a fullset of tokens) mode_token_edit = sxsubcmd_config.token_edit_list[0] - if mode_token_edit.key_base not in fullset_token_dict.keys(): ERROR("Logical Error: This condition should not happen! Subset command configuration must be incorrect. Key (%s) should exists." % (mode_token_edit.key_base), "%s in %s" % (__name__, os.path.basename(__file__))) + if mode_token_edit.key_base not in list(fullset_token_dict.keys()): ERROR("Logical Error: This condition should not happen! Subset command configuration must be incorrect. Key (%s) should exists." % (mode_token_edit.key_base), "%s in %s" % (__name__, os.path.basename(__file__))) mode_token = fullset_token_dict[mode_token_edit.key_base] # Create mode name of this subset, append key base of mode token to mode_name of this command @@ -1181,7 +1181,7 @@ def apply_sxsubcmd_config(sxsubcmd_config, sxcmd): if token_edit.key_base == "": ERROR("Logical Error: This condition should not happen! Subset command configuration must be incorrect. Invalid empty string Key (%s)." % (token_edit.key_base) , "%s in %s" % (__name__, os.path.basename(__file__))) token = None - if token_edit.key_base not in fullset_token_dict.keys(): + if token_edit.key_base not in list(fullset_token_dict.keys()): # token key base is not found in fullset. This must be an argument to be added if token_edit.key_prefix is None: ERROR("Logical Error: This condition should not happen! Subset command configuration must be incorrect. Prefix (%s) for Key (%s) should NOT be None." % (token_edit.key_prefix, token_edit.key_base) , "%s in %s" % (__name__, os.path.basename(__file__))) if token_edit.key_prefix != "": ERROR("Logical Error: This condition should not happen! Subset command configuration must be incorrect. Key (%s) should be argument (Prefix (%s) should be empty string)." % (token_edit.key_base, token_edit.key_prefix) , "%s in %s" % (__name__, os.path.basename(__file__)))