Exemple #1
0
class ErasingPanel:  # copied for ideas for the morph panel
    def __init__(self, target, erase_radius=128):
        self.busy = True
        self.erase_radius = erase_radius
        self.target = weakref.ref(target)
        self.erase_rad_edit = None
        self.widget = None
        self.busy = False

    def set_erase_radius(self, erase_rad_edit):
        self.busy = True
        self.erase_radius = erase_rad_edit
        if self.erase_rad_edit != None:
            self.erase_rad_edit.setValue(erase_rad_edit)
        self.busy = False

    def get_widget(self):
        if self.widget == None:
            from PyQt4 import QtCore, QtGui, Qt
            self.widget = QtGui.QWidget()
            vbl = QtGui.QVBoxLayout(self.widget)
            vbl.setMargin(0)
            vbl.setSpacing(6)
            vbl.setObjectName("vbl")

            hbl = QtGui.QHBoxLayout()
            hbl.addWidget(QtGui.QLabel("Erase Radius:"))
            from valslider import ValSlider
            self.erase_rad_edit = ValSlider(None, (0.0, 1000.0), "")
            self.erase_rad_edit.setValue(int(self.erase_radius))
            self.erase_rad_edit.setEnabled(True)
            hbl.addWidget(self.erase_rad_edit)

            self.unerase = QtGui.QCheckBox("Unerase")
            self.unerase.setChecked(False)

            vbl.addLayout(hbl)
            vbl.addWidget(self.unerase)
            QtCore.QObject.connect(self.erase_rad_edit,
                                   QtCore.SIGNAL("sliderReleased"),
                                   self.new_erase_radius)
            QtCore.QObject.connect(self.unerase,
                                   QtCore.SIGNAL("clicked(bool)"),
                                   self.unerase_checked)

        return self.widget

    def new_erase_radius(self, erase_rad_edit):
        if self.busy: return
        self.target().set_erase_radius(erase_rad_edit)

    def unerase_checked(self, val):
        if self.busy: return
        self.target().toggle_unerase(val)
Exemple #2
0
class ErasingPanel: # copied for ideas for the morph panel

	def __init__(self,target,erase_radius=128):
		self.busy = True
		self.erase_radius = erase_radius
		self.target = weakref.ref(target)
		self.erase_rad_edit = None
		self.widget = None
		self.busy = False

	def set_erase_radius(self, erase_rad_edit):
		self.busy=True
		self.erase_radius = erase_rad_edit
		if self.erase_rad_edit != None: self.erase_rad_edit.setValue(erase_rad_edit)
		self.busy=False

	def get_widget(self):
		if self.widget == None:
			from PyQt4 import QtCore, QtGui, Qt
			self.widget = QtGui.QWidget()
			vbl = QtGui.QVBoxLayout(self.widget)
			vbl.setMargin(0)
			vbl.setSpacing(6)
			vbl.setObjectName("vbl")

			hbl = QtGui.QHBoxLayout()
			hbl.addWidget(QtGui.QLabel("Erase Radius:"))
			from valslider import ValSlider
			self.erase_rad_edit = ValSlider(None,(0.0,1000.0),"")
			self.erase_rad_edit.setValue(int(self.erase_radius))
			self.erase_rad_edit.setEnabled(True)
			hbl.addWidget(self.erase_rad_edit)

			self.unerase = QtGui.QCheckBox("Unerase")
			self.unerase.setChecked(False)

			vbl.addLayout(hbl)
			vbl.addWidget(self.unerase)
			QtCore.QObject.connect(self.erase_rad_edit,QtCore.SIGNAL("sliderReleased"),self.new_erase_radius)
			QtCore.QObject.connect(self.unerase,QtCore.SIGNAL("clicked(bool)"),self.unerase_checked)

		return self.widget

	def new_erase_radius(self, erase_rad_edit):
		if self.busy: return
		self.target().set_erase_radius(erase_rad_edit)

	def unerase_checked(self,val):
		if self.busy: return
		self.target().toggle_unerase(val)
Exemple #3
0
class GUIctf(QtGui.QWidget):
	def __init__(self,application,data):
		"""Implements the CTF fitting dialog using various EMImage and EMPlot2D widgets
		'data' is a list of (filename,ctf,im_1d,bg_1d,im_2d,bg_2d)
		"""
		try:
			from emimage2d import EMImage2DWidget
		except:
			print "Cannot import EMAN image GUI objects (EMImage2DWidget)"
			sys.exit(1)
		try: 
			from emplot2d import EMPlot2DWidget
		except:
			print "Cannot import EMAN plot GUI objects (is matplotlib installed?)"
			sys.exit(1)
		
		self.app = weakref.ref(application)
		
		QtGui.QWidget.__init__(self,None)
		self.setWindowIcon(QtGui.QIcon(get_image_directory() + "ctf.png"))
		
		self.data=data
		self.curset=0
		self.plotmode=0
		
		self.guiim=EMImage2DWidget(application=self.app())
		self.guiplot=EMPlot2DWidget(application=self.app())
		
		self.guiim.connect(self.guiim,QtCore.SIGNAL("mousedown"),self.imgmousedown)
		self.guiim.connect(self.guiim,QtCore.SIGNAL("mousedrag"),self.imgmousedrag)
		self.guiim.connect(self.guiim,QtCore.SIGNAL("mouseup")  ,self.imgmouseup)
		self.guiplot.connect(self.guiplot,QtCore.SIGNAL("mousedown"),self.plotmousedown)
		
		self.guiim.mmode="app"

		# This object is itself a widget we need to set up
		self.hbl = QtGui.QHBoxLayout(self)
		self.hbl.setMargin(0)
		self.hbl.setSpacing(6)
		self.hbl.setObjectName("hbl")
		
		# plot list and plot mode combobox
		self.vbl2 = QtGui.QVBoxLayout()
		self.setlist=QtGui.QListWidget(self)
		self.setlist.setSizePolicy(QtGui.QSizePolicy.Preferred,QtGui.QSizePolicy.Expanding)
		self.vbl2.addWidget(self.setlist)
		
		self.splotmode=QtGui.QComboBox(self)
		self.splotmode.addItem("Bgsub & fit")
		self.splotmode.addItem("Ptcl & BG power")
		self.splotmode.addItem("SNR")
		self.splotmode.addItem("Smoothed SNR")
		self.splotmode.addItem("Integrated SNR")
		self.splotmode.addItem("Total CTF")
		self.vbl2.addWidget(self.splotmode)
		self.hbl.addLayout(self.vbl2)
		
		# ValSliders for CTF parameters
		self.vbl = QtGui.QVBoxLayout()
		self.vbl.setMargin(0)
		self.vbl.setSpacing(6)
		self.vbl.setObjectName("vbl")
		self.hbl.addLayout(self.vbl)
		
		#self.samp = ValSlider(self,(0,5.0),"Amp:",0)
		#self.vbl.addWidget(self.samp)
		
		self.sdefocus=ValSlider(self,(0,5),"Defocus:",0,90)
		self.vbl.addWidget(self.sdefocus)
		
		self.sbfactor=ValSlider(self,(0,1600),"B factor:",0,90)
		self.vbl.addWidget(self.sbfactor)
		
		self.sampcont=ValSlider(self,(0,100),"% AC",0,90)
		self.vbl.addWidget(self.sampcont)
		
#		self.sapix=ValSlider(self,(.2,10),"A/Pix:",2,90)
#		self.vbl.addWidget(self.sapix)
		
		self.svoltage=ValSlider(self,(0,500),"Voltage (kV):",0,90)
		self.vbl.addWidget(self.svoltage)
		
		self.scs=ValSlider(self,(0,5),"Cs (mm):",0,90)
		self.vbl.addWidget(self.scs)
		self.hbl_buttons = QtGui.QHBoxLayout()
		self.saveparms = QtGui.QPushButton("Save parms")
		self.recallparms = QtGui.QPushButton("Recall")
		self.output = QtGui.QPushButton("Output")
		self.hbl_buttons.addWidget(self.saveparms)
		self.hbl_buttons.addWidget(self.recallparms)
		self.hbl_buttons2 = QtGui.QHBoxLayout()
		self.hbl_buttons2.addWidget(self.output)
		self.vbl.addLayout(self.hbl_buttons)
		self.vbl.addLayout(self.hbl_buttons2)
		
		QtCore.QObject.connect(self.sdefocus, QtCore.SIGNAL("valueChanged"), self.newCTF)
		QtCore.QObject.connect(self.sbfactor, QtCore.SIGNAL("valueChanged"), self.newCTF)
#		QtCore.QObject.connect(self.sapix, QtCore.SIGNAL("valueChanged"), self.newCTF)
		QtCore.QObject.connect(self.sampcont, QtCore.SIGNAL("valueChanged"), self.newCTF)
		QtCore.QObject.connect(self.svoltage, QtCore.SIGNAL("valueChanged"), self.newCTF)
		QtCore.QObject.connect(self.scs, QtCore.SIGNAL("valueChanged"), self.newCTF)
		QtCore.QObject.connect(self.setlist,QtCore.SIGNAL("currentRowChanged(int)"),self.newSet)
		QtCore.QObject.connect(self.splotmode,QtCore.SIGNAL("currentIndexChanged(int)"),self.newPlotMode)

	   	QtCore.QObject.connect(self.saveparms,QtCore.SIGNAL("clicked(bool)"),self.on_save_params)
		QtCore.QObject.connect(self.recallparms,QtCore.SIGNAL("clicked(bool)"),self.on_recall_params)
		QtCore.QObject.connect(self.output,QtCore.SIGNAL("clicked(bool)"),self.on_output)
		
		self.update_data()
		
		self.update_data()
		self.resize(460,380) # figured these values out by printing the width and height in resize event
		self.setWindowTitle("CTF")
		
	def on_save_params(self):
		
		if len(self.setlist.selectedItems()) == 0: return
			
		val = self.curset
		name = str(self.setlist.item(val).text())
		name = get_file_tag(name)
		
#		if not db_check_dict(name):
#			print "error, the db doesn't exist:",name
#			
		db_parms=db_open_dict("bdb:e2ctf.parms")
		ctf = self.data[val][1].to_string()
		output = []
		for i,val in enumerate(self.data[val]):
			# ignore i == 0 it's just the filename
			if i > 1:
				output.append(val)
			elif i == 1:
				output.append(ctf)

		db_parms[name] = output

	def on_recall_params(self):
		if len(self.setlist.selectedItems()) == 0: return
			
		val = self.curset
		name = str(self.setlist.item(val).text())
		data = [name]
		name = get_file_tag(name)
		
		db_parms=db_open_dict("bdb:e2ctf.parms")
		if not db_parms.has_key(name):
			print "error, ctf parameters do not exist for:",name
#			
		
		data.extend(db_parms[name])
		ctf=EMAN2Ctf()
		ctf.from_string(data[1])
		data[1] = ctf
		
		self.data[val] = data
		self.newSet(self.curset)
	
#	def get_output_params(self):
	
	def on_output(self):
		from emsprworkflow import E2CTFOutputTaskGeneral
		self.form = E2CTFOutputTaskGeneral()
		self.form.run_form()
	
	def show_guis(self):
		if self.guiim != None:
			self.app().show_specific(self.guiim)
		if self.guiplot != None:
			self.app().show_specific(self.guiplot)
		
		self.app().show_specific(self)
	def closeEvent(self,event):
#		QtGui.QWidget.closeEvent(self,event)
#		self.app.app.closeAllWindows()
		if self.guiim != None:
			self.app().close_specific(self.guiim)
			self.guiim = None 
		if self.guiplot != None:
			self.app().close_specific(self.guiplot)
		event.accept()

	def newData(self,data):
		self.data=data
		self.update_data()
		
	def update_data(self):
		"""This will make sure the various widgets properly show the current data sets"""
		self.setlist.clear()
		for i,j in enumerate(self.data):
			self.setlist.addItem(j[0])
		self.setlist.setCurrentRow(self.curset)

	def update_plot(self):
		val=self.curset
		ctf=self.data[val][1]
		ds=self.data[val][1].dsbg
		s=[ds*i for i in xrange(len(ctf.background))]
		if self.plotmode==1:
			self.guiplot.set_data((s,self.data[val][2]),"fg",True,True)
			self.guiplot.set_data((s,self.data[val][3]),"bg")
			self.guiplot.setAxisParms("s (1/A)","Intensity (a.u)")
		elif self.plotmode==0: 
			bgsub=[self.data[val][2][i]-self.data[val][3][i] for i in range(len(self.data[val][2]))]
			self.guiplot.set_data((s,bgsub),"fg-bg",True,True)
			
			fit=ctf.compute_1d(len(s)*2,ds,Ctf.CtfType.CTF_AMP)		# The fit curve
			sf = sfact(s, "ribosome","nono")
			fit=[sf[i]*fit[i]**2 for i in xrange(len(s))]		# squared * a generic structure factor

			# auto-amplitude for b-factor adjustment
			rto,nrto=0,0
			for i in xrange(int(.04/ds)+1,min(int(0.15/ds),len(s)-1)): 
				if bgsub[i]>0 : 
					#rto+=fit[i]**2/fabs(bgsub[i])
					#nrto+=fit[i]
					#rto+=fit[i]**2
					#nrto+=bgsub[i]**2
					rto+=fit[i]
					nrto+=fabs(bgsub[i])
			if nrto==0 : rto=1.0
			else : rto/=nrto
			fit=[fit[i]/rto for i in range(len(s))]

			self.guiplot.set_data((s,fit),"fit")
			self.guiplot.setAxisParms("s (1/A)","Intensity (a.u)")
		elif self.plotmode==2:
			snr=ctf.compute_1d(len(s)*2,ds,Ctf.CtfType.CTF_SNR)		# The snr curve
			self.guiplot.set_data((s,snr[:len(s)]),"snr",True)
			self.guiplot.setAxisParms("s (1/A)","SNR (intensity ratio)")
		elif self.plotmode==3:
			snr=ctf.compute_1d(len(s)*2,ds,Ctf.CtfType.CTF_SNR)		# The snr curve
			self.guiplot.set_data((s,snr[:len(s)]),"snr",True)
			ssnr=ctf.compute_1d(len(s)*2,ds,Ctf.CtfType.CTF_SNR_SMOOTH)		# The fit curve
			self.guiplot.set_data((s,ssnr[:len(s)]),"ssnr")
			self.guiplot.setAxisParms("s (1/A)","SNR (intensity ratio)")
		elif self.plotmode==4:
			snr=ctf.compute_1d(len(s)*2,ds,Ctf.CtfType.CTF_SNR)		# The snr curve
			for i in range(1,len(snr)): snr[i]=snr[i]*i+snr[i-1]			# integrate SNR*s
#			for i in range(1,len(snr)): snr[i]/=snr[-1]				# normalize
			for i in range(1,len(snr)): snr[i]/=len(snr)			# this way the relative quality of images can be compared
			self.guiplot.set_data((s,snr[:len(s)]),"snr",True)
			self.guiplot.setAxisParms("s (1/A)","Integrated SNR")
		elif self.plotmode==5:
			inten=[fabs(i) for i in ctf.compute_1d(len(s)*2,ds,Ctf.CtfType.CTF_AMP)]		# The snr curve
			self.guiplot.set_data((s,inten[:len(s)]),"single",True)
			all=[0 for i in inten]
			for st in self.data:
				print st
				inten=[fabs(i) for i in st[1].compute_1d(len(s)*2,ds,Ctf.CtfType.CTF_AMP)]
				for i in range(len(all)): all[i]+=inten[i]
			self.guiplot.set_data((s,all[:len(s)]),"total")
						
			#bgsub=[self.data[val][2][i]-self.data[val][3][i] for i in range(len(self.data[val][2]))]
			#self.guiplot.set_data("fg-bg",(s,bgsub),True,True)
			
			#fit=[bgsub[i]/sfact(s[i]) for i in range(len(s))]		# squared * a generic structure factor

			#self.guiplot.set_data("fit",(s,fit))

	def newSet(self,val):
		"called when a new data set is selected from the list"
		self.curset=val

		self.sdefocus.setValue(self.data[val][1].defocus,True)
		self.sbfactor.setValue(self.data[val][1].bfactor,True)
#		self.sapix.setValue(self.data[val][1].apix)
		self.sampcont.setValue(self.data[val][1].ampcont,True)
		self.svoltage.setValue(self.data[val][1].voltage,True)
		self.scs.setValue(self.data[val][1].cs,True)
		
		self.guiim.set_data(self.data[val][4])
		self.update_plot()

	def newPlotMode(self,mode):
		self.plotmode=mode
		self.update_plot()

	def newCTF(self) :
		self.data[self.curset][1].defocus=self.sdefocus.value
		self.data[self.curset][1].bfactor=self.sbfactor.value
#		self.data[self.curset][1].apix=self.sapix.value
		self.data[self.curset][1].ampcont=self.sampcont.value
		self.data[self.curset][1].voltage=self.svoltage.value
		self.data[self.curset][1].cs=self.scs.value
		self.update_plot()

	def imgmousedown(self,event) :
		m=self.guiim.scr_to_img((event.x(),event.y()))
		#self.guiim.add_shape("cen",["rect",.9,.9,.4,x0,y0,x0+2,y0+2,1.0])
		
	def imgmousedrag(self,event) :
		m=self.guiim.scr_to_img((event.x(),event.y()))
		
		# box deletion when shift held down
		#if event.modifiers()&Qt.ShiftModifier:
			#for i,j in enumerate(self.boxes):
		
	def imgmouseup(self,event) :
		m=self.guiim.scr_to_img((event.x(),event.y()))
	
	def plotmousedown(self,event) :
		m=self.guiim.scr_to_img((event.x(),event.y()))
	
	def run(self):
		"""If you make your own application outside of this object, you are free to use
		your own local app.exec_(). This is a convenience for ctf-only programs."""
		self.app.exec_()
		
#		E2saveappwin("boxer","imagegeom",self.guiim)
#		try:
#			E2setappval("boxer","imcontrol",self.guiim.inspector.isVisible())
#			if self.guiim.inspector.isVisible() : E2saveappwin("boxer","imcontrolgeom",self.guiim.inspector)
#		except : E2setappval("boxer","imcontrol",False)
		
		return
Exemple #4
0
class EMIsoInspector(QtGui.QWidget):
	def __init__(self,target,enable_browse=False) :
		QtGui.QWidget.__init__(self,None)

		self.setWindowIcon(QtGui.QIcon(get_image_directory() +"desktop.png"))
		self.target=weakref.ref(target)
		self.rotation_sliders = EMTransformPanel(target,self)
		
		self.vbl = QtGui.QVBoxLayout(self)
		self.vbl.setMargin(0)
		self.vbl.setSpacing(6)
		self.vbl.setObjectName("vbl")
		
		self.mrcChanged = False #added by Muthu
		
		if enable_browse:
			hblbrowse = QtGui.QHBoxLayout()
			self.mrc_text = QtGui.QLineEdit()
			hblbrowse.addWidget(self.mrc_text)
			self.mrc_browse = QtGui.QPushButton("Browse")
			hblbrowse.addWidget(self.mrc_browse)
			self.vbl.addLayout(hblbrowse)

			QtCore.QObject.connect(self.mrc_text, QtCore.SIGNAL("textEdited(const QString&)"), self.on_mrc_text_change) #added by Muthu
			QtCore.QObject.connect(self.mrc_browse, QtCore.SIGNAL("clicked(bool)"), self.on_mrc_browse) # added by Muthu

		self.hbl = QtGui.QHBoxLayout()
		self.hbl.setMargin(0)
		self.hbl.setSpacing(6)
		self.hbl.setObjectName("hbl")
		self.vbl.addLayout(self.hbl)
		
		self.hist = ImgHistogram(self)
		self.hist.setObjectName("hist")
		self.hbl.addWidget(self.hist)
		
		self.vbl2 = QtGui.QVBoxLayout()
		self.vbl2.setMargin(0)
		self.vbl2.setSpacing(6)
		self.vbl2.setObjectName("vbl2")
		self.hbl.addLayout(self.vbl2)
		
		self.wiretog = QtGui.QPushButton("Wire")
		self.wiretog.setCheckable(1)
		self.vbl2.addWidget(self.wiretog)
		
		self.lighttog = QtGui.QPushButton("Light")
		self.lighttog.setCheckable(1)
		self.vbl2.addWidget(self.lighttog)
		
		self.cubetog = QtGui.QPushButton("Cube")
		self.cubetog.setCheckable(1)
		self.vbl2.addWidget(self.cubetog)
		
		self.texturetog = QtGui.QPushButton("Texture")
		self.texturetog.setCheckable(1)
		self.vbl2.addWidget(self.texturetog)
		self.texture = False
		
		self.tabwidget = QtGui.QTabWidget()
		self.maintab = None
		self.tabwidget.addTab(self.get_main_tab(), "Main")
		self.texturetab = None
		self.tabwidget.addTab(self.get_GL_tab(),"GL")
		self.tabwidget.addTab(self.get_texture_tab(),"Texture")
		self.get_texture_tab().setEnabled(False)
		self.vbl.addWidget(self.tabwidget)
		self.n3_showing = False
		
		QtCore.QObject.connect(self.thr, QtCore.SIGNAL("valueChanged"), self.on_threshold_slider)
		QtCore.QObject.connect(self.contrast, QtCore.SIGNAL("valueChanged"), target.set_contrast)
		QtCore.QObject.connect(self.bright, QtCore.SIGNAL("valueChanged"), target.set_brightness)
		QtCore.QObject.connect(self.cbb, QtCore.SIGNAL("currentIndexChanged(QString)"), self.set_material)
		QtCore.QObject.connect(self.smp, QtCore.SIGNAL("valueChanged(int)"), target.set_sample)
		QtCore.QObject.connect(self.wiretog, QtCore.SIGNAL("toggled(bool)"), target.toggle_wire)
		QtCore.QObject.connect(self.lighttog, QtCore.SIGNAL("toggled(bool)"), target.toggle_light)
		QtCore.QObject.connect(self.texturetog, QtCore.SIGNAL("toggled(bool)"), self.toggle_texture)
		QtCore.QObject.connect(self.cubetog, QtCore.SIGNAL("toggled(bool)"), target.toggle_cube)
		QtCore.QObject.connect(self.glcontrast, QtCore.SIGNAL("valueChanged"), target.set_GL_contrast)
		QtCore.QObject.connect(self.glbrightness, QtCore.SIGNAL("valueChanged"), target.set_GL_brightness)
		
		QtCore.QObject.connect(self.ambient_tab.r, QtCore.SIGNAL("valueChanged"), self.update_material)
		QtCore.QObject.connect(self.ambient_tab.g, QtCore.SIGNAL("valueChanged"), self.update_material)
		QtCore.QObject.connect(self.ambient_tab.b, QtCore.SIGNAL("valueChanged"), self.update_material)
		QtCore.QObject.connect(self.diffuse_tab.r, QtCore.SIGNAL("valueChanged"), self.update_material)
		QtCore.QObject.connect(self.diffuse_tab.g, QtCore.SIGNAL("valueChanged"), self.update_material)
		QtCore.QObject.connect(self.diffuse_tab.b, QtCore.SIGNAL("valueChanged"), self.update_material)
		QtCore.QObject.connect(self.specular_tab.r, QtCore.SIGNAL("valueChanged"), self.update_material)
		QtCore.QObject.connect(self.specular_tab.g, QtCore.SIGNAL("valueChanged"), self.update_material)
		QtCore.QObject.connect(self.specular_tab.b, QtCore.SIGNAL("valueChanged"), self.update_material)
		QtCore.QObject.connect(self.emission_tab.r, QtCore.SIGNAL("valueChanged"), self.update_material)
		QtCore.QObject.connect(self.emission_tab.g, QtCore.SIGNAL("valueChanged"), self.update_material)
		QtCore.QObject.connect(self.emission_tab.b, QtCore.SIGNAL("valueChanged"), self.update_material)
		QtCore.QObject.connect(self.shininess, QtCore.SIGNAL("valueChanged"), self.update_material)



	def on_mrc_text_change(self,text): #if enable_browse, added by muthu
		print "Use the Browse button to update the mrc file"

	def on_mrc_browse(self): #if enable_browse, added by muthu
		import os
		self.mrcfileName = QtGui.QFileDialog.getOpenFileName(self, "open file", os.getcwd(), "Text files (*.mrc)")
		if (self.mrcfileName == ""): return
		mrcData = EMData(str(self.mrcfileName))
		self.target().set_data(mrcData)
		self.mrc_text.setText(self.mrcfileName) 
		self.mrcChanged = True
		self.target().updateGL()
	
	def update_rotations(self,t3d):
		self.rotation_sliders.update_rotations(t3d)
	
	def set_scale(self,val):
		self.rotation_sliders.set_scale(val)
	
	def set_xy_trans(self, x, y):
		self.rotation_sliders.set_xy_trans(x,y)
	
	def set_xyz_trans(self,x,y,z):
		self.rotation_sliders.set_xyz_trans(x,y,z)
	
	def get_transform_layout(self):
		return self.maintab.vbl
	
	
	def update_material(self):
		self.target().isocolor = "custom"
		custom = {}
		
		custom["ambient"] = [self.ambient_tab.r.getValue(), self.ambient_tab.g.getValue(), self.ambient_tab.b.getValue(),1.0]
		custom["diffuse"] = [self.diffuse_tab.r.getValue(), self.diffuse_tab.g.getValue(), self.diffuse_tab.b.getValue(),1.0]
		custom["specular"] = [self.specular_tab.r.getValue(), self.specular_tab.g.getValue(), self.specular_tab.b.getValue(),1.0]
		custom["emission"] = [self.emission_tab.r.getValue(), self.emission_tab.g.getValue(), self.emission_tab.b.getValue(),1.0]
		custom["shininess"] = self.shininess.getValue()
		self.target().colors["custom"] = custom

		n = self.cbb.findText(QtCore.QString("custom"))
		if n < 0: return
		self.cbb.setCurrentIndex(n)
		self.target().updateGL()
	
	def set_material(self,color):
		self.target().set_material(color)
		material = self.target().get_material()
		
		self.ambient_tab.r.setValue(material["ambient"][0])
		self.ambient_tab.g.setValue(material["ambient"][1])
		self.ambient_tab.b.setValue(material["ambient"][2])
		
		self.diffuse_tab.r.setValue(material["diffuse"][0])
		self.diffuse_tab.g.setValue(material["diffuse"][1])
		self.diffuse_tab.b.setValue(material["diffuse"][2])
		
		self.specular_tab.r.setValue(material["specular"][0])
		self.specular_tab.g.setValue(material["specular"][1])
		self.specular_tab.b.setValue(material["specular"][2])
		
		self.emission_tab.r.setValue(material["emission"][0])
		self.emission_tab.g.setValue(material["emission"][1])
		self.emission_tab.b.setValue(material["emission"][2])
		
		self.shininess.setValue(material["shininess"])
	
	def get_RGB_tab(self, name=""):
		return get_RGB_tab(self,name)
		#rgbtab = QtGui.QWidget(self)
		#rgbtab.vbl = QtGui.QVBoxLayout(rgbtab)
		#rgbtab.vbl.setMargin(0)
		#rgbtab.vbl.setSpacing(6)
		#rgbtab.vbl.setObjectName(name)
		
		#rgbtab.r = ValSlider(rgbtab,(0.0,1.0),"R:")
		#rgbtab.r.setObjectName("R")
		#rgbtab.r.setValue(0.5)
		#rgbtab.vbl.addWidget(rgbtab.r)
		
		#rgbtab.g = ValSlider(rgbtab,(0.0,1.0),"G:")
		#rgbtab.g.setObjectName("G")
		#rgbtab.g.setValue(0.5)
		#rgbtab.vbl.addWidget(rgbtab.g)
		
		#rgbtab.b = ValSlider(rgbtab,(0.0,1.0),"B:")
		#rgbtab.b.setObjectName("B")
		#rgbtab.b.setValue(0.5)
		#rgbtab.vbl.addWidget(rgbtab.b)
		
		#return rgbtab
	
	def get_GL_tab(self):
		self.gltab = QtGui.QWidget()
		gltab = self.gltab
		
		gltab.vbl = QtGui.QVBoxLayout(self.gltab )
		gltab.vbl.setMargin(0)
		gltab.vbl.setSpacing(6)
		gltab.vbl.setObjectName("GL")
		
		
		self.glcontrast = ValSlider(gltab,(1.0,5.0),"GLShd:")
		self.glcontrast.setObjectName("GLShade")
		self.glcontrast.setValue(1.0)
		gltab.vbl.addWidget(self.glcontrast)
		
		self.glbrightness = ValSlider(gltab,(-1.0,0.0),"GLBst:")
		self.glbrightness.setObjectName("GLBoost")
		self.glbrightness.setValue(0.1)
		self.glbrightness.setValue(0.0)
		gltab.vbl.addWidget(self.glbrightness)
	
		self.material_tab_widget = QtGui.QTabWidget()
		self.ambient_tab = self.get_RGB_tab("ambient")
		self.material_tab_widget.addTab(self.ambient_tab, "Ambient")
		
		self.diffuse_tab = self.get_RGB_tab("diffuse")
		self.material_tab_widget.addTab(self.diffuse_tab, "Diffuse")
		
		self.specular_tab = self.get_RGB_tab("specular")
		self.material_tab_widget.addTab(self.specular_tab, "Specular")
		
		self.emission_tab = self.get_RGB_tab("emission")
		self.material_tab_widget.addTab(self.emission_tab, "Emission")
		
		gltab.vbl.addWidget(self.material_tab_widget)

		self.shininess = ValSlider(gltab,(0,128),"Shininess:")
		self.shininess.setObjectName("Shininess")
		self.shininess.setValue(64)
		gltab.vbl.addWidget(self.shininess)

		self.hbl_color = QtGui.QHBoxLayout()
		self.hbl_color.setMargin(0)
		self.hbl_color.setSpacing(6)
		self.hbl_color.setObjectName("Material")
		gltab.vbl.addLayout(self.hbl_color)
		
		self.color_label = QtGui.QLabel()
		self.color_label.setText('Material')
		self.hbl_color.addWidget(self.color_label)
		
		self.cbb = QtGui.QComboBox(gltab)
		self.hbl_color.addWidget(self.cbb)
		
		return gltab
	
	def toggle_texture(self):
		self.texture = not self.texture
		self.target().toggle_texture()
		self.get_texture_tab().setEnabled(self.texture)
	
	def get_texture_tab(self):
		if ( self.texturetab == None ):
			self.texturetab = QtGui.QWidget()
			texturetab = self.texturetab
			texturetab.vbl = QtGui.QVBoxLayout(self.texturetab)
			texturetab.vbl.setMargin(0)
			texturetab.vbl.setSpacing(6)
			texturetab.vbl.setObjectName("Main")
		
			self.contrast = ValSlider(texturetab,(0.0,20.0),"Cont:")
			self.contrast.setObjectName("contrast")
			self.contrast.setValue(10.0)
			texturetab.vbl.addWidget(self.contrast)
	
			self.bright = ValSlider(texturetab,(-5.0,5.0),"Brt:")
			self.bright.setObjectName("bright")
			self.bright.setValue(0.1)
			self.bright.setValue(0.0)
			texturetab.vbl.addWidget(self.bright)
			
			#self.glcontrast = ValSlider(texturetab,(1.0,5.0),"GLShd:")
			#self.glcontrast.setObjectName("GLShade")
			#self.glcontrast.setValue(1.0)
			#texturetab.vbl.addWidget(self.glcontrast)
			
			#self.glbrightness = ValSlider(texturetab,(-1.0,0.0),"GLBst:")
			#self.glbrightness.setObjectName("GLBoost")
			#self.glbrightness.setValue(0.1)
			#self.glbrightness.setValue(0.0)
			#texturetab.vbl.addWidget(self.glbrightness)
			
		return self.texturetab
	
	def get_main_tab(self):
		if ( self.maintab == None ):
			self.maintab = QtGui.QWidget()
			maintab = self.maintab
			maintab.vbl = QtGui.QVBoxLayout(self.maintab)
			maintab.vbl.setMargin(0)
			maintab.vbl.setSpacing(6)
			maintab.vbl.setObjectName("Main")
			
			self.thr = ValSlider(maintab,(0.0,4.0),"Thr:")
			self.thr.setObjectName("thr")
			self.thr.setValue(0.5)
			maintab.vbl.addWidget(self.thr)
			
			self.hbl_smp = QtGui.QHBoxLayout()
			self.hbl_smp.setMargin(0)
			self.hbl_smp.setSpacing(6)
			self.hbl_smp.setObjectName("Sample")
			maintab.vbl.addLayout(self.hbl_smp)
			
			self.smp_label = QtGui.QLabel()
			self.smp_label.setText('Sample Level')
			self.hbl_smp.addWidget(self.smp_label)
			
			self.smp = QtGui.QSpinBox(maintab)
			self.smp.setValue(1)
			self.hbl_smp.addWidget(self.smp)
	
			self.rotation_sliders.addWidgets(maintab.vbl)
			
		return self.maintab
	
	def set_sampling_range(self,range):
		self.smp.setMinimum(1)
		self.smp.setMaximum(1+range-1)
	
	def slider_rotate(self):
		self.target().load_rotation(self.get_current_rotation())
	
	
	def set_materials(self,colors,current_color):
		a = 0
		for i in colors:
			self.cbb.addItem(i)
			if ( i == current_color):
				self.cbb.setCurrentIndex(a)
			a += 1

	def on_threshold_slider(self,val):
		self.target().set_threshold(val)
		self.bright.setValue(-val,True)
		
	def set_thresholds(self,low,high,val):
		self.thr.setRange(low,high)
		self.thr.setValue(val, True)
		self.bright.setValue(-val,True)
	
	def set_sample(self,low,high,val):
		self.smp.setRange(int(low),int(high))
		self.smp.setValue(val, True)
		
	def set_hist(self,hist,minden,maxden):
		self.hist.set_data(hist,minden,maxden)
