Example #1
0
def main():
	progname = os.path.basename(sys.argv[0])
	usage = """prog [options] <image file>

	Provides a GUI interface for applying a sequence of processors to an image, stack of images or a volume."""

	parser = EMArgumentParser(usage=usage,version=EMANVERSION)

#	parser.add_argument("--boxsize","-B",type=int,help="Box size in pixels",default=64)
#	parser.add_argument("--shrink",type=int,help="Shrink factor for full-frame view, default=0 (auto)",default=0)
	parser.add_argument("--apix",type=float,help="Override the A/pix value stored in the file header",default=0.0)
#	parser.add_argument("--force2d",action="store_true",help="Display 3-D data as 2-D slices",default=False)
	parser.add_argument("--ppid", type=int, help="Set the PID of the parent process, used for cross platform PPID",default=-1)
	parser.add_argument("--verbose", "-v", dest="verbose", action="store", metavar="n", type=int, default=0, help="verbose level [0-9], higner number means higher level of verboseness")

	(options, args) = parser.parse_args()

	if len(args) != 1: parser.error("You must specify a single data file on the command-line.")
	if not file_exists(args[0]): parser.error("%s does not exist" %args[0])
#	if options.boxsize < 2: parser.error("The boxsize you specified is too small")
#	# The program will not run very rapidly at such large box sizes anyhow
#	if options.boxsize > 2048: parser.error("The boxsize you specified is too large.\nCurrently there is a hard coded max which is 2048.\nPlease contact developers if this is a problem.")

#	logid=E2init(sys.argv,options.ppid)

	app = EMApp()
	pix_init()
	control=EMFilterTool(datafile=args[0],apix=options.apix,force2d=False,verbose=options.verbose)
#	control=EMFilterTool(datafile=args[0],apix=options.apix,force2d=options.force2d,verbose=options.verbose)
	control.show()
	try: control.raise_()
	except: pass

	app.execute()
Example #2
0
def main():
	# an application
	em_app = EMApp()
	control1=TestControl(em_app)
	control2=TestControl(em_app)

	em_app.execute()
Example #3
0
def main():
	progname = os.path.basename(sys.argv[0])
	usage = """prog  <projection file>  <particles file>
	
Compare different similarity metrics for a given particle stack. Note that all particles and projections are
read into memory. Do not use it on large sets of particles !!!
"""

	parser = EMArgumentParser(usage=usage,version=EMANVERSION)
	parser.add_argument("--ppid", type=int, help="Set the PID of the parent process, used for cross platform PPID",default=-1)

	(options, args) = parser.parse_args()
	
	if len(args)<2 :
		print "Error, please specify projection file and particles file"
		sys.exit(1)
	
	logid=E2init(sys.argv,options.ppid)
	
	em_app = EMApp()
	window = EM3DGLWidget() #TODO: see if this should be a subclass of EMSymViewerWidget instead
	explorer = EMCmpExplorer(window)
	window.set_model(explorer)
	explorer.set_data(args[0],args[1])

	em_app.show()
	em_app.execute()
	
	E2end(logid)
Example #4
0
def main():
	
	usage="[prog] <2D image file> "
	parser = EMArgumentParser(usage=usage,version=EMANVERSION)
	(options, args) = parser.parse_args()
	logid=E2init(sys.argv)


	
	filename=args[0]
	
	app = EMApp()
	img=EMData(filename)
	
	
	#print img[0]["mean"]
	w=EMBreakBrick(img,app)
	#w.set_data(img,filename)
	
	app.show_specific(w)
	app.exec_()
	
	
	
	
	
	E2end(logid)
Example #5
0
def main():
	progname = os.path.basename(sys.argv[0])
	usage = """prog

	Presents a graphical representation of the orientation distribution of the particles in a single particle
	reconstruction. This is displayed as a single asymmetric unit on a sphere, with cylinders of varying height
	representing the number of particles found in each orientation. Middle-click will produce a control-panel
	as usual, and clicking on a single peak will permit viewing the class-average and related projection
	(and particles).

	Normally launched without arguments from a e2workflow project directory.

"""

	parser = EMArgumentParser(usage=usage,version=EMANVERSION)
	parser.add_header(name="e2eulerxplorheader", help="Click Launch to Run e2eulerxplor.py", title="### Click Launch to Run e2eulerxplor.py ###", row=0, col=0, rowspan=1, colspan=3)
	parser.add_argument("--eulerdata", "-e", type=str,help="File for Eulerdata, Ryan style, if none is given, data is read from the DB.",default=None)
	parser.add_argument("--ppid", type=int, help="Set the PID of the parent process, used for cross platform PPID",default=-1)
	parser.add_argument("--verbose", "-v", dest="verbose", action="store", metavar="n", type=int, default=0, help="verbose level [0-9], higner number means higher level of verboseness")

	global options
	(options, args) = parser.parse_args()


	logid=E2init(sys.argv,options.ppid)

	em_app = EMApp()
	window = EMEulerWidget(file_name = options.eulerdata)
	em_app.show_specific(window)
	em_app.execute()

	E2end(logid)
Example #6
0
def main():

    usage = "Electron Microscope simulation"
    parser = EMArgumentParser(usage=usage, version=EMANVERSION)
    parser.add_argument(
        "--mode",
        type=int,
        help=
        "operating mode. 0: imaging mode with all lens; 1:diffraction mode with all lens; 2: imaging mode with single lens and phase plate; else: imaging mode with one lens.",
        default=0)
    parser.add_argument("--cs",
                        type=float,
                        help="Cs of microscope.",
                        default=0.0)
    parser.add_argument(
        "--twod",
        action="store_true",
        help=
        "Show twod image instead of 1D plot and beam propagation in the microscope.",
        default=False)
    (options, args) = parser.parse_args()
    logid = E2init(sys.argv)

    app = EMApp()
    #	app=QtGui.QApplication([""])

    window = MainWindow(options.mode, options.cs, options.twod)
    window.show()

    app.execute()

    E2end(logid)
Example #7
0
def main():
    # an application
    em_app = EMApp()
    control1 = TestControl(em_app)
    control2 = TestControl(em_app)

    em_app.execute()
Example #8
0
def main():
	progname = os.path.basename(sys.argv[0])
	usage = """prog [classfile]

	This program provides tools for evaluating particle data in various ways. For example it will allow you to select class-averages
	containing bad (or good) particles and manipulate the project to in/exclude them. It will locate files with class-averages automatically,
	but you can specify additional files at the command-line.

"""

	parser = EMArgumentParser(usage=usage,version=EMANVERSION)

	parser.add_header(name="runeval", help='Click Launch to launch the particle evaluation interface', title="### Click Launch to run e2evalparticles ###", row=0, col=0, rowspan=1, colspan=1)
	parser.add_argument("--gui",action="store_true",help="Start the GUI for interactive use (default=True)",default=True)
	parser.add_argument("--ppid", type=int, help="Set the PID of the parent process, used for cross platform PPID",default=-1)
	parser.add_argument("--verbose", "-v", dest="verbose", action="store", metavar="n", type=int, default=0, help="verbose level [0-9], higner number means higher level of verboseness")

	(options, args) = parser.parse_args()

	#logid=E2init(sys.argv, options.ppid)

	app = EMApp()
	control=EMEvalPtclTool(args,verbose=options.verbose)
	control.show()
	app.execute()
Example #9
0
def main():
	progname = os.path.basename(sys.argv[0])
	usage = """prog [classfile]

	This program provides tools for evaluating particle data in various ways. For example it will allow you to select class-averages
	containing bad (or good) particles and manipulate the project to in/exclude them. It will locate files with class-averages automatically,
	but you can specify additional files at the command-line.

"""

	parser = EMArgumentParser(usage=usage,version=EMANVERSION)

	parser.add_header(name="runeval", help='Click Launch to launch the particle evaluation interface', title="### Click Launch to run e2evalparticles ###", row=0, col=0, rowspan=1, colspan=1)
	parser.add_argument("--gui",action="store_true",help="Start the GUI for interactive use (default=True)",default=True)
	parser.add_argument("--ppid", type=int, help="Set the PID of the parent process, used for cross platform PPID",default=-1)
	parser.add_argument("--verbose", "-v", dest="verbose", action="store", metavar="n", type=int, default=0, help="verbose level [0-9], higner number means higher level of verboseness")

	(options, args) = parser.parse_args()

	#logid=E2init(sys.argv, options.ppid)

	app = EMApp()
	control=EMEvalPtclTool(args,verbose=options.verbose)
	control.show()
	app.execute()
Example #10
0
def main():
    global debug, logid
    progname = os.path.basename(sys.argv[0])
    usage = """%prog [options]

This program allows the user to play around with Fourier synthesis graphically
	
"""

    parser = OptionParser(usage=usage, version=EMANVERSION)

    #	parser.add_option("--gui",action="store_true",help="Start the GUI for interactive fitting",default=False)
    parser.add_option(
        "--verbose",
        "-v",
        dest="verbose",
        action="store",
        metavar="n",
        type="int",
        default=0,
        help=
        "verbose level [0-9], higner number means higher level of verboseness")

    (options, args) = parser.parse_args()

    app = EMApp()
    win = GUIFourierSynth(app)
    win.show()
    try:
        win.raise_()
        win.synthplot.raise_()
    except:
        pass
    app.exec_()
Example #11
0
def main():
	progname = os.path.basename(sys.argv[0])
	usage = """prog 3Dstack [options]
	Visulaizse and compute the mean amplitude and sigma in the missing wedge region. After you are sasified that the missing wedge looks sane, compute missing wedge stats
	on all volumes. These stats are used by the aligner tomo.fsc, for subtomogram alignment and averaging.
	"""
	
	parser = EMArgumentParser(usage=usage,version=EMANVERSION)
	
	parser.add_pos_argument(name="tdstack",help="The 3D stack to examine.", default="", guitype='filebox',  row=0, col=0,rowspan=1, colspan=2)
	parser.add_header(name="wedgeheader", help='Options below this label are specific to e2wedge', title="### e2wedge options ###", row=1, col=0, rowspan=1, colspan=2)
	parser.add_argument("--wedgeangle",type=float,help="Missing wedge angle",default=60.0, guitype='floatbox', row=2, col=0, rowspan=1, colspan=1)
	parser.add_argument("--wedgei",type=float,help="Missingwedge begining", default=0.05)
	parser.add_argument("--wedgef",type=float,help="Missingwedge ending", default=0.5)
	parser.add_argument("--ppid", type=int, help="Set the PID of the parent process, used for cross platform PPID",default=-1)
	parser.add_argument("--nogui", action="store_true", default=False, help="Do not launch the GUI and set the average of the missing wedge statistics on all the volumes.")
	parser.add_argument("--averagestats", action="store_true", default=False, help="Do not launch the GUI and set the average of the missing wedge statistics on all the volumes.")

	(options, args) = parser.parse_args()
	
	stack=args[0]
	
	if not options.nogui:	
		em_app = EMApp()
		wedgeviewer = MissingWedgeViewer(stack, options.wedgeangle, wedgei=options.wedgei, wedgef=options.wedgef)
		wedgeviewer.show()
		ret=em_app.exec_()
		sys.exit(ret)
	else:
		means=[]
		sigmas=[]
		
		n=EMUtil.get_image_count(stack)
		for i in range(n):
			a = EMData(stack,i)
			retr = wedgestats(a,options.wedgeangle,options.wedgei,options.wedgef)
			mean = retr[0]
			sigma = retr[1]
			
			if options.averagestats:
				means.append(mean)
				sigmas.append(sigma)
			else:
				a['spt_wedge_mean'] = mean
				a['spt_wedge_sigma'] = sigma
				print "The mean and sigma for subvolume %d are: mean=%f, sigma=%f" % (i,mean,sigma)
				a.write_image(stack,i)
		
		if options.averagestats:
			meanavg = sum(means)/len(means)
			sigmaavg = sum(sigmas)/len(sigmas)
			
			print "The average mean and sigma for the wedges in the stack are", meanavg, sigmaavg
			for i in range(n):
				a = EMData(stack,i)
				a['spt_wedge_mean'] = meanavg
				a['spt_wedge_sigma'] = sigmaavg
				a.write_image(stack,i)
	return()
Example #12
0
def main():
	from emapplication import EMApp

	em_app = EMApp()
	
	pref_task = EMPreferencesTask()
	pref_task.run_form()
	em_app.execute()
Example #13
0
def main():
    from emapplication import EMApp

    em_app = EMApp()

    pref_task = EMPreferencesTask()
    pref_task.run_form()
    em_app.execute()
Example #14
0
def main():
	global cur_data,data,imdisp
	
	# an application
	em_app = EMApp()

	widget=TestDisplay()
	widget.show()

	em_app.execute()
Example #15
0
def main():
    progname = os.path.basename(sys.argv[0])
    usage = """%prog [options] <input ali>
	
This program will allow the user to select a specific feature within a tomogram and track it, boxing out the
feature from all slices. Generally best for uniform objects like vesicles."""

    parser = OptionParser(usage=usage, version=EMANVERSION)

    parser.add_option("--prefix",
                      type="string",
                      help="Output file prefix",
                      default=None)
    parser.add_option("--tiltstep",
                      type="float",
                      help="Step between tilts in degrees, default=2",
                      default=2.0)
    parser.add_option("--maxshift",
                      type="int",
                      help="Maximum shift in autoalign, default=8",
                      default=8)
    parser.add_option(
        "--seqali",
        action="store_true",
        default=False,
        help=
        "Average particles in previous slices for better alignments of near-spherical objects"
    )
    parser.add_option("--invert",
                      action="store_true",
                      default=False,
                      help="Inverts image data contrast on the fly")

    #parser.add_option("--boxsize","-B",type="int",help="Box size in pixels",default=64)
    #parser.add_option("--writeoutput",action="store_true",default=False,help="Uses coordinates stored in the tomoboxer database to write output")
    #parser.add_option("--stack",action="store_true",default=False,help="Causes the output images to be written to a stack")
    #parser.add_option("--force",action="store_true",default=False,help="Force overwrite output")
    #parser.add_option("--normproc", help="Normalization processor to apply to particle images. Should be normalize, normalize.edgemean or None", default="normalize.edgemean")
    #parser.add_option("--invertoutput",action="store_true",help="If writing output only, this will invert the pixel intensities of the boxed files",default=False)
    #parser.add_option("--dbls",type="string",help="data base list storage, used by the workflow. You can ignore this argument.",default=None)
    #parser.add_option("--outformat", help="Format of the output particles images, should be bdb,img, or hdf", default="bdb")

    (options, args) = parser.parse_args()

    logid = E2init(sys.argv)

    app = EMApp()

    track = TrackerControl(app, options.maxshift, options.invert,
                           options.seqali, options.tiltstep)
    track.set_image(args[0])

    app.execute()

    E2end(logid)
