Example #1
0
    def up(self, event, lc):
        if self.downloc != None:
            dx = abs(lc[0] - self.downloc[0])
            dy = abs(lc[1] - self.downloc[1])
            dx = max(dx, dy)  # Make box square
            dx = good_size(dx * 2) / 2  # use only good sizes
            dy = dx
            s = EMShape([
                "rectpoint", .7, .2, 0, self.downloc[0] - dx,
                self.downloc[1] - dy, self.downloc[0] + dx,
                self.downloc[1] + dy, 1
            ])
            self.im2d.del_shape("box")
            if hypot(lc[0] - self.downloc[0], lc[1] - self.downloc[1]) > 5:
                self.tiltshapes = [None for i in range(self.imageparm["nz"])]
                self.find_boxes(s)

            self.update_tilt()
            self.downloc = None
        elif self.downadjloc != None:
            dx = (lc[0] - self.downadjloc[0][0])
            dy = (lc[1] - self.downadjloc[0][1])
            s = self.tiltshapes[self.curtilt].getShape()[:]
            s[4] = self.downadjloc[1][0] + dx
            s[5] = self.downadjloc[1][1] + dy
            s[6] = self.downadjloc[1][2] + dx
            s[7] = self.downadjloc[1][3] + dy
            self.tiltshapes[self.curtilt] = EMShape(s)
            self.im2d.add_shape("finalbox", self.tiltshapes[self.curtilt])
            self.im2d.del_shape("box")

            self.update_tilt()
            self.update_stack()
            self.downadjloc = None
Example #2
0
    def drag(self, event, lc):
        if self.downloc != None:
            dx = abs(lc[0] - self.downloc[0])
            dy = abs(lc[1] - self.downloc[1])
            dx = max(dx, dy)  # Make box square
            dx = good_size(dx * 2) / 2  # use only good sizes
            dy = dx
            s = EMShape([
                "rectpoint", 0, .7, 0, self.downloc[0] - dx,
                self.downloc[1] - dy, self.downloc[0] + dx,
                self.downloc[1] + dy, 1
            ])
            self.im2d.add_shape("box", s)
            s = EMShape([
                "scrlabel", .7, .7, 0, 20.0, 20.0,
                "%d (%d x %d)" % (self.curtilt, dx * 2, dy * 2), 200.0, 1
            ])
            self.im2d.add_shape("tilt", s)
        elif self.downadjloc != None:
            dx = (lc[0] - self.downadjloc[0][0])
            dy = (lc[1] - self.downadjloc[0][1])
            s = self.tiltshapes[self.curtilt].getShape()[:]
            s[4] = self.downadjloc[1][0] + dx
            s[5] = self.downadjloc[1][1] + dy
            s[6] = self.downadjloc[1][2] + dx
            s[7] = self.downadjloc[1][3] + dy
            self.im2d.add_shape("box", EMShape(s))

        self.im2d.updateGL()
Example #3
0
	def paint_mask(self,v1x,v1y,v2x,v2y,v3x,v3y,v4x,v4y):
		if self.masktype == "None":
			self.boxes.add_mask(None)
		elif self.masktype == "LineMask":
			self.boxes.add_mask(EMShape(["linemask",1,0,0,v1x, v1y,v2x,v2y,v3x,v3y,v4x,v4y,4.0]))
		elif self.masktype == "SolidMask":
			# 10 is used to prevent aliasing
			self.boxes.add_mask(EMShape(["mask",0,0,0, -10, -10, v1x, v1y, self.win_xsize+10, -10, v2x, v2y, self.win_xsize+10, self.win_ysize+10, v3x, v3y, -10, self.win_ysize+10, v4x, v4y]))
		else:
			self.boxes.add_mask(None)
Example #4
0
    def update_view(self):
        shps = {}
        for i, s in enumerate(self.all_shapes):
            shp = ["ellipse", 1, 0, 0] + s[1:] + [2] + [s[0]]
            shps[i] = EMShape(shp)

        shps[len(
            self.all_shapes)] = EMShape(["ellipse", 1, 0, 0] + self.shape[1:] +
                                        [2] + [self.shape[0]])
        self.imgview.shapes = shps
        self.imgview.shapechange = 1
        self.imgview.updateGL()