Exemple #5
0
class EMTransformPanel:
    def __init__(self, target, parent):
        self.target = weakref.ref(target)
        self.parent = weakref.ref(parent)

        self.label_src = QtGui.QLabel(parent)
        self.label_src.setText('Rotation Convention')

        self.src = QtGui.QComboBox(parent)
        self.load_src_options(self.src)

        self.x_label = QtGui.QLabel()
        self.x_label.setText('x')

        self.x_trans = QtGui.QDoubleSpinBox(parent)
        self.x_trans.setMinimum(-10000)
        self.x_trans.setMaximum(10000)
        self.x_trans.setValue(0.0)

        self.y_label = QtGui.QLabel()
        self.y_label.setText('y')

        self.y_trans = QtGui.QDoubleSpinBox(parent)
        self.y_trans.setMinimum(-10000)
        self.y_trans.setMaximum(10000)
        self.y_trans.setValue(0.0)

        self.z_label = QtGui.QLabel()
        self.z_label.setText('z')

        self.z_trans = QtGui.QDoubleSpinBox(parent)
        self.z_trans.setMinimum(-10000)
        self.z_trans.setMaximum(10000)
        self.z_trans.setValue(0.0)

        self.az = ValSlider(parent, (-360.0, 360.0), "az", -1)
        self.az.setObjectName("az")
        self.az.setValue(0.0)

        self.alt = ValSlider(parent, (-180.0, 180.0), "alt", -1)
        self.alt.setObjectName("alt")
        self.alt.setValue(0.0)

        self.phi = ValSlider(parent, (-360.0, 360.0), "phi", -1)
        self.phi.setObjectName("phi")
        self.phi.setValue(0.0)

        self.scale = ValSlider(parent, (0.01, 30.0), "Zoom:")
        self.scale.setObjectName("scale")
        self.scale.setValue(1.0)

        self.n3_showing = False

        self.current_src = "eman"

        QtCore.QObject.connect(self.az, QtCore.SIGNAL("valueChanged"),
                               self.slider_rotate)
        QtCore.QObject.connect(self.alt, QtCore.SIGNAL("valueChanged"),
                               self.slider_rotate)
        QtCore.QObject.connect(self.phi, QtCore.SIGNAL("valueChanged"),
                               self.slider_rotate)
        QtCore.QObject.connect(self.src,
                               QtCore.SIGNAL("currentIndexChanged(QString)"),
                               self.set_src)
        QtCore.QObject.connect(self.scale, QtCore.SIGNAL("valueChanged"),
                               self.target().set_scale)
        QtCore.QObject.connect(self.x_trans,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.target().set_cam_x)
        QtCore.QObject.connect(self.y_trans,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.target().set_cam_y)
        QtCore.QObject.connect(self.z_trans,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.target().set_cam_z)

    def set_defaults(self):
        self.x_trans.setValue(0.0)
        self.y_trans.setValue(0.0)
        self.z_trans.setValue(0.0)
        self.scale.setValue(1.0)
        self.az.setValue(0.0)
        self.alt.setValue(0.0)
        self.phi.setValue(0.0)

    def slider_rotate(self):
        self.target().load_rotation(self.get_current_rotation())

    def get_current_rotation(self):
        convention = self.src.currentText()
        rot = {}
        if (self.current_src == "spin"):
            rot[self.az.getLabel()] = self.az.getValue()

            n1 = self.alt.getValue()
            n2 = self.phi.getValue()
            n3 = self.n3.getValue()

            norm = sqrt(n1 * n1 + n2 * n2 + n3 * n3)

            n1 /= norm
            n2 /= norm
            n3 /= norm

            rot[self.alt.getLabel()] = n1
            rot[self.phi.getLabel()] = n2
            rot[self.n3.getLabel()] = n3

        else:
            rot[self.az.getLabel()] = self.az.getValue()
            rot[self.alt.getLabel()] = self.alt.getValue()
            rot[self.phi.getLabel()] = self.phi.getValue()

        rot["type"] = self.current_src

        return Transform(rot)

    def addWidgets(self, target):

        target.addWidget(self.scale)
        self.hbl_trans = QtGui.QHBoxLayout()
        self.hbl_trans.setMargin(0)
        self.hbl_trans.setSpacing(6)
        self.hbl_trans.setObjectName("Trans")
        self.hbl_trans.addWidget(self.x_label)
        self.hbl_trans.addWidget(self.x_trans)
        self.hbl_trans.addWidget(self.y_label)
        self.hbl_trans.addWidget(self.y_trans)
        self.hbl_trans.addWidget(self.z_label)
        self.hbl_trans.addWidget(self.z_trans)

        target.addLayout(self.hbl_trans)

        self.hbl_src = QtGui.QHBoxLayout()
        self.hbl_src.setMargin(0)
        self.hbl_src.setSpacing(6)
        self.hbl_src.setObjectName("hbl")
        self.hbl_src.addWidget(self.label_src)
        self.hbl_src.addWidget(self.src)

        target.addLayout(self.hbl_src)
        target.addWidget(self.az)
        target.addWidget(self.alt)
        target.addWidget(self.phi)

    def set_src(self, val):
        t3d = self.get_current_rotation()

        if (self.n3_showing):
            self.parent().get_transform_layout().removeWidget(self.n3)
            self.n3.deleteLater()
            self.n3_showing = False
            self.az.setRange(-360, 360)
            self.alt.setRange(-180, 180)
            self.phi.setRange(-360, 660)

        if (self.src_map[str(val)] == "spider"):
            self.az.setLabel('phi')
            self.alt.setLabel('theta')
            self.phi.setLabel('psi')
        elif (self.src_map[str(val)] == "eman"):
            self.az.setLabel('az')
            self.alt.setLabel('alt')
            self.phi.setLabel('phi')
        elif (self.src_map[str(val)] == "imagic"):
            self.az.setLabel('alpha')
            self.alt.setLabel('beta')
            self.phi.setLabel('gamma')
        elif (self.src_map[str(val)] == "xyz"):
            self.az.setLabel('xtilt')
            self.alt.setLabel('ytilt')
            self.phi.setLabel('ztilt')
        elif (self.src_map[str(val)] == "mrc"):
            self.az.setLabel('phi')
            self.alt.setLabel('theta')
            self.phi.setLabel('omega')
        elif (self.src_map[str(val)] == "spin"):
            self.az.setLabel('omega')
            self.alt.setRange(-1, 1)
            self.phi.setRange(-1, 1)

            self.alt.setLabel('n1')
            self.phi.setLabel('n2')

            self.n3 = ValSlider(self.parent(), (-360.0, 360.0), "n3", -1)
            self.n3.setRange(-1, 1)
            self.n3.setObjectName("n3")
            self.parent().get_transform_layout().addWidget(self.n3)
            QtCore.QObject.connect(self.n3, QtCore.SIGNAL("valueChanged"),
                                   self.slider_rotate)
            self.n3_showing = True

        self.current_src = self.src_map[str(val)]
        self.update_rotations(t3d)

    def load_src_options(self, widgit):
        self.load_src()
        for i in self.src_strings:
            widgit.addItem(i)

    def load_src(self):
        # supported_rot_conventions
        src_flags = []
        src_flags.append("eman")
        src_flags.append("spider")
        src_flags.append("imagic")
        src_flags.append("mrc")
        src_flags.append("spin")
        src_flags.append("xyz")

        self.src_strings = []
        self.src_map = {}
        for i in src_flags:
            self.src_strings.append(str(i))
            self.src_map[str(i)] = i

    def update_rotations(self, t3d):
        rot = t3d.get_rotation(self.src_map[str(
            self.src.itemText(self.src.currentIndex()))])

        convention = self.src.currentText()
        if (self.src_map[str(convention)] == "spin"):
            self.n3.setValue(rot[self.n3.getLabel()], True)

        self.az.setValue(rot[self.az.getLabel()], True)
        self.alt.setValue(rot[self.alt.getLabel()], True)
        self.phi.setValue(rot[self.phi.getLabel()], True)

    def set_scale(self, newscale):
        self.scale.setValue(newscale)

    def set_xy_trans(self, x, y):
        self.x_trans.setValue(x)
        self.y_trans.setValue(y)

    def set_xyz_trans(self, x, y, z):
        self.x_trans.setValue(x)
        self.y_trans.setValue(y)
        self.z_trans.setValue(z)
class EMGLPlotInspector(QtGui.QWidget):
	def __init__(self,target) :
		QtGui.QWidget.__init__(self,None)
		self.target=target
		
		self.vbl = QtGui.QVBoxLayout(self)
		self.vbl.setMargin(0)
		self.vbl.setSpacing(6)
		self.vbl.setObjectName("vbl")
		
		self.hbl = QtGui.QHBoxLayout()
		self.hbl.setMargin(0)
		self.hbl.setSpacing(6)
		self.hbl.setObjectName("hbl")
		self.vbl.addLayout(self.hbl)
		
		self.hist = ImgHistogram(self)
		self.hist.setObjectName("hist")
		self.hbl.addWidget(self.hist)
		
		self.vbl2 = QtGui.QVBoxLayout()
		self.vbl2.setMargin(0)
		self.vbl2.setSpacing(6)
		self.vbl2.setObjectName("vbl2")
		self.hbl.addLayout(self.vbl2)
		
		self.wiretog = QtGui.QPushButton("Wire")
		self.wiretog.setCheckable(1)
		self.vbl2.addWidget(self.wiretog)
		
		self.lighttog = QtGui.QPushButton("Light")
		self.lighttog.setCheckable(1)
		self.vbl2.addWidget(self.lighttog)
		
		self.tabwidget = QtGui.QTabWidget()
		self.maintab = None
		self.tabwidget.addTab(self.get_main_tab(), "Main")
		self.tabwidget.addTab(self.get_GL_tab(),"GL")
		self.vbl.addWidget(self.tabwidget)
		self.n3_showing = False
		
		QtCore.QObject.connect(self.scale, QtCore.SIGNAL("valueChanged"), target.set_scale)
		QtCore.QObject.connect(self.az, QtCore.SIGNAL("valueChanged"), self.slider_rotate)
		QtCore.QObject.connect(self.alt, QtCore.SIGNAL("valueChanged"), self.slider_rotate)
		QtCore.QObject.connect(self.phi, QtCore.SIGNAL("valueChanged"), self.slider_rotate)
		QtCore.QObject.connect(self.cbb, QtCore.SIGNAL("currentIndexChanged(QString)"), target.setColor)
		QtCore.QObject.connect(self.src, QtCore.SIGNAL("currentIndexChanged(QString)"), self.set_src)
		QtCore.QObject.connect(self.x_trans, QtCore.SIGNAL("valueChanged(double)"), target.set_cam_x)
		QtCore.QObject.connect(self.y_trans, QtCore.SIGNAL("valueChanged(double)"), target.set_cam_y)
		QtCore.QObject.connect(self.z_trans, QtCore.SIGNAL("valueChanged(double)"), target.set_cam_z)
		QtCore.QObject.connect(self.wiretog, QtCore.SIGNAL("toggled(bool)"), target.toggle_wire)
		QtCore.QObject.connect(self.lighttog, QtCore.SIGNAL("toggled(bool)"), target.toggle_light)
		QtCore.QObject.connect(self.glcontrast, QtCore.SIGNAL("valueChanged"), target.set_GL_contrast)
		QtCore.QObject.connect(self.glbrightness, QtCore.SIGNAL("valueChanged"), target.set_GL_brightness)
	
	def get_GL_tab(self):
		self.gltab = QtGui.QWidget()
		gltab = self.gltab
		
		gltab.vbl = QtGui.QVBoxLayout(self.gltab )
		gltab.vbl.setMargin(0)
		gltab.vbl.setSpacing(6)
		gltab.vbl.setObjectName("Main")
		
		self.glcontrast = ValSlider(gltab,(1.0,5.0),"GLShd:")
		self.glcontrast.setObjectName("GLShade")
		self.glcontrast.setValue(1.0)
		gltab.vbl.addWidget(self.glcontrast)
		
		self.glbrightness = ValSlider(gltab,(-1.0,0.0),"GLBst:")
		self.glbrightness.setObjectName("GLBoost")
		self.glbrightness.setValue(0.1)
		self.glbrightness.setValue(0.0)
		gltab.vbl.addWidget(self.glbrightness)
	
		return gltab
	
	def get_main_tab(self):
		if ( self.maintab == None ):
			self.maintab = QtGui.QWidget()
			maintab = self.maintab
			maintab.vbl = QtGui.QVBoxLayout(self.maintab)
			maintab.vbl.setMargin(0)
			maintab.vbl.setSpacing(6)
			maintab.vbl.setObjectName("Main")
			
			self.scale = ValSlider(maintab,(0.01,30.0),"Zoom:")
			self.scale.setObjectName("scale")
			self.scale.setValue(1.0)
			maintab.vbl.addWidget(self.scale)
			
			self.hbl_color = QtGui.QHBoxLayout()
			self.hbl_color.setMargin(0)
			self.hbl_color.setSpacing(6)
			self.hbl_color.setObjectName("Material")
			maintab.vbl.addLayout(self.hbl_color)
			
			self.color_label = QtGui.QLabel()
			self.color_label.setText('Material')
			self.hbl_color.addWidget(self.color_label)
			
			self.cbb = QtGui.QComboBox(maintab)
			self.hbl_color.addWidget(self.cbb)
	
			self.hbl_trans = QtGui.QHBoxLayout()
			self.hbl_trans.setMargin(0)
			self.hbl_trans.setSpacing(6)
			self.hbl_trans.setObjectName("Trans")
			maintab.vbl.addLayout(self.hbl_trans)
			
			self.x_label = QtGui.QLabel()
			self.x_label.setText('x')
			self.hbl_trans.addWidget(self.x_label)
			
			self.x_trans = QtGui.QDoubleSpinBox(self)
			self.x_trans.setMinimum(-10000)
			self.x_trans.setMaximum(10000)
			self.x_trans.setValue(0.0)
			self.hbl_trans.addWidget(self.x_trans)
			
			self.y_label = QtGui.QLabel()
			self.y_label.setText('y')
			self.hbl_trans.addWidget(self.y_label)
			
			self.y_trans = QtGui.QDoubleSpinBox(maintab)
			self.y_trans.setMinimum(-10000)
			self.y_trans.setMaximum(10000)
			self.y_trans.setValue(0.0)
			self.hbl_trans.addWidget(self.y_trans)
			
			
			self.z_label = QtGui.QLabel()
			self.z_label.setText('z')
			self.hbl_trans.addWidget(self.z_label)
			
			self.z_trans = QtGui.QDoubleSpinBox(maintab)
			self.z_trans.setMinimum(-10000)
			self.z_trans.setMaximum(10000)
			self.z_trans.setValue(0.0)
			self.hbl_trans.addWidget(self.z_trans)
			
			self.hbl_src = QtGui.QHBoxLayout()
			self.hbl_src.setMargin(0)
			self.hbl_src.setSpacing(6)
			self.hbl_src.setObjectName("hbl")
			maintab.vbl.addLayout(self.hbl_src)
			
			self.label_src = QtGui.QLabel()
			self.label_src.setText('Rotation Convention')
			self.hbl_src.addWidget(self.label_src)
			
			self.src = QtGui.QComboBox(maintab)
			self.load_src_options(self.src)
			self.hbl_src.addWidget(self.src)
			
			# set default value -1 ensures that the val slider is updated the first time it is created
			self.az = ValSlider(self,(-360.0,360.0),"az",-1)
			self.az.setObjectName("az")
			maintab.vbl.addWidget(self.az)
			
			self.alt = ValSlider(self,(-180.0,180.0),"alt",-1)
			self.alt.setObjectName("alt")
			maintab.vbl.addWidget(self.alt)
			
			self.phi = ValSlider(self,(-360.0,360.0),"phi",-1)
			self.phi.setObjectName("phi")
			maintab.vbl.addWidget(self.phi)
		
			self.current_src = EULER_EMAN
		
		return self.maintab

	def set_xy_trans(self, x, y):
		self.x_trans.setValue(x)
		self.y_trans.setValue(y)
	
	def set_translate_scale(self, xscale,yscale,zscale):
		self.x_trans.setSingleStep(xscale)
		self.y_trans.setSingleStep(yscale)
		self.z_trans.setSingleStep(zscale)

	def update_rotations(self,t3d):
		rot = t3d.get_rotation(self.src_map[str(self.src.itemText(self.src.currentIndex()))])
		
		convention = self.src.currentText()
		if ( self.src_map[str(convention)] == EULER_SPIN ):
			self.n3.setValue(rot[self.n3.getLabel()],True)
		
		self.az.setValue(rot[self.az.getLabel()],True)
		self.alt.setValue(rot[self.alt.getLabel()],True)
		self.phi.setValue(rot[self.phi.getLabel()],True)
	
	def slider_rotate(self):
		self.target.load_rotation(self.get_current_rotation())
	
	def get_current_rotation(self):
		convention = self.src.currentText()
		rot = {}
		if ( self.current_src == EULER_SPIN ):
			rot[self.az.getLabel()] = self.az.getValue()
			
			n1 = self.alt.getValue()
			n2 = self.phi.getValue()
			n3 = self.n3.getValue()
			
			norm = sqrt(n1*n1 + n2*n2 + n3*n3)
			
			n1 /= norm
			n2 /= norm
			n3 /= norm
			
			rot[self.alt.getLabel()] = n1
			rot[self.phi.getLabel()] = n2
			rot[self.n3.getLabel()] = n3
			
		else:
			rot[self.az.getLabel()] = self.az.getValue()
			rot[self.alt.getLabel()] = self.alt.getValue()
			rot[self.phi.getLabel()] = self.phi.getValue()
		
		return Transform3D(self.current_src, rot)
	
	def set_src(self, val):
		t3d = self.get_current_rotation()
		
		if (self.n3_showing) :
			self.vbl.removeWidget(self.n3)
			self.n3.deleteLater()
			self.n3_showing = False
			self.az.setRange(-360,360)
			self.alt.setRange(-180,180)
			self.phi.setRange(-360,660)
		
		if ( self.src_map[str(val)] == EULER_SPIDER ):
			self.az.setLabel('phi')
			self.alt.setLabel('theta')
			self.phi.setLabel('psi')
		elif ( self.src_map[str(val)] == EULER_EMAN ):
			self.az.setLabel('az')
			self.alt.setLabel('alt')
			self.phi.setLabel('phi')
		elif ( self.src_map[str(val)] == EULER_IMAGIC ):
			self.az.setLabel('alpha')
			self.alt.setLabel('beta')
			self.phi.setLabel('gamma')
		elif ( self.src_map[str(val)] == EULER_XYZ ):
			self.az.setLabel('xtilt')
			self.alt.setLabel('ytilt')
			self.phi.setLabel('ztilt')
		elif ( self.src_map[str(val)] == EULER_MRC ):
			self.az.setLabel('phi')
			self.alt.setLabel('theta')
			self.phi.setLabel('omega')
		elif ( self.src_map[str(val)] == EULER_SPIN ):
			self.az.setLabel('Omega')
			self.alt.setRange(-1,1)
			self.phi.setRange(-1,1)
			
			self.alt.setLabel('n1')
			self.phi.setLabel('n2')
			
			self.n3 = ValSlider(self,(-360.0,360.0),"n3",-1)
			self.n3.setRange(-1,1)
			self.n3.setObjectName("n3")
			self.vbl.addWidget(self.n3)
			QtCore.QObject.connect(self.n3, QtCore.SIGNAL("valueChanged"), self.slider_rotate)
			self.n3_showing = True
		
		self.current_src = self.src_map[str(val)]
		self.update_rotations(t3d)
	
	def load_src_options(self,widgit):
		self.load_src()
		for i in self.src_strings:
			widgit.addItem(i)
	
	# read src as 'supported rotation conventions'
	def load_src(self):
		# supported_rot_conventions
		src_flags = []
		src_flags.append(EULER_EMAN)
		src_flags.append(EULER_SPIDER)
		src_flags.append(EULER_IMAGIC)
		src_flags.append(EULER_MRC)
		src_flags.append(EULER_SPIN)
		src_flags.append(EULER_XYZ)
		
		self.src_strings = []
		self.src_map = {}
		for i in src_flags:
			self.src_strings.append(str(i))
			self.src_map[str(i)] = i
		
	
	def setColors(self,colors,current_color):
		a = 0
		for i in colors:
			self.cbb.addItem(i)
			if ( i == current_color):
				self.cbb.setCurrentIndex(a)
			a += 1

	def set_scale(self,newscale):
		self.scale.setValue(newscale)
class EMImageInspectorMX(QtGui.QWidget):
	def __init__(self,target) :
		QtGui.QWidget.__init__(self,None)
		self.target=target
		
		self.vboxlayout = QtGui.QVBoxLayout(self)
		self.vboxlayout.setMargin(0)
		self.vboxlayout.setSpacing(6)
		self.vboxlayout.setObjectName("vboxlayout")
		
		self.hist = ImgHistogram(self)
		self.hist.setObjectName("hist")
		self.vboxlayout.addWidget(self.hist)
		
		self.hboxlayout = QtGui.QHBoxLayout()
		self.hboxlayout.setMargin(0)
		self.hboxlayout.setSpacing(6)
		self.hboxlayout.setObjectName("hboxlayout")
		self.vboxlayout.addLayout(self.hboxlayout)
		
		self.lbl = QtGui.QLabel("#/row:")
		self.lbl.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
		self.hboxlayout.addWidget(self.lbl)
		
		self.nrow = QtGui.QSpinBox(self)
		self.nrow.setObjectName("nrow")
		self.nrow.setRange(1,50)
		self.nrow.setValue(6)
		self.hboxlayout.addWidget(self.nrow)
		
		self.lbl = QtGui.QLabel("N:")
		self.lbl.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
		self.hboxlayout.addWidget(self.lbl)
		
		self.imgn = QtGui.QSpinBox(self)
		self.imgn.setObjectName("imgn")
		self.imgn.setRange(-1,50)
		self.imgn.setValue(0)
		self.imgn.setSpecialValueText("All")
		self.hboxlayout.addWidget(self.imgn)
		
		self.scale = ValSlider(self,(0.1,5.0),"Mag:")
		self.scale.setObjectName("scale")
		self.scale.setValue(1.0)
		self.vboxlayout.addWidget(self.scale)
		
		self.mins = ValSlider(self,label="Min:")
		self.mins.setObjectName("mins")
		self.vboxlayout.addWidget(self.mins)
		
		self.maxs = ValSlider(self,label="Max:")
		self.maxs.setObjectName("maxs")
		self.vboxlayout.addWidget(self.maxs)
		
		self.brts = ValSlider(self,(-1.0,1.0),"Brt:")
		self.brts.setObjectName("brts")
		self.vboxlayout.addWidget(self.brts)
		
		self.conts = ValSlider(self,(0.0,1.0),"Cont:")
		self.conts.setObjectName("conts")
		self.vboxlayout.addWidget(self.conts)
		
		self.lowlim=0
		self.highlim=1.0
		self.busy=0
		
		QtCore.QObject.connect(self.nrow, QtCore.SIGNAL("valueChanged(int)"), target.setNPerRow)
		QtCore.QObject.connect(self.imgn, QtCore.SIGNAL("valueChanged(int)"), target.setNShow)
		QtCore.QObject.connect(self.scale, QtCore.SIGNAL("valueChanged"), target.set_scale)
		QtCore.QObject.connect(self.mins, QtCore.SIGNAL("valueChanged"), self.newMin)
		QtCore.QObject.connect(self.maxs, QtCore.SIGNAL("valueChanged"), self.newMax)
		QtCore.QObject.connect(self.brts, QtCore.SIGNAL("valueChanged"), self.newBrt)
		QtCore.QObject.connect(self.conts, QtCore.SIGNAL("valueChanged"), self.newCont)


	def newMin(self,val):
		if self.busy : return
		self.busy=1
		self.target.setDenMin(val)

		self.update_brightness_contrast()
		self.busy=0
		
	def newMax(self,val):
		if self.busy : return
		self.busy=1
		self.target.setDenMax(val)
		self.update_brightness_contrast()
		self.busy=0
	
	def newBrt(self,val):
		if self.busy : return
		self.busy=1
		self.update_min_max()
		self.busy=0
		
	def newCont(self,val):
		if self.busy : return
		self.busy=1
		self.update_min_max()
		self.busy=0

	def update_brightness_contrast(self):
		b=0.5*(self.mins.value+self.maxs.value-(self.lowlim+self.highlim))
		c=(self.mins.value-self.maxs.value)/(2.0*(self.lowlim-self.highlim))
		self.brts.setValue(-b)
		self.conts.setValue(1.0-c)
		
	def update_min_max(self):
		x0=((self.lowlim+self.highlim)/2.0-(self.highlim-self.lowlim)*(1.0-self.conts.value+self.brts.value))
		x1=((self.lowlim+self.highlim)/2.0+(self.highlim-self.lowlim)*(1.0-self.conts.value-self.brts.value))
		self.mins.setValue(x0)
		self.maxs.setValue(x1)
		self.target.setDenRange(x0,x1)
		
	def set_hist(self,hist,minden,maxden):
		self.hist.set_data(hist,minden,maxden)

	def set_limits(self,lowlim,highlim,curmin,curmax):
		self.lowlim=lowlim
		self.highlim=highlim
		self.mins.setRange(lowlim,highlim)
		self.maxs.setRange(lowlim,highlim)
		self.mins.setValue(curmin)
		self.maxs.setValue(curmax)