Example #16
0
def main():
	progname = os.path.basename(sys.argv[0])
	usage = """prog [classfile]

	THIS PROGRAM IS NOT YET COMPLETE

	This program allows you to manually mark bad particles via a graphical interface.

"""

	parser = EMArgumentParser(usage=usage,version=EMANVERSION)

	parser.add_pos_argument(name="particles",help="List the file to process with e2ctf here.", default="", guitype='filebox', browser="EMCTFParticlesTable(withmodal=True,multiselect=True)",  filecheck=False, row=0, col=0,rowspan=1, colspan=2, mode='autofit,tuning,genoutp,gensf')
	parser.add_argument("--allparticles",action="store_true",help="Will process all particle stacks stored in the particles subdirectory (no list of files required)",default=False, guitype='boolbox',row=1, col=0, mode='autofit,tuning,genoutp,gensf')
	parser.add_argument("--minptcl",type=int,help="Files with fewer than the specified number of particles will be skipped",default=0,guitype='intbox', row=2, col=0, mode='autofit,tuning,genoutp,gensf')
	parser.add_argument("--minqual",type=int,help="Files with a quality value lower than specified will be skipped",default=0,guitype='intbox', row=2, col=1, mode='autofit,tuning,genoutp,gensf')
	parser.add_argument("--gui",action="store_true",help="Start the GUI for interactive use (default=True)",default=True)
	parser.add_argument("--ppid", type=int, help="Set the PID of the parent process, used for cross platform PPID",default=-1)
	parser.add_argument("--verbose", "-v", dest="verbose", action="store", metavar="n", type=int, default=0, help="verbose level [0-9], higner number means higher level of verboseness")

	(options, args) = parser.parse_args()

	if options.allparticles:
		args=["particles/"+i for i in os.listdir("particles") if "__" not in i and i[0]!="." and ".hed" not in i ]
		args.sort()
		if options.verbose : print "%d particle stacks identified"%len(args)

	# remove any files that don't have enough particles from the list
	if options.minptcl>0 :
		args=[i for i in args if imcount(i)>=options.minptcl]
		if options.verbose: print "{} stacks after minptcl filter".format(len(args))


	# remove files with quality too low
	if options.minqual>0 :
		outargs=[]
		for i in args:
			try:
				if js_open_dict(info_name(i))["quality"]>=options.minqual : outargs.append(i)
			except:
#				traceback.print_exc()
				print "Unknown quality for {}, including it".format(info_name(i))
				outargs.append(i)

		args=outargs

		if options.verbose: print "{} stacks after quality filter".format(len(args))
	#logid=E2init(sys.argv, options.ppid)

	app = EMApp()
	control=EMMarkPtclTool(args,verbose=options.verbose)
	control.show()
	app.execute()
Example #17
0
def main():

    progname = os.path.basename(sys.argv[0])
    usage = """e2pdbviewer.py <project directory>
	
	A wrapper program to view a .pdb file on your computer. This is simply an PDB
	specific interface to the more general EMScene3D viewer.
	"""
    parser = EMArgumentParser(usage=usage, version=EMANVERSION)
    parser.add_argument(
        "--pdbfiles",
        type=str,
        help="Specify one or mode pdb files you \
		wish to view",
        nargs="*",
        required=False,
        default=None,
    )
    parser.add_argument(
        "--ppid",
        type=int,
        help="Set the PID of the parent \
		process, used for cross platform PPID",
        default=-1,
    )
    parser.add_argument(
        "--verbose",
        "-v",
        dest="verbose",
        action="store",
        metavar="n",
        type=int,
        default=0,
        help="verbose level [0-9], higner \
		number means higher level of verboseness",
    )
    (options, args) = parser.parse_args()

    logid = E2init(sys.argv, options.ppid)

    app = EMApp()
    viewer = EMScene3D()

    if options.pdbfiles:
        models = [EMStructureItem3D(pdb_file=pdbf) for pdbf in options.pdbfiles]
        viewer.addChildren(models)

    viewer.show()
    app.execute()

    E2end(logid)
Example #18
0
def main():
    progname = os.path.basename(sys.argv[0])
    usage = """prog [options]

	WARNING: This program still under development.
	
	This program is used to interactively generate sequences of class-averages from sets of particles. It can be
	used for many purposes, but is primarily intended at studies of macromolecular dynamics and variability. A stack
	of particles ostensibly in the same 3-D (but not 2-D) orientation are read in, then alignment, classification
	and averaging is performed to produce pseudo time-series animations detailing some aspect of the structure's
	variability.
	
	This program is NOT designed for use with stacks of tens of thousands of images. All images are kept in system
	memory. All images are theoretically supposed to share a common overall orientation. That is, for a normal single
	particle project, you would first subclassify the overall image stack used for 3-D using e2refine2d.py or
	e2refine.py, then run this program only on a subset of particles.
	
	If an existing project is specified with --path, previous results will be re-opened"""

    parser = EMArgumentParser(usage=usage, version=EMANVERSION)

    parser.add_argument("--path",
                        type=str,
                        default=None,
                        help="Path for the refinement, default=auto")
    parser.add_argument(
        "--ppid",
        type=int,
        help="Set the PID of the parent process, used for cross platform PPID",
        default=-1)

    global options
    (options, args) = parser.parse_args()

    if options.path == None:
        options.path = numbered_path("motion", True)


#		os.makedirs(options.path)

    pid = E2init(argv)

    app = EMApp()
    motion = EMMotion(app, options.path)
    motion.show()
    app.execute()

    E2end(pid)
Example #19
0
def display_validation_plots(path,
                             radcut,
                             planethres,
                             plotdatalabels=False,
                             color='#00ff00',
                             plotzaxiscolor=False):
    from emimage2d import EMImage2DWidget
    from emapplication import EMApp
    r = []
    theta = []
    datap = []
    zaxis = []

    try:
        tpdb = js_open_dict("%s/perparticletilts.json" % path)
        tplist = tpdb["particletilt_list"]
        maxcolorval = max(tplist, key=lambda x: x[3])[3]

        for tp in tplist:
            if tp[3] > planethres:  # if the out of plane threshold is too much
                continue
            if plotdatalabels: datap.append(tp[0])
            r.append(tp[1])
            theta.append(math.radians(tp[2]))
            # Color the Z axis out of planeness
            zaxis.append(computeRGBcolor(tp[3], 0, maxcolorval))
        tpdb.close()
    except:
        print "Couldn't load tp from DB, not showing polar plot"
    data = None
    try:
        data = EMData("%s/contour.hdf" % path)
    except:
        print "Couldn't open contour plot"

    if not data and not (theta and r): return
    app = EMApp()
    if theta and r:
        plot = EMValidationPlot()
        plot.set_data((theta, r), 50, radcut, datap)
        # Color by Z axis if desired
        if plotzaxiscolor: plot.set_scattercolor([zaxis])
        plot.set_datalabelscolor(color)
        plot.show()
    if data:
        image = EMImage2DWidget(data)
        image.show()
    app.exec_()
Example #20
0
def main():
	global debug,logid
	progname = os.path.basename(sys.argv[0])
	usage = """prog [options] <single image file> ...

This program will allow you to evaluate an individual scanned micrograph or CCD frame, by looking at its
power spectrum in various ways."""

	parser = EMArgumentParser(usage=usage,version=EMANVERSION)

	parser.add_pos_argument(name="image",help="Image to process with e2evalimage.", default="", guitype='filebox', browser="EMBrowserWidget(withmodal=True,multiselect=True)",  row=0, col=0,rowspan=1, colspan=2, mode="eval")
	parser.add_header(name="evalimageheader", help='Options below this label are specific to e2evalimage', title="### e2evalimage options ###", default=None, row=1, col=0, rowspan=1, colspan=2, mode="eval")

	parser.add_argument("--gui",action="store_true",help="This is a GUI-only program. This option is provided for self-consistency",default=True)
	parser.add_argument("--apix",type=float,help="Angstroms per pixel for all images",default=None, guitype='floatbox', row=3, col=0, rowspan=1, colspan=1, mode="eval['self.pm().getAPIX()']")
	parser.add_argument("--constbfactor",type=float,help="Set B-factor to fixed specified value, negative value autofits",default=-1.0, guitype='floatbox', row=8, col=0, rowspan=1, colspan=1, mode='eval[-1.0]')
	parser.add_argument("--voltage",type=float,help="Microscope voltage in KV",default=None, guitype='floatbox', row=3, col=1, rowspan=1, colspan=1, mode="eval['self.pm().getVoltage()']")
	parser.add_argument("--cs",type=float,help="Microscope Cs (spherical aberation)",default=None, guitype='floatbox', row=4, col=0, rowspan=1, colspan=1, mode="eval['self.pm().getCS()']")
	parser.add_argument("--ac",type=float,help="Amplitude contrast (percentage, default=10)",default=10, guitype='floatbox', row=4, col=1, rowspan=1, colspan=1, mode="eval")
	parser.add_argument("--phaseplate",action="store_true",help="Include phase/amplitude contrast in CTF estimation. For use with hole-less phase plates.",default=False, guitype='boolbox', row=3, col=2, rowspan=1, colspan=1, mode='filter[False]')
	parser.add_argument("--astigmatism",action="store_true",help="Includes astigmatism in automatic fitting",default=False, guitype='boolbox', row=8, col=1, rowspan=1, colspan=1, mode='eval')
	parser.add_argument("--box",type=int,help="Forced box size in grid mode. Overrides any previous setting. ",default=-1, guitype='intbox', row=5, col=0, rowspan=1, colspan=1, mode="eval")
	parser.add_argument("--usefoldername",action="store_true",help="If you have the same image filename in multiple folders, and need to import into the same project, this will prepend the folder name on each image name",default=False,guitype='boolbox',row=5, col=1, rowspan=1, colspan=1, mode="eval")
	parser.add_argument("--ppid", type=int, help="Set the PID of the parent process, used for cross platform PPID",default=-1)
	parser.add_argument("--verbose", "-v", dest="verbose", action="store", metavar="n", type=int, default=0, help="verbose level [0-9], higner number means higher level of verboseness")

	(options, args) = parser.parse_args()

	logid=E2init(sys.argv,options.ppid)

	from emapplication import EMApp
	app=EMApp()
	gui=GUIEvalImage(args,options.voltage,options.apix,options.cs,options.ac,options.box,options.usefoldername,options.constbfactor,options.astigmatism,options.phaseplate)
	gui.show()

	try:
		gui.wimage.raise_()
		gui.wfft.raise_()
		gui.wplot.raise_()
		gui.raise_()
	except: pass

# 	try: gui.raise_()
# 	except: pass
	app.execute()

	E2end(logid)
Example #21
0
def main():
	global debug,logid
	progname = os.path.basename(sys.argv[0])
	usage = """prog [options] <single image file> ...

This program will allow you to evaluate an individual scanned micrograph or CCD frame, by looking at its
power spectrum in various ways."""

	parser = EMArgumentParser(usage=usage,version=EMANVERSION)

	parser.add_pos_argument(name="image",help="Image to process with e2evalimage.", default="", guitype='filebox', browser="EMBrowserWidget(withmodal=True,multiselect=True)",  row=0, col=0,rowspan=1, colspan=2, mode="eval")
	parser.add_header(name="evalimageheader", help='Options below this label are specific to e2evalimage', title="### e2evalimage options ###", default=None, row=1, col=0, rowspan=1, colspan=2, mode="eval")

	parser.add_argument("--gui",action="store_true",help="This is a GUI-only program. This option is provided for self-consistency",default=True)
	parser.add_argument("--apix",type=float,help="Angstroms per pixel for all images",default=None, guitype='floatbox', row=3, col=0, rowspan=1, colspan=1, mode="eval['self.pm().getAPIX()']")
	parser.add_argument("--constbfactor",type=float,help="Set B-factor to fixed specified value, negative value autofits",default=-1.0, guitype='floatbox', row=8, col=0, rowspan=1, colspan=1, mode='eval[-1.0]')
	parser.add_argument("--voltage",type=float,help="Microscope voltage in KV",default=None, guitype='floatbox', row=3, col=1, rowspan=1, colspan=1, mode="eval['self.pm().getVoltage()']")
	parser.add_argument("--cs",type=float,help="Microscope Cs (spherical aberation)",default=None, guitype='floatbox', row=4, col=0, rowspan=1, colspan=1, mode="eval['self.pm().getCS()']")
	parser.add_argument("--ac",type=float,help="Amplitude contrast (percentage, default=10)",default=10, guitype='floatbox', row=4, col=1, rowspan=1, colspan=1, mode="eval")
	parser.add_argument("--astigmatism",action="store_true",help="Includes astigmatism in automatic fitting",default=False, guitype='boolbox', row=8, col=1, rowspan=1, colspan=1, mode='eval')
	parser.add_argument("--box",type=int,help="Forced box size in grid mode. Overrides any previous setting. ",default=-1, guitype='intbox', row=5, col=0, rowspan=1, colspan=1, mode="eval")
	parser.add_argument("--usefoldername",action="store_true",help="If you have the same image filename in multiple folders, and need to import into the same project, this will prepend the folder name on each image name",default=False,guitype='boolbox',row=5, col=1, rowspan=1, colspan=1, mode="eval")
	parser.add_argument("--ppid", type=int, help="Set the PID of the parent process, used for cross platform PPID",default=-1)
	parser.add_argument("--verbose", "-v", dest="verbose", action="store", metavar="n", type=int, default=0, help="verbose level [0-9], higner number means higher level of verboseness")

	(options, args) = parser.parse_args()

	logid=E2init(sys.argv,options.ppid)

	from emapplication import EMApp
	app=EMApp()
	gui=GUIEvalImage(args,options.voltage,options.apix,options.cs,options.ac,options.box,options.usefoldername,options.constbfactor,options.astigmatism)
	gui.show()

	try:
		gui.wimage.raise_()
		gui.wfft.raise_()
		gui.wplot.raise_()
		gui.raise_()
	except: pass

# 	try: gui.raise_()
# 	except: pass
	app.execute()

	E2end(logid)
Example #22
0
def main():

    usage = " "
    parser = EMArgumentParser(usage=usage, version=EMANVERSION)
    parser.add_argument("--load", type=str, help="load text", default=None)
    #parser.add_argument("--noupdate", action="store_true",help="do not erase shapes", default=False)
    (options, args) = parser.parse_args()
    logid = E2init(sys.argv)
    img = EMData(args[0])

    app = EMApp()

    drawer = EMDrawWindow(app, options, datafile=img)

    drawer.show()
    app.execute()
    E2end(logid)
