def home_data(cls): if platform.system() == "Windows": return resources.package_dirname( "orangecontrib.xoppy.util") + "\data/" else: return resources.package_dirname( "orangecontrib.xoppy.util") + "/data/"
def home_bin(cls): if platform.system() == "Windows": return resources.package_dirname( "orangecontrib.xoppy.util") + "\\bin\windows\\" else: return resources.package_dirname( "orangecontrib.xoppy.util") + "/bin/" + str(sys.platform) + "/"
class OWthermal_load(OWAbstractThermalLoadConverter): name = "Thermal load data converter" id = "thermal_load_data_converter" description = "Converter from FE simulations to Shadow format" icon = "icons/thermal_load.png" author = "Aljosa Hafner" author_email = "aljosa.hafner(@at@)ceric-eric.eu" priority = 2 category = "" keywords = ["thermal", "load", "converter"] # outputs = [{"name": "PreProcessor_Data", # "type": ShadowPreProcessorData, # "doc": "PreProcessor Data", # "id": "PreProcessor_Data"}] #TODO: Here comes the usage diagram, not so urgent, using the one from flux calculator at the moment... usage_path = os.path.join( resources.package_dirname( "orangecontrib.elettra.shadow.widgets.extension"), "misc", "thermal_load_usage.png") def __init__(self): super().__init__() def get_usage_path(self): return self.usage_path def get_axis_um(self): return self.workspace_units_label
class OWheight_profile_simulator(OWAbstractHeightErrorProfileSimulator): name = "Height Profile Simulator" id = "height_profile_simulator" description = "Calculation of mirror surface height profile" icon = "icons/simulator.png" author = "Luca Rebuffi" maintainer_email = "[email protected]; [email protected]" priority = 1 category = "" keywords = ["height_profile_simulator"] outputs = [{"name": "PreProcessor_Data", "type": SRWPreProcessorData, "doc": "PreProcessor Data", "id": "PreProcessor_Data"}] usage_path = os.path.join(resources.package_dirname("orangecontrib.srw.widgets.gui"), "misc", "height_error_profile_usage.png") def __init__(self): super().__init__() def get_usage_path(self): return self.usage_path def write_error_profile_file(self): SU.write_error_profile_file(self.zz, self.xx, self.yy, self.heigth_profile_file_name) def send_data(self, dimension_x, dimension_y): self.send("PreProcessor_Data", SRWPreProcessorData(error_profile_data=SRWErrorProfileData(error_profile_data_file=self.heigth_profile_file_name, error_profile_x_dim=dimension_x, error_profile_y_dim=dimension_y)))
def get_doc(self): print("help pressed.") home_doc = resources.package_dirname("orangecontrib.oasyscrystalpy") + "/doc_files/" filename1 = os.path.join(home_doc,'IdealPhaseRetarder'+'.txt') print("Opening file %s"%filename1) if sys.platform == 'darwin': command = "open -a TextEdit "+filename1+" &" elif sys.platform == 'linux': command = "gedit "+filename1+" &" os.system(command)
def get_doc(self): print("help pressed.") home_doc = resources.package_dirname( "orangecontrib.oasysaddontemplate") + "/doc_files/" filename1 = os.path.join(home_doc, 'dyndiffraction' + '.txt') print("Opening file %s" % filename1) if sys.platform == 'darwin': command = "open -a TextEdit " + filename1 + " &" elif sys.platform == 'linux': command = "gedit " + filename1 + " &" os.system(command)
def get_doc(self): print("Crystal: help pressed.\n") home_doc = resources.package_dirname("orangecontrib.oasyscrystalpy") + "/doc_files/" filename1 = os.path.join(home_doc, 'CrystalActive'+'.txt') print("Crystal: Opening file %s\n" % filename1) if sys.platform == 'darwin': command = "open -a TextEdit "+filename1+" &" elif sys.platform == 'linux': command = "gedit "+filename1+" &" else: raise Exception("Crystal: sys.platform did not yield an acceptable value!\n") os.system(command)
def plot_emtpy(self, progressBarValue, plot_canvas_index): if self.plot_canvas[plot_canvas_index] is None: widget = QWidget() widget.setLayout(QHBoxLayout()) label = QLabel(widget) label.setPixmap(QPixmap(QImage(os.path.join(resources.package_dirname("orangecontrib.shadow.widgets.special_elements"), "icons", "no_result.png")))) widget.layout().addWidget(label) self.plot_canvas[plot_canvas_index] = widget self.tab[plot_canvas_index].layout().addWidget(self.plot_canvas[plot_canvas_index]) self.progressBarSet(progressBarValue)
class OWMultipleHeightProfileSimulatorT( OWAbstractMultipleHeightProfileSimulatorT): name = "Multiple Height Profile Simulator (T)" id = "height_profile_simulator_t" icon = "icons/simulator_T.png" description = "Calculation of mirror surface height profile" author = "Luca Rebuffi" maintainer_email = "*****@*****.**" priority = 3 category = "" keywords = ["height_profile_simulator"] outputs = [{ "name": "PreProcessor_Data", "type": SRWPreProcessorData, "doc": "PreProcessor Data", "id": "PreProcessor_Data" }, { "name": "Files", "type": list, "doc": "Files", "id": "Files" }] usage_path = os.path.join( resources.package_dirname("orangecontrib.srw.widgets.gui"), "misc", "height_error_profile_usage.png") def __init__(self): super().__init__() def get_usage_path(self): return self.usage_path def write_error_profile_file(self, zz, xx, yy, outFile): SU.write_error_profile_file(zz, xx, yy, outFile) def send_data(self, height_profile_file_names, dimension_x, dimension_y): self.send( "PreProcessor_Data", SRWPreProcessorData(error_profile_data=SRWErrorProfileData( error_profile_data_file=height_profile_file_names, error_profile_x_dim=dimension_x, error_profile_y_dim=dimension_y))) self.send("Files", height_profile_file_names) def get_file_format(self): return ".dat"
def plot_image(self, image_url, progressBarValue, tabs_canvas_index): layout = self.tabs[tabs_canvas_index].layout() for i in reversed(range(layout.count())): widgetToRemove = layout.itemAt( i ).widget() layout.removeWidget(widgetToRemove) widgetToRemove.setParent( None ) if image_url is None: label = QLabel(self.tabs[tabs_canvas_index]) label.setPixmap(QPixmap(QImage(resources.package_dirname("orangecontrib.xrayserver.widgets.xrayserver") + "/icons/no_standing_waves_result.png"))) layout.addWidget(label) else: layout.addWidget(FigureWidget(image_url)) self.tabs[tabs_canvas_index].setLayout(layout)
def __init__(self, parent=None): QDialog.__init__(self, parent) self.setWindowTitle('Symmetry vs Longitudinal Position') layout = QVBoxLayout(self) label = QLabel("") file = os.path.join( resources.package_dirname( "orangecontrib.srw.widgets.light_sources"), "misc", "symmetry.png") label.setPixmap(QPixmap(file)) bbox = QDialogButtonBox(QDialogButtonBox.Ok) bbox.accepted.connect(self.accept) layout.addWidget(label) layout.addWidget(bbox)
def plot_image(self, image_url, progressBarValue, tabs_canvas_index): layout = self.tabs[tabs_canvas_index].layout() for i in reversed(range(layout.count())): widgetToRemove = layout.itemAt(i).widget() layout.removeWidget(widgetToRemove) widgetToRemove.setParent(None) if image_url is None: label = QLabel(self.tabs[tabs_canvas_index]) label.setPixmap( QPixmap( QImage( resources.package_dirname( "orangecontrib.xrayserver.widgets.xrayserver") + "/icons/no_standing_waves_result.png"))) layout.addWidget(label) else: layout.addWidget(FigureWidget(image_url)) self.tabs[tabs_canvas_index].setLayout(layout)
def home_bin(cls): return resources.package_dirname("orangecontrib.xoppy.util") + "/bin/" + str(sys.platform) + "/"
def home_doc(cls): return resources.package_dirname("orangecontrib.xoppy.util") + "/doc_txt/"
class OWMultipleHeightProfileSimulatorS( OWAbstractMultipleHeightProfileSimulatorS): name = "Multiple Height Profile Simulator (S)" id = "height_profile_simulator_s" icon = "icons/simulator_S.png" description = "Calculation of mirror surface height profile" author = "Luca Rebuffi" maintainer_email = "*****@*****.**" priority = 7.2 category = "" keywords = ["height_profile_simulator"] outputs = [{ "name": "PreProcessor_Data", "type": ShadowPreProcessorData, "doc": "PreProcessor Data", "id": "PreProcessor_Data" }, { "name": "Files", "type": list, "doc": "Files", "id": "Files" }] usage_path = os.path.join( resources.package_dirname("orangecontrib.shadow.widgets.gui"), "misc", "height_error_profile_usage.png") def __init__(self): super().__init__() def after_change_workspace_units(self): self.si_to_user_units = 1 / self.workspace_units_to_m self.axis.set_xlabel("X [" + self.workspace_units_label + "]") self.axis.set_ylabel("Y [" + self.workspace_units_label + "]") label = self.le_dimension_y.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_step_y.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_correlation_length_y.parent().layout().itemAt( 0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_dimension_x.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_step_x.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_correlation_length_x.parent().layout().itemAt( 0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_conversion_factor_y_x.parent().layout().itemAt( 0).widget() label.setText("Conversion from file to " + self.workspace_units_label + "\n(Abscissa)") label = self.le_conversion_factor_y_y.parent().layout().itemAt( 0).widget() label.setText("Conversion from file to " + self.workspace_units_label + "\n(Height Profile Values)") label = self.le_conversion_factor_x_x.parent().layout().itemAt( 0).widget() label.setText("Conversion from file to " + self.workspace_units_label + "\n(Abscissa)") label = self.le_conversion_factor_x_y.parent().layout().itemAt( 0).widget() label.setText("Conversion from file to " + self.workspace_units_label + "\n(Height Profile Values)") label = self.le_new_length_y_1.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_new_length_y_2.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_new_length_x_1.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_new_length_x_2.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") def get_usage_path(self): return self.usage_path def write_error_profile_file(self, zz, xx, yy, outFile): ST.write_shadow_surface(zz, xx, yy, outFile) def send_data(self, height_profile_file_names, dimension_x, dimension_y): self.send( "PreProcessor_Data", ShadowPreProcessorData( error_profile_data_file=height_profile_file_names, error_profile_x_dim=dimension_x, error_profile_y_dim=dimension_y)) self.send("Files", height_profile_file_names) def get_file_format(self): return ".dat"
def home_bin(cls): if platform.system() == "Windows": return resources.package_dirname("orangecontrib.xoppy.util") + "\\bin\windows\\" else: return resources.package_dirname("orangecontrib.xoppy.util") + "/bin/" + str(sys.platform) + "/"
class OWxsh_prerefl(OWWidget): name = "PreRefl" id = "xsh_prerefl" description = "Calculation of mirror reflectivity profile" icon = "icons/prerefl.png" author = "create_widget.py" maintainer_email = "*****@*****.**" priority = 2 category = "" keywords = ["xoppy", "xsh_prerefl"] outputs = [{ "name": "PreProcessor_Data", "type": ShadowPreProcessorData, "doc": "PreProcessor Data", "id": "PreProcessor_Data" }] want_main_area = False SYMBOL = Setting("SiC") DENSITY = Setting(3.217) SHADOW_FILE = Setting("reflec.dat") E_MIN = Setting(100.0) E_MAX = Setting(20000.0) E_STEP = Setting(100.0) usage_path = os.path.join( resources.package_dirname("orangecontrib.shadow.widgets.gui"), "misc", "prerefl_usage.png") def __init__(self): super().__init__() self.runaction = widget.OWAction("Compute", self) self.runaction.triggered.connect(self.compute) self.addAction(self.runaction) self.setFixedWidth(550) self.setFixedHeight(550) gui.separator(self.controlArea) box0 = gui.widgetBox(self.controlArea, "", orientation="horizontal") #widget buttons: compute, set defaults, help button = gui.button(box0, self, "Compute", callback=self.compute) button.setFixedHeight(45) button = gui.button(box0, self, "Defaults", callback=self.defaults) button.setFixedHeight(45) button = gui.button(box0, self, "Help", callback=self.help1) button.setFixedHeight(45) gui.separator(self.controlArea) tabs_setting = oasysgui.tabWidget(self.controlArea) tab_bas = oasysgui.createTabPage(tabs_setting, "Reflectivity Settings") tab_out = oasysgui.createTabPage(tabs_setting, "Output") tab_usa = oasysgui.createTabPage(tabs_setting, "Use of the Widget") tab_usa.setStyleSheet("background-color: white;") usage_box = oasysgui.widgetBox(tab_usa, "", addSpace=True, orientation="horizontal") label = QLabel("") label.setAlignment(Qt.AlignCenter) label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) label.setPixmap(QPixmap(self.usage_path)) usage_box.layout().addWidget(label) box = oasysgui.widgetBox(tab_bas, "Reflectivity Parameters", orientation="vertical") idx = -1 #widget index 0 idx += 1 oasysgui.lineEdit(box, self, "SYMBOL", label=self.unitLabels()[idx], addSpace=True, labelWidth=350, orientation="horizontal", callback=self.set_Density) self.show_at(self.unitFlags()[idx], box) #widget index 1 idx += 1 oasysgui.lineEdit(box, self, "DENSITY", label=self.unitLabels()[idx], addSpace=True, valueType=float, validator=QDoubleValidator(), labelWidth=350, orientation="horizontal") self.show_at(self.unitFlags()[idx], box) #widget index 2 idx += 1 box_2 = oasysgui.widgetBox(box, "", addSpace=True, orientation="horizontal") self.le_SHADOW_FILE = oasysgui.lineEdit(box_2, self, "SHADOW_FILE", label=self.unitLabels()[idx], addSpace=True, labelWidth=180, orientation="horizontal") gui.button(box_2, self, "...", callback=self.selectFile) self.show_at(self.unitFlags()[idx], box) #widget index 3 idx += 1 oasysgui.lineEdit(box, self, "E_MIN", label=self.unitLabels()[idx], addSpace=True, valueType=float, validator=QDoubleValidator(), labelWidth=350, orientation="horizontal") self.show_at(self.unitFlags()[idx], box) #widget index 4 idx += 1 oasysgui.lineEdit(box, self, "E_MAX", label=self.unitLabels()[idx], addSpace=True, valueType=float, validator=QDoubleValidator(), labelWidth=350, orientation="horizontal") self.show_at(self.unitFlags()[idx], box) #widget index 5 idx += 1 oasysgui.lineEdit(box, self, "E_STEP", label=self.unitLabels()[idx], addSpace=True, valueType=float, validator=QDoubleValidator(), labelWidth=350, orientation="horizontal") self.show_at(self.unitFlags()[idx], box) self.process_showers() self.shadow_output = oasysgui.textArea() out_box = oasysgui.widgetBox(tab_out, "System Output", addSpace=True, orientation="horizontal", height=400) out_box.layout().addWidget(self.shadow_output) gui.rubber(self.controlArea) def unitLabels(self): return [ 'Element/Compound formula', 'Density [ g/cm3 ]', 'File for SHADOW (trace):', 'Minimum energy [eV]', 'Maximum energy [eV]', 'Energy step [eV]' ] def unitFlags(self): return ['True', 'True', 'True', 'True', 'True', 'True'] def selectFile(self): self.le_SHADOW_FILE.setText( oasysgui.selectFileFromDialog( self, self.SHADOW_FILE, "Select Output File", file_extension_filter="Data Files (*.dat)")) def set_Density(self): if not self.SYMBOL is None: if not self.SYMBOL.strip() == "": self.SYMBOL = self.SYMBOL.strip() self.DENSITY = ShadowPhysics.getMaterialDensity(self.SYMBOL) def compute(self): try: sys.stdout = EmittingStream(textWritten=self.writeStdOut) self.checkFields() tmp = prerefl(interactive=False, SYMBOL=self.SYMBOL, DENSITY=self.DENSITY, FILE=congruence.checkFileName(self.SHADOW_FILE), E_MIN=self.E_MIN, E_MAX=self.E_MAX, E_STEP=self.E_STEP) self.send( "PreProcessor_Data", ShadowPreProcessorData(prerefl_data_file=self.SHADOW_FILE)) except Exception as exception: QMessageBox.critical(self, "Error", str(exception), QMessageBox.Ok) def checkFields(self): self.SYMBOL = ShadowPhysics.checkCompoundName(self.SYMBOL) self.DENSITY = congruence.checkStrictlyPositiveNumber( self.DENSITY, "Density") self.E_MIN = congruence.checkPositiveNumber(self.E_MIN, "Minimum Energy") self.E_MAX = congruence.checkStrictlyPositiveNumber( self.E_MAX, "Maximum Energy") self.E_STEP = congruence.checkStrictlyPositiveNumber( self.E_STEP, "Energy step") congruence.checkLessOrEqualThan(self.E_MIN, self.E_MAX, "Minimum Energy", "Maximum Energy") congruence.checkDir(self.SHADOW_FILE) def defaults(self): self.resetSettings() self.compute() return def help1(self): print("help pressed.") xoppy_doc('xsh_prerefl') def writeStdOut(self, text): cursor = self.shadow_output.textCursor() cursor.movePosition(QTextCursor.End) cursor.insertText(text) self.shadow_output.setTextCursor(cursor) self.shadow_output.ensureCursorVisible()
def home_data(cls): return resources.package_dirname("orangecontrib.xoppy.util") + "/data/"
class OWxsh_bragg(OWWidget): name = "Bragg" id = "xsh_bragg" description = "Calculation of crystal diffraction profile" icon = "icons/bragg.png" author = "create_widget.py" maintainer_email = "*****@*****.**" priority = 1 category = "" keywords = ["oasys", "bragg"] outputs = [{ "name": "PreProcessor_Data", "type": ShadowPreProcessorData, "doc": "PreProcessor Data", "id": "PreProcessor_Data" }] want_main_area = False DESCRIPTOR = Setting(0) H_MILLER_INDEX = Setting(1) K_MILLER_INDEX = Setting(1) L_MILLER_INDEX = Setting(1) TEMPERATURE_FACTOR = Setting(1.0) E_MIN = Setting(5000.0) E_MAX = Setting(15000.0) E_STEP = Setting(100.0) SHADOW_FILE = Setting("bragg.dat") crystals = [ "Si", "Si_NIST", "Si2", "Ge", "Diamond", "GaAs", "GaSb", "GaP", "InAs", "InP", "InSb", "SiC", "NaCl", "CsF", "LiF", "KCl", "CsCl", "Be", "Graphite", "PET", "Beryl", "KAP", "RbAP", "TlAP", "Muscovite", "AlphaQuartz", "Copper", "LiNbO3", "Platinum", "Gold", "Sapphire", "LaB6", "LaB6_NIST", "KTP", "AlphaAlumina", "Aluminum", "Iron", "Titanium" ] usage_path = os.path.join( resources.package_dirname("orangecontrib.shadow.widgets.gui"), "misc", "bragg_usage.png") def __init__(self): super().__init__() self.runaction = widget.OWAction("Compute", self) self.runaction.triggered.connect(self.compute) self.addAction(self.runaction) self.setFixedWidth(550) self.setFixedHeight(550) idx = -1 gui.separator(self.controlArea) box0 = oasysgui.widgetBox(self.controlArea, "", orientation="horizontal") #widget buttons: compute, set defaults, help button = gui.button(box0, self, "Compute", callback=self.compute) button.setFixedHeight(45) button = gui.button(box0, self, "Defaults", callback=self.defaults) button.setFixedHeight(45) button = gui.button(box0, self, "Help", callback=self.help1) button.setFixedHeight(45) gui.separator(self.controlArea) tabs_setting = oasysgui.tabWidget(self.controlArea) tab_bas = oasysgui.createTabPage(tabs_setting, "Crystal Settings") tab_out = oasysgui.createTabPage(tabs_setting, "Output") tab_usa = oasysgui.createTabPage(tabs_setting, "Use of the Widget") tab_usa.setStyleSheet("background-color: white;") usage_box = oasysgui.widgetBox(tab_usa, "", addSpace=True, orientation="horizontal") label = QLabel("") label.setAlignment(Qt.AlignCenter) label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) label.setPixmap(QPixmap(self.usage_path)) usage_box.layout().addWidget(label) #widget index 0 idx += 1 box = oasysgui.widgetBox(tab_bas, "Crystal Parameters", orientation="vertical") gui.comboBox(box, self, "DESCRIPTOR", label=self.unitLabels()[idx], addSpace=True, items=self.crystals, sendSelectedValue=False, valueType=int, orientation="horizontal", labelWidth=350) self.show_at(self.unitFlags()[idx], box) #widget index 1 idx += 1 box_miller = oasysgui.widgetBox(box, "", orientation="horizontal") oasysgui.lineEdit(box_miller, self, "H_MILLER_INDEX", label="Miller Indices [h k l]", addSpace=True, valueType=int, validator=QIntValidator(), labelWidth=350, orientation="horizontal") self.show_at(self.unitFlags()[idx], box_miller) #widget index 2 idx += 1 oasysgui.lineEdit(box_miller, self, "K_MILLER_INDEX", addSpace=True, valueType=int, validator=QIntValidator()) self.show_at(self.unitFlags()[idx], box) #widget index 3 idx += 1 oasysgui.lineEdit(box_miller, self, "L_MILLER_INDEX", addSpace=True, valueType=int, validator=QIntValidator(), orientation="horizontal") self.show_at(self.unitFlags()[idx], box) gui.separator(box) #widget index 4 idx += 1 oasysgui.lineEdit(box, self, "TEMPERATURE_FACTOR", label=self.unitLabels()[idx], addSpace=True, valueType=float, validator=QDoubleValidator(), labelWidth=350, orientation="horizontal") self.show_at(self.unitFlags()[idx], box) #widget index 5 idx += 1 oasysgui.lineEdit(box, self, "E_MIN", label=self.unitLabels()[idx], addSpace=True, valueType=float, validator=QDoubleValidator(), labelWidth=350, orientation="horizontal") self.show_at(self.unitFlags()[idx], box) #widget index 6 idx += 1 oasysgui.lineEdit(box, self, "E_MAX", label=self.unitLabels()[idx], addSpace=True, valueType=float, validator=QDoubleValidator(), labelWidth=350, orientation="horizontal") self.show_at(self.unitFlags()[idx], box) #widget index 7 idx += 1 oasysgui.lineEdit(box, self, "E_STEP", label=self.unitLabels()[idx], addSpace=True, valueType=float, validator=QDoubleValidator(), labelWidth=350, orientation="horizontal") self.show_at(self.unitFlags()[idx], box) #widget index 8 idx += 1 box_2 = oasysgui.widgetBox(box, "", addSpace=True, orientation="horizontal") self.le_SHADOW_FILE = oasysgui.lineEdit(box_2, self, "SHADOW_FILE", label=self.unitLabels()[idx], addSpace=True, labelWidth=180, orientation="horizontal") gui.button(box_2, self, "...", callback=self.selectFile) self.show_at(self.unitFlags()[idx], box) self.shadow_output = oasysgui.textArea() out_box = oasysgui.widgetBox(tab_out, "System Output", addSpace=True, orientation="horizontal", height=400) out_box.layout().addWidget(self.shadow_output) self.process_showers() gui.rubber(self.controlArea) def unitLabels(self): return [ 'Crystal descriptor', 'H miller index', 'K miller index', 'L miller index', 'Temperature factor', 'Minimum energy [eV]', 'Maximum energy [eV]', 'Energy step [eV]', 'File name (for SHADOW)' ] def unitFlags(self): return [ 'True', 'True', 'True', 'True', 'True', 'True', 'True', 'True', 'True' ] def selectFile(self): self.le_SHADOW_FILE.setText( oasysgui.selectFileFromDialog(self, self.SHADOW_FILE, "Select Output File")) def compute(self): try: sys.stdout = EmittingStream(textWritten=self.writeStdOut) self.checkFields() if not self.DESCRIPTOR == 18: # GRAPHITE tmp = bragg(interactive=False, DESCRIPTOR=self.crystals[self.DESCRIPTOR], H_MILLER_INDEX=self.H_MILLER_INDEX, K_MILLER_INDEX=self.K_MILLER_INDEX, L_MILLER_INDEX=self.L_MILLER_INDEX, TEMPERATURE_FACTOR=self.TEMPERATURE_FACTOR, E_MIN=self.E_MIN, E_MAX=self.E_MAX, E_STEP=self.E_STEP, SHADOW_FILE=congruence.checkFileName( self.SHADOW_FILE)) else: OWxsh_bragg.new_bragg( H_MILLER_INDEX=self.H_MILLER_INDEX, K_MILLER_INDEX=self.K_MILLER_INDEX, L_MILLER_INDEX=self.L_MILLER_INDEX, TEMPERATURE_FACTOR=self.TEMPERATURE_FACTOR, E_MIN=self.E_MIN, E_MAX=self.E_MAX, E_STEP=self.E_STEP, SHADOW_FILE=congruence.checkFileName(self.SHADOW_FILE)) self.send("PreProcessor_Data", ShadowPreProcessorData(bragg_data_file=self.SHADOW_FILE)) except Exception as exception: QMessageBox.critical(self, "Error", str(exception), QMessageBox.Ok) if self.IS_DEVELOP: raise exception @classmethod def new_bragg(cls, DESCRIPTOR="Graphite", H_MILLER_INDEX=0, K_MILLER_INDEX=0, L_MILLER_INDEX=2, TEMPERATURE_FACTOR=1.0, E_MIN=5000.0, E_MAX=15000.0, E_STEP=100.0, SHADOW_FILE="bragg.dat"): """ SHADOW preprocessor for crystals - python+xraylib version -""" # retrieve physical constants needed codata = scipy.constants.codata.physical_constants codata_e2_mc2, tmp1, tmp2 = codata["classical electron radius"] # or, hard-code them # In [179]: print("codata_e2_mc2 = %20.11e \n" % codata_e2_mc2 ) # codata_e2_mc2 = 2.81794032500e-15 fileout = SHADOW_FILE descriptor = DESCRIPTOR hh = int(H_MILLER_INDEX) kk = int(K_MILLER_INDEX) ll = int(L_MILLER_INDEX) temper = float(TEMPERATURE_FACTOR) emin = float(E_MIN) emax = float(E_MAX) estep = float(E_STEP) # # end input section, start calculations # f = open(fileout, 'wt') cryst = xraylib.Crystal_GetCrystal(descriptor) volume = cryst['volume'] #test crystal data - not needed itest = 1 if itest: if (cryst == None): sys.exit(1) print(" Unit cell dimensions are %f %f %f" % (cryst['a'], cryst['b'], cryst['c'])) print(" Unit cell angles are %f %f %f" % (cryst['alpha'], cryst['beta'], cryst['gamma'])) print(" Unit cell volume is %f A^3" % volume) print(" Atoms at:") print(" Z fraction X Y Z") for i in range(cryst['n_atom']): atom = cryst['atom'][i] print(" %3i %f %f %f %f" % (atom['Zatom'], atom['fraction'], atom['x'], atom['y'], atom['z'])) print(" ") volume = volume * 1e-8 * 1e-8 * 1e-8 # in cm^3 #flag ZincBlende f.write("%i " % 0) #1/V*electronRadius f.write("%e " % ((1e0 / volume) * (codata_e2_mc2 * 1e2))) #dspacing dspacing = xraylib.Crystal_dSpacing(cryst, hh, kk, ll) f.write("%e " % (dspacing * 1e-8)) f.write("\n") #Z's atom = cryst['atom'] f.write("%i " % atom[0]["Zatom"]) f.write("%i " % atom[-1]["Zatom"]) f.write("%e " % temper) # temperature parameter f.write("\n") ga = (1e0+0j) + cmath.exp(1j*cmath.pi*(hh+kk)) \ + cmath.exp(1j*cmath.pi*(hh+ll)) \ + cmath.exp(1j*cmath.pi*(kk+ll)) gb = ga * cmath.exp(1j * cmath.pi * 0.5 * (hh + kk + ll)) ga_bar = ga.conjugate() gb_bar = gb.conjugate() f.write("(%20.11e,%20.11e ) \n" % (ga.real, ga.imag)) f.write("(%20.11e,%20.11e ) \n" % (ga_bar.real, ga_bar.imag)) f.write("(%20.11e,%20.11e ) \n" % (gb.real, gb.imag)) f.write("(%20.11e,%20.11e ) \n" % (gb_bar.real, gb_bar.imag)) zetas = numpy.array([atom[0]["Zatom"], atom[-1]["Zatom"]]) for zeta in zetas: xx01 = 1e0 / 2e0 / dspacing xx00 = xx01 - 0.1 xx02 = xx01 + 0.1 yy00 = xraylib.FF_Rayl(int(zeta), xx00) yy01 = xraylib.FF_Rayl(int(zeta), xx01) yy02 = xraylib.FF_Rayl(int(zeta), xx02) xx = numpy.array([xx00, xx01, xx02]) yy = numpy.array([yy00, yy01, yy02]) fit = numpy.polyfit(xx, yy, 2) #print "zeta: ",zeta #print "z,xx,YY: ",zeta,xx,yy #print "fit: ",fit[::-1] # reversed coeffs #print "fit-tuple: ",(tuple(fit[::-1].tolist())) # reversed coeffs #print("fit-tuple: %e %e %e \n" % (tuple(fit[::-1].tolist())) ) # reversed coeffs f.write("%e %e %e \n" % (tuple(fit[::-1].tolist()))) # reversed coeffs npoint = int((emax - emin) / estep + 1) f.write(("%i \n") % npoint) for i in range(npoint): energy = (emin + estep * i) f1a = xraylib.Fi(int(zetas[0]), energy * 1e-3) f2a = xraylib.Fii(int(zetas[0]), energy * 1e-3) f1b = xraylib.Fi(int(zetas[1]), energy * 1e-3) f2b = xraylib.Fii(int(zetas[1]), energy * 1e-3) out = numpy.array([energy, f1a, abs(f2a), f1b, abs(f2b)]) f.write(("%20.11e %20.11e %20.11e \n %20.11e %20.11e \n") % (tuple(out.tolist()))) f.close() print("File written to disk: %s" % fileout) def checkFields(self): if type(self.DESCRIPTOR) == str: # back compatibility with old version try: self.DESCRIPTOR = self.crystals.index(self.DESCRIPTOR) except: self.DESCRIPTOR = 0 self.H_MILLER_INDEX = congruence.checkNumber(self.H_MILLER_INDEX, "H miller index") self.K_MILLER_INDEX = congruence.checkNumber(self.K_MILLER_INDEX, "K miller index") self.L_MILLER_INDEX = congruence.checkNumber(self.L_MILLER_INDEX, "L miller index") self.TEMPERATURE_FACTOR = congruence.checkNumber( self.TEMPERATURE_FACTOR, "Temperature factor") self.E_MIN = congruence.checkPositiveNumber(self.E_MIN, "Minimum energy") self.E_MAX = congruence.checkStrictlyPositiveNumber( self.E_MAX, "Maximum Energy") self.E_STEP = congruence.checkStrictlyPositiveNumber( self.E_STEP, "Energy step") congruence.checkLessOrEqualThan(self.E_MIN, self.E_MAX, "From Energy", "To Energy") congruence.checkDir(self.SHADOW_FILE) def defaults(self): self.resetSettings() self.compute() return def help1(self): print("help pressed.") try: xoppy_doc('xsh_bragg') except: pass def writeStdOut(self, text): cursor = self.shadow_output.textCursor() cursor.movePosition(QTextCursor.End) cursor.insertText(text) self.shadow_output.setTextCursor(cursor) self.shadow_output.ensureCursorVisible()
class OWxsh_pre_mlayer(OWWidget): name = "PreMLayer" id = "xsh_pre_mlayer" description = "Calculation of multilayer mirror reflectivity profile" icon = "icons/premlayer.png" author = "create_widget.py" maintainer_email = "*****@*****.**" priority = 3 category = "" keywords = ["xoppy", "xsh_pre_mlayer"] outputs = [{ "name": "PreProcessor_Data", "type": ShadowPreProcessorData, "doc": "PreProcessor Data", "id": "PreProcessor_Data" }] want_main_area = False FILE = Setting("mlayer.dat") E_MIN = Setting(5000.0) E_MAX = Setting(20000.0) S_DENSITY = Setting("2.33") S_MATERIAL = Setting("Si") E_DENSITY = Setting("2.40") E_MATERIAL = Setting("B4C") O_DENSITY = Setting("9.40") O_MATERIAL = Setting("Ru") GRADE_DEPTH = Setting(0) N_PAIRS = Setting(70) THICKNESS = Setting(33.1) GAMMA = Setting(0.483) ROUGHNESS_EVEN = Setting(3.3) ROUGHNESS_ODD = Setting(3.1) FILE_DEPTH = Setting("myfile_depth.dat") GRADE_SURFACE = Setting(0) FILE_SHADOW = Setting("mlayer1.sha") FILE_THICKNESS = Setting("mythick.dat") FILE_GAMMA = Setting("mygamma.dat") AA0 = Setting(1.0) AA1 = Setting(0.0) AA2 = Setting(0.0) AA3 = Setting(0.0) MAX_WIDTH = 700 MAX_HEIGHT = 560 CONTROL_AREA_WIDTH = 685 TABS_AREA_HEIGHT = 455 usage_path = os.path.join( resources.package_dirname("orangecontrib.shadow.widgets.gui"), "misc", "premlayer_usage.png") def __init__(self): super().__init__() self.runaction = widget.OWAction("Compute", self) self.runaction.triggered.connect(self.compute) self.addAction(self.runaction) self.setFixedWidth(self.MAX_WIDTH) self.setFixedHeight(self.MAX_HEIGHT) gui.separator(self.controlArea) box0 = gui.widgetBox(self.controlArea, "", orientation="horizontal") #widget buttons: compute, set defaults, help button = gui.button(box0, self, "Compute", callback=self.compute) button.setFixedHeight(45) button = gui.button(box0, self, "Defaults", callback=self.defaults) button.setFixedHeight(45) button = gui.button(box0, self, "Help", callback=self.help1) button.setFixedHeight(45) gui.separator(self.controlArea) tabs_setting = oasysgui.tabWidget(self.controlArea) tabs_setting.setFixedHeight(self.TABS_AREA_HEIGHT) tabs_setting.setFixedWidth(self.CONTROL_AREA_WIDTH - 5) tab_input = oasysgui.createTabPage(tabs_setting, "Basic Settings") tab_input_2 = oasysgui.createTabPage(tabs_setting, "Bilayer Settings") tab_out = oasysgui.createTabPage(tabs_setting, "Output") tab_usa = oasysgui.createTabPage(tabs_setting, "Use of the Widget") tab_usa.setStyleSheet("background-color: white;") tab_usa.setStyleSheet("background-color: white;") usage_box = oasysgui.widgetBox(tab_usa, "", addSpace=True, orientation="horizontal") label = QLabel("") label.setAlignment(Qt.AlignCenter) label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) label.setPixmap(QPixmap(self.usage_path)) usage_box.layout().addWidget(label) box = gui.widgetBox(tab_input, "Multilayer Parameters", orientation="vertical") idx = -1 #widget index 0 idx += 1 box_file = oasysgui.widgetBox(box, "", addSpace=True, orientation="horizontal") self.le_FILE = oasysgui.lineEdit(box_file, self, "FILE", label=self.unitLabels()[idx], addSpace=True, labelWidth=380, orientation="horizontal") gui.button(box_file, self, "...", callback=self.selectFile) self.show_at(self.unitFlags()[idx], box) #widget index 1 idx += 1 oasysgui.lineEdit(box, self, "E_MIN", label=self.unitLabels()[idx], addSpace=True, valueType=float, labelWidth=550, orientation="horizontal") self.show_at(self.unitFlags()[idx], box) #widget index 2 idx += 1 oasysgui.lineEdit(box, self, "E_MAX", label=self.unitLabels()[idx], addSpace=True, valueType=float, labelWidth=550, orientation="horizontal") self.show_at(self.unitFlags()[idx], box) #widget index 4 idx += 1 oasysgui.lineEdit(box, self, "S_MATERIAL", label=self.unitLabels()[idx], addSpace=True, labelWidth=550, orientation="horizontal", callback=self.set_SDensity) self.show_at(self.unitFlags()[idx], box) #widget index 3 idx += 1 oasysgui.lineEdit(box, self, "S_DENSITY", label=self.unitLabels()[idx], addSpace=True, valueType=float, labelWidth=550, orientation="horizontal") self.show_at(self.unitFlags()[idx], box) #widget index 6 idx += 1 oasysgui.lineEdit(box, self, "E_MATERIAL", label=self.unitLabels()[idx], addSpace=True, labelWidth=550, orientation="horizontal", callback=self.set_EDensity) self.show_at(self.unitFlags()[idx], box) #widget index 5 idx += 1 oasysgui.lineEdit(box, self, "E_DENSITY", label=self.unitLabels()[idx], addSpace=True, valueType=float, labelWidth=550, orientation="horizontal") self.show_at(self.unitFlags()[idx], box) #widget index 8 idx += 1 oasysgui.lineEdit(box, self, "O_MATERIAL", label=self.unitLabels()[idx], addSpace=True, labelWidth=550, orientation="horizontal", callback=self.set_ODensity) self.show_at(self.unitFlags()[idx], box) #widget index 7 idx += 1 oasysgui.lineEdit(box, self, "O_DENSITY", label=self.unitLabels()[idx], addSpace=True, valueType=float, labelWidth=550, orientation="horizontal") self.show_at(self.unitFlags()[idx], box) box_byl = gui.widgetBox(tab_input_2, "Multilayer Parameters", orientation="vertical") #widget index 9 idx += 1 gui.comboBox(box_byl, self, "GRADE_DEPTH", label=self.unitLabels()[idx], addSpace=True, items=[ 'No (Constant)', 'thicknesses, gamma, rough_even, rough_odd from file ' ], valueType=int, orientation="horizontal", labelWidth=270) self.show_at(self.unitFlags()[idx], box) box_2 = oasysgui.widgetBox(box_byl, "", orientation="vertical", height=160) #widget index 10 idx += 1 oasysgui.lineEdit(box_2, self, "N_PAIRS", label=self.unitLabels()[idx], addSpace=True, valueType=int, labelWidth=550, orientation="horizontal") self.show_at(self.unitFlags()[idx], box_2) #widget index 11 idx += 1 oasysgui.lineEdit(box_2, self, "THICKNESS", label=self.unitLabels()[idx], addSpace=True, valueType=float, labelWidth=550, orientation="horizontal") self.show_at(self.unitFlags()[idx], box_2) #widget index 12 idx += 1 oasysgui.lineEdit(box_2, self, "GAMMA", label=self.unitLabels()[idx], addSpace=True, valueType=float, labelWidth=550, orientation="horizontal") self.show_at(self.unitFlags()[idx], box_2) #widget index 13 idx += 1 oasysgui.lineEdit(box_2, self, "ROUGHNESS_EVEN", label=self.unitLabels()[idx], addSpace=True, valueType=float, labelWidth=550, orientation="horizontal") self.show_at(self.unitFlags()[idx], box_2) #widget index 14 idx += 1 oasysgui.lineEdit(box_2, self, "ROUGHNESS_ODD", label=self.unitLabels()[idx], addSpace=True, valueType=float, labelWidth=550, orientation="horizontal") self.show_at(self.unitFlags()[idx], box_2) #widget index 15 idx += 1 box_file_depth = oasysgui.widgetBox(box_byl, "", addSpace=True, orientation="horizontal", height=160) self.le_FILE_DEPTH = oasysgui.lineEdit(box_file_depth, self, "FILE_DEPTH", label=self.unitLabels()[idx], addSpace=True, labelWidth=400, orientation="horizontal") gui.button(box_file_depth, self, "...", callback=self.selectFileDepth) self.show_at(self.unitFlags()[idx], box_file_depth) #widget index 16 idx += 1 gui.comboBox(box_byl, self, "GRADE_SURFACE", label=self.unitLabels()[idx], addSpace=True, items=[ 'No (Constant)', 'thick and gamma graded (from spline files)', 'thickness graded (from quadratic fit)' ], valueType=int, orientation="horizontal", labelWidth=380) self.show_at(self.unitFlags()[idx], box) box_3_empty = oasysgui.widgetBox(box_byl, "", orientation="vertical", height=100) self.show_at("self.GRADE_SURFACE == 0", box_3_empty) box_3 = oasysgui.widgetBox(box_byl, "", orientation="vertical", height=100) #widget index 17 idx += 1 box_file_shadow = oasysgui.widgetBox(box_3, "", addSpace=True, orientation="horizontal") self.le_FILE_SHADOW = oasysgui.lineEdit(box_file_shadow, self, "FILE_SHADOW", label=self.unitLabels()[idx], addSpace=True, labelWidth=400, orientation="horizontal") gui.button(box_file_shadow, self, "...", callback=self.selectFileShadow) self.show_at(self.unitFlags()[idx], box_3) #widget index 18 idx += 1 box_file_thickness = oasysgui.widgetBox(box_3, "", addSpace=True, orientation="horizontal") self.le_FILE_THICKNESS = oasysgui.lineEdit( box_file_thickness, self, "FILE_THICKNESS", label=self.unitLabels()[idx], addSpace=True, labelWidth=400, orientation="horizontal") gui.button(box_file_thickness, self, "...", callback=self.selectFileThickness) self.show_at(self.unitFlags()[idx], box_3) #widget index 19 idx += 1 box_file_gamma = oasysgui.widgetBox(box_3, "", addSpace=True, orientation="horizontal") self.le_FILE_GAMMA = oasysgui.lineEdit(box_file_gamma, self, "FILE_GAMMA", label=self.unitLabels()[idx], addSpace=True, labelWidth=400, orientation="horizontal") gui.button(box_file_gamma, self, "...", callback=self.selectFileGamma) self.show_at(self.unitFlags()[idx], box_3) box_4 = oasysgui.widgetBox(box_byl, "", orientation="vertical", height=100) #widget index 20 idx += 1 oasysgui.lineEdit(box_4, self, "AA0", label=self.unitLabels()[idx], addSpace=True, valueType=float, labelWidth=550, orientation="horizontal") self.show_at(self.unitFlags()[idx], box_4) #widget index 21 idx += 1 oasysgui.lineEdit(box_4, self, "AA1", label=self.unitLabels()[idx], addSpace=True, valueType=float, labelWidth=550, orientation="horizontal") self.show_at(self.unitFlags()[idx], box_4) #widget index 22 idx += 1 oasysgui.lineEdit(box_4, self, "AA2", label=self.unitLabels()[idx], addSpace=True, valueType=float, labelWidth=550, orientation="horizontal") self.show_at(self.unitFlags()[idx], box_4) #widget index 23 idx += 1 oasysgui.lineEdit(box_4, self, "AA3", label=self.unitLabels()[idx], addSpace=True, valueType=float, labelWidth=550, orientation="horizontal") self.show_at(self.unitFlags()[idx], box_4) self.process_showers() self.shadow_output = oasysgui.textArea() out_box = oasysgui.widgetBox(tab_out, "System Output", addSpace=True, orientation="horizontal", height=400) out_box.layout().addWidget(self.shadow_output) gui.rubber(self.controlArea) def unitLabels(self): return [ 'Output file (for SHADOW/trace): ', 'Min Energy [eV]', 'Max Energy [eV]', 'Material (substrate) (element or formula)', 'Density (substrate) [g/cm3]', 'Material (even sublayer) (element or formula)', 'Density (even "bottom" sublayer) [g/cm3]', 'Material (odd sublayer) (element or formula)', 'Density (odd "top" sublayer) [g/cm3]', 'Bilayer thicknesses graded along the depth? ', 'Number of bilayers ', 'bilayer thickness t [A]', 'gamma ratio [t_even/(t_odd+t_even)]', 'Roughness even layer [A]', 'Roughness odd layer [A]', 'File with list of t_bilayer, gamma, roughness_even, roughness_odd', 'Bilayer thicknesses/gamma graded along the surface? ', 'Output binary file (for SHADOW) with splines', 'File with bilayer thicknesses versus surface (PRESURFACE format)', 'File with bilayer gamma versus surface (PRESURFACE format)', 'Fit bilayer t(y)/t(y=0) vs y: zero-order coefficient (constant)', 'Fit bilayer t(y)/t(y=0) vs y: linear coefficient (slope)', 'Fit bilayer t(y)/t(y=0) vs y: 2nd degree coefficient', 'Fit bilayer t(y)/t(y=0) vs y: 3rd degree coefficient' ] def unitFlags(self): return [ 'True', 'True', 'True', 'True', 'True', 'True', 'True', 'True', 'True', 'True', 'self.GRADE_DEPTH == 0', 'self.GRADE_DEPTH == 0', 'self.GRADE_DEPTH == 0', 'self.GRADE_DEPTH == 0', 'self.GRADE_DEPTH == 0', 'self.GRADE_DEPTH == 1', 'True', 'self.GRADE_SURFACE == 1', 'self.GRADE_SURFACE == 1', 'self.GRADE_SURFACE == 1', 'self.GRADE_SURFACE == 2', 'self.GRADE_SURFACE == 2', 'self.GRADE_SURFACE == 2', 'self.GRADE_SURFACE == 2' ] def set_SDensity(self): if not self.S_MATERIAL is None: if not self.S_MATERIAL.strip() == "": self.S_MATERIAL = self.S_MATERIAL.strip() self.S_DENSITY = ShadowPhysics.getMaterialDensity( self.S_MATERIAL) def set_EDensity(self): if not self.E_MATERIAL is None: if not self.E_MATERIAL.strip() == "": self.E_MATERIAL = self.E_MATERIAL.strip() self.E_DENSITY = ShadowPhysics.getMaterialDensity( self.E_MATERIAL) def set_ODensity(self): if not self.O_MATERIAL is None: if not self.O_MATERIAL.strip() == "": self.O_MATERIAL = self.O_MATERIAL.strip() self.O_DENSITY = ShadowPhysics.getMaterialDensity( self.O_MATERIAL) def compute(self): try: sys.stdout = EmittingStream(textWritten=self.writeStdOut) self.checkFields() if self.GRADE_DEPTH == 0: FILE_DEPTH = "NONE" else: FILE_DEPTH = congruence.checkFileName(self.FILE_DEPTH) if self.GRADE_SURFACE == 1: FILE_SHADOW = congruence.checkFileName(self.FILE_SHADOW) FILE_THICKNESS = congruence.checkFileName(self.FILE_THICKNESS) FILE_GAMMA = congruence.checkFileName(self.FILE_GAMMA) else: FILE_SHADOW = "NONE" FILE_THICKNESS = "NONE" FILE_GAMMA = "NONE" tmp = pre_mlayer( interactive=False, FILE=congruence.checkFileName(self.FILE), E_MIN=self.E_MIN, E_MAX=self.E_MAX, S_DENSITY=self.S_DENSITY, S_MATERIAL=self.S_MATERIAL, E_DENSITY=self.E_DENSITY, E_MATERIAL=self.E_MATERIAL, O_DENSITY=self.O_DENSITY, O_MATERIAL=self.O_MATERIAL, GRADE_DEPTH=self.GRADE_DEPTH, N_PAIRS=self.N_PAIRS, THICKNESS=self.THICKNESS, GAMMA=self.GAMMA, ROUGHNESS_EVEN=self.ROUGHNESS_EVEN, ROUGHNESS_ODD=self.ROUGHNESS_ODD, FILE_DEPTH=FILE_DEPTH, GRADE_SURFACE=self.GRADE_SURFACE, FILE_SHADOW=FILE_SHADOW, FILE_THICKNESS=FILE_THICKNESS, FILE_GAMMA=FILE_GAMMA, AA0=self.AA0, AA1=self.AA1, AA2=self.AA2, AA3=self.AA3, ) self.send( "PreProcessor_Data", ShadowPreProcessorData(m_layer_data_file_dat=self.FILE, m_layer_data_file_sha=self.FILE_SHADOW)) except Exception as exception: QMessageBox.critical(self, "Error", str(exception), QMessageBox.Ok) def checkFields(self): congruence.checkDir(self.FILE) self.E_MIN = congruence.checkPositiveNumber(self.E_MIN, "Min Energy") self.E_MAX = congruence.checkStrictlyPositiveNumber( self.E_MAX, "Max Energy") congruence.checkLessOrEqualThan(self.E_MIN, self.E_MAX, "Minimum Energy", "Maximum Energy") self.S_MATERIAL = ShadowPhysics.checkCompoundName(self.S_MATERIAL) self.S_DENSITY = congruence.checkStrictlyPositiveNumber( float(self.S_DENSITY), "Density (substrate)") self.E_MATERIAL = ShadowPhysics.checkCompoundName(self.E_MATERIAL) self.E_DENSITY = congruence.checkStrictlyPositiveNumber( float(self.E_DENSITY), "Density (even sublayer)") self.O_MATERIAL = ShadowPhysics.checkCompoundName(self.O_MATERIAL) self.O_DENSITY = congruence.checkStrictlyPositiveNumber( float(self.O_DENSITY), "Density (odd sublayer)") if self.GRADE_DEPTH == 0: self.N_PAIRS = congruence.checkStrictlyPositiveNumber( int(self.N_PAIRS), "Number of bilayers") self.THICKNESS = congruence.checkStrictlyPositiveNumber( float(self.THICKNESS), "bilayer thickness t") self.GAMMA = congruence.checkStrictlyPositiveNumber( float(self.GAMMA), "gamma ratio") self.ROUGHNESS_EVEN = congruence.checkPositiveNumber( float(self.ROUGHNESS_EVEN), "Roughness even layer") self.ROUGHNESS_ODD = congruence.checkPositiveNumber( float(self.ROUGHNESS_ODD), "Roughness odd layer") else: congruence.checkDir(self.FILE_DEPTH) if self.GRADE_SURFACE == 1: congruence.checkDir(self.FILE_SHADOW) congruence.checkDir(self.FILE_THICKNESS) congruence.checkDir(self.FILE_GAMMA) elif self.GRADE_SURFACE == 2: self.AA0 = congruence.checkNumber(float(self.AA0), "zero-order coefficient") self.AA1 = congruence.checkNumber(float(self.AA1), "linear coefficient") self.AA2 = congruence.checkNumber(float(self.AA2), "2nd degree coefficient") self.AA3 = congruence.checkNumber(float(self.AA3), "3rd degree coefficient") def selectFile(self): self.le_FILE.setText( oasysgui.selectFileFromDialog( self, self.FILE, "Select Output File", file_extension_filter="Data Files (*.dat)")) def selectFileDepth(self): self.le_FILE_DEPTH.setText( oasysgui.selectFileFromDialog( self, self.FILE_DEPTH, "Open File with list of t_bilayer,gamma,roughness_even,roughness_odd", file_extension_filter="Data Files (*.dat)")) def selectFileThickness(self): self.le_FILE_THICKNESS.setText( oasysgui.selectFileFromDialog( self, self.FILE_THICKNESS, "Open File with bilayer thicknesses versus surface (PRESURFACE format)", file_extension_filter="Data Files (*.dat)")) def selectFileShadow(self): self.le_FILE_SHADOW.setText( oasysgui.selectFileFromDialog( self, self.FILE_SHADOW, "Select Output binary file (for SHADOW) with splines", file_extension_filter="Data Files (*.dat)")) def selectFileGamma(self): self.le_FILE_GAMMA.setText( oasysgui.selectFileFromDialog( self, self.FILE_GAMMA, "Open File with bilayer gamma versus surface (PRESURFACE format)", file_extension_filter="Data Files (*.dat)")) def defaults(self): self.resetSettings() #self.compute() return def help1(self): print("help pressed.") try: xoppy_doc('xsh_pre_mlayer') except: pass def writeStdOut(self, text): cursor = self.shadow_output.textCursor() cursor.movePosition(QTextCursor.End) cursor.insertText(text) self.shadow_output.setTextCursor(cursor) self.shadow_output.ensureCursorVisible()
def home_data(cls): return pathlib.Path( resources.package_dirname("orangecontrib.xoppy.util"), "data")
class Lens(ow_compound_optical_element.CompoundOpticalElement): name = "Lens" description = "Shadow Compound OE: Lens" icon = "icons/lens.png" priority = 1 NONE_SPECIFIED = "NONE SPECIFIED" p = Setting(0.0) q = Setting(0.0) surface_shape = Setting(1) convex_to_the_beam = Setting(0) has_finite_diameter = Setting(0) diameter = Setting(0.632) is_cylinder = Setting(0) cylinder_angle = Setting(0.0) ri_calculation_mode = Setting(0) prerefl_file = Setting(NONE_SPECIFIED) refraction_index = Setting(1.0) attenuation_coefficient = Setting(0.0) radius = Setting(0.1) interthickness = Setting(0.03) use_ccc = Setting(0) help_path = os.path.join(resources.package_dirname("orangecontrib.shadow.widgets.gui"), "misc", "lens_help.png") def __init__(self): super().__init__() tab_help = oasysgui.createTabPage(self.tabs_setting, "Help") tab_help.setStyleSheet("background-color: white;") help_box = oasysgui.widgetBox(tab_help, "", addSpace=True, orientation="horizontal") label = QLabel("") label.setAlignment(Qt.AlignCenter | Qt.AlignTop) label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) label.setPixmap(QPixmap(self.help_path).scaledToWidth(self.CONTROL_AREA_WIDTH-20)) help_box.layout().addWidget(label) lens_box = oasysgui.widgetBox(self.tab_bas, "Input Parameters", addSpace=False, orientation="vertical", height=450) self.le_p = oasysgui.lineEdit(lens_box, self, "p", "Source Plane Distance to First Interface (P)", labelWidth=290, valueType=float, orientation="horizontal") self.le_q = oasysgui.lineEdit(lens_box, self, "q", "Last Interface Distance to Image plane (Q)" , labelWidth=290, valueType=float, orientation="horizontal") gui.comboBox(lens_box, self, "has_finite_diameter", label="Lens Diameter", labelWidth=260, items=["Finite", "Infinite"], callback=self.set_diameter, sendSelectedValue=False, orientation="horizontal") self.diameter_box = oasysgui.widgetBox(lens_box, "", addSpace=False, orientation="vertical") self.diameter_box_empty = oasysgui.widgetBox(lens_box, "", addSpace=False, orientation="vertical", height=20) self.le_diameter = oasysgui.lineEdit(self.diameter_box, self, "diameter", "Lens Diameter Value", labelWidth=260, valueType=float, orientation="horizontal") self.set_diameter() gui.comboBox(lens_box, self, "surface_shape", label="Surface Shape", labelWidth=260, items=["Sphere", "Paraboloid", "Plane"], callback=self.set_surface_shape, sendSelectedValue=False, orientation="horizontal") self.surface_shape_box = oasysgui.widgetBox(lens_box, "", addSpace=False, orientation="vertical") self.surface_shape_box_empty = oasysgui.widgetBox(lens_box, "", addSpace=False, orientation="vertical", height=20) self.le_radius = oasysgui.lineEdit(self.surface_shape_box, self, "radius", "Curvature Radius", labelWidth=260, valueType=float, orientation="horizontal") self.set_surface_shape() self.le_interthickness = oasysgui.lineEdit(lens_box, self, "interthickness", "Lens Thickness", labelWidth=260, valueType=float, orientation="horizontal") gui.comboBox(lens_box, self, "use_ccc", label="Use C.C.C.", labelWidth=310, items=["No", "Yes"], sendSelectedValue=False, orientation="horizontal") gui.comboBox(oasysgui.widgetBox(lens_box, "", addSpace=False, orientation="vertical", height=40), self, "convex_to_the_beam", label="Convexity of the 1st interface exposed to the beam\n(the 2nd interface has opposite convexity)", labelWidth=310, items=["No", "Yes"], sendSelectedValue=False, orientation="horizontal") gui.comboBox(lens_box, self, "is_cylinder", label="Cylindrical", labelWidth=310, items=["No", "Yes"], callback=self.set_cylindrical, sendSelectedValue=False, orientation="horizontal") self.box_cyl = oasysgui.widgetBox(lens_box, "", addSpace=False, orientation="vertical") self.box_cyl_empty = oasysgui.widgetBox(lens_box, "", addSpace=False, orientation="vertical", height=20) gui.comboBox(self.box_cyl, self, "cylinder_angle", label="Cylinder Angle (deg)", labelWidth=260, items=["0 (Meridional)", "90 (Sagittal)"], sendSelectedValue=False, orientation="horizontal") self.set_cylindrical() self.ri_calculation_mode_combo = gui.comboBox(lens_box, self, "ri_calculation_mode", label="Refraction Index calculation mode", labelWidth=260, items=["User Parameters", "Prerefl File"], callback=self.set_ri_calculation_mode, sendSelectedValue=False, orientation="horizontal") self.calculation_mode_1 = oasysgui.widgetBox(lens_box, "", addSpace=False, orientation="vertical") oasysgui.lineEdit(self.calculation_mode_1, self, "refraction_index", "Refraction index", labelWidth=260, valueType=float, orientation="horizontal") oasysgui.lineEdit(self.calculation_mode_1, self, "attenuation_coefficient", "Attenuation coefficient [cm-1]", labelWidth=260, valueType=float, orientation="horizontal") self.calculation_mode_2 = oasysgui.widgetBox(lens_box, "", addSpace=False, orientation="vertical") file_box = oasysgui.widgetBox(self.calculation_mode_2, "", addSpace=True, orientation="horizontal") self.le_file_prerefl = oasysgui.lineEdit(file_box, self, "prerefl_file", "File Prerefl", labelWidth=100, valueType=str, orientation="horizontal") gui.button(file_box, self, "...", callback=self.selectFilePrerefl) self.set_ri_calculation_mode() ############################################################ # # GRAPHIC USER INTERFACE MANAGEMENT # ############################################################ def after_change_workspace_units(self): label = self.le_p.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_q.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_diameter.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_radius.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_interthickness.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") def selectFilePrerefl(self): self.le_file_prerefl.setText(oasysgui.selectFileFromDialog(self, self.prerefl_file, "Select File Prerefl", file_extension_filter="Data Files (*.dat)")) def get_surface_shape(self): if self.surface_shape == 0: return 1 elif self.surface_shape == 1: return 4 elif self.surface_shape == 2: return 5 else: raise ValueError("Surface Shape") def get_cylinder_angle(self): if self.is_cylinder: if self.cylinder_angle == 0: return 0.0 elif self.cylinder_angle == 1: return 90.0 else: raise ValueError("Cylinder Angle") else: return None def get_diameter(self): if self.has_finite_diameter == 0: return self.diameter else: return None def get_prerefl_file(self): if self.ri_calculation_mode == 1: return bytes(congruence.checkFileName(self.prerefl_file), 'utf-8') else: return None def set_surface_shape(self): self.surface_shape_box.setVisible(self.surface_shape != 2) self.surface_shape_box_empty.setVisible(self.surface_shape == 2) def set_diameter(self): self.diameter_box.setVisible(self.has_finite_diameter == 0) self.diameter_box_empty.setVisible(self.has_finite_diameter == 1) def set_cylindrical(self): self.box_cyl.setVisible(self.is_cylinder == 1) self.box_cyl_empty.setVisible(self.is_cylinder == 0) def set_ri_calculation_mode(self): self.calculation_mode_1.setVisible(self.ri_calculation_mode == 0) self.calculation_mode_2.setVisible(self.ri_calculation_mode == 1) ############################################################ # # USER INPUT MANAGEMENT # ############################################################ def populateFields(self, shadow_oe): shadow_oe._oe.append_lens(p=self.p, q=self.q, surface_shape=self.get_surface_shape(), convex_to_the_beam=self.convex_to_the_beam, diameter=self.get_diameter(), cylinder_angle=self.get_cylinder_angle(), prerefl_file=self.get_prerefl_file(), refraction_index=self.refraction_index, attenuation_coefficient=self.attenuation_coefficient, radius=self.radius, interthickness=self.interthickness, use_ccc=self.use_ccc) def doSpecificSetting(self, shadow_oe): pass def checkFields(self): congruence.checkPositiveNumber(self.p, "P") congruence.checkPositiveNumber(self.q, "Q") if self.has_finite_diameter == 0: congruence.checkStrictlyPositiveNumber(self.diameter, "Diameter") if self.ri_calculation_mode == 1: congruence.checkFile(self.prerefl_file) else: congruence.checkPositiveNumber(self.refraction_index, "Refraction Index") congruence.checkPositiveNumber(self.attenuation_coefficient, "Attenuation Coefficient") congruence.checkStrictlyPositiveNumber(self.radius, "Radius") congruence.checkPositiveNumber(self.interthickness, "Lens Thickness") def setPreProcessorData(self, data): if data is not None: if data.prerefl_data_file != ShadowPreProcessorData.NONE: self.prerefl_file = data.prerefl_data_file self.ri_calculation_mode = 1 self.set_ri_calculation_mode() else: QMessageBox.warning(self, "Warning", "Incompatible Preprocessor Data", QMessageBox.Ok) def setupUI(self): self.set_surface_shape() self.set_diameter() self.set_cylindrical() self.set_ri_calculation_mode()
class Transfocator(ow_compound_optical_element.CompoundOpticalElement): name = "Transfocator" description = "Shadow Compound OE: Transfocator" icon = "icons/transfocator.png" priority = 2 NONE_SPECIFIED = "NONE SPECIFIED" nlenses = Setting([4, 2]) slots_empty = Setting([0, 0]) thickness = Setting([2.5, 2.5]) p = Setting([0.0, 0.0]) q = Setting([0.0, 0.0]) surface_shape = Setting([1, 1]) convex_to_the_beam = Setting([0, 0]) has_finite_diameter = Setting([0, 0]) diameter = Setting([0.632, 0.894]) is_cylinder = Setting([0, 0]) cylinder_angle = Setting([0.0, 0.0]) ri_calculation_mode = Setting([0, 0]) prerefl_file = Setting([NONE_SPECIFIED, NONE_SPECIFIED]) refraction_index = Setting([1.0, 1.0]) attenuation_coefficient = Setting([0.0, 0.0]) radius = Setting([0.1, 0.2]) interthickness = Setting([0.03, 0.03]) use_ccc = Setting([0, 0]) help_path = os.path.join( resources.package_dirname("orangecontrib.shadow.widgets.gui"), "misc", "crl_help.png") def __init__(self): super().__init__() tab_help = oasysgui.createTabPage(self.tabs_setting, "Help") tab_help.setStyleSheet("background-color: white;") help_box = oasysgui.widgetBox(tab_help, "", addSpace=True, orientation="horizontal", height=300) label = QLabel("") label.setAlignment(Qt.AlignCenter | Qt.AlignTop) label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) label.setPixmap( QPixmap(self.help_path).scaledToWidth(self.CONTROL_AREA_WIDTH - 20)) help_box.layout().addWidget(label) tabs_button_box = oasysgui.widgetBox(self.tab_bas, "", addSpace=False, orientation="horizontal") btns = [ gui.button(tabs_button_box, self, "Insert C.R.L. Before", callback=self.crl_insert_before), gui.button(tabs_button_box, self, "Insert C.R.L. After", callback=self.crl_insert_after), gui.button(tabs_button_box, self, "Remove C.R.L.", callback=self.crl_remove) ] for btn in btns: btn.setFixedHeight(40) self.tab_crls = oasysgui.tabWidget(self.tab_bas) self.crl_box_array = [] for index in range(len(self.p)): tab_crl = oasysgui.createTabPage(self.tab_crls, "C.R.L. " + str(index + 1)) crl_box = CRLBox( transfocator=self, parent=tab_crl, nlenses=self.nlenses[index], slots_empty=self.slots_empty[index], thickness=self.thickness[index], p=self.p[index], q=self.q[index], surface_shape=self.surface_shape[index], convex_to_the_beam=self.convex_to_the_beam[index], has_finite_diameter=self.has_finite_diameter[index], diameter=self.diameter[index], is_cylinder=self.is_cylinder[index], cylinder_angle=self.cylinder_angle[index], ri_calculation_mode=self.ri_calculation_mode[index], prerefl_file=self.prerefl_file[index], refraction_index=self.refraction_index[index], attenuation_coefficient=self.attenuation_coefficient[index], radius=self.radius[index], interthickness=self.interthickness[index], use_ccc=self.use_ccc[index]) self.crl_box_array.append(crl_box) def after_change_workspace_units(self): for box in self.crl_box_array: box.after_change_workspace_units() def callResetSettings(self): if ConfirmDialog.confirmed( parent=self, message= "Confirm Reset of the Fields?\n\nWarning: C.R.L. stack will be regenerated" ): self.resetSettings() while self.tab_crls.count() > 0: self.tab_crls.removeTab(0) self.crl_box_array = [] for index in range(len(self.p)): tab_crl = oasysgui.widgetBox(self.tab_crls, addToLayout=0, margin=4) crl_box = CRLBox( transfocator=self, parent=tab_crl, nlenses=self.nlenses[index], slots_empty=self.slots_empty[index], thickness=self.thickness[index], p=self.p[index], q=self.q[index], surface_shape=self.surface_shape[index], convex_to_the_beam=self.convex_to_the_beam[index], has_finite_diameter=self.has_finite_diameter[index], diameter=self.diameter[index], is_cylinder=self.is_cylinder[index], cylinder_angle=self.cylinder_angle[index], ri_calculation_mode=self.ri_calculation_mode[index], prerefl_file=self.prerefl_file[index], refraction_index=self.refraction_index[index], attenuation_coefficient=self. attenuation_coefficient[index], radius=self.radius[index], interthickness=self.interthickness[index], use_ccc=self.use_ccc[index]) self.tab_crls.addTab(tab_crl, "C.R.L " + str(index + 1)) self.crl_box_array.append(crl_box) self.setupUI() def crl_insert_before(self): current_index = self.tab_crls.currentIndex() if ConfirmDialog.confirmed( parent=self, message="Confirm Insertion of a new element before " + self.tab_crls.tabText(current_index) + "?"): tab_crl = oasysgui.widgetBox(self.tab_crls, addToLayout=0, margin=4) crl_box = CRLBox(transfocator=self, parent=tab_crl) crl_box.after_change_workspace_units() self.tab_crls.insertTab(current_index, tab_crl, "TEMP") self.crl_box_array.insert(current_index, crl_box) self.dumpSettings() for index in range(current_index, self.tab_crls.count()): self.tab_crls.setTabText(index, "C.R.L " + str(index + 1)) self.tab_crls.setCurrentIndex(current_index) def crl_insert_after(self): current_index = self.tab_crls.currentIndex() if ConfirmDialog.confirmed( parent=self, message="Confirm Insertion of a new element after " + self.tab_crls.tabText(current_index) + "?"): tab_crl = oasysgui.widgetBox(self.tab_crls, addToLayout=0, margin=4) crl_box = CRLBox(transfocator=self, parent=tab_crl) crl_box.after_change_workspace_units() if current_index == self.tab_crls.count() - 1: # LAST self.tab_crls.addTab(tab_crl, "TEMP") self.crl_box_array.append(crl_box) else: self.tab_crls.insertTab(current_index + 1, tab_crl, "TEMP") self.crl_box_array.insert(current_index + 1, crl_box) self.dumpSettings() for index in range(current_index, self.tab_crls.count()): self.tab_crls.setTabText(index, "C.R.L " + str(index + 1)) self.tab_crls.setCurrentIndex(current_index + 1) def crl_remove(self): if self.tab_crls.count() <= 1: QMessageBox.critical( self, "Error", "Remove not possible, transfocator needs at least 1 element", QMessageBox.Ok) else: current_index = self.tab_crls.currentIndex() if ConfirmDialog.confirmed(parent=self, message="Confirm Removal of " + self.tab_crls.tabText(current_index) + "?"): self.tab_crls.removeTab(current_index) self.crl_box_array.pop(current_index) self.dumpSettings() for index in range(current_index, self.tab_crls.count()): self.tab_crls.setTabText(index, "C.R.L " + str(index + 1)) self.tab_crls.setCurrentIndex(current_index) def dumpSettings(self): bkp_nlenses = copy.deepcopy(self.nlenses) bkp_slots_empty = copy.deepcopy(self.slots_empty) bkp_thickness = copy.deepcopy(self.thickness) bkp_p = copy.deepcopy(self.p) bkp_q = copy.deepcopy(self.q) bkp_surface_shape = copy.deepcopy(self.surface_shape) bkp_convex_to_the_beam = copy.deepcopy(self.convex_to_the_beam) bkp_has_finite_diameter = copy.deepcopy(self.has_finite_diameter) bkp_diameter = copy.deepcopy(self.diameter) bkp_is_cylinder = copy.deepcopy(self.is_cylinder) bkp_cylinder_angle = copy.deepcopy(self.cylinder_angle) bkp_ri_calculation_mode = copy.deepcopy(self.ri_calculation_mode) bkp_prerefl_file = copy.deepcopy(self.prerefl_file) bkp_refraction_index = copy.deepcopy(self.refraction_index) bkp_attenuation_coefficient = copy.deepcopy( self.attenuation_coefficient) bkp_radius = copy.deepcopy(self.radius) bkp_interthickness = copy.deepcopy(self.interthickness) bkp_use_ccc = copy.deepcopy(self.use_ccc) try: self.nlenses = [] self.slots_empty = [] self.thickness = [] self.p = [] self.q = [] self.surface_shape = [] self.convex_to_the_beam = [] self.has_finite_diameter = [] self.diameter = [] self.is_cylinder = [] self.cylinder_angle = [] self.ri_calculation_mode = [] self.prerefl_file = [] self.refraction_index = [] self.attenuation_coefficient = [] self.radius = [] self.interthickness = [] self.use_ccc = [] for index in range(len(self.crl_box_array)): self.nlenses.append(self.crl_box_array[index].nlenses) self.slots_empty.append(self.crl_box_array[index].slots_empty) self.thickness.append(self.crl_box_array[index].thickness) self.p.append(self.crl_box_array[index].p) self.q.append(self.crl_box_array[index].q) self.surface_shape.append( self.crl_box_array[index].surface_shape) self.convex_to_the_beam.append( self.crl_box_array[index].convex_to_the_beam) self.has_finite_diameter.append( self.crl_box_array[index].has_finite_diameter) self.diameter.append(self.crl_box_array[index].diameter) self.is_cylinder.append(self.crl_box_array[index].is_cylinder) self.cylinder_angle.append( self.crl_box_array[index].cylinder_angle) self.ri_calculation_mode.append( self.crl_box_array[index].ri_calculation_mode) self.prerefl_file.append( self.crl_box_array[index].prerefl_file) self.refraction_index.append( self.crl_box_array[index].refraction_index) self.attenuation_coefficient.append( self.crl_box_array[index].attenuation_coefficient) self.radius.append(self.crl_box_array[index].radius) self.interthickness.append( self.crl_box_array[index].interthickness) self.use_ccc.append(self.crl_box_array[index].use_ccc) except: self.nlenses = copy.deepcopy(bkp_nlenses) self.slots_empty = copy.deepcopy(bkp_slots_empty) self.thickness = copy.deepcopy(bkp_thickness) self.p = copy.deepcopy(bkp_p) self.q = copy.deepcopy(bkp_q) self.surface_shape = copy.deepcopy(bkp_surface_shape) self.convex_to_the_beam = copy.deepcopy(bkp_convex_to_the_beam) self.has_finite_diameter = copy.deepcopy(bkp_has_finite_diameter) self.diameter = copy.deepcopy(bkp_diameter) self.is_cylinder = copy.deepcopy(bkp_is_cylinder) self.cylinder_angle = copy.deepcopy(bkp_cylinder_angle) self.ri_calculation_mode = copy.deepcopy(bkp_ri_calculation_mode) self.prerefl_file = copy.deepcopy(bkp_prerefl_file) self.refraction_index = copy.deepcopy(bkp_refraction_index) self.attenuation_coefficient = copy.deepcopy( bkp_attenuation_coefficient) self.radius = copy.deepcopy(bkp_radius) self.interthickness = copy.deepcopy(bkp_interthickness) self.use_ccc = copy.deepcopy(bkp_use_ccc) ############################## # SINGLE FIELDS SIGNALS ############################## def dump_nlenses(self): bkp_nlenses = copy.deepcopy(self.nlenses) try: self.nlenses = [] for index in range(len(self.crl_box_array)): self.nlenses.append(self.crl_box_array[index].nlenses) except: self.nlenses = copy.deepcopy(bkp_nlenses) def dump_slots_empty(self): bkp_slots_empty = copy.deepcopy(self.slots_empty) try: self.slots_empty = [] for index in range(len(self.crl_box_array)): self.slots_empty.append(self.crl_box_array[index].slots_empty) except: self.slots_empty = copy.deepcopy(bkp_slots_empty) def dump_thickness(self): bkp_thickness = copy.deepcopy(self.thickness) try: self.thickness = [] for index in range(len(self.crl_box_array)): self.thickness.append(self.crl_box_array[index].thickness) except: self.thickness = copy.deepcopy(bkp_thickness) def dump_p(self): bkp_p = copy.deepcopy(self.p) try: self.p = [] for index in range(len(self.crl_box_array)): self.p.append(self.crl_box_array[index].p) except: self.p = copy.deepcopy(bkp_p) def dump_q(self): bkp_q = copy.deepcopy(self.q) try: self.q = [] for index in range(len(self.crl_box_array)): self.q.append(self.crl_box_array[index].q) except: self.q = copy.deepcopy(bkp_q) def dump_surface_shape(self): bkp_surface_shape = copy.deepcopy(self.surface_shape) try: self.surface_shape = [] for index in range(len(self.crl_box_array)): self.surface_shape.append( self.crl_box_array[index].surface_shape) except: self.surface_shape = copy.deepcopy(bkp_surface_shape) def dump_convex_to_the_beam(self): bkp_convex_to_the_beam = copy.deepcopy(self.convex_to_the_beam) try: self.convex_to_the_beam = [] for index in range(len(self.crl_box_array)): self.convex_to_the_beam.append( self.crl_box_array[index].convex_to_the_beam) except: self.convex_to_the_beam = copy.deepcopy(bkp_convex_to_the_beam) def dump_has_finite_diameter(self): bkp_has_finite_diameter = copy.deepcopy(self.has_finite_diameter) try: self.has_finite_diameter = [] for index in range(len(self.crl_box_array)): self.has_finite_diameter.append( self.crl_box_array[index].has_finite_diameter) except: self.has_finite_diameter = copy.deepcopy(bkp_has_finite_diameter) def dump_diameter(self): bkp_diameter = copy.deepcopy(self.diameter) try: self.diameter = [] for index in range(len(self.crl_box_array)): self.diameter.append(self.crl_box_array[index].diameter) except: self.diameter = copy.deepcopy(bkp_diameter) def dump_is_cylinder(self): bkp_is_cylinder = copy.deepcopy(self.is_cylinder) try: self.is_cylinder = [] for index in range(len(self.crl_box_array)): self.is_cylinder.append(self.crl_box_array[index].is_cylinder) except: self.is_cylinder = copy.deepcopy(bkp_is_cylinder) def dump_cylinder_angle(self): bkp_cylinder_angle = copy.deepcopy(self.cylinder_angle) try: self.cylinder_angle = [] for index in range(len(self.crl_box_array)): self.cylinder_angle.append( self.crl_box_array[index].cylinder_angle) except: self.cylinder_angle = copy.deepcopy(bkp_cylinder_angle) def dump_ri_calculation_mode(self): bkp_ri_calculation_mode = copy.deepcopy(self.ri_calculation_mode) try: self.ri_calculation_mode = [] for index in range(len(self.crl_box_array)): self.ri_calculation_mode.append( self.crl_box_array[index].ri_calculation_mode) except: self.ri_calculation_mode = copy.deepcopy(bkp_ri_calculation_mode) def dump_prerefl_file(self): bkp_prerefl_file = copy.deepcopy(self.prerefl_file) try: self.prerefl_file = [] for index in range(len(self.crl_box_array)): self.prerefl_file.append( self.crl_box_array[index].prerefl_file) except: self.prerefl_file = copy.deepcopy(bkp_prerefl_file) def dump_refraction_index(self): bkp_refraction_index = copy.deepcopy(self.refraction_index) try: self.refraction_index = [] for index in range(len(self.crl_box_array)): self.refraction_index.append( self.crl_box_array[index].refraction_index) except: self.refraction_index = copy.deepcopy(bkp_refraction_index) def dump_attenuation_coefficient(self): bkp_attenuation_coefficient = copy.deepcopy( self.attenuation_coefficient) try: self.attenuation_coefficient = [] for index in range(len(self.crl_box_array)): self.attenuation_coefficient.append( self.crl_box_array[index].attenuation_coefficient) except: self.attenuation_coefficient = copy.deepcopy( bkp_attenuation_coefficient) def dump_radius(self): bkp_radius = copy.deepcopy(self.radius) try: self.radius = [] for index in range(len(self.crl_box_array)): self.radius.append(self.crl_box_array[index].radius) except: self.radius = copy.deepcopy(bkp_radius) def dump_interthickness(self): bkp_interthickness = copy.deepcopy(self.interthickness) try: self.interthickness = [] for index in range(len(self.crl_box_array)): self.interthickness.append( self.crl_box_array[index].interthickness) except: self.interthickness = copy.deepcopy(bkp_interthickness) def dump_use_ccc(self): bkp_use_ccc = copy.deepcopy(self.use_ccc) try: self.use_ccc = [] for index in range(len(self.crl_box_array)): self.use_ccc.append(self.crl_box_array[index].use_ccc) except: self.use_ccc = copy.deepcopy(bkp_use_ccc) ############################################################ # # USER INPUT MANAGEMENT # ############################################################ def populateFields(self, shadow_oe): self.dumpSettings() surface_shape_out = [] diameter_out = [] cylinder_angle_out = [] prerefl_file_out = [] for box in self.crl_box_array: surface_shape_out.append(box.get_surface_shape()) diameter_out.append(box.get_diameter()) cylinder_angle_out.append(box.get_cylinder_angle()) prerefl_file_out.append(box.get_prerefl_file()) if numpy.sum(self.nlenses) > 0: shadow_oe._oe.append_transfocator( p0=self.p, q0=self.q, nlenses=self.nlenses, slots_empty=self.slots_empty, thickness=self.thickness, surface_shape=surface_shape_out, convex_to_the_beam=self.convex_to_the_beam, diameter=diameter_out, cylinder_angle=cylinder_angle_out, prerefl_file=prerefl_file_out, refraction_index=self.refraction_index, attenuation_coefficient=self.attenuation_coefficient, radius=self.radius, interthickness=self.interthickness, use_ccc=self.use_ccc) def checkFields(self): for box in self.crl_box_array: box.checkFields() def setPreProcessorData(self, data): if data is not None: if data.prerefl_data_file != ShadowPreProcessorData.NONE: for box in self.crl_box_array: box.prerefl_file = data.prerefl_data_file box.le_prerefl_file.setText(data.prerefl_data_file) box.ri_calculation_mode = 1 box.ri_calculation_mode_combo.setCurrentIndex(1) box.set_ri_calculation_mode() else: QMessageBox.warning(self, "Warning", "Incompatible Preprocessor Data", QMessageBox.Ok) self.dump_prerefl_file() def setupUI(self): for box in self.crl_box_array: box.setupUI()
class OWheight_profile_simulator(OWAbstractHeightErrorProfileSimulator): name = "Height Profile Simulator" id = "height_profile_simulator" description = "Calculation of mirror surface height profile" icon = "icons/simulator.png" author = "Luca Rebuffi" maintainer_email = "[email protected]; [email protected]" priority = 5 category = "" keywords = ["height_profile_simulator"] outputs = [{ "name": "PreProcessor_Data", "type": ShadowPreProcessorData, "doc": "PreProcessor Data", "id": "PreProcessor_Data" }] usage_path = os.path.join( resources.package_dirname("orangecontrib.shadow.widgets.gui"), "misc", "height_error_profile_usage.png") def __init__(self): super().__init__() def after_change_workspace_units(self): self.si_to_user_units = 1 / self.workspace_units_to_m self.axis.set_xlabel("X [" + self.workspace_units_label + "]") self.axis.set_ylabel("Y [" + self.workspace_units_label + "]") label = self.le_dimension_y.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_step_y.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_correlation_length_y.parent().layout().itemAt( 0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_dimension_x.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_step_x.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_correlation_length_x.parent().layout().itemAt( 0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_conversion_factor_y_x.parent().layout().itemAt( 0).widget() label.setText("Conversion from file to " + self.workspace_units_label + "\n(Abscissa)") label = self.le_conversion_factor_y_y.parent().layout().itemAt( 0).widget() label.setText("Conversion from file to " + self.workspace_units_label + "\n(Height Profile Values)") label = self.le_conversion_factor_x_x.parent().layout().itemAt( 0).widget() label.setText("Conversion from file to " + self.workspace_units_label + "\n(Abscissa)") label = self.le_conversion_factor_x_y.parent().layout().itemAt( 0).widget() label.setText("Conversion from file to " + self.workspace_units_label + "\n(Height Profile Values)") label = self.le_new_length_y_1.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_new_length_y_2.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_new_length_x_1.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_new_length_x_2.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") if not self.heigth_profile_file_name is None: if self.heigth_profile_file_name.endswith("hdf5"): self.heigth_profile_file_name = self.heigth_profile_file_name[: -4] + "dat" def get_usage_path(self): return self.usage_path def get_axis_um(self): return self.workspace_units_label def write_error_profile_file(self): ST.write_shadow_surface(self.zz, self.xx, self.yy, self.heigth_profile_file_name) def send_data(self, dimension_x, dimension_y): self.send( "PreProcessor_Data", ShadowPreProcessorData( error_profile_data_file=self.heigth_profile_file_name, error_profile_x_dim=dimension_x, error_profile_y_dim=dimension_y))
class FluxCalculator(AutomaticElement): name = "Flux Calculator" description = "Tools: Flux Calculator" icon = "icons/flux.png" maintainer = "Luca Rebuffi" maintainer_email = "lrebuffi(@at@)anl.gov" priority = 10 category = "User Defined" keywords = ["data", "file", "load", "read"] inputs = [("Shadow Beam", ShadowBeam, "setBeam"), ("Spectrum Data", DataExchangeObject, "setSpectrumData")] outputs = [{ "name": "Beam", "type": ShadowBeam, "doc": "Shadow Beam", "id": "beam" }] want_main_area = 0 want_control_area = 1 input_beam = None input_spectrum = None flux_index = -1 usage_path = os.path.join( resources.package_dirname( "orangecontrib.aps.shadow.widgets.extension"), "misc", "flux_calculator.png") def __init__(self): super(FluxCalculator, self).__init__() self.runaction = OWAction("Calculate Flux", self) self.runaction.triggered.connect(self.calculate_flux) self.addAction(self.runaction) self.setMaximumWidth(self.CONTROL_AREA_WIDTH + 10) self.setMaximumHeight(580) box0 = gui.widgetBox(self.controlArea, "", orientation="horizontal") gui.button(box0, self, "Calculate Flux", callback=self.calculate_flux, height=45) tabs_setting = oasysgui.tabWidget(self.controlArea) tabs_setting.setFixedHeight(440) tabs_setting.setFixedWidth(self.CONTROL_AREA_WIDTH - 8) tab_out = oasysgui.createTabPage(tabs_setting, "Flux Calculation Results") tab_usa = oasysgui.createTabPage(tabs_setting, "Use of the Widget") tab_usa.setStyleSheet("background-color: white;") self.text = oasysgui.textArea(width=self.CONTROL_AREA_WIDTH - 22, height=400) tab_out.layout().addWidget(self.text) usage_box = oasysgui.widgetBox(tab_usa, "", addSpace=True, orientation="horizontal") label = QLabel("") label.setAlignment(Qt.AlignCenter) label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) label.setPixmap(QPixmap(self.usage_path)) usage_box.layout().addWidget(label) gui.rubber(self.controlArea) def setBeam(self, beam): try: if ShadowCongruence.checkEmptyBeam(beam): if ShadowCongruence.checkGoodBeam(beam): self.input_beam = beam if self.is_automatic_run: self.calculate_flux() except Exception as exception: QMessageBox.critical(self, "Error", str(exception), QMessageBox.Ok) if self.IS_DEVELOP: raise exception def setSpectrumData(self, data): if not data is None: try: if data.get_program_name() == "XOPPY": if data.get_widget_name( ) == "UNDULATOR_FLUX" or data.get_widget_name( ) == "XWIGGLER" or data.get_widget_name() == "WS": self.flux_index = 1 elif data.get_widget_name() == "BM": self.flux_index = 5 else: raise Exception( "Connect to one of the following XOPPY widgets: Undulator Spectrum, BM, XWIGGLER, WS" ) self.input_spectrum = data.get_content('xoppy_data') elif data.get_program_name() == "SRW": if data.get_widget_name() == "UNDULATOR_SPECTRUM": self.flux_index = 1 else: raise Exception( "Connect to one of the following SRW widgets: Undulator Spectrum" ) self.input_spectrum = data.get_content('srw_data') else: raise ValueError( "Widget accept data from the following Add-ons: XOPPY, SRW" ) if self.is_automatic_run: self.calculate_flux() except Exception as exception: QMessageBox.critical(self, "Error", str(exception), QMessageBox.Ok) if self.IS_DEVELOP: raise exception def calculate_flux(self): if not self.input_beam is None and not self.input_spectrum is None: try: flux_factor, resolving_power, energy, ttext = calculate_flux_factor_and_resolving_power( self.input_beam) total_text = ttext flux_at_sample, ttext = calculate_flux_at_sample( self.input_spectrum, self.flux_index, flux_factor, energy) ticket = self.input_beam._beam.histo2(1, 3, nbins=100, nolost=1, ref=23) dx = ticket['fwhm_v'] * self.workspace_units_to_m * 1000 dy = ticket['fwhm_h'] * self.workspace_units_to_m * 1000 total_text += "\n" + ttext total_text += "\n\n ---> Integrated Flux : %g" % flux_at_sample + " ph/s" total_text += "\n ---> <Flux Density> : %g" % ( flux_at_sample / (dx * dy)) + " ph/s/mm^2" total_text += "\n ---> Resolving Power : %g" % resolving_power self.text.clear() self.text.setText(total_text) self.send("Beam", self.input_beam) except Exception as exception: QMessageBox.critical(self, "Error", str(exception), QMessageBox.Ok) if self.IS_DEVELOP: raise exception
class OWxsh_waviness(OWWidget): name = "Waviness" id = "xsh_waviness" description = "Calculation of mirror surface error profile" icon = "icons/waviness.png" author = "Luca Rebuffi" maintainer_email = "[email protected]; [email protected]" priority = 4 category = "" keywords = ["xoppy", "xsh_waviness"] outputs = [{ "name": "PreProcessor_Data", "type": ShadowPreProcessorData, "doc": "PreProcessor Data", "id": "PreProcessor_Data" }] want_main_area = 1 want_control_area = 1 MAX_WIDTH = 1320 MAX_HEIGHT = 700 IMAGE_WIDTH = 860 IMAGE_HEIGHT = 645 CONTROL_AREA_WIDTH = 405 TABS_AREA_HEIGHT = 618 xx = None yy = None zz = None number_of_points_x = Setting(10) number_of_points_y = Setting(100) dimension_x = Setting(20.1) dimension_y = Setting(113.1) estimated_slope_error = Setting(0.9) montecarlo_seed = Setting(2387427) waviness_file_name = Setting('waviness.dat') harmonic_maximum_index = Setting(60) data = Setting({ 'c': [ '0.3', '0.1', '0.1', '0.0', '0.0', '0.0', '0.3', '0.0', '0.0', '0.3', '0.0', '0.0', '0.5', '0.0', '0.0', '0.2', '0.2', '0.2', '0.9', '0.0', '0.0', '0.0', '0.0', '0.0', '0.4', '0.0', '0.0', '0.4', '0.0', '0.0', '0.0', '0.6', '0.6', '0.0', '0.4', '0.4', '0.0', '0.4', '0.4', '0.1', '0.4', '0.4', '0.1', '0.2', '0.2', '0.0', '0.2', '0.2', '0.0', '0.3', '0.3', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0', '0.0' ], 'y': [ '0.0', '-0.1', '-0.1', '0.0', '0.0', '0.0', '0.03', '0.0', '0.0', '0.2', '0.0', '0.0', '0.2', '0.0', '0.0', '0.1', '0.1', '0.1', '0.1', '0.0', '0.0', '0.0', '0.0', '0.0', '0.01', '0.0', '0.0', '0.03', '0.0', '0.0', '0.0', '0.02', '0.02', '0.0', '0.1', '0.1', '0.0', '0.1', '0.1', '0.0', '0.1', '0.1', '0.0', '0.0', '0.0', '0.0', '0.3', '0.3', '0.0', '0.2', '0.2', '0.0', '0.2', '0.2', '0.0', '0.2', '0.2', '0.0', '0.0', '0.0', '0.0' ], 'g': [ '0.0', '0.3', '0.3', '0.0', '0.0', '0.0', '0.05', '0.0', '0.0', '0.05', '0.0', '0.0', '0.1', '0.0', '0.0', '0.05', '0.05', '0.05', '0.2', '0.0', '0.0', '0.0', '0.0', '0.0', '0.1', '0.0', '0.0', '0.1', '0.0', '0.0', '0.0', '0.2', '0.2', '0.0', '0.1', '0.1', '0.0', '0.1', '0.1', '0.0', '0.1', '0.1', '0.0', '0.0', '0.0', '0.0', '0.1', '0.1', '0.0', '0.2', '0.2', '0.0', '0.1', '0.1', '0.0', '0.1', '0.1', '0.0', '0.0', '0.0', '0.0' ] }) usage_path = os.path.join( resources.package_dirname("orangecontrib.shadow.widgets.gui"), "misc", "waviness_usage.png") def __init__(self): super().__init__() self.runaction = widget.OWAction("Calculate Waviness", self) self.runaction.triggered.connect(self.calculate_waviness_ni) self.addAction(self.runaction) self.runaction = widget.OWAction("Generate Waviness File", self) self.runaction.triggered.connect(self.generate_waviness_file) self.addAction(self.runaction) geom = QApplication.desktop().availableGeometry() self.setGeometry( QRect(round(geom.width() * 0.05), round(geom.height() * 0.05), round(min(geom.width() * 0.98, self.MAX_WIDTH)), round(min(geom.height() * 0.95, self.MAX_HEIGHT)))) self.setMaximumHeight(self.geometry().height()) self.setMaximumWidth(self.geometry().width()) gui.separator(self.controlArea) button_box = oasysgui.widgetBox(self.controlArea, "", addSpace=False, orientation="horizontal") button = gui.button(button_box, self, "Calculate\nWaviness", callback=self.calculate_waviness) button.setFixedHeight(45) button = gui.button(button_box, self, "Generate\nWaviness File", callback=self.generate_waviness_file) font = QFont(button.font()) font.setBold(True) button.setFont(font) palette = QPalette(button.palette()) # make a copy of the palette palette.setColor(QPalette.ButtonText, QColor('Dark Blue')) button.setPalette(palette) # assign new palette button.setFixedHeight(45) button.setFixedWidth(150) button = gui.button(button_box, self, "Reset Fields", callback=self.call_reset_settings) font = QFont(button.font()) font.setItalic(True) button.setFont(font) palette = QPalette(button.palette()) # make a copy of the palette palette.setColor(QPalette.ButtonText, QColor('Dark Red')) button.setPalette(palette) # assign new palette button.setFixedHeight(45) gui.separator(self.controlArea) tabs_setting = oasysgui.tabWidget(self.controlArea) tabs_setting.setFixedHeight(self.TABS_AREA_HEIGHT) tabs_setting.setFixedWidth(self.CONTROL_AREA_WIDTH - 5) tab_input = oasysgui.createTabPage(tabs_setting, "Input Parameter") tab_harmonics = oasysgui.createTabPage(tabs_setting, "Harmonics") tab_out = oasysgui.createTabPage(tabs_setting, "Output") tab_usa = oasysgui.createTabPage(tabs_setting, "Use of the Widget") tab_usa.setStyleSheet("background-color: white;") usage_box = oasysgui.widgetBox(tab_usa, "", addSpace=True, orientation="horizontal") label = QLabel("") label.setAlignment(Qt.AlignCenter) label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) label.setPixmap(QPixmap(self.usage_path)) usage_box.layout().addWidget(label) self.input_box = oasysgui.widgetBox(tab_input, "Inputs", addSpace=True, orientation="vertical") gui.button(self.input_box, self, "Load xsh_waviness input file ...", callback=self.load_inp_file) gui.separator(self.input_box) oasysgui.lineEdit(self.input_box, self, "number_of_points_x", "Number of Points (<201) X (width)", labelWidth=260, valueType=int, orientation="horizontal") oasysgui.lineEdit(self.input_box, self, "number_of_points_y", "Number of Points (<201) Y (length)", labelWidth=260, valueType=int, orientation="horizontal") gui.separator(self.input_box) self.le_dimension_x = oasysgui.lineEdit(self.input_box, self, "dimension_x", "Dimensions X (width)", labelWidth=260, valueType=float, orientation="horizontal") self.le_dimension_y = oasysgui.lineEdit(self.input_box, self, "dimension_y", "Dimensions Y (length)", labelWidth=260, valueType=float, orientation="horizontal") gui.separator(self.input_box) oasysgui.lineEdit(self.input_box, self, "estimated_slope_error", "Estimated slope error [arcsec]", labelWidth=260, valueType=float, orientation="horizontal") oasysgui.lineEdit(self.input_box, self, "montecarlo_seed", "Monte Carlo initial seed", labelWidth=260, valueType=int, orientation="horizontal") self.output_box = oasysgui.widgetBox(tab_input, "Outputs", addSpace=True, orientation="vertical") gui.button(self.output_box, self, "Write xsh_waviness input file (optional) ...", callback=self.write_inp_file) gui.separator(self.output_box) self.select_file_box = oasysgui.widgetBox(self.output_box, "", addSpace=True, orientation="horizontal") self.le_waviness_file_name = oasysgui.lineEdit( self.select_file_box, self, "waviness_file_name", "Output File Name", labelWidth=120, valueType=str, orientation="horizontal") gui.button(self.select_file_box, self, "...", callback=self.selectFile) self.harmonics_box = oasysgui.widgetBox(tab_harmonics, "Harmonics", addSpace=True, orientation="vertical", height=580) oasysgui.lineEdit(self.harmonics_box, self, "harmonic_maximum_index", "Harmonic Maximum Index", labelWidth=260, valueType=int, orientation="horizontal", callback=self.set_harmonics) gui.separator(self.harmonics_box) self.scrollarea = QScrollArea() self.scrollarea.setMaximumWidth(400) self.harmonics_box.layout().addWidget(self.scrollarea, alignment=Qt.AlignHCenter) self.shadow_output = oasysgui.textArea() out_box = oasysgui.widgetBox(tab_out, "System Output", addSpace=True, orientation="horizontal", height=580) out_box.layout().addWidget(self.shadow_output) gui.rubber(self.controlArea) self.figure = Figure(figsize=(600, 600)) self.figure.patch.set_facecolor('white') self.axis = self.figure.add_subplot(111, projection='3d') self.axis.set_zlabel("Z [nm]") self.figure_canvas = FigureCanvas3D(ax=self.axis, fig=self.figure) self.mainArea.layout().addWidget(self.figure_canvas) gui.rubber(self.mainArea) def after_change_workspace_units(self): self.si_to_user_units = 1e2 / self.workspace_units_to_cm self.axis.set_xlabel("X [" + self.workspace_units_label + "]") self.axis.set_ylabel("Y [" + self.workspace_units_label + "]") label = self.le_dimension_y.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_dimension_x.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") def restoreWidgetPosition(self): super().restoreWidgetPosition() self.table = QTableWidget(self.harmonic_maximum_index + 1, 3) self.table.setStyleSheet("background-color: white;") self.table.setAlternatingRowColors(True) self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Fixed) for i in range(0, 3): self.table.setColumnWidth(i, 70) horHeaders = [] verHeaders = [] for n, key in enumerate(sorted(self.data.keys())): horHeaders.append(key) for m, item in enumerate(self.data[key]): table_item = QTableWidgetItem(str(item)) table_item.setTextAlignment(Qt.AlignRight) self.table.setItem(m, n, table_item) verHeaders.append(str(m)) self.table.setHorizontalHeaderLabels(horHeaders) self.table.setVerticalHeaderLabels(verHeaders) self.table.resizeRowsToContents() self.table.itemChanged.connect(self.table_item_changed) self.scrollarea.setWidget(self.table) self.scrollarea.setWidgetResizable(1) gui.rubber(self.controlArea) def reload_harmonics_table(self): horHeaders = [] verHeaders = [] self.table.itemChanged.disconnect(self.table_item_changed) self.table.clear() row_count = self.table.rowCount() for n in range(0, row_count): self.table.removeRow(0) for index in range(0, self.harmonic_maximum_index + 1): self.table.insertRow(0) for n, key in enumerate(sorted(self.data.keys())): horHeaders.append(key) for m, item in enumerate(self.data[key]): table_item = QTableWidgetItem(str(item)) table_item.setTextAlignment(Qt.AlignRight) self.table.setItem(m, n, table_item) verHeaders.append(str(m)) self.table.setHorizontalHeaderLabels(horHeaders) self.table.setVerticalHeaderLabels(verHeaders) self.table.resizeRowsToContents() for i in range(0, 3): self.table.setColumnWidth(i, 70) self.table.itemChanged.connect(self.table_item_changed) def table_item_changed(self): dict = {} message = "" error_row_index = -1 error_column_index = -1 previous_value = "" try: row_count = self.harmonic_maximum_index + 1 for column_index in range(0, self.table.columnCount()): column_name = self.table.horizontalHeaderItem( column_index).data(0) row_content = [] for row_index in range(0, row_count): if not self.table.item(row_index, column_index) is None: message = "Value at row " + str( row_index ) + " and column \'" + column_name + "\' is not numeric" error_row_index = row_index error_column_index = column_index previous_value = self.data[column_name][row_index] value = float( self.table.item( row_index, column_index).data(0)) # to raise exception row_content.append(str(value)) dict[column_name] = row_content self.data = dict except ValueError: QMessageBox.critical( self, "Error", message + "\nValue is reset to previous value", QMessageBox.Ok) table_item = QTableWidgetItem(previous_value) table_item.setTextAlignment(Qt.AlignRight) self.table.setItem(error_row_index, error_column_index, table_item) self.table.setCurrentCell(error_row_index, error_column_index) except Exception as exception: QMessageBox.critical(self, "Error", exception.args[0], QMessageBox.Ok) def set_harmonics(self): if self.harmonic_maximum_index < 0: QMessageBox.critical( self, "Error", "Harmonic Maximum Index should be a positive integer number", QMessageBox.Ok) else: row_count = len(self.data["c"]) if self.harmonic_maximum_index + 1 > row_count: for n, key in enumerate(sorted(self.data.keys())): for m in range(row_count, self.harmonic_maximum_index + 1): self.data[key].append('0.0') else: for n, key in enumerate(sorted(self.data.keys())): self.data[key] = copy.deepcopy( self.data[key][0:self.harmonic_maximum_index + 1]) self.reload_harmonics_table() def load_inp_file(self): file_name = oasysgui.selectFileFromDialog( self, None, "Select a input file for XSH_WAVINESS", file_extension_filter="Input Files (*.inp)") if not file_name is None: sys.stdout = EmittingStream(textWritten=self.writeStdOut) if not file_name.strip() == "": dict = ST.waviness_read(file=file_name) self.number_of_points_x = dict["npointx"] self.number_of_points_y = dict["npointy"] self.dimension_y = dict["xlength"] self.dimension_x = dict["width"] self.estimated_slope_error = dict["slp"] self.montecarlo_seed = dict["iseed"] self.waviness_file_name = dict["file"].strip('\n\r').strip() self.harmonic_maximum_index = dict["nharmonics"] self.data["c"] = self.to_str_array(dict["c"]) self.data["y"] = self.to_str_array(dict["y"]) self.data["g"] = self.to_str_array(dict["g"]) self.reload_harmonics_table() def write_inp_file(self): try: sys.stdout = EmittingStream(textWritten=self.writeStdOut) self.check_fields() file_name = congruence.checkFileName( self.waviness_file_name.split(sep=".dat")[0] + ".inp") dict = {} dict["npointx"] = self.number_of_points_x dict["npointy"] = self.number_of_points_y dict["xlength"] = self.dimension_y dict["width"] = self.dimension_x dict["slp"] = self.estimated_slope_error dict["iseed"] = self.montecarlo_seed dict["file"] = self.waviness_file_name.strip('\n\r') dict["nharmonics"] = self.harmonic_maximum_index dict["c"] = self.to_float_array(self.data["c"]) dict["y"] = self.to_float_array(self.data["y"]) dict["g"] = self.to_float_array(self.data["g"]) ST.waviness_write(dict, file=file_name) QMessageBox.information( self, "QMessageBox.information()", "File \'" + file_name + "\' written to disk", QMessageBox.Ok) except Exception as exception: QMessageBox.critical(self, "Error", exception.args[0], QMessageBox.Ok) def calculate_waviness_ni(self): self.calculate_waviness(not_interactive_mode=True) def calculate_waviness(self, not_interactive_mode=False): try: sys.stdout = EmittingStream(textWritten=self.writeStdOut) self.check_fields() xx, yy, zz = ST.waviness_calc( npointx=self.number_of_points_x, npointy=self.number_of_points_y, width=self.dimension_x * self.workspace_units_to_cm, xlength=self.dimension_y * self.workspace_units_to_cm, slp=self.estimated_slope_error, nharmonics=self.harmonic_maximum_index, iseed=self.montecarlo_seed, c=self.to_float_array(self.data["c"]), y=self.to_float_array(self.data["y"]), g=self.to_float_array(self.data["g"])) self.xx = xx / self.workspace_units_to_cm self.yy = yy / self.workspace_units_to_cm self.zz = zz / self.workspace_units_to_cm self.axis.clear() x_to_plot, y_to_plot = numpy.meshgrid(self.xx, self.yy) z_to_plot = [] for y_index in range(0, len(yy)): z_array = [] for x_index in range(0, len(xx)): z_array.append(1e7 * float(zz[x_index][y_index])) # to nm z_to_plot.append(z_array) z_to_plot = numpy.array(z_to_plot) self.axis.plot_surface(x_to_plot, y_to_plot, z_to_plot, rstride=1, cstride=1, cmap=cm.autumn, linewidth=0.5, antialiased=True) slope, sloperms = ST.slopes(zz, xx, yy) title = ' Slope error rms in X direction: %f $\mu$rad' % (sloperms[0]*1e6) + '\n' + \ ' Slope error rms in Y direction: %f $\mu$rad' % (sloperms[1]*1e6) self.axis.set_xlabel("X [" + self.workspace_units_label + "]") self.axis.set_ylabel("Y [" + self.workspace_units_label + "]") self.axis.set_zlabel("Z [nm]") self.axis.set_title(title) self.axis.mouse_init() if not not_interactive_mode: self.figure_canvas.draw() QMessageBox.information( self, "QMessageBox.information()", "Waviness calculated: if the result is satisfactory,\nclick \'Generate Waviness File\' to complete the operation ", QMessageBox.Ok) except Exception as exception: QMessageBox.critical(self, "Error", exception.args[0], QMessageBox.Ok) def generate_waviness_file(self, not_interactive_mode=False): if not self.zz is None and not self.yy is None and not self.xx is None: try: congruence.checkDir(self.waviness_file_name) sys.stdout = EmittingStream(textWritten=self.writeStdOut) ST.write_shadow_surface(self.zz.T, self.xx, self.yy, outFile=congruence.checkFileName( self.waviness_file_name)) if not not_interactive_mode: QMessageBox.information( self, "QMessageBox.information()", "Waviness file " + self.waviness_file_name + " written on disk", QMessageBox.Ok) self.send( "PreProcessor_Data", ShadowPreProcessorData( error_profile_data_file=self.waviness_file_name, error_profile_x_dim=self.dimension_x, error_profile_y_dim=self.dimension_y)) except Exception as exception: QMessageBox.critical(self, "Error", exception.args[0], QMessageBox.Ok) def call_reset_settings(self): if ConfirmDialog.confirmed(parent=self, message="Confirm Reset of the Fields?"): try: self.resetSettings() self.reload_harmonics_table() except: pass def check_fields(self): self.number_of_points_x = congruence.checkStrictlyPositiveNumber( self.number_of_points_x, "Number of Points X") self.number_of_points_y = congruence.checkStrictlyPositiveNumber( self.number_of_points_y, "Number of Points Y") self.dimension_x = congruence.checkStrictlyPositiveNumber( self.dimension_x, "Dimension X") self.dimension_y = congruence.checkStrictlyPositiveNumber( self.dimension_y, "Dimension Y") self.estimated_slope_error = congruence.checkPositiveNumber( self.estimated_slope_error, "Estimated slope error") self.montecarlo_seed = congruence.checkPositiveNumber( self.montecarlo_seed, "Monte Carlo initial seed") self.harmonic_maximum_index = congruence.checkPositiveNumber( self.harmonic_maximum_index, "Harmonic Maximum Index") congruence.checkDir(self.waviness_file_name) def to_float_array(self, string_array): float_array = [] for index in range(len(string_array)): float_array.append(float(string_array[index])) return float_array def to_str_array(self, float_array): string_array = [] for index in range(len(float_array)): string_array.append(str(float_array[index])) return string_array def writeStdOut(self, text): cursor = self.shadow_output.textCursor() cursor.movePosition(QTextCursor.End) cursor.insertText(text) self.shadow_output.setTextCursor(cursor) self.shadow_output.ensureCursorVisible() def selectFile(self): self.le_waviness_file_name.setText( oasysgui.selectFileFromDialog( self, self.waviness_file_name, "Select Output File", file_extension_filter="Data Files (*.dat)"))
def home_data(cls): if platform.system() == "Windows": return resources.package_dirname("orangecontrib.xoppy.util") + "\data/" else: return resources.package_dirname("orangecontrib.xoppy.util") + "/data/"
class OWReflectivityGenerator(SRWWidget): name = "SRW Reflectivity Generator" description = "Utility: SRW Reflectivity Generator" icon = "icons/reflectivity.png" maintainer = "Luca Rebuffi" maintainer_email = "lrebuffi(@at@)anl.gov" priority = 3 category = "Utility" keywords = ["data", "file", "load", "read"] want_main_area = 1 file_name = Setting("") data_path = Setting("") inputs = [] inputs = [("Reflectivity (Total/Unpol.)", DataExchangeObject, "set_input_1"), ("Reflectivity (\u03c3)", DataExchangeObject, "set_input_2"), ("Reflectivity (\u03c0)", DataExchangeObject, "set_input_3")] outputs = [{ "name": "Reflectivity Data", "type": SRWPreProcessorData, "doc": "Reflectivity Data", "id": "data" }] reflectivity_unpol_data = None reflectivity_p_data = None reflectivity_s_data = None data_file_name = Setting("reflectivity.dat") energy_single_value = Setting(0.0) angle_single_value = Setting(0.0) TABS_AREA_HEIGHT = 618 CONTROL_AREA_WIDTH = 405 usage_path = os.path.join( resources.package_dirname("orangecontrib.srw.widgets.gui"), "misc", "reflectivity_generator_usage.png") def __init__(self): super().__init__(show_general_option_box=False, show_automatic_box=False) self.main_tabs = oasysgui.tabWidget(self.mainArea) self.clear_tabs() button_box = oasysgui.widgetBox(self.controlArea, "", addSpace=False, orientation="horizontal") button = gui.button(button_box, self, "Generate Reflectivity File", callback=self.generate_reflectivity_file) font = QFont(button.font()) font.setBold(True) button.setFont(font) palette = QPalette(button.palette()) # make a copy of the palette palette.setColor(QPalette.ButtonText, QColor('Dark Blue')) button.setPalette(palette) # assign new palette button.setFixedHeight(45) button = gui.button(button_box, self, "Reset Fields", callback=self.callResetSettings) font = QFont(button.font()) font.setItalic(True) button.setFont(font) palette = QPalette(button.palette()) # make a copy of the palette palette.setColor(QPalette.ButtonText, QColor('Dark Red')) button.setPalette(palette) # assign new palette button.setFixedHeight(45) button.setFixedWidth(150) gui.separator(self.controlArea) self.controlArea.setFixedWidth(self.CONTROL_AREA_WIDTH) tabs_setting = oasysgui.tabWidget(self.controlArea) tabs_setting.setFixedHeight(self.TABS_AREA_HEIGHT) tabs_setting.setFixedWidth(self.CONTROL_AREA_WIDTH - 5) tab_bas = oasysgui.createTabPage(tabs_setting, "Reflectivity Generator Setting") tab_usa = oasysgui.createTabPage(tabs_setting, "Use of the Widget") tab_usa.setStyleSheet("background-color: white;") usage_box = oasysgui.widgetBox(tab_usa, "", addSpace=True, orientation="horizontal") label = QLabel("") label.setAlignment(Qt.AlignCenter) label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) label.setPixmap(QPixmap(self.usage_path)) usage_box.layout().addWidget(label) file_box = oasysgui.widgetBox(tab_bas, "", addSpace=False, orientation="horizontal") self.le_data_file_name = oasysgui.lineEdit(file_box, self, "data_file_name", "Output File Name", labelWidth=150, valueType=str, orientation="horizontal") gui.button(file_box, self, "...", callback=self.selectDataFile) self.energy_box = oasysgui.widgetBox(tab_bas, "", addSpace=False, orientation="vertical") oasysgui.lineEdit(self.energy_box, self, "energy_single_value", "Energy Single Value [eV]", labelWidth=250, valueType=float, orientation="horizontal") self.angle_box = oasysgui.widgetBox(tab_bas, "", addSpace=False, orientation="vertical") oasysgui.lineEdit(self.angle_box, self, "angle_single_value", "Angle Single Value [rad]", labelWidth=250, valueType=float, orientation="horizontal") self.energy_box.setVisible(False) self.angle_box.setVisible(False) def selectDataFile(self): self.le_data_file_name.setText( oasysgui.selectFileFromDialog(self, self.data_file_name, "Output Data File")) def generate_reflectivity_file(self): file_name = congruence.checkFileName(self.data_file_name) output_data = SRWPreProcessorData( reflectivity_data=SRWReflectivityData( reflectivity_data_file=self.data_file_name)) data_txt = "" if not self.reflectivity_unpol_data is None: try: reflectivity_data = self.reflectivity_unpol_data.get_content( "data2D") energy = self.reflectivity_unpol_data.get_content("dataX") angle = self.reflectivity_unpol_data.get_content( "dataY") * 0.001 #to rad output_data.reflectivity_data.energies_number = len(energy) output_data.reflectivity_data.angles_number = len(angle) output_data.reflectivity_data.components_number = 1 output_data.reflectivity_data.energy_start = energy[0] output_data.reflectivity_data.energy_end = energy[-1] output_data.reflectivity_data.energy_scale_type = ScaleType.LINEAR output_data.reflectivity_data.angle_start = angle[0] output_data.reflectivity_data.angle_end = angle[-1] output_data.reflectivity_data.angle_scale_type = ScaleType.LINEAR data_txt = "" for i in range(0, len(angle)): for j in range(0, len(energy)): if not (i == 0 and j == 0): data_txt += "\n" data_txt += str(reflectivity_data[j, i]) + "\n0.0" except: try: reflectivity_data = self.reflectivity_unpol_data.get_content( "xoppy_data") labels = self.reflectivity_unpol_data.get_content("labels") x_col = int( self.reflectivity_unpol_data.get_content("plot_x_col")) y_col = int( self.reflectivity_unpol_data.get_content("plot_y_col")) if "Energy" in labels[0]: congruence.checkStrictlyPositiveNumber( self.angle_single_value, "Angle Single Value") output_data.reflectivity_data.energies_number = len( reflectivity_data) output_data.reflectivity_data.angles_number = 1 output_data.reflectivity_data.energy_start = reflectivity_data[ 0, x_col] output_data.reflectivity_data.energy_end = reflectivity_data[ -1, x_col] output_data.reflectivity_data.angle_start = self.angle_single_value output_data.reflectivity_data.angle_end = self.angle_single_value elif "Theta" in labels[0]: congruence.checkStrictlyPositiveNumber( self.energy_single_value, "Energy Single Value") output_data.reflectivity_data.energies_number = 1 output_data.reflectivity_data.angles_number = len( reflectivity_data) output_data.reflectivity_data.energy_start = self.energy_single_value output_data.reflectivity_data.energy_end = self.energy_single_value output_data.reflectivity_data.angle_start = reflectivity_data[ 0, x_col] * 0.001 #to rad output_data.reflectivity_data.angle_end = reflectivity_data[ -1, x_col] * 0.001 #to rad output_data.reflectivity_data.components_number = 1 output_data.reflectivity_data.energy_scale_type = ScaleType.LINEAR output_data.reflectivity_data.angle_scale_type = ScaleType.LINEAR for i in range(0, len(reflectivity_data)): if i != 0: data_txt += "\n" data_txt += str(reflectivity_data[i, y_col]) + "\n0.0" except Exception as exception: QMessageBox.critical(self, "Error", str(exception), QMessageBox.Ok) if self.IS_DEVELOP: raise exception return if not data_txt == "": file = open(file_name, "w") file.write(data_txt) file.flush() file.close() self.send("Reflectivity Data", output_data) elif not self.reflectivity_s_data is None and not self.reflectivity_p_data is None: try: reflectivity_s = self.reflectivity_s_data.get_content("data2D") energy_s = self.reflectivity_s_data.get_content("dataX") angle_s = self.reflectivity_s_data.get_content( "dataY") * 0.001 #to rad try: reflectivity_p = self.reflectivity_p_data.get_content( "data2D") energy_p = self.reflectivity_p_data.get_content("dataX") angle_p = self.reflectivity_p_data.get_content( "dataY") * 0.001 #to rad if (len(energy_s) != len(energy_p)) or \ (energy_p[0] != energy_s[0]) or \ (energy_p[-1] != energy_s[-1]) or \ (len(angle_s) != len(angle_p)) or \ (angle_p[0] != angle_s[0]) or \ (angle_p[-1] != angle_s[-1]): QMessageBox.critical( self, "Error", "Reflectivity data have different dimension or different range of Energy/Angle values", QMessageBox.Ok) return output_data.reflectivity_data.energies_number = len( energy_s) output_data.reflectivity_data.angles_number = len(angle_s) output_data.reflectivity_data.components_number = 2 output_data.reflectivity_data.energy_start = energy_s[0] output_data.reflectivity_data.energy_end = energy_s[-1] output_data.reflectivity_data.energy_scale_type = ScaleType.LINEAR output_data.reflectivity_data.angle_start = angle_s[0] output_data.reflectivity_data.angle_end = angle_s[-1] output_data.reflectivity_data.angle_scale_type = ScaleType.LINEAR data_txt = "" for i in range(0, len(angle_s)): for j in range(0, len(energy_s)): if not (i == 0 and j == 0): data_txt += "\n" data_txt += str(reflectivity_s[j, i]) + "\n0.0" for i in range(0, len(angle_p)): for j in range(0, len(energy_p)): data_txt += "\n" + str(reflectivity_p[j, i]) + "\n0.0" except: QMessageBox.critical( self, "Error", "Reflectivity data have different dimension", QMessageBox.Ok) return except: try: reflectivity_s = self.reflectivity_s_data.get_content( "xoppy_data") labels_s = self.reflectivity_s_data.get_content("labels") x_col = int( self.reflectivity_s_data.get_content("plot_x_col")) y_col = int( self.reflectivity_s_data.get_content("plot_y_col")) try: reflectivity_p = self.reflectivity_p_data.get_content( "xoppy_data") labels_p = self.reflectivity_p_data.get_content( "labels") if (len(reflectivity_p) != len(reflectivity_s)) or \ (reflectivity_s[0, x_col] != reflectivity_p[0, x_col]) or \ (reflectivity_s[-1, x_col] != reflectivity_p[-1, x_col]) or \ (labels_s[0] != labels_p[0]): QMessageBox.critical( self, "Error", "Reflectivity data have different dimension or different range of Energy/Angle values", QMessageBox.Ok) return try: if "Energy" in labels_s[0]: congruence.checkStrictlyPositiveNumber( self.angle_single_value, "Angle Single Value") output_data.reflectivity_data.energies_number = len( reflectivity_s) output_data.reflectivity_data.angles_number = 1 output_data.reflectivity_data.energy_start = reflectivity_s[ 0, x_col] output_data.reflectivity_data.energy_end = reflectivity_s[ -1, x_col] output_data.reflectivity_data.angle_start = self.angle_single_value output_data.reflectivity_data.angle_end = self.angle_single_value elif "Theta" in labels_s[0]: congruence.checkStrictlyPositiveNumber( self.energy_single_value, "Energy Single Value") output_data.reflectivity_data.energies_number = 1 output_data.reflectivity_data.angles_number = len( reflectivity_s) output_data.reflectivity_data.energy_start = self.energy_single_value output_data.reflectivity_data.energy_end = self.energy_single_value output_data.reflectivity_data.angle_start = reflectivity_s[ 0, x_col] * 0.001 #to rad output_data.reflectivity_data.angle_end = reflectivity_s[ -1, x_col] * 0.001 #to rad except Exception as exception: QMessageBox.critical(self, "Error", str(exception), QMessageBox.Ok) if self.IS_DEVELOP: raise exception return output_data.reflectivity_data.components_number = 2 output_data.reflectivity_data.energy_scale_type = ScaleType.LINEAR output_data.reflectivity_data.angle_scale_type = ScaleType.LINEAR for i in range(0, len(reflectivity_s)): if i != 0: data_txt += "\n" data_txt += str(reflectivity_s[i, y_col]) + "\n0.0" for i in range(0, len(reflectivity_p)): data_txt += "\n" + str( reflectivity_p[i, y_col]) + "\n0.0" except: QMessageBox.critical( self, "Error", "Reflectivity data have different dimension", QMessageBox.Ok) return except Exception as exception: QMessageBox.critical(self, "Error", str(exception), QMessageBox.Ok) if self.IS_DEVELOP: raise exception return if not data_txt == "": file = open(file_name, "w") file.write(data_txt) file.flush() file.close() self.send("Reflectivity Data", output_data) else: QMessageBox.critical( self, "Error", "Incomplete Data: connect Total Polarization Data or BOTH Polarizations Data", QMessageBox.Ok) def set_input_1(self, data): self.reflectivity_unpol_data = data if not self.reflectivity_unpol_data is None: self.reflectivity_p_data = None self.reflectivity_s_data = None try: self.reflectivity_unpol_data.get_content("xoppy_data") labels = self.reflectivity_unpol_data.get_content("labels") if "Energy" in labels[0]: self.angle_box.setVisible(True) self.energy_box.setVisible(False) elif "Theta" in labels[0]: self.angle_box.setVisible(False) self.energy_box.setVisible(True) except: self.angle_box.setVisible(False) self.energy_box.setVisible(False) self.plot_results() self.main_tabs.setCurrentIndex(0) def set_input_2(self, data): self.reflectivity_s_data = data if not self.reflectivity_s_data is None: self.reflectivity_unpol_data = None try: self.reflectivity_s_data.get_content("xoppy_data") labels = self.reflectivity_s_data.get_content("labels") if "Energy" in labels[0]: self.angle_box.setVisible(True) self.energy_box.setVisible(False) elif "Theta" in labels[0]: self.angle_box.setVisible(False) self.energy_box.setVisible(True) except: #2D if not self.reflectivity_p_data is None: try: self.reflectivity_p_data.get_content("xoppy_data") except: self.angle_box.setVisible(False) self.energy_box.setVisible(False) self.plot_results() self.main_tabs.setCurrentIndex(1) def set_input_3(self, data): self.reflectivity_p_data = data if not self.reflectivity_p_data is None: self.reflectivity_unpol_data = None try: self.reflectivity_p_data.get_content("xoppy_data") labels = self.reflectivity_p_data.get_content("labels") if "Energy" in labels[0]: self.angle_box.setVisible(True) self.energy_box.setVisible(False) elif "Theta" in labels[0]: self.angle_box.setVisible(False) self.energy_box.setVisible(True) except: #2D if not self.reflectivity_s_data is None: try: self.reflectivity_s_data.get_content("xoppy_data") except: self.angle_box.setVisible(False) self.energy_box.setVisible(False) self.plot_results() self.main_tabs.setCurrentIndex(2) def plot_results(self): self.progressBarInit() self.clear_tabs() self.plot_data(self.reflectivity_unpol_data, 0, 0, "Reflectivity (Total/Unpol.)") self.progressBarSet(30) self.plot_data(self.reflectivity_s_data, 1, 1, "Reflectivity (\u03c3)") self.progressBarSet(60) self.plot_data(self.reflectivity_p_data, 2, 2, "Reflectivity (\u03c0)") self.progressBarSet(90) self.progressBarFinished() def clear_tabs(self): self.main_tabs.clear() self.tab = [ oasysgui.createTabPage(self.main_tabs, "Total/Unpolarized Reflectivity"), oasysgui.createTabPage(self.main_tabs, "\u03c3 Reflectivity"), oasysgui.createTabPage(self.main_tabs, "\u03c0 Reflectivity") ] self.plot_canvas = [None, None, None] def plot_data(self, data, tabs_canvas_index, plot_canvas_index, title): if not data is None: try: data2D = data.get_content("data2D") dataX = data.get_content("dataX") dataY = data.get_content("dataY") self.plot_data2D(data2D, dataX, dataY, tabs_canvas_index, plot_canvas_index, xtitle='Energy [eV]', ytitle='Theta [mrad]', title=title) except: try: xoppy_data = data.get_content("xoppy_data") x_col = int(data.get_content("plot_x_col")) y_col = int(data.get_content("plot_y_col")) labels = data.get_content("labels") self.plot_histo(xoppy_data[:, x_col], xoppy_data[:, y_col], tabs_canvas_index=tabs_canvas_index, plot_canvas_index=plot_canvas_index, title=title, xtitle=labels[0], ytitle=labels[1]) except Exception as exception: QMessageBox.critical(self, "Error", str(exception), QMessageBox.Ok) if self.IS_DEVELOP: raise exception def plot_histo(self, x, y, tabs_canvas_index, plot_canvas_index, title="", xtitle="", ytitle="", log_x=False, log_y=False, color='blue', replace=True, control=False): self.plot_canvas[plot_canvas_index] = oasysgui.plotWindow( parent=None, backend=None, resetzoom=True, autoScale=False, logScale=True, grid=True, curveStyle=True, colormap=False, aspectRatio=False, yInverted=False, copy=True, save=True, print_=True, control=control, position=True, roi=False, mask=False, fit=False) self.plot_canvas[plot_canvas_index].setDefaultPlotLines(True) self.plot_canvas[plot_canvas_index].setActiveCurveColor( color="#00008B") self.plot_canvas[plot_canvas_index].setGraphTitle(title) self.plot_canvas[plot_canvas_index].setGraphXLabel(xtitle) self.plot_canvas[plot_canvas_index].setGraphYLabel(ytitle) self.tab[tabs_canvas_index].layout().addWidget( self.plot_canvas[plot_canvas_index]) import matplotlib matplotlib.rcParams['axes.formatter.useoffset'] = 'False' self.plot_canvas[plot_canvas_index].addCurve( x, y, title, symbol='', color=color, xlabel=xtitle, ylabel=ytitle, replace=replace) #'+', '^', ',' self.plot_canvas[plot_canvas_index].resetZoom() self.plot_canvas[plot_canvas_index].replot() self.plot_canvas[plot_canvas_index].setActiveCurve(title) self.plot_canvas[plot_canvas_index].setXAxisLogarithmic(log_x) self.plot_canvas[plot_canvas_index].setYAxisLogarithmic(log_y) if min(y) < 0: if log_y: self.plot_canvas[plot_canvas_index].setGraphYLimits( min(y) * 1.2, max(y) * 1.2) else: self.plot_canvas[plot_canvas_index].setGraphYLimits( min(y) * 1.01, max(y) * 1.01) else: if log_y: self.plot_canvas[plot_canvas_index].setGraphYLimits( min(y), max(y) * 1.2) else: self.plot_canvas[plot_canvas_index].setGraphYLimits( min(y), max(y) * 1.01) def plot_data2D(self, data2D, dataX, dataY, tabs_canvas_index, plot_canvas_index, title="", xtitle="", ytitle=""): origin = (dataX[0], dataY[0]) scale = (dataX[1] - dataX[0], dataY[1] - dataY[0]) data_to_plot = data2D.T colormap = { "name": "temperature", "normalization": "linear", "autoscale": True, "vmin": 0, "vmax": 0, "colors": 256 } self.plot_canvas[plot_canvas_index] = Plot2D() self.plot_canvas[plot_canvas_index].resetZoom() self.plot_canvas[plot_canvas_index].setXAxisAutoScale(True) self.plot_canvas[plot_canvas_index].setYAxisAutoScale(True) self.plot_canvas[plot_canvas_index].setGraphGrid(False) self.plot_canvas[plot_canvas_index].setKeepDataAspectRatio(True) self.plot_canvas[plot_canvas_index].yAxisInvertedAction.setVisible( False) self.plot_canvas[plot_canvas_index].setXAxisLogarithmic(False) self.plot_canvas[plot_canvas_index].setYAxisLogarithmic(False) self.plot_canvas[plot_canvas_index].getMaskAction().setVisible(False) self.plot_canvas[plot_canvas_index].getRoiAction().setVisible(False) self.plot_canvas[plot_canvas_index].getColormapAction().setVisible( False) self.plot_canvas[plot_canvas_index].setKeepDataAspectRatio(False) self.plot_canvas[plot_canvas_index].addImage(numpy.array(data_to_plot), legend="image1", scale=scale, origin=origin, colormap=colormap, replace=True) self.plot_canvas[plot_canvas_index].setActiveImage("image1") self.plot_canvas[plot_canvas_index].setGraphXLabel(xtitle) self.plot_canvas[plot_canvas_index].setGraphYLabel(ytitle) self.plot_canvas[plot_canvas_index].setGraphTitle(title) self.tab[tabs_canvas_index].layout().addWidget( self.plot_canvas[plot_canvas_index])
class OWVlsPgmCoefficientsCalculator(OWWidget): name = "VLS PGM Coefficients Calculator" id = "VlsPgmCoefficientsCalculator" description = "Calculation of coefficients for VLS PGM" icon = "icons/vls_pgm.png" author = "Luca Rebuffi" maintainer_email = "*****@*****.**" priority = 10 category = "" keywords = ["oasys", "vls", "pgm"] outputs = [{ "name": "PreProcessor_Data", "type": VlsPgmPreProcessorData, "doc": "PreProcessor Data", "id": "PreProcessor_Data" }] want_main_area = True last_element_distance = Setting(0.0) r_a = Setting(0.0) r_b = Setting(0.0) k = Setting(1000) h = Setting(20) units_in_use = Setting(0) photon_wavelength = Setting(25.0) photon_energy = Setting(500.0) c = Setting(1.2) grating_diffraction_order = Setting(-1) new_units_in_use = Setting(0) new_photon_wavelength = Setting(25.0) new_photon_energy = Setting(500.0) image_path = os.path.join( resources.package_dirname("orangecontrib.shadow.widgets.gui"), "misc", "vls_pgm_layout.png") usage_path = os.path.join( resources.package_dirname("orangecontrib.shadow.widgets.gui"), "misc", "vls_pgm_usage.png") design_alpha = 0.0 design_beta = 0.0 b2 = 0.0 b3 = 0.0 b4 = 0.0 shadow_coeff_0 = 0.0 shadow_coeff_1 = 0.0 shadow_coeff_2 = 0.0 shadow_coeff_3 = 0.0 d_source_to_mirror = 0.0 d_source_plane_to_mirror = 0.0 d_mirror_to_grating = 0.0 raytracing_alpha = 0.0 raytracing_beta = 0.0 def __init__(self): super().__init__() self.runaction = widget.OWAction("Compute", self) self.runaction.triggered.connect(self.compute) self.addAction(self.runaction) self.setFixedWidth(1170) self.setFixedHeight(500) gui.separator(self.controlArea) box0 = oasysgui.widgetBox(self.controlArea, "", orientation="horizontal") #widget buttons: compute, set defaults, help button = gui.button(box0, self, "Compute", callback=self.compute) button.setFixedHeight(45) button = gui.button(box0, self, "Defaults", callback=self.defaults) button.setFixedHeight(45) tabs_setting = oasysgui.tabWidget(self.controlArea) tabs_setting.setFixedHeight(425) tab_step_1 = oasysgui.createTabPage(tabs_setting, "Line Density Calculation") tab_step_2 = oasysgui.createTabPage(tabs_setting, "Angles Calculation") tab_usa = oasysgui.createTabPage(tabs_setting, "Use of the Widget") tab_usa.setStyleSheet("background-color: white;") usage_box = oasysgui.widgetBox(tab_usa, "", addSpace=True, orientation="horizontal") label = QLabel("") label.setAlignment(Qt.AlignCenter) label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) label.setPixmap(QPixmap(self.usage_path)) usage_box.layout().addWidget(label) box = oasysgui.widgetBox(tab_step_1, "VLS-PGM Layout Parameters", orientation="vertical") self.le_r_a = oasysgui.lineEdit(box, self, "r_a", "Distance Source-Grating", labelWidth=260, valueType=float, orientation="horizontal") self.le_r_b = oasysgui.lineEdit(box, self, "r_b", "Distance Grating-Exit Slits", labelWidth=260, valueType=float, orientation="horizontal") self.le_h = oasysgui.lineEdit(box, self, "h", "Vertical Distance Mirror-Grating", labelWidth=260, valueType=float, orientation="horizontal") self.le_l_e = oasysgui.lineEdit( box, self, "last_element_distance", "Distance Source-Last Image Plane\nbefore Mirror (if present)", labelWidth=260, valueType=float, orientation="horizontal") self.le_k = oasysgui.lineEdit(box, self, "k", "Line Density (0th coeff.)", labelWidth=260, valueType=float, orientation="horizontal") gui.separator(box) box_2 = oasysgui.widgetBox(tab_step_1, "Grating Design Parameters", orientation="vertical") gui.comboBox(box_2, self, "units_in_use", label="Units in use", labelWidth=260, items=["eV", "Angstroms"], callback=self.set_UnitsInUse, sendSelectedValue=False, orientation="horizontal") self.autosetting_box_units_1 = oasysgui.widgetBox( box_2, "", addSpace=False, orientation="vertical") oasysgui.lineEdit(self.autosetting_box_units_1, self, "photon_energy", "Photon energy [eV]", labelWidth=260, valueType=float, orientation="horizontal") self.autosetting_box_units_2 = oasysgui.widgetBox( box_2, "", addSpace=False, orientation="vertical") oasysgui.lineEdit(self.autosetting_box_units_2, self, "photon_wavelength", "Wavelength [Å]", labelWidth=260, valueType=float, orientation="horizontal") self.set_UnitsInUse() oasysgui.lineEdit(box_2, self, "c", "C factor for optimized energy", labelWidth=260, valueType=float, orientation="horizontal") oasysgui.lineEdit(box_2, self, "grating_diffraction_order", "Diffraction Order (- for inside orders)", labelWidth=260, valueType=int, orientation="horizontal") ################################## box_3 = oasysgui.widgetBox(tab_step_2, "Ray-Tracing Parameter", orientation="vertical") gui.comboBox(box_3, self, "new_units_in_use", label="Units in use", labelWidth=260, items=["eV", "Angstroms"], callback=self.set_UnitsInUse2, sendSelectedValue=False, orientation="horizontal") self.autosetting_box_units_3 = oasysgui.widgetBox( box_3, "", addSpace=False, orientation="vertical") oasysgui.lineEdit(self.autosetting_box_units_3, self, "new_photon_energy", "New photon energy [eV]", labelWidth=260, valueType=float, orientation="horizontal") self.autosetting_box_units_4 = oasysgui.widgetBox( box_3, "", addSpace=False, orientation="vertical") oasysgui.lineEdit(self.autosetting_box_units_4, self, "new_photon_wavelength", "New wavelength [Å]", labelWidth=260, valueType=float, orientation="horizontal") self.set_UnitsInUse2() tabs_out = oasysgui.tabWidget(self.mainArea) tab_out_1 = oasysgui.createTabPage(tabs_out, "Calculation Results") tab_out_2 = oasysgui.createTabPage(tabs_out, "Output") figure_box_1 = oasysgui.widgetBox(tab_out_1, "", addSpace=True, orientation="horizontal") label = QLabel("") label.setPixmap(QPixmap(self.image_path)) figure_box_1.layout().addWidget(label) output_box = oasysgui.widgetBox(tab_out_1, "", addSpace=True, orientation="horizontal") output_box_1 = oasysgui.widgetBox(output_box, "Design Ouput", addSpace=True, orientation="vertical") oasysgui.lineEdit(output_box_1, self, "design_alpha", "Alpha [deg]", labelWidth=220, valueType=float, orientation="horizontal") oasysgui.lineEdit(output_box_1, self, "design_beta", "Beta [deg]", labelWidth=220, valueType=float, orientation="horizontal") gui.separator(output_box_1) self.le_shadow_coeff_0 = oasysgui.lineEdit(output_box_1, self, "shadow_coeff_0", "Line Density 0-coeff.", labelWidth=220, valueType=float, orientation="horizontal") self.le_shadow_coeff_1 = oasysgui.lineEdit(output_box_1, self, "shadow_coeff_1", "Line Density 1-coeff.", labelWidth=220, valueType=float, orientation="horizontal") self.le_shadow_coeff_2 = oasysgui.lineEdit(output_box_1, self, "shadow_coeff_2", "Line Density 2-coeff.", labelWidth=220, valueType=float, orientation="horizontal") self.le_shadow_coeff_3 = oasysgui.lineEdit(output_box_1, self, "shadow_coeff_3", "Line Density 3-coeff.", labelWidth=220, valueType=float, orientation="horizontal") output_box_2 = oasysgui.widgetBox(output_box, "Ray-Tracing Ouput", addSpace=True, orientation="vertical") oasysgui.lineEdit(output_box_2, self, "raytracing_alpha", "Alpha [deg]", labelWidth=220, valueType=float, orientation="horizontal") oasysgui.lineEdit(output_box_2, self, "raytracing_beta", "Beta [deg]", labelWidth=220, valueType=float, orientation="horizontal") gui.separator(output_box_2) self.le_d_source_to_mirror = oasysgui.lineEdit( output_box_2, self, "d_source_to_mirror", "Source to Mirror distance", labelWidth=230, valueType=float, orientation="horizontal") self.le_d_source_plane_to_mirror = oasysgui.lineEdit( output_box_2, self, "d_source_plane_to_mirror", "Source Plane to Mirror distance", labelWidth=230, valueType=float, orientation="horizontal") self.le_d_mirror_to_grating = oasysgui.lineEdit( output_box_2, self, "d_mirror_to_grating", "Mirror to Grating distance", labelWidth=230, valueType=float, orientation="horizontal") self.shadow_output = oasysgui.textArea() out_box = oasysgui.widgetBox(tab_out_2, "System Output", addSpace=True, orientation="horizontal", height=400) out_box.layout().addWidget(self.shadow_output) gui.rubber(self.controlArea) def after_change_workspace_units(self): label = self.le_r_a.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_r_b.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_l_e.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_k.parent().layout().itemAt(0).widget() label.setText(label.text() + " [Lines/" + self.workspace_units_label + "]") label = self.le_d_source_to_mirror.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_d_source_plane_to_mirror.parent().layout().itemAt( 0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_d_mirror_to_grating.parent().layout().itemAt( 0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_shadow_coeff_0.parent().layout().itemAt(0).widget() label.setText(label.text() + " [Lines." + self.workspace_units_label + "-1]") label = self.le_shadow_coeff_1.parent().layout().itemAt(0).widget() label.setText(label.text() + " [Lines." + self.workspace_units_label + "-2]") label = self.le_shadow_coeff_2.parent().layout().itemAt(0).widget() label.setText(label.text() + " [Lines." + self.workspace_units_label + "-3]") label = self.le_shadow_coeff_3.parent().layout().itemAt(0).widget() label.setText(label.text() + " [Lines." + self.workspace_units_label + "-4]") def set_UnitsInUse(self): self.autosetting_box_units_1.setVisible(self.units_in_use == 0) self.autosetting_box_units_2.setVisible(self.units_in_use == 1) def set_UnitsInUse2(self): self.autosetting_box_units_3.setVisible(self.new_units_in_use == 0) self.autosetting_box_units_4.setVisible(self.new_units_in_use == 1) def compute(self): try: self.shadow_output.setText("") sys.stdout = EmittingStream(textWritten=self.writeStdOut) self.checkFields() m = -self.grating_diffraction_order if self.units_in_use == 0: wavelength = ShadowPhysics.getWavelengthFromEnergy( self.photon_energy) / self.workspace_units_to_m * 1e-10 elif self.units_in_use == 1: wavelength = self.photon_wavelength / self.workspace_units_to_m * 1e-10 sin_alpha = (-m*self.k*wavelength/(self.c**2 - 1)) + \ numpy.sqrt(1 + (m*m*self.c*self.c*self.k*self.k*wavelength*wavelength)/((self.c**2 - 1)**2)) alpha = numpy.arcsin(sin_alpha) beta = numpy.arcsin(sin_alpha - m * self.k * wavelength) self.design_alpha = round(numpy.degrees(alpha), 3) self.design_beta = round(numpy.degrees(beta), 3) #_beta = numpy.arccos(self.c*numpy.cos(alpha)) print("####################################################") print("# DESIGN PHASE") print("####################################################\n") print("Photon Wavelength:", wavelength, self.workspace_units_label) print("Design ALPHA :", self.design_alpha, "deg") print("Design BETA :", self.design_beta, "deg") self.b2 = (((numpy.cos(alpha)**2) / self.r_a) + ((numpy.cos(beta)**2) / self.r_b)) / (-2 * m * self.k * wavelength) self.b3 = ((numpy.sin(alpha)*numpy.cos(alpha)**2)/self.r_a**2 - \ (numpy.sin(beta)*numpy.cos(beta)**2)/self.r_b**2)/(-2*m*self.k*wavelength) self.b4 = (((4*numpy.sin(alpha)**2 - numpy.cos(alpha)**2)*numpy.cos(alpha)**2)/self.r_a**3 + \ ((4*numpy.sin(beta)**2 - numpy.cos(beta)**2)*numpy.cos(beta)**2)/self.r_b**3)/(-8*m*self.k*wavelength) print("\nb2:", self.b2) print("b3:", self.b3) print("b4:", self.b4) self.shadow_coeff_0 = round(self.k, 8) self.shadow_coeff_1 = round(-2 * self.k * self.b2, 8) self.shadow_coeff_2 = round(3 * self.k * self.b3, 8) self.shadow_coeff_3 = round(-4 * self.k * self.b4, 8) print("\nshadow_coeff_0:", self.shadow_coeff_0) print("shadow_coeff_1:", self.shadow_coeff_1) print("shadow_coeff_2:", self.shadow_coeff_2) print("shadow_coeff_3:", self.shadow_coeff_3) ############################################ # # 1 - in case of mirror recalculate real ray tracing distance (r_a') from initial r_a and vertical distance # between grating and mirror (h) # gamma = (alpha + beta) / 2 d_source_to_mirror = self.r_a - ( self.h / numpy.abs(numpy.tan(numpy.pi - 2 * gamma))) d_mirror_to_grating = self.h / numpy.abs( numpy.sin(numpy.pi - 2 * gamma)) r_a_first = d_source_to_mirror + d_mirror_to_grating print("\ngamma :", numpy.degrees(gamma), "deg") print("Source to Mirror distance :", d_source_to_mirror, self.workspace_units_label) print("Mirror to Grating distance:", d_mirror_to_grating, self.workspace_units_label) print("R_a' :", r_a_first, self.workspace_units_label) ############################################ if self.new_units_in_use == 0: newwavelength = ShadowPhysics.getWavelengthFromEnergy( self.new_photon_energy) / self.workspace_units_to_m * 1e-10 elif self.new_units_in_use == 1: newwavelength = self.new_photon_wavelength / self.workspace_units_to_m * 1e-10 r = self.r_b / r_a_first A0 = self.k * newwavelength A2 = self.k * newwavelength * self.r_b * self.b2 new_c_num = 2*A2 + 4*(A2/A0)**2 + \ (4 + 2*A2 - A0**2)*r - \ 4*(A2/A0)*numpy.sqrt((1 + r)**2 + 2*A2*(1 + r) - r*A0**2) new_c_den = -4 + A0**2 - 4 * A2 + 4 * (A2 / A0)**2 new_c = numpy.sqrt(new_c_num / new_c_den) new_sin_alpha = (-m*self.k*newwavelength/(new_c**2 - 1)) + \ numpy.sqrt(1 + (m*m*new_c*new_c*self.k*self.k*newwavelength*newwavelength)/((new_c**2 - 1)**2)) new_alpha = numpy.arcsin(new_sin_alpha) new_beta = numpy.arcsin(new_sin_alpha - m * self.k * newwavelength) self.raytracing_alpha = round(numpy.degrees(new_alpha), 6) self.raytracing_beta = round(numpy.degrees(new_beta), 6) #_new_beta = numpy.arccos(new_c*numpy.cos(new_alpha)) print("####################################################") print("# RAY-TRACING PHASE") print("####################################################\n") print("Ray-Tracing Wavelength:", newwavelength, self.workspace_units_label) print("Ray-Tracing C :", new_c) print("Ray-Tracing ALPHA :", self.raytracing_alpha, "deg") print("Ray-Tracing BETA :", self.raytracing_beta, "deg") gamma = (new_alpha + new_beta) / 2 self.d_source_to_mirror = self.r_a - ( self.h / numpy.abs(numpy.tan(numpy.pi - 2 * gamma))) self.d_mirror_to_grating = self.h / numpy.abs( numpy.sin(numpy.pi - 2 * gamma)) r_a_first = self.d_source_to_mirror + self.d_mirror_to_grating self.d_source_to_mirror = round(self.d_source_to_mirror, 3) self.d_source_plane_to_mirror = round( self.d_source_to_mirror - self.last_element_distance, 3) self.d_mirror_to_grating = round(self.d_mirror_to_grating, 3) print("\ngamma :", numpy.degrees(gamma), "deg") print("Source to Mirror distance :", self.d_source_to_mirror, self.workspace_units_label) print("Source Plane to Mirror distance :", self.d_source_plane_to_mirror, self.workspace_units_label) print("Mirror to Grating distance :", self.d_mirror_to_grating, self.workspace_units_label) print("R_a' :", r_a_first, self.workspace_units_label) self.send( "PreProcessor_Data", VlsPgmPreProcessorData( shadow_coeff_0=self.shadow_coeff_0, shadow_coeff_1=self.shadow_coeff_1, shadow_coeff_2=self.shadow_coeff_2, shadow_coeff_3=self.shadow_coeff_3, d_source_plane_to_mirror=self.d_source_plane_to_mirror, d_mirror_to_grating=self.d_mirror_to_grating, d_grating_to_exit_slits=self.r_b, alpha=self.raytracing_alpha, beta=self.raytracing_beta)) except Exception as exception: QMessageBox.critical(self, "Error", str(exception), QMessageBox.Ok) def checkFields(self): self.r_a = congruence.checkPositiveNumber(self.r_a, "Distance Source-Grating") self.r_b = congruence.checkPositiveNumber( self.r_b, "Distance Grating-Exit Slits") self.last_element_distance = congruence.checkPositiveNumber( self.last_element_distance, "Distance Source-Last Image Plane before Mirror") congruence.checkLessOrEqualThan( self.last_element_distance, self.r_a, "Distance Source-Last Image Plane before Mirror", "Distance Source-Grating") self.k = congruence.checkStrictlyPositiveNumber(self.k, "Line Density") if self.units_in_use == 0: self.photon_energy = congruence.checkPositiveNumber( self.photon_energy, "Photon Energy") elif self.units_in_use == 1: self.photon_wavelength = congruence.checkPositiveNumber( self.photon_wavelength, "Photon Wavelength") def defaults(self): self.resetSettings() def writeStdOut(self, text): cursor = self.shadow_output.textCursor() cursor.movePosition(QTextCursor.End) cursor.insertText(text) self.shadow_output.setTextCursor(cursor) self.shadow_output.ensureCursorVisible()
class OWSRWCrystal(OWSRWOpticalElement): inputs = [("SRWData", SRWData, "set_input"), ("Trigger", TriggerOut, "propagate_new_wavefront"), ("ExchangeData", DataExchangeObject, "acceptExchangeData"), WidgetDecorator.syned_input_data()[0]] d_spacing = Setting(0.0) asymmetry_angle = Setting(0.0) thickness = Setting(0.0) psi_0r = Setting(0.0) psi_0i = Setting(0.0) psi_hr = Setting(0.0) psi_hi = Setting(0.0) psi_hbr = Setting(0.0) psi_hbi = Setting(0.0) diffraction_geometry = Setting(0) notes = Setting("") usage_path = os.path.join(resources.package_dirname("orangecontrib.srw.widgets.gui"), "misc", "crystal_usage.png") def __init__(self): super().__init__(azimuth_hor_vert=True) def draw_specific_box(self): self.crystal_box = oasysgui.widgetBox(self.tab_bas, "Crystal Setting", addSpace=False, orientation="vertical") oasysgui.lineEdit(self.crystal_box, self, "d_spacing", "d-spacing [Å]", labelWidth=260, valueType=float, orientation="horizontal") oasysgui.lineEdit(self.crystal_box, self, "asymmetry_angle", "Asymmetry Angle [rad]", labelWidth=260, valueType=float, orientation="horizontal") oasysgui.lineEdit(self.crystal_box, self, "thickness", "Crystal Thickness [m]", labelWidth=260, valueType=float, orientation="horizontal") polarization_box = oasysgui.widgetBox(self.crystal_box, "Crystal Polarizability", addSpace=False, orientation="horizontal") polarization_box_l = oasysgui.widgetBox(polarization_box, "", addSpace=False, orientation="vertical", width=200) polarization_box_r = oasysgui.widgetBox(polarization_box, "", addSpace=False, orientation="vartical") gui.label(polarization_box_l, self, " Real Part") oasysgui.lineEdit(polarization_box_l, self, "psi_0r" , "X0", labelWidth=50, valueType=float, orientation="horizontal") oasysgui.lineEdit(polarization_box_l, self, "psi_hr" , "Xh \u03c3", labelWidth=50, valueType=float, orientation="horizontal") oasysgui.lineEdit(polarization_box_l, self, "psi_hbr", "Xh \u03c0", labelWidth=50, valueType=float, orientation="horizontal") gui.label(polarization_box_r, self, "Imaginary Part") oasysgui.lineEdit(polarization_box_r, self, "psi_0i", "", labelWidth=50, valueType=float, orientation="horizontal") oasysgui.lineEdit(polarization_box_r, self, "psi_hi", "", labelWidth=50, valueType=float, orientation="horizontal") oasysgui.lineEdit(polarization_box_r, self, "psi_hbi", "", labelWidth=50, valueType=float, orientation="horizontal") self.notes_area = oasysgui.textArea(height=40, width=370) self.notes_area.setText(self.notes) self.crystal_box.layout().addWidget(self.notes_area) tab_usa = oasysgui.createTabPage(self.tabs_setting, "Use of the Widget") tab_usa.setStyleSheet("background-color: white;") usage_box = oasysgui.widgetBox(tab_usa, "", addSpace=True, orientation="horizontal") label = QLabel("") label.setAlignment(Qt.AlignCenter) label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) label.setPixmap(QPixmap(self.usage_path)) usage_box.layout().addWidget(label) def get_optical_element(self): return SRWCrystal(orientation_of_reflection_plane = self.orientation_azimuthal, invert_tangent_component = self.invert_tangent_component == 1, d_spacing = self.d_spacing, asymmetry_angle = self.asymmetry_angle, thickness = self.thickness, psi_0r = self.psi_0r, psi_0i = self.psi_0i, psi_hr = self.psi_hr, psi_hi = self.psi_hi, psi_hbr = self.psi_hbr, psi_hbi = self.psi_hbi, incident_angle = numpy.radians(90-self.angle_radial)) def receive_specific_syned_data(self, optical_element): if not optical_element is None: if isinstance(optical_element, Crystal): self.asymmetry_angle = optical_element._asymmetry_angle, self.thickness = optical_element._thickness, self.diffraction_geometry = optical_element._diffraction_geometry else: raise Exception("Syned Data not correct: Optical Element is not a Crystal") else: raise Exception("Syned Data not correct: Empty Optical Element") def check_data(self): super().check_data() congruence.checkStrictlyPositiveNumber(self.d_spacing, "d-spacing") def acceptExchangeData(self, exchangeData): if not exchangeData is None: try: if exchangeData.get_program_name() == "XRAYSERVER": if exchangeData.get_widget_name() == "X0H": self.notes = "Data from X-Ray Server: " + exchangeData.get_content("structure") + "(" + \ str(exchangeData.get_content("h")) + "," + str(exchangeData.get_content("k")) + "," + str(exchangeData.get_content("l")) + ")" + \ " at " + str(round(exchangeData.get_content("energy")*1000, 4)) + " eV" self.notes_area.setText(self.notes) self.angle_radial = 90 - exchangeData.get_content("bragg_angle") self.d_spacing = exchangeData.get_content("d_spacing") self.psi_0r = exchangeData.get_content("xr0") self.psi_0i = exchangeData.get_content("xi0") self.psi_hr = exchangeData.get_content("xrh_s") self.psi_hi = exchangeData.get_content("xih_s") self.psi_hbr = exchangeData.get_content("xrh_p") self.psi_hbi = exchangeData.get_content("xih_p") except Exception as e: QMessageBox.critical(self, "Error", str(e.args[0]), QMessageBox.Ok)
class OWdabam_height_profile(OWAbstractDabamHeightProfile): name = "DABAM Height Profile" id = "dabam_height_profile" description = "Calculation of mirror surface error profile" icon = "icons/dabam.png" author = "Luca Rebuffi" maintainer_email = "[email protected]; [email protected]" priority = 6 category = "" keywords = ["dabam_height_profile"] outputs = [ OWAbstractDabamHeightProfile.get_dabam_output(), { "name": "PreProcessor_Data", "type": ShadowPreProcessorData, "doc": "PreProcessor Data", "id": "PreProcessor_Data" } ] usage_path = os.path.join( resources.package_dirname("orangecontrib.shadow.widgets.gui"), "misc", "dabam_height_profile_usage.png") def __init__(self): super().__init__() def after_change_workspace_units(self): self.si_to_user_units = 1 / self.workspace_units_to_m self.horHeaders = [ "Entry", "Shape", "Length\n[" + self.get_axis_um() + "]", "Heights St.Dev.\n[nm]", "Slopes St.Dev.\n[" + u"\u03BC" + "rad]" ] self.table.setHorizontalHeaderLabels(self.horHeaders) self.plot_canvas[0].setGraphXLabel("Y [" + self.get_axis_um() + "]") self.plot_canvas[1].setGraphXLabel("Y [" + self.get_axis_um() + "]") self.axis.set_xlabel("X [" + self.get_axis_um() + "]") self.axis.set_ylabel("Y [" + self.get_axis_um() + "]") label = self.le_dimension_y_from.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_dimension_y_to.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_dimension_x.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_step_x.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_new_length_1.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") label = self.le_new_length_2.parent().layout().itemAt(0).widget() label.setText(label.text() + " [" + self.workspace_units_label + "]") def get_usage_path(self): return self.usage_path def get_axis_um(self): return self.workspace_units_label def write_error_profile_file(self): ST.write_shadow_surface(self.zz, self.xx, self.yy, self.heigth_profile_file_name) def send_data(self, dimension_x, dimension_y): self.send( "PreProcessor_Data", ShadowPreProcessorData( error_profile_data_file=self.heigth_profile_file_name, error_profile_x_dim=dimension_x, error_profile_y_dim=dimension_y))
def home_bin(cls): return pathlib.Path( resources.package_dirname("orangecontrib.xoppy.util"), "bin", "windows")