Exemple #8
0
class GUIctfsim(QtGui.QWidget):
	def __init__(self,application,apix=1.0,voltage=300.0,cs=4.1,ac=10.0,samples=256):
		"""CTF simulation dialog
		"""
		try:
			from emimage2d import EMImage2DWidget
		except:
			print "Cannot import EMAN image GUI objects (EMImage2DWidget)"
			sys.exit(1)
		try:
			from emplot2d import EMPlot2DWidget
		except:
			print "Cannot import EMAN plot GUI objects (is matplotlib installed?)"
			sys.exit(1)

		self.app = weakref.ref(application)

		self.df_voltage=voltage
		self.df_apix=apix
		self.df_cs=cs
		self.df_ac=ac
		self.df_samples=samples
		self.img=None

		QtGui.QWidget.__init__(self,None)
		self.setWindowIcon(QtGui.QIcon(get_image_directory() + "ctf.png"))

		self.data=[]
		self.curset=0
		self.plotmode=0

		self.guiim=EMImage2DWidget(application=self.app())
		self.guiiminit = True # a flag that's used to auto resize the first time the gui's set_data function is called
		self.guiplot=EMPlot2DWidget(application=self.app())
#		self.guirealim=EMImage2DWidget(application=self.app())	# This will show the original particle images

#		self.guirealim.connect(self.guirealim,QtCore.SIGNAL("keypress"),self.realimgkey)
		self.guiim.connect(self.guiim,QtCore.SIGNAL("mousedown"),self.imgmousedown)
		self.guiim.connect(self.guiim,QtCore.SIGNAL("mousedrag"),self.imgmousedrag)
		self.guiim.connect(self.guiim,QtCore.SIGNAL("mouseup")  ,self.imgmouseup)
		self.guiplot.connect(self.guiplot,QtCore.SIGNAL("mousedown"),self.plotmousedown)

		self.guiim.mmode="app"

		# This object is itself a widget we need to set up
		self.hbl = QtGui.QHBoxLayout(self)
		self.hbl.setMargin(0)
		self.hbl.setSpacing(6)
		self.hbl.setObjectName("hbl")

		# plot list and plot mode combobox
		self.vbl2 = QtGui.QVBoxLayout()
		self.setlist=MyListWidget(self)
		self.setlist.setSizePolicy(QtGui.QSizePolicy.Preferred,QtGui.QSizePolicy.Expanding)
		self.vbl2.addWidget(self.setlist)

		self.splotmode=QtGui.QComboBox(self)
		self.splotmode.addItem("Amplitude")
		self.splotmode.addItem("Intensity")
		self.splotmode.addItem("Int w sum")
		self.splotmode.addItem("Amp w sum")
		self.vbl2.addWidget(self.splotmode)
		self.hbl.addLayout(self.vbl2)

		# ValSliders for CTF parameters
		self.vbl = QtGui.QVBoxLayout()
		self.vbl.setMargin(0)
		self.vbl.setSpacing(6)
		self.vbl.setObjectName("vbl")
		self.hbl.addLayout(self.vbl)

		#self.samp = ValSlider(self,(0,5.0),"Amp:",0)
		#self.vbl.addWidget(self.samp)

		self.imginfo=QtGui.QLabel("Info",self)
		self.vbl.addWidget(self.imginfo)

		self.sdefocus=ValSlider(self,(0,5),"Defocus:",0,90)
		self.vbl.addWidget(self.sdefocus)

		self.sbfactor=ValSlider(self,(0,1600),"B factor:",0,90)
		self.vbl.addWidget(self.sbfactor)

		self.sdfdiff=ValSlider(self,(0,1),"DF Diff:",0,90)
		self.vbl.addWidget(self.sdfdiff)

		self.sdfang=ValSlider(self,(0,180),"Df Angle:",0,90)
		self.vbl.addWidget(self.sdfang)

		self.sampcont=ValSlider(self,(0,100),"% AC",0,90)
		self.vbl.addWidget(self.sampcont)

		self.sapix=ValSlider(self,(.2,10),"A/Pix:",2,90)
		self.vbl.addWidget(self.sapix)

		self.svoltage=ValSlider(self,(0,1000),"Voltage (kV):",0,90)
		self.vbl.addWidget(self.svoltage)

		self.scs=ValSlider(self,(0,5),"Cs (mm):",0,90)
		self.vbl.addWidget(self.scs)

		self.ssamples=ValSlider(self,(32,1024),"# Samples:",0,90)
		self.ssamples.setIntonly(True)
		self.vbl.addWidget(self.ssamples)


		self.hbl_buttons = QtGui.QHBoxLayout()
		self.newbut = QtGui.QPushButton("New")
		self.hbl_buttons.addWidget(self.newbut)
		self.vbl.addLayout(self.hbl_buttons)

		self.on_new_but()

		QtCore.QObject.connect(self.sdefocus, QtCore.SIGNAL("valueChanged"), self.newCTF)
		QtCore.QObject.connect(self.sbfactor, QtCore.SIGNAL("valueChanged"), self.newCTF)
		QtCore.QObject.connect(self.sdfdiff, QtCore.SIGNAL("valueChanged"), self.newCTF)
		QtCore.QObject.connect(self.sdfang, QtCore.SIGNAL("valueChanged"), self.newCTF)
		QtCore.QObject.connect(self.sapix, QtCore.SIGNAL("valueChanged"), self.newCTF)
		QtCore.QObject.connect(self.sampcont, QtCore.SIGNAL("valueChanged"), self.newCTF)
		QtCore.QObject.connect(self.svoltage, QtCore.SIGNAL("valueChanged"), self.newCTF)
		QtCore.QObject.connect(self.scs, QtCore.SIGNAL("valueChanged"), self.newCTF)
		QtCore.QObject.connect(self.ssamples, QtCore.SIGNAL("valueChanged"), self.newCTF)
		QtCore.QObject.connect(self.setlist,QtCore.SIGNAL("currentRowChanged(int)"),self.newSet)
		QtCore.QObject.connect(self.setlist,QtCore.SIGNAL("keypress"),self.listkey)
		QtCore.QObject.connect(self.splotmode,QtCore.SIGNAL("currentIndexChanged(int)"),self.newPlotMode)

	   	QtCore.QObject.connect(self.newbut,QtCore.SIGNAL("clicked(bool)"),self.on_new_but)


		self.resize(720,380) # figured these values out by printing the width and height in resize event


		E2loadappwin("e2ctfsim","main",self)
		E2loadappwin("e2ctfsim","image",self.guiim.qt_parent)
#		E2loadappwin("e2ctf","realimage",self.guirealim.qt_parent)
		E2loadappwin("e2ctfsim","plot",self.guiplot.qt_parent)

		self.setWindowTitle("CTF")

	def listkey(self,event):

		if event.key()>=Qt.Key_0 and event.key()<=Qt.Key_9 :
			q=int(event.key())-Qt.Key_0
			self.squality.setValue(q)
		elif event.key() == Qt.Key_Left:
			self.sdefocus.setValue(self.sdefocus.getValue()-0.01)
		elif event.key() == Qt.Key_Right:
			self.sdefocus.setValue(self.sdefocus.getValue()+0.01)
		elif event.key()==Qt.Key_R :
			self.on_recall_params()


	def on_new_but(self):
		ctf=EMAN2Ctf()
		ctf.defocus=1.0
		ctf.voltage=self.df_voltage
		ctf.apix=self.df_apix
		ctf.cs=self.df_cs
		ctf.ac=self.df_ac
		ctf.samples=self.df_samples
		self.data.append((str(len(self.setlist)+1),ctf))
		self.curset=len(self.data)
		self.update_data()
		
	def show_guis(self):
		if self.guiim != None:
			self.app().show_specific(self.guiim)
		if self.guiplot != None:
			self.app().show_specific(self.guiplot)
		#if self.guirealim != None:
			#self.app().show_specific(self.guirealim)

		self.show()

	def closeEvent(self,event):
#		QtGui.QWidget.closeEvent(self,event)
#		self.app.app.closeAllWindows()
		E2saveappwin("e2ctf","main",self)

		if self.guiim != None:
			E2saveappwin("e2ctf","image",self.guiim.qt_parent)
			self.app().close_specific(self.guiim)
			self.guiim = None
		if self.guiplot != None:
			E2saveappwin("e2ctf","plot",self.guiplot.qt_parent)
			self.app().close_specific(self.guiplot)
		#if self.guirealim != None:
			#E2saveappwin("e2ctf","realimage",self.guirealim.qt_parent)
			#self.app().close_specific(self.guirealim)

		event.accept()
		self.app().close_specific(self)
		self.emit(QtCore.SIGNAL("module_closed")) # this signal is important when e2ctf is being used by a program running its own event loop

	def update_data(self):
		"""This will make sure the various widgets properly show the current data sets"""
		self.setlist.clear()
		for i,j in enumerate(self.data):
			self.setlist.addItem(j[0])
		self.setlist.setCurrentRow(self.curset)

	def update_plot(self):
		if self.guiplot == None: return # it's closed/not visible

		for d in xrange(len(self.data)):
			ctf=self.data[d][1]
			ds=1.0/(ctf.apix*2.0*ctf.samples)
			s=arange(0,ds*ctf.samples,ds)
			
			curve=array(ctf.compute_1d(len(s)*2,ds,Ctf.CtfType.CTF_AMP))
			if self.plotmode==1 or self.plotmode==2:
				curve=curve**2
			
			if self.plotmode==2 or self.plotmode==3:
				if d==0 : avg=curve[:]
				else:
					if len(curve)!=len(avg) :
						print "Number of samples must be fixed to compute an average ({})".format(d+1)
					else:
						avg+=curve
			
			self.guiplot.set_data((s,curve),self.data[d][0],d==0,True,color=d+1)

		if self.plotmode in (2,3) :
			self.guiplot.set_data((s,avg),"Sum",False,True,color=0)
			
		self.guiplot.setAxisParms("s (1/$\AA$)","CTF")

		ctf.compute_2d_complex(self.img,Ctf.CtfType.CTF_AMP,None)
		self.guiim.set_data(self.img)

	def newSet(self,val=0):
		"called when a new data set is selected from the list"
		self.curset=val

		self.sdefocus.setValue(self.data[val][1].defocus,True)
		self.sbfactor.setValue(self.data[val][1].bfactor,True)
		self.sapix.setValue(self.data[val][1].apix,True)
		self.sampcont.setValue(self.data[val][1].ampcont,True)
		self.svoltage.setValue(self.data[val][1].voltage,True)
		self.scs.setValue(self.data[val][1].cs,True)
		self.sdfdiff.setValue(self.data[val][1].dfdiff,True)
		self.sdfang.setValue(self.data[val][1].dfang,True)
		self.ssamples.setValue(self.data[val][1].samples,True)

		# make new image if necessary
		if self.img==None or self.img["ny"]!=self.data[val][1].samples :
			self.img=EMData(self.data[val][1].samples+2,self.data[val][1].samples)
			self.img.to_zero()
			self.img.set_complex(1)
		self.guiim.set_data(self.img)
#		self.imginfo.setText("%s particles     SNR = %s"%(ptcl,ssnr))

		#if self.guiim != None:
##			print self.data
			#self.guiim.set_data(self.data[val][4])
			#if self.guiiminit:
				#self.guiim.optimally_resize()
				#self.guiiminit = False
			#self.guiim.updateGL()
		#self.update_plot()

#		print "self.data[val]=",self.data[val][0].split('#')[-1]


		self.guiim.qt_parent.setWindowTitle("e2ctfsim - 2D FFT - "+self.data[val][0])
#		self.guirealim.qt_parent.setWindowTitle("e2ctf - "+self.data[val][0].split('#')[-1])
		self.guiplot.qt_parent.setWindowTitle("e2ctfsim - Plot ")

		#n=EMUtil.get_image_count(self.data[val][0])
		#if n>1:
			#self.ptcldata=EMData.read_images(self.data[val][0],range(0,min(20,n)))
			#im=sum(self.ptcldata)
			#im.mult(1.0/len(self.ptcldata))
			#self.ptcldata.insert(0,im)
			#self.guirealim.set_data(self.ptcldata)
		#else : self.guirealim.set_data([EMData()])
		self.update_plot()

	def newPlotMode(self,mode):
		self.plotmode=mode
		self.update_plot()

	def newCTF(self) :
#		print traceback.print_stack()
		self.data[self.curset][1].defocus=self.sdefocus.value
		self.data[self.curset][1].bfactor=self.sbfactor.value
		self.data[self.curset][1].dfdiff=self.sdfdiff.value
		self.data[self.curset][1].dfang=self.sdfang.value
		self.data[self.curset][1].apix=self.sapix.value
		self.data[self.curset][1].ampcont=self.sampcont.value
		self.data[self.curset][1].voltage=self.svoltage.value
		self.data[self.curset][1].cs=self.scs.value
		self.data[self.curset][1].samples=self.ssamples.value
		
		if self.img==None or self.img["ny"]!=self.ssamples.value :
			self.img=EMData(self.ssamples.value+2,self.ssamples.value)
			self.img.to_zero()
			self.img.set_complex(1)
			self.guiim.set_data(self.img)
		self.update_plot()

	def realimgkey(self,event):
		"""Keypress in the image display window"""

		if event.key()==Qt.Key_I:			# if user presses I in this window we invert the stack on disk
			fsp=self.data[self.curset][0]
			n=EMUtil.get_image_count(fsp)
			print "Inverting images in %s"%fsp
			for i in xrange(n):
				img=EMData(fsp,i)
				img.mult(-1.0)
				img.write_image(fsp,i)

			#self.ptcldata=EMData.read_images(fsp,range(0,20))
			#self.guirealim.set_data(self.ptcldata)


	def imgmousedown(self,event) :
		m=self.guiim.scr_to_img((event.x(),event.y()))
		#self.guiim.add_shape("cen",["rect",.9,.9,.4,x0,y0,x0+2,y0+2,1.0])

	def imgmousedrag(self,event) :
		m=self.guiim.scr_to_img((event.x(),event.y()))

		# box deletion when shift held down
		#if event.modifiers()&Qt.ShiftModifier:
			#for i,j in enumerate(self.boxes):

	def imgmouseup(self,event) :
		m=self.guiim.scr_to_img((event.x(),event.y()))

	def plotmousedown(self,event) :
		m=self.guiim.scr_to_img((event.x(),event.y()))

	def run(self):
		"""If you make your own application outside of this object, you are free to use
		your own local app.exec_(). This is a convenience for ctf-only programs."""
		self.app.exec_()

#		E2saveappwin("boxer","imagegeom",self.guiim)
#		try:
#			E2setappval("boxer","imcontrol",self.guiim.inspector.isVisible())
#			if self.guiim.inspector.isVisible() : E2saveappwin("boxer","imcontrolgeom",self.guiim.inspector)
#		except : E2setappval("boxer","imcontrol",False)

		return
class EMLightsInspector(QtGui.QWidget,EMLightsInspectorBase):
	def __init__(self,target) :
		QtGui.QWidget.__init__(self,None)
		EMLightsInspectorBase.__init__(self)
		self.target=weakref.ref(target)
		
		self.vbl = QtGui.QVBoxLayout(self)
		self.vbl.setMargin(0)
		self.vbl.setSpacing(6)
		self.vbl.setObjectName("vbl")
		
		self.hbl = QtGui.QHBoxLayout()
		self.hbl.setMargin(0)
		self.hbl.setSpacing(6)
		self.hbl.setObjectName("hbl")
		self.vbl.addLayout(self.hbl)

		self.vbl2 = QtGui.QVBoxLayout()
		self.vbl2.setMargin(0)
		self.vbl2.setSpacing(6)
		self.vbl2.setObjectName("vbl2")
		self.hbl.addLayout(self.vbl2)
		
		self.wiretog = QtGui.QPushButton("Wire")
		self.wiretog.setCheckable(1)
		self.vbl2.addWidget(self.wiretog)
		
		self.lighttog = QtGui.QPushButton("Light")
		self.lighttog.setCheckable(1)
		self.lighttog.setChecked(True)
		self.vbl2.addWidget(self.lighttog)
		
		self.tabwidget = QtGui.QTabWidget()
		self.maintab = None
		self.tabwidget.addTab(self.get_light_tab(), "Lights")
		self.tabwidget.addTab(self.get_main_tab(), "Transform")
		self.tabwidget.addTab(self.get_GL_tab(),"GL")
		self.vbl.addWidget(self.tabwidget)
		self.n3_showing = False
		self.quiet = False

		QtCore.QObject.connect(self.cbb, QtCore.SIGNAL("currentIndexChanged(QString)"), target.setColor)
		QtCore.QObject.connect(self.wiretog, QtCore.SIGNAL("toggled(bool)"), target.toggle_wire)
		QtCore.QObject.connect(self.lighttog, QtCore.SIGNAL("toggled(bool)"), target.toggle_light)
		QtCore.QObject.connect(self.glcontrast, QtCore.SIGNAL("valueChanged"), target.set_GL_contrast)
		QtCore.QObject.connect(self.glbrightness, QtCore.SIGNAL("valueChanged"), target.set_GL_brightness)

	def update_rotations(self,t3d):
		self.rotation_sliders.update_rotations(t3d)
	
	def set_scale(self,val):
		self.rotation_sliders.set_scale(val)
	
	def set_xy_trans(self, x, y):
		self.rotation_sliders.set_xy_trans(x,y)
	
	def set_xyz_trans(self,x,y,z):
		self.rotation_sliders.set_xyz_trans(x,y,z)
		#return self.advanced_tab
	
	def get_GL_tab(self):
		self.gltab = QtGui.QWidget()
		gltab = self.gltab
		
		gltab.vbl = QtGui.QVBoxLayout(self.gltab )
		gltab.vbl.setMargin(0)
		gltab.vbl.setSpacing(6)
		gltab.vbl.setObjectName("Main")
		
		self.hbl_color = QtGui.QHBoxLayout()
		self.hbl_color.setMargin(0)
		self.hbl_color.setSpacing(6)
		gltab.vbl.addLayout(self.hbl_color)

		self.color_label = QtGui.QLabel()
		self.color_label.setText('Material')
		self.hbl_color.addWidget(self.color_label)
		
		self.cbb = QtGui.QComboBox(gltab)
		self.hbl_color.addWidget(self.cbb)
		
		self.glcontrast = ValSlider(gltab,(1.0,5.0),"GLShd:")
		self.glcontrast.setObjectName("GLShade")
		self.glcontrast.setValue(1.0)
		gltab.vbl.addWidget(self.glcontrast)
		
		self.glbrightness = ValSlider(gltab,(-1.0,0.0),"GLBst:")
		self.glbrightness.setObjectName("GLBoost")
		self.glbrightness.setValue(0.1)
		self.glbrightness.setValue(0.0)
		gltab.vbl.addWidget(self.glbrightness)
	
		return gltab
	
	def get_main_tab(self):
		if ( self.maintab == None ):
			self.maintab = QtGui.QWidget()
			maintab = self.maintab
			maintab.vbl = QtGui.QVBoxLayout(self.maintab)
			maintab.vbl.setMargin(0)
			maintab.vbl.setSpacing(6)
			maintab.vbl.setObjectName("Main")
			
			self.rotation_sliders = EMTransformPanel(self.target(),self)
			self.rotation_sliders.addWidgets(maintab.vbl)
		
		return self.maintab
	
	def set_colors(self,colors,current_color):
		a = 0
		for i in colors:
			self.cbb.addItem(i)
			if ( i == current_color):
				self.cbb.setCurrentIndex(a)
			a += 1