Example #23
0
def display_validation_plots(path, radcut, planethres, plotdatalabels=False, color='#00ff00', plotzaxiscolor=False):
	from emimage2d import EMImage2DWidget
	from emapplication import EMApp
	r = []
	theta = []
	datap = []
	zaxis = []
	
	try:
		tpdb = js_open_dict("%s/perparticletilts.json"%path)
		tplist = tpdb["particletilt_list"]
		maxcolorval = max(tplist, key=lambda x: x[3])[3]

		for tp in tplist:
			if tp[3] > planethres:	# if the out of plane threshold is too much
				continue
			if plotdatalabels: datap.append(tp[0])
			r.append(tp[1])
			theta.append(math.radians(tp[2]))
			# Color the Z axis out of planeness
			zaxis.append(computeRGBcolor(tp[3],0,maxcolorval))
		tpdb.close()
	except:
		print "Couldn't load tp from DB, not showing polar plot"
	data = None	
	try:
		data = EMData("%s/contour.hdf"%path)
	except:
		print "Couldn't open contour plot"
	
	if not data and not (theta and r): return
	app = EMApp()
	if theta and r:
		plot = EMValidationPlot()
		plot.set_data((theta,r),50,radcut,datap)
		# Color by Z axis if desired
		if plotzaxiscolor: plot.set_scattercolor([zaxis])
		plot.set_datalabelscolor(color)
		plot.show()
	if data:
		image = EMImage2DWidget(data)
		image.show()
	app.exec_()
Example #24
0
def main():

    progname = os.path.basename(sys.argv[0])
    usage = """e2pdbviewer.py <project directory>
	
	A wrapper program to view a .pdb file on your computer. This is simply an PDB
	specific interface to the more general EMScene3D viewer.
	"""
    parser = EMArgumentParser(usage=usage, version=EMANVERSION)
    parser.add_argument("--pdbfiles",
                        type=str,
                        help="Specify one or mode pdb files you \
		wish to view",
                        nargs='*',
                        required=False,
                        default=None)
    parser.add_argument("--ppid",
                        type=int,
                        help="Set the PID of the parent \
		process, used for cross platform PPID",
                        default=-1)
    parser.add_argument("--verbose", "-v", dest="verbose", action="store", \
     metavar="n", type=int, default=0, help="verbose level [0-9], higner \
		number means higher level of verboseness"                                              )
    (options, args) = parser.parse_args()

    logid = E2init(sys.argv, options.ppid)

    app = EMApp()
    viewer = EMScene3D()

    if options.pdbfiles:
        models = [
            EMStructureItem3D(pdb_file=pdbf) for pdbf in options.pdbfiles
        ]
        viewer.addChildren(models)

    viewer.show()
    app.execute()

    E2end(logid)
Example #25
0
def main():
    progname = os.path.basename(sys.argv[0])
    usage = """prog  <projection file>  <particles file>
	
Compare different similarity metrics for a given particle stack. Note that all particles and projections are
read into memory. Do not use it on large sets of particles !!!
"""

    parser = EMArgumentParser(usage=usage, version=EMANVERSION)
    parser.add_argument(
        "--ppid",
        type=int,
        help="Set the PID of the parent process, used for cross platform PPID",
        default=-1)

    (options, args) = parser.parse_args()

    if len(args) < 2:
        print "Error, please specify projection file and particles file"
        sys.exit(1)

    logid = E2init(sys.argv, options.ppid)

    em_app = EMApp()
    window = EM3DGLWidget(
    )  #TODO: see if this should be a subclass of EMSymViewerWidget instead
    explorer = EMCmpExplorer(window)
    window.set_model(explorer)
    explorer.set_data(args[0], args[1])

    em_app.show()
    em_app.execute()

    E2end(logid)
Example #26
0
def main():
	progname = os.path.basename(sys.argv[0])
	usage = """prog

	Presents a graphical representation of the orientation distribution of the particles in a single particle
	reconstruction. This is displayed as a single asymmetric unit on a sphere, with cylinders of varying height
	representing the number of particles found in each orientation. Middle-click will produce a control-panel
	as usual, and clicking on a single peak will permit viewing the class-average and related projection
	(and particles).

	Normally launched without arguments from a e2workflow project directory.

"""

	parser = EMArgumentParser(usage=usage,version=EMANVERSION)
	parser.add_header(name="e2eulerxplorheader", help="Click Launch to Run e2eulerxplor.py", title="### Click Launch to Run e2eulerxplor.py ###", row=0, col=0, rowspan=1, colspan=3)
	parser.add_argument("--eulerdata", "-e", type=str,help="File for Eulerdata, Ryan style, if none is given, data is read from the DB.",default=None)
	parser.add_argument("--ppid", type=int, help="Set the PID of the parent process, used for cross platform PPID",default=-1)
	parser.add_argument("--verbose", "-v", dest="verbose", action="store", metavar="n", type=int, default=0, help="verbose level [0-9], higner number means higher level of verboseness")

	global options
	(options, args) = parser.parse_args()


	logid=E2init(sys.argv,options.ppid)

	em_app = EMApp()
	window = EMEulerWidget(file_name = options.eulerdata, read_from=args)
	em_app.show_specific(window)
	em_app.execute()

	E2end(logid)
Example #27
0
def main():
	progname = os.path.basename(sys.argv[0])
	usage = """prog [options]

	WARNING: This program still under development.
	
	This program is used to interactively generate sequences of class-averages from sets of particles. It can be
	used for many purposes, but is primarily intended at studies of macromolecular dynamics and variability. A stack
	of particles ostensibly in the same 3-D (but not 2-D) orientation are read in, then alignment, classification
	and averaging is performed to produce pseudo time-series animations detailing some aspect of the structure's
	variability.
	
	This program is NOT designed for use with stacks of tens of thousands of images. All images are kept in system
	memory. All images are theoretically supposed to share a common overall orientation. That is, for a normal single
	particle project, you would first subclassify the overall image stack used for 3-D using e2refine2d.py or
	e2refine.py, then run this program only on a subset of particles.
	
	If an existing project is specified with --path, previous results will be re-opened"""

	parser = EMArgumentParser(usage=usage,version=EMANVERSION)

	parser.add_argument("--path",type=str,default=None,help="Path for the refinement, default=auto")
	parser.add_argument("--ppid", type=int, help="Set the PID of the parent process, used for cross platform PPID",default=-1)

	global options
	(options, args) = parser.parse_args()
	
	if options.path==None:
		options.path=numbered_path("motion",True)
#		os.makedirs(options.path)

	pid=E2init(argv)
	
	app = EMApp()
	motion=EMMotion(app,options.path)
	motion.show()
	app.execute()
	
	E2end(pid)
Example #28
0
def main():
	progname = os.path.basename(sys.argv[0])
	usage = progname + """ [options] <xml>
	Convert xml to txt and optionally display them.
	"""
	
	args_def = {'display':1}	
	parser = argparse.ArgumentParser()
	parser.add_argument("xml", nargs='*', help="specify xml files to be processed")
	parser.add_argument("-d", "--display", type=int, help="disply (1) or not (0), by default {}".format(args_def['display']))
	args = parser.parse_args()
	
	if len(sys.argv) == 1:
		print "usage: " + usage
		print "Please run '" + progname + " -h' for detailed options."
		sys.exit(1)
	# get default values
	for i in args_def:
		if args.__dict__[i] == None:
			args.__dict__[i] = args_def[i]
	#		
	for xml in args.xml:
		with open(xml+'.txt', 'w') as w_txt:
			for coord in XE.parse(xml).getroot():
				for xy in coord:
					if xy.tag == 'x':
						w_txt.write(xy.text + '\t')
					else:
						w_txt.write(xy.text + '\n')
	# display
	if args.display == 1:
		app = EMApp()
		for xml in args.xml:
			filename = xml+'.txt'
			w = EMWidgetFromFile(filename,application=app,force_2d=False)
			w.setWindowTitle(base_name(filename))
			app.show_specific(w)
		app.exec_()			
Example #29
0
def main():
	progname = os.path.basename(sys.argv[0])

	usage = """prog [options]
A simple CTF simulation program. Doesn't read or process data. Just does mathematical simulations.
"""

	parser = EMArgumentParser(usage=usage,version=EMANVERSION)

	parser.add_argument("--apix",type=float,help="Angstroms per pixel for all images",default=1.0, guitype='floatbox', row=4, col=0, rowspan=1, colspan=1, mode="autofit['self.pm().getAPIX()']")
	parser.add_argument("--voltage",type=float,help="Microscope voltage in KV",default=300.0, guitype='floatbox', row=4, col=1, rowspan=1, colspan=1, mode="autofit['self.pm().getVoltage()']")
	parser.add_argument("--cs",type=float,help="Microscope Cs (spherical aberation)",default=4.1, guitype='floatbox', row=5, col=0, rowspan=1, colspan=1, mode="autofit['self.pm().getCS()']")
	parser.add_argument("--ac",type=float,help="Amplitude contrast (percentage, default=10)",default=10, guitype='floatbox', row=5, col=1, rowspan=1, colspan=1, mode='autofit')
	parser.add_argument("--samples",type=int,help="Number of samples in the plotted curve",default=256)
	parser.add_argument("--verbose", "-v", dest="verbose", action="store", metavar="n", type=int, default=0, help="verbose level [0-9], higner number means higher level of verboseness")

	(options, args) = parser.parse_args()

	from emapplication import EMApp
	app=EMApp()
	gui=GUIctfsim(app,options.apix,options.voltage,options.cs,options.ac,options.samples)
	gui.show_guis()
	app.exec_()
Example #30
0
def main():
	progname = os.path.basename(sys.argv[0])
	usage = """prog [options] 
	This is a program to compute the resolution of a n averaged subtomogram. Right now it is very simple simple divide the aligned
	subtomos into even/odd classes, average and then compute the FSC. In the future this program will be extended to compute 
	resolution of an averged subtomo vs a reference and hopefuly of a single sub/tomogram.
	"""
	
	parser = EMArgumentParser(usage=usage,version=EMANVERSION)
	
	parser.add_pos_argument(name="tomodir",help="The refinement directory to use for tomoresolution.", default="", guitype='dirbox', dirbasename='spt_',  row=0, col=0,rowspan=1, colspan=2)
	parser.add_header(name="tomoresoheader", help='Options below this label are specific to e2tomoresolution', title="### e2tomoresolution options ###", row=1, col=0, rowspan=1, colspan=2)
	parser.add_argument("--averager",type=str,help="The averager used to generate the averages. Default is \'mean\'.",default="mean", guitype='combobox', choicelist='dump_averagers_list()', row=2, col=0, rowspan=1, colspan=2)
	parser.add_argument("--sym",  type=str,help="The recon symmetry", default="c1", guitype='symbox', row=3, col=0, rowspan=1, colspan=2)
	parser.add_argument("--mask", type=str,help="The mask to apply before FSC calculation", default=None, guitype='comboparambox', choicelist='re_filter_list(dump_processors_list(),\'mask\')', row=4, col=0, rowspan=1, colspan=2)
	parser.add_argument("--ppid", type=int, help="Set the PID of the parent process, used for cross platform PPID",default=-1)
	
	(options, args) = parser.parse_args()
	if options.mask: options.mask = parsemodopt(options.mask)
	
	logid=E2init(sys.argv,options.ppid)
	
	fscstrategy = EvenOddReso(args[0], options)
	fscstrategy.execute()
	
	results_db = db_open_dict("bdb:%s#convergence.results"%args[0])
	results_db["tomo_fsc"] = [fscstrategy.getFreq(),fscstrategy.getFSC(),fscstrategy.getError()]
	results_db.close()
	
	E2end(logid)
	
	# Plot FSC
	app = EMApp()
	plot = EMPlot2DWidget()
	plot.set_data((fscstrategy.getFreq(),fscstrategy.getFSC()))
	plot.show()
	app.exec_()
Example #31
0
def main():
	progname = os.path.basename(sys.argv[0])
	usage = """%prog [options] <input ali>
	
This program will allow the user to select a specific feature within a tomogram and track it, boxing out the
feature from all slices. Generally best for uniform objects like vesicles."""

	parser = OptionParser(usage=usage,version=EMANVERSION)

	parser.add_option("--prefix",type="string",help="Output file prefix",default=None)
	parser.add_option("--tiltstep",type="float",help="Step between tilts in degrees, default=2",default=2.0)
	parser.add_option("--maxshift",type="int",help="Maximum shift in autoalign, default=8",default=8)
	parser.add_option("--seqali",action="store_true",default=False,help="Average particles in previous slices for better alignments of near-spherical objects")
	parser.add_option("--invert",action="store_true",default=False,help="Inverts image data contrast on the fly")

	#parser.add_option("--boxsize","-B",type="int",help="Box size in pixels",default=64)
	#parser.add_option("--writeoutput",action="store_true",default=False,help="Uses coordinates stored in the tomoboxer database to write output")
	#parser.add_option("--stack",action="store_true",default=False,help="Causes the output images to be written to a stack")
	#parser.add_option("--force",action="store_true",default=False,help="Force overwrite output")
	#parser.add_option("--normproc", help="Normalization processor to apply to particle images. Should be normalize, normalize.edgemean or None", default="normalize.edgemean")
	#parser.add_option("--invertoutput",action="store_true",help="If writing output only, this will invert the pixel intensities of the boxed files",default=False)
	#parser.add_option("--dbls",type="string",help="data base list storage, used by the workflow. You can ignore this argument.",default=None)
	#parser.add_option("--outformat", help="Format of the output particles images, should be bdb,img, or hdf", default="bdb")
	
	(options, args) = parser.parse_args()

	logid=E2init(sys.argv)
	
	app = EMApp()

	
	track=TrackerControl(app,options.maxshift,options.invert,options.seqali,options.tiltstep)
	track.set_image(args[0])

	app.execute()
	
	E2end(logid)
Example #32
0
def main():

    usage = "This shows the alignment result from e2tomogram.py uing the information from a tomorecon_xx folder. "
    parser = EMArgumentParser(usage=usage, version=EMANVERSION)
    parser.add_argument("--path", type=str, help="path", default=None)
    parser.add_argument("--iter", type=int, help="iteration number", default=2)
    (options, args) = parser.parse_args()
    logid = E2init(sys.argv)

    fname = os.path.join(options.path, "ali_{:02d}.hdf".format(options.iter))
    pname = os.path.join(options.path,
                         "landmarks_{:02d}.txt".format(options.iter))
    pks = np.loadtxt(pname)
    imgs = EMData.read_images(fname)
    img = EMData(imgs[0]["nx"], imgs[0]["ny"], len(imgs))
    xfs = []
    for i, m in enumerate(imgs):
        img.insert_clip(m, (0, 0, i))
        xfs.append(m["xform.projection"])

    aname = os.path.join(options.path,
                         "ptclali_{:02d}.hdf".format(options.iter))
    n = EMUtil.get_image_count(aname)
    dirs = np.zeros((len(imgs), len(pks), 2))
    for i in range(n):
        e = EMData(aname, i, True)
        s = e["score"]
        dirs[e["nid"], e["pid"]] = [s[1], -s[0]]
    print dirs

    app = EMApp()

    drawer = EMDrawWindow(app, options, img, pks, xfs, dirs)

    drawer.show()
    app.execute()
    E2end(logid)
