Ejemplo n.º 1
0
def reconstruction_by_make3d(imagefile, mapfile, options, mapfile2e, mapfile2o, fscfile):
	cmd_prefix = EMAN.pre_mpirun(mpilib = options.mpi, mpi_nodefile = options.mpi_nodefile, single_job_per_node = 1)
	cmd_3drec = "%s `which make3d` %s hard=90 lowmem sym=%s mode=2 apix=%g pad=%d usecenter iter=1" % \
			(cmd_prefix, imagefile, options.endSym, options.apix, options.pad)
	if options.sffile: 
		cmd_3drec += " wiener3d=%s" % ( options.sffile )
		if not options.phasecorrected: cmd_3drec += " flipphase"
	cmd = "%s out=%s" % (cmd_3drec, mapfile)
	if options.eotest and mapfile2e and mapfile2o:
		cmd += "\n%s subset=0/2 out=%s" % (cmd_3drec, mapfile2e)
		cmd += "\n%s subset=1/2 out=%s" % (cmd_3drec, mapfile2o)
	print cmd
	if options.mpi:
		os.system(cmd)
	else:
		runpar_file = "runpar.make3d"
		runparfp = open(runpar_file,"w")
		runparfp.write("%s\n" % (cmd))
		runparfp.close()
		cmd = "runpar proc=%d,%d file=%s nofs" % (options.cpus, options.cpus, runpar_file)
		print cmd
		os.system(cmd)
	if not (os.path.exists(mapfile) and os.path.getsize(mapfile)):
		print "ERROR: 3D map \"%s\" is not generated properly" % (mapfile)
		sys.exit()
	if mapfile2e and mapfile2o and os.path.exists(mapfile2e) and os.path.exists(mapfile2o):
		cmd = "proc3d %s %s fsc=%s" % (mapfile2e,mapfile2o,fscfile)
		print cmd
		os.system(cmd)
	EMAN.post_mpirun(mpilib = options.mpi)
Ejemplo n.º 2
0
def main():
    (options, args) = parse_command_line()

    LOGbegin(sys.argv)

    map1 = EMAN.EMData()
    map1.readImage(args[0])

    map2 = EMAN.EMData()
    map2.readImage(args[1])
    map2t = map2.copy()

    print "Start searching the scale factor in range [%g, %g]" % (options.scale_min, options.scale_max)
    scale = brent(matching_score, brack=[options.scale_min, options.scale_max], args=(map1, map2t))
    print "Final result: scale = %g" % (scale)
    if options.save_map or options.save_fsc:
        map2.setTAlign(0, 0, 0)
        map2.setRAlign(0, 0, 0)
        map2.rotateAndTranslate(scale)
        if options.save_map:
            map2.writeImage(options.save_map)
            print "Final transformed map2 is saved to %s" % (options.save_map)
        if options.save_fsc:
            fsc = map1.fsc(map2)
            if options.apix:
                EMAN.save_data(0, 1.0 / (options.apix * 2.0 * len(fsc)), fsc, len(fsc), options.save_fsc)
            else:
                EMAN.save_data(0, 1.0, fsc, len(fsc), options.save_fsc)
            print "Final Fourier Shell Correlation curve is saved to %s" % (options.save_fsc)

    LOGend()
Ejemplo n.º 3
0
def main():
	
	(options, input_imagefiles, output_lstfile) = parse_command_line()
	
	Particle.sym = options.sym
	Particle.max_ang_diff = options.max_ang_diff * math.pi/180.0
	Particle.max_cen_diff = options.max_cen_diff
		
	image_lists = []
	
	for f in input_imagefiles:	# build the image sets
		tmp_image_list = EMAN.image2list(f)
		
		# first check and remove duplicate images
		seen = sets.Set()
		tmp_image_list2 = []
		for i, img in enumerate(tmp_image_list): 
			imgid = "%s-%d" % (os.path.abspath(img[0]), img[1])
			if imgid in seen:
				print "%s: particle %d/%d (%s %d) is a duplicate image, ignored" % (f, i, len(tmp_image_list), img[0], img[1])
			else:
				seen.add(imgid)
				tmp_image_list2.append(img)
		
		image_list = sets.Set()
		for i, img in enumerate(tmp_image_list2): 
			p = Particle(img)
			image_list.add(p)
		print "%s: %d images" % (f, len(image_list))
		image_lists.append( image_list )

	all_images = image_lists[0]
	print "Begining with %d images in %s" % (len(all_images), input_imagefiles[0])
	for i in range(1,len(image_lists)):
		image_list = image_lists[i]
		if options.mode == "common":	# all_images & imageset
			all_images = intersection(all_images, image_list)
			print "%d common images after processing %d images in %s" % ( len(all_images), len(image_list), input_imagefiles[i] )
		elif options.mode == "union":
			all_images = union(all_images, image_list)	# all_images | imageset
			print "%d images after merging %d images in %s" % ( len(all_images), len(image_list), input_imagefiles[i] )
		elif options.mode == "diff":
			all_images = difference(all_images,image_list)	# all_images-imageset
			print "%d different images after processing %d images in %s" % ( len(all_images), len(image_list), input_imagefiles[i] )
		elif options.mode == "symdiff":
			all_images = symmetric_difference(all_images,image_list)	# all_images ^ imageset
			print "%d different images after processing %d images in %s" % ( len(all_images), len(image_list), input_imagefiles[i] )
	
	all_images=list(all_images)
	all_images.sort()
	
	all_images_output_list = [i.image for i in  all_images]
			
	if len(all_images_output_list):
		print "%d images saved to %s" % ( len(all_images_output_list), output_lstfile )
		EMAN.imagelist2lstfile(all_images_output_list, output_lstfile)
	else:
		print "No image left after the image sets operation"
Ejemplo n.º 4
0
def random_sample(num_maps, sf, particles):
	#subset_num = int (len(particles)*fraction)
	num_part = int(len(particles))
	num_proj = EMAN.fileCount("proj.img")[0]
	
	for i in range(num_maps):
		#print "Model %d" % (i)
		#random.shuffle(particles)
		directory = "model_%d" % (i)
		os.mkdir(directory)
		os.chdir(directory)
		for files in ["start.hed","proj.hed"]:
		#up_dir_file = "../"+file
			cmd="lstcat.py "+files+" ../"+files
			os.system(cmd)
			os.link(files, files[:-3]+"img")
		os.link("../"+sf,sf)
		for c in range(num_proj):
			clsfile="cls%04d.lst" % (c)
			fp = file(clsfile,"w")
			fp.write("#LST\n%d\tproj.hed\n" % (c) )
			fp.close()
		#for j in range(subset_num):
		for j in range(num_part):
			#p = int(particles[j][0])	
			#c = int(particles[j][1])
			partt=random.choice(particles)
			p = partt[0]
			c = int(partt[1])
			#print "Index %d/%d/%d\tParticle %d -> Class %d" % (j, subset_num, len(particles), p, c)
			clsfile="cls%04d.lst" % (c)
			fp = open(clsfile,"a")
			fp.write(p)
			fp.close()
		os.chdir("..")
Ejemplo n.º 5
0
def parse_command_line():
	usage="Usage: %prog <image filename> <output filename> [options]"
	parser = OptionParser(usage=usage)
	parser.add_option("--mode",metavar="['defocus', 'snr', 'ctfb', 'ctfamp']",dest="mode",type="choice",choices=['defocus', 'snr', 'ctfb', 'ctfamp'], help="ctf mode to plot. default to \"defocus\"", default="defocus")
	parser.add_option("--sf",dest="sffile",type="string",help="structural factor file name", default="")
	parser.add_option("--first",dest="first",type="int",help="first image to use. default to 0", default=0)
	parser.add_option("--last",dest="last",type="int",help="last image to use. default to last image in the file", default=-1)
	
	(options, args) = parser.parse_args()
	if len(args) != 2:
		parser.print_help()
		sys.exit(-1)
	else:
		image = args[0]
		output = args[1]
	
	if options.mode in ['snr']:
		if not options.sffile:
			print "Error: --sf should be specified"
			sys.exit(1)
		elif not os.path.exists(options.sffile):
			print "Error: sffile %s does not exist" % (options.sffile)
			sys.exit(2)
	imgnum = EMAN.fileCount(image)[0]
	if options.last==-1: options.last=imgnum-1
	if options.first>0 or options.last>0:
		if not (0<=options.first<imgnum):
			print "Error: --first=%d is out of correct range [0, %d]" % (options.first, imgnum-1)
			sys.exit(3)
		if not (options.first<=options.last<imgnum):
			print "Error: --last=%d is out of correct range [%d, %d]" % (options.last, options.first, imgnum-1)
			sys.exit(4)

	return (options, image, output)
Ejemplo n.º 6
0
def main():
	(options, input_lstfiles) = parse_command_line()
	ptcls = readLstFiles(input_lstfiles, nBest = options.nBest)
	
	if options.ortLstFile:
		ptcls_list = []
		for p in ptcls:
			ptcls_list += ptcls[p].items()
		ptcls_list.sort()

		fp = open(options.ortLstFile, 'w')
		fp.write("#LST\n")
		for p in ptcls_list:
			fp.write("%d\t%s\teuler=%g,%g,%g\tcenter=%g,%g\n" % (p.imageIndex, p.imageFile, p.euler[0], p.euler[1], p.euler[2], p.center[0], p.center[1]))
		fp.close()
		cmd = "images2lst.py %s %s" % (options.ortLstFile, options.ortLstFile)
		os.system(cmd)
	
	if options.saveClsLst:
		nProj = EMAN.fileCount(options.projFile)[0]
		clses = [ 1 ]* nProj
		for i in range(len(clses)): clses[i] = []

		for p in ptcls:
			solutions = ptcls[p].items()
			for pi in solutions: 
				clses[pi.refid].append(pi)
		import math
		#digits = int(math.log10(nProj)+1)
		digits = 4
		for cls in range(len(clses)):
			ptcls_list = clses[cls]
			ptcls_list.sort()

			clsfn = "%d" % (cls)
			clsfn = "%s%s.lst" % (options.clsFileTag, clsfn.zfill(digits))
			fp = open(clsfn,'w')
			fp.write("#LST\n")
			fp.write("%d\t%s\n" % (cls, options.projFile))
			for p in ptcls_list:
				fp.write("%d\t%s\t%s\n" % (p.imageIndex, p.imageFile, p.clsinfo))
			fp.close()
			
			if options.eotest:
				clsfn = "%d" % (cls)
				clsfn_even = "%s%s.even.lst" % (options.clsFileTag, clsfn.zfill(digits))
				clsfn_odd = "%s%s.odd.lst" % (options.clsFileTag, clsfn.zfill(digits))
				fp_even = open(clsfn_even,'w')
				fp_even.write("#LST\n")
				fp_even.write("%d\t%s\n" % (cls, options.projFile))
				fp_odd = open(clsfn_odd,'w')
				fp_odd.write("#LST\n")
				fp_odd.write("%d\t%s\n" % (cls, options.projFile))
				for p in ptcls_list:
					if p.imageIndex%2:
						fp_odd.write("%d\t%s\t%s\n" % (p.imageIndex, p.imageFile, p.clsinfo))
					else:
						fp_even.write("%d\t%s\t%s\n" % (p.imageIndex, p.imageFile, p.clsinfo))
				fp_even.close()
				fp_odd.close()