Exemple #10
0
class EMLightsInspectorBase:
	'''
	Inherit from this if you want its functionality
	'''

	def __init__(self):
		self.gl_lights = get_gl_lights_vector()
		self.quiet = False


	def set_positional_light_pos(self,pos):
		self.quiet = True
		p = [self.light_x_pos,self.light_y_pos,self.light_z_pos]
		for i,w in enumerate(p):
			w.setValue(pos[i])
		
		self.quiet = False

	def set_positional_light_dir(self,direction):
		self.quiet = True
		p = [self.light_ps_xdir,self.light_ps_ydir,self.light_ps_zdir]
		for i,w in enumerate(p):
			w.setValue(direction[i])
		
		self.quiet = False

	def set_directional_light_dir(self,direction):
		
		self.quiet = True
		p = [self.light_x_dir,self.light_y_dir,self.light_z_dir]
		for i,w in enumerate(p):
			w.setValue(direction[i])
		
		self.quiet = False
	
	def update_light(self):
		if self.quiet: return
		
		l = self.get_current_light()
		if l == None: return
		
		attribs = ["r","g","b"]
		amb = [ getattr(self.light_ambient, a).getValue() for a in attribs]
		amb.append(1.0) # alpha
		dif = [ getattr(self.light_diffuse, a).getValue() for a in attribs]
		dif.append(1.0) # alpha
		spec = [ getattr(self.light_specular, a).getValue() for a in attribs]
		spec.append(1.0) # alpha
		
		glLightfv(l, GL_AMBIENT, amb)
		glLightfv(l, GL_DIFFUSE, dif)
		glLightfv(l, GL_SPECULAR, spec)
		
		pos = glGetLightfv(l,GL_POSITION)
		if pos[3] == 0:
			# directional light
			p = [self.light_x_dir,self.light_y_dir,self.light_z_dir]
			pos = [float(a.value()) for a in p]
			pos.append(0) # i.e. directional light
			glLightfv(l, GL_POSITION, pos)
		else:
			p = [self.light_x_pos,self.light_y_pos,self.light_z_pos]
			pos = [float(a.value()) for a in p]
			pos.append(1) # i.e.point light
			glLightfv(l, GL_POSITION, pos)
			
			d = [self.light_ps_xdir,self.light_ps_ydir,self.light_ps_zdir]
			dr = [float(a.value()) for a in d]
			glLightfv(l, GL_SPOT_DIRECTION, dr)
			
			glLightfv(l,GL_CONSTANT_ATTENUATION,self.const_atten.getValue())
			glLightfv(l,GL_LINEAR_ATTENUATION,self.linear_atten.getValue())
			glLightfv(l,GL_QUADRATIC_ATTENUATION,self.quad_atten.getValue())
			glLightfv(l,GL_SPOT_CUTOFF,self.spot_cutoff.getValue())
			glLightfv(l,GL_SPOT_EXPONENT,self.spot_exponent.getValue())

		
		self.target().updateGL()
		
	def get_light_tab(self):
		self.light_tab = QtGui.QWidget()
		light_tab = self.light_tab
		
		vbl = QtGui.QVBoxLayout(self.light_tab )
		vbl.setMargin(0)
		vbl.setSpacing(6)
		vbl.setObjectName("Lights")
		
		self.light_manip_check = QtGui.QCheckBox("Mouse moves lights")
		self.local_viewer_check = QtGui.QCheckBox("Local light model")
		self.local_viewer_check.setChecked(glGetInteger(GL_LIGHT_MODEL_LOCAL_VIEWER))
		show_lights = QtGui.QCheckBox("Show lights")
		show_lights.setChecked(self.target().display_lights)
		max_lights_label = QtGui.QLabel()
		max_lights_label.setText("Max lights : " + str(glGetInteger(GL_MAX_LIGHTS)))
		
		hdl_l = QtGui.QHBoxLayout()
		hdl_t = QtGui.QHBoxLayout()
		
		hdl_l.addWidget(self.light_manip_check)
		hdl_l.addWidget(self.local_viewer_check)
		hdl_t.addWidget(show_lights)
		hdl_t.addWidget(max_lights_label)
		
		vbl.addLayout(hdl_l)
		vbl.addLayout(hdl_t)
		
		self.light_tab_widget = QtGui.QTabWidget()
		
		
		self.light_tab_widget.addTab(self.get_directional_light_tab(), "Directional")
		self.light_tab_widget.addTab(self.get_pointsource_light_tab(), "Point source")
		
		vbl.addWidget(self.light_tab_widget)
		
		light_material_tab_widget = QtGui.QTabWidget()
		self.light_ambient = get_RGB_tab(self,"ambient")
		light_material_tab_widget.addTab(self.light_ambient, "Ambient")
		self.light_diffuse = get_RGB_tab(self,"diffuse")
		light_material_tab_widget.addTab(self.light_diffuse, "Diffuse")
		self.light_specular = get_RGB_tab(self,"specular")
		light_material_tab_widget.addTab(self.light_specular, "Specular")
		
		
		self.refresh_light_states()
		
		vbl.addWidget(light_material_tab_widget)

		QtCore.QObject.connect(self.light_ambient.r, QtCore.SIGNAL("valueChanged"), self.update_light)
		QtCore.QObject.connect(self.light_ambient.g, QtCore.SIGNAL("valueChanged"), self.update_light)
		QtCore.QObject.connect(self.light_ambient.b, QtCore.SIGNAL("valueChanged"), self.update_light)
		QtCore.QObject.connect(self.light_diffuse.r, QtCore.SIGNAL("valueChanged"), self.update_light)
		QtCore.QObject.connect(self.light_diffuse.g, QtCore.SIGNAL("valueChanged"), self.update_light)
		QtCore.QObject.connect(self.light_diffuse.b, QtCore.SIGNAL("valueChanged"), self.update_light)
		QtCore.QObject.connect(self.light_specular.r, QtCore.SIGNAL("valueChanged"), self.update_light)
		QtCore.QObject.connect(self.light_specular.g, QtCore.SIGNAL("valueChanged"), self.update_light)
		QtCore.QObject.connect(self.light_specular.b, QtCore.SIGNAL("valueChanged"), self.update_light)
		QtCore.QObject.connect(self.light_x_dir, QtCore.SIGNAL("valueChanged(double)"), self.update_light)
		QtCore.QObject.connect(self.light_y_dir, QtCore.SIGNAL("valueChanged(double)"), self.update_light)
		QtCore.QObject.connect(self.light_z_dir, QtCore.SIGNAL("valueChanged(double)"), self.update_light)
		QtCore.QObject.connect(self.light_manip_check, QtCore.SIGNAL("valueChanged(double)"), self.update_light)
		QtCore.QObject.connect(self.light_manip_check, QtCore.SIGNAL("stateChanged(int)"), self.target().light_manipulation_toggled)
		QtCore.QObject.connect(show_lights, QtCore.SIGNAL("stateChanged(int)"), self.target().show_lights)
		QtCore.QObject.connect(self.local_viewer_check, QtCore.SIGNAL("stateChanged(int)"), self.local_viewer_checked)
		#QtCore.QObject.connect(self.light_w_pos, QtCore.SIGNAL("valueChanged(int)"), self.update_light)
	 
		return light_tab
	
	def get_current_light(self):
		selected_items = self.light_list.selectedItems()
		if len(selected_items) == 0: selected_items = self.point_light_list.selectedItems()
			
		if len(selected_items) == 0:
			return None
		if len(selected_items) > 1:
			print "write a message box to say there is a function that assumes only one light is selected"
			return None
		
		item = selected_items[0]

		#print "selected lights is",item.text()
		idx = int(str(item.text())[-1]) # this shouldn't really ever fail
		return self.gl_lights[idx]
	
	
	def refresh_light_states(self):
		self.quiet = True
		l = self.get_current_light()
		if l == None: return
		
		self.target().set_current_light(l)
		amb = glGetLightfv(l,GL_AMBIENT)
		dif =  glGetLightfv(l,GL_DIFFUSE)
		spec = glGetLightfv(l,GL_SPECULAR)
		self.light_ambient.r.setValue(float(amb[0]))
		self.light_ambient.g.setValue(float(amb[1]))
		self.light_ambient.b.setValue(float(amb[2]))
		
		self.light_diffuse.r.setValue(float(dif[0]))
		self.light_diffuse.g.setValue(float(dif[1]))
		self.light_diffuse.b.setValue(float(dif[2]))
		
		self.light_specular.r.setValue(float(spec[0]))
		self.light_specular.g.setValue(float(spec[1]))
		self.light_specular.b.setValue(float(spec[2]))
		
		pos = glGetLightfv(l,GL_POSITION)
		if pos[3] == 0:
			self.light_x_dir.setValue(float(pos[0]))
			self.light_y_dir.setValue(float(pos[1]))
			self.light_z_dir.setValue(float(pos[2]))
		else:
			# it's a point source
			
			# have to figure out the model coordinates, do this
			# by setting the light position to zero and then 
			# getting the light position. Calculate the difference...
			test_pos = [0,0,0,1]
			glLightfv(l,GL_POSITION,test_pos)
			test_pos_out = glGetLightfv(l,GL_POSITION)
			# reset to the correction position
			pos = [ (pos[i] - test_pos_out[i]) for i in range(3)]
			pos.append(1)
			glLightfv(l,GL_POSITION,pos)
			
			self.light_x_pos.setValue(float(pos[0]))
			self.light_y_pos.setValue(float(pos[1]))
			self.light_z_pos.setValue(float(pos[2]))
			
			dr = glGetLightfv(l,GL_SPOT_DIRECTION)
			self.light_ps_xdir.setValue(float(dr[0]))
			self.light_ps_ydir.setValue(float(dr[1]))
			self.light_ps_zdir.setValue(float(dr[2]))
			
			self.const_atten.setValue(float(glGetLightfv(l,GL_CONSTANT_ATTENUATION)))
			self.linear_atten.setValue(float(glGetLightfv(l,GL_LINEAR_ATTENUATION)))
			self.quad_atten.setValue(float(glGetLightfv(l,GL_QUADRATIC_ATTENUATION)))
			
			self.spot_cutoff.setValue(float(glGetLightfv(l,GL_SPOT_CUTOFF)))
			self.spot_exponent.setValue(float(glGetLightfv(l,GL_SPOT_EXPONENT)))
			
			
		self.target().updateGL()
		self.quiet = False
	def local_viewer_checked(self,i):
		glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER,i)
		self.target().updateGL()
	
	
	def del_directional_light(self):
		glDisable(self.get_current_light())
		self.redo_directional_light_list()
		
		self.refresh_light_states()
		self.target().updateGL()
		
	def del_pointsource_light(self):
		glDisable(self.get_current_light())
		self.redo_pointsource_light_list()
		self.refresh_light_states()
		self.target().updateGL()
		
	def redo_directional_light_list(self):
		self.light_list.clear()
		for i,l in enumerate(self.gl_lights):
			if glIsEnabled(l):
				pos = glGetLightfv(l,GL_POSITION)
				if pos[3] == 0:
					a = QtGui.QListWidgetItem("Light "+str(i),self.light_list)
					if len(self.light_list.selectedItems()) == 0:
						a.setSelected(True)
						
	def redo_pointsource_light_list(self):
		self.point_light_list.clear()
		for i,l in enumerate(self.gl_lights):
			if glIsEnabled(l):
				pos = glGetLightfv(l,GL_POSITION)
				if pos[3] == 1:
					a = QtGui.QListWidgetItem("Light "+str(i),self.light_list)
					if len(self.light_list.selectedItems()) == 0 and len(self.point_light_list.selectedItems()) == 0:
						a.setSelected(True)
		
	
	def new_directional_light(self):
		self.new_light()
	
	def new_pointsource_light(self):
		self.new_light(point_source=True)
		
	def new_light(self,point_source=False):
		for i,l in enumerate(self.gl_lights):
			if not glIsEnabled(l):
				glEnable(l)
				pos = glGetLightfv(l,GL_POSITION)
				
				if point_source:
					# make sure that it's a point source
					if pos[3] != 1:
						pos[3] = 1
						glLightfv(l,GL_POSITION,pos)
					
					spot_cutoff = glGetLightfv(l,GL_SPOT_CUTOFF)
					if spot_cutoff > 90: glLightfv(l,GL_SPOT_CUTOFF,90)
				else:
					# make sure that it's directionaly
					if pos[3] != 0:
						pos[3] = 0
						glLightfv(l,GL_POSITION,pos)
						
					
				new_label = "Light "+str(i)
				
				if not point_source: 
					a = QtGui.QListWidgetItem(new_label,self.light_list)
					for item in self.point_light_list.selectedItems(): item.setSelected(False)
						
				else:
					a = QtGui.QListWidgetItem(new_label,self.point_light_list)
					for item in self.light_list.selectedItems(): item.setSelected(False)
					
				a.setSelected(True)
				self.refresh_light_states()
				break
		else:
			print "write a message box to say that there are no available lights!"
	
	def new_point_source_light(self):
		for i,l in enumerate(self.gl_lights):
			if not glIsEnabled(l):
				glEnable(l)
				new_label = "Light "+str(i)
				
				a = QtGui.QListWidgetItem(new_label,self.light_list)
				a.setSelected(True)
				
				self.refresh_light_states()
				break
		else:
			print "write a message box to say that there are no available lights!"
			
		#print "new directional",glGetInteger(GL_MAX_LIGHTS)
		#for i in range(glGetInteger(GL_MAX_LIGHTS)):
			
			#if glIsEnabled(
	
	def light_list_clicked(self,item):
		for item in self.point_light_list.selectedItems(): item.setSelected(False)
		self.refresh_light_states()
		
	def point_light_list_clicked(self,item):
		for item in self.light_list.selectedItems(): item.setSelected(False)
		self.refresh_light_states()
		
	
	def get_directional_light_tab(self):
		
		self.directional_light_widget = QtGui.QWidget()
		
		vbl = QtGui.QVBoxLayout(self.directional_light_widget)
		vbl.setMargin(0)
		vbl.setSpacing(6)
		vbl.setObjectName("Lights")
		
		hbl = QtGui.QHBoxLayout()
		hbl.setMargin(0)
		hbl.setSpacing(6)
		hbl.setObjectName("hbl")
		vbl.addLayout(hbl)

		self.light_list = QtGui.QListWidget(None)
		self.light_list.setMouseTracking(True)
		self.redo_directional_light_list()

		hbl.addWidget(self.light_list)

		vbl2 = QtGui.QVBoxLayout()
		vbl2.setMargin(0)
		vbl2.setSpacing(6)
		vbl2.setObjectName("vbl2")
		hbl.addLayout(vbl2)
		
		new_light = QtGui.QPushButton("New")
		vbl2.addWidget(new_light)
		#copy_light = QtGui.QPushButton("Copy")
		#vbl2.addWidget(copy_light)
		del_light = QtGui.QPushButton("Delete")
		vbl2.addWidget(del_light)
		
		
		x_label = QtGui.QLabel()
		x_label.setText('x')
		
		self.light_x_dir = QtGui.QDoubleSpinBox(self)
		self.light_x_dir.setMinimum(-100000)
		self.light_x_dir.setMaximum(100000)
		self.light_x_dir.setValue(0.0)
	
		y_label = QtGui.QLabel()
		y_label.setText('y')
		
		self.light_y_dir = QtGui.QDoubleSpinBox(self)
		self.light_y_dir.setMinimum(-100000)
		self.light_y_dir.setMaximum(100000)
		self.light_y_dir.setValue(0.0)
		
		z_label = QtGui.QLabel()
		z_label.setText('z')
		
		self.light_z_dir = QtGui.QDoubleSpinBox(self)
		self.light_z_dir.setMinimum(-100000)
		self.light_z_dir.setMaximum(100000)
		self.light_z_dir.setValue(0.0)
		
		
		hbl_trans = QtGui.QHBoxLayout()
		hbl_trans.setMargin(0)
		hbl_trans.setSpacing(6)
		hbl_trans.setObjectName("Trans")
		hbl_trans.addWidget(x_label)
		hbl_trans.addWidget(self.light_x_dir)
		hbl_trans.addWidget(y_label)
		hbl_trans.addWidget(self.light_y_dir)
		hbl_trans.addWidget(z_label)
		hbl_trans.addWidget(self.light_z_dir)
		
		vbl.addLayout(hbl_trans)
		
		QtCore.QObject.connect(new_light, QtCore.SIGNAL("clicked()"), self.new_directional_light)
		QtCore.QObject.connect(del_light, QtCore.SIGNAL("clicked()"), self.del_directional_light)
		QtCore.QObject.connect(self.light_list, QtCore.SIGNAL("itemPressed(QListWidgetItem*)"), self.light_list_clicked)
		
		return self.directional_light_widget
	
	
	def get_pointsource_light_tab(self):
		
		self.pointsource_light_widget = QtGui.QWidget()
		
		vbl = QtGui.QVBoxLayout(self.pointsource_light_widget)
		vbl.setMargin(0)
		vbl.setSpacing(6)
		vbl.setObjectName("Lights")
		
		hbl = QtGui.QHBoxLayout()
		hbl.setMargin(0)
		hbl.setSpacing(6)
		hbl.setObjectName("hbl")
		vbl.addLayout(hbl)

		self.point_light_list = QtGui.QListWidget(None)
		self.point_light_list.setMouseTracking(True)
		
		self.redo_pointsource_light_list()
		#a = QtGui.QListWidgetItem(str("Light 0"),self.light_list)
		#a.setSelected(True)
		hbl.addWidget(self.point_light_list)

		vbl2 = QtGui.QVBoxLayout()
		vbl2.setMargin(0)
		vbl2.setSpacing(6)
		vbl2.setObjectName("vbl2")
		hbl.addLayout(vbl2)
		
		new_light = QtGui.QPushButton("New")
		vbl2.addWidget(new_light)
		#copy_light = QtGui.QPushButton("Copy")
		#vbl2.addWidget(copy_light)
		del_light = QtGui.QPushButton("Delete")
		vbl2.addWidget(del_light)
		
		
		pos_label = QtGui.QLabel()
		pos_label.setText('Pos: ')
		
		x_label = QtGui.QLabel()
		x_label.setText('x')
		
		self.light_x_pos = QtGui.QDoubleSpinBox(self)
		self.light_x_pos.setMinimum(-100000)
		self.light_x_pos.setMaximum(100000)
		self.light_x_pos.setValue(0.0)
	
		y_label = QtGui.QLabel()
		y_label.setText('y')
		
		self.light_y_pos = QtGui.QDoubleSpinBox(self)
		self.light_y_pos.setMinimum(-100000)
		self.light_y_pos.setMaximum(100000)
		self.light_y_pos.setValue(0.0)
		
		z_label = QtGui.QLabel()
		z_label.setText('z')
		
		self.light_z_pos = QtGui.QDoubleSpinBox(self)
		self.light_z_pos.setMinimum(-100000)
		self.light_z_pos.setMaximum(100000)
		self.light_z_pos.setValue(0.0)
		
		
		hbl_trans = QtGui.QHBoxLayout()
		hbl_trans.setMargin(0)
		hbl_trans.setSpacing(6)
		hbl_trans.setObjectName("Trans")
		hbl_trans.addWidget(pos_label)
		hbl_trans.addWidget(x_label)
		hbl_trans.addWidget(self.light_x_pos)
		hbl_trans.addWidget(y_label)
		hbl_trans.addWidget(self.light_y_pos)
		hbl_trans.addWidget(z_label)
		hbl_trans.addWidget(self.light_z_pos)
		
		vbl.addLayout(hbl_trans)
	
		
		self.const_atten = ValSlider(self.pointsource_light_widget,(0.0,5.0),"Const atten.:")
		self.const_atten.setValue(1.0)
		vbl.addWidget(self.const_atten)
		
		self.linear_atten = ValSlider(self.pointsource_light_widget,(0.0,0.5),"Linear atten.:")
		self.linear_atten.setValue(0.5)# why o why?
		self.linear_atten.setValue(0.0)
		vbl.addWidget(self.linear_atten)
		
		self.quad_atten = ValSlider(self.pointsource_light_widget,(0.0,0.05),"Quad. atten.:")
		self.quad_atten.setValue(0.05) # why o why?
		self.quad_atten.setValue(0.0)
		vbl.addWidget(self.quad_atten)
		
		
		dir_label = QtGui.QLabel()
		dir_label.setText('Dir: ')
		
		self.light_ps_xdir = QtGui.QDoubleSpinBox(self)
		self.light_ps_xdir.setMinimum(-100000)
		self.light_ps_xdir.setMaximum(100000)
		self.light_ps_xdir.setValue(0.0)
	
		y_label = QtGui.QLabel()
		y_label.setText('y')
		
		self.light_ps_ydir = QtGui.QDoubleSpinBox(self)
		self.light_ps_ydir.setMinimum(-100000)
		self.light_ps_ydir.setMaximum(100000)
		self.light_ps_ydir.setValue(0.0)
		
		z_label = QtGui.QLabel()
		z_label.setText('z')
		
		self.light_ps_zdir = QtGui.QDoubleSpinBox(self)
		self.light_ps_zdir.setMinimum(-100000)
		self.light_ps_zdir.setMaximum(100000)
		self.light_ps_zdir.setValue(0.0)
		
		hbl_trans2 = QtGui.QHBoxLayout()
		hbl_trans2.setMargin(0)
		hbl_trans2.setSpacing(6)
		hbl_trans2.setObjectName("Trans")
		hbl_trans2.addWidget(dir_label)
		hbl_trans2.addWidget(x_label)
		hbl_trans2.addWidget(self.light_ps_xdir)
		hbl_trans2.addWidget(y_label)
		hbl_trans2.addWidget(self.light_ps_ydir)
		hbl_trans2.addWidget(z_label)
		hbl_trans2.addWidget(self.light_ps_zdir)
		
		vbl.addLayout(hbl_trans2)
		
			
		self.spot_cutoff = ValSlider(self.pointsource_light_widget,(0.0,90.0),"Spot cutoff:")
		self.spot_cutoff.setValue(90)
		vbl.addWidget(self.spot_cutoff)
		
		self.spot_exponent = ValSlider(self.pointsource_light_widget,(0,10.0),"Spot exponent:")
		self.spot_exponent.setValue(1.0) # why o why?
		self.spot_exponent.setValue(0.0)
		vbl.addWidget(self.spot_exponent)
		
		
		QtCore.QObject.connect(new_light, QtCore.SIGNAL("clicked()"), self.new_pointsource_light)
		QtCore.QObject.connect(self.point_light_list, QtCore.SIGNAL("itemPressed(QListWidgetItem*)"), self.point_light_list_clicked)
		QtCore.QObject.connect(self.light_x_pos, QtCore.SIGNAL("valueChanged(double)"), self.update_light)
		QtCore.QObject.connect(self.light_y_pos, QtCore.SIGNAL("valueChanged(double)"), self.update_light)
		QtCore.QObject.connect(self.light_z_pos, QtCore.SIGNAL("valueChanged(double)"), self.update_light)
		QtCore.QObject.connect(self.light_ps_xdir, QtCore.SIGNAL("valueChanged(double)"), self.update_light)
		QtCore.QObject.connect(self.light_ps_ydir, QtCore.SIGNAL("valueChanged(double)"), self.update_light)
		QtCore.QObject.connect(self.light_ps_zdir, QtCore.SIGNAL("valueChanged(double)"), self.update_light)
		QtCore.QObject.connect(self.spot_cutoff, QtCore.SIGNAL("valueChanged"), self.update_light)
		QtCore.QObject.connect(self.spot_exponent, QtCore.SIGNAL("valueChanged"), self.update_light)
		QtCore.QObject.connect(self.const_atten, QtCore.SIGNAL("valueChanged"), self.update_light)
		QtCore.QObject.connect(self.linear_atten, QtCore.SIGNAL("valueChanged"), self.update_light)
		QtCore.QObject.connect(self.quad_atten, QtCore.SIGNAL("valueChanged"), self.update_light)

		QtCore.QObject.connect(del_light, QtCore.SIGNAL("clicked()"), self.del_pointsource_light)
		
		return self.pointsource_light_widget
Exemple #11
0
class EMFontInspector(QtGui.QWidget, EMLightsInspectorBase):
    def __init__(self, target):
        QtGui.QWidget.__init__(self, None)
        EMLightsInspectorBase.__init__(self)
        self.target = weakref.ref(target)
        self.transform_panel = EMTransformPanel(target, self)
        self.transform_vbl = None  # This will eventually be a vertical box layout for the transform panel
        self.init_fonts()

        self.vbl = QtGui.QVBoxLayout(self)
        self.vbl.setMargin(0)
        self.vbl.setSpacing(6)
        self.vbl.setObjectName("vbl")

        self.hbl = QtGui.QHBoxLayout()
        self.hbl.setMargin(0)
        self.hbl.setSpacing(6)
        self.hbl.setObjectName("hbl")
        self.vbl.addLayout(self.hbl)

        self.vbl2 = QtGui.QVBoxLayout()
        self.vbl2.setMargin(0)
        self.vbl2.setSpacing(6)
        self.vbl2.setObjectName("vbl2")
        self.hbl.addLayout(self.vbl2)

        self.wiretog = QtGui.QPushButton("Wire")
        self.wiretog.setCheckable(1)
        self.vbl2.addWidget(self.wiretog)

        self.lighttog = QtGui.QPushButton("Light")
        self.lighttog.setCheckable(1)
        self.vbl2.addWidget(self.lighttog)

        self.tabwidget2 = QtGui.QTabWidget()
        self.maintab = None
        self.tabwidget2.addTab(self.get_main_tab(), "Main")
        #self.tabwidget2.addTab(self.get_GL_tab(),"GL")
        self.tabwidget2.addTab(self.get_format_tab(), "Formatting")
        self.tabwidget2.addTab(self.get_light_tab(), "Lights")
        self.vbl.addWidget(self.tabwidget2)
        self.n3_showing = False

        QtCore.QObject.connect(self.cbb,
                               QtCore.SIGNAL("currentIndexChanged(QString)"),
                               target.setColor)
        QtCore.QObject.connect(self.wiretog, QtCore.SIGNAL("toggled(bool)"),
                               target.toggle_wire)
        QtCore.QObject.connect(self.lighttog, QtCore.SIGNAL("toggled(bool)"),
                               target.toggle_light)
        QtCore.QObject.connect(self.glcontrast, QtCore.SIGNAL("valueChanged"),
                               target.set_GL_contrast)
        QtCore.QObject.connect(self.glbrightness,
                               QtCore.SIGNAL("valueChanged"),
                               target.set_GL_brightness)
        QtCore.QObject.connect(
            self.combo, QtCore.SIGNAL("currentIndexChanged (const QString&)"),
            self.on_combo_change)
        QtCore.QObject.connect(self.text,
                               QtCore.SIGNAL("textChanged(const QString&)"),
                               self.on_text_change)
        QtCore.QObject.connect(self.lspacing, QtCore.SIGNAL("valueChanged"),
                               self.set_GL_lspacing)
        QtCore.QObject.connect(self.length, QtCore.SIGNAL("valueChanged"),
                               self.set_GL_length)
        QtCore.QObject.connect(self.tsize, QtCore.SIGNAL("valueChanged(int)"),
                               self.set_GL_tsize)
        QtCore.QObject.connect(
            self.Dfont, QtCore.SIGNAL("currentIndexChanged (const QString&)"),
            self.on_Dfont_change)
        QtCore.QObject.connect(self.bgR, QtCore.SIGNAL("valueChanged"),
                               self.set_GL_bgR)
        QtCore.QObject.connect(self.bgG, QtCore.SIGNAL("valueChanged"),
                               self.set_GL_bgG)
        QtCore.QObject.connect(self.bgB, QtCore.SIGNAL("valueChanged"),
                               self.set_GL_bgB)
        QtCore.QObject.connect(self.bg_a, QtCore.SIGNAL("valueChanged"),
                               self.set_GL_bg_a)

    def get_transform_layout(self):
        return self.transform_vbl

    def set_GL_bgR(self, bgR):
        self.target().set_bg_r(bgR)
        self.target().updateGL()

    def set_GL_bgG(self, bgG):
        self.target().set_bg_g(bgG)
        self.target().updateGL()

    def set_GL_bgB(self, bgB):
        self.target().set_bg_b(bgB)
        self.target().updateGL()

    def set_GL_bg_a(self, bg_a):
        self.target().set_bg_a(bg_a)
        self.target().updateGL()

    def init_fonts(self):
        self.d = {}
        self.l = []
        platform = get_platform()
        if platform == "Linux":
            f_dir = "/usr/share/fonts/"
        elif platform == "Windows" or platform == "win32":
            f_dir = ":/windows/fonts/"
        elif platform in ["Apple", "Darwin"]:
            f_dir = "/Library/Fonts/"
        else:
            raise RuntimeError("Platform %s is not supported" % platform)

        for root, dirs, files in os.walk(f_dir):
            for name in files:
                if name.find("ttf") != -1:
                    filename = os.path.join(root, name)
                    self.d[name] = filename
                    self.l.extend([name])
        return self.l, self.d

    def on_Dfont_change(self, Dfont):
        self.target().font_renderer.set_font_file_name(self.d[str(Dfont)])
        self.target().updateGL()

    def set_GL_lspacing(self, lspacing):
        self.target().set_lspacing(lspacing)
        #THE FOLLOWING IF STATEMENT DOES IS NOT EFFECTIVE
        if len(self.target().render_string.split("\n")) != 1:
            self.lspacing.setEnabled(True)
        else:
            self.lspacing.setEnabled(False)
        self.target().updateGL()

    def set_GL_length(self, length):
        self.target().font_renderer.set_depth(int(length))
        self.target().updateGL()

    def set_GL_tsize(self, tsize):
        self.target().font_renderer.set_face_size(tsize)
        self.target().updateGL()

    def on_text_change(self, text):
        try:
            evalt = str(eval(str(text)))
            self.target().set_render_string(evalt)
        except:
            self.target().set_render_string(str(text))

        if len(self.target().render_string.split("\n")) != 1:
            self.lspacing.setEnabled(True)
        else:
            self.lspacing.setEnabled(False)
        self.target().updateGL()

    def on_combo_change(self, mode):
        d = {}
        d["Extrude"] = FTGLFontMode.EXTRUDE
        d["Pixmap"] = FTGLFontMode.PIXMAP
        d["Bitmap"] = FTGLFontMode.BITMAP
        d["Polygon"] = FTGLFontMode.POLYGON
        d["Outline"] = FTGLFontMode.OUTLINE
        d["Texture"] = FTGLFontMode.TEXTURE
        self.target().font_renderer.set_font_mode(d[str(mode)])
        if mode == "Extrude":
            self.length.setEnabled(True)
        else:
            self.length.setEnabled(False)
        self.target().updateGL()

    def update_rotations(self, t3d):
        self.transform_panel.update_rotations(t3d)

    def set_scale(self, val):
        self.transform_panel.set_scale(val)

    def set_xy_trans(self, x, y):
        self.transform_panel.set_xy_trans(x, y)

    def set_xyz_trans(self, x, y, z):
        self.transform_panel.set_xyz_trans(x, y, z)

    def get_GL_tab(self):
        self.gltab = QtGui.QWidget()
        gltab = self.gltab

        gltab.vbl = QtGui.QVBoxLayout(self.gltab)
        gltab.vbl.setMargin(0)
        gltab.vbl.setSpacing(6)
        gltab.vbl.setObjectName("Main")

        self.glcontrast = ValSlider(gltab, (1.0, 5.0), "GLShd:")
        self.glcontrast.setObjectName("GLShade")
        self.glcontrast.setValue(1.0)
        gltab.vbl.addWidget(self.glcontrast)

        self.glbrightness = ValSlider(gltab, (-1.0, 0.0), "GLBst:")
        self.glbrightness.setObjectName("GLBoost")
        self.glbrightness.setValue(0.1)
        self.glbrightness.setValue(0.0)
        gltab.vbl.addWidget(self.glbrightness)

        return gltab

    def get_main_tab(self):
        if (self.maintab == None):
            self.maintab = QtGui.QWidget()
            maintab = self.maintab
            maintab.vbl = QtGui.QVBoxLayout(self.maintab)
            maintab.vbl.setMargin(0)
            maintab.vbl.setSpacing(6)
            maintab.vbl.setObjectName("Main")

            self.transform_vbl = QtGui.QVBoxLayout()
            self.transform_panel.addWidgets(self.transform_vbl)
            maintab.vbl.addLayout(self.transform_vbl)
            self.glwidget = QtGui.QTabWidget()
            self.glwidget.addTab(self.get_GL_tab(), "GL")
            maintab.vbl.addWidget(self.glwidget)

        return maintab

    def get_format_tab(self):
        self.formattab = QtGui.QWidget()
        formattab = self.formattab
        formattab.vbl = QtGui.QVBoxLayout(self.formattab)
        formattab.vbl.setMargin(0)
        formattab.vbl.setSpacing(6)
        formattab.vbl.setObjectName("Format")

        self.hbl1 = QtGui.QHBoxLayout()
        self.text = QtGui.QLineEdit()
        self.text.setText("hello world")
        text_label = QtGui.QLabel("Enter Text:", self)
        text_label.setToolTip(
            "Enters quotes to evaluate new line e.g. \"hello\\nworld\". Evaluates numerical expressions e.g. 9*9 (with out quotes)"
        )
        self.hbl1.addWidget(text_label)
        self.hbl1.addWidget(self.text)
        formattab.vbl.addLayout(self.hbl1)

        self.hbl1 = QtGui.QHBoxLayout()
        self.Dfont = QtGui.QComboBox()
        for k in self.l:
            self.Dfont.addItem(k)
        self.hbl1.addWidget(QtGui.QLabel("Fonts:", self))
        self.hbl1.addWidget(self.Dfont)
        formattab.vbl.addLayout(self.hbl1)

        self.hbl1 = QtGui.QHBoxLayout()
        self.tsize = QtGui.QSpinBox()
        self.tsize.setRange(0, 500)
        self.tsize.setValue(32)
        self.hbl1.addWidget(QtGui.QLabel("Size:", self), Qt.AlignLeft)
        self.hbl1.addWidget(self.tsize, Qt.AlignRight)
        self.combo = QtGui.QComboBox()
        self.items = [
            "Extrude", "Pixmap", "Bitmap", "Polygon", "Outline", "Texture"
        ]
        for k in self.items:
            self.combo.addItem(k)
        self.hbl1.addWidget(QtGui.QLabel("Style:", self), Qt.AlignLeft)
        self.hbl1.addWidget(self.combo, Qt.AlignRight)
        formattab.vbl.addLayout(self.hbl1)

        self.hbl1 = QtGui.QHBoxLayout()
        self.lspacing = ValSlider(self, (-100.0, 100.0), "Line Spacing:")
        self.lspacing.setObjectName("Length")
        self.lspacing.setValue(75.0)
        self.lspacing.setEnabled(False)
        self.hbl1.addWidget(self.lspacing)
        formattab.vbl.addLayout(self.hbl1)

        self.hbl1 = QtGui.QHBoxLayout()
        self.length = ValSlider(self, (0.0, 500.0), "Length:")
        self.length.setObjectName("Length")
        self.length.setValue(75.0)
        self.hbl1.addWidget(self.length)
        formattab.vbl.addLayout(self.hbl1)

        self.hbl1 = QtGui.QHBoxLayout()
        self.cbb = QtGui.QComboBox()
        self.hbl1.addWidget(QtGui.QLabel("Material:", self))
        self.hbl1.addWidget(self.cbb)
        formattab.vbl.addLayout(self.hbl1)

        self.hbl1 = QtGui.QHBoxLayout()
        self.bgtabwidget = QtGui.QTabWidget()
        self.maintab = None
        self.bgtabwidget.addTab(self.get_bgRGB_tab(), "BG RGB")
        self.hbl1.addWidget(self.bgtabwidget)
        self.n3_showing = False
        formattab.vbl.addLayout(self.hbl1)

        return formattab

    def get_bgRGB_tab(self):
        self.bgRGBtab = QtGui.QWidget()
        bgRGBtab = self.bgRGBtab
        bgRGBtab.vbl2 = QtGui.QVBoxLayout(self.bgRGBtab)
        bgRGBtab.vbl2.setMargin(0)
        bgRGBtab.vbl2.setSpacing(6)
        bgRGBtab.vbl2.setObjectName("BG RGB")

        self.hbl2 = QtGui.QHBoxLayout()
        self.bgR = ValSlider(self, (0, 1), "R:")
        self.bgR.setObjectName("R")
        self.bgR.setValue(0.5)
        self.hbl2.addWidget(self.bgR)
        bgRGBtab.vbl2.addLayout(self.hbl2)

        self.hbl2 = QtGui.QHBoxLayout()
        self.bgG = ValSlider(self, (0, 1), "G:")
        self.bgG.setObjectName("G")
        self.bgG.setValue(0.5)
        self.hbl2.addWidget(self.bgG)
        bgRGBtab.vbl2.addLayout(self.hbl2)

        self.hbl2 = QtGui.QHBoxLayout()
        self.bgB = ValSlider(self, (0, 1), "B:")
        self.bgB.setObjectName("B")
        self.bgB.setValue(0.5)
        self.hbl2.addWidget(self.bgB)
        bgRGBtab.vbl2.addLayout(self.hbl2)

        self.hbl2 = QtGui.QHBoxLayout()
        self.bg_a = ValSlider(self, (0, 1), "Alpha:")
        self.bg_a.setObjectName("Alpha")
        self.bg_a.setValue(1.0)
        self.hbl2.addWidget(self.bg_a)
        bgRGBtab.vbl2.addLayout(self.hbl2)

        return bgRGBtab

#	def slider_rotate(self):
#		self.target.load_rotation(self.get_current_rotation())

#	def set_xy_trans(self, x, y):
#		self.x_trans.setValue(x)
#		self.y_trans.setValue(y)

#	def set_translate_scale(self, xscale,yscale,zscale):
#		self.x_trans.setSingleStep(xscale)
#		self.y_trans.setSingleStep(yscale)
#		self.z_trans.setSingleStep(zscale)

#	def update_rotations(self,t3d):
#		rot = t3d.get_rotation(self.src_map[str(self.src.itemText(self.src.currentIndex()))])
#
#		convention = self.src.currentText()
#		if ( self.src_map[str(convention)] == EULER_SPIN ):
#			self.n3.setValue(rot[self.n3.getLabel()],True)
#
#		self.az.setValue(rot[self.az.getLabel()],True)
#		self.alt.setValue(rot[self.alt.getLabel()],True)
#		self.phi.setValue(rot[self.phi.getLabel()],True)

#	def slider_rotate(self):
#		self.target.load_rotation(self.get_current_rotation())

#	def get_current_rotation(self):
#		convention = self.src.currentText()
#		rot = {}
#		if ( self.current_src == EULER_SPIN ):
#			rot[self.az.getLabel()] = self.az.getValue()
#
#			n1 = self.alt.getValue()
#			n2 = self.phi.getValue()
#			n3 = self.n3.getValue()
#
#			norm = sqrt(n1*n1 + n2*n2 + n3*n3)
#
#			n1 /= norm
#			n2 /= norm
#			n3 /= norm
#
#			rot[self.alt.getLabel()] = n1
#			rot[self.phi.getLabel()] = n2
#			rot[self.n3.getLabel()] = n3
#
#		else:
#			rot[self.az.getLabel()] = self.az.getValue()
#			rot[self.alt.getLabel()] = self.alt.getValue()
#			rot[self.phi.getLabel()] = self.phi.getValue()
#
#		return Transform(self.current_src, rot)

    def setColors(self, colors, current_color):
        a = 0
        for i in colors:
            self.cbb.addItem(i)
            if (i == current_color):
                self.cbb.setCurrentIndex(a)
            a += 1