Example #33
0
def main():
	progname = os.path.basename(sys.argv[0])
	usage = """prog [options] 
	This is a program to compute the resolution of a n averaged subtomogram. Right now it is very simple simple divide the aligned
	subtomos into even/odd classes, average and then compute the FSC. In the future this program will be extended to compute 
	resolution of an averged subtomo vs a reference and hopefuly of a single sub/tomogram.
	"""
	
	parser = EMArgumentParser(usage=usage,version=EMANVERSION)
	
	parser.add_pos_argument(name="tomodir",help="The refinement directory to use for tomoresolution.", default="", guitype='dirbox', dirbasename='spt_',  row=0, col=0,rowspan=1, colspan=2)
	parser.add_header(name="tomoresoheader", help='Options below this label are specific to e2tomoresolution', title="### e2tomoresolution options ###", row=1, col=0, rowspan=1, colspan=2)
	parser.add_argument("--averager",type=str,help="The averager used to generate the averages. Default is \'mean\'.",default="mean", guitype='combobox', choicelist='dump_averagers_list()', row=2, col=0, rowspan=1, colspan=2)
	parser.add_argument("--sym",  type=str,help="The recon symmetry", default="c1", guitype='symbox', row=3, col=0, rowspan=1, colspan=2)
	parser.add_argument("--mask", type=str,help="The mask to apply before FSC calculation", default=None, guitype='comboparambox', choicelist='re_filter_list(dump_processors_list(),\'mask\')', row=4, col=0, rowspan=1, colspan=2)
	parser.add_argument("--ppid", type=int, help="Set the PID of the parent process, used for cross platform PPID",default=-1)
	
	(options, args) = parser.parse_args()
	if options.mask: options.mask = parsemodopt(options.mask)
	
	logid=E2init(sys.argv,options.ppid)
	
	fscstrategy = EvenOddReso(args[0], options)
	fscstrategy.execute()
	
	results_db = db_open_dict("bdb:%s#convergence.results"%args[0])
	results_db["tomo_fsc"] = [fscstrategy.getFreq(),fscstrategy.getFSC(),fscstrategy.getError()]
	results_db.close()
	
	E2end(logid)
	
	# Plot FSC
	app = EMApp()
	plot = EMPlot2DWidget()
	plot.set_data((fscstrategy.getFreq(),fscstrategy.getFSC()))
	plot.show()
	app.exec_()
Example #34
0
def main():
	progname = os.path.basename(sys.argv[0])
	usage = """prog  <simmx file> <projection file>  <particles file>

	This program allows you to look at per-particle classification based on a pre-computed similarity
	matrix. If a particle seems to be mis-classified, you can use this program to help figure out
	why. It will display a single asymmetric triangle on the unit sphere, with cylinders representing
	the similarity value for the selected particle vs. each possible reference projection. Use the
	normal middle-click on the asymmetric unit viewer for more options.
"""

	parser = EMArgumentParser(usage=usage,version=EMANVERSION)

	parser.add_argument("--ppid", type=int, help="Set the PID of the parent process, used for cross platform PPID",default=-1)
	parser.add_argument("--verbose", "-v", dest="verbose", action="store", metavar="n", type=int, default=0, help="verbose level [0-9], higner number means higher level of verboseness")

	(options, args) = parser.parse_args()



	logid=E2init(sys.argv,options.ppid)

	em_app = EMApp()

	window = EMSymViewerWidget()
	explorer = EMSimmxExplorer(window)
	window.model = explorer

	if len(args) > 0: explorer.set_simmx_file(args[0])
	if len(args) > 1: explorer.set_projection_file(args[1])
	if len(args) > 2: explorer.set_particle_file(args[2])

	em_app.show()
	em_app.execute()

	E2end(logid)
Example #35
0
def main():
	global debug,logid
	progname = os.path.basename(sys.argv[0])
	usage = """%prog [options]

This program allows the user to play around with Fourier synthesis graphically
	
"""

	parser = OptionParser(usage=usage,version=EMANVERSION)

#	parser.add_option("--gui",action="store_true",help="Start the GUI for interactive fitting",default=False)
	parser.add_option("--verbose", "-v", dest="verbose", action="store", metavar="n", type="int", default=0, help="verbose level [0-9], higner number means higher level of verboseness")
	
	(options, args) = parser.parse_args()

	app=EMApp()
	win=GUIFourierSynth(app)
	win.show()
	try: 
		win.raise_()
		win.synthplot.raise_()
	except: pass
	app.exec_()
Example #36
0
def main():
    progname = os.path.basename(sys.argv[0])
    usage = """prog  <simmx file> <projection file>  <particles file>

	This program allows you to look at per-particle classification based on a pre-computed similarity
	matrix. If a particle seems to be mis-classified, you can use this program to help figure out
	why. It will display a single asymmetric triangle on the unit sphere, with cylinders representing
	the similarity value for the selected particle vs. each possible reference projection. Use the
	normal middle-click on the asymmetric unit viewer for more options.
"""

    parser = EMArgumentParser(usage=usage, version=EMANVERSION)

    parser.add_argument(
        "--ppid",
        type=int,
        help="Set the PID of the parent process, used for cross platform PPID",
        default=-1)
    parser.add_argument(
        "--verbose",
        "-v",
        dest="verbose",
        action="store",
        metavar="n",
        type=int,
        default=0,
        help=
        "verbose level [0-9], higner number means higher level of verboseness")

    (options, args) = parser.parse_args()

    logid = E2init(sys.argv, options.ppid)

    em_app = EMApp()

    window = EMSymViewerWidget()
    explorer = EMSimmxExplorer(window)
    window.model = explorer

    if len(args) > 0: explorer.set_simmx_file(args[0])
    if len(args) > 1: explorer.set_projection_file(args[1])
    if len(args) > 2: explorer.set_particle_file(args[2])

    em_app.show()
    em_app.execute()

    E2end(logid)
Example #37
0
def main():

    usage = "[prog] <2D image file> "
    parser = EMArgumentParser(usage=usage, version=EMANVERSION)
    (options, args) = parser.parse_args()
    logid = E2init(sys.argv)

    filename = args[0]

    app = EMApp()
    img = EMData(filename)

    #print img[0]["mean"]
    w = EMBreakBrick(img, app)
    #w.set_data(img,filename)

    app.show_specific(w)
    app.exec_()

    E2end(logid)
Example #38
0
def main():
	progname = os.path.basename(sys.argv[0])
	usage = progname + """ [options]
	A tool for displaying EMAN2 command history
	"""
	
	parser = EMArgumentParser(usage=usage)
	parser.add_argument("--gui", "-g",default=False, action="store_true",help="Open history in an interface with a sortable table.")
	parser.add_argument("--all", "-a",default=False, action="store_true",help="Show for all directories.")
	parser.add_argument("--ppid", type=int, help="Set the PID of the parent process, used for cross platform PPID",default=-1)
	parser.add_argument("--verbose", "-v", dest="verbose", action="store", metavar="n", type=int, default=0, help="verbose level [0-9], higner number means higher level of verboseness")
	
	(options, args) = parser.parse_args()
	
	if options.gui:
		from emapplication import EMApp
		app = EMApp()
		hist = HistoryForm(app,os.getcwd())
		app.show()
		app.execute()
		
	else: print_to_std_out(options.all)
Example #39
0
				if 'C' in self.atom_names[i]: self.load_gl_color("white")
				elif 'N' in self.atom_names[i]: self.load_gl_color("green")
				elif 'O' in self.atom_names[i]: self.load_gl_color("blue")
				elif 'S' in self.atom_names[i]: self.load_gl_color("red")
				elif 'H' in self.atom_names[i]: self.load_gl_color("yellow")
				else: self.load_gl_color("dark_grey")
				
				glCallList(self.highresspheredl)
				glPopMatrix()
			glEndList()
		try:
			glCallList(self.dl)
		except:
			print "call list failed",self.dl
			glDeleteLists(self.dl,1)
			self.dl = None

class EMSphereModelInspector(EMPDBItem3DInspector):
	
	def __init__(self, name, item3d):
		EMPDBItem3DInspector.__init__(self, name, item3d)

if __name__ == '__main__' :
	print("WARNING: This module is not designed to be run as a program. The browser you see is for testing purposes.")
	from emapplication import EMApp
	from embrowser import EMBrowserWidget
	app = EMApp()
	browser = EMBrowserWidget(withmodal = False, multiselect = False)
	browser.show()
	app.execute()
	
Example #40
0
def main():

    usage = "Generate training set for tomogram segmentation. Please run this program from the GUI in e2projectmanager.py."
    #print usage
    parser = EMArgumentParser(usage=usage, version=EMANVERSION)
    #parser.add_header(name="tmpheader", help='temp label', title="### This program is NOT avaliable yet... ###", row=0, col=0, rowspan=1, colspan=2, mode="box,seg,set")
    #### boxing ####
    parser.add_argument("--boxing",
                        action="store_true",
                        help="Boxing particles.",
                        default=False,
                        guitype='boolbox',
                        row=4,
                        col=0,
                        rowspan=1,
                        colspan=1,
                        mode='box[True]')
    parser.add_pos_argument(
        name="micrographs",
        help="List the file to process with e2boxer here.",
        default="",
        guitype='filebox',
        browser="EMRawDataTable(withmodal=True,startpath=\"rawtomograms\")",
        row=1,
        col=0,
        rowspan=1,
        colspan=3,
        mode="box")
    parser.add_argument("--boxsize",
                        "-B",
                        type=int,
                        help="Box size in pixels",
                        default=-1,
                        guitype='intbox',
                        row=3,
                        col=0,
                        rowspan=1,
                        colspan=3,
                        mode="box")

    #### segment ####
    #parser.add_header(name="instruction", help='instruction', title="### Mark the target features white ###", row=0, col=0, rowspan=1, colspan=2, mode="seg")
    parser.add_argument("--segment",
                        action="store_true",
                        help="Segment particles.",
                        default=False,
                        guitype='boolbox',
                        row=4,
                        col=0,
                        rowspan=1,
                        colspan=1,
                        mode='seg[True]')
    parser.add_pos_argument(name="particles",
                            help="Particle file.",
                            default="",
                            guitype='filebox',
                            browser="EMParticlesTable(withmodal=True)",
                            row=1,
                            col=0,
                            rowspan=1,
                            colspan=3,
                            mode="seg")
    parser.add_argument(
        "--output",
        type=str,
        help=
        "output file name. Default is the input particle file name plus _seg.hdf",
        default=None,
        guitype='strbox',
        row=3,
        col=0,
        rowspan=1,
        colspan=3,
        mode="seg")

    #### build set ####
    parser.add_argument("--buildset",
                        action="store_true",
                        help="Segment particles.",
                        default=False,
                        guitype='boolbox',
                        row=7,
                        col=0,
                        rowspan=1,
                        colspan=1,
                        mode='set[True]')
    parser.add_argument("--particles_raw",
                        type=str,
                        help="Input raw particle file",
                        default=None,
                        guitype='filebox',
                        browser="EMParticlesTable(withmodal=True)",
                        row=1,
                        col=0,
                        rowspan=1,
                        colspan=3,
                        mode="set")
    parser.add_argument("--particles_label",
                        type=str,
                        help="Input labels for particle file",
                        default=None,
                        guitype='filebox',
                        browser="EMParticlesTable(withmodal=True)",
                        row=2,
                        col=0,
                        rowspan=1,
                        colspan=3,
                        mode="set")
    parser.add_argument("--boxes_negative",
                        type=str,
                        help="Input boxes of negative samples",
                        default=None,
                        guitype='filebox',
                        browser="EMParticlesTable(withmodal=True)",
                        row=3,
                        col=0,
                        rowspan=1,
                        colspan=3,
                        mode="set")
    parser.add_argument(
        "--ncopy",
        type=int,
        help=
        "Number of copies for NEGATIVE samples. (number of copies of particles is calculated accordingly) ",
        default=10,
        guitype='intbox',
        row=5,
        col=0,
        rowspan=1,
        colspan=1,
        mode="set")
    parser.add_argument(
        "--trainset_output",
        type=str,
        help=
        "output file name of the training set.Default is the input particle file name plus _trainset.hdf",
        default=None,
        guitype='strbox',
        row=4,
        col=0,
        rowspan=1,
        colspan=3,
        mode="set")
    parser.add_argument("--zthick",
                        type=int,
                        help="Thickness in z ",
                        default=0,
                        guitype='intbox',
                        row=5,
                        col=1,
                        rowspan=1,
                        colspan=1,
                        mode="set")
    parser.add_argument(
        "--validset",
        type=float,
        help="Propotion of particles in validation set. Default is 0.2 ",
        default=0.0,
        guitype='floatbox',
        row=7,
        col=1,
        rowspan=1,
        colspan=1,
        mode="set")

    ##################
    parser.add_argument(
        "--ppid",
        type=int,
        help="Set the PID of the parent process, used for cross platform PPID",
        default=-1)
    (options, args) = parser.parse_args()
    logid = E2init(sys.argv)

    #### boxing ###
    if options.boxing:
        db = js_open_dict(EMBOXERBASE_DB)
        cache_box_size = True
        if options.boxsize == -1:
            cache_box_size = False
            options.boxsize = db.setdefault("box_size", 64)

        application = EMApp()
        module = EMBoxerModule(args, options.boxsize)
        module.show_interfaces()

        application.execute(logid)

    #### segment ###
    if options.segment:
        filename = args[0]
        if options.output == None:
            options.output = filename[:-4] + "_seg.hdf"
        app = EMApp()
        img = EMData.read_images(filename)
        #print img[0]["mean"]
        w = EMImageWidget(data=img, old=None, app=app, force_2d=True)
        #w = EMWidgetFromFile(filename,application=app,force_2d=True)
        w.setWindowTitle(base_name(filename))
        w.show_inspector(1)
        ins = w.get_inspector()
        ins.mmtab.setCurrentIndex(5)
        ins.dtpenv.setText('100')
        w.set_mouse_mode(5)
        app.show_specific(w)
        app.exec_()
        try:
            os.remove(options.output)
        except:
            pass
        for e in img:
            e.process_inplace("threshold.belowtozero", {"minval": 99})
            e.process_inplace("threshold.binary", {"value": 1})
            e.write_image(options.output, -1)

    #### build set ###

    if options.buildset:
        tomo_in = options.particles_raw
        seg_in = options.particles_label
        neg_in = options.boxes_negative
        if tomo_in and neg_in and seg_in:
            n_ptcl = EMUtil.get_image_count(tomo_in)
            n_neg = EMUtil.get_image_count(neg_in)
            if options.trainset_output == None:
                options.trainset_output = tomo_in[:-4] + "_trainset.hdf"
            p_copy = options.ncopy * n_neg / n_ptcl
        else:
            p_copy = options.ncopy
        try:
            os.remove(options.trainset_output)
        except:
            pass
        print(
            "making {} copies for particles, and {} copies for negative samples"
            .format(p_copy, options.ncopy))
        imgs = []
        if tomo_in and seg_in:
            n_ptcl = EMUtil.get_image_count(tomo_in)
            for i in range(n_ptcl):
                #t=EMData(tomo_in,i)
                t = get_box(tomo_in, i, options.zthick)
                if t == None: continue
                s = EMData(seg_in, i)
                for c in range(p_copy):
                    tr = Transform()
                    rd = random.random() * 360
                    tr.set_rotation({"type": "2d", "alpha": rd})
                    e = t.process("xform", {"transform": tr})
                    #e.process_inplace("normalize")
                    imgs.append(e)
                    #e.write_image(options.trainset_output,-1)
                    e = s.process("xform", {"transform": tr})
                    #e.write_image(options.trainset_output,-1)
                    imgs.append(e)
        ngood = len(imgs)
        if neg_in:
            s = EMData(neg_in, 0)
            s.to_zero()
            n_neg = EMUtil.get_image_count(neg_in)
            for i in range(n_neg):
                t = get_box(neg_in, i, options.zthick)
                if t == None: continue
                for c in range(options.ncopy):
                    tr = Transform()
                    rd = random.random() * 360
                    tr.set_rotation({"type": "2d", "alpha": rd})
                    e = t.process("xform", {"transform": tr})
                    #e.process_inplace("normalize")
                    #e.write_image(options.trainset_output,-1)
                    imgs.append(e)
                    e = s.process("xform", {"transform": tr})
                    #e.write_image(options.trainset_output,-1)
                    imgs.append(e)

        print("Shuffling particles...")
        ### randomize
        n = len(imgs)

        #n=EMUtil.get_image_count(options.trainset_output)
        idx = range(int((ngood / 2) * (1 - options.validset))) + range(
            (ngood / 2), int(n / 2 * (1 - options.validset)))
        random.shuffle(idx)
        for i in idx:
            imgs[i * 2]["valid_set"] = 0
            imgs[i * 2].write_image(options.trainset_output, -1)
            imgs[i * 2 + 1]["valid_set"] = 0
            imgs[i * 2 + 1].write_image(options.trainset_output, -1)

        idx = range(int(
            (ngood / 2) * (1 - options.validset)), ngood / 2) + range(
                int(n / 2 * (1 - options.validset)), n / 2)
        random.shuffle(idx)
        for i in idx:
            imgs[i * 2]["valid_set"] = 1
            imgs[i * 2].write_image(options.trainset_output, -1)
            imgs[i * 2 + 1]["valid_set"] = 1
            imgs[i * 2 + 1].write_image(options.trainset_output, -1)
            #e=EMData(options.trainset_output,i*2)
            #e.process_inplace("normalize")
            #e.write_image(tmpfile,-1)
            #e=EMData(options.trainset_output,i*2+1)
            #e.write_image(tmpfile,-1)
        #shutil.move(tmpfile,options.trainset_output)
        print("Generate a training set of {:d} samples.".format(n / 2))

    print("Done")
    E2end(logid)