def numberParticlesInStack(stackname, startnum=0, verbose=True):
        ### new faster methond
        apImagicFile.numberStackFile(stackname, startnum=0)
        return

        # store the particle number in the stack header
        # NOTE!!! CONFORMS TO EMAN CONVENTION, STARTS AT 0!!!
        import EMAN
        t0 = time.time()
        apDisplay.printMsg("saving particle numbers to stack header")
        n=EMAN.fileCount(stackname)[0]
        im=EMAN.EMData()
        i = 0
        back = "\b\b\b\b\b\b\b"
        while i < n:
                j=startnum+i
                im.readImage(stackname,i)
                im.setNImg(j)
                im.writeImage(stackname,i)
                if verbose is True and i%100 == 0:
                        sys.stderr.write(back+back+back+str(j)+" of "+str(n))
                i+=1
        sys.stderr.write("\n")
        apDisplay.printMsg("finished in "+apDisplay.timeString(time.time()-t0))
        return
Ejemplo n.º 8
0
def alignParticlesInLST(lstfile,outstack):
        import EMAN
        ### create a stack of particles aligned according to an LST file
        images=EMAN.readImages(lstfile,-1,-1,0)
        for i in images:
                i.edgeNormalize()
                i.rotateAndTranslate()
                if i.isFlipped():
                        i.hFlip()
                i.writeImage(outstack,-1)
def alignParticlesInLST(lstfile,outstack):
        import EMAN
        ### create a stack of particles aligned according to an LST file
        apDisplay.printMsg("aligning particles in '%s', saving to stack: %s"%(lstfile,outstack))        
        images=EMAN.readImages(lstfile,-1,-1,0)
        for i in images:
                i.edgeNormalize()
                i.rotateAndTranslate()
                if i.isFlipped():
                        i.hFlip()
                i.writeImage(outstack,-1)
def writeStackParticlesToFile(stackname, filename):
        import EMAN
        # write out the particle numbers from imagic header to a file
        # NOTE!!! CONFORMS TO EMAN CONVENTION, STARTS AT 0!!!
        apDisplay.printMsg("saving list of saved particles to:")
        apDisplay.printMsg(filename)
        f = open(filename,'w')
        n=EMAN.fileCount(stackname)[0]
        im=EMAN.EMData()
        for i in range(n):
                im.readImage(stackname,i)
                f.write(str(im.NImg())+"\n")
        f.close()
        return
Ejemplo n.º 11
0
def main():
	if len(sys.argv) != 3:
		print "Usage::  %s <input particles file name> <output particles file name>"%(sys.argv[0])
		sys.exit(-1)
	input = sys.argv[1]
	output = sys.argv[2]
	
	stack=EMAN.readImages(input,-1,-1)
	i = 0
	for image in stack:
		print "Working on image %s"%(i)
		new_image = speckle_filter(image)
		new_image.writeImage(output,i)
		i=i+1
def checkStackNumbering(stackname):
        import EMAN
        # check that the numbering is stored in the NImg parameter
        apDisplay.printMsg("checking that original stack is numbered")
        n=EMAN.fileCount(stackname)[0]
        im=EMAN.EMData()
        im.readImage(stackname,n-1)

        # if last particle is not numbered with same value as # of particles,
        # renumber the entire stack
        if n-1 != im.NImg():
                apDisplay.printWarning("Original stack is not numbered! numbering now...")
                # check that the stack exists in a writable directory and is not read-only
                if os.access(stackname, os.W_OK) is True:
                        numberParticlesInStack(stackname, startnum=0, verbose=True)
                else:
                        apDisplay.printWarning("old stack header exists in a READ-only directory and cannot be numbered according to EMAN")
        return
def makeClassAverages(lst, outputstack,e,mask):
        import EMAN
        #align images in class
        print "creating class average from",lst,"to",outputstack
        images=EMAN.readImages(lst,-1,-1,0)
        for image in images:
                image.rotateAndTranslate()
                if image.isFlipped():
                        image.hFlip()

        #make class average
        avg=EMAN.EMData()
        avg.makeMedian(images)

        #write class average
        avg.setRAlign(e)
        avg.setNImg(len(images))
        avg.applyMask(mask,0)
        avg.writeImage(outputstack,-1)
def getClassInfo(classes):
        import EMAN
        # read a classes.*.img file, get # of images
        imgnum, imgtype = EMAN.fileCount(classes)
        img = EMAN.EMData()
        img.readImage(classes, 0, 1)

        # for projection images, get eulers
        projeulers=[]
        for i in range(imgnum):
                img.readImage(classes, i, 1)
                e = img.getEuler()
                alt = e.thetaMRC()*180./math.pi
                az = e.phiMRC()*180./math.pi
                phi = e.omegaMRC()*180./math.pi
                eulers=[alt,az,phi]
                if i%2==0:
                        projeulers.append(eulers)
        return projeulers
def makeClassAverages(lst, outputstack, classdata, params):
    # align images in class
    images = EMAN.readImages(lst, -1, -1, 0)
    for image in images:
        image.rotateAndTranslate()
        if image.isFlipped():
            image.hFlip()

    # make class average
    avg = EMAN.EMData()
    avg.makeMedian(images)

    # write class average
    e = EMAN.Euler()
    alt = classdata["euler1"] * math.pi / 180
    az = classdata["euler2"] * math.pi / 180
    phi = 0.0
    e.setAngle(alt, az, phi)
    avg.setRAlign(e)
    avg.setNImg(len(images))
    avg.applyMask(params["mask"], 0)
    avg.writeImage(outputstack, -1)
Ejemplo n.º 16
0
def follow_lst_link(image, index, lstfiles, imagefiles):
    if not (
        imagefiles.has_key(image) or lstfiles.has_key(image)
    ):  # it has not seen this image before and will find out
        imgnum, imgtype = EMAN.fileCount(image)
        if imgtype == "lst":
            tmplst = []
            fp = open(image, "r")
            lines = fp.readlines()
            fp.close()
            if lines[0].startswith("#LST"):
                line0 = 1
            elif lines[0].startswith("#LSX"):
                line0 = 3

            for l in lines[line0:]:
                tokens = l.split()
                tmplst.append((tokens[1], int(tokens[0])))
            lstfiles[image] = tmplst
        else:
            imagefiles[image] = imgnum

    if imagefiles.has_key(image):  # it has already known this image is a binary format image
        if index >= imagefiles[image]:
            print "Error: image file %s only has %d images, not enough for %d" % (image, imagefiles[image], index)
            sys.exit(-1)
        else:
            return (image, index)
    elif lstfiles.has_key(image):  # it has already known this image is a list format image
        if index >= len(lstfiles[image]):
            print "Error: lst file %s only has images, not enough for %d" % (image, len(lstfiles[image]), index)
            sys.exit(-1)
        else:
            return follow_lst_link(lstfiles[image][index][0], lstfiles[image][index][1], lstfiles, imagefiles)
    else:
        print "Something is wrong, need to debug this program and the image file"
        sys.exit(-1)
        def makeClassAverages(self, classlist, outputstack, classdata, maskrad):
                #align images in class
                #print classlist
                images = EMAN.readImages(classlist, -1, -1, 0)
                for image in images:
                        image.rotateAndTranslate()
                        if image.isFlipped():
                                image.hFlip()

                #make class average
                avg = EMAN.EMData()
                avg.makeMedian(images)

                #write class average
                e = EMAN.Euler()
                alt = classdata['euler1']*math.pi/180
                az  = classdata['euler2']*math.pi/180
                phi = 0.0 #classdata['euler3']*math.pi/180
                e.setAngle(alt, az, phi)
                avg.setRAlign(e)
                avg.setNImg(len(images))
                avg.applyMask(maskrad, 0)

                avg.writeImage(outputstack,-1)
if __name__== '__main__':
	# write command & time to emanlog if exists:
	if os.path.exists('refine.log'):
		cmd = string.join(sys.argv,' ')
		apEMAN.writeEMANTime('refine.log',cmd)
	#Parse inputs
	args=sys.argv[1:]
	params=createDefaults()
	parseInput(args,params)
	
	if params['coranmask'] is None:
		params['coranmask'] = params['mask']
		
	#Determine box size
	tmpimg=EMAN.readImages('start.hed',1,1)
	params['boxsize']=tmpimg[0].xSize()

	#Set up for coran
	params['corandir']=params['corandir']+str(params['iter'])
	if os.path.exists(params['corandir']):
		print "WARNING!!! %s exists and is being overwritten" % params['corandir']
		shutil.rmtree(params['corandir'])
		os.mkdir(params['corandir'])
	else:
		os.mkdir(params['corandir'])
	classfile='cls.'+str(params['iter'])+'.tar'
	shutil.copy(classfile,os.path.join(params['corandir'],classfile))
	shutil.copy('proj.hed',os.path.join(params['corandir'],'proj.hed'))
	shutil.copy('proj.img',os.path.join(params['corandir'],'proj.img'))
	os.chdir(params['corandir'])
#!/usr/bin/env python

# this will save the particle stack number into the header of a stack.
# use this if you want to run cenalignint, and keep track of the particles.
# NOTE!!! CONFORMS TO EMAN CONVENTION, STARTS AT 0!!!!

import sys
try:
	import EMAN
except ImportError:
	print "EMAN module did not get imported"

if __name__ == "__main__":

	if len(sys.argv) < 2:
		print "usage: renumber.py [filename]"
		sys.exit()

	filename=sys.argv[1]

	n=EMAN.fileCount(filename)[0]
	im=EMAN.EMData()
	for i in range(n):
		im.readImage(filename,i)
		im.setNImg(i)
		im.writeImage(filename,i)
		print i