class EMInspectorControlShape(EMItem3DInspector):
	"""
	Class to make EMItem GUI SHAPE Inspector
	"""
	def __init__(self, name, item3d):
		EMItem3DInspector.__init__(self, name, item3d)
		
	def updateItemControls(self):
		""" Updates this item inspector. Function is called by the item it observes"""
		super(EMInspectorControlShape, self).updateItemControls()
		self.ambcolorbox.setColor(QtGui.QColor(255*self.item3d().ambient[0],255*self.item3d().ambient[1],255*self.item3d().ambient[2]))
		self.diffusecolorbox.setColor(QtGui.QColor(255*self.item3d().diffuse[0],255*self.item3d().diffuse[1],255*self.item3d().diffuse[2]))
		self.specularcolorbox.setColor(QtGui.QColor(255*self.item3d().specular[0],255*self.item3d().specular[1],255*self.item3d().specular[2]))
	
	def addTabs(self):
		""" Add a tab for each 'column' """
		tabwidget = QtGui.QWidget()
		gridbox = QtGui.QGridLayout()
		
		EMInspectorControlShape.addControls(self, gridbox)
		
		tabwidget.setLayout(gridbox)
		self.addTab(tabwidget, "basic")
			
	def addControls(self, gridbox):
		""" Construct all the widgets in this Item Inspector """
		super(EMInspectorControlShape, self).addControls(gridbox)
		colorframe = QtGui.QFrame()
		colorframe.setFrameShape(QtGui.QFrame.StyledPanel)
		colorvbox = QtGui.QVBoxLayout()
		lfont = QtGui.QFont()
		lfont.setBold(True)
		colorlabel = QtGui.QLabel("Color",colorframe)
		colorlabel.setFont(lfont)
		colorlabel.setAlignment(QtCore.Qt.AlignCenter)

		# These boxes are a pain maybe I should use a Grid?
		cdialoghbox = QtGui.QHBoxLayout()
		cabox = QtGui.QHBoxLayout()
		self.ambcolorbox = EMQTColorWidget(parent=colorframe)
		cabox.addWidget(self.ambcolorbox)
		cabox.setAlignment(QtCore.Qt.AlignCenter)
		cdbox = QtGui.QHBoxLayout()
		self.diffusecolorbox = EMQTColorWidget(parent=colorframe)
		cdbox.addWidget(self.diffusecolorbox)
		cdbox.setAlignment(QtCore.Qt.AlignCenter)
		csbox = QtGui.QHBoxLayout()
		self.specularcolorbox = EMQTColorWidget(parent=colorframe)
		csbox.addWidget(self.specularcolorbox)
		csbox.setAlignment(QtCore.Qt.AlignCenter)
		cdialoghbox.addLayout(cabox)
		cdialoghbox.addLayout(cdbox)
		cdialoghbox.addLayout(csbox)
		
		colorhbox = QtGui.QHBoxLayout()
		self.ambient = QtGui.QLabel("Ambient", colorframe)
		self.ambient.setAlignment(QtCore.Qt.AlignCenter)
		self.diffuse = QtGui.QLabel("Diffuse", colorframe)
		self.diffuse.setAlignment(QtCore.Qt.AlignCenter)
		self.specular = QtGui.QLabel("Specular", colorframe)
		self.specular.setAlignment(QtCore.Qt.AlignCenter)
		colorhbox.addWidget(self.ambient)
		colorhbox.addWidget(self.diffuse)
		colorhbox.addWidget(self.specular)
		
		self.shininess = ValSlider(colorframe, (0.0, 50.0), "Shine")
		self.shininess.setValue(self.item3d().shininess)
		
		colorvbox.addWidget(colorlabel)
		colorvbox.addLayout(cdialoghbox)
		colorvbox.addLayout(colorhbox)
		colorvbox.addWidget(self.shininess)
		colorframe.setLayout(colorvbox)
		colorframe.setMaximumWidth(350)
		gridbox.addWidget(colorframe, 3, 0, 1, 1)
		
		# Set to default, but do not run if being inherited
		if type(self) == EMInspectorControlShape: self.updateItemControls()
		
		QtCore.QObject.connect(self.ambcolorbox,QtCore.SIGNAL("newcolor(QColor)"),self._on_ambient_color)
		QtCore.QObject.connect(self.diffusecolorbox,QtCore.SIGNAL("newcolor(QColor)"),self._on_diffuse_color)
		QtCore.QObject.connect(self.specularcolorbox,QtCore.SIGNAL("newcolor(QColor)"),self._on_specular_color)
		QtCore.QObject.connect(self.shininess,QtCore.SIGNAL("valueChanged"),self._on_shininess)
		
	def _on_ambient_color(self, color):
		rgb = color.getRgb()
		if self.item3d():
			self.item3d().setAmbientColor((float(rgb[0])/255.0),(float(rgb[1])/255.0),(float(rgb[2])/255.0))
			self.inspector().updateSceneGraph()
		
	def _on_diffuse_color(self, color):
		rgb = color.getRgb()
		if self.item3d():
			self.item3d().setDiffuseColor((float(rgb[0])/255.0),(float(rgb[1])/255.0),(float(rgb[2])/255.0))
			self.inspector().updateSceneGraph()
		
	def _on_specular_color(self, color):
		rgb = color.getRgb()
		if self.item3d():	
			self.item3d().setSpecularColor((float(rgb[0])/255.0),(float(rgb[1])/255.0),(float(rgb[2])/255.0))
			self.inspector().updateSceneGraph()
		
	def _on_shininess(self, shininess):
		if self.item3d():
			self.item3d().setShininess(shininess)
			self.inspector().updateSceneGraph()
class EMInspectorControlLine(EMInspectorControlShape):
	"""
	Class to make EMItem GUI SHAPE Line Inspector
	"""
	def __init__(self, name, item3d):
		EMInspectorControlShape.__init__(self, name, item3d)
		
	def updateItemControls(self):
		""" Updates this item inspector. Function is called by the item it observes"""
		super(EMInspectorControlLine, self).updateItemControls()
	
	def updateMetaData(self):
		""" Updates the items metadata, such as line length, width. Function is called by the item it observes when the items meta data changes """
		super(EMInspectorControlLine, self).updateMetaData()
		self.leftArrowSize.setValue(self.item3d().leftArrowSize, quiet=1)
		self.leftArrowLength.setValue(self.item3d().leftArrowLength, quiet=1)
		self.rightArrowSize.setValue(self.item3d().rightArrowSize, quiet=1)
		self.rightArrowLength.setValue(self.item3d().rightArrowLength, quiet=1)
		self.slice.setValue(self.item3d().slices, quiet=1)
		self.stack.setValue(self.item3d().stacks, quiet=1)
		self.linelength.setValue(int(self.item3d().length), quiet=1)
	
	def addTabs(self):
		""" Add a tab for each 'column' """
		super(EMInspectorControlLine, self).addTabs()
		tabwidget = QtGui.QWidget()
		gridbox = QtGui.QGridLayout()
		
		EMInspectorControlLine.addControls(self, gridbox)
		
		tabwidget.setLayout(gridbox)
		self.addTab(tabwidget, "line")
		
	def addControls(self, gridbox):
		""" Construct all the widgets in this Item Inspector """
		#frame to control properties of left/right arrows
		lineframe = QtGui.QFrame()
		lineframe.setFrameShape(QtGui.QFrame.StyledPanel)
		lfont = QtGui.QFont()
		lfont.setBold(True)
		linegridbox = QtGui.QGridLayout()
		
		leftlabel = QtGui.QLabel("Left arrow")
		leftlabel.setFont(lfont)
		leftlabel.setAlignment(QtCore.Qt.AlignCenter)
		linegridbox.addWidget(leftlabel, 0, 1, 1, 1)
		
		sidelabel1 = QtGui.QLabel("Size")
		sidelabel1.setFont(lfont)
		sidelabel1.setAlignment(QtCore.Qt.AlignVCenter)
		linegridbox.addWidget(sidelabel1, 2, 0, 1, 1)
		
		sidelabel2 = QtGui.QLabel("Length")
		sidelabel2.setFont(lfont)
		sidelabel2.setAlignment(QtCore.Qt.AlignVCenter)
		linegridbox.addWidget(sidelabel2, 3, 0, 1, 1)
		
		self.leftShowArrow = QtGui.QCheckBox("Show")
		self.leftShowArrow.setChecked(self.item3d().showLeftArrow)
		linegridbox.addWidget(self.leftShowArrow, 1, 1, 1, 1)
		
		self.leftArrowSize = EMSpinWidget(int(self.item3d().leftArrowSize), 1.0, rounding=0)
		self.leftArrowSize.setMinimumWidth(120)
		linegridbox.addWidget(self.leftArrowSize, 2, 1, 1, 1)
		
		self.leftArrowLength = EMSpinWidget(int(self.item3d().leftArrowLength), 1.0, rounding=0)
		self.leftArrowLength.setMinimumWidth(120)
		linegridbox.addWidget(self.leftArrowLength, 3, 1, 1, 1)
		
		rightlabel = QtGui.QLabel("Right arrow")
		rightlabel.setFont(lfont)
		rightlabel.setAlignment(QtCore.Qt.AlignCenter)
		linegridbox.addWidget(rightlabel, 0, 2, 1, 1)
		
		self.rightShowArrow = QtGui.QCheckBox("Show")
		self.rightShowArrow.setChecked(self.item3d().showRightArrow)
		linegridbox.addWidget(self.rightShowArrow, 1, 2, 1, 1)
		
		self.rightArrowSize = EMSpinWidget(int(self.item3d().rightArrowSize), 1.0, rounding=0)
		self.rightArrowSize.setMinimumWidth(120)
		linegridbox.addWidget(self.rightArrowSize, 2, 2, 1, 1)
		
		self.rightArrowLength = EMSpinWidget(int(self.item3d().rightArrowLength), 1.0, rounding=0)
		self.rightArrowLength.setMinimumWidth(120)
		linegridbox.addWidget(self.rightArrowLength, 3, 2, 1, 1)
		
		linelengthlabel = QtGui.QLabel("Line Length")
		linelengthlabel.setFont(lfont)
		linelengthlabel.setAlignment(QtCore.Qt.AlignCenter)
		linegridbox.addWidget(linelengthlabel, 4, 0, 2, 2)
		
		self.linelength = EMSpinWidget(int(self.item3d().length), 1.0, rounding=0)
		linegridbox.addWidget(self.linelength, 4, 2, 2, 2)
		
		linewidthlabel = QtGui.QLabel("Line Width")
		linewidthlabel.setFont(lfont)
		linewidthlabel.setAlignment(QtCore.Qt.AlignCenter)
		linegridbox.addWidget(linewidthlabel, 5, 0, 1, 2)
		
		self.linewidth = EMSpinWidget(int(self.item3d().width), 1.0, rounding=0)
		linegridbox.addWidget(self.linewidth, 5, 2, 1, 2)
		
		lineframe.setLayout(linegridbox)	
		gridbox.addWidget(lineframe, 2, 0)
		
		#frame to control slice/stack of the line
		lineframe2 = QtGui.QFrame()
		lineframe2.setFrameShape(QtGui.QFrame.StyledPanel)
		linehbox = QtGui.QVBoxLayout()
				
		self.slice = ValSlider(lineframe2, (1, 100), "Slice", rounding=0)
		self.slice.setValue(self.item3d().slices)
		
		self.stack = ValSlider(lineframe2, (1, 100), "Stack", rounding=0)
		self.slice.setValue(self.item3d().stacks)
		
		linehbox.addWidget(self.slice)
		linehbox.addWidget(self.stack)
		
		lineframe2.setLayout(linehbox)
		gridbox.addWidget(lineframe2, 3, 0)
		
		# set to default, but run only as a base class
		if type(self) == EMInspectorControl3DText: 
			self.updateItemControls()
			self.updateMetaData()
		
		QtCore.QObject.connect(self.leftShowArrow, QtCore.SIGNAL("stateChanged(int)"), self.redraw)
		QtCore.QObject.connect(self.rightShowArrow, QtCore.SIGNAL("stateChanged(int)"), self.redraw)
		QtCore.QObject.connect(self.leftArrowSize,QtCore.SIGNAL("valueChanged(int)"),self.redraw)
		QtCore.QObject.connect(self.leftArrowLength,QtCore.SIGNAL("valueChanged(int)"),self.redraw)
		QtCore.QObject.connect(self.rightArrowSize,QtCore.SIGNAL("valueChanged(int)"),self.redraw)
		QtCore.QObject.connect(self.rightArrowLength,QtCore.SIGNAL("valueChanged(int)"),self.redraw)
		QtCore.QObject.connect(self.linelength,QtCore.SIGNAL("valueChanged(int)"),self.redraw)
		QtCore.QObject.connect(self.linewidth,QtCore.SIGNAL("valueChanged(int)"),self.redraw)
		
		QtCore.QObject.connect(self.slice,QtCore.SIGNAL("valueChanged"),self.redraw)
		QtCore.QObject.connect(self.stack,QtCore.SIGNAL("valueChanged"),self.redraw)

	def redraw(self):
		self.item3d().setShowLeftArrow(self.leftShowArrow.isChecked())
		self.item3d().setShowRightArrow(self.rightShowArrow.isChecked())
		self.item3d().leftArrowSize = self.leftArrowSize.getValue()
		self.item3d().leftArrowLength = self.leftArrowLength.getValue()
		self.item3d().rightArrowSize = self.rightArrowSize.getValue()
		self.item3d().rightArrowLength = self.rightArrowLength.getValue()
		self.item3d().setLength(self.linelength.getValue())
		self.item3d().setWidth(self.linewidth.getValue())
		
		self.item3d().setSlices(self.slice.getValue())
		self.item3d().setStacks(self.stack.getValue())
		
		if self.inspector:
			self.inspector().updateSceneGraph()
Exemple #14
0
class EM3DSliceInspector(QtGui.QWidget):
	def __init__(self,target) :
		self.busy = False
		QtGui.QWidget.__init__(self,None)
		self.setWindowIcon(QtGui.QIcon(get_image_directory() +"desktop.png"))
		self.transform_panel = EMTransformPanel(target,self)
		self.target=weakref.ref(target)
		
		self.vbl = QtGui.QVBoxLayout(self)
		self.vbl.setMargin(0)
		self.vbl.setSpacing(6)
		self.vbl.setObjectName("vbl")
		
		self.hbl = QtGui.QHBoxLayout()
		self.hbl.setMargin(0)
		self.hbl.setSpacing(6)
		self.hbl.setObjectName("hbl")
		self.vbl.addLayout(self.hbl)
		
		self.hist = ImgHistogram(self)
		self.hist.setObjectName("hist")
		self.hbl.addWidget(self.hist)
		
		self.vbl2 = QtGui.QVBoxLayout()
		self.vbl2.setMargin(0)
		self.vbl2.setSpacing(6)
		self.vbl2.setObjectName("vbl2")
		self.hbl.addLayout(self.vbl2)
	
		self.cubetog = QtGui.QPushButton("Cube")
		self.cubetog.setCheckable(1)
		self.vbl2.addWidget(self.cubetog)
		
		self.defaults = QtGui.QPushButton("Defaults")
		self.vbl2.addWidget(self.defaults)
		
		self.vbl.addWidget(self.get_main_tab())
		
		self.n3_showing = False
		
#		self.current_src = EULER_EMAN
		
		QtCore.QObject.connect(self.slice, QtCore.SIGNAL("valueChanged"), target.set_slice)
		QtCore.QObject.connect(self.glcontrast, QtCore.SIGNAL("valueChanged"), target.set_GL_contrast)
		QtCore.QObject.connect(self.glbrightness, QtCore.SIGNAL("valueChanged"), target.set_GL_brightness)
		QtCore.QObject.connect(self.axisCombo, QtCore.SIGNAL("currentIndexChanged(QString)"), target.setAxis)
		QtCore.QObject.connect(self.cubetog, QtCore.SIGNAL("toggled(bool)"), target.toggle_cube)
		QtCore.QObject.connect(self.defaults, QtCore.SIGNAL("clicked(bool)"), self.set_defaults)
		QtCore.QObject.connect(self.contrast, QtCore.SIGNAL("valueChanged"), self.on_contrast_changed)
		QtCore.QObject.connect(self.bright, QtCore.SIGNAL("valueChanged"), self.on_brightness_changed)
	
	def on_contrast_changed(self,val):
		if self.busy: return
		self.target().set_contrast(val)
	
	def on_brightness_changed(self,val):
		if self.busy: return
		self.target().set_brightness(val)
	
	def set_contrast_bright(self,c,b):
		self.busy = True
		self.contrast.setValue(c)
		self.bright.setValue(b)
		self.busy = False
	def update_rotations(self,t3d):
		self.transform_panel.update_rotations(t3d)
	
	def set_scale(self,val):
		self.transform_panel.set_scale(val)
	
	def set_xy_trans(self, x, y):
		self.transform_panel.set_xy_trans(x,y)
		
	def set_xyz_trans(self,x,y,z):
		self.transform_panel.set_xyz_trans(x,y,z)	
	
	def get_transform_layout(self):
		return self.maintab.vbl
	
	def set_defaults(self):
		self.target().set_default_contrast_settings()
		self.set_contrast_bright(self.target().contrast,self.target().bright)
		self.glcontrast.setValue(1.0)
		self.glbrightness.setValue(0.0)
		self.transform_panel.set_defaults()
		
		self.target().generate_current_display_list()
		self.target().updateGL()

	def get_main_tab(self):
	
		self.maintab = QtGui.QWidget()
		maintab = self.maintab
		maintab.vbl = QtGui.QVBoxLayout(self.maintab)
		maintab.vbl.setMargin(0)
		maintab.vbl.setSpacing(6)
		maintab.vbl.setObjectName("Main")
		
		self.hbl_slice = QtGui.QHBoxLayout()
		self.hbl_slice.setMargin(0)
		self.hbl_slice.setSpacing(6)
		self.hbl_slice.setObjectName("Axis")
		maintab.vbl.addLayout(self.hbl_slice)
		
		self.slice = ValSlider(maintab,(0.0,10.0),"Slice:")
		self.slice.setObjectName("slice")
		self.slice.setValue(1.0)
		self.hbl_slice.addWidget(self.slice)
		
		self.axisCombo = QtGui.QComboBox(maintab)
		self.axisCombo.addItem(' z ')
		self.axisCombo.addItem(' y ')
		self.axisCombo.addItem(' x ')
		self.axisCombo.addItem(' track ')
		self.hbl_slice.addWidget(self.axisCombo)
		
		
		self.contrast = ValSlider(maintab,(0.0,20.0),"Cont:")
		self.contrast.setObjectName("contrast")
		self.contrast.setValue(1.0)
		maintab.vbl.addWidget(self.contrast)

		self.bright = ValSlider(maintab,(-5.0,5.0),"Brt:")
		self.bright.setObjectName("bright")
		self.bright.setValue(0.1)
		self.bright.setValue(0.0)
		maintab.vbl.addWidget(self.bright)
		
		self.glcontrast = ValSlider(maintab,(1.0,5.0),"GLShd:")
		self.glcontrast.setObjectName("GLShade")
		self.glcontrast.setValue(1.0)
		maintab.vbl.addWidget(self.glcontrast)
		
		self.glbrightness = ValSlider(maintab,(-1.0,0.0),"GLBst:")
		self.glbrightness.setObjectName("GLBoost")
		self.glbrightness.setValue(0.1)
		self.glbrightness.setValue(0.0)
		maintab.vbl.addWidget(self.glbrightness)
	
		self.transform_panel.addWidgets(maintab.vbl)
		
		return maintab
	
	def slider_rotate(self):
		self.target().load_rotation(self.get_current_rotation())

	def set_hist(self,hist,minden,maxden):
		self.hist.set_data(hist,minden,maxden)
		
	def set_slice(self,val):
		self.slice.setValue(val)
	
	def set_sliceRange(self,min,max):
		self.slice.setRange(min,max)
class EMImageInspector2D(QtGui.QWidget):
	def __init__(self,target) :
		QtGui.QWidget.__init__(self,None)
		self.target=target
		
		self.vboxlayout = QtGui.QVBoxLayout(self)
		self.vboxlayout.setMargin(0)
		self.vboxlayout.setSpacing(6)
		self.vboxlayout.setObjectName("vboxlayout")
		
		self.hist = ImgHistogram(self)
		self.hist.setObjectName("hist")
		self.vboxlayout.addWidget(self.hist)
		
		self.scale = ValSlider(self,(0.1,5.0),"Mag:")
		self.scale.setObjectName("scale")
		self.scale.setValue(1.0)
		self.vboxlayout.addWidget(self.scale)
		
		self.mins = ValSlider(self,label="Min:")
		self.mins.setObjectName("mins")
		self.vboxlayout.addWidget(self.mins)
		
		self.combo = QtGui.QComboBox(self)
		
		for i in range(0,10):
			self.combo.addItem(str(i))
		self.vboxlayout.addWidget(self.combo)
		
		self.maxs = ValSlider(self,label="Max:")
		self.maxs.setObjectName("maxs")
		self.vboxlayout.addWidget(self.maxs)
		
		self.brts = ValSlider(self,(-1.0,1.0),"Brt:")
		self.brts.setObjectName("brts")
		self.vboxlayout.addWidget(self.brts)
		
		self.conts = ValSlider(self,(0.0,1.0),"Cont:")
		self.conts.setObjectName("conts")
		self.vboxlayout.addWidget(self.conts)
		
		self.lowlim=0
		self.highlim=1.0
		self.busy=0
		
		QtCore.QObject.connect(self.scale, QtCore.SIGNAL("valueChanged"), target.set_scale)
		QtCore.QObject.connect(self.mins, QtCore.SIGNAL("valueChanged"), self.newMin)
		QtCore.QObject.connect(self.maxs, QtCore.SIGNAL("valueChanged"), self.newMax)
		QtCore.QObject.connect(self.brts, QtCore.SIGNAL("valueChanged"), self.newBrt)
		QtCore.QObject.connect(self.conts, QtCore.SIGNAL("valueChanged"), self.newCont)
		QtCore.QObject.connect(self.combo, QtCore.SIGNAL("currentIndexChanged(QString)"), self.setCombo)
		
	def setCombo(self,val):
		pass
		#print val
		#print "yeealllow"
	
	def newMin(self,val):
		if self.busy : return
		self.busy=1
		self.target.setDenMin(val)

		self.update_brightness_contrast()
		self.busy=0
		
	def newMax(self,val):
		if self.busy : return
		self.busy=1
		self.target.setDenMax(val)
		self.update_brightness_contrast()
		self.busy=0
	
	def newBrt(self,val):
		if self.busy : return
		self.busy=1
		self.update_min_max()
		self.busy=0
		
	def newCont(self,val):
		if self.busy : return
		self.busy=1
		self.update_min_max()
		self.busy=0

	def update_brightness_contrast(self):
		b=0.5*(self.mins.value+self.maxs.value-(self.lowlim+self.highlim))
		c=(self.mins.value-self.maxs.value)/(2.0*(self.lowlim-self.highlim))
		self.brts.setValue(-b)
		self.conts.setValue(1.0-c)
		
	def update_min_max(self):
		x0=((self.lowlim+self.highlim)/2.0-(self.highlim-self.lowlim)*(1.0-self.conts.value+self.brts.value))
		x1=((self.lowlim+self.highlim)/2.0+(self.highlim-self.lowlim)*(1.0-self.conts.value-self.brts.value))
		self.mins.setValue(x0)
		self.maxs.setValue(x1)
		self.target.setDenRange(x0,x1)
		
	def set_hist(self,hist,minden,maxden):
		self.hist.set_data(hist,minden,maxden)

	def set_limits(self,lowlim,highlim,curmin,curmax):
		self.lowlim=lowlim
		self.highlim=highlim
		self.mins.setRange(lowlim,highlim)
		self.maxs.setRange(lowlim,highlim)
		self.mins.setValue(curmin)
		self.maxs.setValue(curmax)
Exemple #16
0
class GUIctf(QtGui.QWidget):
    def __init__(self, application, data):
        """Implements the CTF fitting dialog using various EMImage and EMPlot2D widgets
		'data' is a list of (filename,ctf,im_1d,bg_1d,im_2d,bg_2d)
		"""
        try:
            from emimage2d import EMImage2DWidget
        except:
            print "Cannot import EMAN image GUI objects (EMImage2DWidget)"
            sys.exit(1)
        try:
            from emplot2d import EMPlot2DWidget
        except:
            print "Cannot import EMAN plot GUI objects (is matplotlib installed?)"
            sys.exit(1)

        self.app = weakref.ref(application)

        QtGui.QWidget.__init__(self, None)
        self.setWindowIcon(QtGui.QIcon(get_image_directory() + "ctf.png"))

        self.data = data
        self.curset = 0
        self.plotmode = 0

        self.guiim = EMImage2DWidget(application=self.app())
        self.guiplot = EMPlot2DWidget(application=self.app())

        self.guiim.connect(self.guiim, QtCore.SIGNAL("mousedown"),
                           self.imgmousedown)
        self.guiim.connect(self.guiim, QtCore.SIGNAL("mousedrag"),
                           self.imgmousedrag)
        self.guiim.connect(self.guiim, QtCore.SIGNAL("mouseup"),
                           self.imgmouseup)
        self.guiplot.connect(self.guiplot, QtCore.SIGNAL("mousedown"),
                             self.plotmousedown)

        self.guiim.mmode = "app"

        # This object is itself a widget we need to set up
        self.hbl = QtGui.QHBoxLayout(self)
        self.hbl.setMargin(0)
        self.hbl.setSpacing(6)
        self.hbl.setObjectName("hbl")

        # plot list and plot mode combobox
        self.vbl2 = QtGui.QVBoxLayout()
        self.setlist = QtGui.QListWidget(self)
        self.setlist.setSizePolicy(QtGui.QSizePolicy.Preferred,
                                   QtGui.QSizePolicy.Expanding)
        self.vbl2.addWidget(self.setlist)

        self.splotmode = QtGui.QComboBox(self)
        self.splotmode.addItem("Bgsub & fit")
        self.splotmode.addItem("Ptcl & BG power")
        self.splotmode.addItem("SNR")
        self.splotmode.addItem("Smoothed SNR")
        self.splotmode.addItem("Integrated SNR")
        self.splotmode.addItem("Total CTF")
        self.vbl2.addWidget(self.splotmode)
        self.hbl.addLayout(self.vbl2)

        # ValSliders for CTF parameters
        self.vbl = QtGui.QVBoxLayout()
        self.vbl.setMargin(0)
        self.vbl.setSpacing(6)
        self.vbl.setObjectName("vbl")
        self.hbl.addLayout(self.vbl)

        #self.samp = ValSlider(self,(0,5.0),"Amp:",0)
        #self.vbl.addWidget(self.samp)

        self.sdefocus = ValSlider(self, (0, 5), "Defocus:", 0, 90)
        self.vbl.addWidget(self.sdefocus)

        self.sbfactor = ValSlider(self, (0, 1600), "B factor:", 0, 90)
        self.vbl.addWidget(self.sbfactor)

        self.sampcont = ValSlider(self, (0, 100), "% AC", 0, 90)
        self.vbl.addWidget(self.sampcont)

        #		self.sapix=ValSlider(self,(.2,10),"A/Pix:",2,90)
        #		self.vbl.addWidget(self.sapix)

        self.svoltage = ValSlider(self, (0, 500), "Voltage (kV):", 0, 90)
        self.vbl.addWidget(self.svoltage)

        self.scs = ValSlider(self, (0, 5), "Cs (mm):", 0, 90)
        self.vbl.addWidget(self.scs)
        self.hbl_buttons = QtGui.QHBoxLayout()
        self.saveparms = QtGui.QPushButton("Save parms")
        self.recallparms = QtGui.QPushButton("Recall")
        self.output = QtGui.QPushButton("Output")
        self.hbl_buttons.addWidget(self.saveparms)
        self.hbl_buttons.addWidget(self.recallparms)
        self.hbl_buttons2 = QtGui.QHBoxLayout()
        self.hbl_buttons2.addWidget(self.output)
        self.vbl.addLayout(self.hbl_buttons)
        self.vbl.addLayout(self.hbl_buttons2)

        QtCore.QObject.connect(self.sdefocus, QtCore.SIGNAL("valueChanged"),
                               self.newCTF)
        QtCore.QObject.connect(self.sbfactor, QtCore.SIGNAL("valueChanged"),
                               self.newCTF)
        #		QtCore.QObject.connect(self.sapix, QtCore.SIGNAL("valueChanged"), self.newCTF)
        QtCore.QObject.connect(self.sampcont, QtCore.SIGNAL("valueChanged"),
                               self.newCTF)
        QtCore.QObject.connect(self.svoltage, QtCore.SIGNAL("valueChanged"),
                               self.newCTF)
        QtCore.QObject.connect(self.scs, QtCore.SIGNAL("valueChanged"),
                               self.newCTF)
        QtCore.QObject.connect(self.setlist,
                               QtCore.SIGNAL("currentRowChanged(int)"),
                               self.newSet)
        QtCore.QObject.connect(self.splotmode,
                               QtCore.SIGNAL("currentIndexChanged(int)"),
                               self.newPlotMode)

        QtCore.QObject.connect(self.saveparms, QtCore.SIGNAL("clicked(bool)"),
                               self.on_save_params)
        QtCore.QObject.connect(self.recallparms,
                               QtCore.SIGNAL("clicked(bool)"),
                               self.on_recall_params)
        QtCore.QObject.connect(self.output, QtCore.SIGNAL("clicked(bool)"),
                               self.on_output)

        self.update_data()

        self.update_data()
        self.resize(
            460, 380
        )  # figured these values out by printing the width and height in resize event
        self.setWindowTitle("CTF")

    def on_save_params(self):

        if len(self.setlist.selectedItems()) == 0: return

        val = self.curset
        name = str(self.setlist.item(val).text())
        name = get_file_tag(name)

        #		if not db_check_dict(name):
        #			print "error, the db doesn't exist:",name
        #
        db_parms = db_open_dict("bdb:e2ctf.parms")
        ctf = self.data[val][1].to_string()
        output = []
        for i, val in enumerate(self.data[val]):
            # ignore i == 0 it's just the filename
            if i > 1:
                output.append(val)
            elif i == 1:
                output.append(ctf)

        db_parms[name] = output

    def on_recall_params(self):
        if len(self.setlist.selectedItems()) == 0: return

        val = self.curset
        name = str(self.setlist.item(val).text())
        data = [name]
        name = get_file_tag(name)

        db_parms = db_open_dict("bdb:e2ctf.parms")
        if not db_parms.has_key(name):
            print "error, ctf parameters do not exist for:", name