Example #41
0
def main():
	progname = os.path.basename(sys.argv[0])
	usage = """prog [options] <image file> ...

	This program can be used to visualize most files used in EMAN2. Running it without arguments
	will open a browser window with more flexible functionality than the command-line.
	
	"""
	global app,win,options

	parser = EMArgumentParser(usage=usage,version=EMANVERSION)

	parser.add_argument("--classmx",type=str,help="<classmx>,<#> Show particles in one class from a classification matrix. Pass raw particle file as first argument to command.")
	parser.add_argument("--classes",type=str,help="<rawptcl>,<classmx> Show particles associated class-averages")
	parser.add_argument("--pdb",type=str,help="<pdb file> Show PDB structure.")
	parser.add_argument("--singleimage",action="store_true",default=False,help="Display a stack in a single image view")
	parser.add_argument("--plot",action="store_true",default=False,help="Data file(s) should be plotted rather than displayed in 2-D")
	parser.add_argument("--plot3",action="store_true",default=False,help="Data file(s) should be plotted rather than displayed in 3-D")
	parser.add_argument("--fullrange",action="store_true",default=False,help="A specialized flag that disables auto contrast for the display of particles stacks and 2D images only.")
	parser.add_argument("--newwidget",action="store_true",default=False,help="Use the new 3D widgetD. Highly recommended!!!!")
	parser.add_argument("--ppid", type=int, help="Set the PID of the parent process, used for cross platform PPID",default=-2)
	parser.add_argument("--verbose", "-v", dest="verbose", action="store", metavar="n", type=int, default=0, help="verbose level [0-9], higner number means higher level of verboseness")

	(options, args) = parser.parse_args()

#	logid=E2init(sys.argv)

	app = EMApp()
	#gapp = app
	#QtGui.QApplication(sys.argv)
	win=[]
	if options.fullrange:
		fullrangeparms = set_full_range()
	
	if len(args) < 1:
		global dialog
		file_list = []
		dialog = embrowser.EMBrowserWidget(withmodal=False,multiselect=False)
		dialog.show()
		try: dialog.raise_()
# 			QtCore.QObject.connect(dialog,QtCore.SIGNAL("ok"),on_browser_done)
# 			QtCore.QObject.connect(dialog,QtCore.SIGNAL("cancel"),on_browser_cancel)
		except: pass
	
	elif options.pdb:
		load_pdb(args,app)
	
	elif options.plot:
		plot(args,app)
		
	elif options.plot3:
		plot_3d(args,app)
		
	elif options.classes:
		options.classes=options.classes.split(",")
		imgs=EMData.read_images(args[0])
		display(imgs,app,args[0])

		QtCore.QObject.connect(win[0].child,QtCore.SIGNAL("mousedown"),lambda a,b:selectclass(options.classes[0],options.classes[1],a,b))
		try:
			out=file("selected.lst","w")
			out.write("#LST\n")
			out.close()
		except: pass
		
	elif options.classmx:
		options.classmx=options.classmx.split(",")
		clsnum=int(options.classmx[1])
		imgs=getmxim(args[0],options.classmx[0],clsnum)
		display(imgs,app,args[0])
	
	else:
		for i in args:
			if not file_exists(i):
				print "%s doesn't exist" %i
				sys.exit(1)
			display_file(i,app,options.singleimage,usescenegraph=options.newwidget)
	
	if options.fullrange:
		revert_full_range(fullrangeparms)

	app.exec_()
Example #42
0
def main():
    global debug, logid
    progname = os.path.basename(sys.argv[0])
    usage = """%prog [options] <input stack/image> ...
	
Various CTF-related operations on images, including automatic fitting. Note that automatic fitting is limited to 5 microns
underfocus at most. Input particles should be unmasked and unfiltered. A minimum of ~20% padding around the
particles is required for background extraction, even if this brings the edge of another particle into the box in some cases.
Particles should be reasonably well centered. Can also optionally phase flip and Wiener filter particles. Wiener filtration comes
after phase-flipping, so if phase flipping is performed Wiener filtered particles will also be phase-flipped. Note that both
operations are performed on oversampled images if specified (though final real-space images are clipped back to their original
size. Increasing padding during the particle picking process will improve the accuracy of phase-flipping, particularly for
images far from focus."""

    parser = OptionParser(usage=usage, version=EMANVERSION)

    parser.add_option("--gui",
                      action="store_true",
                      help="Start the GUI for interactive fitting",
                      default=False)
    parser.add_option("--auto_fit",
                      action="store_true",
                      help="Runs automated CTF fitting on the input images",
                      default=False)
    parser.add_option(
        "--bgmask",
        type="int",
        help=
        "Compute the background power spectrum from the edge of the image, specify a mask radius in pixels which would largely mask out the particles. Default is boxsize/2.",
        default=0)
    parser.add_option("--apix",
                      type="float",
                      help="Angstroms per pixel for all images",
                      default=0)
    parser.add_option("--voltage",
                      type="float",
                      help="Microscope voltage in KV",
                      default=0)
    parser.add_option("--cs",
                      type="float",
                      help="Microscope Cs (spherical aberation)",
                      default=0)
    parser.add_option("--ac",
                      type="float",
                      help="Amplitude contrast (percentage, default=10)",
                      default=10)
    parser.add_option(
        "--autohp",
        action="store_true",
        help=
        "Automatic high pass filter of the SNR only to remove initial sharp peak, phase-flipped data is not directly affected (default false)",
        default=False)
    #parser.add_option("--invert",action="store_true",help="Invert the contrast of the particles in output files (default false)",default=False)
    parser.add_option("--nonorm",
                      action="store_true",
                      help="Suppress per image real-space normalization",
                      default=False)
    parser.add_option(
        "--nosmooth",
        action="store_true",
        help=
        "Disable smoothing of the background (running-average of the log with adjustment at the zeroes of the CTF)",
        default=False)
    #parser.add_option("--phaseflip",action="store_true",help="Perform phase flipping after CTF determination and writes to specified file.",default=False)
    #parser.add_option("--wiener",action="store_true",help="Wiener filter (optionally phaseflipped) particles.",default=False)
    parser.add_option("--oversamp",
                      type="int",
                      help="Oversampling factor",
                      default=1)
    parser.add_option(
        "--sf",
        type="string",
        help=
        "The name of a file containing a structure factor curve. Can improve B-factor determination.",
        default=None)
    parser.add_option("--debug", action="store_true", default=False)

    (options, args) = parser.parse_args()

    if len(args) < 1: parser.error("Input image required")

    if global_def.CACHE_DISABLE:
        from utilities import disable_bdb_cache
        disable_bdb_cache()

    if options.auto_fit:
        if options.voltage == 0: parser.error("Please specify voltage")
        if options.cs == 0: parser.error("Please specify Cs")
    if options.apix == 0: print "Using A/pix from header"

    debug = options.debug

    global sfcurve
    if options.sf:
        sfcurve = XYData()
        sfcurve.read_file(options.sf)

    logid = E2init(sys.argv)

    #	if options.oversamp>1 : options.apix/=float(options.oversamp)

    db_project = db_open_dict("bdb:project")
    db_parms = db_open_dict("bdb:e2ctf.parms")
    db_misc = db_open_dict("bdb:e2ctf.misc")

    options.filenames = args
    ### Power spectrum and CTF fitting
    if options.auto_fit:
        img_sets = pspec_and_ctf_fit(
            options,
            debug)  # converted to a function so to work with the workflow

        ### This computes the intensity of the background subtracted power spectrum at each CTF maximum for all sets
        global envelopes  # needs to be a global for the Simplex minimizer
        # envelopes is essentially a cache of information that could be useful at later stages of refinement
        # as according to Steven Ludtke
        for i in img_sets:
            envelopes.append(ctf_env_points(i[2], i[3], i[1]))

        # we use a simplex minimizer to try to rescale the individual sets to match as best they can
        scales = [1.0] * len(img_sets)
        if (len(img_sets) > 3):
            incr = [0.2] * len(img_sets)
            simp = Simplex(env_cmp, scales, incr)
            scales = simp.minimize(maxiters=1000)[0]
            #		print scales
            print " "

        # apply the final rescaling
        envelope = []
        for i in range(len(scales)):
            cur = envelopes[i]
            for j in range(len(cur)):
                envelope.append((cur[j][0], cur[j][1] * scales[i]))

        envelope.sort()
        envelope = [i for i in envelope
                    if i[1] > 0]  # filter out all negative peak values

        db_misc = db_open_dict("bdb:e2ctf.misc")
        db_misc["envelope"] = envelope
        #db_close_dict("bdb:e2ctf.misc")

        #out=file("envelope.txt","w")
        #for i in envelope: out.write("%f\t%f\n"%(i[0],i[1]))
        #out.close()

    ### GUI - user can update CTF parameters interactively
    if options.gui:
        img_sets = get_gui_arg_img_sets(options.filenames)
        if len(img_sets) == 0:
            E2end(logid)
            sys.exit(1)
        app = EMApp()
        gui = GUIctf(app, img_sets)
        gui.show_guis()
        app.exec_()

        print "done execution"

    ### Process input files
    #if debug : print "Phase flipping / Wiener filtration"
    # write wiener filtered and/or phase flipped particle data to the local database
    #if options.phaseflip or options.wiener: # only put this if statement here to make the program flow obvious
    #	write_e2ctf_output(options) # converted to a function so to work with the workflow

    E2end(logid)
Example #43
0
def main():
    progname = os.path.basename(sys.argv[0])
    usage = """prog [options]

	WARNING: This program still under development.
	
	This program is used to interactively generate sequences of class-averages from sets of particles. It can be
	used for many purposes, but is primarily intended at studies of macromolecular dynamics and variability. A stack
	of particles ostensibly in the same 3-D (but not 2-D) orientation are read in, then alignment, classification
	and averaging is performed to produce pseudo time-series animations detailing some aspect of the structure's
	variability.
	
	This program is NOT designed for use with stacks of tens of thousands of images. All images are kept in system
	memory. All images are theoretically supposed to share a common overall orientation. That is, for a normal single
	particle project, you would first subclassify the overall image stack used for 3-D using e2refine2d.py or
	e2refine.py, then run this program only on a subset of particles.
	
	If an existing project is specified with --path, previous results will be re-opened"""

    parser = EMArgumentParser(usage=usage, version=EMANVERSION)

    parser.add_argument(
        "--threads",
        default=0,
        type=int,
        help=
        "Number of alignment threads to run in parallel on a single computer. This is the only parallelism supported by e2spt_align at present."
    )
    parser.add_argument("--path",
                        type=str,
                        default=None,
                        help="Path for the refinement, default=auto")
    parser.add_argument(
        "--iter",
        type=int,
        help="Iteration number within path. Default = start a new iteration",
        default=0)
    parser.add_argument(
        "--ppid",
        type=int,
        help="Set the PID of the parent process, used for cross platform PPID",
        default=-1)

    global options
    (options, args) = parser.parse_args()

    if options.path == None:
        options.path = numbered_path("m2d", True)


#		os.makedirs(options.path)

    if options.threads < 1: options.threads = num_cpus()

    if options.path == None:
        fls = [
            int(i[-2:]) for i in os.listdir(".")
            if i[:4] == "m2d_" and len(i) == 6 and str.isdigit(i[-2:])
        ]
        if len(fls) == 0: fls = [1]
        options.path = "m2d_{:02d}".format(max(fls))
        if options.verbose: print("Using --path ", options.path)

    if not os.path.exists(options.path):
        os.mkdir(options.path)
        if itr == 0: itr = 1

    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()])
        except:
            options.iter = 0
        print("Iteration: ", options.iter)

    pid = E2init(argv)

    app = EMApp()
    motion = EMMotion(app, options.path, options.iter, options.threads)
    motion.show()
    app.execute()

    E2end(pid)