Ejemplo n.º 20
0
def createClassAverages(stack,projs,apmq,numprojs,boxsz,outclass="classes",rotated=False,shifted=False,dataext=".spi"):
	"""
	creates EMAN-style class average file "classes.hed" & "classes.img"
	and variance files "variances.hed" & "variances.img"
	from spider classification
	"""
	apFile.removeFile(outclass)
	outf=spyder.fileFilter(outclass)
	outvf="tmpvar"
	apmqlist = readDocFile(apmq)
	mySpi = spyder.SpiderSession(dataext=dataext, logo=False, log=False)

	# create file containing the number of particles matched to each projection
	mySpi.toSpiderQuiet(
		"VO MQ",
		"0.0",
		spyder.fileFilter(apmq),
		str(numprojs),
		"cls*****",
		"numinclass",
	)
	mySpi.close()
	os.remove("numinclass%s" % dataext)

	# create class average file
	mySpi = spyder.SpiderSession(dataext=dataext, logo=False, log=False)
	for i in range(0,numprojs):
		clsfile = readDocFile("cls%05d%s" % (i+1,dataext))
		if clsfile == []:
			apDisplay.printMsg("class %d has no particles" %(i+1))
			mySpi.toSpiderQuiet("BL","%s@%d" % (outf,(i+1)),"(%d,%d)" % (boxsz,boxsz),"N","(0.0)",)
			mySpi.toSpiderQuiet("BL","%s@%d" % (outvf,(i+1)),"(%d,%d)" % (boxsz,boxsz),"N","(0.0)",)
		else:
			mySpi.toSpiderQuiet("DE","_2@")
			mySpi.toSpiderQuiet("MS","_2@","%d,%d,1" % (boxsz,boxsz), str(len(clsfile)))
			for p in range(0,len(clsfile)):
				mySpi.toSpiderQuiet("DE","_1")
				# get the particle
				part = int(float(clsfile[p][2]))-1
				pimg = spyder.fileFilter(stack)+"@%d"%(part+1)
				
				rot=float(apmqlist[part][4])
				shx=float(apmqlist[part][5])
				shy=float(apmqlist[part][6])
				if shifted is True:
					shx=0
					shy=0
				if rotated is True:
					rot=0
				p_out="_2@%d" % (p+1)
				rotAndShiftImg(
					pimg,
					"_1",
					rot,
					shx,
					shy,
					inMySpi=mySpi
				)
				# mirror
				if int(float(apmqlist[part][2])) < 0:
					mirrorImg("_1",p_out,inMySpi=mySpi)
				else:
					mySpi.toSpiderQuiet("CP","_1",p_out)
			if len(clsfile) == 1:
				mySpi.toSpiderQuiet("CP","_2@1","%s@%d" % (outf,(i+1)))
				mySpi.toSpiderQuiet("BL","%s@%d" % (outvf,(i+1)),"(%d,%d)" % (boxsz,boxsz),"N","(0.0)",)
			else:
				mySpi.toSpiderQuiet("AS R","_2@*****","1-%d" % len(clsfile), "A","%s@%d" % (outf,(i+1)),"%s@%d" % (outvf,i+1))
	mySpi.close()

	# convert the class averages to EMAN class averages
	# read classes & projections for EMAN classes output
	if os.path.exists('variances.hed'):
		os.remove('variances.hed')
	if os.path.exists('variances.img'):
		os.remove('variances.img')
	if os.path.exists('classes.hed'):
		os.remove('classes.hed')
	if os.path.exists('classes.img'):
		os.remove('classes.img')
	### I would prefer to use apImagicFile.readImagic, writeImagic
	variances = EMAN.readImages(outvf+dataext,-1,-1,0)
	averages = EMAN.readImages(outf+dataext,-1,-1,0)
	projections=EMAN.readImages(projs,-1,-1,0)
	for i in range (0,numprojs):
		# copy projection to class average file
		projections[i].writeImage('classes.hed')
		projections[i].writeImage('variances.hed')
		# get num of particles in class
		clsfile=readDocFile("cls%05d%s" % (i+1,dataext))
		averages[i].setNImg(len(clsfile))
		averages[i].writeImage('classes.hed',-1)
		variances[i].setNImg(len(clsfile))
		variances[i].writeImage('variances.hed',-1)
		os.remove("cls%05d%s" % (i+1,dataext))
	os.remove(outf+dataext)
	return
Ejemplo n.º 21
0
#!/usr/bin/env python

# by Wen Jiang 2005-12-9

# $Id: ctfcopy.py,v 1.1 2005/12/09 00:23:32 wjiang Exp $

import sys
import EMAN

usage = "Usage: %s <input image> <output image>" % (sys.argv[0])
if len(sys.argv) != 3: 
	print usage
	sys.exit(1)

n1 = EMAN.fileCount(sys.argv[1])[0]
n2 = EMAN.fileCount(sys.argv[2])[0]

if n1 != n2:
	print "ERROR: %d in %s != %d in %s" % (n1, sys.argv[1], n2, sys.argv[2])
	sys.exit(1)

d1 = EMAN.EMData()
d2 = EMAN.EMData()

for i in range(n1):
	d1.readImage(sys.argv[1],i,1)
	d2.readImage(sys.argv[2],i,1)
	
	if d1.hasCTF():
		ctf = d1.getCTF()
		print "%d\t%g,%g,%g,%g,%g,%g,%g,%g,%g,%g,%g" % (i, ctf[0], ctf[1], ctf[2], ctf[3], ctf[4], ctf[5], ctf[6], ctf[7], ctf[8], ctf[9], ctf[10])
Ejemplo n.º 22
0
def main():
	(options, rawimage) = parse_command_line()

	pid = EMAN.LOGbegin(sys.argv)
	EMAN.LOGInfile(pid, rawimage)

	imagenum = EMAN.fileCount(rawimage)[0]
	for iter in range(options.iters):
		projfile = "proj.%d.hdf" % (iter+1)
		cmplstfile = "cmp.%d.lst" % (iter+1)
		ortlstfile = "ort.%d.lst" % (iter+1)
		mapfile = "threed.%da.mrc" % (iter)
		mapfile2 = "threed.%da.mrc" % (iter+1)
		if options.eotest:
			mapfile2e = "threed.%da.e.mrc" % (iter+1)
			mapfile2o = "threed.%da.o.mrc" % (iter+1)
			subsetlste = "ort.%d.e.lst"  % (iter+1)
			subsetlsto = "ort.%d.o.lst"  % (iter+1)
			fscfile = "fsc.%d.txt" % (iter+1)
		else:
			mapfile2e = None
			mapfile2o = None
			subsetlste = None
			subsetlsto = None
			fscfile = None

		if not os.path.exists(mapfile):
			print "ERROR: cannot find 3D map \"%s\"" % (mapfile)
			sys.exit()
		else:
			d = EMAN.EMData()
			d.readImage(rawimage,0,1)	# read header
			rnx = d.xSize()
			rny = d.ySize()
			d.readImage(mapfile,-1,1)	# read header
			mnx = d.xSize()
			mny = d.ySize()
			mnz = d.zSize()
			if rnx!=mnx or rny!=mny:
				print "ERROR: raw images (%s) sizes (%dx%d) are different from the 3D map (%s) sizes (%dx%dx%d)" % 	(rawimage, rnx, rny, mapfile, mnx, mny, mnz)
				sys.exit()
		
		if not os.path.exists(cmplstfile):
			runpar_file = "runpar.%d.ortcen.txt" % (iter+1)
			n = imagenum/options.batchsize
			if imagenum%n: n+=1
			if n<options.cpus: 
				n=options.cpus
				options.batchsize=imagenum/n+1
				if options.batchsize==1: 
					n = imagenum
					options.batchsize=1
			
			num_tries = 0
			max_tries = 3
			while not os.path.exists(ortlstfile) and num_tries < max_tries:
				runparfp = open(runpar_file, "w")
				num_tries += 1
				todo_num = 0
				sublstfiles = []
				cmpsublstfiles = []
				for i in range(n):
					cmplstfile_tmp = "cmp.%d.%d.lst" % (iter+1, i)
					ortlstfile_tmp = "ort.%d.%d.lst" % (iter+1, i)
					startNum = i * options.batchsize
					endNum = (i+1) * options.batchsize
					if startNum>=imagenum: break
					if endNum>imagenum: endNum=imagenum
					sublstfiles.append(ortlstfile_tmp)
					cmpsublstfiles.append(cmplstfile_tmp)
					if os.path.exists(ortlstfile_tmp):	continue
					else: todo_num += 1
					
					cmd  = "symrelax.py %s %s " % (rawimage, mapfile)
					if options.sffile: cmd += "--sf=%s " % ( options.sffile )
					if options.phasecorrected: cmd += "--phasecorrected "
					cmd += "--verbose=%d " % (options.verbose )
					cmd += "--mask=%d " % (options.mask)
					cmd += "--startSym=%s " % (options.startSym)
					cmd += "--endSym=%s " % (options.endSym)
					cmd += "--first=%d --last=%d " % (startNum, endNum)
					cmd += "--shrink=%d " % (options.shrink)
					cmd += "--ortlstfile=%s " % (ortlstfile_tmp)
					cmd += "--score=%s " % (options.scorefunc)
					if options.saveprojection:
						cmd += "--projection=%s " % (projfile)
						cmd += "--cmplstfile=%s " % (cmplstfile_tmp)					
					if i: cmd += "--nocmdlog "
						
					if i == 0: print cmd
					
					runparfp.write("%s\n" % (cmd))
				runparfp.close()
				if todo_num:
					cmd = "runpar proc=%d,%d file=%s" % (options.cpus, options.cpus, runpar_file)
					print cmd
					os.system(cmd)
			
				#now merge all sublst file
				# first test if all jobs are done properly
				done = 1
				for lstfile_tmp in sublstfiles:
					if not os.path.exists(lstfile_tmp): done = 0
				
				if done:
					EMAN.merge_lstfiles(sublstfiles, ortlstfile, delete_lstfiles = 1)
					# pool the cmplstfiles
					if options.saveprojection:
						EMAN.merge_lstfiles(cmpsublstfiles, cmplstfile, delete_lstfiles = 1)

			if not os.path.exists(ortlstfile) or (os.path.exists(ortlstfile) and os.path.getsize(ortlstfile)<=5):
				print "ERROR: raw image new orientation results lst file \"%s\" is not generated properly" % (ortlstfile)
				sys.exit()
	
		if not os.path.exists(mapfile2):
			reconstruction_by_make3d(ortlstfile, mapfile2, options=options, mapfile2e=mapfile2e, mapfile2o=mapfile2o, fscfile=fscfile)
			if not (os.path.exists(mapfile2) and os.path.getsize(mapfile2)):
				print "ERROR: 3D map \"%s\" is not generated properly" % (mapfile2)
				sys.exit()
		
	EMAN.LOGend()