#

        data.extend(db_parms[name])
        ctf = EMAN2Ctf()
        ctf.from_string(data[1])
        data[1] = ctf

        self.data[val] = data
        self.newSet(self.curset)


#	def get_output_params(self):

    def on_output(self):
        from emsprworkflow import E2CTFOutputTaskGeneral
        self.form = E2CTFOutputTaskGeneral()
        self.form.run_form()

    def show_guis(self):
        if self.guiim != None:
            self.app().show_specific(self.guiim)
        if self.guiplot != None:
            self.app().show_specific(self.guiplot)

        self.app().show_specific(self)

    def closeEvent(self, event):
        #		QtGui.QWidget.closeEvent(self,event)
        #		self.app.app.closeAllWindows()
        if self.guiim != None:
            self.app().close_specific(self.guiim)
            self.guiim = None
        if self.guiplot != None:
            self.app().close_specific(self.guiplot)
        event.accept()

    def newData(self, data):
        self.data = data
        self.update_data()

    def update_data(self):
        """This will make sure the various widgets properly show the current data sets"""
        self.setlist.clear()
        for i, j in enumerate(self.data):
            self.setlist.addItem(j[0])
        self.setlist.setCurrentRow(self.curset)

    def update_plot(self):
        val = self.curset
        ctf = self.data[val][1]
        ds = self.data[val][1].dsbg
        s = [ds * i for i in xrange(len(ctf.background))]
        if self.plotmode == 1:
            self.guiplot.set_data((s, self.data[val][2]), "fg", True, True)
            self.guiplot.set_data((s, self.data[val][3]), "bg")
            self.guiplot.setAxisParms("s (1/A)", "Intensity (a.u)")
        elif self.plotmode == 0:
            bgsub = [
                self.data[val][2][i] - self.data[val][3][i]
                for i in range(len(self.data[val][2]))
            ]
            self.guiplot.set_data((s, bgsub), "fg-bg", True, True)

            fit = ctf.compute_1d(len(s) * 2, ds,
                                 Ctf.CtfType.CTF_AMP)  # The fit curve
            sf = sfact(s, "ribosome", "nono")
            fit = [sf[i] * fit[i]**2 for i in xrange(len(s))
                   ]  # squared * a generic structure factor

            # auto-amplitude for b-factor adjustment
            rto, nrto = 0, 0
            for i in xrange(
                    int(.04 / ds) + 1, min(int(0.15 / ds),
                                           len(s) - 1)):
                if bgsub[i] > 0:
                    #rto+=fit[i]**2/fabs(bgsub[i])
                    #nrto+=fit[i]
                    #rto+=fit[i]**2
                    #nrto+=bgsub[i]**2
                    rto += fit[i]
                    nrto += fabs(bgsub[i])
            if nrto == 0: rto = 1.0
            else: rto /= nrto
            fit = [fit[i] / rto for i in range(len(s))]

            self.guiplot.set_data((s, fit), "fit")
            self.guiplot.setAxisParms("s (1/A)", "Intensity (a.u)")
        elif self.plotmode == 2:
            snr = ctf.compute_1d(len(s) * 2, ds,
                                 Ctf.CtfType.CTF_SNR)  # The snr curve
            self.guiplot.set_data((s, snr[:len(s)]), "snr", True)
            self.guiplot.setAxisParms("s (1/A)", "SNR (intensity ratio)")
        elif self.plotmode == 3:
            snr = ctf.compute_1d(len(s) * 2, ds,
                                 Ctf.CtfType.CTF_SNR)  # The snr curve
            self.guiplot.set_data((s, snr[:len(s)]), "snr", True)
            ssnr = ctf.compute_1d(len(s) * 2, ds,
                                  Ctf.CtfType.CTF_SNR_SMOOTH)  # The fit curve
            self.guiplot.set_data((s, ssnr[:len(s)]), "ssnr")
            self.guiplot.setAxisParms("s (1/A)", "SNR (intensity ratio)")
        elif self.plotmode == 4:
            snr = ctf.compute_1d(len(s) * 2, ds,
                                 Ctf.CtfType.CTF_SNR)  # The snr curve
            for i in range(1, len(snr)):
                snr[i] = snr[i] * i + snr[i - 1]  # integrate SNR*s
            #			for i in range(1,len(snr)): snr[i]/=snr[-1]				# normalize
            for i in range(1, len(snr)):
                snr[i] /= len(
                    snr
                )  # this way the relative quality of images can be compared
            self.guiplot.set_data((s, snr[:len(s)]), "snr", True)
            self.guiplot.setAxisParms("s (1/A)", "Integrated SNR")
        elif self.plotmode == 5:
            inten = [
                fabs(i)
                for i in ctf.compute_1d(len(s) * 2, ds, Ctf.CtfType.CTF_AMP)
            ]  # The snr curve
            self.guiplot.set_data((s, inten[:len(s)]), "single", True)
            all = [0 for i in inten]
            for st in self.data:
                print st
                inten = [
                    fabs(i) for i in st[1].compute_1d(
                        len(s) * 2, ds, Ctf.CtfType.CTF_AMP)
                ]
                for i in range(len(all)):
                    all[i] += inten[i]
            self.guiplot.set_data((s, all[:len(s)]), "total")

            #bgsub=[self.data[val][2][i]-self.data[val][3][i] for i in range(len(self.data[val][2]))]
            #self.guiplot.set_data("fg-bg",(s,bgsub),True,True)

            #fit=[bgsub[i]/sfact(s[i]) for i in range(len(s))]		# squared * a generic structure factor

            #self.guiplot.set_data("fit",(s,fit))

    def newSet(self, val):
        "called when a new data set is selected from the list"
        self.curset = val

        self.sdefocus.setValue(self.data[val][1].defocus, True)
        self.sbfactor.setValue(self.data[val][1].bfactor, True)
        #		self.sapix.setValue(self.data[val][1].apix)
        self.sampcont.setValue(self.data[val][1].ampcont, True)
        self.svoltage.setValue(self.data[val][1].voltage, True)
        self.scs.setValue(self.data[val][1].cs, True)

        self.guiim.set_data(self.data[val][4])
        self.update_plot()

    def newPlotMode(self, mode):
        self.plotmode = mode
        self.update_plot()

    def newCTF(self):
        self.data[self.curset][1].defocus = self.sdefocus.value
        self.data[self.curset][1].bfactor = self.sbfactor.value
        #		self.data[self.curset][1].apix=self.sapix.value
        self.data[self.curset][1].ampcont = self.sampcont.value
        self.data[self.curset][1].voltage = self.svoltage.value
        self.data[self.curset][1].cs = self.scs.value
        self.update_plot()

    def imgmousedown(self, event):
        m = self.guiim.scr_to_img((event.x(), event.y()))
        #self.guiim.add_shape("cen",["rect",.9,.9,.4,x0,y0,x0+2,y0+2,1.0])

    def imgmousedrag(self, event):
        m = self.guiim.scr_to_img((event.x(), event.y()))

        # box deletion when shift held down
        #if event.modifiers()&Qt.ShiftModifier:
        #for i,j in enumerate(self.boxes):

    def imgmouseup(self, event):
        m = self.guiim.scr_to_img((event.x(), event.y()))

    def plotmousedown(self, event):
        m = self.guiim.scr_to_img((event.x(), event.y()))

    def run(self):
        """If you make your own application outside of this object, you are free to use
		your own local app.exec_(). This is a convenience for ctf-only programs."""
        self.app.exec_()

        #		E2saveappwin("boxer","imagegeom",self.guiim)
        #		try:
        #			E2setappval("boxer","imcontrol",self.guiim.inspector.isVisible())
        #			if self.guiim.inspector.isVisible() : E2saveappwin("boxer","imcontrolgeom",self.guiim.inspector)
        #		except : E2setappval("boxer","imcontrol",False)

        return
class EMFontInspector(QtGui.QWidget, EMLightsInspectorBase):
	def __init__(self,target) :
		QtGui.QWidget.__init__(self,None)
		EMLightsInspectorBase.__init__(self)
		self.target=weakref.ref(target)
		self.transform_panel = EMTransformPanel(target,self)
		self.transform_vbl = None # This will eventually be a vertical box layout for the transform panel
		self.init_fonts()

		self.vbl = QtGui.QVBoxLayout(self)
		self.vbl.setMargin(0)
		self.vbl.setSpacing(6)
		self.vbl.setObjectName("vbl")

		self.hbl = QtGui.QHBoxLayout()
		self.hbl.setMargin(0)
		self.hbl.setSpacing(6)
		self.hbl.setObjectName("hbl")
		self.vbl.addLayout(self.hbl)

		self.vbl2 = QtGui.QVBoxLayout()
		self.vbl2.setMargin(0)
		self.vbl2.setSpacing(6)
		self.vbl2.setObjectName("vbl2")
		self.hbl.addLayout(self.vbl2)

		self.wiretog = QtGui.QPushButton("Wire")
		self.wiretog.setCheckable(1)
		self.vbl2.addWidget(self.wiretog)

		self.lighttog = QtGui.QPushButton("Light")
		self.lighttog.setCheckable(1)
		self.vbl2.addWidget(self.lighttog)

		self.tabwidget2 = QtGui.QTabWidget()
		self.maintab = None
		self.tabwidget2.addTab(self.get_main_tab(), "Main")
		#self.tabwidget2.addTab(self.get_GL_tab(),"GL")
		self.tabwidget2.addTab(self.get_format_tab(),"Formatting")
		self.tabwidget2.addTab(self.get_light_tab(), "Lights")
		self.vbl.addWidget(self.tabwidget2)
		self.n3_showing = False

		QtCore.QObject.connect(self.cbb, QtCore.SIGNAL("currentIndexChanged(QString)"), target.setColor)
		QtCore.QObject.connect(self.wiretog, QtCore.SIGNAL("toggled(bool)"), target.toggle_wire)
		QtCore.QObject.connect(self.lighttog, QtCore.SIGNAL("toggled(bool)"), target.toggle_light)
		QtCore.QObject.connect(self.glcontrast, QtCore.SIGNAL("valueChanged"), target.set_GL_contrast)
		QtCore.QObject.connect(self.glbrightness, QtCore.SIGNAL("valueChanged"), target.set_GL_brightness)
		QtCore.QObject.connect(self.combo, QtCore.SIGNAL("currentIndexChanged (const QString&)"), self.on_combo_change)
		QtCore.QObject.connect(self.text, QtCore.SIGNAL("textChanged(const QString&)"), self.on_text_change)
		QtCore.QObject.connect(self.lspacing, QtCore.SIGNAL("valueChanged"), self.set_GL_lspacing)
		QtCore.QObject.connect(self.length, QtCore.SIGNAL("valueChanged"), self.set_GL_length)
		QtCore.QObject.connect(self.tsize, QtCore.SIGNAL("valueChanged(int)"), self.set_GL_tsize)
		QtCore.QObject.connect(self.Dfont, QtCore.SIGNAL("currentIndexChanged (const QString&)"), self.on_Dfont_change)
		QtCore.QObject.connect(self.bgR, QtCore.SIGNAL("valueChanged"), self.set_GL_bgR)
		QtCore.QObject.connect(self.bgG, QtCore.SIGNAL("valueChanged"), self.set_GL_bgG)
		QtCore.QObject.connect(self.bgB, QtCore.SIGNAL("valueChanged"), self.set_GL_bgB)
		QtCore.QObject.connect(self.bg_a, QtCore.SIGNAL("valueChanged"), self.set_GL_bg_a)
	
	def get_transform_layout(self):
		return self.transform_vbl
		
	def set_GL_bgR(self,bgR):
		self.target().set_bg_r(bgR)
		self.target().updateGL()

	def set_GL_bgG(self,bgG):
		self.target().set_bg_g(bgG)
		self.target().updateGL()

	def set_GL_bgB(self,bgB):
		self.target().set_bg_b(bgB)
		self.target().updateGL()

	def set_GL_bg_a(self,bg_a):
		self.target().set_bg_a(bg_a)
		self.target().updateGL()

	def init_fonts(self):
		self.d = {}
		self.l = []
		platform = get_platform()
		if platform == "Linux":
			f_dir = "/usr/share/fonts/"
		elif platform == "Windows" or platform == "win32":
			f_dir = ":/windows/fonts/"
		elif platform in ["Apple", "Darwin"]:
			f_dir = "/Library/Fonts/"
		else:
			raise RuntimeError("Platform %s is not supported" %platform )
		
		for root, dirs, files in os.walk(f_dir):
			for name in files:
				if name.find("ttf")!=-1:
					filename = os.path.join(root, name)
					self.d[name] = filename
					self.l.extend([name])
		return self.l, self.d

	def on_Dfont_change(self,Dfont):
		self.target().font_renderer.set_font_file_name(self.d[str(Dfont)])
		self.target().updateGL()

	def set_GL_lspacing(self,lspacing):
		self.target().set_lspacing(lspacing)
		#THE FOLLOWING IF STATEMENT DOES IS NOT EFFECTIVE
		if len(self.target().render_string.split("\n")) != 1:
			self.lspacing.setEnabled(True)
		else:
			self.lspacing.setEnabled(False)
		self.target().updateGL()

	def set_GL_length(self,length):
		self.target().font_renderer.set_depth(int(length))	
		self.target().updateGL()

	def set_GL_tsize(self,tsize):
		self.target().font_renderer.set_face_size(tsize)
		self.target().updateGL()

	def on_text_change(self,text):
		try:
			evalt=str(eval(str(text)))
			self.target().set_render_string(evalt)
		except:
			self.target().set_render_string(str(text))
			
		if len(self.target().render_string.split("\n")) != 1:
			self.lspacing.setEnabled(True)
		else:
			self.lspacing.setEnabled(False)
		self.target().updateGL()

	def on_combo_change(self,mode):
		d = {}
		d["Extrude"] = FTGLFontMode.EXTRUDE
		d["Pixmap"] = FTGLFontMode.PIXMAP
		d["Bitmap"] = FTGLFontMode.BITMAP
		d["Polygon"] = FTGLFontMode.POLYGON
		d["Outline"] = FTGLFontMode.OUTLINE
		d["Texture"] = FTGLFontMode.TEXTURE
		self.target().font_renderer.set_font_mode(d[str(mode)])
		if mode == "Extrude":
			self.length.setEnabled(True)
		else:
			self.length.setEnabled(False)
		self.target().updateGL()

	def update_rotations(self,t3d):
		self.transform_panel.update_rotations(t3d)

	def set_scale(self,val):
		self.transform_panel.set_scale(val)

	def set_xy_trans(self, x, y):
		self.transform_panel.set_xy_trans(x,y)

	def set_xyz_trans(self,x,y,z):
		self.transform_panel.set_xyz_trans(x,y,z)	

	def get_GL_tab(self):
		self.gltab = QtGui.QWidget()
		gltab = self.gltab

		gltab.vbl = QtGui.QVBoxLayout(self.gltab)
		gltab.vbl.setMargin(0)
		gltab.vbl.setSpacing(6)
		gltab.vbl.setObjectName("Main")

		self.glcontrast = ValSlider(gltab,(1.0,5.0),"GLShd:")
		self.glcontrast.setObjectName("GLShade")
		self.glcontrast.setValue(1.0)
		gltab.vbl.addWidget(self.glcontrast)

		self.glbrightness = ValSlider(gltab,(-1.0,0.0),"GLBst:")
		self.glbrightness.setObjectName("GLBoost")
		self.glbrightness.setValue(0.1)
		self.glbrightness.setValue(0.0)
		gltab.vbl.addWidget(self.glbrightness)

		return gltab

	def get_main_tab(self):
		if ( self.maintab == None ):
			self.maintab = QtGui.QWidget()
			maintab = self.maintab
			maintab.vbl = QtGui.QVBoxLayout(self.maintab)
			maintab.vbl.setMargin(0)
			maintab.vbl.setSpacing(6)
			maintab.vbl.setObjectName("Main")
			
			self.transform_vbl = QtGui.QVBoxLayout()
			self.transform_panel.addWidgets(self.transform_vbl)
			maintab.vbl.addLayout(self.transform_vbl)
			self.glwidget = QtGui.QTabWidget()
			self.glwidget.addTab(self.get_GL_tab(),"GL")
			maintab.vbl.addWidget(self.glwidget)

		return maintab

	def get_format_tab(self):
		self.formattab = QtGui.QWidget()
		formattab = self.formattab
		formattab.vbl = QtGui.QVBoxLayout(self.formattab)
		formattab.vbl.setMargin(0)
		formattab.vbl.setSpacing(6)
		formattab.vbl.setObjectName("Format")

		self.hbl1 = QtGui.QHBoxLayout()
		self.text = QtGui.QLineEdit()
		self.text.setText("hello world")
		text_label = QtGui.QLabel("Enter Text:",self)
		text_label.setToolTip("Enters quotes to evaluate new line e.g. \"hello\\nworld\". Evaluates numerical expressions e.g. 9*9 (with out quotes)")
		self.hbl1.addWidget(text_label)
		self.hbl1.addWidget(self.text)
		formattab.vbl.addLayout(self.hbl1)

		self.hbl1 = QtGui.QHBoxLayout()
		self.Dfont = QtGui.QComboBox()
		for k in self.l: self.Dfont.addItem(k)
		self.hbl1.addWidget(QtGui.QLabel("Fonts:",self))
		self.hbl1.addWidget(self.Dfont)
		formattab.vbl.addLayout(self.hbl1)

		self.hbl1 = QtGui.QHBoxLayout()
		self.tsize = QtGui.QSpinBox()
		self.tsize.setRange(0,500)
		self.tsize.setValue(32)
		self.hbl1.addWidget(QtGui.QLabel("Size:",self),Qt.AlignLeft)
		self.hbl1.addWidget(self.tsize,Qt.AlignRight)
		self.combo = QtGui.QComboBox()
		self.items = ["Extrude","Pixmap","Bitmap","Polygon","Outline","Texture"]
		for k in self.items: self.combo.addItem(k)
		self.hbl1.addWidget(QtGui.QLabel("Style:",self),Qt.AlignLeft)
		self.hbl1.addWidget(self.combo,Qt.AlignRight)
		formattab.vbl.addLayout(self.hbl1)

		self.hbl1 = QtGui.QHBoxLayout()
		self.lspacing = ValSlider(self,(-100.0,100.0),"Line Spacing:")
		self.lspacing.setObjectName("Length")
		self.lspacing.setValue(75.0)
		self.lspacing.setEnabled(False)
		self.hbl1.addWidget(self.lspacing)
		formattab.vbl.addLayout(self.hbl1)

		self.hbl1 = QtGui.QHBoxLayout()
		self.length = ValSlider(self,(0.0,500.0),"Length:")
		self.length.setObjectName("Length")
		self.length.setValue(75.0)
		self.hbl1.addWidget(self.length)
		formattab.vbl.addLayout(self.hbl1)

		self.hbl1 = QtGui.QHBoxLayout()
		self.cbb = QtGui.QComboBox()
		self.hbl1.addWidget(QtGui.QLabel("Material:",self))
		self.hbl1.addWidget(self.cbb)
		formattab.vbl.addLayout(self.hbl1)

		self.hbl1 = QtGui.QHBoxLayout()
		self.bgtabwidget = QtGui.QTabWidget()
		self.maintab = None
		self.bgtabwidget.addTab(self.get_bgRGB_tab(), "BG RGB")
		self.hbl1.addWidget(self.bgtabwidget)
		self.n3_showing = False
		formattab.vbl.addLayout(self.hbl1)

		return formattab

	def get_bgRGB_tab(self):
		self.bgRGBtab = QtGui.QWidget()
		bgRGBtab = self.bgRGBtab
		bgRGBtab.vbl2 = QtGui.QVBoxLayout(self.bgRGBtab)
		bgRGBtab.vbl2.setMargin(0)
		bgRGBtab.vbl2.setSpacing(6)
		bgRGBtab.vbl2.setObjectName("BG RGB")

		self.hbl2 = QtGui.QHBoxLayout()
		self.bgR = ValSlider(self,(0,1),"R:")
		self.bgR.setObjectName("R")
		self.bgR.setValue(0.5)
		self.hbl2.addWidget(self.bgR)
		bgRGBtab.vbl2.addLayout(self.hbl2)

		self.hbl2 = QtGui.QHBoxLayout()
		self.bgG = ValSlider(self,(0,1),"G:")
		self.bgG.setObjectName("G")
		self.bgG.setValue(0.5)
		self.hbl2.addWidget(self.bgG)
		bgRGBtab.vbl2.addLayout(self.hbl2)

		self.hbl2 = QtGui.QHBoxLayout()
		self.bgB = ValSlider(self,(0,1),"B:")
		self.bgB.setObjectName("B")
		self.bgB.setValue(0.5)
		self.hbl2.addWidget(self.bgB)
		bgRGBtab.vbl2.addLayout(self.hbl2)		

		self.hbl2 = QtGui.QHBoxLayout()
		self.bg_a = ValSlider(self,(0,1),"Alpha:")
		self.bg_a.setObjectName("Alpha")
		self.bg_a.setValue(1.0)
		self.hbl2.addWidget(self.bg_a)
		bgRGBtab.vbl2.addLayout(self.hbl2)

		return bgRGBtab

#	def slider_rotate(self):
#		self.target.load_rotation(self.get_current_rotation())

#	def set_xy_trans(self, x, y):
#		self.x_trans.setValue(x)
#		self.y_trans.setValue(y)

#	def set_translate_scale(self, xscale,yscale,zscale):
#		self.x_trans.setSingleStep(xscale)
#		self.y_trans.setSingleStep(yscale)
#		self.z_trans.setSingleStep(zscale)

#	def update_rotations(self,t3d):
#		rot = t3d.get_rotation(self.src_map[str(self.src.itemText(self.src.currentIndex()))])
#		
#		convention = self.src.currentText()
#		if ( self.src_map[str(convention)] == EULER_SPIN ):
#			self.n3.setValue(rot[self.n3.getLabel()],True)
#		
#		self.az.setValue(rot[self.az.getLabel()],True)
#		self.alt.setValue(rot[self.alt.getLabel()],True)
#		self.phi.setValue(rot[self.phi.getLabel()],True)

#	def slider_rotate(self):
#		self.target.load_rotation(self.get_current_rotation())

#	def get_current_rotation(self):
#		convention = self.src.currentText()
#		rot = {}
#		if ( self.current_src == EULER_SPIN ):
#			rot[self.az.getLabel()] = self.az.getValue()
#			
#			n1 = self.alt.getValue()
#			n2 = self.phi.getValue()
#			n3 = self.n3.getValue()
#			
#			norm = sqrt(n1*n1 + n2*n2 + n3*n3)
#			
#			n1 /= norm
#			n2 /= norm
#			n3 /= norm
#			
#			rot[self.alt.getLabel()] = n1
#			rot[self.phi.getLabel()] = n2
#			rot[self.n3.getLabel()] = n3
#
#		else:
#			rot[self.az.getLabel()] = self.az.getValue()
#			rot[self.alt.getLabel()] = self.alt.getValue()
#			rot[self.phi.getLabel()] = self.phi.getValue()
#		
#		return Transform(self.current_src, rot)

	def setColors(self,colors,current_color):
		a = 0
		for i in colors:
			self.cbb.addItem(i)
			if ( i == current_color):
				self.cbb.setCurrentIndex(a)
			a += 1