Example #44
0
def main():
	progname = os.path.basename(sys.argv[0])
	usage = """prog [options] <untilted micrograph> <tilted micrograph>....
This is a tilted - untilted particle particle picker, for use in RCT particle picking. A tilted and untilted micrograph are loaded and the user picks a untilted particle and a corresponding tilted particle.
After atleast 3 particle pairs are picked a transformation matrix is completed which can be used to predict the postion of the tilted or untilted particle from a untilted or tilted particle respectily.
From the transform matrix, the tilt angle, tilit axis(with respect to Y) and the gamma angle are all computed. 
The program uses the mediator pattern. The mediator, a RCTboxer object HAS A strategy(itself a strategy pattern), HAS A set of windows(in this case 2, but more can be added), HAS A control pannel, and
HAS a particle list. The strategy object implements the strategy pattern(currently a maunal and a pair picker strategy are implemented). This code is in 'emrctstrategy'. The control pannel object HAS A strategy
widget(so there must be one widget for each strategy) and the strategy GUI widget and the strategy itself are tightly coupled. The window object each HAS A EMBoxList, which is a composite of EMBox objects.
(A class diagram is located in my lab notebook, page16)
Usage: e2RCTboxer.py untilted.hdf tilted.hdf options.
"""

	parser = EMArgumentParser(usage=usage,version=EMANVERSION)
	
	parser.add_pos_argument(name="untilted micrograph",help="List the untilted micrograph here.", default="", guitype='filebox', browser="EMRCTBoxesTable(withmodal=True,multiselect=False)", row=0, col=0,rowspan=1, colspan=3, mode="boxing,extraction")
	parser.add_pos_argument(name="tilted micrograph",help="List the tilted micrograph here.", default="", guitype='filebox', browser="EMRCTBoxesTable(withmodal=True,multiselect=False)", row=1, col=0,rowspan=1, colspan=3, mode="boxing,extraction")
	parser.add_header(name="RCTboxerheader", help='Options below this label are specific to e2RCTboxer', title="### e2RCTboxer options ###", row=2, col=0, rowspan=1, colspan=3, mode="boxing,extraction")
	parser.add_argument("--boxsize","-B",type=int,help="Box size in pixels",default=-1, guitype='intbox', row=3, col=0, rowspan=1, colspan=3, mode="boxing,extraction")
	parser.add_argument("--write_boxes",action="store_true",help="Write coordinate file (eman1 dbbox) files",default=False, guitype='boolbox', row=4, col=0, rowspan=1, colspan=1, mode="extraction")
	parser.add_argument("--write_ptcls",action="store_true",help="Write particles to disk",default=False, guitype='boolbox', row=4, col=1, rowspan=1, colspan=1, mode="extraction[True]")
	parser.add_argument("--format", help="Format of the output particles images, should be hdf", default="hdf", guitype='combobox', choicelist="['hdf']", row=7, col=0, rowspan=1, colspan=2, mode="extraction")
	parser.add_argument("--shrink", type=int, help="Shrink the images by an integer, uses math.meanshrink", default = 0, guitype='shrinkbox', row=6, col=2, rowspan=1, colspan=1, mode="extraction")
	parser.add_argument("--norm", type=str,help="Normalization processor to apply to written particle images. Should be normalize, normalize.edgemean,etc.Specifc \"None\" to turn this off", default="normalize.edgemean", guitype='combobox', choicelist='re_filter_list(dump_processors_list(),\'normalize\')', row=6, col=0, rowspan=1, colspan=2, mode="extraction")
	parser.add_argument("--invert",action="store_true",help="If writing outputt inverts pixel intensities",default=False, guitype='boolbox', row=4, col=2, rowspan=1, colspan=1, mode="extraction")
	parser.add_argument("--suffix",type=str,help="suffix which is appended to the names of output particle and coordinate files",default="_ptcls", guitype='strbox', expert=True, row=5, col=1, rowspan=1, colspan=2, mode="extraction")
	parser.add_argument("--ppid", type=int, help="Set the PID of the parent process, used for cross platform PPID",default=-1)
	parser.add_argument("--verbose", "-v", dest="verbose", action="store", metavar="n", type=int, default=0, help="verbose level [0-9], higner number means higher level of verboseness")


	# Options need to be accessible, anywhere
	(options, args) = parser.parse_args()
	
	logid=E2init(sys.argv,options.ppid)
	
	# The RCT DB needs to be accessible, anywhere
	rctdb = js_open_dict(EMBOXERRCT_DB)
	
	# Get and set the boxsize
	cache_box_size = True
	if options.boxsize == -1:
		cache_box_size = False
		options.boxsize = rctdb.get("box_size",dfl=128)
	if cache_box_size: rctdb["box_size"] = options.boxsize
	
	if len(args) != 2:
		print "You need to supply both untiled and tilted micrographs.\nUsage: e2RCTboxer.py [options] <untilted micrograph> <tilted micrograph>"
		sys.exit(1)
	
	if options.write_boxes or options.write_ptcls:
		# Just write output and don't move to GUI mode
		rctproc = RCTprocessor(args,options)
		if options.write_ptcls: rctproc.write_particles()
		if options.write_boxes: rctproc.write_boxes()
	else:
		# Open Application, setup rct object, and run
		application = EMApp()
		rctboxer = RCTboxer(application, options.boxsize)	# Initialize the boxertools
		rctboxer.load_untilt_image(args[0])		# Load the untilted image
		rctboxer.load_tilt_image(args[1])		# Load the tilted image
		rctboxer.init_control_pannel()
		rctboxer.init_control_pannel_tools()			# Initialize control panel tools, this needs to be done last as loaded data maybe be used
		application.execute()
	
	# Clean up
	E2end(logid)
	js_close_dict(EMBOXERRCT_DB)
Example #45
0
def main():
    progname = os.path.basename(sys.argv[0])
    helpstring = """Help is available on the following topics:
processors, cmps, aligners, averagers, projectors, reconstructors, analyzers, symmetries, orientgens, rotationtypes"""
    usage = """prog <topic> [contains]
	
Interactive help on a variety of the eman2 library's modular functions. The optional 'contains' argument will
act as a filter on the names of the algorithms."""
    usage += " " + helpstring

    parser = EMArgumentParser(usage=usage, version=EMANVERSION)

    #parser.add_argument("--res", "-R", type=float, help="Resolution in A, equivalent to Gaussian lowpass with 1/e width at 1/res",default=2.8)
    #parser.add_argument("--box", "-B", type=str, help="Box size in pixels, <xyz> or <x>,<y>,<z>")
    parser.add_argument("--gui",
                        action="store_true",
                        help="Use the GUI for display help",
                        default=False)
    parser.add_argument(
        "--ppid",
        type=int,
        help="Set the PID of the parent process, used for cross platform PPID",
        default=-2)
    parser.add_argument(
        "--verbose",
        "-v",
        dest="verbose",
        action="store",
        metavar="n",
        type=int,
        default=0,
        help=
        "verbose level [0-9], higner number means higher level of verboseness")

    (options, args) = parser.parse_args()

    if options.gui:
        from e2projectmanager import TheHelp
        from emapplication import EMApp
        app = EMApp()
        thehelp = TheHelp()
        thehelp.show()
        if args:
            print(args[0])
            if args[0] in ("aligner", "aligners"):
                thehelp._helpchange(0)
            elif args[0] in ("analyzer", "analyzers"):
                thehelp._helpchange(1)
            elif args[0] in ("averager", "averagers"):
                thehelp._helpchange(2)
            elif args[0] in ("cmp", "cmps"):
                thehelp._helpchange(3)
            elif args[0] in ("orientgen", "orientationgen", "orientgens",
                             "orientationgens", "orientationgenerators"):
                thehelp._helpchange(4)
            elif args[0] in ("processor", "processors"):
                thehelp._helpchange(5)
            elif args[0] in ("projector", "projectors"):
                thehelp._helpchange(6)
            elif args[0] in ("reconstructor", "reconstructors"):
                thehelp._helpchange(7)
            elif args[0] in ("sym", "symmetry", "symmetries"):
                thehelp._helpchange(8)
        app.exec_()
        exit(0)

    if len(args) < 1:
        print(helpstring)
        exit(0)

    l = None
    if args[0] in ("cmp", "cmps"):
        print("Available comparators:")
        l = dump_cmps_list()
    elif args[0] in ("analyzer", "analyzers"):
        print("Available analysers:")
        l = dump_analyzers_list()
    elif args[0] in ("averager", "averagers"):
        print("Available averagers:")
        l = dump_averagers_list()
    elif args[0] in ("processor", "processors"):
        print("Available processors:")
        l = dump_processors_list()
    elif args[0] in ("projector", "projectors"):
        print("Available projectors:")
        l = dump_projectors_list()
    elif args[0] in ("reconstructor", "reconstructors"):
        print("Available reconstructors:")
        l = dump_reconstructors_list()
    elif args[0] in ("aligner", "aligners"):
        print("Available aligners:")
        l = dump_aligners_list()
    elif args[0] in ("sym", "symmetry", "symmetries"):
        print("Available symmetries:")
        l = dump_symmetries_list()
    elif args[0] in ("orientgen", "orientationgen", "orientgens",
                     "orientationgens", "orientationgenerators"):
        print("Available orientation generators:")
        l = dump_orientgens_list()
    elif args[0][:8] == "rotation":
        print("Available rotation conventions:")
        l = {
            "eman": [
                "EMAN convention, az(Z),alt(X),phi(Z') Eulers", "alt", "FLOAT",
                "Altitude, X-axis", "az", "FLOAT", "Azimuth, Z-axis", "phi",
                "FLOAT", "Z' Axis. in-plane rotation in 2-D"
            ],
            "imagic": [
                "IMAGIC convention", "alpha", "FLOAT", "alpha", "beta",
                "FLOAT", "beta", "gamma", "FLOAT", "gamma"
            ],
            "spider": [
                "SPIDER convention", "phi", "FLOAT", "phi", "theta", "FLOAT",
                "theta", "psi", "FLOAT", "psi"
            ],
            "mrc": [
                "MRC/CCP4 convention", "omega", "FLOAT", "omega", "theta",
                "FLOAT", "theta", "psi", "FLOAT", "psi"
            ],
            "xyz": [
                "XYZ convention (Chimera)", "x", "FLOAT", "X-axis", "y",
                "FLOAT", "Y-axis", "z", "FLOAT", "Z-axis"
            ],
            "spin": [
                "Spin-Axis (n1,n2,n3) vector with angle omega", "n1", "FLOAT",
                "X vector component", "n2", "FLOAT", "Y vector component",
                "n3", "FLOAT", "Z vector component", "omega", "FLOAT",
                "Angle of rotation in degrees"
            ],
            "sgirot": [
                "SGI Spin-Axis (n1,n2,n3) vector with angle q", "n1", "FLOAT",
                "X vector component", "n2", "FLOAT", "Y vector component",
                "n3", "FLOAT", "Z vector component", "q", "FLOAT",
                "Angle of rotation in degrees"
            ],
            "quaternion": [
                "Standard 4 component quaternion (e0,e1,e2,e3)", "e0", "FLOAT",
                "e0", "e1", "FLOAT", "e1", "e2", "FLOAT", "e2", "e3", "FLOAT",
                "e3"
            ]
        }

    elif args[0] in ("version"):
        print(FULLVERSIONSTRING)
    else:
        print(helpstring)
        print("unknown option:", args[0])

    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()
            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(k) == 0:
                print("Empty list - no items met search criteria")
                sys.exit(0)
            maxk = max([len(ii) for ii in k])
            fmt = "%%-%0ds : " % maxk
            k.sort()
            for i in k:
                print(fmt % i, end=' ')
                for j in range(1, len(l[i]), 3):
                    print("%s(%s)  " % (l[i][j], l[i][j + 1]), end=' ')
                if len(k) > 1: print("")
Example #46
0
                self.cbb.setCurrentIndex(a)
            a += 1

    def on_threshold_slider(self, val):
        self.target().set_threshold(val)
        self.bright.setValue(-val, True)

    def set_thresholds(self, low, high, val):
        self.thr.setRange(low, high)
        self.thr.setValue(val, True)
        self.bright.setValue(-val, True)

    def set_sample(self, low, high, val):
        self.smp.setRange(int(low), int(high))
        self.smp.setValue(val, True)

    def set_hist(self, hist, minden, maxden):
        self.hist.set_data(hist, minden, maxden)


if __name__ == '__main__':
    from emglobjects import EM3DGLWidget
    from emapplication import EMApp
    app = EMApp()
    window = EM3DGLWidget()
    iso_model = EMIsosurfaceModel(window, test_image_3d(1, size=(64, 64, 64)))
    window.set_model(iso_model)
    window.updateGL()

    app.show()
    app.execute()
Example #47
0
def main():
	progname = os.path.basename(sys.argv[0])
	usage = """prog [options] <image> <image2>....

	The even newer version of e2boxer. Complete rewrite. Incomplete.
	
	This program 
"""
	parser = EMArgumentParser(usage=usage,version=EMANVERSION)

	parser.add_pos_argument(name="micrographs",help="List the file to process with e2boxer here.", default="", guitype='filebox', browser="EMBoxesTable(withmodal=True,multiselect=True)",  row=0, col=0,rowspan=1, colspan=3, mode="boxing,extraction")
	parser.add_argument("--invert",action="store_true",help="If specified, inverts input contrast. Particles MUST be white on a darker background.",default=False, guitype='boolbox', row=3, col=2, rowspan=1, colspan=1, mode="extraction")
	parser.add_argument("--boxsize","-B",type=int,help="Box size in pixels",default=-1, guitype='intbox', row=2, col=0, rowspan=1, colspan=3, mode="boxing,extraction")
	parser.add_argument("--ptclsize","-P",type=int,help="Longest axis of particle in pixels (diameter, not radius)",default=-1, guitype='intbox', row=2, col=0, rowspan=1, colspan=3, mode="boxing,extraction")
	parser.add_argument("--apix",type=float,help="Angstroms per pixel for all images",default=-1, guitype='floatbox', row=4, col=0, rowspan=1, colspan=1, mode="autofit['self.pm().getAPIX()']")
	parser.add_argument("--voltage",type=float,help="Microscope voltage in KV",default=-1, guitype='floatbox', row=4, col=1, rowspan=1, colspan=1, mode="autofit['self.pm().getVoltage()']")
	parser.add_argument("--cs",type=float,help="Microscope Cs (spherical aberation)",default=-1, guitype='floatbox', row=5, col=0, rowspan=1, colspan=1, mode="autofit['self.pm().getCS()']")
	parser.add_argument("--ac",type=float,help="Amplitude contrast (percentage, default=10)",default=10, guitype='floatbox', row=5, col=1, rowspan=1, colspan=1, mode='autofit')
	parser.add_argument("--no_ctf",action="store_true",default=False,help="Disable CTF determination", guitype='boolbox', row=3, col=0, rowspan=1, colspan=1, mode="extraction")
	parser.add_argument("--autopick",type=str,default=None,help="Perform automatic particle picking. Provide mode and parameter string")
	parser.add_argument("--write_dbbox",action="store_true",default=False,help="Export EMAN1 .box files",guitype='boolbox', row=3, col=0, rowspan=1, colspan=1, mode="extraction")
	parser.add_argument("--write_ptcls",action="store_true",default=False,help="Extract selected particles from micrographs and write to disk", guitype='boolbox', row=3, col=1, rowspan=1, colspan=1, mode="extraction[True]")
	parser.add_argument("--gui", action="store_true", default=False, help="Interactive GUI mode")
	parser.add_argument("--ppid", type=int, help="Set the PID of the parent process, used for cross platform PPID",default=-1)
	parser.add_argument("--verbose", "-v", dest="verbose", action="store", metavar="n", type=int, default=0, help="verbose level [0-9], higner number means higher level of verboseness")

	(options, args) = parser.parse_args()
	
	global invert_on_read
	if options.invert : invert_on_read = True


	#####
	# Parameter Validation
	project_db = js_open_dict("info/project.json")

	if not (options.gui or options.write_ptcls or options.write_dbbox or options.autopick):
		print "Error: No actions specified. Try --gui for interactive/semi-automated particle picking." 

	if not options.no_ctf :
		if options.voltage>1500 :
			options.voltage/=1000
			print "Voltage specified in kV. Adjusting specified value to ",options.voltage
		if options.voltage<10 :
			try: 
				options.voltage=project_db["global.microscope_voltage"]
				print "Using project voltage of ",options.voltage,"kV"
			except:
				print "Error: No voltage specified, and no project settings available. Disabling CTF mode."
				options.no_ctf=True
		if options.cs<0 :
			try:
				options.cs=project_db["global.microscope_cs"]
				print "Using project Cs of ",options.cs,"mm"
			except:
				print "Error: No Cs specified, and no project settings available. Disabling CTF mode."
				options.no_ctf=True
		if options.ac<0 and not options.no_ctf:
			print "Error: Invalid %AC value. Disabling CTF mode."
			options.no_ctf=True
		if options.ac<1.0 :
			print "Warning: %AC should be specified as a %. If you intended a %AC>1%, please try again. Will proceed with the specified value"
	
	if options.apix<=0 :
		try:
			options.apix=project_db["global.apix"]
			print "Warning: No A/pix specified. Using ",options.apix," from project. Please insure this is correct for the images being boxed!"
		except:
			print "Error: Value required for A/pixel. If this is a non TEM image, suggest --apix=1 and --no_ctf."
			sys.exit(1)
		
	logid=E2init(sys.argv,options.ppid)

	if options.autopick!=None :
		pass

	if options.gui :
		if isinstance(QtGui,nothing) :
			print "====================================="
			print "ERROR: GUI mode unavailable without PyQt4"
			sys.exit(1)
		from emapplication import EMApp
		app=EMApp()
		gui=GUIBoxer(args,options.voltage,options.apix,options.cs,options.ac,options.boxsize,options.ptclsize)
		gui.show()
		app.exec_()

	if options.write_dbbox:
		pass
	
	if options.write_ptcls:
		pass
		

	E2end(logid)