Ejemplo n.º 23
0
def main():
	if sys.argv[-1].startswith("usefs="): sys.argv = sys.argv[:-1]	# remove the runpar fileserver info

	(options,args) =  parse_command_line()
	
	if not options.nolog and (not mpi or (mpi and mpi.rank==0)): EMAN.appinit(sys.argv)

	inputParm = EMAN.ccmlInputParm()
	sf = EMAN.XYData()
	if options.sfFileName != "" :
		readsf = sf.readFile(options.sfFileName)
		if ((readsf == -1) and (options.verbose > 0)) :
			print "The file of scattering factor does NOT exist"
	inputParm.scateringFactor = sf

	startNumOfRawImages = options.startNumOfRawImages
	#endNumOfRawImages = options.endNumOfRawImages

	refImageFileName = args[-1]
	numOfRefImages = options.numOfRefImages
	solutionFile = options.solutionFile

	# write log info to .emanlog file so that eman program can browse the history
	if not options.nolog and (not mpi or (mpi and mpi.rank==0)): 
		pid = EMAN.LOGbegin(sys.argv)
		for f in args[0:-1]: EMAN.LOGInfile(pid,f)
		EMAN.LOGReffile(pid,args[-1])
		if options.solutionFile: EMAN.LOGOutfile(pid,options.solutionFile)
		if options.listFile: EMAN.LOGOutfile(pid,options.listFile)
		if options.mrcSolutionFile: EMAN.LOGOutfile(pid,options.mrcSolutionFile)

	inputParm.sym = options.sym
	inputParm.FFTOverSampleScale = options.FFTOverSampleScale
	inputParm.pftStepSize = options.pftStepSize
	inputParm.deltaR = options.deltaR
	inputParm.RMin = options.RMin
	inputParm.RMax = options.RMax
	inputParm.searchMode = options.searchMode
	inputParm.scalingMode = options.scalingMode
	inputParm.residualMode = options.residualMode
	inputParm.weightMode = options.weightMode
	# inputParm.rawImageFN will be set later
	inputParm.refImagesFN = refImageFileName
	inputParm.rawImageIniParmFN = options.rawImageIniParmFN
	inputParm.rawImagePhaseCorrected = options.phasecorrected

	inputParm.maxNumOfRun = options.maxNumOfRun
	inputParm.zScoreCriterion = options.zScoreCriterion
	inputParm.residualCriterion = options.residualCriterion
	inputParm.solutionCenterDiffCriterion = options.solutionCenterDiffCriterion
	inputParm.solutionOrientationDiffCriterion = options.solutionOrientationDiffCriterion/180.0*pi
	inputParm.maxNumOfIteration = options.maxNumOfIteration
	inputParm.numOfRandomJump = options.numOfRandomJump
	inputParm.numOfFastShrink = options.numOfFastShrink
	inputParm.numOfStartConfigurations = options.numOfStartConfigurations
	inputParm.orientationSearchRange = options.orientationSearchRange/180.0*pi
	inputParm.centerSearchRange = options.centerSearchRange

	inputParm.numOfRefImages = options.numOfRefImages
	inputParm.refEulerConvention = options.refEulerConvention
	#maskR = options.maskR
	#if (maskR<=0): maskR = refImageSizeY/2

	inputParm.verbose = options.verbose
	verbose = options.verbose
	#verboseSolution = options.verboseSolution

	updataHeader = options.updataHeader
	solutionFile = options.solutionFile
	mrcSolutionFile = options.mrcSolutionFile
	iniCenterOrientationMode = options.iniCenterOrientationMode
	refCenterOrientationMode = options.refCenterOrientationMode

	rawImages = []
	if not mpi or (mpi and mpi.rank==0):
		for imgfile in args[0:-1]:
			imgnum = EMAN.fileCount(imgfile)[0]
			for i in range(imgnum): rawImages.append((imgfile, i))
	if mpi: rawImages = mpi.bcast(rawImages)
	
	endNumOfRawImages = options.endNumOfRawImages
	if endNumOfRawImages <=0  or endNumOfRawImages > len(rawImages):
		endNumOfRawImages = len(rawImages)

	numRawImages = endNumOfRawImages - startNumOfRawImages

	if mpi:
		ptclset = range(startNumOfRawImages + mpi.rank, endNumOfRawImages, mpi.size)
	else:
		ptclset = range(startNumOfRawImages, endNumOfRawImages)
	
	solutions = []

	rMask = options.rMask        #mask size is given
	if options.rMask <= 0 : rMask = refImageSizeY/2   #mask size = half image size
	
	rMask1 = options.rMask1             #output tnf mask size is given
	if options.rMask1 <= 0 : rMask1 = rMask    #output tnf mask size = half image size

	inputParm.rMask = rMask
	inputParm.rMask1 = rMask1

	rawImage = EMAN.EMData()
	rawImage.getEuler().setSym(inputParm.sym) #set the symmetry of the raw partile
	inputParm.rawImageFN = rawImages[0][0] #give the initial raw particle filename
	print "start to prepare------"
	rawImage.crossCommonLineSearchPrepare(inputParm) #prepare, create pseudo PFT of ref images
	print "end to prepare------"
	inputParm.rawImage = rawImage
	#for rawImgSN in ptclset:
	for index in range(len(ptclset)):
		rawImgSN = ptclset[index]
		inputParm.rawImageFN = rawImages[rawImgSN][0]
		inputParm.thisRawImageSN = rawImages[rawImgSN][1]
		if mpi: print "rank %d: %d in %d-%d (%d in %d-%d)" % (mpi.rank, rawImgSN, startNumOfRawImages, endNumOfRawImages, index, 0, len(ptclset))
		#rawImage.readImage(rawImages[rawImgSN][0], rawImages[rawImgSN][1])

		#rawImage.applyMask(rMask, 6) #apply mask type 6 [edge mean value] to raw image, center will be image center
		#rawImage.getEuler().setSym("icos")
		#if rawImage.hasCTF() == 1:
			#ctfParm = rawImage.getCTF()
			#inputParm.zScoreCriterion = options.zScoreCriterion + atan(abs(ctfParm[0])-1.5)/(pi/4) +0.59 #adjust zScore criterion -0.6 --> +1.2, 1.5, 2.0
			#inputParm.numOfRefImages = int(min(numOfRefImages, max(numOfRefImages*exp(-(abs(ctfParm[0])/2.0-0.15))+0.5, 5.0))) # adjust maxNumOfRun, the min is 2

		inputParm.thisRawImageSN = rawImgSN

		solutionCenterDiffCriterion = inputParm.solutionCenterDiffCriterion
		solutionOrientationDiffCriterion = inputParm.solutionOrientationDiffCriterion

		#initialize Center And Orientation by ont of the following modes

		if iniCenterOrientationMode == "iniparmfile" :
			inputParm.initializeCenterAndOrientationFromIniParmFile() # need to set "refEulerConvention"
		elif iniCenterOrientationMode == "headerfile" :
			inputParm.initializeCenterAndOrientationFromParticle() # need to set "refEulerConvention"
		else :
			inputParm.initializeCenterAndOrientationFromRandom()  # default is random orientation and physical center

		#set the refence Center And Orientation by ont of the following modes

		if refCenterOrientationMode == "iniparmfile" : inputParm.setRefCenterAndOrientationFromIniParmFile() # need to set "refEulerConvention"
		elif refCenterOrientationMode == "headerfile" : inputParm.setRefCenterAndOrientationFromParticle() # need to set "refEulerConvention"
		else : inputParm.setRefCenterAndOrientationFromInitializedParms() # default is copy the initial center and orientation

		rawImage.crossCommonLineSearchReadRawParticle(inputParm) #create pseudo PFT of raw image

		maxNumOfRun = inputParm.maxNumOfRun
		outputParmList = []
		numOfRun = 0
		passAllConsistencyCriteria = 0
		while (numOfRun < maxNumOfRun) or (len(outputParmList) < 2):

			if (iniCenterOrientationMode != "iniparmfile") and (iniCenterOrientationMode != "headerfile") :
				inputParm.initializeCenterAndOrientationFromRandom()  # default is random orientation and physical center
			if (refCenterOrientationMode != "iniparmfile") and (refCenterOrientationMode != "headerfile") :
				inputParm.setRefCenterAndOrientationFromInitializedParms() # default is copy the initial center and orientation

			numOfRun = numOfRun + 1
			print "numOfRun = ", numOfRun

			############################################################################
			############ execute cross common line search for reference ################
			############################################################################
			outputParm  = rawImage.crossCommonLineSearch(inputParm)
			############################################################################
			# pass criteria check
			outputParmList.append(outputParm) #if passed criteria, e.g. zscore, residualThreshold, etc
			############################################################################

			outputParmList.sort(lambda x, y: cmp(x.residual, y.residual))

			############################################################################
			########################## consistency check ###############################
			############################################################################
			#passConsistencyCriteria = 0
			finalOutputParmList = []
			lowestResidualList = []
			lengthOfList = len(outputParmList)
			if lengthOfList < 2 : continue
			for i in range(lengthOfList-1):
				thisOutputParm = outputParmList[i]
				numOfPairsPassConsistencyCheck = 0
				for j in range(i+1,lengthOfList):
					refOutputParm = outputParmList[j]
					tmpOutputParm = EMAN.ccmlOutputParm() #create a new output parm object
					tmpOutputParm.rawImageSN = thisOutputParm.rawImageSN #copy all paramenters
					tmpOutputParm.residual = thisOutputParm.residual
					tmpOutputParm.sigma = thisOutputParm.sigma
					tmpOutputParm.verbose = thisOutputParm.verbose
					tmpOutputParm.zScore = thisOutputParm.zScore
					tmpOutputParm.zScoreCriterion = thisOutputParm.zScoreCriterion

					tmpOutputParm.passAllCriteria = 0
					tmpOutputParm.setCalculatedCenterAndOrientation(thisOutputParm.cx,thisOutputParm.cy,thisOutputParm.q)
					tmpOutputParm.setRefCenterAndOrientation(refOutputParm.cx, refOutputParm.cy, refOutputParm.q)
					tmpOutputParm.calculateDifferenceWithRefParm() #calculated the difference

					centerDiff = tmpOutputParm.centerDiff
					orientationDiff = tmpOutputParm.orientationDiff
					
					#####  FLIP CASE :  if no consistency found, try flip this orientation
					if ((centerDiff > solutionCenterDiffCriterion) or (orientationDiff > solutionOrientationDiffCriterion)) :
						quatFlip = EMAN.Quaternion(refOutputParm.q.getEuler().alt(), refOutputParm.q.getEuler().az(), refOutputParm.q.getEuler().phi()+pi)
						tmpOutputParm.setRefCenterAndOrientation(refOutputParm.cx, refOutputParm.cy, quatFlip)
						tmpOutputParm.calculateDifferenceWithRefParm() #calculated the difference
						centerDiff = tmpOutputParm.centerDiff
						orientationDiff = tmpOutputParm.orientationDiff
						tmpOutputParm.setRefCenterAndOrientation(refOutputParm.cx, refOutputParm.cy, refOutputParm.q) #set back the exact orientation of reference 

					#Save the configurations with lowest residuals
					if (i<3) and (j==i+1) : lowestResidualList.append(tmpOutputParm)
					
					#make the good/answers list
					if ((centerDiff < solutionCenterDiffCriterion) and (orientationDiff < solutionOrientationDiffCriterion)) :
						numOfPairsPassConsistencyCheck += 1
						if numOfPairsPassConsistencyCheck == 1 : #save to the final list
							tmpOutputParm.passAllCriteria = 1
							finalOutputParmList.append(tmpOutputParm)
						if i==0 and numOfPairsPassConsistencyCheck >= options.numConsistentRun: #if the first one, check whether it has 3 pair of consistencies
							passAllConsistencyCriteria = 1
							break
						if i>0 : break #if not the first one, find one pair of consistency, then break
				
				#no break here, just for saving all possible solutions

			if passAllConsistencyCriteria and len(finalOutputParmList) >= options.numConsistentRun: break #if 3 consistent pair orientations were found, then stop


		rawImage.crossCommonLineSearchReleaseParticle(inputParm) # release the memory related to this raw particle

		# if no consistency found, keep the lowest ones as output
		if len(finalOutputParmList) == 0 : finalOutputParmList = lowestResidualList
		for i in range(len(finalOutputParmList)) : 
			if passAllConsistencyCriteria : finalOutputParmList[i].passAllCriteria = 1
			else : finalOutputParmList[i].passAllCriteria = 0

		if options.solutionFile:
			for i in range(len(finalOutputParmList)) : finalOutputParmList[i].outputResult(solutionFile)

		outputParm = finalOutputParmList[0] #just use the lowest residual as regular output
		if outputParm.passAllCriteria: 	passfail = "pass"
		else: passfail = "fail"

		print "Final result: euler=%g\t%g\t%g\tcenter=%g\t%g\tresidue=%g\t%s" % (outputParm.alt*180/pi, outputParm.az*180/pi, outputParm.phi*180/pi, outputParm.cx, outputParm.cy, outputParm.residual, passfail)
		
		if options.scoreFile:
			rawImage.readImage(rawImages[rawImgSN][0], rawImages[rawImgSN][1], 1) # read header only
			if rawImage.hasCTF(): 
				defocus = rawImage.getCTF()[0]
		else:
			defocus = 0

		solution = (rawImages[rawImgSN][0], rawImages[rawImgSN][1], outputParm.alt, outputParm.az, outputParm.phi, \
					   outputParm.cx, outputParm.cy, defocus, outputParm.residual, outputParm.passAllCriteria)
		solutions.append( solution )

		sys.stdout.flush()

	rawImage.crossCommonLineSearchFinalize(inputParm) #finalize, i.e. delete memories

	if mpi:
		if options.verbose: 
			print "rank %d: done and ready to output" % (mpi.rank)
			sys.stdout.flush()
		mpi.barrier()
		#print "rank %d: %s" % (mpi.rank, solutions)
		if mpi.rank==0:
			for r in range(1,mpi.size):
				msg, status = mpi.recv(source = r, tag = r)
				solutions += msg
			def ptcl_cmp(x, y):
				eq = cmp(x[0], y[0])
				if not eq: return cmp(x[1],y[1])
				else: return eq
			solutions.sort(ptcl_cmp)
		else:
			mpi.send(solutions, 0, tag = mpi.rank)

	if not mpi or (mpi and mpi.rank==0):
		if options.scoreFile:
			sFile = open(options.scoreFile, "w")
			sFile.write("#LST\n")
			for i in solutions:
				if i[-1]: 
					sFile.write("%d\t%s\tdefocus=%g\tresidual=%g\n" % (i[1], i[0], i[7], i[8]))
			sFile.close()
			
		if options.listFile:
			lFile = open(options.listFile, "w")
			lFile.write("#LST\n")
			for i in solutions:
				if i[-1]: 
					lFile.write("%d\t%s\t%g\t%g\t%g\t%g\t%g\n" % (i[1], i[0], i[2]*180.0/pi, i[3]*180.0/pi, i[4]*180.0/pi, i[5], i[6]))
			lFile.close()
		if options.mrcSolutionFile:
			outFile = open(options.mrcSolutionFile, "w")
			for i in solutions:
				if i[-1]:
					#rawImage.readImage(i[0], i[1], 1)
					rawImage.readImage(i[0], i[1])
					thisEu = EMAN.Euler(i[2], i[3], i[4])
					thisEu.convertToMRCAngle()
					alt = thisEu.alt_MRC()*180.0/pi
					az  = thisEu.az_MRC()*180.0/pi
					phi = thisEu.phi_MRC()*180.0/pi
		
					cx  = i[5]
					cy  = i[6]
					dx = cx - rawImage.xSize()/2
					dy = cy - rawImage.ySize()/2
					rawImage.applyMask(rMask1,6,dx,dy,0) #apply mask type 4 [outside=0] to raw image, center will be the solved center
					#tnfFileName = "%s-%d.tnf" % (os.path.basename(os.path.splitext(rawImages[rawImgSN][0])[0]), rawImages[rawImgSN][1])
					prefix = os.path.dirname(options.mrcSolutionFile).replace(" ", "")
					if prefix != "" : prefix = prefix + "/"
					tnfFileName = "%s%s-%d.tnf" % (prefix,os.path.basename(os.path.splitext(i[0])[0]), i[1])
					rawFFT = rawImage.doFFT()
					rawFFT.writeImage(tnfFileName,0)  #tnf file no header information, it is a pure FFT of raw image file
		
					outFile.write("%s\n" % (os.path.abspath(tnfFileName)))
					outFile.write(" %d, %.4f, %.4f, %.4f, %.4f, %.4f, 0.0\n" % (0, alt, az, phi, cy, cx))
			outFile.close()
		if updataHeader:
			for i in solutions:
				rawImage.readImage(i[0], i[1], 1)
				if options.verbose:
					cx  = rawImage.get_center_x()
					cy  = rawImage.get_center_y()
					alt = rawImage.alt()
					az  = rawImage.az()
					phi = rawImage.phi()
					print "Update header: %s %d\t%7.5f  %7.5f  %7.2f  %7.2f  %7.2f => %7.5f  %7.5f  %7.2f  %7.2f  %7.2f" % \
						(i[0], i[1], alt*180.0/pi, az*180.0/pi, phi*180.0/pi, cx, cy, i[2]*180.0/pi, i[3]*180.0/pi, i[4]*180.0/pi, i[5], i[6])
				rawImage.setRAlign(i[2], i[3], i[4])
				rawImage.set_center_x(i[5])
				rawImage.set_center_y(i[6])
				imgtype = EMAN.EMData.ANY
				rawImage.writeImage(i[0], i[1], imgtype, 1)
	if not options.nolog and (not mpi or (mpi and mpi.rank==0)): EMAN.LOGend()