Example #5
0
    def update_tilt(self):
        if self.imagefile == None: return

        self.curimg = EMData(
            self.imagefile, 0, False,
            Region(0, 0, self.curtilt, self.imageparm["nx"],
                   self.imageparm["ny"], 1))
        if self.invert: self.curimg.mult(-1.0)
        self.im2d.set_data(self.curimg)

        s = EMShape(
            ["scrlabel", .7, .3, 0, 20.0, 20.0,
             "%d" % self.curtilt, 200.0, 1])
        self.im2d.add_shape("tilt", s)

        if self.tiltshapes[self.curtilt] != None:
            self.im2d.add_shape("finalbox", self.tiltshapes[self.curtilt])

            s0 = self.tiltshapes[self.oldtilt].getShape()
            s1 = self.tiltshapes[self.curtilt].getShape()
            dx = s0[4] - s1[4]
            dy = s0[5] - s1[5]

            self.im2d.set_origin(self.im2d.origin[0] - dx,
                                 self.im2d.origin[1] - dy)
            self.oldtilt = self.curtilt

        self.im2d.updateGL()
Example #6
0
	def get_shape(self,shape_string,box_size):
		if EMBox.BOX_COLORS.has_key(self.type):
			r,g,b = EMBox.BOX_COLORS[self.type]
		else:
			r,g,b = 1.0,0.42,0.71 # hot pink, apparently ;)
		shape = EMShape([shape_string,r,g,b,self.x-box_size/2,self.y-box_size/2,self.x+box_size/2,self.y+box_size/2,2.0])
		return shape
Example #7
0
 def up(self, event, lc):
     s = EMShape([
         "line", .7, .2, 0, self.downloc[0], self.downloc[1], lc[0], lc[1],
         1
     ])
     self.im2d.del_shape("mine")
     self.im2d.add_shape("done", s)
     self.im2d.updateGL()