Exemple #18
0
class EMIsoInspector(QtGui.QWidget):
    def __init__(self, target, enable_browse=False):
        QtGui.QWidget.__init__(self, None)

        self.setWindowIcon(QtGui.QIcon(get_image_directory() + "desktop.png"))
        self.target = weakref.ref(target)
        self.rotation_sliders = EMTransformPanel(target, self)

        self.vbl = QtGui.QVBoxLayout(self)
        self.vbl.setMargin(0)
        self.vbl.setSpacing(6)
        self.vbl.setObjectName("vbl")

        self.mrcChanged = False  #added by Muthu

        if enable_browse:
            hblbrowse = QtGui.QHBoxLayout()
            self.mrc_text = QtGui.QLineEdit()
            hblbrowse.addWidget(self.mrc_text)
            self.mrc_browse = QtGui.QPushButton("Browse")
            hblbrowse.addWidget(self.mrc_browse)
            self.vbl.addLayout(hblbrowse)

            QtCore.QObject.connect(self.mrc_text,
                                   QtCore.SIGNAL("textEdited(const QString&)"),
                                   self.on_mrc_text_change)  #added by Muthu
            QtCore.QObject.connect(self.mrc_browse,
                                   QtCore.SIGNAL("clicked(bool)"),
                                   self.on_mrc_browse)  # added by Muthu

        self.hbl = QtGui.QHBoxLayout()
        self.hbl.setMargin(0)
        self.hbl.setSpacing(6)
        self.hbl.setObjectName("hbl")
        self.vbl.addLayout(self.hbl)

        self.hist = ImgHistogram(self)
        self.hist.setObjectName("hist")
        self.hbl.addWidget(self.hist)

        self.vbl2 = QtGui.QVBoxLayout()
        self.vbl2.setMargin(0)
        self.vbl2.setSpacing(6)
        self.vbl2.setObjectName("vbl2")
        self.hbl.addLayout(self.vbl2)

        self.wiretog = QtGui.QPushButton("Wire")
        self.wiretog.setCheckable(1)
        self.vbl2.addWidget(self.wiretog)

        self.lighttog = QtGui.QPushButton("Light")
        self.lighttog.setCheckable(1)
        self.vbl2.addWidget(self.lighttog)

        self.cubetog = QtGui.QPushButton("Cube")
        self.cubetog.setCheckable(1)
        self.vbl2.addWidget(self.cubetog)

        self.texturetog = QtGui.QPushButton("Texture")
        self.texturetog.setCheckable(1)
        self.vbl2.addWidget(self.texturetog)
        self.texture = False

        self.tabwidget = QtGui.QTabWidget()
        self.maintab = None
        self.tabwidget.addTab(self.get_main_tab(), "Main")
        self.texturetab = None
        self.tabwidget.addTab(self.get_GL_tab(), "GL")
        self.tabwidget.addTab(self.get_texture_tab(), "Texture")
        self.get_texture_tab().setEnabled(False)
        self.vbl.addWidget(self.tabwidget)
        self.n3_showing = False

        QtCore.QObject.connect(self.thr, QtCore.SIGNAL("valueChanged"),
                               self.on_threshold_slider)
        QtCore.QObject.connect(self.contrast, QtCore.SIGNAL("valueChanged"),
                               target.set_contrast)
        QtCore.QObject.connect(self.bright, QtCore.SIGNAL("valueChanged"),
                               target.set_brightness)
        QtCore.QObject.connect(self.cbb,
                               QtCore.SIGNAL("currentIndexChanged(QString)"),
                               self.set_material)
        QtCore.QObject.connect(self.smp, QtCore.SIGNAL("valueChanged(int)"),
                               target.set_sample)
        QtCore.QObject.connect(self.wiretog, QtCore.SIGNAL("toggled(bool)"),
                               target.toggle_wire)
        QtCore.QObject.connect(self.lighttog, QtCore.SIGNAL("toggled(bool)"),
                               target.toggle_light)
        QtCore.QObject.connect(self.texturetog, QtCore.SIGNAL("toggled(bool)"),
                               self.toggle_texture)
        QtCore.QObject.connect(self.cubetog, QtCore.SIGNAL("toggled(bool)"),
                               target.toggle_cube)
        QtCore.QObject.connect(self.glcontrast, QtCore.SIGNAL("valueChanged"),
                               target.set_GL_contrast)
        QtCore.QObject.connect(self.glbrightness,
                               QtCore.SIGNAL("valueChanged"),
                               target.set_GL_brightness)

        QtCore.QObject.connect(self.ambient_tab.r,
                               QtCore.SIGNAL("valueChanged"),
                               self.update_material)
        QtCore.QObject.connect(self.ambient_tab.g,
                               QtCore.SIGNAL("valueChanged"),
                               self.update_material)
        QtCore.QObject.connect(self.ambient_tab.b,
                               QtCore.SIGNAL("valueChanged"),
                               self.update_material)
        QtCore.QObject.connect(self.diffuse_tab.r,
                               QtCore.SIGNAL("valueChanged"),
                               self.update_material)
        QtCore.QObject.connect(self.diffuse_tab.g,
                               QtCore.SIGNAL("valueChanged"),
                               self.update_material)
        QtCore.QObject.connect(self.diffuse_tab.b,
                               QtCore.SIGNAL("valueChanged"),
                               self.update_material)
        QtCore.QObject.connect(self.specular_tab.r,
                               QtCore.SIGNAL("valueChanged"),
                               self.update_material)
        QtCore.QObject.connect(self.specular_tab.g,
                               QtCore.SIGNAL("valueChanged"),
                               self.update_material)
        QtCore.QObject.connect(self.specular_tab.b,
                               QtCore.SIGNAL("valueChanged"),
                               self.update_material)
        QtCore.QObject.connect(self.emission_tab.r,
                               QtCore.SIGNAL("valueChanged"),
                               self.update_material)
        QtCore.QObject.connect(self.emission_tab.g,
                               QtCore.SIGNAL("valueChanged"),
                               self.update_material)
        QtCore.QObject.connect(self.emission_tab.b,
                               QtCore.SIGNAL("valueChanged"),
                               self.update_material)
        QtCore.QObject.connect(self.shininess, QtCore.SIGNAL("valueChanged"),
                               self.update_material)

    def on_mrc_text_change(self, text):  #if enable_browse, added by muthu
        print "Use the Browse button to update the mrc file"

    def on_mrc_browse(self):  #if enable_browse, added by muthu
        import os
        self.mrcfileName = QtGui.QFileDialog.getOpenFileName(
            self, "open file", os.getcwd(), "Text files (*.mrc)")
        if (self.mrcfileName == ""): return
        mrcData = EMData(str(self.mrcfileName))
        self.target().set_data(mrcData)
        self.mrc_text.setText(self.mrcfileName)
        self.mrcChanged = True
        self.target().updateGL()

    def update_rotations(self, t3d):
        self.rotation_sliders.update_rotations(t3d)

    def set_scale(self, val):
        self.rotation_sliders.set_scale(val)

    def set_xy_trans(self, x, y):
        self.rotation_sliders.set_xy_trans(x, y)

    def set_xyz_trans(self, x, y, z):
        self.rotation_sliders.set_xyz_trans(x, y, z)

    def get_transform_layout(self):
        return self.maintab.vbl

    def update_material(self):
        self.target().isocolor = "custom"
        custom = {}

        custom["ambient"] = [
            self.ambient_tab.r.getValue(),
            self.ambient_tab.g.getValue(),
            self.ambient_tab.b.getValue(), 1.0
        ]
        custom["diffuse"] = [
            self.diffuse_tab.r.getValue(),
            self.diffuse_tab.g.getValue(),
            self.diffuse_tab.b.getValue(), 1.0
        ]
        custom["specular"] = [
            self.specular_tab.r.getValue(),
            self.specular_tab.g.getValue(),
            self.specular_tab.b.getValue(), 1.0
        ]
        custom["emission"] = [
            self.emission_tab.r.getValue(),
            self.emission_tab.g.getValue(),
            self.emission_tab.b.getValue(), 1.0
        ]
        custom["shininess"] = self.shininess.getValue()
        self.target().colors["custom"] = custom

        n = self.cbb.findText(QtCore.QString("custom"))
        if n < 0: return
        self.cbb.setCurrentIndex(n)
        self.target().updateGL()

    def set_material(self, color):
        self.target().set_material(color)
        material = self.target().get_material()

        self.ambient_tab.r.setValue(material["ambient"][0])
        self.ambient_tab.g.setValue(material["ambient"][1])
        self.ambient_tab.b.setValue(material["ambient"][2])

        self.diffuse_tab.r.setValue(material["diffuse"][0])
        self.diffuse_tab.g.setValue(material["diffuse"][1])
        self.diffuse_tab.b.setValue(material["diffuse"][2])

        self.specular_tab.r.setValue(material["specular"][0])
        self.specular_tab.g.setValue(material["specular"][1])
        self.specular_tab.b.setValue(material["specular"][2])

        self.emission_tab.r.setValue(material["emission"][0])
        self.emission_tab.g.setValue(material["emission"][1])
        self.emission_tab.b.setValue(material["emission"][2])

        self.shininess.setValue(material["shininess"])

    def get_RGB_tab(self, name=""):
        return get_RGB_tab(self, name)
        #rgbtab = QtGui.QWidget(self)
        #rgbtab.vbl = QtGui.QVBoxLayout(rgbtab)
        #rgbtab.vbl.setMargin(0)
        #rgbtab.vbl.setSpacing(6)
        #rgbtab.vbl.setObjectName(name)

        #rgbtab.r = ValSlider(rgbtab,(0.0,1.0),"R:")
        #rgbtab.r.setObjectName("R")
        #rgbtab.r.setValue(0.5)
        #rgbtab.vbl.addWidget(rgbtab.r)

        #rgbtab.g = ValSlider(rgbtab,(0.0,1.0),"G:")
        #rgbtab.g.setObjectName("G")
        #rgbtab.g.setValue(0.5)
        #rgbtab.vbl.addWidget(rgbtab.g)

        #rgbtab.b = ValSlider(rgbtab,(0.0,1.0),"B:")
        #rgbtab.b.setObjectName("B")
        #rgbtab.b.setValue(0.5)
        #rgbtab.vbl.addWidget(rgbtab.b)

        #return rgbtab

    def get_GL_tab(self):
        self.gltab = QtGui.QWidget()
        gltab = self.gltab

        gltab.vbl = QtGui.QVBoxLayout(self.gltab)
        gltab.vbl.setMargin(0)
        gltab.vbl.setSpacing(6)
        gltab.vbl.setObjectName("GL")

        self.glcontrast = ValSlider(gltab, (1.0, 5.0), "GLShd:")
        self.glcontrast.setObjectName("GLShade")
        self.glcontrast.setValue(1.0)
        gltab.vbl.addWidget(self.glcontrast)

        self.glbrightness = ValSlider(gltab, (-1.0, 0.0), "GLBst:")
        self.glbrightness.setObjectName("GLBoost")
        self.glbrightness.setValue(0.1)
        self.glbrightness.setValue(0.0)
        gltab.vbl.addWidget(self.glbrightness)

        self.material_tab_widget = QtGui.QTabWidget()
        self.ambient_tab = self.get_RGB_tab("ambient")
        self.material_tab_widget.addTab(self.ambient_tab, "Ambient")

        self.diffuse_tab = self.get_RGB_tab("diffuse")
        self.material_tab_widget.addTab(self.diffuse_tab, "Diffuse")

        self.specular_tab = self.get_RGB_tab("specular")
        self.material_tab_widget.addTab(self.specular_tab, "Specular")

        self.emission_tab = self.get_RGB_tab("emission")
        self.material_tab_widget.addTab(self.emission_tab, "Emission")

        gltab.vbl.addWidget(self.material_tab_widget)

        self.shininess = ValSlider(gltab, (0, 128), "Shininess:")
        self.shininess.setObjectName("Shininess")
        self.shininess.setValue(64)
        gltab.vbl.addWidget(self.shininess)

        self.hbl_color = QtGui.QHBoxLayout()
        self.hbl_color.setMargin(0)
        self.hbl_color.setSpacing(6)
        self.hbl_color.setObjectName("Material")
        gltab.vbl.addLayout(self.hbl_color)

        self.color_label = QtGui.QLabel()
        self.color_label.setText('Material')
        self.hbl_color.addWidget(self.color_label)

        self.cbb = QtGui.QComboBox(gltab)
        self.hbl_color.addWidget(self.cbb)

        return gltab

    def toggle_texture(self):
        self.texture = not self.texture
        self.target().toggle_texture()
        self.get_texture_tab().setEnabled(self.texture)

    def get_texture_tab(self):
        if (self.texturetab == None):
            self.texturetab = QtGui.QWidget()
            texturetab = self.texturetab
            texturetab.vbl = QtGui.QVBoxLayout(self.texturetab)
            texturetab.vbl.setMargin(0)
            texturetab.vbl.setSpacing(6)
            texturetab.vbl.setObjectName("Main")

            self.contrast = ValSlider(texturetab, (0.0, 20.0), "Cont:")
            self.contrast.setObjectName("contrast")
            self.contrast.setValue(10.0)
            texturetab.vbl.addWidget(self.contrast)

            self.bright = ValSlider(texturetab, (-5.0, 5.0), "Brt:")
            self.bright.setObjectName("bright")
            self.bright.setValue(0.1)
            self.bright.setValue(0.0)
            texturetab.vbl.addWidget(self.bright)

            #self.glcontrast = ValSlider(texturetab,(1.0,5.0),"GLShd:")
            #self.glcontrast.setObjectName("GLShade")
            #self.glcontrast.setValue(1.0)
            #texturetab.vbl.addWidget(self.glcontrast)

            #self.glbrightness = ValSlider(texturetab,(-1.0,0.0),"GLBst:")
            #self.glbrightness.setObjectName("GLBoost")
            #self.glbrightness.setValue(0.1)
            #self.glbrightness.setValue(0.0)
            #texturetab.vbl.addWidget(self.glbrightness)

        return self.texturetab

    def get_main_tab(self):
        if (self.maintab == None):
            self.maintab = QtGui.QWidget()
            maintab = self.maintab
            maintab.vbl = QtGui.QVBoxLayout(self.maintab)
            maintab.vbl.setMargin(0)
            maintab.vbl.setSpacing(6)
            maintab.vbl.setObjectName("Main")

            self.thr = ValSlider(maintab, (0.0, 4.0), "Thr:")
            self.thr.setObjectName("thr")
            self.thr.setValue(0.5)
            maintab.vbl.addWidget(self.thr)

            self.hbl_smp = QtGui.QHBoxLayout()
            self.hbl_smp.setMargin(0)
            self.hbl_smp.setSpacing(6)
            self.hbl_smp.setObjectName("Sample")
            maintab.vbl.addLayout(self.hbl_smp)

            self.smp_label = QtGui.QLabel()
            self.smp_label.setText('Sample Level')
            self.hbl_smp.addWidget(self.smp_label)

            self.smp = QtGui.QSpinBox(maintab)
            self.smp.setValue(1)
            self.hbl_smp.addWidget(self.smp)

            self.rotation_sliders.addWidgets(maintab.vbl)

        return self.maintab

    def set_sampling_range(self, range):
        self.smp.setMinimum(1)
        self.smp.setMaximum(1 + range - 1)

    def slider_rotate(self):
        self.target().load_rotation(self.get_current_rotation())

    def set_materials(self, colors, current_color):
        a = 0
        for i in colors:
            self.cbb.addItem(i)
            if (i == current_color):
                self.cbb.setCurrentIndex(a)
            a += 1

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

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

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

    def set_hist(self, hist, minden, maxden):
        self.hist.set_data(hist, minden, maxden)
Exemple #19
0
class EM3DSliceInspector(QtGui.QWidget):
    def __init__(self, target):
        self.busy = False
        QtGui.QWidget.__init__(self, None)
        self.setWindowIcon(QtGui.QIcon(get_image_directory() + "desktop.png"))
        self.transform_panel = EMTransformPanel(target, self)
        self.target = weakref.ref(target)

        self.vbl = QtGui.QVBoxLayout(self)
        self.vbl.setMargin(0)
        self.vbl.setSpacing(6)
        self.vbl.setObjectName("vbl")

        self.hbl = QtGui.QHBoxLayout()
        self.hbl.setMargin(0)
        self.hbl.setSpacing(6)
        self.hbl.setObjectName("hbl")
        self.vbl.addLayout(self.hbl)

        self.hist = ImgHistogram(self)
        self.hist.setObjectName("hist")
        self.hbl.addWidget(self.hist)

        self.vbl2 = QtGui.QVBoxLayout()
        self.vbl2.setMargin(0)
        self.vbl2.setSpacing(6)
        self.vbl2.setObjectName("vbl2")
        self.hbl.addLayout(self.vbl2)

        self.cubetog = QtGui.QPushButton("Cube")
        self.cubetog.setCheckable(1)
        self.vbl2.addWidget(self.cubetog)

        self.defaults = QtGui.QPushButton("Defaults")
        self.vbl2.addWidget(self.defaults)

        self.vbl.addWidget(self.get_main_tab())

        self.n3_showing = False

        #		self.current_src = EULER_EMAN

        QtCore.QObject.connect(self.slice, QtCore.SIGNAL("valueChanged"),
                               target.set_slice)
        QtCore.QObject.connect(self.glcontrast, QtCore.SIGNAL("valueChanged"),
                               target.set_GL_contrast)
        QtCore.QObject.connect(self.glbrightness,
                               QtCore.SIGNAL("valueChanged"),
                               target.set_GL_brightness)
        QtCore.QObject.connect(self.axisCombo,
                               QtCore.SIGNAL("currentIndexChanged(QString)"),
                               target.setAxis)
        QtCore.QObject.connect(self.cubetog, QtCore.SIGNAL("toggled(bool)"),
                               target.toggle_cube)
        QtCore.QObject.connect(self.defaults, QtCore.SIGNAL("clicked(bool)"),
                               self.set_defaults)
        QtCore.QObject.connect(self.contrast, QtCore.SIGNAL("valueChanged"),
                               self.on_contrast_changed)
        QtCore.QObject.connect(self.bright, QtCore.SIGNAL("valueChanged"),
                               self.on_brightness_changed)

    def on_contrast_changed(self, val):
        if self.busy: return
        self.target().set_contrast(val)

    def on_brightness_changed(self, val):
        if self.busy: return
        self.target().set_brightness(val)

    def set_contrast_bright(self, c, b):
        self.busy = True
        self.contrast.setValue(c)
        self.bright.setValue(b)
        self.busy = False

    def update_rotations(self, t3d):
        self.transform_panel.update_rotations(t3d)

    def set_scale(self, val):
        self.transform_panel.set_scale(val)

    def set_xy_trans(self, x, y):
        self.transform_panel.set_xy_trans(x, y)

    def set_xyz_trans(self, x, y, z):
        self.transform_panel.set_xyz_trans(x, y, z)

    def get_transform_layout(self):
        return self.maintab.vbl

    def set_defaults(self):
        self.target().set_default_contrast_settings()
        self.set_contrast_bright(self.target().contrast, self.target().bright)
        self.glcontrast.setValue(1.0)
        self.glbrightness.setValue(0.0)
        self.transform_panel.set_defaults()

        self.target().generate_current_display_list()
        self.target().updateGL()

    def get_main_tab(self):

        self.maintab = QtGui.QWidget()
        maintab = self.maintab
        maintab.vbl = QtGui.QVBoxLayout(self.maintab)
        maintab.vbl.setMargin(0)
        maintab.vbl.setSpacing(6)
        maintab.vbl.setObjectName("Main")

        self.hbl_slice = QtGui.QHBoxLayout()
        self.hbl_slice.setMargin(0)
        self.hbl_slice.setSpacing(6)
        self.hbl_slice.setObjectName("Axis")
        maintab.vbl.addLayout(self.hbl_slice)

        self.slice = ValSlider(maintab, (0.0, 10.0), "Slice:")
        self.slice.setObjectName("slice")
        self.slice.setValue(1.0)
        self.hbl_slice.addWidget(self.slice)

        self.axisCombo = QtGui.QComboBox(maintab)
        self.axisCombo.addItem(' z ')
        self.axisCombo.addItem(' y ')
        self.axisCombo.addItem(' x ')
        self.axisCombo.addItem(' track ')
        self.hbl_slice.addWidget(self.axisCombo)

        self.contrast = ValSlider(maintab, (0.0, 20.0), "Cont:")
        self.contrast.setObjectName("contrast")
        self.contrast.setValue(1.0)
        maintab.vbl.addWidget(self.contrast)

        self.bright = ValSlider(maintab, (-5.0, 5.0), "Brt:")
        self.bright.setObjectName("bright")
        self.bright.setValue(0.1)
        self.bright.setValue(0.0)
        maintab.vbl.addWidget(self.bright)

        self.glcontrast = ValSlider(maintab, (1.0, 5.0), "GLShd:")
        self.glcontrast.setObjectName("GLShade")
        self.glcontrast.setValue(1.0)
        maintab.vbl.addWidget(self.glcontrast)

        self.glbrightness = ValSlider(maintab, (-1.0, 0.0), "GLBst:")
        self.glbrightness.setObjectName("GLBoost")
        self.glbrightness.setValue(0.1)
        self.glbrightness.setValue(0.0)
        maintab.vbl.addWidget(self.glbrightness)

        self.transform_panel.addWidgets(maintab.vbl)

        return maintab

    def slider_rotate(self):
        self.target().load_rotation(self.get_current_rotation())

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

    def set_slice(self, val):
        self.slice.setValue(val)

    def set_sliceRange(self, min, max):
        self.slice.setRange(min, max)
Exemple #20
0
class GUIctfsim(QtGui.QWidget):
    def __init__(self,
                 application,
                 apix=1.0,
                 voltage=300.0,
                 cs=4.1,
                 ac=10.0,
                 samples=256):
        """CTF simulation dialog
		"""
        try:
            from emimage2d import EMImage2DWidget
        except:
            print "Cannot import EMAN image GUI objects (EMImage2DWidget)"
            sys.exit(1)
        try:
            from emplot2d import EMPlot2DWidget
        except:
            print "Cannot import EMAN plot GUI objects (is matplotlib installed?)"
            sys.exit(1)

        self.app = weakref.ref(application)

        self.df_voltage = voltage
        self.df_apix = apix
        self.df_cs = cs
        self.df_ac = ac
        self.df_samples = samples
        self.img = None

        QtGui.QWidget.__init__(self, None)
        self.setWindowIcon(QtGui.QIcon(get_image_directory() + "ctf.png"))

        self.data = []
        self.curset = 0
        self.plotmode = 0

        self.guiim = EMImage2DWidget(application=self.app())
        self.guiiminit = True  # a flag that's used to auto resize the first time the gui's set_data function is called
        self.guiplot = EMPlot2DWidget(application=self.app())
        #		self.guirealim=EMImage2DWidget(application=self.app())	# This will show the original particle images

        #		self.guirealim.connect(self.guirealim,QtCore.SIGNAL("keypress"),self.realimgkey)
        self.guiim.connect(self.guiim, QtCore.SIGNAL("mousedown"),
                           self.imgmousedown)
        self.guiim.connect(self.guiim, QtCore.SIGNAL("mousedrag"),
                           self.imgmousedrag)
        self.guiim.connect(self.guiim, QtCore.SIGNAL("mouseup"),
                           self.imgmouseup)
        self.guiplot.connect(self.guiplot, QtCore.SIGNAL("mousedown"),
                             self.plotmousedown)

        self.guiim.mmode = "app"

        # This object is itself a widget we need to set up
        self.hbl = QtGui.QHBoxLayout(self)
        self.hbl.setMargin(0)
        self.hbl.setSpacing(6)
        self.hbl.setObjectName("hbl")

        # plot list and plot mode combobox
        self.vbl2 = QtGui.QVBoxLayout()
        self.setlist = MyListWidget(self)
        self.setlist.setSizePolicy(QtGui.QSizePolicy.Preferred,
                                   QtGui.QSizePolicy.Expanding)
        self.vbl2.addWidget(self.setlist)

        self.splotmode = QtGui.QComboBox(self)
        self.splotmode.addItem("Amplitude")
        self.splotmode.addItem("Intensity")
        self.splotmode.addItem("Int w sum")
        self.splotmode.addItem("Amp w sum")
        self.vbl2.addWidget(self.splotmode)
        self.hbl.addLayout(self.vbl2)

        # ValSliders for CTF parameters
        self.vbl = QtGui.QVBoxLayout()
        self.vbl.setMargin(0)
        self.vbl.setSpacing(6)
        self.vbl.setObjectName("vbl")
        self.hbl.addLayout(self.vbl)

        #self.samp = ValSlider(self,(0,5.0),"Amp:",0)
        #self.vbl.addWidget(self.samp)

        self.imginfo = QtGui.QLabel("Info", self)
        self.vbl.addWidget(self.imginfo)

        self.sdefocus = ValSlider(self, (0, 5), "Defocus:", 0, 90)
        self.vbl.addWidget(self.sdefocus)

        self.sbfactor = ValSlider(self, (0, 1600), "B factor:", 0, 90)
        self.vbl.addWidget(self.sbfactor)

        self.sdfdiff = ValSlider(self, (0, 1), "DF Diff:", 0, 90)
        self.vbl.addWidget(self.sdfdiff)

        self.sdfang = ValSlider(self, (0, 180), "Df Angle:", 0, 90)
        self.vbl.addWidget(self.sdfang)

        self.sampcont = ValSlider(self, (0, 100), "% AC", 0, 90)
        self.vbl.addWidget(self.sampcont)

        self.sapix = ValSlider(self, (.2, 10), "A/Pix:", 2, 90)
        self.vbl.addWidget(self.sapix)

        self.svoltage = ValSlider(self, (0, 1000), "Voltage (kV):", 0, 90)
        self.vbl.addWidget(self.svoltage)

        self.scs = ValSlider(self, (0, 5), "Cs (mm):", 0, 90)
        self.vbl.addWidget(self.scs)

        self.ssamples = ValSlider(self, (32, 1024), "# Samples:", 0, 90)
        self.ssamples.setIntonly(True)
        self.vbl.addWidget(self.ssamples)

        self.hbl_buttons = QtGui.QHBoxLayout()
        self.newbut = QtGui.QPushButton("New")
        self.hbl_buttons.addWidget(self.newbut)
        self.vbl.addLayout(self.hbl_buttons)

        self.on_new_but()

        QtCore.QObject.connect(self.sdefocus, QtCore.SIGNAL("valueChanged"),
                               self.newCTF)
        QtCore.QObject.connect(self.sbfactor, QtCore.SIGNAL("valueChanged"),
                               self.newCTF)
        QtCore.QObject.connect(self.sdfdiff, QtCore.SIGNAL("valueChanged"),
                               self.newCTF)
        QtCore.QObject.connect(self.sdfang, QtCore.SIGNAL("valueChanged"),
                               self.newCTF)
        QtCore.QObject.connect(self.sapix, QtCore.SIGNAL("valueChanged"),
                               self.newCTF)
        QtCore.QObject.connect(self.sampcont, QtCore.SIGNAL("valueChanged"),
                               self.newCTF)
        QtCore.QObject.connect(self.svoltage, QtCore.SIGNAL("valueChanged"),
                               self.newCTF)
        QtCore.QObject.connect(self.scs, QtCore.SIGNAL("valueChanged"),
                               self.newCTF)
        QtCore.QObject.connect(self.ssamples, QtCore.SIGNAL("valueChanged"),
                               self.newCTF)
        QtCore.QObject.connect(self.setlist,
                               QtCore.SIGNAL("currentRowChanged(int)"),
                               self.newSet)
        QtCore.QObject.connect(self.setlist, QtCore.SIGNAL("keypress"),
                               self.listkey)
        QtCore.QObject.connect(self.splotmode,
                               QtCore.SIGNAL("currentIndexChanged(int)"),
                               self.newPlotMode)

        QtCore.QObject.connect(self.newbut, QtCore.SIGNAL("clicked(bool)"),
                               self.on_new_but)

        self.resize(
            720, 380
        )  # figured these values out by printing the width and height in resize event

        E2loadappwin("e2ctfsim", "main", self)
        E2loadappwin("e2ctfsim", "image", self.guiim.qt_parent)
        #		E2loadappwin("e2ctf","realimage",self.guirealim.qt_parent)
        E2loadappwin("e2ctfsim", "plot", self.guiplot.qt_parent)

        self.setWindowTitle("CTF")

    def listkey(self, event):

        if event.key() >= Qt.Key_0 and event.key() <= Qt.Key_9:
            q = int(event.key()) - Qt.Key_0
            self.squality.setValue(q)
        elif event.key() == Qt.Key_Left:
            self.sdefocus.setValue(self.sdefocus.getValue() - 0.01)
        elif event.key() == Qt.Key_Right:
            self.sdefocus.setValue(self.sdefocus.getValue() + 0.01)
        elif event.key() == Qt.Key_R:
            self.on_recall_params()

    def on_new_but(self):
        ctf = EMAN2Ctf()
        ctf.defocus = 1.0
        ctf.voltage = self.df_voltage
        ctf.apix = self.df_apix
        ctf.cs = self.df_cs
        ctf.ac = self.df_ac
        ctf.samples = self.df_samples
        self.data.append((str(len(self.setlist) + 1), ctf))
        self.curset = len(self.data)
        self.update_data()

    def show_guis(self):
        if self.guiim != None:
            self.app().show_specific(self.guiim)
        if self.guiplot != None:
            self.app().show_specific(self.guiplot)
        #if self.guirealim != None:
        #self.app().show_specific(self.guirealim)

        self.show()

    def closeEvent(self, event):
        #		QtGui.QWidget.closeEvent(self,event)
        #		self.app.app.closeAllWindows()
        E2saveappwin("e2ctf", "main", self)

        if self.guiim != None:
            E2saveappwin("e2ctf", "image", self.guiim.qt_parent)
            self.app().close_specific(self.guiim)
            self.guiim = None
        if self.guiplot != None:
            E2saveappwin("e2ctf", "plot", self.guiplot.qt_parent)
            self.app().close_specific(self.guiplot)
        #if self.guirealim != None:
        #E2saveappwin("e2ctf","realimage",self.guirealim.qt_parent)
        #self.app().close_specific(self.guirealim)

        event.accept()
        self.app().close_specific(self)
        self.emit(
            QtCore.SIGNAL("module_closed")
        )  # this signal is important when e2ctf is being used by a program running its own event loop

    def update_data(self):
        """This will make sure the various widgets properly show the current data sets"""
        self.setlist.clear()
        for i, j in enumerate(self.data):
            self.setlist.addItem(j[0])
        self.setlist.setCurrentRow(self.curset)

    def update_plot(self):
        if self.guiplot == None: return  # it's closed/not visible

        for d in xrange(len(self.data)):
            ctf = self.data[d][1]
            ds = 1.0 / (ctf.apix * 2.0 * ctf.samples)
            s = arange(0, ds * ctf.samples, ds)

            curve = array(ctf.compute_1d(len(s) * 2, ds, Ctf.CtfType.CTF_AMP))
            if self.plotmode == 1 or self.plotmode == 2:
                curve = curve**2

            if self.plotmode == 2 or self.plotmode == 3:
                if d == 0: avg = curve[:]
                else:
                    if len(curve) != len(avg):
                        print "Number of samples must be fixed to compute an average ({})".format(
                            d + 1)
                    else:
                        avg += curve

            self.guiplot.set_data((s, curve),
                                  self.data[d][0],
                                  d == 0,
                                  True,
                                  color=d + 1)

        if self.plotmode in (2, 3):
            self.guiplot.set_data((s, avg), "Sum", False, True, color=0)

        self.guiplot.setAxisParms("s (1/$\AA$)", "CTF")

        ctf.compute_2d_complex(self.img, Ctf.CtfType.CTF_AMP, None)
        self.guiim.set_data(self.img)

    def newSet(self, val=0):
        "called when a new data set is selected from the list"
        self.curset = val

        self.sdefocus.setValue(self.data[val][1].defocus, True)
        self.sbfactor.setValue(self.data[val][1].bfactor, True)
        self.sapix.setValue(self.data[val][1].apix, True)
        self.sampcont.setValue(self.data[val][1].ampcont, True)
        self.svoltage.setValue(self.data[val][1].voltage, True)
        self.scs.setValue(self.data[val][1].cs, True)
        self.sdfdiff.setValue(self.data[val][1].dfdiff, True)
        self.sdfang.setValue(self.data[val][1].dfang, True)
        self.ssamples.setValue(self.data[val][1].samples, True)

        # make new image if necessary
        if self.img == None or self.img["ny"] != self.data[val][1].samples:
            self.img = EMData(self.data[val][1].samples + 2,
                              self.data[val][1].samples)
            self.img.to_zero()
            self.img.set_complex(1)
        self.guiim.set_data(self.img)
        #		self.imginfo.setText("%s particles     SNR = %s"%(ptcl,ssnr))

        #if self.guiim != None:
        ##			print self.data
        #self.guiim.set_data(self.data[val][4])
        #if self.guiiminit:
        #self.guiim.optimally_resize()
        #self.guiiminit = False
        #self.guiim.updateGL()
        #self.update_plot()

        #		print "self.data[val]=",self.data[val][0].split('#')[-1]

        self.guiim.qt_parent.setWindowTitle("e2ctfsim - 2D FFT - " +
                                            self.data[val][0])
        #		self.guirealim.qt_parent.setWindowTitle("e2ctf - "+self.data[val][0].split('#')[-1])
        self.guiplot.qt_parent.setWindowTitle("e2ctfsim - Plot ")

        #n=EMUtil.get_image_count(self.data[val][0])
        #if n>1:
        #self.ptcldata=EMData.read_images(self.data[val][0],range(0,min(20,n)))
        #im=sum(self.ptcldata)
        #im.mult(1.0/len(self.ptcldata))
        #self.ptcldata.insert(0,im)
        #self.guirealim.set_data(self.ptcldata)
        #else : self.guirealim.set_data([EMData()])
        self.update_plot()

    def newPlotMode(self, mode):
        self.plotmode = mode
        self.update_plot()

    def newCTF(self):
        #		print traceback.print_stack()
        self.data[self.curset][1].defocus = self.sdefocus.value
        self.data[self.curset][1].bfactor = self.sbfactor.value
        self.data[self.curset][1].dfdiff = self.sdfdiff.value
        self.data[self.curset][1].dfang = self.sdfang.value
        self.data[self.curset][1].apix = self.sapix.value
        self.data[self.curset][1].ampcont = self.sampcont.value
        self.data[self.curset][1].voltage = self.svoltage.value
        self.data[self.curset][1].cs = self.scs.value
        self.data[self.curset][1].samples = self.ssamples.value

        if self.img == None or self.img["ny"] != self.ssamples.value:
            self.img = EMData(self.ssamples.value + 2, self.ssamples.value)
            self.img.to_zero()
            self.img.set_complex(1)
            self.guiim.set_data(self.img)
        self.update_plot()

    def realimgkey(self, event):
        """Keypress in the image display window"""

        if event.key(
        ) == Qt.Key_I:  # if user presses I in this window we invert the stack on disk
            fsp = self.data[self.curset][0]
            n = EMUtil.get_image_count(fsp)
            print "Inverting images in %s" % fsp
            for i in xrange(n):
                img = EMData(fsp, i)
                img.mult(-1.0)
                img.write_image(fsp, i)

            #self.ptcldata=EMData.read_images(fsp,range(0,20))
            #self.guirealim.set_data(self.ptcldata)

    def imgmousedown(self, event):
        m = self.guiim.scr_to_img((event.x(), event.y()))
        #self.guiim.add_shape("cen",["rect",.9,.9,.4,x0,y0,x0+2,y0+2,1.0])

    def imgmousedrag(self, event):
        m = self.guiim.scr_to_img((event.x(), event.y()))

        # box deletion when shift held down
        #if event.modifiers()&Qt.ShiftModifier:
        #for i,j in enumerate(self.boxes):

    def imgmouseup(self, event):
        m = self.guiim.scr_to_img((event.x(), event.y()))

    def plotmousedown(self, event):
        m = self.guiim.scr_to_img((event.x(), event.y()))

    def run(self):
        """If you make your own application outside of this object, you are free to use
		your own local app.exec_(). This is a convenience for ctf-only programs."""
        self.app.exec_()

        #		E2saveappwin("boxer","imagegeom",self.guiim)
        #		try:
        #			E2setappval("boxer","imcontrol",self.guiim.inspector.isVisible())
        #			if self.guiim.inspector.isVisible() : E2saveappwin("boxer","imcontrolgeom",self.guiim.inspector)
        #		except : E2setappval("boxer","imcontrol",False)

        return