# get eulers from proj.img file

import sys, os
from math import pi
try:
    import EMAN
except ImportError:
    print "EMAN module did not get imported"

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print "Usage: getProjEulers.py <infile> <outfile>\n"
        sys.exit(1)

    projfile = sys.argv[1]
    outfile = sys.argv[2]

    out = open(outfile, "w")

    count, imgtype = EMAN.fileCount(projfile)
    imgs = EMAN.EMData()
    imgs.readImage(projfile, 0, 1)
    for i in range(count):
        imgs.readImage(projfile, i, 1)
        e = imgs.getEuler()
        alt = e.alt() * 180. / pi
        az = e.az() * 180. / pi
        phi = e.phi() * 180. / pi
        out.write("%i\t%f\t%f\t%f\n" % (i, alt, az, phi))
    out.close()
Ejemplo n.º 25
0
#===============================
if __name__ == '__main__':
    # write command & time to emanlog if exists:
    if os.path.exists('refine.log'):
        cmd = string.join(sys.argv, ' ')
        apEMAN.writeEMANTime('refine.log', cmd)
    #Parse inputs
    args = sys.argv[1:]
    params = createDefaults()
    parseInput(args, params)

    if params['coranmask'] is None:
        params['coranmask'] = params['mask']

    #Determine box size
    tmpimg = EMAN.readImages('start.hed', 1, 1)
    params['boxsize'] = tmpimg[0].xSize()

    #determine num of projections needed
    im = EMAN.EMData()
    e = im.getEuler()
    e.setSym(params['sym'])
    params['symnum'] = e.getMaxSymEl()

    #Set up for symmetry relax
    params['relaxdir'] = params['relaxdir'] + str(params['iter'])
    if os.path.exists(params['relaxdir']):
        print "WARNING!!! %s exists and is being overwritten" % params[
            'relaxdir']
        shutil.rmtree(params['relaxdir'])
        os.mkdir(params['relaxdir'])
Ejemplo n.º 26
0
#!/bin/python

# this will save the particle stack number into the header of a stack.
# use this if you want to run cenalignint, and keep track of the particles.
# NOTE!!! CONFORMS TO EMAN CONVENTION, STARTS AT 0!!!!

import sys
try:
    import EMAN
except ImportError:
    print "EMAN module did not get imported"

if __name__ == "__main__":

    if len(sys.argv) < 2:
        print "usage: renumber.py [filename]"
        sys.exit()

    filename = sys.argv[1]

    n = EMAN.fileCount(filename)[0]
    im = EMAN.EMData()
    for i in range(n):
        im.readImage(filename, i)
        im.setNImg(i)
        im.writeImage(filename, i)
        print i
Ejemplo n.º 27
0
#!/usr/bin/env python
import sys
import EMAN

if len(sys.argv)!=4:
	print "Usage: %s <input box file> <scale> <output box file>" % (sys.argv[0])
	sys.exit()

boxin = EMAN.readEMANBoxfile(sys.argv[1])
boxout = EMAN.scaleBoxes(boxin, int(sys.argv[2]))
EMAN.writeEMANBoxfile(sys.argv[3], boxout)

Ejemplo n.º 28
0
        rap = float(s[1])
    elif (s[0] == 'norm'):
        norm = int(s[1])
    elif (s[0] == 'searchx'):
        searchx = int(s[1])
    elif (s[0] == 'searchy'):
        searchy = int(s[1])
    elif (s[0] == 'searchz'):
        searchz = int(s[1])
    else:
        print("Unknown argument " + a)
        exit(1)

print target, probe

targetMRC = EMAN.EMData()
targetMRC.readImage(argv[1], -1)
targetMean = targetMRC.Mean()
targetSigma = targetMRC.Sigma()
print "Target Information"
print "   mean:       %f" % (targetMean)
print "   sigma:      %f" % (targetSigma)

target_xsize = targetMRC.xSize()
target_ysize = targetMRC.ySize()
target_zsize = targetMRC.zSize()
if (target_xsize != target_ysize != target_zsize) or (target_xsize % 2 == 1):
    print "The density map must be even and cubic. Terminating."
    sys.exit()
box = target_xsize
Ejemplo n.º 29
0
#!/usr/bin/env python
import sys, os
from math import pi
import EMAN

if len(sys.argv) != 3:
	print "%s: convert image orientation and center (in EMAN convention) stored in the image headers into a text file in MRC/IMIRS format/convention" % (sys.argv[0])
	print "Usage: %s <input image file> <output ortcen file>" % (sys.argv[0])
	sys.exit(1)

imagefile = sys.argv[1]
output_ortcen_file = sys.argv[2]