Example #48
0
def main():
	progname = os.path.basename(sys.argv[0])
	helpstring =  """Help is available on the following topics:
processors, cmps, aligners, averagers, projectors, reconstructors, analyzers, symmetries, orientgens, rotationtypes"""
	usage = """prog <topic> [contains]
	
Interactive help on a variety of the eman2 library's modular functions. The optional 'contains' argument will
act as a filter on the names of the algorithms."""
	usage += " "+helpstring

	parser = EMArgumentParser(usage=usage,version=EMANVERSION)

	#parser.add_argument("--res", "-R", type=float, help="Resolution in A, equivalent to Gaussian lowpass with 1/e width at 1/res",default=2.8)
	#parser.add_argument("--box", "-B", type=str, help="Box size in pixels, <xyz> or <x>,<y>,<z>")
	parser.add_argument("--gui", action="store_true", help="Use the GUI for display help", default=False)
	parser.add_argument("--ppid", type=int, help="Set the PID of the parent process, used for cross platform PPID",default=-2)
	parser.add_argument("--verbose", "-v", dest="verbose", action="store", metavar="n", type=int, default=0, help="verbose level [0-9], higner number means higher level of verboseness")
	
	(options, args) = parser.parse_args()
		
	if options.gui:
		from e2projectmanager import TheHelp
		from emapplication import EMApp
		app = EMApp()
		thehelp = TheHelp()
		thehelp.show()
		if args:
			print args[0]
			if args[0] in ("aligner","aligners"):
				thehelp._helpchange(0)
			elif args[0] in ("analyzer","analyzers"):
				thehelp._helpchange(1)
			elif args[0] in ("averager","averagers"):
				thehelp._helpchange(2)
			elif args[0] in ("cmp","cmps"):
				thehelp._helpchange(3)
			elif args[0] in ("orientgen","orientationgen","orientgens","orientationgens","orientationgenerators"):
				thehelp._helpchange(4)
			elif args[0] in ("processor","processors"):
				thehelp._helpchange(5)
			elif args[0] in ("projector","projectors"):
				thehelp._helpchange(6)
			elif args[0] in ("reconstructor","reconstructors"):
				thehelp._helpchange(7)
			elif args[0] in ("sym","symmetry","symmetries"):
				thehelp._helpchange(8)
		app.exec_()
		exit(0)

	if len(args)<1 : 
		print helpstring
		exit(0)
		
	l=None
	if args[0] in ("cmp","cmps") :
		print "Available comparators:"
		l=dump_cmps_list()
	elif args[0] in ("analyzer","analyzers") :
		print "Available analysers:"
		l=dump_analyzers_list()
	elif args[0] in ("averager","averagers") :
		print "Available averagers:"
		l=dump_averagers_list()
	elif args[0] in ("processor","processors") :
		print "Available processors:"
		l=dump_processors_list()
	elif args[0] in ("projector","projectors") :
		print "Available projectors:"
		l=dump_projectors_list()
	elif args[0] in ("reconstructor","reconstructors") :
		print "Available reconstructors:"
		l=dump_reconstructors_list()
	elif args[0] in ("aligner","aligners") :
		print "Available aligners:"
		l=dump_aligners_list()
	elif args[0] in ("sym","symmetry","symmetries") :
		print "Available symmetries:"
		l=dump_symmetries_list()
	elif args[0] in ("orientgen","orientationgen","orientgens","orientationgens","orientationgenerators") :
		print "Available orientation generators:"
		l=dump_orientgens_list()
	elif args[0][:8]=="rotation" :
		print "Available rotation conventions:"
		l={"eman":["EMAN convention, az(Z),alt(X),phi(Z') Eulers","alt","FLOAT","Altitude, X-axis","az","FLOAT","Azimuth, Z-axis","phi","FLOAT","Z' Axis. in-plane rotation in 2-D"],
		"imagic":["IMAGIC convention","alpha","FLOAT","alpha","beta","FLOAT","beta","gamma","FLOAT","gamma"],
		"spider":["SPIDER convention","phi","FLOAT","phi","theta","FLOAT","theta","psi","FLOAT","psi"],
		"mrc":["MRC/CCP4 convention","omega","FLOAT","omega","theta","FLOAT","theta","psi","FLOAT","psi"],
		"xyz":["XYZ convention (Chimera)","x","FLOAT","X-axis","y","FLOAT","Y-axis","z","FLOAT","Z-axis"],
		"spin":["Spin-Axis (n1,n2,n3) vector with angle omega","n1","FLOAT","X vector component","n2","FLOAT","Y vector component","n3","FLOAT","Z vector component","omega","FLOAT","Angle of rotation in degrees"],
		"sgirot":["SGI Spin-Axis (n1,n2,n3) vector with angle q","n1","FLOAT","X vector component","n2","FLOAT","Y vector component","n3","FLOAT","Z vector component","q","FLOAT","Angle of rotation in degrees"],
		"quaternion":["Standard 4 component quaternion (e0,e1,e2,e3)","e0","FLOAT","e0","e1","FLOAT","e1","e2","FLOAT","e2","e3","FLOAT","e3"]}

	elif args[0] in ("version"):
	   print EMANVERSION + ' (CVS' + DATESTAMP[6:-2] +')' 
	else:
		print helpstring
		print "unknown option:",args[0]
		
	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()
			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(k)==0 :
				print "Empty list - no items met search criteria"
				sys.exit(0)
			maxk=max([len(ii) for ii in k])
			fmt="%%-%0ds : "%maxk
			k.sort()
			for i in k:
				print fmt%i,
				for j in range(1,len(l[i]),3): 
					print "%s(%s)  "%(l[i][j],l[i][j+1]),
				if len(k)>1: print ""
Example #49
0
def main():
	global debug,logid
	progname = os.path.basename(sys.argv[0])
	usage = """%prog [options] <input stack/image> ...
	
Various CTF-related operations on images, including automatic fitting. Note that automatic fitting is limited to 5 microns
underfocus at most. Input particles should be unmasked and unfiltered. A minimum of ~20% padding around the
particles is required for background extraction, even if this brings the edge of another particle into the box in some cases.
Particles should be reasonably well centered. Can also optionally phase flip and Wiener filter particles. Wiener filtration comes
after phase-flipping, so if phase flipping is performed Wiener filtered particles will also be phase-flipped. Note that both
operations are performed on oversampled images if specified (though final real-space images are clipped back to their original
size. Increasing padding during the particle picking process will improve the accuracy of phase-flipping, particularly for
images far from focus."""

	parser = OptionParser(usage=usage,version=EMANVERSION)

	parser.add_option("--gui",action="store_true",help="Start the GUI for interactive fitting",default=False)
	parser.add_option("--auto_fit",action="store_true",help="Runs automated CTF fitting on the input images",default=False)
	parser.add_option("--bgmask",type="int",help="Compute the background power spectrum from the edge of the image, specify a mask radius in pixels which would largely mask out the particles. Default is boxsize/2.",default=0)
	parser.add_option("--apix",type="float",help="Angstroms per pixel for all images",default=0)
	parser.add_option("--voltage",type="float",help="Microscope voltage in KV",default=0)
	parser.add_option("--cs",type="float",help="Microscope Cs (spherical aberation)",default=0)
	parser.add_option("--ac",type="float",help="Amplitude contrast (percentage, default=10)",default=10)
	parser.add_option("--autohp",action="store_true",help="Automatic high pass filter of the SNR only to remove initial sharp peak, phase-flipped data is not directly affected (default false)",default=False)
	#parser.add_option("--invert",action="store_true",help="Invert the contrast of the particles in output files (default false)",default=False)
	parser.add_option("--nonorm",action="store_true",help="Suppress per image real-space normalization",default=False)
	parser.add_option("--nosmooth",action="store_true",help="Disable smoothing of the background (running-average of the log with adjustment at the zeroes of the CTF)",default=False)
	#parser.add_option("--phaseflip",action="store_true",help="Perform phase flipping after CTF determination and writes to specified file.",default=False)
	#parser.add_option("--wiener",action="store_true",help="Wiener filter (optionally phaseflipped) particles.",default=False)
	parser.add_option("--oversamp",type="int",help="Oversampling factor",default=1)
	parser.add_option("--sf",type="string",help="The name of a file containing a structure factor curve. Can improve B-factor determination.",default=None)
	parser.add_option("--debug",action="store_true",default=False)
	
	(options, args) = parser.parse_args()

	if len(args)<1 : parser.error("Input image required")
	
	if global_def.CACHE_DISABLE:
		from utilities import disable_bdb_cache
		disable_bdb_cache()

	if options.auto_fit:
		if options.voltage==0 : parser.error("Please specify voltage")
		if options.cs==0 : parser.error("Please specify Cs")
	if options.apix==0 : print "Using A/pix from header"
		
	debug=options.debug

	global sfcurve
	if options.sf :
		sfcurve=XYData()
		sfcurve.read_file(options.sf)

	logid=E2init(sys.argv)

#	if options.oversamp>1 : options.apix/=float(options.oversamp)

	db_project=db_open_dict("bdb:project")
	db_parms=db_open_dict("bdb:e2ctf.parms")
	db_misc=db_open_dict("bdb:e2ctf.misc")

	options.filenames = args
	### Power spectrum and CTF fitting
	if options.auto_fit:
		img_sets=pspec_and_ctf_fit(options,debug) # converted to a function so to work with the workflow
		
		### This computes the intensity of the background subtracted power spectrum at each CTF maximum for all sets
		global envelopes # needs to be a global for the Simplex minimizer
		# envelopes is essentially a cache of information that could be useful at later stages of refinement
		# as according to Steven Ludtke
		for i in img_sets:
			envelopes.append(ctf_env_points(i[2],i[3],i[1]))

		# we use a simplex minimizer to try to rescale the individual sets to match as best they can
		scales=[1.0]*len(img_sets)
		if (len(img_sets)>3) :
			incr=[0.2]*len(img_sets)
			simp=Simplex(env_cmp,scales,incr)
			scales=simp.minimize(maxiters=1000)[0]
	#		print scales
			print " "

		# apply the final rescaling
		envelope=[]
		for i in range(len(scales)):
			cur=envelopes[i]
			for j in range(len(cur)):
				envelope.append((cur[j][0],cur[j][1]*scales[i]))

		envelope.sort()
		envelope=[i for i in envelope if i[1]>0]	# filter out all negative peak values

		db_misc=db_open_dict("bdb:e2ctf.misc")
		db_misc["envelope"]=envelope
		#db_close_dict("bdb:e2ctf.misc")

		#out=file("envelope.txt","w")
		#for i in envelope: out.write("%f\t%f\n"%(i[0],i[1]))
		#out.close()

	### GUI - user can update CTF parameters interactively
	if options.gui :
		img_sets = get_gui_arg_img_sets(options.filenames)
		if len(img_sets) == 0:
			E2end(logid)
			sys.exit(1)
		app=EMApp()
		gui=GUIctf(app,img_sets)
		gui.show_guis()
		app.exec_()

		print "done execution"

	### Process input files
	#if debug : print "Phase flipping / Wiener filtration"
	# write wiener filtered and/or phase flipped particle data to the local database
	#if options.phaseflip or options.wiener: # only put this if statement here to make the program flow obvious
	#	write_e2ctf_output(options) # converted to a function so to work with the workflow

	E2end(logid)
Example #50
0
File: e22.py Project: cryoem/test
def IPY():
    global ttx
    launch_new_instance()
    # app = TerminalIPythonApp.instance()
    # app.initialize()
    # app.start()

    print "Exiting e22.py"
    ttx = True


def on_timer():
    global ttx

    if ttx:
        QtGui.qApp.quit()


ipythr = threading.Thread(target=IPY)
ipythr.run()


app = EMApp()
EMAN2.GUIMode = True
EMAN2.app = app
mytimer = QtCore.QTimer()
QtCore.QObject.connect(mytimer, QtCore.SIGNAL("timeout()"), on_timer)
mytimer.start(500)

app.exec_()
Example #51
0
#

import EMAN2
import os
from EMAN2 import *

failed = False
try:
    if get_platform() == "Linux" and os.getenv("DISPLAY") == None:
        raise Exception

    from PyQt4 import QtCore, QtGui, QtOpenGL
    from emapplication import EMApp
    import IPython.lib.inputhook

    app = EMApp()
    IPython.lib.inputhook.enable_qt4(app)

    from emimage import image_update

    def ipy_on_timer():
        image_update()

    ipytimer = QtCore.QTimer()
    ipytimer.timeout.connect(ipy_on_timer)
    ipytimer.start(200)

    EMAN2.GUIMode = True
    EMAN2.app = app
except:
    failed = True
