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 completeOperations(self, shadow_oe=None): 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() ########################################### beam_out = ShadowBeam.traceFromOE(self.input_beam, shadow_oe) self.adjust_divergence_and_intensity(beam_out) 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))
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 completeOperations(self, shadow_oe=None): 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() ########################################### write_start_files, write_end_files, write_star_files, write_mirr_files = self.get_write_file_options( ) beam_out = ShadowBeam.traceFromCompoundOE( self.input_beam, shadow_oe, write_start_files=write_start_files, write_end_files=write_end_files, write_star_files=write_star_files, write_mirr_files=write_mirr_files, widget_class_name=type(self).__name__) 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))
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 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()
def traceOpticalElement(self): try: self.setStatusMessage("") self.progressBarInit() if ShadowCongruence.checkEmptyBeam(self.input_beam): if ShadowCongruence.checkGoodBeam(self.input_beam): self.checkFields() sys.stdout = EmittingStream(textWritten=self.writeStdOut) if self.trace_shadow: grabber = TTYGrabber() grabber.start() ########################################### # TODO: TO BE ADDED JUST IN CASE OF BROKEN # ENVIRONMENT: MUST BE FOUND A PROPER WAY # TO TEST SHADOW self.fixWeirdShadowBug() ########################################### self.progressBarSet(10) if self.source_distance_flag == 0: self.source_distance = self.source_plane_distance zone_plate_beam = self.get_zone_plate_beam() go = numpy.where(zone_plate_beam._beam.rays[:, 9] == GOOD) self.avg_wavelength = ShadowPhysics.getWavelengthFromShadowK(numpy.average(zone_plate_beam._beam.rays[go, 10]))*1e-1 #ANGSTROM->nm self.focal_distance = (self.delta_rn*(self.diameter*1000)/self.avg_wavelength)* (1e-9/self.workspace_units_to_m) # WS Units self.image_position = self.focal_distance*self.source_distance/(self.source_distance-self.focal_distance) # WS Units self.magnification = numpy.abs(self.image_position/self.source_distance) self.avg_wavelength = numpy.round(self.avg_wavelength, 6) # nm self.focal_distance = numpy.round(self.focal_distance, 6) self.image_position = numpy.round(self.image_position, 6) self.magnification = numpy.round(self.magnification, 6) if self.automatically_set_image_plane == 1: self.image_plane_distance = self.image_position self.progressBarSet(30) if self.type_of_zp == PHASE_ZP: efficiency, max_efficiency, thickness_max_efficiency = ZonePlate.calculate_efficiency(self.avg_wavelength, # Angstrom self.zone_plate_material, self.zone_plate_thickness) self.efficiency = numpy.round(100*efficiency, 3) self.max_efficiency = numpy.round(100*max_efficiency, 3) self.thickness_max_efficiency = thickness_max_efficiency else: self.efficiency = numpy.round(100/(numpy.pi**2), 3) self.max_efficiency = numpy.nan self.thickness_max_efficiency = numpy.nan focused_beam, \ self.number_of_zones = ZonePlate.apply_fresnel_zone_plate(zone_plate_beam, # WS Units self.type_of_zp, self.diameter, # micron self.delta_rn, # nm self.substrate_material, self.substrate_thickness, self.zone_plate_material, self.zone_plate_thickness, self.source_distance, # WS Units self.workspace_units_to_m) self.progressBarSet(60) beam_out = self.get_output_beam(focused_beam) self.progressBarSet(80) if self.trace_shadow: grabber.stop() for row in grabber.ttyData: self.writeStdOut(row) self.setStatusMessage("Plotting Results") self.plot_results(beam_out) self.plot_efficiency() self.setStatusMessage("") beam_out.setScanningData(self.input_beam.scanned_variable_data) self.send("Beam", beam_out) self.send("Trigger", TriggerIn(new_object=True)) 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: QMessageBox.critical(self, "Error", str(exception), QMessageBox.Ok) if self.IS_DEVELOP: raise exception self.progressBarFinished()
def xoppy_calc_power3Dcomponent(self): # # important: the transmittivity calculated here is referred on axes perp to the beam # therefore they do not include geometrical corrections for correct integral # substance = self.EL1_FOR thick = self.EL1_THI angle = self.EL1_ANG defection = self.EL1_DEF dens = self.EL1_DEN roughness = self.EL1_ROU flags = self.EL1_FLAG hgap = self.EL1_HGAP vgap = self.EL1_VGAP hmag = self.EL1_HMAG vmag = self.EL1_VMAG hrot = self.EL1_HROT vrot = self.EL1_VROT if self.INPUT_BEAM_FROM == 1: self.load_input_file() p0, e0, h0, v0 = self.input_beam.get_content("xoppy_data") p = p0.copy() e = e0.copy() h = h0.copy() v = v0.copy() transmittance = numpy.ones_like(p) E = e.copy() H = h.copy() V = v.copy() # initialize results # # get undefined densities # if flags <= 1: try: # apply written value rho = float(dens) except: # in case of ? # grabber = TTYGrabber() # grabber.start() rho = density(substance) # grabber.stop() # for row in grabber.ttyData: # self.writeStdOut(row) print("Density for %s: %g g/cm3"%(substance,rho)) dens = rho txt = "" if flags == 0: txt += ' ***** oe [Filter] *************\n' txt += ' Material: %s\n'%(substance) txt += ' Density [g/cm^3]: %f \n'%(dens) txt += ' thickness [mm] : %f \n'%(thick) txt += ' H gap [mm]: %f \n'%(hgap) txt += ' V gap [mm]: %f \n'%(vgap) txt += ' H rotation angle [deg]: %f \n'%(hrot) txt += ' V rotation angle [deg]: %f \n'%(vrot) elif flags == 1: txt += ' ***** oe [Mirror] *************\n' txt += ' Material: %s\n'%(substance) txt += ' Density [g/cm^3]: %f \n'%(dens) txt += ' grazing angle [mrad]: %f \n'%(angle) txt += ' roughness [A]: %f \n'%(roughness) elif flags == 2: txt += ' ***** oe [Aperture] *************\n' txt += ' H gap [mm]: %f \n'%(hgap) txt += ' V gap [mm]: %f \n'%(vgap) elif flags == 3: txt += ' ***** oe [Magnifier] *************\n' txt += ' H magnification: %f \n'%(hmag) txt += ' V magnification: %f \n'%(vmag) elif flags == 4: txt += ' ***** oe [Screen rotated] *************\n' txt += ' H rotation angle [deg]: %f \n'%(hrot) txt += ' V rotation angle [deg]: %f \n'%(vrot) if flags == 0: # filter grabber = TTYGrabber() grabber.start() for j,energy in enumerate(e): tmp = xraylib.CS_Total_CP(substance,energy/1000.0) transmittance[j,:,:] = numpy.exp(-tmp*dens*(thick/10.0)) grabber.stop() for row in grabber.ttyData: self.writeStdOut(row) # rotation H = h / numpy.cos(hrot * numpy.pi / 180) V = v / numpy.cos(vrot * numpy.pi / 180) # aperture h_indices_bad = numpy.where(numpy.abs(H) > 0.5*hgap) if len(h_indices_bad) > 0: transmittance[:, h_indices_bad, :] = 0.0 v_indices_bad = numpy.where(numpy.abs(V) > 0.5*vgap) if len(v_indices_bad) > 0: transmittance[:, :, v_indices_bad] = 0.0 absorbance = 1.0 - transmittance elif flags == 1: # mirror tmp = numpy.zeros(e.size) for j,energy in enumerate(e): tmp[j] = xraylib.Refractive_Index_Re(substance,energy/1000.0,dens) if tmp[0] == 0.0: raise Exception("Probably the substrance %s is wrong"%substance) delta = 1.0 - tmp beta = numpy.zeros(e.size) for j,energy in enumerate(e): beta[j] = xraylib.Refractive_Index_Im(substance,energy/1000.0,dens) try: (rs,rp,runp) = reflectivity_fresnel(refraction_index_beta=beta,refraction_index_delta=delta,\ grazing_angle_mrad=angle,roughness_rms_A=roughness,\ photon_energy_ev=e) except: raise Exception("Failed to run reflectivity_fresnel") for j,energy in enumerate(e): transmittance[j,:,:] = rs[j] # rotation if defection == 0: # horizontally deflecting H = h / numpy.sin(self.EL1_ANG * 1e-3) elif defection == 1: # vertically deflecting V = v / numpy.sin(self.EL1_ANG * 1e-3) # size absorbance = 1.0 - transmittance h_indices_bad = numpy.where(numpy.abs(H) > 0.5*hgap) if len(h_indices_bad) > 0: transmittance[:, h_indices_bad, :] = 0.0 absorbance[:, h_indices_bad, :] = 0.0 v_indices_bad = numpy.where(numpy.abs(V) > 0.5*vgap) if len(v_indices_bad) > 0: transmittance[:, :, v_indices_bad] = 0.0 absorbance[:, :, v_indices_bad] = 0.0 elif flags == 2: # aperture h_indices_bad = numpy.where(numpy.abs(H) > 0.5*hgap) if len(h_indices_bad) > 0: transmittance[:, h_indices_bad, :] = 0.0 v_indices_bad = numpy.where(numpy.abs(V) > 0.5*vgap) if len(v_indices_bad) > 0: transmittance[:, :, v_indices_bad] = 0.0 absorbance = 1.0 - transmittance elif flags == 3: # magnifier H = h * hmag V = v * vmag absorbance = 1.0 - transmittance elif flags == 4: # rotation screen # transmittance[:, :, :] = numpy.cos(hrot * numpy.pi / 180) * numpy.cos(vrot * numpy.pi / 180) H = h / numpy.cos(hrot * numpy.pi / 180) V = v / numpy.cos(vrot * numpy.pi / 180) absorbance = 1.0 - transmittance txt += self.info_total_power(p, e, v, h, transmittance, absorbance) print(txt) calculated_data = (transmittance, absorbance, E, H, V) if self.FILE_DUMP == 0: pass elif self.FILE_DUMP == 1: self.xoppy_write_h5file(calculated_data) elif self.FILE_DUMP == 2: self.xoppy_write_txt(calculated_data, method="3columns") elif self.FILE_DUMP == 3: self.xoppy_write_txt(calculated_data, method="matrix") return calculated_data