imgnum, imgtype = EMAN.fileCount(imagefile)

img = EMAN.EMData()
img.readImage(imagefile, 0, 1)	# read Header only
imagesize = img.xSize()

imagefile_prefix = os.path.splitext(output_ortcen_file)[0]

outFile = open(output_ortcen_file, "w")
	
e5fto2f = EMAN.Euler(1.0172219678978513677, pi, -pi/2)	# rotation from 2fold to 5fold

for i in range(imgnum):
	print "Working on image %d/%d\r" % (i, imgnum) , 
	img.readImage(imagefile, i, 1)
	e = img.getEuler()
	
	e2 = e * e5fto2f;	# use 2-fold view instead of 5-fold view as orientation origin
Ejemplo n.º 30
0
def parse_command_line():
	usage="Usage: %prog <Raw image filename 1> ... <Raw image filename n> <reference filename> [options]"
	parser = OptionParser(usage=usage)

	parser.add_option("--createconfigFile",dest="createconfigFile",type="string",help="use to create a configure file under a given directory and file name (Default file name is [./ccmlConfigFile.ini])", default="./ccmlConfigFile.ini")
        parser.add_option("--configFile",dest="configFile",type="string",help="all/parts of the parameters can be read from this file. command line parameters have higher priority, but it will be enforced to use if an 'endforce' is followed by the corresponding values. (Default file name is [./ccmlConfigFile.ini])", default="./ccmlConfigFile.ini")
        parser.add_option("--saveParms",dest="saveParms",type="string",help="if a file name is given, the actually parameters will be saved to the file. (default is not save if no name)", default="")

	#options
	parser.add_option("--sym",dest="sym",type="string",help="set symmetry of the particle, (default is \"icos\")",default="icos")
	parser.add_option("--rMask",dest="rMask",type="int",help="Mask will be applied to image center. The radial size = rMask, [half image size]",default=0)
	parser.add_option("--rMask1",dest="rMask1",type="int",help="Mask will be applied to solved particle center. The radial size = rMask1, [rMask]",default=0)
	parser.add_option("--startNum",dest="startNumOfRawImages",type="int",help="The starting image number",default=0)
	parser.add_option("--endNum",dest="endNumOfRawImages",type="int",help="The ending image number, (0 is default, all images)",default=0)
	parser.add_option("--numOfRefImages",dest="numOfRefImages",type="int",help="Number of projection images to use for calculating orientation, (5 is default)",default=5)
	parser.add_option("--scatteringFactorFile",dest="sfFileName",type="string",help="File name for scattering factor of raw images",default="")
	parser.add_option("--phasecorrected",dest="phasecorrected",action="store_true",help="if the particle images already phase flipped. default to false", default=0)
	parser.add_option("--overSample",dest="FFTOverSampleScale",type="int",help="Scale of over sample FFT, (1 is default, NO over sample)",default=1)
	parser.add_option("--pftStepSize",dest="pftStepSize",type="float",help="Angular step size for creating pseudo PFT, (0.1 degree is default)",default=0.1)
	parser.add_option("--radialStepSize",dest="deltaR",type="float",help="Radial step size for collecting data on common line, (1.0 is default)",default=1.0)
	parser.add_option("--radialStartPoint",dest="RMin",type="int",help="Radial start point for collecting data on common line, (5 is default)",default=5)
	parser.add_option("--radialEndPoint",dest="RMax",type="int",help="Radial end point for collecting data on common line, (35 is default)",default=35)
	#parser.add_option("--maskRadius",dest="maskR",type="int",help="Mask radius to remove background pixels at large radius (default to half of image size)",default=0)
	parser.add_option("--orientationSearchRange",dest="orientationSearchRange",type="float",help="Maximum orientation deviation from a given one, (36.0 is default)",default=36.0)
	parser.add_option("--centerSearchRange",dest="centerSearchRange",type="float",help="Maximum center deviation from a given one, (15.0 is default)",default=15.0)
	parser.add_option("--maxIteration",dest="maxNumOfIteration",type="int",help="Maximum iteration, (1000 is default for coarse search, 150 for refinement)",default=150)
	parser.add_option("--numOfRandomJump",dest="numOfRandomJump",type="int",help="iteration of beginning random jump, (50 is default for coarse search, 20 for refinement)",default=20)
	parser.add_option("--numOfFastShrink",dest="numOfFastShrink",type="int",help="iteration of ending fast shrink, (150 is default for coarse search, 80 for refinement)",default=80)
	parser.add_option("--numOfStartConfigurations",dest="numOfStartConfigurations",type="int",help="starting configurations, (10 is default)",default=10)
	parser.add_option("--searchMode",dest="searchMode",type="int",help="Mode to handle a raw image, (0 is default)",default=0)
	parser.add_option("--scalingMode",dest="scalingMode",type="int",help="Mode to handle a raw image, (0 is default)",default=0)
	parser.add_option("--residualMode",dest="residualMode",type="int",help="Mode to calculate residual, (2 is default)",default=2)
	parser.add_option("--weightMode",dest="weightMode",type="int",help="Weighting function mode to calculate residual, default to 1",default=1)
	parser.add_option("--iniParameterFile",dest="rawImageIniParmFN",type="string",help="File name for initial orientation and center of raw images",default="")
	parser.add_option("--refEulerConvention",dest="refEulerConvention",type="choice",choices=["eman","mrc"],help='Spcify an euler convention of the refence orientation. choices are ["eman","mrc"]. default to "eman"',default="eman")
	parser.add_option("--iniCenterOrientationMode",dest="iniCenterOrientationMode",type="choice",choices=["random","headerfile","iniparmfile"],help='mode to initialize particle center and orientation. choices are  ["random","headerfile","iniparmfile"]. default to "random"',default="random")
	parser.add_option("--refCenterOrientationMode",dest="refCenterOrientationMode",type="string",help="mode to set reference center and orientation of the particle [copy from ini]",default="")
	parser.add_option("--zScoreCriterion",dest="zScoreCriterion",type="float",help="The criterion of stopping run, (6.0 is default)",default=6.0)
	parser.add_option("--residualCriterion",dest="residualCriterion",type="float",help="The criterion of stopping run, (default: no residual criterion)",default=-1.0)
	parser.add_option("--solutionCenterDiffCriterion",dest="solutionCenterDiffCriterion",type="float",help="The criterion of stopping run, (default: no solution center diff criterion)",default=-1.0)
	parser.add_option("--solutionOrientationDiffCriterion",dest="solutionOrientationDiffCriterion",type="float",help="The criterion of stopping run, (default: no solution orientation diff criterion)",default=-1.0)
	parser.add_option("--numConsistentRun",dest="numConsistentRun",type="int",help="number of runs with consistent orienttion/center to accept as success. default to 2", default=2)
	parser.add_option("--maxNumOfRun",dest="maxNumOfRun",type="int",help="Maximum number of re-search, (5 is default)",default=5)
	parser.add_option("--updateHeader", dest="updataHeader",type="int", help="Write the calculated result to the header file, (default is O, NO update)",default=0)
	parser.add_option("--solutionFile",dest="solutionFile",type="string",help="File name for outputing results, (default is Raw image filename + \"-OrientationCenter.dat\")",default="")
	parser.add_option("--mrcSolutionFile",dest="mrcSolutionFile",type="string",help="File name for outputing results in MRC format, (default is Raw image filename + \"-MRC-OrientationCenter.dat\") ",default="")
	parser.add_option("--listFile",dest="listFile",type="string",help="File name for listing good particles in EMAN LST format",default="")
	parser.add_option("--scoreFile",dest="scoreFile",type="string",help="File name for the defocus and residual values of good particles in EMAN LST format",default="")
	parser.add_option("--verbose", dest="verbose",type="int", help="verbose level [0-5], (default is O, no screen print out)",default=0)
	parser.add_option("--nolog",dest="nolog",action="store_true",help="don't log the command in .emanlog", default=0)

	if(len(sys.argv) > 1) : #for creating configure file
		configFileName = ""
		if (sys.argv[1] == "--createconfigFile" ) or (sys.argv[1] == "--createconfigFile=" ) : configFileName = "./ccmlConfigFile.ini" #default value
		elif re.match("--createconfigFile=",sys.argv[1]) : #if specified
			splitPosition = re.match("--createconfigFile=",sys.argv[1]).end()
			configFileName = sys.argv[1][splitPosition:]
		if configFileName != "" : createConfigureFile(configFileName) #create the configure file, then quite the program


	(options, args)=parser.parse_args() #this is first parse the command line inputs, later a pseudo command line option will be parsed

	allAdoptedOptions = {} #make a dictionary for saving the final adopted options which combines the command line options and the options form configure file
	for aArg in sys.argv[1:] : 
		if re.match('--.*.=', aArg) :
			splitPosition = re.match('--.*.=', aArg).end()
			allAdoptedOptions[aArg[2:(splitPosition-1)]] = aArg[splitPosition:]
		elif re.match('--.*.', aArg) :
			allAdoptedOptions[aArg[2:]] = ""


	if not os.path.exists(options.configFile) : #check if the default or given configure file is exist or not
		if options.configFile != "./ccmlConfigFile.ini" : 
			print "The configure file : %s does NOT exist, QUIT the program!!!" % (options.configFile)
			sys.exit(-1)
	else :

		config = ConfigParser.ConfigParser()
		config.optionxform = str #output case-sensitive options
		config.read(options.configFile)

	        tempListCommandParms = []
		tempListArgs = []
		tempRefImg = ""
                tempListOptions = []
		rawImgEnforced = False
		refImgEnforced = False
		tempListOptions.append("--%s=%s" % ("configFile",options.configFile)) #set value for configFile option
		for section in config.sections(): #parse the configure file
        		for option in config.options(section):
				#print option, " = ", config.get(section, option)
				values = config.get(section, option).replace(","," ").split()
				if len(values)==0 : continue  # if give nothing, it will be ignored
				if values[0][0] == ";" or values[0][0] == "#" : continue  #sometimes, no value given, the parse will take comments as its value
				enforced = False
				if len(values) > 1 and re.search('enforce', values[-1]) : enforced = True  #detect if this value will be enforced to replace the command line value
				if re.search('option',section.lower()) :
					if ((values[0].lower == 'yes') or (values[0].lower == 'true')) : values[0]='True' 
                                        if ((values[0].lower == 'no') or (values[0].lower == 'false')) : values[0]='False'
					if not allAdoptedOptions.has_key(option) : allAdoptedOptions[option] = values[0] #if not specified in command line, add this option
					elif enforced : allAdoptedOptions[option] = values[0]                             #if enforced, this option will replce the corresponding command line's value
				if re.search('require',section.lower()) : #for required arguments in configure file
                                        if  re.match('raw.*.image.*.file', string.join(option.split(), sep=" ").lower()) : #remove all unneccessary spaces and convert to lower cases
						if enforced : 
							rawImgEnforced = True 
							tempListArgs = values[:-1]
						else :  tempListArgs = values  #raw images could be in multiple files
					if  re.match('ref.*.image.*.file', string.join(option.split(), sep=" ").lower()) : 
                                                if enforced : refImgEnforced = True
						tempRefImg = values[0] #for reference image
		argsFinal = []
		if len(args) == 0 :
                        argsFinal = tempListArgs
			argsFinal.append(tempRefImg)
		if len(args) == 1 :
			if not rawImgEnforced: 
				argsFinal = args
				argsFinal.append(tempRefImg)
			else : 
				argsFinal = tempListArgs
                                argsFinal.append(tempRefImg)
                if len(args) >= 2 :
			if rawImgEnforced and refImgEnforced : 
				argsFinal = tempListArgs
				argsFinal.append(tempRefImg)
                        elif (not rawImgEnforced) and refImgEnforced :
                                argsFinal = args[:-1]
                                argsFinal.append(tempRefImg)
                        elif rawImgEnforced and (not refImgEnforced) :
                                argsFinal = tempListArgs
                                argsFinal.append(args[-1])
			else : argsFinal = args

		args = argsFinal #copy the final args to the args, the adopted options is already in list, allAdoptedOptions

        adoptedArguments = [] #all actually adopted paramemters
	#adoptedArguments = args #copy all the required argument to the list
	for i in range(len(args)) : adoptedArguments += glob.glob(args[i]) #check if the raw and ref images exist and extend the pattern file name to all real names
       	for anOption in allAdoptedOptions : #it combines the both comand line options and the options from configure file
		if allAdoptedOptions[anOption] == "False" : continue  #if it is False, does not space
		if allAdoptedOptions[anOption] == "True" or allAdoptedOptions[anOption] == "" : adoptedArguments.append("--" + anOption) #for the option take no value, just specifiy it as True
               	else : adoptedArguments.append("--" + anOption + "=" + str(allAdoptedOptions[anOption]))

	#print adoptedArguments

	(options, args)=parser.parse_args(adoptedArguments) # parse the adoptedArguments by command line parser
	
	if len(args) < 2:
		parser.print_help()
		sys.exit(-1)

	if options.saveParms != "" :
		commandtime = time
		t = commandtime.localtime()
		timeStr = "# Command start time    %s/%s/%s %s:%s:%s\n" % (t[1],t[2],t[0],t[3],t[4],t[5])
	        commandStr = sys.argv[0] #save all actually used paramemters
        	for aArg in args :  commandStr += (" " + aArg)
        	#for anOption in options.__dict__ : commandStr += (" --" + anOption + "=" + str(options.__dict__[anOption])) #output all internal used parameters
		for anOption in allAdoptedOptions : 
			if allAdoptedOptions[anOption] == "False" : continue  #if it is False, does not space
			if allAdoptedOptions[anOption] == "True" or allAdoptedOptions[anOption] == "" : commandStr += (" --" + anOption) #for the option take no value, just specifiy it as True
			else : commandStr += (" --" + anOption + "=" + str(allAdoptedOptions[anOption])) #output all input parameters
		commandStr += "\n" 

		f=open(options.saveParms, "a")
		f.write(timeStr)
		f.write(commandStr)
		f.close()


	for key in parser.option_list[1:]:  #this omits the -h/--help option
		eval_string = "options.%s" % (key.dest)
		value = eval(eval_string)
		if value == None:
			if (options.verbose > 0) :
				print "The option %s must be specified on the command line" % (key)
			sys.exit(-1)

	#remove the input string's spaces, some string may need to convert to lower cases
	options.sfFileName = options.sfFileName.replace(" ", "")
	options.rawImageIniParmFN = options.rawImageIniParmFN.replace(" ", "")
	options.solutionFile = options.solutionFile.replace(" ", "")
	options.mrcSolutionFile = options.mrcSolutionFile.replace(" ", "")
	options.iniCenterOrientationMode = options.iniCenterOrientationMode.lower().replace(" ", "")
	options.refCenterOrientationMode = options.refCenterOrientationMode.lower().replace(" ", "")
	options.refEulerConvention = options.refEulerConvention.lower().replace(" ", "")

	#if options.solutionFile == "":
	#	options.solutionFile = os.path.splitext(args[0])[0] + "-OrientationCenter.dat"

	#if options.mrcSolutionFile == "":
	#	options.mrcSolutionFile = os.path.splitext(args[0])[0] + "-MRC-OrientationCenter.dat"

	#numOfRawImages = EMAN.fileCount(args[0])[0]
	#if options.endNumOfRawImages < 1:
	#	options.endNumOfRawImages = numOfRawImages

	numOfRefImages = EMAN.fileCount(args[-1])[0]
	if options.numOfRefImages > numOfRefImages:
		options.numOfRefImages = numOfRefImages

	if options.startNumOfRawImages < 0:
		options.startNumOfRawImages = 0

	if (options.searchMode) == 0 : # coarse search
		# set default values
		if options.numOfRandomJump == 20 : options.numOfRandomJump = 1000
		if options.numOfFastShrink == 50 : options.numOfFastShrink = 300
		if options.maxNumOfIteration == 150 : options.maxNumOfIteration = 2500
		# check if the given values are less than mins
		if options.numOfRandomJump < 500 : options.numOfRandomJump = 500
		if options.numOfFastShrink <150 : options.numOfFastShrink = 150
		if options.maxNumOfIteration < (options.numOfRandomJump + options.numOfFastShrink + 500) :
			options.maxNumOfIteration = (options.numOfRandomJump + options.numOfFastShrink + 500)
		if options.maxNumOfIteration < 1500 : options.maxNumOfIteration = 1500
	elif (options.searchMode) == 1 : # refinement
		if options.rawImageIniParmFN == "" :
			if (options.verbose > 0) : print "\n\n\tFor refinement, you need to give a file name which specifies orientation and center of each image\n"
			#sys.exit(0)
		# check if the given values are less than mins
		if options.numOfRandomJump < 20 : options.numOfRandomJump = 20
		if options.numOfFastShrink < 50 : options.numOfFastShrink = 50
		if options.maxNumOfIteration < (options.numOfRandomJump + options.numOfFastShrink + 50) :
			options.maxNumOfIteration = (options.numOfRandomJump + options.numOfFastShrink + 50)
		if options.maxNumOfIteration < 120 : options.maxNumOfIteration = 120
	if options.orientationSearchRange > 36 : options.orientationSearchRange = 36
	if options.centerSearchRange > 100 : options.centerSearchRange = 100
	if options.zScoreCriterion < 0 : options.zScoreCriterion = 0
	
	allInputParameters   = "-------------------------------------------------------------------------\n"
	allInputParameters  += "--------------- All input parameters are listed as follows --------------\n"
	allInputParameters  += "-------------------------------------------------------------------------\n"
	allInputParameters  += "%40s :: %s \n" % ("Raw image file name",args[0:-1])
	allInputParameters  += "%40s :: %s \n" % ("Reference image file name",args[-1])
	if options.sfFileName != "" : allInputParameters  += "%40s :: %s \n" % ("Scattering factor file name",options.sfFileName)
	if options.searchMode == 1  : allInputParameters  += "%40s :: %s \n" % ("Raw image initial parameter file name",  options.rawImageIniParmFN)
	allInputParameters  += "%40s :: %s \n" % ("Starting number of raw images", options.startNumOfRawImages)
	allInputParameters  += "%40s :: %s \n" % ("Ending number of raw images", options.endNumOfRawImages)
	allInputParameters  += "%40s :: %s \n" % ("Number of reference images", options.numOfRefImages)
	allInputParameters  += "%40s :: %d \n" % ("Mask radius (pixels)", options.rMask)
	allInputParameters  += "%40s :: %s \n" % ("Scale of over sample FFT", options.FFTOverSampleScale)
	allInputParameters  += "%40s :: %s \n" % ("Maximum number of iteration", options.maxNumOfIteration)
	allInputParameters  += "%40s :: %s \n" % ("Iteration number of random jump", options.numOfRandomJump)
	allInputParameters  += "%40s :: %s \n" % ("Iteration number of fast shrink", options.numOfFastShrink)
	allInputParameters  += "%40s :: %s \n" % ("Center search range", options.centerSearchRange)
	allInputParameters  += "%40s :: %s \n" % ("Orientation search range", options.orientationSearchRange)
	allInputParameters  += "%40s :: %s \n" % ("Radial Step size of a common line", options.deltaR)
	allInputParameters  += "%40s :: %s \n" % ("Radial start point of a common line", options.RMin)
	allInputParameters  += "%40s :: %s \n" % ("Radial end point of a common line", options.RMax)
	allInputParameters  += "%40s :: %s \n" % ("Mode to handle a raw image", options.searchMode)
	allInputParameters  += "%40s :: %s \n" % ("Mode to calculate residual", options.residualMode)
	allInputParameters  += "%40s :: %s \n" % ("Weighting mode to calculate residual", options.weightMode)

	allInputParameters  += "%40s :: %s \n" % ("Maximum number of re-run", options.maxNumOfRun)
	allInputParameters  += "%40s :: %s%s \n" % ("The criteria of discriminating data", "z score = ", options.zScoreCriterion)
	if options.residualCriterion > 0 : allInputParameters  += "%40s :: %s%s \n" % ("", "residual threshold = ", options.residualCriterion)
	else : allInputParameters  += "%40s :: %s \n" % ("", "residual threshold = N/A")
	if options.solutionCenterDiffCriterion > 0 : allInputParameters  += "%40s :: %s%s \n" % ("", "center difference = ", options.solutionCenterDiffCriterion)
	else : allInputParameters  += "%40s :: %s \n" % ("", "center difference = N/A")
	if options.solutionOrientationDiffCriterion > 0 : allInputParameters  += "%40s :: %s%s \n" % ("", "orientation difference = ", options.solutionOrientationDiffCriterion)
	else : allInputParameters  += "%40s :: %s \n" % ("", "orientation difference = N/A")

	printOnScreen   = allInputParameters
	printOnScreen  += "-------------------------------------------------------------------------\n"
	printOnScreen  += "%40s :: %s \n" % ("Solution file name", options.solutionFile)
	printOnScreen  += "-------------------------------------------------------------------------\n"

	writeToSolutionFile  = allInputParameters
	writeToSolutionFile += "-------------------------------------------------------------------------\n\n"
	writeToSolutionFile += "%6s%8s%7s%7s%7s%7s%10s%34s%16s%24s%9s%12s\n" % ("######","X","Y","Alt","Az","Phi","residual","  sigma      Z  Z-crti Run# Status","ref center", "ref orientation", "XY diff","angle diff")
	writeToSolutionFile += "------------------------------------------------------------------------------------------------------------------------\n"
	if options.verbose > 0 and (not mpi or (mpi and mpi.rank==0)) : #print out the input parameters on screen
		print "%s " % (printOnScreen)

	if options.solutionFile and options.startNumOfRawImages == 0 : #write the input parameters to the solution file
		solutionFile = open(options.solutionFile, "w")
		solutionFile.write("%s" % (writeToSolutionFile))
		solutionFile.close()


	return (options,args)