Example #52
0
def main():
    progname = os.path.basename(sys.argv[0])

    usage = """prog [options]
A simple CTF simulation program. Doesn't read or process data. Just does mathematical simulations.
"""

    parser = EMArgumentParser(usage=usage, version=EMANVERSION)

    parser.add_argument("--apix",
                        type=float,
                        help="Angstroms per pixel for all images",
                        default=1.0,
                        guitype='floatbox',
                        row=4,
                        col=0,
                        rowspan=1,
                        colspan=1,
                        mode="autofit['self.pm().getAPIX()']")
    parser.add_argument("--voltage",
                        type=float,
                        help="Microscope voltage in KV",
                        default=300.0,
                        guitype='floatbox',
                        row=4,
                        col=1,
                        rowspan=1,
                        colspan=1,
                        mode="autofit['self.pm().getVoltage()']")
    parser.add_argument("--cs",
                        type=float,
                        help="Microscope Cs (spherical aberation)",
                        default=4.1,
                        guitype='floatbox',
                        row=5,
                        col=0,
                        rowspan=1,
                        colspan=1,
                        mode="autofit['self.pm().getCS()']")
    parser.add_argument("--ac",
                        type=float,
                        help="Amplitude contrast (percentage, default=10)",
                        default=10,
                        guitype='floatbox',
                        row=5,
                        col=1,
                        rowspan=1,
                        colspan=1,
                        mode='autofit')
    parser.add_argument("--samples",
                        type=int,
                        help="Number of samples in the plotted curve",
                        default=256)
    parser.add_argument(
        "--verbose",
        "-v",
        dest="verbose",
        action="store",
        metavar="n",
        type=int,
        default=0,
        help=
        "verbose level [0-9], higner number means higher level of verboseness")

    (options, args) = parser.parse_args()

    from emapplication import EMApp
    app = EMApp()
    gui = GUIctfsim(app, options.apix, options.voltage, options.cs, options.ac,
                    options.samples)
    gui.show_guis()
    app.exec_()
Example #53
0
	
	def perspective_clicked(self):
		self.target().set_perspective(True)
		
	def ortho_clicked(self):
		self.target().set_perspective(False)


class EMImage3DModule(EMImage3DWidget):
	def __init__(self, parent=None, image=None,application=None,winid=None):
		import warnings	
		warnings.warn("convert EMImage3DModule to EMImage3DWidget", DeprecationWarning)
		EMImage3DWidget.__init__(self, parent, image, application, winid)
	
if __name__ == '__main__':
	from emapplication import EMApp
	import sys
	em_app = EMApp()
	window = EMImage3DWidget(application=em_app)

	if len(sys.argv)==1 : 
		data = []
		#for i in range(0,200):
		e = test_image_3d(1,size=(64,64,64))
		window.set_data(e)
	else :
		a=EMData(sys.argv[1])
		window.set_data(a,sys.argv[1])
	em_app.show()
	em_app.execute()
Example #54
0
	
	def perspective_clicked(self):
		self.target().set_perspective(True)
		
	def ortho_clicked(self):
		self.target().set_perspective(False)


class EMImage3DModule(EMImage3DWidget):
	def __init__(self, parent=None, image=None,application=None,winid=None):
		import warnings	
		warnings.warn("convert EMImage3DModule to EMImage3DWidget", DeprecationWarning)
		EMImage3DWidget.__init__(self, parent, image, application, winid)
	
if __name__ == '__main__':
	from emapplication import EMApp
	import sys
	em_app = EMApp()
	window = EMImage3DWidget(application=em_app)

	if len(sys.argv)==1 : 
		data = []
		#for i in range(0,200):
		e = test_image_3d(1,size=(64,64,64))
		window.set_data(e)
	else :
		a=EMData(sys.argv[1])
		window.set_data(a,sys.argv[1])
	em_app.show()
	em_app.execute()
Example #55
0
def main():
    progname = os.path.basename(sys.argv[0])
    usage = """prog 3Dstack [options]
	Visulaizse and compute the mean amplitude and sigma in the missing wedge region. After you are sasified that the missing wedge looks sane, compute missing wedge stats
	on all volumes. These stats are used by the aligner tomo.fsc, for subtomogram alignment and averaging.
	"""

    parser = EMArgumentParser(usage=usage, version=EMANVERSION)

    parser.add_pos_argument(name="tdstack",
                            help="The 3D stack to examine.",
                            default="",
                            guitype='filebox',
                            row=0,
                            col=0,
                            rowspan=1,
                            colspan=2)
    parser.add_header(name="wedgeheader",
                      help='Options below this label are specific to e2wedge',
                      title="### e2wedge options ###",
                      row=1,
                      col=0,
                      rowspan=1,
                      colspan=2)
    parser.add_argument("--wedgeangle",
                        type=float,
                        help="Missing wedge angle",
                        default=60.0,
                        guitype='floatbox',
                        row=2,
                        col=0,
                        rowspan=1,
                        colspan=1)
    parser.add_argument("--wedgei",
                        type=float,
                        help="Missingwedge begining",
                        default=0.05)
    parser.add_argument("--wedgef",
                        type=float,
                        help="Missingwedge ending",
                        default=0.5)
    parser.add_argument(
        "--ppid",
        type=int,
        help="Set the PID of the parent process, used for cross platform PPID",
        default=-1)
    parser.add_argument(
        "--nogui",
        action="store_true",
        default=False,
        help=
        "Do not launch the GUI and set the average of the missing wedge statistics on all the volumes."
    )
    parser.add_argument(
        "--averagestats",
        action="store_true",
        default=False,
        help=
        "Do not launch the GUI and set the average of the missing wedge statistics on all the volumes."
    )

    (options, args) = parser.parse_args()

    stack = args[0]

    if not options.nogui:
        em_app = EMApp()
        wedgeviewer = MissingWedgeViewer(stack,
                                         options.wedgeangle,
                                         wedgei=options.wedgei,
                                         wedgef=options.wedgef)
        wedgeviewer.show()
        ret = em_app.exec_()
        sys.exit(ret)
    else:
        means = []
        sigmas = []

        n = EMUtil.get_image_count(stack)
        for i in range(n):
            a = EMData(stack, i)
            retr = wedgestats(a, options.wedgeangle, options.wedgei,
                              options.wedgef)
            mean = retr[0]
            sigma = retr[1]

            if options.averagestats:
                means.append(mean)
                sigmas.append(sigma)
            else:
                a['spt_wedge_mean'] = mean
                a['spt_wedge_sigma'] = sigma
                print "The mean and sigma for subvolume %d are: mean=%f, sigma=%f" % (
                    i, mean, sigma)
                a.write_image(stack, i)

        if options.averagestats:
            meanavg = sum(means) / len(means)
            sigmaavg = sum(sigmas) / len(sigmas)

            print "The average mean and sigma for the wedges in the stack are", meanavg, sigmaavg
            for i in range(n):
                a = EMData(stack, i)
                a['spt_wedge_mean'] = meanavg
                a['spt_wedge_sigma'] = sigmaavg
                a.write_image(stack, i)
    return ()
def main():
	
	usage="Generate training set for tomogram segmentation. This program is still experimental. Please consult the developers before using. "
	print usage
	parser = EMArgumentParser(usage=usage,version=EMANVERSION)
	parser.add_header(name="tmpheader", help='temp label', title="### This program is NOT avaliable yet... ###", row=0, col=0, rowspan=1, colspan=2, mode="box,seg,set")
	#### boxing ####
	parser.add_argument("--boxing",action="store_true",help="Boxing particles.",default=False, guitype='boolbox', row=4, col=0, rowspan=1, colspan=1, mode='box[True]')
	parser.add_pos_argument(name="micrographs",help="List the file to process with e2boxer here.", default="", guitype='filebox', browser="EMRawDataTable(withmodal=True,startpath=\"rawtomograms\")",  row=1, col=0,rowspan=1, colspan=3, mode="box")
	parser.add_argument("--boxsize","-B",type=int,help="Box size in pixels",default=-1, guitype='intbox', row=3, col=0, rowspan=1, colspan=3, mode="box")
	
	#### segment ####
	#parser.add_header(name="instruction", help='instruction', title="### Mark the target features white ###", row=0, col=0, rowspan=1, colspan=2, mode="seg")
	parser.add_argument("--segment",action="store_true",help="Segment particles.",default=False, guitype='boolbox', row=4, col=0, rowspan=1, colspan=1, mode='seg[True]')
	parser.add_pos_argument(name="particles",help="Particle file.", default="", guitype='filebox', browser="EMParticlesTable(withmodal=True)",  row=1, col=0,rowspan=1, colspan=3, mode="seg")
	parser.add_argument("--output", type=str,help="output file name. Default is the input particle file name plus _seg.hdf", default=None,guitype='strbox', row=3, col=0, rowspan=1, colspan=3, mode="seg")
	
	
	#### build set ####
	parser.add_argument("--buildset",action="store_true",help="Segment particles.",default=False, guitype='boolbox', row=7, col=0, rowspan=1, colspan=1, mode='set[True]')
	parser.add_argument("--particles_raw", type=str,help="Input raw particle file", default=None,guitype='filebox',browser="EMParticlesTable(withmodal=True)", row=1, col=0, rowspan=1, colspan=3, mode="set")
	parser.add_argument("--particles_label", type=str,help="Input labels for particle file", default=None,guitype='filebox',browser="EMParticlesTable(withmodal=True)", row=2, col=0, rowspan=1, colspan=3, mode="set")
	parser.add_argument("--boxes_negative", type=str,help="Input boxes of negative samples", default=None,guitype='filebox',browser="EMParticlesTable(withmodal=True)", row=3, col=0, rowspan=1, colspan=3, mode="set")
	parser.add_argument("--ncopy",type=int,help="Number of copies for NEGATIVE samples. (number of copies of particles is calculated accordingly) ",default=20, guitype='intbox', row=5, col=0, rowspan=1, colspan=1, mode="set")
	parser.add_argument("--trainset_output", type=str,help="output file name of the training set.Default is the input particle file name plus _trainset.hdf", default=None,guitype='strbox', row=4, col=0, rowspan=1, colspan=3, mode="set")

	##################
	parser.add_argument("--ppid", type=int, help="Set the PID of the parent process, used for cross platform PPID",default=-1)
	(options, args) = parser.parse_args()
	logid=E2init(sys.argv)
	
	#### boxing ###
	if options.boxing:
		db = js_open_dict(EMBOXERBASE_DB)
		cache_box_size = True
		if options.boxsize == -1:
			cache_box_size = False
			options.boxsize = db.setdefault("box_size",64)

		application = EMApp()
		module = EMBoxerModule(args,options.boxsize)
		module.show_interfaces()

		application.execute(logid)
	
	
	#### segment ###
	if options.segment:
		filename=args[0]
		if options.output==None:
			options.output=filename[:-4]+"_seg.hdf"
		app = EMApp()
		img=EMData.read_images(filename)
		#print img[0]["mean"]
		w=EMImageWidget(data=img,old=None,app=app,force_2d=True)
		#w = EMWidgetFromFile(filename,application=app,force_2d=True)
		w.setWindowTitle(base_name(filename))
		w.show_inspector(1)
		ins=w.get_inspector()
		ins.mmtab.setCurrentIndex(5)
		ins.dtpenv.setText('100')
		w.set_mouse_mode(5)
		app.show_specific(w)
		app.exec_()
		try: os.remove(options.output)
		except:pass
		for e in img:
			e.process_inplace("threshold.belowtozero", {"minval":99})
			e.process_inplace("threshold.binary", {"value":1})
			e.write_image(options.output,-1)
			
	#### build set ###
	
	if options.buildset:
		tomo_in=options.particles_raw
		seg_in=options.particles_label
		neg_in=options.boxes_negative
		if tomo_in and neg_in and seg_in:
			n_ptcl=EMUtil.get_image_count(tomo_in)
			n_neg=EMUtil.get_image_count(neg_in)
			if options.trainset_output==None:
				options.trainset_output=tomo_in[:-4]+"_trainset.hdf"
			p_copy=options.ncopy*n_neg/n_ptcl
		else:
			p_copy=options.ncopy
		try: os.remove(options.trainset_output)
		except: pass
		print "making {} copies for particles, and {} copies for negative samples".format(p_copy,options.ncopy)
		if tomo_in and seg_in:
			n_ptcl=EMUtil.get_image_count(tomo_in)
			for i in range(n_ptcl):
				t=EMData(tomo_in,i)
				s=EMData(seg_in,i)
				for c in range(p_copy):
					tr=Transform()
					rd=random.random()*360
					tr.set_rotation({"type":"2d","alpha":rd})
					e=t.process("xform",{"transform":tr})
					#e.process_inplace("normalize")
					e.write_image(options.trainset_output,-1)
					e=s.process("xform",{"transform":tr})
					e.write_image(options.trainset_output,-1)
		if neg_in:
			s=EMData(neg_in,0)
			s.to_zero()
			n_neg=EMUtil.get_image_count(neg_in)
			for i in range(n_neg):
				t=EMData(neg_in,i)
				for c in range(options.ncopy):
					tr=Transform()
					rd=random.random()*360
					tr.set_rotation({"type":"2d","alpha":rd})
					e=t.process("xform",{"transform":tr})
					#e.process_inplace("normalize")
					e.write_image(options.trainset_output,-1)
					e=s.process("xform",{"transform":tr})
					e.write_image(options.trainset_output,-1)

		print "Shuffling particles..."
		### randomize
		n=EMUtil.get_image_count(options.trainset_output)
		idx=range(n/2)
		random.shuffle(idx)
		tmpfile="tmpfile_maketomotrainset.hdf"
		for i in idx:
			e=EMData(options.trainset_output,i*2)
			#e.process_inplace("normalize")
			e.write_image(tmpfile,-1)
			e=EMData(options.trainset_output,i*2+1)
			e.write_image(tmpfile,-1)
		shutil.move(tmpfile,options.trainset_output)
		print "Generate a training set of {:d} samples.".format(n/2)
		
	print "Done"
	E2end(logid)
Example #57
0
			if ( i == current_color):
				self.cbb.setCurrentIndex(a)
			a += 1

	def on_threshold_slider(self,val):
		self.target().set_threshold(val)
		self.bright.setValue(-val,True)
		
	def set_thresholds(self,low,high,val):
		self.thr.setRange(low,high)
		self.thr.setValue(val, True)
		self.bright.setValue(-val,True)
	
	def set_sample(self,low,high,val):
		self.smp.setRange(int(low),int(high))
		self.smp.setValue(val, True)
		
	def set_hist(self,hist,minden,maxden):
		self.hist.set_data(hist,minden,maxden)

if __name__ == '__main__':
	from emglobjects import EM3DGLWidget
	from emapplication import EMApp
	app = EMApp()
	window = EM3DGLWidget()
	iso_model = EMIsosurfaceModel(window, test_image_3d(1,size=(64,64,64)))
	window.set_model(iso_model)
	window.updateGL()
	
	app.show()
	app.execute()