def runShadowSource(self): self.setStatusMessage("") self.progressBarInit() try: self.checkFields() ########################################### # TODO: TO BE ADDED JUST IN CASE OF BROKEN # ENVIRONMENT: MUST BE FOUND A PROPER WAY # TO TEST SHADOW self.fixWeirdShadowBug() ########################################### shadow_src = ShadowSource.create_bm_src() self.populateFields(shadow_src) self.progressBarSet(10) self.setStatusMessage("Running SHADOW") sys.stdout = EmittingStream(textWritten=self.writeStdOut) if self.trace_shadow: grabber = TTYGrabber() grabber.start() self.progressBarSet(50) write_begin_file, write_start_file, write_end_file = self.get_write_file_options( ) beam_out = ShadowBeam.traceFromSource( shadow_src, write_begin_file=write_begin_file, write_start_file=write_start_file, write_end_file=write_end_file, widget_class_name=self.__class__.name) if self.trace_shadow: grabber.stop() for row in grabber.ttyData: self.writeStdOut(row) self.setStatusMessage("Plotting Results") self.progressBarSet(80) self.plot_results(beam_out) self.setStatusMessage("") self.send("Beam", beam_out) except Exception as exception: QtWidgets.QMessageBox.critical(self, "Error", str(exception), QtWidgets.QMessageBox.Ok) if self.IS_DEVELOP: raise exception self.progressBarFinished()
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_heigth_profile(self, not_interactive_mode=False): try: sys.stdout = EmittingStream(textWritten=self.writeStdOut) self.check_fields() if self.error_type_y == profiles_simulation.FIGURE_ERROR: rms_y = self.rms_y * 1e-9 # from nm to m else: rms_y = self.rms_y * 1e-6 # from urad to rad xx, yy = profiles_simulation.simulate_profile_1D( step=self.step_y * self.workspace_units_to_m, mirror_length=self.dimension_y * self.workspace_units_to_m, random_seed=self.montecarlo_seed_y, error_type=self.error_type_y, profile_type=1 - self.kind_of_profile_y, rms=rms_y, correlation_length=self.correlation_length_y * self.workspace_units_to_m, power_law_exponent_beta=self.power_law_exponent_beta_y) xx_to_plot = xx / self.workspace_units_to_m # to user units yy_to_plot = yy * 1e9 # nm self.yy = yy / self.workspace_units_to_m # to user units ny = yy.size slope = numpy.zeros(ny) for i in range(ny - 1): step = xx[i + 1] - xx[i] slope[i] = numpy.arctan((yy[i + 1] - yy[i]) / step) slope[ny - 1] = slope[ny - 2] sloperms = slope.std() title = ' Slope error rms in Z direction: %f $\mu$rad' % ( sloperms * 1e6) if self.plot_canvas is None: self.plot_canvas = oasysgui.plotWindow(roi=False, control=False, position=False) self.plot_canvas.setDefaultPlotLines(True) self.plot_canvas.setActiveCurveColor(color='blue') self.plot_tab.layout().addWidget(self.plot_canvas) WiserPlot.plot_histo(self.plot_canvas, xx_to_plot, yy_to_plot, title, "X [" + self.workspace_units_label + "]", "Z [nm]") QMessageBox.information( self, "QMessageBox.information()", "Height Profile calculated: if the result is satisfactory,\nclick \'Generate Height Profile File\' to complete the operation ", QMessageBox.Ok) except Exception as exception: QMessageBox.critical(self, "Error", exception.args[0], QMessageBox.Ok) raise exception
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 plot_results(self): try: plotted = False sys.stdout = EmittingStream(textWritten=self.writeStdOut) if not self.input_srw_data is None: x, title, x_title, y_title, xum = self.get_titles() self.plot_histo(x, title=title, xtitle=x_title, ytitle=y_title, xum=xum) plotted = True time.sleep( 0.5 ) # prevents a misterious dead lock in the Orange cycle when refreshing the histogram return plotted except Exception as exception: QMessageBox.critical(self, "Error", str(exception), QMessageBox.Ok) if self.IS_DEVELOP: raise exception return False
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 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
def traceOpticalElement(self): try: self.error(self.error_id) self.setStatusMessage("") self.progressBarInit() if ShadowCongruence.checkEmptyBeam(self.input_beam): if ShadowCongruence.checkGoodBeam(self.input_beam): sys.stdout = EmittingStream(textWritten=self.writeStdOut) self.checkFields() shadow_oe = ShadowOpticalElement.create_screen_slit() self.populateFields(shadow_oe) self.doSpecificSetting(shadow_oe) self.progressBarSet(10) self.completeOperations(shadow_oe) else: raise Exception("Input Beam with no good rays") else: raise Exception("Empty Input Beam") except Exception as exception: QtWidgets.QMessageBox.critical(self, "QMessageBox.critical()", str(exception), QtWidgets.QMessageBox.Ok) self.error_id = self.error_id + 1 self.error(self.error_id, "Exception occurred: " + str(exception)) self.progressBarFinished()
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 compute(self): self.setStatusMessage("Running WISEr") self.progressBarInit() try: sys.stdout = EmittingStream(textWritten=self.writeStdOut) self.progressBarSet(20) self.check_fields() calculation_output = self.do_wise_calculation() self.progressBarSet(50) self.setStatusMessage("Plotting Results") try: self.plot_data = self.extract_plot_data_from_calculation_output( calculation_output) self.plot_results(self.plot_data, progressBarValue=60) self.setStatusMessage("") wise_data = self.extract_wise_data_from_calculation_output( calculation_output) if not wise_data is None: self.send("WiserData", wise_data) except Exception as exception: QtWidgets.QMessageBox.critical(self, "No input data", str(exception), QtWidgets.QMessageBox.Ok) self.setStatusMessage("Calculation impossible") # raise exception except Exception as exception: QtWidgets.QMessageBox.critical(self, "Compute impossible", str(exception), QtWidgets.QMessageBox.Ok) self.setStatusMessage("Error") # raise exception self.progressBarFinished()
def plot_results(self): try: sys.stdout = EmittingStream(textWritten=self.writeStdOut) if ShadowCongruence.checkEmptyBeam(self.input_beam): self.number_of_bins = congruence.checkStrictlyPositiveNumber(self.number_of_bins, "Number of Bins") self.plot_xy(self.x_column_index+1, self.y_column_index+1) time.sleep(0.1) # prevents a misterious dead lock in the Orange cycle when refreshing the histogram except Exception as exception: QMessageBox.critical(self, "Error", str(exception), QMessageBox.Ok) if self.IS_DEVELOP: raise exception
def plot_results(self): try: plotted = False sys.stdout = EmittingStream(textWritten=self.writeStdOut) if self.trace_shadow: grabber = TTYGrabber() grabber.start() if ShadowCongruence.checkEmptyBeam(self.input_beam): ShadowPlot.set_conversion_active(self.getConversionActive()) # self.number_of_bins = congruence.checkStrictlyPositiveNumber(self.number_of_bins, "Number of Bins") x, y, c, auto_x_title, auto_y_title, xum, yum = self.get_titles( ) self.plot_scatter(x, y, c, title=self.title, xtitle=auto_x_title, ytitle=auto_y_title, xum=xum, yum=yum) plotted = True if self.trace_shadow: grabber.stop() for row in grabber.ttyData: self.writeStdOut(row) time.sleep( 0.5 ) # prevents a misterious dead lock in the Orange cycle when refreshing the histogram return plotted except Exception as exception: QtWidgets.QMessageBox.critical(self, "Error", str(exception), QtWidgets.QMessageBox.Ok) if self.IS_DEVELOP: raise exception return False
def runSRWSource(self): self.setStatusMessage("") self.progressBarInit() try: self.checkFields() srw_source = self.get_srw_source(self.get_electron_beam()) srw_source.name = self.source_name if not self.source_name is None else self.windowTitle(), self.progressBarSet(10) self.setStatusMessage("Running SRW") sys.stdout = EmittingStream(textWritten=self.writeStdOut) self.print_specific_infos(srw_source) self.progressBarSet(20) self.setStatusMessage("") beamline = SRWBeamline(light_source=srw_source) self.output_wavefront = self.calculate_wavefront_propagation(srw_source) if self.is_do_plots(): self.setStatusMessage("Plotting Results") tickets = [] self.run_calculation_for_plots(tickets, 50) self.plot_results(tickets, 80) self.setStatusMessage("") self.send("SRWData", SRWData(srw_beamline=beamline, srw_wavefront=self.output_wavefront)) except Exception as exception: QMessageBox.critical(self, "Error", str(exception), QMessageBox.Ok) if self.IS_DEVELOP: raise exception self.progressBarFinished()
def compute(self): self.setStatusMessage("Running XOPPY") self.progressBarInit() try: self.xoppy_output.setText("") sys.stdout = EmittingStream(textWritten=self.writeStdOut) self.progressBarSet(20) self.check_fields() calculation_output = self.do_xoppy_calculation() self.progressBarSet(50) if calculation_output is None: raise Exception("Xoppy gave no result") else: self.calculated_data = self.extract_data_from_xoppy_output( calculation_output) self.add_specific_content_to_calculated_data( self.calculated_data) self.setStatusMessage("Plotting Results") self.plot_results(self.calculated_data, progressBarValue=60) self.setStatusMessage("") self.send("xoppy_data", self.calculated_data) except Exception as exception: QtWidgets.QMessageBox.critical(self, "Error", str(exception), QtWidgets.QMessageBox.Ok) self.setStatusMessage("Error!") #raise exception self.progressBarFinished()
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 calculateRadiation(self): if not self.received_light_source is None: self.setStatusMessage("") self.progressBarInit() try: self.checkFields() srw_source = self.get_srw_source(self.get_electron_beam()) self.progressBarSet(10) self.setStatusMessage("Running SRW") sys.stdout = EmittingStream(textWritten=self.writeStdOut) print(srw_source.get_electron_beam(). get_electron_beam_geometrical_properties().to_info()) self.print_specific_infos(srw_source) self.progressBarSet(20) tickets = [] self.run_calculation_flux(srw_source, tickets) self.setStatusMessage("Plotting Results") self.plot_results(tickets) self.setStatusMessage("") self.send("srw_data", self.create_exchange_data(tickets)) except Exception as exception: QMessageBox.critical(self, "Error", str(exception), QMessageBox.Ok) if self.IS_DEVELOP: raise exception self.progressBarFinished()
def compute(self): self.setStatusMessage("Running XOPPY") self.progressBarInit() try: sys.stdout = EmittingStream(textWritten=self.writeStdOut) self.progressBarSet(20) self.check_fields() calculation_output = self.do_wise_calculation() self.progressBarSet(50) if calculation_output is None: raise Exception("Wise gave no result") else: self.setStatusMessage("Plotting Results") self.plot_data = self.extract_plot_data_from_calculation_output( calculation_output) self.plot_results(self.plot_data, progressBarValue=60) self.setStatusMessage("") wise_output = self.extract_wise_output_from_calculation_output( calculation_output) if not wise_output is None: self.send("wise_output", wise_output) except Exception as exception: QtWidgets.QMessageBox.critical(self, "Error", str(exception), QtWidgets.QMessageBox.Ok) self.setStatusMessage("Error!") #raise exception self.progressBarFinished()
def interp_save(self, not_interactive_mode=False): try: congruence.checkDir(self.save_height_profile_file_name) sys.stdout = EmittingStream(textWritten=self.writeStdOut) congruence.checkFileName(self.save_height_profile_file_name) self.write_error_profile_file() if not not_interactive_mode: QMessageBox.information( self, "QMessageBox.information()", "Height Profile file " + self.save_height_profile_file_name + " written on disk", QMessageBox.Ok) except Exception as exception: QMessageBox.critical(self, "Error", exception.args[0], QMessageBox.Ok) if self.IS_DEVELOP: raise exception
def traceOpticalElement(self): try: #self.error(self.error_id) self.setStatusMessage("") self.progressBarInit() if ShadowCongruence.checkEmptyBeam(self.input_beam): if ShadowCongruence.checkGoodBeam(self.input_beam): sys.stdout = EmittingStream(textWritten=self.writeStdOut) self.checkFields() shadow_oe = ShadowCompoundOpticalElement.create_compound_oe( workspace_units_to_cm=self.workspace_units_to_cm) self.populateFields(shadow_oe) self.doSpecificSetting(shadow_oe) self.progressBarSet(10) self.completeOperations(shadow_oe) else: if self.not_interactive: self.sendEmptyBeam() else: raise Exception("Input Beam with no good rays") else: if self.not_interactive: self.sendEmptyBeam() else: raise Exception("Empty Input Beam") except Exception as exception: QtWidgets.QMessageBox.critical(self, "Error", str(exception), QtWidgets.QMessageBox.Ok) #self.error_id = self.error_id + 1 #self.error(self.error_id, "Exception occurred: " + str(exception)) if self.IS_DEVELOP: raise exception self.progressBarFinished()
def generate_heigth_profile_file(self, not_interactive_mode=False): if not self.yy is None and not self.xx is None: try: congruence.checkDir(self.heigth_profile_file_name) sys.stdout = EmittingStream(textWritten=self.writeStdOut) numpy.savetxt(self.heigth_profile_file_name, self.yy) QMessageBox.information( self, "QMessageBox.information()", "Height Profile file " + self.heigth_profile_file_name + " written on disk", QMessageBox.Ok) self.send( "PreInput", WiserPreInputData( figure_error_file=self.heigth_profile_file_name, figure_error_step=numpy.abs(self.xx[1] - self.xx[0]), figure_user_units_to_m=self.workspace_units_to_m)) except Exception as exception: QMessageBox.critical(self, "Error", exception.args[0], QMessageBox.Ok)
def refresh_script(self): self.wofry_output.setText("") sys.stdout = EmittingStream(textWritten=self.writeStdOut) if self.input_data is None: raise Exception("No input data") beamline = self.input_data.get_beamline() self.pythonScript.setText( to_python_code( beamline, do_plot=False, mode_index_max=self.mode_index_max, show_graph_flag=self.show_graph_flag, graph_file_flag=self.graph_file_flag, data_file_flag=self.data_file_flag, root_file_name=self.root_file_name, )) if self.script_file_flag: self.save_script()
def calculate_heigth_profile(self, not_interactive_mode=False): import matplotlib print(matplotlib.__version__) try: if self.server.y is None: raise Exception("No Profile Selected") sys.stdout = EmittingStream(textWritten=self.writeStdOut) self.check_fields() # PREVENTS CRASH WITH PYQT5 if not not_interactive_mode: self.tabs.setCurrentIndex(6) if self.modify_y == 2: profile_1D_y_x_temp = self.si_to_user_units * self.server.y if self.use_undetrended == 0: profile_1D_y_y_temp = self.si_to_user_units * self.server.zHeights else: profile_1D_y_y_temp = self.si_to_user_units * self.server.zHeightsUndetrended first_coord = profile_1D_y_x_temp[0] second_coord = profile_1D_y_x_temp[1] last_coord = profile_1D_y_x_temp[-1] step = numpy.abs(second_coord - first_coord) length = numpy.abs(last_coord - first_coord) n_points_old = len(profile_1D_y_x_temp) if self.new_length > length: difference = self.new_length - length n_added_points = int(difference / step) if difference % step == 0: n_added_points += 1 if n_added_points % 2 != 0: n_added_points += 1 profile_1D_y_x = numpy.arange(n_added_points + n_points_old) * step profile_1D_y_y = numpy.ones( n_added_points + n_points_old ) * self.filler_value * 1e-9 * self.si_to_user_units profile_1D_y_y[int(n_added_points / 2):n_points_old + int(n_added_points / 2)] = profile_1D_y_y_temp elif self.new_length < length: difference = length - self.new_length n_removed_points = int(difference / step) if difference % step == 0: n_removed_points -= 1 if n_removed_points % 2 != 0: n_removed_points -= 1 if n_removed_points >= 2: profile_1D_y_x = profile_1D_y_x_temp[0:( n_points_old - n_removed_points)] profile_1D_y_y = profile_1D_y_y_temp[( int(n_removed_points / 2) - 1):(n_points_old - int(n_removed_points / 2) - 1)] else: profile_1D_y_x = profile_1D_y_x_temp profile_1D_y_y = profile_1D_y_y_temp else: profile_1D_y_x = profile_1D_y_x_temp profile_1D_y_y = profile_1D_y_y_temp else: if self.modify_y == 0: profile_1D_y_x = self.si_to_user_units * self.server.y elif self.modify_y == 1: scale_factor_y = self.new_length / ( self.si_to_user_units * (max(self.server.y) - min(self.server.y))) profile_1D_y_x = self.si_to_user_units * self.server.y * scale_factor_y if self.use_undetrended == 0: profile_1D_y_y = self.si_to_user_units * self.server.zHeights else: profile_1D_y_y = self.si_to_user_units * self.server.zHeightsUndetrended if self.center_y: first_coord = profile_1D_y_x[0] last_coord = profile_1D_y_x[-1] length = numpy.abs(last_coord - first_coord) profile_1D_y_x_temp = numpy.linspace(-length / 2, length / 2, len(profile_1D_y_x)) profile_1D_y_x = profile_1D_y_x_temp if self.renormalize_y == 0: rms_y = None else: if self.error_type_y == profiles_simulation.FIGURE_ERROR: rms_y = self.si_to_user_units * self.rms_y * 1e-9 # from nm to user units profile_1D_y_y = profile_1D_y_y / profile_1D_y_y.std( ) * rms_y else: rms_y = self.rms_y * 1e-6 # from urad to rad yslopes = numpy.gradient( profile_1D_y_y, profile_1D_y_x[1] - profile_1D_y_x[0]) profile_1D_y_y = profile_1D_y_y / yslopes.std() * rms_y self.xx = profile_1D_y_x self.yy = profile_1D_y_y x_to_plot = self.xx y_to_plot = self.yy * 1e9 / self.si_to_user_units ny = len(self.yy) slope = numpy.zeros(ny) for i in range(ny - 1): step = self.xx[i + 1] - self.xx[i] slope[i] = numpy.arctan((self.yy[i + 1] - self.yy[i]) / step) slope[ny - 1] = slope[ny - 2] title = ' Slope error rms : %f $\mu$rad' % (slope.std() * 1e6) + '\n' + \ ' Figure error rms : %f nm' % (round(self.yy.std()* 1e9 / self.si_to_user_units, 6)) self.plot_dabam_graph(5, "heights_profile_generated", x_to_plot, y_to_plot, "Y [" + self.workspace_units_label + "]", "Z [nm]", title=title) if not not_interactive_mode: QMessageBox.information( self, "QMessageBox.information()", "Height Profile calculated: if the result is satisfactory,\nclick \'Generate Height Profile File\' to complete the operation ", QMessageBox.Ok) except Exception as exception: QMessageBox.critical(self, "Error", exception.args[0], QMessageBox.Ok)
def traceOpticalElement(self): try: self.error(self.error_id) self.setStatusMessage("") self.progressBarInit() if ShadowCongruence.checkEmptyBeam(self.input_beam): if ShadowCongruence.checkGoodBeam(self.input_beam): sys.stdout = EmittingStream(textWritten=self.writeStdOut) self.progressBarSet(10) self.checkFields() self.setStatusMessage("Running SHADOW") if self.trace_shadow: grabber = TTYGrabber() grabber.start() self.progressBarSet(50) ########################################### # TODO: TO BE ADDED JUST IN CASE OF BROKEN # ENVIRONMENT: MUST BE FOUND A PROPER WAY # TO TEST SHADOW self.fixWeirdShadowBug() ########################################### shadow_oe_1 = ShadowOpticalElement.create_screen_slit() self.populateFields_1(shadow_oe_1) beam_out = ShadowBeam.traceFromOE(self.input_beam, shadow_oe_1) self.adjust_first_divergence(beam_out) self.progressBarSet(60) shadow_oe_2 = ShadowOpticalElement.create_screen_slit() self.populateFields_2(shadow_oe_2) beam_out = ShadowBeam.traceFromOE(beam_out, shadow_oe_2) self.adjust_second_divergence_and_intensity(beam_out) self.progressBarSet(70) shadow_oe_3 = ShadowOpticalElement.create_screen_slit() self.populateFields_3(shadow_oe_3) beam_out = ShadowBeam.traceFromOE(beam_out, shadow_oe_3) if self.trace_shadow: grabber.stop() for row in grabber.ttyData: self.writeStdOut(row) self.setStatusMessage("Plotting Results") self.plot_results(beam_out) self.setStatusMessage("") self.send("Beam", beam_out) self.send("Trigger", TriggerIn(new_object=True)) else: raise Exception("Input Beam with no good rays") else: raise Exception("Empty Input Beam") except Exception as exception: QtWidgets.QMessageBox.critical(self, "QMessageBox.critical()", str(exception), QtWidgets.QMessageBox.Ok) self.error_id = self.error_id + 1 self.error(self.error_id, "Exception occurred: " + str(exception)) self.progressBarFinished()
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 run_hybrid(self): try: self.setStatusMessage("") self.progressBarInit() self.initializeTabs() if ShadowCongruence.checkEmptyBeam(self.input_beam): if ShadowCongruence.checkGoodBeam(self.input_beam): sys.stdout = EmittingStream(textWritten=self.write_stdout) self.check_fields() input_parameters = hybrid_control.HybridInputParameters() input_parameters.ghy_lengthunit = self.workspace_units input_parameters.widget = self input_parameters.ghy_diff_plane = self.ghy_diff_plane + 1 if self.distance_to_image_calc == 0: input_parameters.ghy_distance = -1 else: input_parameters.ghy_distance = self.ghy_distance if self.focal_length_calc == 0: input_parameters.ghy_focallength = -1 else: input_parameters.ghy_focallength = self.ghy_focallength input_parameters.ghy_nf = self.ghy_nf input_parameters.ghy_nbins_x = int(self.ghy_nbins_x) input_parameters.ghy_nbins_z = int(self.ghy_nbins_z) input_parameters.ghy_npeak = int(self.ghy_npeak) input_parameters.ghy_fftnpts = int(self.ghy_fftnpts) input_parameters.file_to_write_out = self.file_to_write_out input_parameters.ghy_automatic = self.ghy_automatic # ----------------------------------------------- #cycling or figure errors # add the reference (no error profile) shadow_beam = self.input_beam.duplicate() history_entry = shadow_beam.getOEHistory( shadow_beam._oe_number) shadow_oe = history_entry._shadow_oe_start # changes to the original object! shadow_oe._oe.F_RIPPLE = 0 input_parameters.ghy_calcType = 2 input_parameters.shadow_beam = shadow_beam calculation_parameters = hybrid_control.hy_run( input_parameters) self.ghy_focallength = input_parameters.ghy_focallength self.ghy_distance = input_parameters.ghy_distance self.ghy_nbins_x = int(input_parameters.ghy_nbins_x) self.ghy_nbins_z = int(input_parameters.ghy_nbins_z) self.ghy_npeak = int(input_parameters.ghy_npeak) self.ghy_fftnpts = int(input_parameters.ghy_fftnpts) if input_parameters.ghy_calcType == 3 or input_parameters.ghy_calcType == 4: do_plot_x = True do_plot_z = True else: if self.ghy_automatic == 1: do_plot_x = not calculation_parameters.beam_not_cut_in_x do_plot_z = not calculation_parameters.beam_not_cut_in_z else: do_plot_x = True do_plot_z = True do_nf = input_parameters.ghy_nf == 1 and input_parameters.ghy_calcType > 1 if do_plot_x or do_plot_z: self.setStatusMessage("Plotting Results") profile = 0 self.current_histo_data_x_ff = None self.current_histo_data_x_nf = None self.current_histo_data_z_ff = None self.current_histo_data_z_nf = None self.current_stats_x_ff = None self.current_stats_x_nf = None self.current_stats_z_ff = None self.current_stats_z_nf = None histo_data_x_ff, \ histo_data_z_ff, \ histo_data_x_nf, \ histo_data_z_nf = self.plot_results(calculation_parameters=calculation_parameters, do_nf=do_nf, do_plot_x=do_plot_x, do_plot_z=do_plot_z, histo_data_x_ff=HistogramData(), histo_data_z_ff=HistogramData(), histo_data_x_nf=HistogramData(), histo_data_z_nf=HistogramData(), profile=profile) if not histo_data_x_ff.bins is None: self.current_histo_data_x_ff = HistogramDataCollection( histo_data_x_ff) if not histo_data_z_ff.bins is None: self.current_histo_data_z_ff = HistogramDataCollection( histo_data_z_ff) if not histo_data_x_nf.bins is None: self.current_histo_data_x_nf = HistogramDataCollection( histo_data_x_nf) if not histo_data_z_nf.bins is None: self.current_histo_data_z_nf = HistogramDataCollection( histo_data_z_nf) stats_x_ff = StatisticalDataCollection(histo_data_x_ff) stats_z_ff = StatisticalDataCollection(histo_data_z_ff) stats_x_nf = StatisticalDataCollection(histo_data_x_nf) stats_z_nf = StatisticalDataCollection(histo_data_z_nf) input_parameters.ghy_calcType = self.ghy_calcType + 3 for file in self.ghy_files: shadow_beam = self.input_beam.duplicate() history_entry = shadow_beam.getOEHistory( shadow_beam._oe_number) shadow_oe = history_entry._shadow_oe_start # changes to the original object! shadow_oe._oe.F_RIPPLE = 1 shadow_oe._oe.F_G_S = 2 file = congruence.checkFile(file) ShadowCongruence.checkErrorProfileFile(file) shadow_oe._oe.FILE_RIP = bytes(file, 'utf-8') input_parameters.shadow_beam = shadow_beam calculation_parameters = hybrid_control.hy_run( input_parameters) if do_plot_x or do_plot_z: self.setStatusMessage("Plotting Results") profile += 1 histo_data_x_ff, \ histo_data_z_ff, \ histo_data_x_nf, \ histo_data_z_nf = self.plot_results(calculation_parameters, do_nf, do_plot_x, do_plot_z, histo_data_x_ff, histo_data_z_ff, histo_data_x_nf, histo_data_z_nf, profile) if not histo_data_x_ff.bins is None: self.current_histo_data_x_ff.add_histogram_data( histo_data_x_ff) if not histo_data_z_ff.bins is None: self.current_histo_data_z_ff.add_histogram_data( histo_data_z_ff) if not histo_data_x_nf.bins is None: self.current_histo_data_x_nf.add_histogram_data( histo_data_x_nf) if not histo_data_z_nf.bins is None: self.current_histo_data_z_nf.add_histogram_data( histo_data_z_nf) stats_x_ff.add_statistical_data(histo_data_x_ff) stats_z_ff.add_statistical_data(histo_data_z_ff) stats_x_nf.add_statistical_data(histo_data_x_nf) stats_z_nf.add_statistical_data(histo_data_z_nf) self.current_stats_x_ff = stats_x_ff self.current_stats_z_ff = stats_z_ff self.current_stats_x_nf = stats_x_nf self.current_stats_z_nf = stats_z_nf self.add_empty_curves(do_nf, do_plot_x, do_plot_z, histo_data_x_ff, histo_data_x_nf, histo_data_z_ff, histo_data_z_nf) self.plot_stats( do_nf, do_plot_x, do_plot_z, stats_x_ff, stats_z_ff, stats_x_nf, stats_z_nf, ) else: raise Exception("Input Beam with no good rays") else: raise Exception("Empty Input Beam") except Exception as exception: QMessageBox.critical(self, "Error", str(exception), QMessageBox.Ok) if self.IS_DEVELOP: raise exception self.setStatusMessage("") self.progressBarFinished()
def generate_FEtoShadow(self, not_interactive_mode=False): try: sys.stdout = EmittingStream(textWritten=self.writeStdOut) node, number, y, x, z_coord, el_no, z = loadtxt( self.simFE_fname, skiprows=1, unpack=True) # Import from ANSYS, first Y, then X, Z # readfile = read_csv(self.simFE_fname, sep='\t', decimal=',').values # node = readfile[:,0] # number = readfile[:,1] # y = readfile[:,2] * 1e-3 # Convert to metres # x = readfile[:,3] * 1e-3 # z = readfile[:,4] * 1e-3 if self.method == 0: # Spacing noPts = (abs(min(x)) + abs(max(x))) / self.spacing_value step = self.spacing_value if noPts > 5000: QMessageBox.critical( self, "Error", "Select larger spacing. Current number of points: {}\nNumber of points cannot be larger than 5000!" .format(int(noPts)), QMessageBox.Ok) else: grid = mgrid[min(x):max(x) + step:step, min(y):max(y) + step:step] elif self.method == 1: # Number of points if self.noPts_x > 5000: QMessageBox.critical( self, "Error", "Select fewer points in x.\nNumber of points cannot be larger than 5000!", QMessageBox.Ok) else: grid = mgrid[min(x):max(x):(1j * self.noPts_x), min(y):max(y):(1j * self.noPts_y)] else: QMessageBox.critical(self, "Error", "Error in: method. Can be only 0 or 1", QMessageBox.Ok) grid_z = griddata((x, y), z, (grid[0], grid[1]), method='cubic') # self.interp_save() self.axis.cla() if self.unit == 0: # metres [m] uname = 'm' unit = 1. elif self.unit == 1: # centimetres [cm] uname = 'cm' unit = 1e2 im = self.axis.contourf(grid[0] * unit, grid[1] * unit, grid_z * 1e9, levels=32, cmap='jet') self.axis.set_xlabel("X [{}]".format(uname)) self.axis.set_ylabel("Y [{}]".format(uname)) self.axis.set_xlim(min(x) * unit, max(x) * unit) self.axis.set_ylim(min(y) * unit, max(y) * unit) self.axis.set_title('Interpolated surface') cb = self.figure.colorbar(im, cax=self.cax) cb.ax.set_ylabel('Z [nm]') self.interp_grid_x = grid[0] self.interp_grid_y = grid[1] self.interp_grid_z = grid_z self.figure_canvas.draw() # if not not_interactive_mode: # self.figure_canvas.draw() # # QMessageBox.information(self, "QMessageBox.information()", # "Height Profile calculated: if the result is satisfactory,\nclick \'Generate Height Profile File\' to complete the operation ", # QMessageBox.Ok) except Exception as exception: QMessageBox.critical(self, "Error", exception.args[0], QMessageBox.Ok) if self.IS_DEVELOP: raise exception
def runShadowSource(self): self.setStatusMessage("") self.progressBarInit() # this is to be able to start the widget out of Oasys try: tmp = self.workspace_units except: self.workspace_units = 'm' self.workspace_units_label = 'm' self.workspace_units_to_m = 1.0 self.workspace_units_to_cm = 1e2 self.workspace_units_to_mm = 1e3 self.checkFields() self.progressBarSet(10) self.setStatusMessage("Running SHADOW") sys.stdout = EmittingStream(textWritten=self.writeStdOut) if self.trace_shadow: grabber = TTYGrabber() grabber.start() self.progressBarSet(50) try: self.shadow_output.setText("") su = Undulator.initialize_as_vertical_undulator( K=self.K, period_length=self.period_length, periods_number=int(self.periods_number)) ebeam = ElectronBeam(energy_in_GeV=self.energy_in_GeV, energy_spread=0.0, current=self.current, number_of_bunches=1, moment_xx=(self.sigma_x)**2, moment_xxp=0.0, moment_xpxp=(self.sigma_divergence_x)**2, moment_yy=(self.sigma_z)**2, moment_yyp=0.0, moment_ypyp=(self.sigma_divergence_z)**2) print(ebeam.info()) codes = ["internal", "pySRU", "SRW"] selected_code = codes[self.code_undul_phot] self.sourceundulator = SourceUndulator( name="shadowOui-Full-Undulator", syned_electron_beam=ebeam, syned_undulator=su, flag_emittance=self.use_emittances_combo, flag_size=self.flag_size, emin=1000, # to be set later emax=1001, # to be set later ng_e=2, # to be set later maxangle=self.maxangle_urad * 1e-6, ng_t=self.ng_t, ng_p=self.ng_p, ng_j=self.ng_j, code_undul_phot=selected_code) if self.set_at_resonance == 0: if self.delta_e == 0: self.sourceundulator.set_energy_box( self.photon_energy, self.photon_energy, 1) else: self.sourceundulator.set_energy_box( self.photon_energy - 0.5 * self.delta_e, self.photon_energy + 0.5 * self.delta_e, self.ng_e) else: self.sourceundulator.set_energy_monochromatic_at_resonance( self.harmonic) if self.delta_e > 0.0: e0, e1, ne = self.sourceundulator.get_energy_box() self.sourceundulator.set_energy_box( e0 - 0.5 * self.delta_e, e0 + 0.5 * self.delta_e, self.ng_e) rays = self.sourceundulator.calculate_rays( user_unit_to_m=self.workspace_units_to_m, F_COHER=self.coherent, SEED=self.seed, NRAYS=self.number_of_rays) if self.plot_aux_graph: self.set_PlotAuxGraphs() print(self.sourceundulator.info()) shadow3_beam = Shadow3Beam(N=rays.shape[0]) shadow3_beam.rays = rays if self.file_to_write_out >= 1: shadow3_beam.write("begin.dat") print("File written to disk: begin.dat") if self.file_to_write_out >= 2: SourceUndulatorInputOutput.write_file_undul_phot_h5( self.sourceundulator.get_result_dictionary(), file_out="radiation.h5", mode="w", entry_name="radiation") beam_out = ShadowBeam(beam=shadow3_beam) beam_out.getOEHistory().append(ShadowOEHistoryItem()) if self.add_power: additional_parameters = {} pd, vx, vy = self.sourceundulator.get_power_density_interpolated_cartesian( ) total_power = self.power_step if self.power_step > 0 else pd.sum( ) * (vx[1] - vx[0]) * (vy[1] - vy[0]) additional_parameters["total_power"] = total_power additional_parameters["photon_energy_step"] = self.delta_e beam_out.setScanningData( ShadowBeam.ScanningData("photon_energy", self.photon_energy, "Energy for Power Calculation", "eV", additional_parameters)) if self.delta_e == 0.0: beam_out.set_initial_flux(self.sourceundulator.get_flux()[0]) self.progressBarSet(80) self.plot_results(beam_out) # # create python script for creating the shadow3 beam and display the script in the standard output # dict_parameters = { "K": self.K, "period_length": self.period_length, "periods_number": self.periods_number, "energy_in_GeV": self.energy_in_GeV, "energy_spread": 0.0, "current": self.current, "number_of_bunches": 1, "moment_xx": (self.sigma_x)**2, "moment_xxp": 0.0, "moment_xpxp": (self.sigma_divergence_x)**2, "moment_yy": (self.sigma_z)**2, "moment_yyp": 0.0, "moment_ypyp": (self.sigma_divergence_z)**2, "name": "shadowOui-Full-Undulator", "flag_emittance": self.use_emittances_combo, "flag_size": self.flag_size, "emin": 1000, # to be set later "emax": 1001, # to be set later "ng_e": 2, # to be set later "maxangle": self.maxangle_urad * 1e-6, "ng_t": self.ng_t, "ng_p": self.ng_p, "ng_j": self.ng_j, "code_undul_phot": selected_code, "user_unit_to_m": self.workspace_units_to_m, "F_COHER": self.coherent, "SEED": self.seed, "NRAYS": self.number_of_rays, "EMIN": self.sourceundulator._EMIN, "EMAX": self.sourceundulator._EMAX, "NG_E": self.sourceundulator._NG_E, "MAXANGLE": self.sourceundulator._MAXANGLE, } # write python script in standard output print(self.script_template().format_map(dict_parameters)) self.setStatusMessage("") self.send("Beam", beam_out) except Exception as exception: QtWidgets.QMessageBox.critical(self, "Error", str(exception), QtWidgets.QMessageBox.Ok) if self.IS_DEVELOP: raise exception self.progressBarFinished()
def run_hybrid(self): try: self.setStatusMessage("") self.progressBarInit() self.initializeTabs() if ShadowCongruence.checkEmptyBeam(self.input_beam): if ShadowCongruence.checkGoodBeam(self.input_beam): sys.stdout = EmittingStream(textWritten=self.write_stdout) self.check_fields() input_parameters = hybrid_control.HybridInputParameters() input_parameters.ghy_lengthunit = self.workspace_units input_parameters.widget = self input_parameters.shadow_beam = self.input_beam input_parameters.ghy_diff_plane = self.ghy_diff_plane + 1 input_parameters.ghy_calcType = self.ghy_calcType + 1 if self.distance_to_image_calc == 0: input_parameters.ghy_distance = -1 else: input_parameters.ghy_distance = self.ghy_distance if self.focal_length_calc == 0: input_parameters.ghy_focallength = -1 else: input_parameters.ghy_focallength = self.ghy_focallength if self.ghy_calcType != 0: input_parameters.ghy_nf = self.ghy_nf else: input_parameters.ghy_nf = 0 input_parameters.ghy_nbins_x = int(self.ghy_nbins_x) input_parameters.ghy_nbins_z = int(self.ghy_nbins_z) input_parameters.ghy_npeak = int(self.ghy_npeak) input_parameters.ghy_fftnpts = int(self.ghy_fftnpts) input_parameters.file_to_write_out = self.file_to_write_out input_parameters.ghy_automatic = self.ghy_automatic try: calculation_parameters = hybrid_control.hy_run(input_parameters) self.ghy_focallength = input_parameters.ghy_focallength self.ghy_distance = input_parameters.ghy_distance self.ghy_nbins_x = int(input_parameters.ghy_nbins_x) self.ghy_nbins_z = int(input_parameters.ghy_nbins_z) self.ghy_npeak = int(input_parameters.ghy_npeak) self.ghy_fftnpts = int(input_parameters.ghy_fftnpts) self.plotted_data = input_parameters, calculation_parameters if self.view_type==1: self.plot_results(calculation_parameters, input_parameters) if not calculation_parameters.ff_beam is None: calculation_parameters.ff_beam.setScanningData(self.input_beam.scanned_variable_data) self.send("Output Beam (Far Field)", calculation_parameters.ff_beam) do_nf = input_parameters.ghy_nf == 1 and input_parameters.ghy_calcType > 1 if do_nf and not calculation_parameters.nf_beam is None: calculation_parameters.nf_beam.setScanningData(self.input_beam.scanned_variable_data) self.send("Output Beam (Near Field)", calculation_parameters.nf_beam) self.send("Trigger", TriggerIn(new_object=True)) except Exception as e: if self.send_original_beam==1: self.send("Output Beam (Far Field)", self.input_beam.duplicate(history=True)) self.send("Trigger", TriggerIn(new_object=True)) else: raise e else: raise Exception("Input Beam with no good rays") else: raise Exception("Empty Input Beam") except Exception as exception: QMessageBox.critical(self, "Error", str(exception), QMessageBox.Ok) if self.IS_DEVELOP: raise exception self.setStatusMessage("") self.progressBarFinished()
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 runShadowSource(self): #self.error(self.error_id) self.setStatusMessage("") self.progressBarInit() sys.stdout = EmittingStream(textWritten=self.writeStdOut) if self.trace_shadow: grabber = TTYGrabber() grabber.start() try: self.checkFields() ########################################### # TODO: TO BE ADDED JUST IN CASE OF BROKEN # ENVIRONMENT: MUST BE FOUND A PROPER WAY # TO TEST SHADOW self.fixWeirdShadowBug() ########################################### wigFile = bytes(congruence.checkFileName("xshwig.sha"), 'utf-8') if self.type_combo == 0: inData = "" elif self.type_combo == 1: inData = congruence.checkUrl(self.file_with_b_vs_y) elif self.type_combo == 2: inData = congruence.checkUrl(self.file_with_harmonics) self.progressBarSet(10) #self.information(0, "Calculate electron trajectory") self.shadow_output.setText("") self.setStatusMessage("Calculate electron trajectory") (traj, pars) = srfunc.wiggler_trajectory(b_from=self.type_combo, inData=inData, nPer=self.number_of_periods, nTrajPoints=501, ener_gev=self.energy, per=self.id_period, kValue=self.k_value, trajFile=congruence.checkFileName("tmp.traj"), shift_x_flag=self.shift_x_flag, shift_x_value=self.shift_x_value, shift_betax_flag=self.shift_betax_flag, shift_betax_value=self.shift_betax_value) # # calculate cdf and write file for Shadow/Source # self.progressBarSet(20) #self.information(0, "Calculate cdf and write file for Shadow/Source") self.setStatusMessage("Calculate cdf and write file for Shadow/Source") srfunc.wiggler_cdf(traj, enerMin=self.e_min, enerMax=self.e_max, enerPoints=1001, outFile=wigFile, elliptical=False) #self.information(0, "CDF written to file %s \n"%(wigFile)) self.setStatusMessage("CDF written to file %s \n"%(str(wigFile))) self.progressBarSet(40) #self.information(0, "Set the wiggler parameters in the wiggler container") self.setStatusMessage("Set the wiggler parameters in the wiggler container") shadow_src = ShadowSource.create_wiggler_src() self.populateFields(shadow_src) shadow_src.src.FILE_TRAJ = wigFile self.progressBarSet(50) self.setStatusMessage("Running Shadow/Source") write_begin_file, write_start_file, write_end_file = self.get_write_file_options() beam_out = ShadowBeam.traceFromSource(shadow_src, write_begin_file=write_begin_file, write_start_file=write_start_file, write_end_file=write_end_file) if self.trace_shadow: grabber.stop() for row in grabber.ttyData: self.writeStdOut(row) #self.information(0, "Plotting Results") self.setStatusMessage("Plotting Results") self.progressBarSet(80) self.plot_results(beam_out, progressBarValue=80) self.setStatusMessage("Plotting Wiggler Data") self.plot_wiggler_results() #self.information() self.setStatusMessage("") self.send("Beam", beam_out) # # create python script for the preprocessors and display in the standard output # dict_parameters = { "b_from" : self.type_combo, "inData" : inData, "nPer" : self.number_of_periods, "nTrajPoints" : 501, "ener_gev" : self.energy, "per" : self.id_period, "kValue" : self.k_value, "trajFile" : "tmp.traj", "shift_x_flag" : self.shift_x_flag, "shift_x_value" : self.shift_x_value, "shift_betax_flag" : self.shift_betax_flag, "shift_betax_value" : self.shift_betax_value, "enerMin" : self.e_min, "enerMax" : self.e_max, "enerPoints" : 1001, "outFile" : wigFile, "elliptical" : False, "electron_current_mA" : self.electron_current, } # write python script in standard output print(self.script_template().format_map(dict_parameters)) except Exception as exception: QtWidgets.QMessageBox.critical(self, "Error", str(exception), QtWidgets.QMessageBox.Ok) #self.error_id = self.error_id + 1 #self.error(self.error_id, "Exception occurred: " + str(exception)) self.progressBarFinished()