Ejemplo n.º 31
0
def getNumParticlesInStack(stackname):
    import EMAN
    numparticles = EMAN.fileCount(stackname)[0]
    return numparticles
Ejemplo n.º 32
0
	# create new list file with only good particles
	if params['clean'] is True:
		f=open(fsp,'r')
		lines=f.readlines()
		f.close()
		fsp=fsp.split('.')[0]+'.good.lst'
		f=open(fsp,'w')
		for l in lines:
			d=l.strip().split()
			if len(d) < 3:
				f.write(l)
				continue
			if d[3][-1]=='1':
				f.write(l)
		f.close()
	n=EMAN.fileCount(fsp)[0]
	
	classnamepath = fsp.split('.')[0]+'.dir'
	if not os.path.exists(classnamepath):
		os.mkdir(classnamepath)
	b=EMAN.EMData()
	b.readImage(fsp,0)
	e=b.getEuler()

	a=EMAN.EMData()
	if format == "eman" or format=="imagic":
		outname="aligned.hed"
	else:
		outname="aligned.spi"

	startn = 1
Ejemplo n.º 33
0
nbasis=20
mask=-1

for i in argv[3:] :
#	s=i.split('=')
	s=string.split(i,'=')
	if (s[0]=="n") : nbasis=int(s[1])
	elif (s[0]=="mask") : mask=int(s[1])
	else:
		print "Unknown argument ",i
		exit(1)