Example #8
0
 def __addBox(self, i, box):
     """takes the number of the box in self.boxes and the (x,y,mode) tuple and displays it"""
     # Display the actual box
     boxsize = self.vbbsize.getValue()
     ptclsize = self.vbbpsize.getValue()
     try:
         color = self.boxcolors[box[2]]
     except:
         color = self.boxcolors["unknown"]
     self.wimage.add_shape(
         "box{}".format(i),
         EMShape(("rect", color[0], color[1], color[2],
                  box[0] - boxsize // 2, box[1] - boxsize // 2,
                  box[0] + boxsize // 2, box[1] + boxsize // 2, 2)))
     self.wimage.add_shape(
         "cir{}".format(i),
         EMShape(("circle", color[0], color[1], color[2], box[0], box[1],
                  ptclsize / 2, 1.5)))
Example #9
0
	def __init__(self,img, app):
		EMImage2DWidget.__init__(self,img,application=app)
		
		self.sx=img["nx"]
		self.sy=img["ny"]
		self.set_scale(.3)
		
		minxy=min(self.sx, self.sy)
		self.bar_len=minxy*.1
		self.bar_ypos=-self.sy*.2
		self.bar_thick=20
		self.bar_xpos=self.sx/2
		self.bar=EMShape()
		self.barspeed=0.02*minxy
		
		self.score=0
		self.score_label=EMShape()
		
		
		self.ball=EMShape()
		self.ball_rad=20
		self.ball_pos=np.array([self.bar_xpos, self.bar_ypos+self.bar_thick+self.ball_rad])
		self.ball_speed=minxy*.01		
		self.set_shapes({0:self.bar, 1:self.ball,2:self.score_label})
		
		self.game_started=False
		
		self.data.mult(-1)
		self.data.process_inplace("filter.lowpass.gauss",{"cutoff_abs":.05})
		self.data.process_inplace("normalize")
		self.data.process_inplace("threshold.belowtozero",{"minval":1})
		self.data.div(self.data["mean"]*self.sx*self.sy)
		self.data.mult(1000)
		self.auto_contrast()
		self.data_grad=self.data.process("math.gradient.direction")
		self.del_msk=self.data.copy()
		self.del_msk.to_one()
		
		self.update_bar()
		self.update_score()
		self.update_ball()
		print "break bricks.."
Example #10
0
    def __init__(self, img, app):
        EMImage2DWidget.__init__(self, img, application=app)

        self.sx = img["nx"]
        self.sy = img["ny"]
        self.set_scale(.3)

        minxy = min(self.sx, self.sy)
        self.bar_len = minxy * .1
        self.bar_ypos = -self.sy * .2
        self.bar_thick = 20
        self.bar_xpos = self.sx / 2
        self.bar = EMShape()
        self.barspeed = 0.02 * minxy

        self.score = 0
        self.score_label = EMShape()

        self.ball = EMShape()
        self.ball_rad = 20
        self.ball_pos = np.array(
            [self.bar_xpos, self.bar_ypos + self.bar_thick + self.ball_rad])
        self.ball_speed = minxy * .01
        self.set_shapes({0: self.bar, 1: self.ball, 2: self.score_label})

        self.game_started = False

        self.data.mult(-1)
        #self.data.process_inplace("filter.lowpass.gauss",{"cutoff_abs":.05})
        #self.data.process_inplace("normalize")
        #self.data.process_inplace("threshold.belowtozero",{"minval":1})
        #print self.data["mean_nonzero"],self.sx,self.sy
        self.data.div(self.data["mean_nonzero"] * self.sx * self.sy)
        self.data.mult(1000)
        self.auto_contrast()
        self.data_grad = self.data.process("math.gradient.direction")
        self.del_msk = self.data.copy()
        self.del_msk.to_one()

        self.update_bar()
        self.update_score()
        self.update_ball()
        print "break bricks.."
Example #11
0
    def find_boxes(self, mainshape):
        """Starting with a user selected box at the current tilt, search for the same shape in the entire
	tilt series"""

        if self.imagefile == None: return

        self.tiltshapes[self.curtilt] = mainshape

        lref = None
        for i in range(self.curtilt + 1, self.imageparm["nz"]):
            refshape = self.tiltshapes[i - 1].getShape()

            # Read the reference at the user specified size, then pad it a bit
            ref = EMData(
                self.imagefile, 0, False,
                Region(refshape[4], refshape[5], i - 1,
                       refshape[6] - refshape[4], refshape[7] - refshape[5],
                       1))
            ref.process_inplace("threshold.clampminmax.nsigma",
                                {"nsigma": 4.0})
            ref.process_inplace("filter.lowpass.gauss", {"cutoff_abs": .1})
            ref.process_inplace("normalize.edgemean")
            ref = ref.get_clip(
                Region(-self.maxshift, -self.maxshift,
                       ref["nx"] + self.maxshift * 2,
                       ref["ny"] + self.maxshift * 2))
            if lref != None and self.seqali: ref.add(lref)
            ref.process_inplace(
                "normalize.edgemean")  # older images contribute less
            lref = ref

            # when we read the alignment target, we pad with actual image data since the object will have moved
            trg = EMData(
                self.imagefile, 0, False,
                Region(refshape[4] - self.maxshift,
                       refshape[5] - self.maxshift, i,
                       refshape[6] - refshape[4] + self.maxshift * 2,
                       refshape[7] - refshape[5] + self.maxshift * 2, 1))
            trg.process_inplace("threshold.clampminmax.nsigma",
                                {"nsigma": 4.0})
            trg.process_inplace("filter.lowpass.gauss", {"cutoff_abs": .1})
            trg.process_inplace("normalize.edgemean")

            aln = ref.align("translational", trg, {
                "intonly": 1,
                "maxshift": self.maxshift * 4 / 5,
                "masked": 1
            })
            ref.write_image("dbug.hdf", -1)
            trg.write_image("dbug.hdf", -1)
            aln.write_image("dbug.hdf", -1)
            trans = aln["xform.align2d"].get_trans()
            #			if i==self.curtilt+3 : display((ref,trg,aln,ref.calc_ccf(trg)))

            self.tiltshapes[i] = EMShape([
                "rectpoint", .7, .2, 0, refshape[4] + trans[0],
                refshape[5] + trans[1], refshape[6] + trans[0],
                refshape[7] + trans[1], 1
            ])
            print i, trans[0], trans[1]

        lref = None
        for i in range(self.curtilt - 1, -1, -1):
            refshape = self.tiltshapes[i + 1].getShape()

            # Read the reference at the user specified size, then pad it a bit
            ref = EMData(
                self.imagefile, 0, False,
                Region(refshape[4], refshape[5], i + 1,
                       refshape[6] - refshape[4], refshape[7] - refshape[5],
                       1))
            ref.process_inplace("filter.lowpass.gauss", {"cutoff_abs": .1})
            ref.process_inplace("normalize.edgemean")
            ref = ref.get_clip(
                Region(-self.maxshift, -self.maxshift,
                       ref["nx"] + self.maxshift * 2,
                       ref["ny"] + self.maxshift * 2))
            if lref != None and self.seqali: ref.add(lref)
            ref.process_inplace("normalize.edgemean")
            lref = ref

            # when we read the alignment target, we pad with actual image data since the object will have moved
            trg = EMData(
                self.imagefile, 0, False,
                Region(refshape[4] - self.maxshift,
                       refshape[5] - self.maxshift, i,
                       refshape[6] - refshape[4] + self.maxshift * 2,
                       refshape[7] - refshape[5] + self.maxshift * 2, 1))
            trg.process_inplace("filter.lowpass.gauss", {"cutoff_abs": .1})
            trg.process_inplace("normalize.edgemean")

            aln = ref.align("translational", trg, {
                "intonly": 1,
                "maxshift": self.maxshift * 4 / 5,
                "masked": 1
            })
            trans = aln["xform.align2d"].get_trans()
            if i == self.curtilt + 3:
                display((ref, trg, aln, ref.calc_ccf(trg)))

            self.tiltshapes[i] = EMShape([
                "rectpoint", .7, .2, 0, refshape[4] + trans[0],
                refshape[5] + trans[1], refshape[6] + trans[0],
                refshape[7] + trans[1], 1
            ])
            print i, trans[0], trans[1]

        self.update_stack()
Example #12
0
class EMBreakBrick(EMImage2DWidget):
	
	def __init__(self,img, app):
		EMImage2DWidget.__init__(self,img,application=app)
		
		self.sx=img["nx"]
		self.sy=img["ny"]
		self.set_scale(.3)
		
		minxy=min(self.sx, self.sy)
		self.bar_len=minxy*.1
		self.bar_ypos=-self.sy*.2
		self.bar_thick=20
		self.bar_xpos=self.sx/2
		self.bar=EMShape()
		self.barspeed=0.02*minxy
		
		self.score=0
		self.score_label=EMShape()
		
		
		self.ball=EMShape()
		self.ball_rad=20
		self.ball_pos=np.array([self.bar_xpos, self.bar_ypos+self.bar_thick+self.ball_rad])
		self.ball_speed=minxy*.01		
		self.set_shapes({0:self.bar, 1:self.ball,2:self.score_label})
		
		self.game_started=False
		
		self.data.mult(-1)
		self.data.process_inplace("filter.lowpass.gauss",{"cutoff_abs":.05})
		self.data.process_inplace("normalize")
		self.data.process_inplace("threshold.belowtozero",{"minval":1})
		self.data.div(self.data["mean"]*self.sx*self.sy)
		self.data.mult(1000)
		self.auto_contrast()
		self.data_grad=self.data.process("math.gradient.direction")
		self.del_msk=self.data.copy()
		self.del_msk.to_one()
		
		self.update_bar()
		self.update_score()
		self.update_ball()
		print "break bricks.."
	
	def update_score(self):
		self.score_label.setShape(["label", 1,1,1, -self.sx*.1, self.sy*1.1, "{:.02f}".format(self.score), 100,5])
		self.update_shapes({2:self.score_label})
		self.updateGL()
	
	def update_bar(self):
		self.bar.setShape(["line",1,1,1,self.bar_xpos-self.bar_len,self.bar_ypos,self.bar_xpos+self.bar_len,self.bar_ypos,self.bar_thick])
		
		self.update_shapes({0:self.bar})
		self.updateGL()
		
		if not self.game_started:
			self.ball_pos=np.array([self.bar_xpos, self.bar_ypos+self.bar_thick+self.ball_rad])
			self.update_ball()
	
	
	def update_ball(self):
		self.ball.setShape(["circle",1,1,1,self.ball_pos[0], self.ball_pos[1], self.ball_rad,2])
		#self.set_shapes({1:self.ball})
		self.update_shapes({1:self.ball})
		self.updateGL()
	
	def start_game(self):
		print "Start~"
		self.ball_ori=45./180.*np.pi
		self.ball_vec=np.array([self.ball_speed*np.cos(self.ball_ori),self.ball_speed*np.sin(self.ball_ori)])
		
		self.game_timer=QTimer()
		self.game_timer.timeout.connect(self.time_update)
		self.game_timer.start(30)
		self.game_started=True
		
	def time_update(self):
		#print "timer~~"
		self.ball_move()
		self.update_ball()
	
	def ball_move(self):
		newpos=self.ball_pos+self.ball_vec
		if newpos[0]>self.sx or newpos[0]<0: self.ball_vec[0]*=-1
		elif newpos[1]>self.sy: self.ball_vec[1]*=-1
		elif abs(newpos[1]-self.bar_ypos)<self.bar_thick and abs(newpos[0]-self.bar_xpos)<self.bar_len:
				self.ball_vec[1]*=-1
		
		elif newpos[1]<self.bar_ypos-200:
			print "Lose..."
			self.game_timer.stop()
		
		else:
			p=newpos.astype(int)
			if p[1]<0 or p[0]<0 or p[0]>self.sx or p[1]>self.sy:
				val=0
			else:
				val=self.data.get_value_at(p[0],p[1])
			if val>0:
				grad=self.data_grad.get_value_at(p[0],p[1])
				#print val, grad
				newori=(grad*2-self.ball_ori)% (np.pi*2)
				oridiff=abs(newori-self.ball_ori)*180./np.pi
				if oridiff>180: oridiff=oridiff-180
				#print self.ball_ori*180./np.pi,newori*180./np.pi,oridiff
				if oridiff<30:
					#print "???"
					newori+=.5*np.pi*np.sign(newori-self.ball_ori)
				self.ball_ori=newori
				self.ball_vec=np.array([self.ball_speed*np.cos(self.ball_ori),self.ball_speed*np.sin(self.ball_ori)])
				
				self.del_msk.to_one()
				self.del_msk.process_inplace("mask.soft", {"dx":p[0]-self.sx/2, "dy": p[1]-self.sy/2, "outer_radius":30})
				delimg=self.data*self.del_msk
				delval=delimg["mean"]*self.sx*self.sy
				self.score+=delval
				self.update_score()
				
				self.data.sub(delimg)
				#self.data_grad=self.data.process("math.gradient.direction")
				self.force_display_update()
				
			
		
		
		self.ball_pos+=self.ball_vec
		
		
	
	def keyPressEvent(self,event):

		if event.key() == Qt.Key_Right:
			if self.bar_xpos+self.bar_len<self.sx:
				self.bar_xpos+=self.barspeed
				self.update_bar()
		elif event.key() == Qt.Key_Left:
			if self.bar_xpos-self.bar_len>0:
				self.bar_xpos-=self.barspeed
				self.update_bar()
		elif event.key() ==Qt.Key_Space:
			if not self.game_started:
				self.start_game()
Example #13
0
class EMBreakBrick(EMImage2DWidget):
    def __init__(self, img, app):
        EMImage2DWidget.__init__(self, img, application=app)

        self.sx = img["nx"]
        self.sy = img["ny"]
        self.set_scale(.3)

        minxy = min(self.sx, self.sy)
        self.bar_len = minxy * .1
        self.bar_ypos = -self.sy * .2
        self.bar_thick = 20
        self.bar_xpos = self.sx / 2
        self.bar = EMShape()
        self.barspeed = 0.02 * minxy

        self.score = 0
        self.score_label = EMShape()

        self.ball = EMShape()
        self.ball_rad = 20
        self.ball_pos = np.array(
            [self.bar_xpos, self.bar_ypos + self.bar_thick + self.ball_rad])
        self.ball_speed = minxy * .01
        self.set_shapes({0: self.bar, 1: self.ball, 2: self.score_label})

        self.game_started = False

        self.data.mult(-1)
        #self.data.process_inplace("filter.lowpass.gauss",{"cutoff_abs":.05})
        #self.data.process_inplace("normalize")
        #self.data.process_inplace("threshold.belowtozero",{"minval":1})
        #print self.data["mean_nonzero"],self.sx,self.sy
        self.data.div(self.data["mean_nonzero"] * self.sx * self.sy)
        self.data.mult(1000)
        self.auto_contrast()
        self.data_grad = self.data.process("math.gradient.direction")
        self.del_msk = self.data.copy()
        self.del_msk.to_one()

        self.update_bar()
        self.update_score()
        self.update_ball()
        print "break bricks.."

    def update_score(self):
        self.score_label.setShape([
            "label", 1, 1, 1, -self.sx * .1, self.sy * 1.1,
            "{:.02f}".format(self.score), 100, 5
        ])
        self.update_shapes({2: self.score_label})
        self.updateGL()

    def update_bar(self):
        self.bar.setShape([
            "line", 1, 1, 1, self.bar_xpos - self.bar_len, self.bar_ypos,
            self.bar_xpos + self.bar_len, self.bar_ypos, self.bar_thick
        ])

        self.update_shapes({0: self.bar})
        self.updateGL()

        if not self.game_started:
            self.ball_pos = np.array([
                self.bar_xpos, self.bar_ypos + self.bar_thick + self.ball_rad
            ])
            self.update_ball()

    def update_ball(self):
        self.ball.setShape([
            "circle", 1, 1, 1, self.ball_pos[0], self.ball_pos[1],
            self.ball_rad, 2
        ])
        #self.set_shapes({1:self.ball})
        self.update_shapes({1: self.ball})
        self.updateGL()

    def start_game(self):
        print "Start~"
        self.ball_ori = 45. / 180. * np.pi
        self.ball_vec = np.array([
            self.ball_speed * np.cos(self.ball_ori),
            self.ball_speed * np.sin(self.ball_ori)
        ])

        self.game_timer = QTimer()
        self.game_timer.timeout.connect(self.time_update)
        self.game_timer.start(30)
        self.game_started = True

    def time_update(self):
        #print "timer~~"
        self.ball_move()
        self.update_ball()

    def ball_move(self):
        newpos = self.ball_pos + self.ball_vec
        if newpos[0] > self.sx or newpos[0] < 0: self.ball_vec[0] *= -1
        elif newpos[1] > self.sy: self.ball_vec[1] *= -1
        elif abs(newpos[1] - self.bar_ypos) < self.bar_thick and abs(
                newpos[0] - self.bar_xpos) < self.bar_len:
            self.ball_vec[1] *= -1

        elif newpos[1] < self.bar_ypos - 200:
            print "Lose..."
            self.game_timer.stop()

        else:
            p = newpos.astype(int)
            if p[1] < 0 or p[0] < 0 or p[0] > self.sx or p[1] > self.sy:
                val = 0
            else:
                val = self.data.get_value_at(p[0], p[1])
            if val > 0:
                grad = self.data_grad.get_value_at(p[0], p[1])
                #print val, grad
                newori = (grad * 2 - self.ball_ori) % (np.pi * 2)
                oridiff = abs(newori - self.ball_ori) * 180. / np.pi
                if oridiff > 180: oridiff = oridiff - 180
                #print self.ball_ori*180./np.pi,newori*180./np.pi,oridiff
                if oridiff < 30:
                    #print "???"
                    newori += .5 * np.pi * np.sign(newori - self.ball_ori)
                self.ball_ori = newori
                self.ball_vec = np.array([
                    self.ball_speed * np.cos(self.ball_ori),
                    self.ball_speed * np.sin(self.ball_ori)
                ])

                self.del_msk.to_one()
                self.del_msk.process_inplace(
                    "mask.soft", {
                        "dx": p[0] - self.sx / 2,
                        "dy": p[1] - self.sy / 2,
                        "outer_radius": 30
                    })
                delimg = self.data * self.del_msk
                delval = delimg["mean"] * self.sx * self.sy
                self.score += delval
                self.update_score()

                self.data.sub(delimg)
                #self.data_grad=self.data.process("math.gradient.direction")
                self.force_display_update()

        self.ball_pos += self.ball_vec

    def keyPressEvent(self, event):

        if event.key() == Qt.Key_Right:
            if self.bar_xpos + self.bar_len < self.sx:
                self.bar_xpos += self.barspeed
                self.update_bar()
        elif event.key() == Qt.Key_Left:
            if self.bar_xpos - self.bar_len > 0:
                self.bar_xpos -= self.barspeed
                self.update_bar()
        elif event.key() == Qt.Key_Space:
            if not self.game_started:
                self.start_game()
Example #14
0
	def get_label(self, text, size, box_size):
		label = EMShape(["label",1,1,1,self.x-box_size/2,self.y+box_size/2+10,str(text),size,2.0])
		return label
Example #15
0
	def drag(self,event,lc):
		s=EMShape(["line",0,.7,0,self.downloc[0],self.downloc[1],lc[0],lc[1],1])
		self.im2d.add_shape("mine",s)
		self.im2d.updateGL()
Example #16
0
    def draw_wave(self):

        sz = 512 - 1  ### length of x-axis
        xdivz = 2e-3  ### x/z scale ratio
        mpix = 4e-8  ### pixel to meter
        wavelen = 2e-12 / mpix  ### wave length
        wid = 8  ### width of the slits
        w2 = 4  ### position of the slits

        #raw=np.zeros(sz) ### input signal
        #raw[sz/2-wid-w2+1:sz/2+wid-w2+1]=1
        #raw[sz/2-wid+w2:sz/2+wid+w2]=1

        #raw[sz/2-wid+1:sz/2+wid]=1
        raw0 = np.exp(-(np.arange(sz, dtype=float) - sz / 2 + 5)**2 / 5)
        raw0 += np.exp(-(np.arange(sz, dtype=float) - sz / 2 - 5)**2 / 5)
        raw0 += np.exp(-(np.arange(sz, dtype=float) - sz / 2 - 15)**2 / 5)
        raw0 += np.exp(-(np.arange(sz, dtype=float) - sz / 2 + 15)**2 / 5)
        #raw0+=np.exp(-(np.arange(sz, dtype=float)-sz/2-7.5)**2/5)
        #raw0+=np.exp(-(np.arange(sz, dtype=float)-sz/2+7.5)**2/5)
        #raw=np.exp(-1j*raw0*1)#*(np.exp(-raw0*.1))
        #raw=raw0.copy()
        raw = self.gauss_edge(sz, cl=.2, gw=.1)
        raw *= np.exp(-1j * raw0 * 1)
        #self.pltwindow.set_data([np.arange(sz)-sz/2, raw], "raw", linetype=0)
        #return
        #print wavelen
        #print raw-raw[::-1]
        #raw=raw*0+1
        #### load lens info
        mult = 400  ### size multiplier from GL lens diagram to wave image
        l = np.array(self.lens)[3:]
        ### use relative distance between lens instead of absolute positions
        lens_gl = np.array([[l[i, 0] - l[i + 1, 0], l[i, 1]]
                            for i in range(len(l) - 1)])
        lens = mult * lens_gl
        #lens[:,0]=np.round(lens[:,0]) ### round z position
        #lens[-1][0]+=10

        ix = (np.arange(sz, dtype=float) -
              sz / 2) * xdivz  ## indices along x direction
        ix_mat = (ix - ix[:, None])**2
        cs = self.cs * mult  ## spherical abberation
        alldata = []
        for parallel in [False]:  ### compute parallel beam when true
            #### start wave propagation
            imgs = []

            #### from scattering point to the first lens
            zmax = np.round((self.lens[2][0] - l[0, 0]) *
                            mult)  ### z position of the first lens
            #iz=np.arange(1,zmax)[:,None,None] ## indices along z direction
            iz = (np.arange(1, int(zmax) + 1, dtype=float) / int(zmax) *
                  zmax)[:, None, None]
            ## zmax x sz x sz matrix
            dst = np.sqrt(ix_mat + iz**2)
            #print dst
            #print ix.shape, iz.shape, dst.shape, raw.shape, (ix-ix[:,None]).shape
            #pmult=1e-3
            if parallel:
                cpx = np.exp(-1j * 2 * np.pi * (iz + np.zeros(
                    (sz, sz))) / wavelen) * np.mean(raw) * (1 / iz**2)
            else:
                cpx = raw[:, None] * np.exp(
                    -1j * 2 * np.pi * dst / wavelen) * (1 / dst**2)

            img = np.sum(cpx, axis=1)
            imgs.append(img)
            shapes = []
            vz = np.sum(lens[:, 0]) - len(lens)  ### to track z position
            #print img.shape
            for il, ln in enumerate(lens):
                #break
                f = ln[1]
                proj = imgs[-1][-1]  ### projection of wave on lens
                fv = lens_gl[il][1]

                if (fv < -3 and fv > -4):  ### aperture
                    ap = fv + 4
                    clip = int((1 - ap) * sz) / 2
                    msk = self.gauss_edge(sz, cl=(1 - ap) / 2.)
                    proj_ps = proj.copy() * msk
                    shapes.append(
                        EMShape(
                            ("rect", .5, .5, 1, 0, vz - 2, clip, vz + 2, 2)))
                    shapes.append(
                        EMShape(("rect", .5, .5, 1, sz - clip, vz - 2, sz,
                                 vz + 2, 2)))

                elif fv == -5:  ### phase plate
                    msk = self.gauss_edge(sz, cl=.1 / 2.)
                    phaseplate = self.gauss_edge(sz, cl=.49, gw=.1, gs=.01)
                    phaseplate = -phaseplate * np.pi / 2.
                    proj_ps = proj.copy() * msk * np.exp(-1j * phaseplate)

                    shapes.append(
                        EMShape(("rect", .8, .5, 1, 0, vz, sz, vz, 2)))

                else:  ### lens
                    ps = ((ix)**2) / (f * 2) * (2 * np.pi / wavelen
                                                )  ### phase shift
                    ps += cs * (ix**4) / 4.
                    proj_ps = proj * np.exp(-1j *
                                            (-ps))  ### projection after phase
                    shapes.append(
                        EMShape(("rect", 1, .5, .5, 0, vz - 2, sz, vz + 2, 2)))

                zmax = ln[0]
                #iz=np.arange(1,zmax, dtype=float)[:,None,None] ## indices along z direction
                iz = (np.arange(1, int(zmax) + 1, dtype=float) / int(zmax) *
                      zmax)[:, None, None]
                dst = np.sqrt(ix_mat + iz**2)
                cpx1 = proj_ps[:, None] * np.exp(
                    -1j * 2 * np.pi * dst / wavelen) * (1 / dst**2)

                img = np.sum(cpx1, axis=1)
                imgs.append(img)
                vz -= zmax - 1
            #print [m.shape for m in imgs]
            final = np.vstack(imgs)
            final /= np.sum(abs(final), axis=1)[:, None]
            img = final[::-1, :].copy()
            #img/=np.max(img)
            alldata.append(img)
        #print img.shape

        #nrm=(np.sum(abs(alldata[0]), axis=1)+np.sum(abs(alldata[1]), axis=1))/sz
        #for i in [0,1]: alldata[i]/=nrm[:,None]

        self.imgwindow.shapes = {i: shapes[i] for i in range(len(shapes))}
        self.imgwindow.shapechange = 1
        #self.imgwindow.set_data([from_numpy(abs(d)*np.sin(np.angle(d))) for d in alldata])
        self.imgwindow.set_data([
            from_numpy(abs(alldata[0])),
            from_numpy(np.cos(np.angle(alldata[0])))
        ])

        if self.pltwindow:

            a0 = alldata[0][0, :]
            #a1=alldata[1][0,:]
            r0 = (np.arange(sz) - sz / 2) * abs(self.mag)
            if self.wavesign < 0: r0 = r0[::-1]
            clip = np.where(abs(r0) < sz / 2)[0]
            if len(clip) > 0:
                c = clip[0]
                rawplot = [r0[c:-c], raw0[c:-c]]
            else:
                rawplot = [r0, raw0]

            #rawplot=[np.arange(sz)-sz/2, raw0]
            self.pltwindow.set_data(
                [np.arange(sz) - sz / 2,
                 abs(a0) / np.max(abs(a0))],
                "scatter",
                linetype=0)
            self.pltwindow.set_data(rawplot, "raw", linetype=0)
            #self.pltwindow.set_data([np.arange(sz)-sz/2, abs(alldata[1][0,:])], "parallel", linetype=0)
            #self.pltwindow.set_data([np.arange(sz)-sz/2,
            #abs(a0/abs(a0)+a1/abs(a1))], "contrast", linetype=0)
            #self.pltwindow.set_data([np.arange(sz)-sz/2, np.sin(np.angle(a0))], "phase_scatter", linetype=0)
            #self.pltwindow.set_data([np.arange(sz)-sz/2, np.sin(np.angle(a1))], "phase_parallel", linetype=0)
            aa = abs(a0)
            if self.wavesign > 0:
                bd = np.where(raw0 > .01)[0]
            else:
                bd = np.where(raw0[::-1] > .01)[0]
            bd = [bd[0], bd[-1]]
            pad = int((bd[1] - bd[0]) * 1.)
            bd = [bd[0] - pad, bd[1] + pad]
            bd = [int((b - sz / 2) * abs(self.mag) + sz / 2) for b in bd]

            bd[0] = max(0, bd[0])
            bd[1] = min(sz - 1, bd[1])
            #print bd
            aa -= (aa[bd[0]] + aa[bd[1]]) / 2.
            #print bd
            aa[:bd[0]] = 0
            aa[bd[1] - 1:] = 0
            aa /= np.max(abs(aa))
            a0ft = np.real(np.fft.fftshift(np.fft.fft(np.fft.fftshift((aa)))))
            #rawft=np.real(np.fft.fftshift(np.fft.fft(np.fft.fftshift(a0))))
            rawft = np.abs(np.fft.fftshift(np.fft.fft(np.fft.fftshift(-raw0))))
            a0ft /= np.max(a0ft)
            #a0ft[sz/2]=1
            rawft /= np.max(rawft)
            rf = rawft.copy()
            rf[abs(rf) < 1e-3] = 1
            ctf = a0ft / rf
            ctf[abs(rawft) < 1e-3] = 0

            ftidx = np.fft.fftfreq(len(a0))
            #print self.mag
            #self.pltwindow.set_data([np.arange(sz)-sz/2, aa], "scatter_msk", linetype=0)
            #self.pltwindow.set_data([r0[c:-c], a0ft[c:-c]], "scatter_fft", linetype=0)
            #self.pltwindow.set_data([np.arange(sz)-sz/2, rawft], "raw_fft", linetype=0)
            #self.pltwindow.set_data([np.arange(sz)-sz/2, ctf], "ctf", linetype=0)
            #contrast=np.sin(np.angle(a0+a1))
            #contrast=(np.angle(a0)-np.angle(a1))*180/np.pi
            #self.pltwindow.set_data([np.arange(sz)-sz/2, contrast], "phase_contrast", linetype=0)
        return img