Exemple #21
0
class EMVolumeInspector(QtGui.QWidget):
	def __init__(self,target) :
		QtGui.QWidget.__init__(self,None)
		self.target=weakref.ref(target)
		self.setWindowIcon(QtGui.QIcon(get_image_directory() +"desktop.png"))
		self.rotation_sliders = EMTransformPanel(target,self)
		
		self.vbl = QtGui.QVBoxLayout(self)
		self.vbl.setMargin(0)
		self.vbl.setSpacing(6)
		self.vbl.setObjectName("vbl")
		
		self.hbl = QtGui.QHBoxLayout()
		self.hbl.setMargin(0)
		self.hbl.setSpacing(6)
		self.hbl.setObjectName("hbl")
		self.vbl.addLayout(self.hbl)
		
		self.hist = ImgHistogram(self)
		self.hist.setObjectName("hist")
		self.hbl.addWidget(self.hist)
		
		self.vbl2 = QtGui.QVBoxLayout()
		self.vbl2.setMargin(0)
		self.vbl2.setSpacing(6)
		self.vbl2.setObjectName("vbl2")
		self.hbl.addLayout(self.vbl2)
	
		self.cubetog = QtGui.QPushButton("Cube")
		self.cubetog.setCheckable(1)
		self.vbl2.addWidget(self.cubetog)
		
		self.defaults = QtGui.QPushButton("Defaults")
		self.vbl2.addWidget(self.defaults)
		
		self.tabwidget = QtGui.QTabWidget()
		
		self.tabwidget.addTab(self.get_main_tab(), "Main")
		self.tabwidget.addTab(self.get_GL_tab(),"GL")
		
		self.vbl.addWidget(self.tabwidget)
		
		self.n3_showing = False
		
		QtCore.QObject.connect(self.contrast, QtCore.SIGNAL("valueChanged"), target.set_contrast)
		QtCore.QObject.connect(self.glcontrast, QtCore.SIGNAL("valueChanged"), target.set_GL_contrast)
		QtCore.QObject.connect(self.glbrightness, QtCore.SIGNAL("valueChanged"), target.set_GL_brightness)
		QtCore.QObject.connect(self.bright, QtCore.SIGNAL("valueChanged"), target.set_brightness)
		QtCore.QObject.connect(self.cubetog, QtCore.SIGNAL("toggled(bool)"), target.toggle_cube)
		QtCore.QObject.connect(self.defaults, QtCore.SIGNAL("clicked(bool)"), self.set_defaults)
		QtCore.QObject.connect(self.smp, QtCore.SIGNAL("valueChanged(int)"), target.set_texture_sample)
	
	def update_rotations(self,t3d):
		self.rotation_sliders.update_rotations(t3d)
	
	def set_scale(self,val):
		self.rotation_sliders.set_scale(val)
	
	def set_xy_trans(self, x, y):
		self.rotation_sliders.set_xy_trans(x,y)
	
	def set_xyz_trans(self,x,y,z):
		self.rotation_sliders.set_xyz_trans(x,y,z)	
		
	def get_transform_layout(self):
		return self.maintab.vbl
	
	def get_GL_tab(self):
		self.gltab = QtGui.QWidget()
		gltab = self.gltab
		
		gltab.vbl = QtGui.QVBoxLayout(self.gltab )
		gltab.vbl.setMargin(0)
		gltab.vbl.setSpacing(6)
		gltab.vbl.setObjectName("Main")
		
		self.glcontrast = ValSlider(gltab,(1.0,5.0),"GLShd:")
		self.glcontrast.setObjectName("GLShade")
		self.glcontrast.setValue(1.0)
		gltab.vbl.addWidget(self.glcontrast)
		
		self.glbrightness = ValSlider(gltab,(-1.0,0.0),"GLBst:")
		self.glbrightness.setObjectName("GLBoost")
		self.glbrightness.setValue(0.1)
		self.glbrightness.setValue(0.0)
		gltab.vbl.addWidget(self.glbrightness)
	
		return gltab
	
	def get_main_tab(self):
	
		self.maintab = QtGui.QWidget()
		maintab = self.maintab
		maintab.vbl = QtGui.QVBoxLayout(self.maintab)
		maintab.vbl.setMargin(0)
		maintab.vbl.setSpacing(6)
		maintab.vbl.setObjectName("Main")
			
		self.contrast = ValSlider(maintab,(0.0,20.0),"Cont:")
		self.contrast.setObjectName("contrast")
		self.contrast.setValue(1.0)
		maintab.vbl.addWidget(self.contrast)

		self.bright = ValSlider(maintab,(-5.0,5.0),"Brt:")
		self.bright.setObjectName("bright")
		self.bright.setValue(0.1)
		self.bright.setValue(0.0)
		maintab.vbl.addWidget(self.bright)

		self.hbl_smp = QtGui.QHBoxLayout()
		self.hbl_smp.setMargin(0)
		self.hbl_smp.setSpacing(6)
		self.hbl_smp.setObjectName("Texture Oversampling")
		maintab.vbl.addLayout(self.hbl_smp)
		
		self.smp_label = QtGui.QLabel()
		self.smp_label.setText('Texture Oversampling')
		self.hbl_smp.addWidget(self.smp_label)
		
		self.smp = QtGui.QSpinBox(maintab)
		self.smp.setMaximum(10)
		self.smp.setMinimum(1)
		self.smp.setValue(1)
		self.hbl_smp.addWidget(self.smp)

		self.lowlim=0
		self.highlim=1.0
		self.busy=0

		self.rotation_sliders.addWidgets(maintab.vbl)

		return maintab
	
	def set_defaults(self):
		self.contrast.setValue(1.0)
		self.bright.setValue(0.0)
		self.glcontrast.setValue(1.0)
		self.glbrightness.setValue(0.0)
		self.rotation_sliders.set_defaults()
	
	def slider_rotate(self):
		self.target().load_rotation(self.get_current_rotation())
	
	def set_hist(self,hist,minden,maxden):
		self.hist.set_data(hist,minden,maxden)
class EMTransformPanel:
	def __init__(self,target,parent):
		self.target = weakref.ref(target)
		self.parent = weakref.ref(parent)
		
		self.label_src = QtGui.QLabel(parent)
		self.label_src.setText('Rotation Convention')
		
		self.src = QtGui.QComboBox(parent)
		self.load_src_options(self.src)
		
		self.x_label = QtGui.QLabel()
		self.x_label.setText('x')
		
		self.x_trans = QtGui.QDoubleSpinBox(parent)
		self.x_trans.setMinimum(-10000)
		self.x_trans.setMaximum(10000)
		self.x_trans.setValue(0.0)
	
		self.y_label = QtGui.QLabel()
		self.y_label.setText('y')
		
		self.y_trans = QtGui.QDoubleSpinBox(parent)
		self.y_trans.setMinimum(-10000)
		self.y_trans.setMaximum(10000)
		self.y_trans.setValue(0.0)
		
		self.z_label = QtGui.QLabel()
		self.z_label.setText('z')
		
		self.z_trans = QtGui.QDoubleSpinBox(parent)
		self.z_trans.setMinimum(-10000)
		self.z_trans.setMaximum(10000)
		self.z_trans.setValue(0.0)
		
		self.az = ValSlider(parent,(-360.0,360.0),"az",-1)
		self.az.setObjectName("az")
		self.az.setValue(0.0)
		
		self.alt = ValSlider(parent,(-180.0,180.0),"alt",-1)
		self.alt.setObjectName("alt")
		self.alt.setValue(0.0)
		
		self.phi = ValSlider(parent,(-360.0,360.0),"phi",-1)
		self.phi.setObjectName("phi")
		self.phi.setValue(0.0)
		
		self.scale = ValSlider(parent,(0.01,30.0),"Zoom:")
		self.scale.setObjectName("scale")
		self.scale.setValue(1.0)
		
		self.n3_showing = False
		
		self.current_src = "eman"
		
		QtCore.QObject.connect(self.az, QtCore.SIGNAL("valueChanged"), self.slider_rotate)
		QtCore.QObject.connect(self.alt, QtCore.SIGNAL("valueChanged"), self.slider_rotate)
		QtCore.QObject.connect(self.phi, QtCore.SIGNAL("valueChanged"), self.slider_rotate)
		QtCore.QObject.connect(self.src, QtCore.SIGNAL("currentIndexChanged(QString)"), self.set_src)
		QtCore.QObject.connect(self.scale, QtCore.SIGNAL("valueChanged"), self.target().set_scale)
		QtCore.QObject.connect(self.x_trans, QtCore.SIGNAL("valueChanged(double)"), self.target().set_cam_x)
		QtCore.QObject.connect(self.y_trans, QtCore.SIGNAL("valueChanged(double)"), self.target().set_cam_y)
		QtCore.QObject.connect(self.z_trans, QtCore.SIGNAL("valueChanged(double)"), self.target().set_cam_z)
		
		
	def set_defaults(self):
		self.x_trans.setValue(0.0)
		self.y_trans.setValue(0.0)
		self.z_trans.setValue(0.0)
		self.scale.setValue(1.0)
		self.az.setValue(0.0)
		self.alt.setValue(0.0)
		self.phi.setValue(0.0)
		
	def slider_rotate(self):
		self.target().load_rotation(self.get_current_rotation())
		
	def get_current_rotation(self):
		convention = self.src.currentText()
		rot = {}
		if ( self.current_src == "spin" ):
			rot[self.az.getLabel()] = self.az.getValue()
			
			n1 = self.alt.getValue()
			n2 = self.phi.getValue()
			n3 = self.n3.getValue()
			
			norm = sqrt(n1*n1 + n2*n2 + n3*n3)
			
			n1 /= norm
			n2 /= norm
			n3 /= norm
			
			rot[self.alt.getLabel()] = n1
			rot[self.phi.getLabel()] = n2
			rot[self.n3.getLabel()] = n3
			
		else:
			rot[self.az.getLabel()] = self.az.getValue()
			rot[self.alt.getLabel()] = self.alt.getValue()
			rot[self.phi.getLabel()] = self.phi.getValue()
		
		rot["type"] = self.current_src
		
		return Transform(rot)
	
	def addWidgets(self,target):
		
		target.addWidget(self.scale)
		self.hbl_trans = QtGui.QHBoxLayout()
		self.hbl_trans.setMargin(0)
		self.hbl_trans.setSpacing(6)
		self.hbl_trans.setObjectName("Trans")
		self.hbl_trans.addWidget(self.x_label)
		self.hbl_trans.addWidget(self.x_trans)
		self.hbl_trans.addWidget(self.y_label)
		self.hbl_trans.addWidget(self.y_trans)
		self.hbl_trans.addWidget(self.z_label)
		self.hbl_trans.addWidget(self.z_trans)
		
		target.addLayout(self.hbl_trans)
		
		self.hbl_src = QtGui.QHBoxLayout()
		self.hbl_src.setMargin(0)
		self.hbl_src.setSpacing(6)
		self.hbl_src.setObjectName("hbl")
		self.hbl_src.addWidget(self.label_src)
		self.hbl_src.addWidget(self.src)
		
		
		target.addLayout(self.hbl_src)
		target.addWidget(self.az)
		target.addWidget(self.alt)
		target.addWidget(self.phi)
	
	def set_src(self, val):
		t3d = self.get_current_rotation()
		
		if (self.n3_showing) :
			self.parent().get_transform_layout().removeWidget(self.n3)
			self.n3.deleteLater()
			self.n3_showing = False
			self.az.setRange(-360,360)
			self.alt.setRange(-180,180)
			self.phi.setRange(-360,660)
		
		if ( self.src_map[str(val)] == "spider" ):
			self.az.setLabel('phi')
			self.alt.setLabel('theta')
			self.phi.setLabel('psi')
		elif ( self.src_map[str(val)] == "eman" ):
			self.az.setLabel('az')
			self.alt.setLabel('alt')
			self.phi.setLabel('phi')
		elif ( self.src_map[str(val)] == "imagic"):
			self.az.setLabel('alpha')
			self.alt.setLabel('beta')
			self.phi.setLabel('gamma')
		elif ( self.src_map[str(val)] == "xyz"):
			self.az.setLabel('xtilt')
			self.alt.setLabel('ytilt')
			self.phi.setLabel('ztilt')
		elif ( self.src_map[str(val)] == "mrc" ):
			self.az.setLabel('phi')
			self.alt.setLabel('theta')
			self.phi.setLabel('omega')
		elif ( self.src_map[str(val)] == "spin" ):
			self.az.setLabel('Omega')
			self.alt.setRange(-1,1)
			self.phi.setRange(-1,1)
			
			self.alt.setLabel('n1')
			self.phi.setLabel('n2')
			
			self.n3 = ValSlider(self.parent(),(-360.0,360.0),"n3",-1)
			self.n3.setRange(-1,1)
			self.n3.setObjectName("n3")
			self.parent().get_transform_layout().addWidget(self.n3)
			QtCore.QObject.connect(self.n3, QtCore.SIGNAL("valueChanged"), self.slider_rotate)
			self.n3_showing = True
		
		self.current_src = self.src_map[str(val)]
		self.update_rotations(t3d)
	
	def load_src_options(self,widgit):
		self.load_src()
		for i in self.src_strings:
			widgit.addItem(i)
			
	def load_src(self):
		# supported_rot_conventions
		src_flags = []
		src_flags.append("eman")
		src_flags.append("spider")
		src_flags.append("imagic")
		src_flags.append("mrc")
		src_flags.append("spin")
		src_flags.append("xyz")
		
		self.src_strings = []
		self.src_map = {}
		for i in src_flags:
			self.src_strings.append(str(i))
			self.src_map[str(i)] = i
			
	def update_rotations(self,t3d):
		rot = t3d.get_rotation(self.src_map[str(self.src.itemText(self.src.currentIndex()))])
		
		convention = self.src.currentText()
		if ( self.src_map[str(convention)] == "spin" ):
			self.n3.setValue(rot[self.n3.getLabel()],True)
		
		self.az.setValue(rot[self.az.getLabel()],True)
		self.alt.setValue(rot[self.alt.getLabel()],True)
		self.phi.setValue(rot[self.phi.getLabel()],True)
		
	def set_scale(self,newscale):
		self.scale.setValue(newscale)
		
	def set_xy_trans(self, x, y):
		self.x_trans.setValue(x)
		self.y_trans.setValue(y)
		
	def set_xyz_trans(self, x, y,z):
		self.x_trans.setValue(x)
		self.y_trans.setValue(y)
		self.z_trans.setValue(z)
Exemple #23
0
class EMHelloWorldInspector(QtGui.QWidget):
	def __init__(self,target) :
		QtGui.QWidget.__init__(self,None)
		self.target=target
		
		self.vbl = QtGui.QVBoxLayout(self)
		self.vbl.setMargin(0)
		self.vbl.setSpacing(6)
		self.vbl.setObjectName("vbl")
		
		self.hbl = QtGui.QHBoxLayout()
		self.hbl.setMargin(0)
		self.hbl.setSpacing(6)
		self.hbl.setObjectName("hbl")
		self.vbl.addLayout(self.hbl)
		
		self.vbl2 = QtGui.QVBoxLayout()
		self.vbl2.setMargin(0)
		self.vbl2.setSpacing(6)
		self.vbl2.setObjectName("vbl2")
		self.hbl.addLayout(self.vbl2)
		
		self.wiretog = QtGui.QPushButton("Wire")
		self.wiretog.setCheckable(1)
		self.vbl2.addWidget(self.wiretog)
		
		self.lighttog = QtGui.QPushButton("Light")
		self.lighttog.setCheckable(1)
		self.vbl2.addWidget(self.lighttog)
		
		self.tabwidget = QtGui.QTabWidget()
		self.maintab = None
		self.tabwidget.addTab(self.get_main_tab(), "Main")
		self.tabwidget.addTab(self.get_GL_tab(),"GL")
		self.vbl.addWidget(self.tabwidget)
		self.n3_showing = False
		
		QtCore.QObject.connect(self.scale, QtCore.SIGNAL("valueChanged"), target.set_scale)
		QtCore.QObject.connect(self.az, QtCore.SIGNAL("valueChanged"), self.slider_rotate)
		QtCore.QObject.connect(self.alt, QtCore.SIGNAL("valueChanged"), self.slider_rotate)
		QtCore.QObject.connect(self.phi, QtCore.SIGNAL("valueChanged"), self.slider_rotate)
		QtCore.QObject.connect(self.cbb, QtCore.SIGNAL("currentIndexChanged(QString)"), target.setColor)
		QtCore.QObject.connect(self.src, QtCore.SIGNAL("currentIndexChanged(QString)"), self.set_src)
		QtCore.QObject.connect(self.x_trans, QtCore.SIGNAL("valueChanged(double)"), target.set_cam_x)
		QtCore.QObject.connect(self.y_trans, QtCore.SIGNAL("valueChanged(double)"), target.set_cam_y)
		QtCore.QObject.connect(self.z_trans, QtCore.SIGNAL("valueChanged(double)"), target.set_cam_z)
		QtCore.QObject.connect(self.wiretog, QtCore.SIGNAL("toggled(bool)"), target.toggle_wire)
		QtCore.QObject.connect(self.lighttog, QtCore.SIGNAL("toggled(bool)"), target.toggle_light)
		QtCore.QObject.connect(self.glcontrast, QtCore.SIGNAL("valueChanged"), target.set_GL_contrast)
		QtCore.QObject.connect(self.glbrightness, QtCore.SIGNAL("valueChanged"), target.set_GL_brightness)
	
	def get_GL_tab(self):
		self.gltab = QtGui.QWidget()
		gltab = self.gltab
		
		gltab.vbl = QtGui.QVBoxLayout(self.gltab )
		gltab.vbl.setMargin(0)
		gltab.vbl.setSpacing(6)
		gltab.vbl.setObjectName("Main")
		
		self.glcontrast = ValSlider(gltab,(1.0,5.0),"GLShd:")
		self.glcontrast.setObjectName("GLShade")
		self.glcontrast.setValue(1.0)
		gltab.vbl.addWidget(self.glcontrast)
		
		self.glbrightness = ValSlider(gltab,(-1.0,0.0),"GLBst:")
		self.glbrightness.setObjectName("GLBoost")
		self.glbrightness.setValue(0.1)
		self.glbrightness.setValue(0.0)
		gltab.vbl.addWidget(self.glbrightness)
	
		return gltab
	
	def get_main_tab(self):
		if ( self.maintab == None ):
			self.maintab = QtGui.QWidget()
			maintab = self.maintab
			maintab.vbl = QtGui.QVBoxLayout(self.maintab)
			maintab.vbl.setMargin(0)
			maintab.vbl.setSpacing(6)
			maintab.vbl.setObjectName("Main")
			
			self.scale = ValSlider(maintab,(0.01,30.0),"Zoom:")
			self.scale.setObjectName("scale")
			self.scale.setValue(1.0)
			maintab.vbl.addWidget(self.scale)
			
			self.hbl_color = QtGui.QHBoxLayout()
			self.hbl_color.setMargin(0)
			self.hbl_color.setSpacing(6)
			self.hbl_color.setObjectName("Material")
			maintab.vbl.addLayout(self.hbl_color)
			
			self.color_label = QtGui.QLabel()
			self.color_label.setText('Material')
			self.hbl_color.addWidget(self.color_label)
			
			self.cbb = QtGui.QComboBox(maintab)
			self.hbl_color.addWidget(self.cbb)
	
			self.hbl_trans = QtGui.QHBoxLayout()
			self.hbl_trans.setMargin(0)
			self.hbl_trans.setSpacing(6)
			self.hbl_trans.setObjectName("Trans")
			maintab.vbl.addLayout(self.hbl_trans)
			
			self.x_label = QtGui.QLabel()
			self.x_label.setText('x')
			self.hbl_trans.addWidget(self.x_label)
			
			self.x_trans = QtGui.QDoubleSpinBox(self)
			self.x_trans.setMinimum(-10000)
			self.x_trans.setMaximum(10000)
			self.x_trans.setValue(0.0)
			self.hbl_trans.addWidget(self.x_trans)
			
			self.y_label = QtGui.QLabel()
			self.y_label.setText('y')
			self.hbl_trans.addWidget(self.y_label)
			
			self.y_trans = QtGui.QDoubleSpinBox(maintab)
			self.y_trans.setMinimum(-10000)
			self.y_trans.setMaximum(10000)
			self.y_trans.setValue(0.0)
			self.hbl_trans.addWidget(self.y_trans)
			
			
			self.z_label = QtGui.QLabel()
			self.z_label.setText('z')
			self.hbl_trans.addWidget(self.z_label)
			
			self.z_trans = QtGui.QDoubleSpinBox(maintab)
			self.z_trans.setMinimum(-10000)
			self.z_trans.setMaximum(10000)
			self.z_trans.setValue(0.0)
			self.hbl_trans.addWidget(self.z_trans)
			
			self.hbl_src = QtGui.QHBoxLayout()
			self.hbl_src.setMargin(0)
			self.hbl_src.setSpacing(6)
			self.hbl_src.setObjectName("hbl")
			maintab.vbl.addLayout(self.hbl_src)
			
			self.label_src = QtGui.QLabel()
			self.label_src.setText('Rotation Convention')
			self.hbl_src.addWidget(self.label_src)
			
			self.src = QtGui.QComboBox(maintab)
			self.load_src_options(self.src)
			self.hbl_src.addWidget(self.src)
			
			# set default value -1 ensures that the val slider is updated the first time it is created
			self.az = ValSlider(self,(-360.0,360.0),"az",-1)
			self.az.setObjectName("az")
			maintab.vbl.addWidget(self.az)
			
			self.alt = ValSlider(self,(-180.0,180.0),"alt",-1)
			self.alt.setObjectName("alt")
			maintab.vbl.addWidget(self.alt)
			
			self.phi = ValSlider(self,(-360.0,360.0),"phi",-1)
			self.phi.setObjectName("phi")
			maintab.vbl.addWidget(self.phi)
		
			self.current_src = EULER_EMAN
		
		return self.maintab

	def set_xy_trans(self, x, y):
		self.x_trans.setValue(x)
		self.y_trans.setValue(y)
	
	def set_xyz_trans(self,x,y,z):
		self.x_trans.setValue(x)
		self.y_trans.setValue(y)
		self.z_trans.setValue(z)
		
	def set_translate_scale(self, xscale,yscale,zscale):
		self.x_trans.setSingleStep(xscale)
		self.y_trans.setSingleStep(yscale)
		self.z_trans.setSingleStep(zscale)

	def update_rotations(self,t3d):
		convention = str( self.src.currentText() )
		#FIXME: Transform.get_rotation() wants a string sometimes and a EulerType other times
		try:
			rot = t3d.get_rotation(str(self.src_map[convention]))
		except Exception as e: #doing a quick fix
			print(e)
			print("Developers: This catches a large range of exceptions... a better way surely exists")
			rot = t3d.get_rotation(self.src_map[convention])
		
		if ( self.src_map[convention] == EULER_SPIN ):
			self.n3.setValue(rot[self.n3.getLabel()],True)
		
		self.az.setValue(rot[self.az.getLabel()],True)
		self.alt.setValue(rot[self.alt.getLabel()],True)
		self.phi.setValue(rot[self.phi.getLabel()],True)
	
	def slider_rotate(self):
		self.target.load_rotation(self.get_current_rotation())
	
	def get_current_rotation(self):
		convention = self.src.currentText()
		rot = {}
		if ( self.current_src == EULER_SPIN ):
			rot[self.az.getLabel()] = self.az.getValue()
			
			n1 = self.alt.getValue()
			n2 = self.phi.getValue()
			n3 = self.n3.getValue()
			
			norm = sqrt(n1*n1 + n2*n2 + n3*n3)
			
			n1 /= norm
			n2 /= norm
			n3 /= norm
			
			rot[self.alt.getLabel()] = n1
			rot[self.phi.getLabel()] = n2
			rot[self.n3.getLabel()] = n3
			
		else:
			rot[self.az.getLabel()] = self.az.getValue()
			rot[self.alt.getLabel()] = self.alt.getValue()
			rot[self.phi.getLabel()] = self.phi.getValue()
		
		return Transform(self.current_src, rot)
	
	def set_src(self, val):
		t3d = self.get_current_rotation()
		
		if (self.n3_showing) :
			self.vbl.removeWidget(self.n3)
			self.n3.deleteLater()
			self.n3_showing = False
			self.az.setRange(-360,360)
			self.alt.setRange(-180,180)
			self.phi.setRange(-360,660)
		
		if ( self.src_map[str(val)] == EULER_SPIDER ):
			self.az.setLabel('phi')
			self.alt.setLabel('theta')
			self.phi.setLabel('psi')
		elif ( self.src_map[str(val)] == EULER_EMAN ):
			self.az.setLabel('az')
			self.alt.setLabel('alt')
			self.phi.setLabel('phi')
		elif ( self.src_map[str(val)] == EULER_IMAGIC ):
			self.az.setLabel('alpha')
			self.alt.setLabel('beta')
			self.phi.setLabel('gamma')
		elif ( self.src_map[str(val)] == EULER_XYZ ):
			self.az.setLabel('xtilt')
			self.alt.setLabel('ytilt')
			self.phi.setLabel('ztilt')
		elif ( self.src_map[str(val)] == EULER_MRC ):
			self.az.setLabel('phi')
			self.alt.setLabel('theta')
			self.phi.setLabel('omega')
		elif ( self.src_map[str(val)] == EULER_SPIN ):
			self.az.setLabel('omega')
			self.alt.setRange(-1,1)
			self.phi.setRange(-1,1)
			
			self.alt.setLabel('n1')
			self.phi.setLabel('n2')
			
			self.n3 = ValSlider(self,(-360.0,360.0),"n3",-1)
			self.n3.setRange(-1,1)
			self.n3.setObjectName("n3")
			self.vbl.addWidget(self.n3)
			QtCore.QObject.connect(self.n3, QtCore.SIGNAL("valueChanged"), self.slider_rotate)
			self.n3_showing = True
		
		self.current_src = self.src_map[str(val)]
		self.update_rotations(t3d)
	
	def load_src_options(self,widgit):
		self.load_src()
		for i in self.src_strings:
			widgit.addItem(i)
	
	# read src as 'supported rotation conventions'
	def load_src(self):
		# supported_rot_conventions
		src_flags = []
		src_flags.append(EULER_EMAN)
		src_flags.append(EULER_SPIDER)
		src_flags.append(EULER_IMAGIC)
		src_flags.append(EULER_MRC)
		src_flags.append(EULER_SPIN)
		src_flags.append(EULER_XYZ)
		
		self.src_strings = []
		self.src_map = {}
		for i in src_flags:
			self.src_strings.append(str(i))
			self.src_map[str(i)] = i
		
	
	def setColors(self,colors,current_color):
		a = 0
		for i in colors:
			self.cbb.addItem(i)
			if ( i == current_color):
				self.cbb.setCurrentIndex(a)
			a += 1

	def set_scale(self,newscale):
		self.scale.setValue(newscale)