EMAN.LOGbegin(argv)

n=EMAN.fileCount(argv[1])
if (n<2) :
	print("Umm... I'd really be happier if the input file had at least 2 images...")
	sys.exit(1)

nbasis=min(n,nbasis)
print "%d source images to consider\nGenerating %d basis images\n"%(n,nbasis)

basis=[EMAN.EMData()]			# the actual basis vectors
basisn=[0]						# list of the input image number used to generate each basis vector
basis[0].readImage(argv[1],0)
basis[0].realFilter(30)			# 'true' normalization. We'll use this a lot
nx=basis[0].xSize()
da=atan2(1.0,nx/2.0)			# da represents 1 pixel at the edge of the image

orig=EMAN.EMData()
# get eulers from proj.img file

import sys, os
from math import pi
try:
	import EMAN
except ImportError:
	print "EMAN module did not get imported"

if __name__ == "__main__":
	if len(sys.argv) !=3:
		print "Usage: getProjEulers.py <infile> <outfile>\n"
		sys.exit(1)

	projfile = sys.argv[1]
	outfile = sys.argv[2]

	out = open(outfile, "w")

	count,imgtype = EMAN.fileCount(projfile)
	imgs = EMAN.EMData()
	imgs.readImage(projfile,0,1)
	for i in range(count):
		imgs.readImage(projfile,i,1)
		e = imgs.getEuler()
		alt = e.alt()*180./pi
		az = e.az()*180./pi
		phi = e.phi()*180./pi
		out.write("%i\t%f\t%f\t%f\n" % (i,alt,az,phi))
	out.close()
Ejemplo n.º 35
0
    def start(self):
        self.params['outputstack'] = os.path.join(self.params['rundir'],
                                                  self.params['stackname'])
        particles, self.params['refineiter'] = getParticleInfo(
            self.params['reconid'], self.params['iter'])
        stackdata = particles[0]['particle']['stack']
        stack = os.path.join(stackdata['path']['path'], stackdata['name'])
        classes, cstats = determineClasses(particles)

        rejectlst = []
        if self.params['sigma'] is not None:
            cutoff = cstats[
                'meanquality'] + self.params['sigma'] * cstats['stdquality']
            apDisplay.printMsg("Cutoff = " + str(cutoff))
            rejectlst = self.removePtclsByQualityFactor(
                particles, rejectlst, cutoff)
        if self.params['avgjump'] is not None:
            rejectlst = self.removePtclsByJumps(particles, rejectlst)
        if self.params['rejectlst']:
            rejectlst = removePtclsByLst(rejectlst, self.params)

        classkeys = classes.keys()
        classkeys.sort()
        classnum = 0
        totalptcls = 0

        keepfile = open('keep.lst', 'w')
        keepfile.write('#LST\n')
        reject = open('reject.lst', 'w')
        reject.write('#LST\n')
        apDisplay.printMsg("Processing classes")
        #loop through classes
        for key in classkeys:

            # file to hold particles of this class
            clsfile = open('clstmp.lst', 'w')
            clsfile.write('#LST\n')

            classnum += 1
            if classnum % 10 == 1:
                apDisplay.printMsg(
                    str(classnum) + " of " + (str(len(classkeys))))
            images = EMAN.EMData()

            #loop through particles in class
            nptcls = 0
            for ptcl in classes[key]['particles']:
                if ptcl['mirror']:
                    mirror = 1
                else:
                    mirror = 0
                rot = ptcl['euler3']
                rot = rot * math.pi / 180
                if ptcl['particle']['particleNumber'] not in rejectlst:
                    l = '%d\t%s\t%f,\t%f,%f,%f,%d\n' % (
                        ptcl['particle']['particleNumber'] - 1, stack,
                        ptcl['quality_factor'], rot, ptcl['shiftx'],
                        ptcl['shifty'], mirror)
                    keepfile.write(l)
                    clsfile.write(l)
                    totalptcls += 1
                    nptcls += 1
                else:
                    reject.write('%d\t%s\t%f,\t%f,%f,%f,%d\n' %
                                 (ptcl['particle']['particleNumber'] - 1,
                                  stack, ptcl['quality_factor'], rot,
                                  ptcl['shiftx'], ptcl['shifty'], mirror))
                #if ptcl['quality_factor']>cstats['meanquality']+3*cstats['stdquality']:
                #       high.write('%d\t%s\t%f,\t%f,%f,%f,%d\n' % (ptcl['particle']['particleNumber']-1,
                #               stack,ptcl['quality_factor'],rot,ptcl['shiftx'],ptcl['shifty'],mirror))

            clsfile.close()

            if nptcls < 1:
                continue
            if self.params['skipavg'] is False:
                makeClassAverages('clstmp.lst', self.params['outputstack'],
                                  classes[key], self.params)

            if self.params['eotest'] is True:
                self.makeEvenOddClasses('clstmp.lst', classes[key])

        apDisplay.printMsg("\n")
        reject.close()
        keepfile.close()
        os.remove('clstmp.lst')

        # make 3d density file if specified:
        if self.params['make3d'] is not None:
            self.params['make3d'] = os.path.basename(self.params['make3d'])
            outfile = os.path.join(self.params['rundir'],
                                   self.params['make3d'])
            apEMAN.make3d(self.params['stackname'],
                          outfile,
                          sym=self.params['sym'],
                          mode=self.params['mode'],
                          hard=self.params['hard'])
            apEMAN.executeEmanCmd("proc3d %s %s mask=%d norm" %
                                  (outfile, outfile, self.params['mask']))
            if self.params['eotest'] is True:
                apEMAN.make3d(self.params['oddstack'],
                              "odd.mrc",
                              sym=self.params['sym'],
                              mode=self.params['mode'],
                              hard=self.params['hard'])
                apEMAN.make3d(self.params['evenstack'],
                              "even.mrc",
                              sym=self.params['sym'],
                              mode=self.params['mode'],
                              hard=self.params['hard'])
                apEMAN.executeEmanCmd("proc3d odd.mrc even.mrc fsc=fsc.eotest")

        if os.path.exists(outfile):
            # run rmeasure
            apix = apStack.getStackPixelSizeFromStackId(self.params['stackid'])
            box = apVolume.getModelDimensions(outfile)
            apDisplay.printMsg('inserting density into database')
            symdata = apSymmetry.findSymmetry(self.params['sym'])
            if not symdata:
                apDisplay.printError('no symmetry associated with this model')
            modq = appiondata.Ap3dDensityData()
            modq['session'] = self.params['sessionname']
            modq['name'] = self.params['make3d']
            modq['path'] = appiondata.ApPathData(
                path=os.path.abspath(self.params['rundir']))
            modq['boxsize'] = box
            modq['mask'] = self.params['mask']
            modq['pixelsize'] = apix
            fscres = apRecon.getResolutionFromFSCFile('fsc.eotest',
                                                      box,
                                                      apix,
                                                      msg=True)
            modq['resolution'] = fscres
            modq['rmeasure'] = apRecon.runRMeasure(apix, outfile)
            modq['md5sum'] = apFile.md5sumfile(outfile)
            modq['maxjump'] = self.params['avgjump']
            modq['sigma'] = self.params['sigma']
            modq['hard'] = self.params['hard']
            modq['symmetry'] = symdata
            modq['refineIter'] = self.params['refineiter']
            if self.params['commit'] is True:
                modq.insert()

            apChimera.filterAndChimera(outfile,
                                       res=fscres,
                                       apix=apix,
                                       box=box,
                                       chimtype='snapshot',
                                       zoom=self.params['zoom'],
                                       sym=self.params['sym'],
                                       mass=self.params['mass'])
        else:
            apDisplay.printError(
                'no 3d volume was generated - check the class averages:')
            apDisplay.printError(self.params['stackname'])
            apDisplay.printError(
                'hard may be set too high, or avg euler jump set too low for the # of particles'
            )

        stackstr = str(stackdata.dbid)
        reconstr = str(self.params['reconid'])
        apDisplay.printColor(
            "Make a new stack with only non-jumpers:\n" +
            "subStack.py --projectid=" + str(self.params['projectid']) +
            " -s " + stackstr + " \\\n " + " -k " +
            os.path.join(self.params['rundir'], "keep.lst") + " \\\n " +
            " -d 'recon " + reconstr + " sitters' -n sitters" + reconstr +
            " -C ", "purple")
Ejemplo n.º 36
0
#!/usr/bin/env python
import EMAN
import sys
from sys import argv
import os
import math

RD = 180.0 / math.pi

if len(argv) < 3:
    print "fsctest.py <refs> <ref #> <ptcl file> <ptcl #>"
    sys.exit(1)

refs = EMAN.readImages(argv[1], -1, -1)
ptcl = EMAN.EMData()
ptcl.readImage(argv[3], int(argv[4]))
ptcl.edgeNormalize()
ptclf = ptcl.copy(0, 0)
ptclf.vFlip()


for i in refs:
    i.normalize()

ali = ptcl.RTFAlign(refs[int(argv[2])], ptclf, 1)
ali.refineAlign(i)
fsc = (1.0 + ali.fscmp(refs[int(argv[2])], None)) * 500.0
print fsc
def getNumParticlesInStack(stackname):
        import EMAN
        numparticles = EMAN.fileCount(stackname)[0]
        return numparticles