def extract_data_from_xoppy_output(self, calculation_output): spec_file_name = calculation_output sf = specfile.Specfile(spec_file_name) if sf.scanno() == 1: #load spec file with one scan, # is comment print("Loading file: ", spec_file_name) out = numpy.loadtxt(spec_file_name) if len(out) == 0 : raise Exception("Calculation gave no results (empty data)") #get labels txt = open(spec_file_name).readlines() tmp = [ line.find("#L") for line in txt] itmp = numpy.where(numpy.array(tmp) != (-1)) labels = txt[itmp[0]].replace("#L ","").split(" ") print("data labels: ", labels) calculated_data = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name()) calculated_data.add_content("xoppy_specfile", spec_file_name) calculated_data.add_content("xoppy_data", out) return calculated_data else: raise Exception("File %s contains %d scans. Cannot send it as xoppy_table" % (spec_file_name, sf.scanno()))
def extract_data_from_xoppy_output(self, calculation_output): data, fm, a, energy_ev = calculation_output calculated_data = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name()) calculated_data.add_content("xoppy_data", data) calculated_data.add_content("xoppy_data_3D", [fm, a, energy_ev]) return calculated_data
def extract_data_from_xoppy_output(self, calculation_output): e, h, v, p, code = calculation_output calculated_data = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name()) calculated_data.add_content("xoppy_data", [p, e, h, v]) calculated_data.add_content("xoppy_code", code) return calculated_data
def extract_data_from_xoppy_output(self, calculation_output): out_dict = calculation_output if "info" in out_dict.keys(): print(out_dict["info"]) calculated_data = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name()) calculated_data.add_content("xoppy_data", out_dict["data"]) return calculated_data
def extract_data_from_xoppy_output(self, calculation_output): e, f, sp = calculation_output data = numpy.zeros((len(e), 3)) data[:, 0] = numpy.array(e) data[:, 1] = numpy.array(f) data[:, 2] = numpy.array(sp) calculated_data = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name()) calculated_data.add_content("xoppy_data", data) return calculated_data
def read_spectrum_and_filters_file(self): try: data = numpy.loadtxt("filters.dat", skiprows=1) calculated_data = DataExchangeObject(program_name="ShadowOui", widget_name="PowerLoopPoint") calculated_data.add_content("filters_data", data) self.acceptFilters(calculated_data) except Exception: self.filters = None self.read_spectrum_file(False)
def read_spectrum_file(self): try: data = numpy.loadtxt("autobinning.dat", skiprows=1) calculated_data = DataExchangeObject( program_name="SRW", widget_name="UNDULATOR_SPECTRUM") calculated_data.add_content("srw_data", data) self.send("ExchangeData", calculated_data) except Exception as e: QMessageBox.critical(self, "Error", str(e), QMessageBox.Ok) if self.IS_DEVELOP: raise e
def example_1d(): app = QtGui.QApplication([]) ow = OWPlotSimpleExchange() a = DataExchangeObject("TEXT","TEST") a.add_content("data",numpy.array([ [ 8.47091837e+04, 1.16210756e+12], [ 8.57285714e+04, 1.10833975e+12], [ 8.67479592e+04, 1.05700892e+12], [ 8.77673469e+04, 1.00800805e+12] ])) ow.do_plot(a) ow.show() app.exec_() ow.saveSettings()
def example_1d(): app = QtWidgets.QApplication([]) ow = OWPlotSimpleExchange() a = DataExchangeObject("TEXT","TEST") a.add_content("data",numpy.array([ [ 8.47091837e+04, 1.16210756e+12], [ 8.57285714e+04, 1.10833975e+12], [ 8.67479592e+04, 1.05700892e+12], [ 8.77673469e+04, 1.00800805e+12] ])) ow.do_plot(a) ow.show() app.exec_() ow.saveSettings()
def extract_data_from_xoppy_output(self, calculation_output): transmittance, absorbance, E, H, V = calculation_output p0, e0, h0, v0 = self.input_beam.get_content("xoppy_data") p = p0.copy() e = e0.copy() h = h0.copy() v = v0.copy() # coordinates to send: the same as incident beam (perpendicular to the optical axis) # except for the magnifier if self.EL1_FLAG == 3: # magnifier <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< h *= self.EL1_HMAG v *= self.EL1_VMAG p_transmitted = p * transmittance / (h[0] / h0[0]) / (v[0] / v0[0]) data_to_send = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name()) data_to_send.add_content("xoppy_data", [p_transmitted, e, h, v]) data_to_send.add_content("xoppy_transmittivity", calculation_output) data_to_send.add_content("xoppy_code", "power3Dcomponent") self.output_beam = data_to_send return data_to_send
def extract_data_from_xoppy_output(self, calculation_output): K_scan,harmonics,P_scan,energy_values_at_flux_peak,flux_values = calculation_output harmonics_data = [] for ih,harmonic_number in enumerate(harmonics): harmonics_data.append([harmonic_number,None]) data = numpy.zeros((K_scan.size, 5)) data[:, 0] = numpy.array(energy_values_at_flux_peak[:,ih]) data[:, 1] = numpy.array(flux_values[:,ih]) data[:, 2] = numpy.array(flux_values[:,ih])*codata.e*1e3 data[:, 3] = numpy.array(K_scan) data[:, 4] = numpy.array(P_scan) harmonics_data[ih][1] = data #send exchange calculated_data = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name()) try: calculated_data.add_content("xoppy_data_harmonics", harmonics_data) calculated_data.add_content("plot_x_col", 1) calculated_data.add_content("plot_y_col", 2) except: pass try: calculated_data.add_content("labels",["Photon energy [eV]","Flux [photons/s/0.1%bw]","Ky","Power [W]"]) except: pass return calculated_data
def read_spectrum_file(self, reset_filters=True): try: if reset_filters: self.filters = None self.filter_plot.clear() data = numpy.loadtxt("autobinning.dat", skiprows=1) calculated_data = DataExchangeObject(program_name="ShadowOui", widget_name="PowerLoopPoint") calculated_data.add_content("spectrum_data", data) self.acceptEnergySpectrum(calculated_data) except Exception as e: QMessageBox.critical(self, "Error", str(e), QMessageBox.Ok) if self.IS_DEVELOP: raise e
def extract_data_from_xoppy_output(self, calculation_output): e, h, v, p, traj = calculation_output calculated_data = DataExchangeObject( "XOPPY", self.get_data_exchange_widget_name()) calculated_data.add_content("xoppy_data", [p, e, h, v]) calculated_data.add_content("xoppy_trajectory", traj) calculated_data.add_content("xoppy_code", "srfunc") return calculated_data
def example_2d(): app = QtGui.QApplication([]) ow = OWPlotSimpleExchange() a = DataExchangeObject("TEXT","TEST") x = numpy.linspace(-4, 4, 20) y = numpy.linspace(-4, 4, 20) z = numpy.sqrt(x[numpy.newaxis, :]**2 + y[:, numpy.newaxis]**2) a.add_content("data2D",z) a.add_content("dataX",x) a.add_content("dataY",y) ow.do_plot(a) ow.show() app.exec_() ow.saveSettings()
def create_exchange_data(self, tickets): ticket = tickets[0] if isinstance(ticket['histogram'].shape, list): f = ticket['histogram'][0] else: f = ticket['histogram'] e = ticket['bins'] data = numpy.zeros((len(e), 2)) data[:, 0] = numpy.array(e) data[:, 1] = numpy.array(f) calculated_data = DataExchangeObject(program_name="SRW", widget_name="UNDULATOR_SPECTRUM") calculated_data.add_content("srw_data", data) return calculated_data
def extract_data_from_xoppy_output(self, calculation_output): spec_file_name = calculation_output sf = SpecFile(spec_file_name) if len(sf) == 1: #load spec file with one scan, # is comment print(("Loading file: ", spec_file_name)) out = numpy.loadtxt(spec_file_name) if len(out) == 0 : raise Exception("Calculation gave no results (empty data)") #get labels # txt = open(spec_file_name).readlines() # tmp = [ line.find("#L") for line in txt] # itmp = numpy.where(numpy.array(tmp) != (-1)) # labels = txt[int(itmp[0])].replace("#L ","").split(" ") # print("data labels: ", labels) calculated_data = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name()) calculated_data.add_content("xoppy_specfile", spec_file_name) calculated_data.add_content("xoppy_data", out) return calculated_data else: raise Exception("File %s contains %d scans. Cannot send it as xoppy_table" % (spec_file_name, len(sf)))
def extract_data_from_xoppy_output(self, calculation_output): [p, e, h, v] = self.input_beam.get_content("xoppy_data") data_to_send = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name()) data_to_send.add_content( "xoppy_data", [p * calculation_output.prod(axis=0), e, h, v]) data_to_send.add_content("xoppy_transmittivity", calculation_output) data_to_send.add_content("xoppy_code", "power3") self.output_beam = data_to_send return data_to_send
def extract_data_from_xoppy_output(self, calculation_output): h, v, p, code = calculation_output calculated_data = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name()) calculated_data.add_content("xoppy_data", [h, v, p]) calculated_data.add_content("xoppy_code", code) return calculated_data
def extract_data_from_xoppy_output(self, calculation_output): [p, e, h, v] = self.input_beam.get_content("xoppy_data") data_to_send = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name()) data_to_send.add_content("xoppy_data", [p*calculation_output.prod(axis=0), e, h, v]) data_to_send.add_content("xoppy_transmittivity", calculation_output) data_to_send.add_content("xoppy_code", "power3") self.output_beam = data_to_send return data_to_send
def load_input_file(self): e, h, v, p, code = self.extract_data_from_h5file(self.INPUT_BEAM_FILE, "XOPPY_RADIATION") received_data = DataExchangeObject("XOPPY", "POWER3DCOMPONENT") received_data.add_content("xoppy_data", [p, e, h, v]) received_data.add_content("xoppy_code", code) self.input_beam = received_data print("Input beam read from file %s \n\n"%self.INPUT_BEAM_FILE)
def example_2d(): app = QtGui.QApplication([]) ow = OWPlotSimpleExchange() a = DataExchangeObject("TEXT", "TEST") x = numpy.linspace(-4, 4, 20) y = numpy.linspace(-4, 4, 20) z = numpy.sqrt(x[numpy.newaxis, :]**2 + y[:, numpy.newaxis]**2) a.add_content("data2D", z) a.add_content("dataX", x) a.add_content("dataY", y) ow.do_plot(a) ow.show() app.exec_() ow.saveSettings()
def extract_data_from_xoppy_output(self, calculation_output): K_scan,harmonics,P_scan,energy_values_at_flux_peak,flux_values = calculation_output harmonics_data = [] for ih in range(len(harmonics)): harmonic_number = int(harmonics[ih]) harmonics_data.append([harmonic_number,None]) data = numpy.zeros((K_scan.size, 5)) data[:, 0] = numpy.array(energy_values_at_flux_peak[:,ih]) data[:, 1] = numpy.array(flux_values[:,ih]) data[:, 2] = numpy.array(flux_values[:,ih])*codata.e*1e3 data[:, 3] = numpy.array(K_scan) data[:, 4] = numpy.array(P_scan) harmonics_data[ih][1] = data #send exchange calculated_data = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name()) try: calculated_data.add_content("xoppy_data_harmonics", harmonics_data) calculated_data.add_content("plot_x_col", 1) calculated_data.add_content("plot_y_col", 2) except: pass try: calculated_data.add_content("labels",["Photon energy [eV]","Flux [photons/s/0.1%bw]","Ky","Power [W]"]) except: pass return calculated_data
def xoppy_calc_xtcap(self): for file in ["tcap.inp","tcap.out","tcap.log"]: try: os.remove(os.path.join(locations.home_bin_run(),file)) except: pass with open("tcap.inp", "wt") as f: f.write("TCAP called from xoppy\n") f.write("%10.3f %10.2f %10.6f %s\n"%(self.ENERGY,self.CURRENT,self.ENERGY_SPREAD,"Ring-Energy(GeV) Current(mA) Beam-Energy-Spread")) f.write("%10.4f %10.4f %10.4f %10.4f %s\n"%(self.SIGX,self.SIGY,self.SIGX1,self.SIGY1,"Sx(mm) Sy(mm) Sx1(mrad) Sy1(mrad)")) f.write("%10.3f %d %s\n"%(self.PERIOD,self.NP,"Period(cm) N")) f.write("%10.1f %10.1f %d %s\n"%(self.EMIN,self.EMAX,self.N,"Emin Emax Ne")) f.write("%10.3f %10.3f %10.3f %10.3f %10.3f %d %d %s\n"%(self.DISTANCE,self.XPC,self.YPC,self.XPS,self.YPS,10,10,"d xpc ypc xps yps nxp nyp")) f.write("%d %d %d %d %s\n"%(self.HARMONIC_FROM,self.HARMONIC_TO,self.HARMONIC_STEP,self.HRED,"Hmin Hmax Hstep Hreduction")) f.write("%d %d %d %d %d %s\n"%(self.HELICAL,self.METHOD,1,self.NEKS,self.BSL,"Helical Method Print_K Neks Bsl-Subtr ")) f.write("foreground\n") if platform.system() == "Windows": command = "\"" + os.path.join(locations.home_bin(),'tcap.exe') + "\"" else: command = "'" + os.path.join(locations.home_bin(), 'tcap') + "'" print("Running command '%s' in directory: %s "%(command, locations.home_bin_run())) print("\n--------------------------------------------------------\n") # os.system(command) # # catch the optut and write the output to a log file as well as print it. # retvalue = os.popen(command).read() print(retvalue) with open("tcap.log", "wt") as f: f.write(retvalue) print("Output file: '%s/tcap.out'"%(os.getcwd()) ) print("\n--------------------------------------------------------\n") # # parse result files to exchange object # with open("tcap.out","r") as f: lines = f.readlines() # print output file # for line in lines: # print(line, end="") # remove returns lines = [line[:-1] for line in lines] harmonics_data = [] # separate numerical data from text floatlist = [] harmoniclist = [] txtlist = [] for line in lines: try: tmp = line.strip() if tmp.startswith("Harmonic"): # harmonic_number = int(tmp.split("Harmonic")[1].strip()) harmonic_number = int(tmp.split()[1]) if harmonic_number != self.HARMONIC_FROM: harmonics_data[-1][1] = harmoniclist harmoniclist = [] harmonics_data.append([harmonic_number, None]) tmp = float(line.strip()[0]) floatlist.append(line) harmoniclist.append(line) except: txtlist.append(line) harmonics_data[-1][1] = harmoniclist data = numpy.loadtxt(floatlist) for index in range(0, len(harmonics_data)): # print (harmonics_data[index][0], harmonics_data[index][1]) harmonics_data[index][1] = numpy.loadtxt(harmonics_data[index][1]) #send exchange calculated_data = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name()) try: calculated_data.add_content("xoppy_data", data) calculated_data.add_content("xoppy_data_harmonics", harmonics_data) calculated_data.add_content("plot_x_col", 0) calculated_data.add_content("plot_y_col", 1) except: pass try: calculated_data.add_content("labels",["Energy(eV)","Flux(ph/s/0.1%bw)","FWHM(eV)","Ky", "Ptot(W)","Pd(W/mm^2)","IntP(W)"]) except: pass try: calculated_data.add_content("info",txtlist) except: pass return calculated_data
def submit(self): self.progressBarInit() self.setStatusMessage("Submitting Request") self.checkFields() parameters = {} parameters.update({"xway" : self.decode_xway()}) parameters.update({"wave" : str(self.wave)}) parameters.update({"line" : self.line}) parameters.update({"ipol" : str(self.ipol + 1)}) parameters.update({"code" : self.code}) parameters.update({"df1df2" : self.decode_df1df2()}) parameters.update({"sigma" : str(self.sigma)}) parameters.update({"w0" : str(self.w0)}) parameters.update({"wh" : str(self.wh)}) parameters.update({"i1" : str(self.i1)}) parameters.update({"i2" : str(self.i2)}) parameters.update({"i3" : str(self.i3)}) parameters.update({"daa" : str(self.daa)}) parameters.update({"igie" : self.decode_igie()}) parameters.update({"fcentre" : str(self.fcentre)}) parameters.update({"unic" : str(self.unic - 1)}) parameters.update({"n1" : str(self.n1)}) parameters.update({"n2" : str(self.n2)}) parameters.update({"n3" : str(self.n3)}) parameters.update({"m1" : str(self.m1)}) parameters.update({"m2" : str(self.m2)}) parameters.update({"m3" : str(self.m3)}) parameters.update({"miscut" : str(self.miscut)}) parameters.update({"unim" : str(self.unim)}) parameters.update({"a1" : str(self.a1)}) parameters.update({"a2" : str(self.a2)}) parameters.update({"a3" : str(self.a3)}) parameters.update({"scanmin" : str(self.scanmin)}) parameters.update({"scanmax" : str(self.scanmax)}) parameters.update({"unis" : str(self.unis)}) parameters.update({"nscan" : str(self.nscan)}) parameters.update({"invert" : str(self.invert)}) parameters.update({"axis" : self.decode_axis()}) parameters.update({"column" : self.decode_column()}) parameters.update({"alphamax" : str(self.alphamax)}) parameters.update({"profile" : self.profile}) try: self.progressBarSet(10) response = HttpManager.send_xray_server_request_GET(APPLICATION, parameters) self.progressBarSet(50) data = self.extract_plots(response) exchange_data = DataExchangeObject("XRAYSERVER", "GID_SL") exchange_data.add_content("x-ray_diffraction_profile", data) exchange_data.add_content("x-ray_diffraction_profile_units_to_degrees", self.get_units_to_degrees()) self.send("xrayserver_data", exchange_data) except urllib.error.HTTPError as e: ShowTextDialog.show_text("Error", 'The server couldn\'t fulfill the request.\nError Code: ' + str(e.code) + "\n\n" + server.BaseHTTPRequestHandler.responses[e.code][1], parent=self) except urllib.error.URLError as e: ShowTextDialog.show_text("Error", 'We failed to reach a server.\nReason: ' + e.reason, parent=self) except XrayServerException as e: ShowHtmlDialog.show_html("X-ray Server Error", e.response, width=750, height=500, parent=self) except Exception as e: ShowTextDialog.show_text("Error", 'Error Occurred.\nReason: ' + str(e), parent=self) self.setStatusMessage("") self.progressBarFinished()
if __name__ == "__main__": from oasys.widgets.exchange import DataExchangeObject input_data_type = "POWER3D" if input_data_type == "POWER": # create fake UNDULATOR_FLUX xoppy exchange data e = numpy.linspace(1000.0, 10000.0, 100) source = e/10 received_data = DataExchangeObject("XOPPY", "POWER") received_data.add_content("xoppy_data", numpy.vstack((e,e,source)).T) received_data.add_content("xoppy_code", "US") elif input_data_type == "POWER3D": # create unulator_radiation xoppy exchange data from orangecontrib.xoppy.util.xoppy_undulators import xoppy_calc_undulator_radiation e, h, v, p, code = xoppy_calc_undulator_radiation(ELECTRONENERGY=6.04,ELECTRONENERGYSPREAD=0.001,ELECTRONCURRENT=0.2,\ ELECTRONBEAMSIZEH=0.000395,ELECTRONBEAMSIZEV=9.9e-06,\ ELECTRONBEAMDIVERGENCEH=1.05e-05,ELECTRONBEAMDIVERGENCEV=3.9e-06,\ PERIODID=0.018,NPERIODS=222,KV=1.68,DISTANCE=30.0, SETRESONANCE=0,HARMONICNUMBER=1, GAPH=0.001,GAPV=0.001,\ HSLITPOINTS=41,VSLITPOINTS=41,METHOD=0, PHOTONENERGYMIN=7000,PHOTONENERGYMAX=8100,PHOTONENERGYPOINTS=20,
def xoppy_calc_xtc(self): for file in ["tc.inp","tc.out"]: try: os.remove(os.path.join(locations.home_bin_run(),file)) except: pass with open("tc.inp", "wt") as f: f.write("TS called from xoppy\n") f.write("%10.3f %10.2f %10.6f %s\n"%(self.ENERGY,self.CURRENT,self.ENERGY_SPREAD,"Ring-Energy(GeV) Current(mA) Beam-Energy-Spread")) f.write("%10.4f %10.4f %10.4f %10.4f %s\n"%(self.SIGX,self.SIGY,self.SIGX1,self.SIGY1,"Sx(mm) Sy(mm) Sx1(mrad) Sy1(mrad)")) f.write("%10.3f %d %s\n"%(self.PERIOD,self.NP,"Period(cm) N")) f.write("%10.1f %10.1f %d %s\n"%(self.EMIN,self.EMAX,self.N,"Emin Emax Ne")) f.write("%d %d %d %s\n"%(self.HARMONIC_FROM,self.HARMONIC_TO,self.HARMONIC_STEP,"Hmin Hmax Hstep")) f.write("%d %d %d %d %s\n"%(self.HELICAL,self.METHOD,1,self.NEKS,"Helical Method Print_K Neks")) f.write("foreground\n") if platform.system() == "Windows": command = os.path.join(locations.home_bin(),'tc.exe') else: command = "'" + os.path.join(locations.home_bin(), 'tc') + "'" print("Running command '%s' in directory: %s "%(command, locations.home_bin_run())) print("\n--------------------------------------------------------\n") os.system(command) print("Output file: %s"%("tc.out")) print("\n--------------------------------------------------------\n") # # parse result files to exchange object # with open("tc.out","r") as f: lines = f.readlines() # print output file # for line in lines: # print(line, end="") # remove returns lines = [line[:-1] for line in lines] harmonics_data = [] # separate numerical data from text floatlist = [] harmoniclist = [] txtlist = [] for line in lines: try: tmp = line.strip() if tmp.startswith("Harmonic"): harmonic_number = int(tmp.split("Harmonic")[1].strip()) if harmonic_number != self.HARMONIC_FROM: harmonics_data[-1][1] = harmoniclist harmoniclist = [] harmonics_data.append([harmonic_number, None]) tmp = float(line.strip()[0]) floatlist.append(line) harmoniclist.append(line) except: txtlist.append(line) harmonics_data[-1][1] = harmoniclist data = numpy.loadtxt(floatlist) for index in range(0, len(harmonics_data)): # print (harmonics_data[index][0], harmonics_data[index][1]) harmonics_data[index][1] = numpy.loadtxt(harmonics_data[index][1]) #send exchange calculated_data = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name()) try: calculated_data.add_content("xoppy_data", data) calculated_data.add_content("xoppy_data_harmonics", harmonics_data) calculated_data.add_content("plot_x_col", 1) calculated_data.add_content("plot_y_col", 2) except: pass try: calculated_data.add_content("labels",["Energy (eV) without emittance", "Energy (eV) with emittance", "Brilliance (ph/s/mrad^2/mm^2/0.1%bw)","Ky","Total Power (W)","Power density (W/mr^2)"]) except: pass try: calculated_data.add_content("info",txtlist) except: pass return calculated_data
def xoppy_calc_mlayer(self): # copy the variable locally, so no more use of self. MODE = self.MODE SCAN = self.SCAN F12_FLAG = self.F12_FLAG SUBSTRATE = self.SUBSTRATE ODD_MATERIAL = self.ODD_MATERIAL EVEN_MATERIAL = self.EVEN_MATERIAL ENERGY = self.ENERGY THETA = self.THETA SCAN_STEP = self.SCAN_STEP NPOINTS = self.NPOINTS ODD_THICKNESS = self.ODD_THICKNESS EVEN_THICKNESS = self.EVEN_THICKNESS NLAYERS = self.NLAYERS FILE=self.FILE for file in ["mlayer.inp","mlayer.par","mlayer.f12"]: try: os.remove(os.path.join(locations.home_bin_run(),file)) except: pass # # write input file for Fortran mlayer: mlayer.inp # f = open('mlayer.inp','w') if SCAN == 0 and MODE == 0: a0 = 1 if SCAN == 1 and MODE == 0: a0 = 5 if SCAN == 0 and MODE == 1: a0 = 3 if SCAN == 1 and MODE == 1: a0 = 5 f.write("%d \n"%a0) f.write("N\n") f.write("%g\n"%( codata.h * codata.c / codata.e * 1e10 / ENERGY)) f.write("%g\n"%THETA) if SCAN == 0: f.write("%g\n"%SCAN_STEP) a2 = codata.h * codata.c / codata.e * 1e10 / ENERGY a3 = codata.h * codata.c / codata.e * 1e10 / (ENERGY + SCAN_STEP) a4 = a3 - a2 if SCAN != 0: f.write("%g\n"%a4) f.write("%d\n"%NPOINTS) if MODE == 0: f.write("%d\n"%NLAYERS) if MODE == 0: if a0 != 5: f.write("%g %g \n"%(ODD_THICKNESS,EVEN_THICKNESS)) else: for i in range(NLAYERS): f.write("%g %g \n"%(ODD_THICKNESS,EVEN_THICKNESS)) if MODE != 0: f1 = open(FILE,'r') a5 = f1.read() f1.close() if MODE != 0: print("Number of layers in %s file is %d "%(FILE,NLAYERS)) f.write("%d\n"%NLAYERS) f.write(a5) f.write("mlayer.par\n") f.write("mlayer.dat\n") f.write("6\n") f.close() print('File written to disk: mlayer.inp') # # create f12 file # if F12_FLAG == 0: energy = numpy.arange(0,500) elefactor = numpy.log10(10000.0 / 30.0) / 300.0 energy = 10.0 * 10**(energy * elefactor) f12_s = f1f2_calc(SUBSTRATE,energy) f12_e = f1f2_calc(EVEN_MATERIAL,energy) f12_o = f1f2_calc(ODD_MATERIAL,energy) f = open("mlayer.f12",'w') f.write('; File created by xoppy for materials [substrate=%s,even=%s,odd=%s]: \n'%(SUBSTRATE,EVEN_MATERIAL,ODD_MATERIAL)) f.write('; Atomic masses: \n') f.write("%g %g %g \n"%(xraylib.AtomicWeight(xraylib.SymbolToAtomicNumber(SUBSTRATE)), xraylib.AtomicWeight(xraylib.SymbolToAtomicNumber(EVEN_MATERIAL)), xraylib.AtomicWeight(xraylib.SymbolToAtomicNumber(ODD_MATERIAL)) )) f.write('; Densities: \n') f.write("%g %g %g \n"%(xraylib.ElementDensity(xraylib.SymbolToAtomicNumber(SUBSTRATE)), xraylib.ElementDensity(xraylib.SymbolToAtomicNumber(EVEN_MATERIAL)), xraylib.ElementDensity(xraylib.SymbolToAtomicNumber(ODD_MATERIAL)) )) f.write('; Number of energy points: \n') f.write("%d\n"%(energy.size)) f.write('; For each energy point, energy[eV], f1[substrate], f2[substrate], f1[even], f2[even], f1[odd], f2[odd]: \n') for i in range(energy.size): f.write("%g %g %g %g %g %g %g \n"%(energy[i],f12_s[0,i],f12_s[1,i],f12_e[0,i],f12_e[1,i],f12_o[0,i],f12_o[1,i])) f.close() print('File written to disk: mlayer.f12') # # run external program mlayer # command = os.path.join(locations.home_bin(), 'mlayer') + " < mlayer.inp" print("Running command '%s' in directory: %s "%(command, locations.home_bin_run())) print("\n--------------------------------------------------------\n") os.system(command) print("\n--------------------------------------------------------\n") #send exchange calculated_data = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name()) try: calculated_data.add_content("xoppy_data", numpy.loadtxt("mlayer.dat")) calculated_data.add_content("plot_x_col", 0) calculated_data.add_content("plot_y_col", 3) calculated_data.add_content("units_to_degrees", 1.0) except: pass try: calculated_data.add_content("labels",["Grazing angle Theta [deg]","s-reflectivity","p-reflectivity","averaged reflectivity","s-phase shift","p-phase shift","(s-electric field)^2","(p-electric field)^2"]) except: pass try: info = "ML %s(%3.2f A):%s(%3.2f A) %d pairs; E=%5.3f eV"%(ODD_MATERIAL,ODD_THICKNESS,EVEN_MATERIAL,EVEN_THICKNESS,NLAYERS,ENERGY) calculated_data.add_content("info",info) except: pass return calculated_data
def submit(self): self.progressBarInit() self.setStatusMessage("Submitting Request") self.checkFields() parameters = {} parameters.update({"xway" : str(self.xway + 1)}) parameters.update({"wave" : str(self.wave)}) parameters.update({"line" : self.line}) parameters.update({"coway" : str(self.coway)}) parameters.update({"code" : self.code}) parameters.update({"amor" : self.amor}) parameters.update({"chem" : self.chem}) parameters.update({"rho" : str(self.rho)}) parameters.update({"i1" : str(self.i1)}) parameters.update({"i2" : str(self.i2)}) parameters.update({"i3" : str(self.i3)}) parameters.update({"df1df2" : self.decode_df1df2()}) parameters.update({"modeout" : "0" }) parameters.update({"detail" : str(self.detail)}) try: response = HttpManager.send_xray_server_request_GET(APPLICATION, parameters) response = self.clear_response(response) self.tabs_widget.setCurrentIndex(0) self.x0h_output.setHtml(response) data0, data1, data2 = self.extract_plots(response) try: exchange_data = DataExchangeObject("XRAYSERVER", "X0H") if self.coway == 0: # crystals dictionary = self.extract_structure_data(response) exchange_data.add_content("structure", dictionary["structure"]) exchange_data.add_content("h", self.i1) exchange_data.add_content("k", self.i2) exchange_data.add_content("l", self.i3) exchange_data.add_content("d_spacing", dictionary["d_spacing"]) exchange_data.add_content("energy", dictionary["energy"]) exchange_data.add_content("bragg_angle", dictionary["bragg_angle"]) exchange_data.add_content("xr0", dictionary["xr0"]) exchange_data.add_content("xi0", dictionary["xi0"]) exchange_data.add_content("xrh_s", dictionary["xrh_s"]) exchange_data.add_content("xih_s", dictionary["xih_s"]) exchange_data.add_content("xrh_p", dictionary["xrh_p"]) exchange_data.add_content("xih_p", dictionary["xih_p"]) exchange_data.add_content("reflectivity", data0) exchange_data.add_content("reflectivity_units_to_degrees", 1.0) exchange_data.add_content("x-ray_diffraction_profile_sigma", data1) exchange_data.add_content("x-ray_diffraction_profile_sigma_units_to_degrees", 0.000277777805) exchange_data.add_content("x-ray_diffraction_profile_pi", data2) exchange_data.add_content("x-ray_diffraction_profile_pi_units_to_degrees", 0.000277777805) self.send("xrayserver_data", exchange_data) except: #problems with xrayserver, no data found pass except urllib.error.HTTPError as e: self.x0h_output.setHtml('The server couldn\'t fulfill the request.\nError Code: ' + str(e.code) + "\n\n" + server.BaseHTTPRequestHandler.responses[e.code][1]) except urllib.error.URLError as e: self.x0h_output.setHtml('We failed to reach a server.\nReason: ' + e.reason) except XrayServerException as e: ShowHtmlDialog.show_html("X-ray Server Error", e.response, width=750, height=500, parent=self) except Exception as e: ShowTextDialog.show_text("Error", 'Error Occurred.\nReason: ' + str(e), parent=self) self.setStatusMessage("") self.progressBarFinished()
def xoppy_calc_xf1f2(self): MAT_FLAG = self.MAT_FLAG DESCRIPTOR = self.DESCRIPTOR density = self.DENSITY CALCULATE = self.CALCULATE GRID = self.GRID GRIDSTART = self.GRIDSTART GRIDEND = self.GRIDEND GRIDN = self.GRIDN THETAGRID = self.THETAGRID ROUGH = self.ROUGH THETA1 = self.THETA1 THETA2 = self.THETA2 THETAN = self.THETAN if MAT_FLAG == 0: # element descriptor = DESCRIPTOR density = xraylib.ElementDensity( xraylib.SymbolToAtomicNumber(DESCRIPTOR)) elif MAT_FLAG == 1: # formula descriptor = DESCRIPTOR if GRID == 0: # standard energy grid energy = numpy.arange(0, 500) elefactor = numpy.log10(10000.0 / 30.0) / 300.0 energy = 10.0 * 10**(energy * elefactor) elif GRID == 1: # user energy grid if GRIDN == 1: energy = numpy.array([GRIDSTART]) else: energy = numpy.linspace(GRIDSTART, GRIDEND, GRIDN) elif GRID == 2: # single energy point energy = numpy.array([GRIDSTART]) if THETAGRID == 0: theta = numpy.array([THETA1]) else: theta = numpy.linspace(THETA1, THETA2, THETAN) CALCULATE_items = [ 'f1', 'f2', 'delta', 'beta', 'mu [cm^-1]', 'mu [cm^2/g]', 'Cross Section [barn]', 'reflectivity-s', 'reflectivity-p', 'reflectivity-unpol', 'delta/beta ' ] out = numpy.zeros((energy.size, theta.size)) for i, itheta in enumerate(theta): if MAT_FLAG == 0: # element tmp = f1f2_calc(descriptor, energy, 1e-3 * itheta, F=1 + CALCULATE, rough=ROUGH, density=density) out[:, i] = tmp else: tmp = f1f2_calc_mix(descriptor, energy, 1e-3 * itheta, F=1 + CALCULATE, rough=ROUGH, density=density) out[:, i] = tmp if ((energy.size == 1) and (theta.size == 1)): info = "** Single value calculation E=%g eV, theta=%g mrad, Result(F=%d)=%g " % ( energy[0], theta[0], 1 + CALCULATE, out[0, 0]) labels = ["Energy [eV]", CALCULATE_items[CALCULATE]] tmp = numpy.vstack((energy, out[:, 0])) print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", energy.shape, out.shape, tmp.shape) out_dict = { "application": "xoppy", "name": "xf12", "info": info, "data": tmp, "labels": labels } elif theta.size == 1: tmp = numpy.vstack((energy, out[:, 0])) labels = ["Energy [eV]", CALCULATE_items[CALCULATE]] out_dict = { "application": "xoppy", "name": "xf12", "data": tmp, "labels": labels } elif energy.size == 1: tmp = numpy.vstack((theta, out[0, :])) labels = ["Theta [mrad]", CALCULATE_items[CALCULATE]] out_dict = { "application": "xoppy", "name": "xf12", "data": tmp, "labels": labels } else: labels = [r"energy[eV]", r"theta [mrad]"] out_dict = { "application": "xoppy", "name": "xf12", "data2D": out, "dataX": energy, "dataY": theta, "labels": labels } # # # if "info" in out_dict.keys(): print(out_dict["info"]) #send exchange calculated_data = DataExchangeObject( "XOPPY", self.get_data_exchange_widget_name()) try: calculated_data.add_content("xoppy_data", out_dict["data"].T) calculated_data.add_content("plot_x_col", 0) calculated_data.add_content("plot_y_col", -1) except: pass try: calculated_data.add_content("labels", out_dict["labels"]) except: pass try: calculated_data.add_content("info", out_dict["info"]) except: pass try: calculated_data.add_content("data2D", out_dict["data2D"]) calculated_data.add_content("dataX", out_dict["dataX"]) calculated_data.add_content("dataY", out_dict["dataY"]) except: pass if self.DUMP_TO_FILE: with open(self.FILE_NAME, "w") as file: try: file.write("#F %s\n" % self.FILE_NAME) file.write("\n#S 1 xoppy f1f2 results\n") print("data shape", out_dict["data"].shape) print("labels: ", out_dict["labels"]) file.write("#N 2\n") file.write("#L %s %s\n" % (out_dict["labels"][0], out_dict["labels"][1])) out = out_dict["data"] for j in range(out.shape[1]): file.write( ("%19.12e " * out.shape[0] + "\n") % tuple(out[i, j] for i in range(out.shape[0]))) file.close() print("File written to disk: %s \n" % self.FILE_NAME) except: raise Exception( "CrossSec: The data could not be dumped onto the specified file!\n" ) return calculated_data
def do_xoppy_calculation(self): out_dict = self.xoppy_calc_xcrosssec() if "info" in out_dict.keys(): print(out_dict["info"]) #send exchange calculated_data = DataExchangeObject( "XOPPY", self.get_data_exchange_widget_name()) try: calculated_data.add_content("xoppy_data", out_dict["data"].T) calculated_data.add_content("plot_x_col", 0) calculated_data.add_content("plot_y_col", -1) except: pass try: calculated_data.add_content("labels", out_dict["labels"]) except: pass try: calculated_data.add_content("info", out_dict["info"]) except: pass return calculated_data
def submit(self): self.progressBarInit() self.setStatusMessage("Submitting Request") self.checkFields() parameters = {} parameters.update({"xway" : self.decode_xway()}) parameters.update({"wave" : str(self.wave)}) parameters.update({"line" : self.line}) parameters.update({"ipol" : str(self.ipol + 1)}) parameters.update({"subway" : str(self.subway + 1)}) parameters.update({"code" : self.code}) parameters.update({"df1df2" : self.decode_df1df2()}) parameters.update({"chem" : self.chem}) parameters.update({"rho" : str(self.rho)}) parameters.update({"x0" : str(self.x0)}) parameters.update({"w0" : str(self.w0)}) parameters.update({"sigma" : str(self.sigma)}) parameters.update({"tr" : str(self.tr)}) parameters.update({"scanmin" : str(self.scanmin)}) parameters.update({"scanmax" : str(self.scanmax)}) parameters.update({"unis" : str(self.unis)}) parameters.update({"nscan" : str(self.nscan)}) parameters.update({"swflag" : self.decode_swflag()}) if self.swflag == True or self.swflag == 1: parameters.update({"swref" : str(self.swref)}) parameters.update({"swmin" : str(self.swmin)}) parameters.update({"swmax" : str(self.swmax)}) parameters.update({"swpts" : str(self.swpts)}) parameters.update({"profile" : self.profile}) try: self.progressBarSet(10) response = HttpManager.send_xray_server_request_GET(APPLICATION, parameters) self.progressBarSet(50) data = self.extract_plots(response) exchange_data = DataExchangeObject("XRAYSERVER", "TER_SL") exchange_data.add_content("ter_sl_result", data) exchange_data.add_content("ter_sl_result_units_to_degrees", self.get_units_to_degrees()) self.send("xrayserver_data", exchange_data) except urllib.error.HTTPError as e: ShowTextDialog.show_text("Error", 'The server couldn\'t fulfill the request.\nError Code: ' + str(e.code) + "\n\n" + server.BaseHTTPRequestHandler.responses[e.code][1], parent=self) except urllib.error.URLError as e: ShowTextDialog.show_text("Error", 'We failed to reach a server.\nReason: ' + e.reason, parent=self) except XrayServerException as e: ShowHtmlDialog.show_html("X-ray Server Error", e.response, width=750, height=500, parent=self) except Exception as e: ShowTextDialog.show_text("Error", 'Error Occurred.\nReason: ' + str(e), parent=self) self.setStatusMessage("") self.progressBarFinished()
def _callable_2(self, html): try: self.x0h_input.loadFinished.disconnect() self.x0h_input.back() self.x0h_input.setHidden(False) response_1 = self.clear_response(html) response_2 = self.clear_response(html) self.tabs_widget.setCurrentIndex(0) self.x0h_output.setHtml(response_1) data0, data1, data2 = self.extract_plots(response_2) exchange_data = DataExchangeObject("XRAYSERVER", "X0H") exchange_data.add_content("reflectivity", data0) exchange_data.add_content("reflectivity_units_to_degrees", 1.0) exchange_data.add_content("x-ray_diffraction_profile_sigma", data1) exchange_data.add_content( "x-ray_diffraction_profile_sigma_units_to_degrees", 0.000277777805) exchange_data.add_content("x-ray_diffraction_profile_pi", data2) exchange_data.add_content( "x-ray_diffraction_profile_pi_units_to_degrees", 0.000277777805) self.send("xrayserver_data", exchange_data) except urllib.error.HTTPError as e: self.x0h_output.setHtml( 'The server couldn\'t fulfill the request.\nError Code: ' + str(e.code) + "\n\n" + server.BaseHTTPRequestHandler.responses[e.code][1]) except urllib.error.URLError as e: self.x0h_output.setHtml('We failed to reach a server.\nReason: ' + e.reason) except XrayServerException as e: ShowHtmlDialog.show_html("X-ray Server Error", e.response, width=750, height=500, parent=self) except Exception as e: self.x0h_output.setHtml('We failed to reach a server.\nReason: ' + str(e)) self.tabs_widget.setCurrentIndex(0) self.setStatusMessage("") self.progressBarFinished()
def xoppy_calc_xcrystal(self): CRYSTAL_MATERIAL = self.CRYSTAL_MATERIAL MILLER_INDEX_H = self.MILLER_INDEX_H MILLER_INDEX_K = self.MILLER_INDEX_K MILLER_INDEX_L = self.MILLER_INDEX_L TEMPER = self.TEMPER MOSAIC = self.MOSAIC GEOMETRY = self.GEOMETRY SCAN = self.SCAN UNIT = self.UNIT SCANFROM = self.SCANFROM SCANTO = self.SCANTO SCANPOINTS = self.SCANPOINTS ENERGY = self.ENERGY ASYMMETRY_ANGLE = self.ASYMMETRY_ANGLE THICKNESS = self.THICKNESS MOSAIC_FWHM = self.MOSAIC_FWHM RSAG = self.RSAG RMER = self.RMER ANISOTROPY = self.ANISOTROPY POISSON = self.POISSON CUT = self.CUT FILECOMPLIANCE = self.FILECOMPLIANCE for file in ["diff_pat.dat","diff_pat.gle","diff_pat.par","diff_pat.xop","xcrystal.bra"]: try: os.remove(os.path.join(locations.home_bin_run(),file)) except: pass if (GEOMETRY == 1) or (GEOMETRY == 3): if ASYMMETRY_ANGLE == 0.0: print("xoppy_calc_xcrystal: WARNING: In xcrystal the asymmetry angle is the angle between Bragg planes and crystal surface,"+ "in BOTH Bragg and Laue geometries.") descriptor = Crystal_GetCrystalsList()[CRYSTAL_MATERIAL] if SCAN == 3: # energy scan emin = SCANFROM - 1 emax = SCANTO + 1 else: emin = ENERGY - 100.0 emax = ENERGY + 100.0 print("Using crystal descriptor: ",descriptor) bragg_dictionary = bragg_calc(descriptor=descriptor, hh=MILLER_INDEX_H,kk=MILLER_INDEX_K,ll=MILLER_INDEX_L, temper=float(TEMPER), emin=emin,emax=emax,estep=5.0,fileout="xcrystal.bra") with open("xoppy.inp", "wt") as f: f.write("xcrystal.bra\n") f.write("%d\n"%MOSAIC) f.write("%d\n"%GEOMETRY) if MOSAIC == 1: f.write("%g\n"%MOSAIC_FWHM) f.write("%g\n"%THICKNESS) else: f.write("%g\n"%THICKNESS) f.write("%g\n"%ASYMMETRY_ANGLE) scan_flag = 1 + SCAN f.write("%d\n"%scan_flag) f.write("%19.9f\n"%ENERGY) if scan_flag <= 3: f.write("%d\n"%UNIT) f.write("%g\n"%SCANFROM) f.write("%g\n"%SCANTO) f.write("%d\n"%SCANPOINTS) if MOSAIC > 1: # bent f.write("%g\n"%RSAG) f.write("%g\n"%RMER) f.write("0\n") if ( (descriptor == "Si") or (descriptor == "Si2") or (descriptor == "Si_NIST") or (descriptor == "Ge") or descriptor == "Diamond"): pass else: # not Si,Ge,Diamond if ((ANISOTROPY == 1) or (ANISOTROPY == 2)): raise Exception("Anisotropy data not available for this crystal. Either use isotropic or use external compliance file. Please change and run again'") f.write("%d\n"%ANISOTROPY) if ANISOTROPY == 0: f.write("%g\n"%POISSON) elif ANISOTROPY == 1: f.write("%d\n"%CRYSTAL_MATERIAL) f.write("%g\n"%ASYMMETRY_ANGLE) f.write("%d\n"%MILLER_INDEX_H) f.write("%d\n"%MILLER_INDEX_K) f.write("%d\n"%MILLER_INDEX_L) elif ANISOTROPY == 2: f.write("%d\n"%CRYSTAL_MATERIAL) f.write("%g\n"%ASYMMETRY_ANGLE) # TODO: check syntax for CUT: Cut syntax is: valong_X valong_Y valong_Z ; vnorm_X vnorm_Y vnorm_Z ; vperp_x vperp_Y vperp_Z f.write("%s\n"%CUT.split(";")[0]) f.write("%s\n"%CUT.split(";")[1]) f.write("%s\n"%CUT.split(";")[2]) elif ANISOTROPY == 3: f.write("%s\n"%FILECOMPLIANCE) command = os.path.join(locations.home_bin(), 'diff_pat') + " < xoppy.inp" print("Running command '%s' in directory: %s "%(command, locations.home_bin_run())) print("\n--------------------------------------------------------\n") os.system(command) print("\n--------------------------------------------------------\n") #show calculated parameters in standard output txt_info = open("diff_pat.par").read() for line in txt_info: print(line,end="") calculated_data = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name()) try: calculated_data.add_content("xoppy_data", numpy.loadtxt("diff_pat.dat", skiprows=5)) calculated_data.add_content("plot_x_col",0) calculated_data.add_content("plot_y_col",-1) calculated_data.add_content("units_to_degrees", self.get_units_to_degrees()) except Exception as e: raise Exception("Error loading diff_pat.dat :" + str(e)) try: calculated_data.add_content("labels", ["Th-ThB{in} [" + self.unit_combo.itemText(self.UNIT) + "]", "Th-ThB{out} [" + self.unit_combo.itemText(self.UNIT) + "]", "phase_p[rad]", "phase_s[rad]","Circ Polariz", "p-polarized reflectivity", "s-polarized reflectivity"]) except: pass try: with open("diff_pat.par") as f: info = f.readlines() calculated_data.add_content("info",info) except: pass return calculated_data
# create unulator_radiation xoppy exchange data from orangecontrib.xoppy.util.xoppy_undulators import xoppy_calc_undulator_radiation from oasys.widgets.exchange import DataExchangeObject e, h, v, p, code = xoppy_calc_undulator_radiation(ELECTRONENERGY=6.04,ELECTRONENERGYSPREAD=0.001,ELECTRONCURRENT=0.2,\ ELECTRONBEAMSIZEH=0.000395,ELECTRONBEAMSIZEV=9.9e-06,\ ELECTRONBEAMDIVERGENCEH=1.05e-05,ELECTRONBEAMDIVERGENCEV=3.9e-06,\ PERIODID=0.018,NPERIODS=222,KV=1.68,DISTANCE=30.0, SETRESONANCE=0,HARMONICNUMBER=1, GAPH=0.001,GAPV=0.001,\ HSLITPOINTS=41,VSLITPOINTS=41,METHOD=2, PHOTONENERGYMIN=7000,PHOTONENERGYMAX=8100,PHOTONENERGYPOINTS=20, USEEMITTANCES=1) # received_data = DataExchangeObject("XOPPY", "UNDULATOR_RADIATION") received_data = DataExchangeObject("XOPPY", "POWER3D") received_data.add_content("xoppy_data", [p, e, h, v]) received_data.add_content("xoppy_code", code) # app = QApplication(sys.argv) w = OWpower3D() w.acceptExchangeData(received_data) w.show() app.exec() w.saveSettings()
def submit(self): self.progressBarInit() self.setStatusMessage("Submitting Request") if platform.system() == 'Darwin': self.x0h_input.page().toHtml(self._callable_1) elif platform.system() == 'Linux': doc = self.x0h_input.page().mainFrame().documentElement() submit_btn = doc.findFirst("input[id=submit-btn]") try: response = "" #response = HttpManager.send_xray_server_request_POST(APPLICATION, parameters) response = self.clear_response(response) self.tabs_widget.setCurrentIndex(0) self.x0h_output.setHtml(response) data0, data1, data2 = self.extract_plots(response) exchange_data = DataExchangeObject("XRAYSERVER", "X0H") exchange_data.add_content("reflectivity", data0) exchange_data.add_content("reflectivity_units_to_degrees", 1.0) exchange_data.add_content("x-ray_diffraction_profile_sigma", data1) exchange_data.add_content("x-ray_diffraction_profile_sigma_units_to_degrees", 0.000277777805) exchange_data.add_content("x-ray_diffraction_profile_pi", data2) exchange_data.add_content("x-ray_diffraction_profile_pi_units_to_degrees", 0.000277777805) self.send("xrayserver_data", exchange_data) pass except urllib.error.HTTPError as e: self.x0h_output.setHtml('The server couldn\'t fulfill the request.\nError Code: ' + str(e.code) + "\n\n" + server.BaseHTTPRequestHandler.responses[e.code][1]) raise e except urllib.error.URLError as e: self.x0h_output.setHtml('We failed to reach a server.\nReason: ' + e.reason) raise e except XrayServerException as e: ShowHtmlDialog.show_html("X-ray Server Error", e.response, width=750, height=500, parent=self) raise e except Exception as e: self.x0h_output.setHtml('We failed to reach a server.\nReason: ' + str(e)) raise e self.setStatusMessage("") self.progressBarFinished()
def xoppy_calc_xpowder_fml(self): for file in ["xpowder_fml.par", "xpowder_fml.ref", "xpowder_fml.out"]: try: os.remove(os.path.join(locations.home_bin_run(), file)) except: pass with open("xoppy.inp", "wt") as f: f.write("%s\n" % (self.FILE)) f.write("%s\n" % (self.TITLE)) f.write("%g\n" % (self.LAMBDA)) f.write("%s\n" % (self.JOB)) f.write("%g\n" % (self.U)) f.write("%g\n" % (self.V)) f.write("%g\n" % (self.W)) f.write("%g\n" % (self.X)) f.write("%g\n" % (self.LS)) f.write("%g\n" % (self.THMIN)) f.write("%g\n" % (self.STEP)) f.write("%s\n" % (self.THMAX)) command = "'" + os.path.join(locations.home_bin(), 'xpowder_fml') + "' < xoppy.inp" print("Running command '%s' in directory: %s " % (command, locations.home_bin_run())) print("\n--------------------------------------------------------\n") os.system(command) print("\n--------------------------------------------------------\n") print( "Files written to disk:\n xpowder_fml.par (text output)\n xpowder_fml.ref (reflections)\n xpowder_fml.out (diffractogram)", ) # # data = numpy.loadtxt("xpowder_fml.out",skiprows=3).T #send exchange calculated_data = DataExchangeObject( "XOPPY", self.get_data_exchange_widget_name()) try: calculated_data.add_content( "xoppy_data", numpy.loadtxt("xpowder_fml.out", skiprows=3)) calculated_data.add_content("plot_x_col", 0) calculated_data.add_content("plot_y_col", -1) except: pass try: calculated_data.add_content("labels", ["TwoTheta[Deg]", "Intensity[a.u.]"]) except: pass try: with open("xpowder_fml.par") as f: info = f.readlines() info = [line[:-1] for line in info] # remove "\n" calculated_data.add_content("info", info) except: pass return calculated_data
def xoppy_calc_xf1f2(self): MAT_FLAG = self.MAT_FLAG DESCRIPTOR = self.DESCRIPTOR density = self.DENSITY CALCULATE = self.CALCULATE GRID = self.GRID GRIDSTART = self.GRIDSTART GRIDEND = self.GRIDEND GRIDN = self.GRIDN THETAGRID = self.THETAGRID ROUGH = self.ROUGH THETA1 = self.THETA1 THETA2 = self.THETA2 THETAN = self.THETAN if MAT_FLAG == 0: # element descriptor = DESCRIPTOR density = xraylib.ElementDensity(xraylib.SymbolToAtomicNumber(DESCRIPTOR)) elif MAT_FLAG == 1: # formula descriptor = DESCRIPTOR if GRID == 0: # standard energy grid energy = numpy.arange(0,500) elefactor = numpy.log10(10000.0 / 30.0) / 300.0 energy = 10.0 * 10**(energy * elefactor) elif GRID == 1: # user energy grid if GRIDN == 1: energy = numpy.array([GRIDSTART]) else: energy = numpy.linspace(GRIDSTART,GRIDEND,GRIDN) elif GRID == 2: # single energy point energy = numpy.array([GRIDSTART]) if THETAGRID == 0: theta = numpy.array([THETA1]) else: theta = numpy.linspace(THETA1,THETA2,THETAN) CALCULATE_items=['f1', 'f2', 'delta', 'beta', 'mu [cm^-1]', 'mu [cm^2/g]', 'Cross Section [barn]', 'reflectivity-s', 'reflectivity-p', 'reflectivity-unpol', 'delta/beta '] out = numpy.zeros((energy.size,theta.size)) for i,itheta in enumerate(theta): if MAT_FLAG == 0: # element tmp = f1f2_calc(descriptor,energy,1e-3*itheta,F=1+CALCULATE,rough=ROUGH,density=density) out[:,i] = tmp else: tmp = f1f2_calc_mix(descriptor,energy,1e-3*itheta,F=1+CALCULATE,rough=ROUGH,density=density) out[:,i] = tmp if ((energy.size == 1) and (theta.size == 1)): info = "** Single value calculation E=%g eV, theta=%g mrad, Result(F=%d)=%g "%(energy[0],theta[0],1+CALCULATE,out[0,0]) labels = ["Energy [eV]",CALCULATE_items[CALCULATE]] tmp = numpy.vstack((energy,out[:,0])) print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>",energy.shape,out.shape,tmp.shape) out_dict = {"application":"xoppy","name":"xf12","info":info, "data":tmp,"labels":labels} elif theta.size == 1: tmp = numpy.vstack((energy,out[:,0])) labels = ["Energy [eV]",CALCULATE_items[CALCULATE]] out_dict = {"application":"xoppy","name":"xf12","data":tmp,"labels":labels} elif energy.size == 1: tmp = numpy.vstack((theta,out[0,:])) labels = ["Theta [mrad]",CALCULATE_items[CALCULATE]] out_dict = {"application":"xoppy","name":"xf12","data":tmp,"labels":labels} else: labels = [r"energy[eV]",r"theta [mrad]"] out_dict = {"application":"xoppy","name":"xf12","data2D":out,"dataX":energy,"dataY":theta,"labels":labels} # # # if "info" in out_dict.keys(): print(out_dict["info"]) #send exchange calculated_data = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name()) try: calculated_data.add_content("xoppy_data", out_dict["data"].T) calculated_data.add_content("plot_x_col", 0) calculated_data.add_content("plot_y_col", -1) except: pass try: calculated_data.add_content("labels", out_dict["labels"]) except: pass try: calculated_data.add_content("info", out_dict["info"]) except: pass try: calculated_data.add_content("data2D", out_dict["data2D"]) calculated_data.add_content("dataX", out_dict["dataX"]) calculated_data.add_content("dataY", out_dict["dataY"]) except: pass return calculated_data
def xoppy_calc_xpower(self): # # prepare input for xpower_calc # Note that the input for xpower_calc accepts any number of elements. # substance = [self.EL1_FOR,self.EL2_FOR,self.EL3_FOR,self.EL4_FOR,self.EL5_FOR] thick = numpy.array( (self.EL1_THI,self.EL2_THI,self.EL3_THI,self.EL4_THI,self.EL5_THI)) angle = numpy.array( (self.EL1_ANG,self.EL2_ANG,self.EL3_ANG,self.EL4_ANG,self.EL5_ANG)) dens = [self.EL1_DEN,self.EL2_DEN,self.EL3_DEN,self.EL4_DEN,self.EL5_DEN] roughness = numpy.array( (self.EL1_ROU,self.EL2_ROU,self.EL3_ROU,self.EL4_ROU,self.EL5_ROU)) flags = numpy.array( (self.EL1_FLAG,self.EL2_FLAG,self.EL3_FLAG,self.EL4_FLAG,self.EL5_FLAG)) substance = substance[0:self.NELEMENTS+1] thick = thick[0:self.NELEMENTS+1] angle = angle[0:self.NELEMENTS+1] dens = dens[0:self.NELEMENTS+1] roughness = roughness[0:self.NELEMENTS+1] flags = flags[0:self.NELEMENTS+1] if self.SOURCE == 0: energies = numpy.arange(0,500) elefactor = numpy.log10(10000.0 / 30.0) / 300.0 energies = 10.0 * 10**(energies * elefactor) source = numpy.ones(energies.size) tmp = numpy.vstack( (energies,source)) if self.SOURCE == 1: energies = numpy.linspace(self.ENER_MIN,self.ENER_MAX,self.ENER_N) source = numpy.ones(energies.size) tmp = numpy.vstack( (energies,source)) if self.SOURCE >= 2: if self.SOURCE == 2: source_file = self.SOURCE_FILE if self.SOURCE == 3: source_file = "SRCOMPE" if self.SOURCE == 4: source_file = "SRCOMPF" try: tmp = numpy.loadtxt(source_file) energies = tmp[:,0] source = tmp[:,1] except: print("Error loading file %s "%(source_file)) raise if self.FILE_DUMP == 0: output_file = None else: output_file = "xpower.spec" out_dictionary = xpower_calc(energies=energies,source=source,substance=substance, flags=flags,dens=dens,thick=thick,angle=angle,roughness=roughness,output_file=output_file) try: print(out_dictionary["info"]) except: pass #send exchange calculated_data = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name()) try: calculated_data.add_content("xoppy_data", out_dictionary["data"].T) calculated_data.add_content("plot_x_col",0) calculated_data.add_content("plot_y_col",-1) except: pass try: print(out_dictionary["labels"]) calculated_data.add_content("labels", out_dictionary["labels"]) except: pass try: calculated_data.add_content("info",out_dictionary["info"]) except: pass return calculated_data
def do_xoppy_calculation(self): out_dict = self.xoppy_calc_xf0() if "info" in out_dict.keys(): print(out_dict["info"]) calculated_data = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name()) try: calculated_data.add_content("xoppy_data", out_dict["data"].T) calculated_data.add_content("plot_x_col",0) calculated_data.add_content("plot_y_col",-1) except: pass try: calculated_data.add_content("labels",out_dict["labels"]) except: pass try: calculated_data.add_content("info",out_dict["info"]) except: pass return calculated_data
def xoppy_calc_xtc(self): for file in ["tc.inp", "tc.out"]: try: os.remove(os.path.join(locations.home_bin_run(), file)) except: pass with open("tc.inp", "wt") as f: f.write("TS called from xoppy\n") f.write("%10.3f %10.2f %10.6f %s\n" % (self.ENERGY, self.CURRENT, self.ENERGY_SPREAD, "Ring-Energy(GeV) Current(mA) Beam-Energy-Spread")) f.write("%10.4f %10.4f %10.4f %10.4f %s\n" % (self.SIGX, self.SIGY, self.SIGX1, self.SIGY1, "Sx(mm) Sy(mm) Sx1(mrad) Sy1(mrad)")) f.write("%10.3f %d %s\n" % (self.PERIOD, self.NP, "Period(cm) N")) f.write("%10.1f %10.1f %d %s\n" % (self.EMIN, self.EMAX, self.N, "Emin Emax Ne")) f.write("%d %d %d %s\n" % (self.HARMONIC_FROM, self.HARMONIC_TO, self.HARMONIC_STEP, "Hmin Hmax Hstep")) f.write("%d %d %d %d %s\n" % (self.HELICAL, self.METHOD, 1, self.NEKS, "Helical Method Print_K Neks")) f.write("foreground\n") if platform.system() == "Windows": command = os.path.join(locations.home_bin(), 'tc.exe') else: command = "'" + os.path.join(locations.home_bin(), 'tc') + "'" print("Running command '%s' in directory: %s " % (command, locations.home_bin_run())) print("\n--------------------------------------------------------\n") os.system(command) print("Output file: %s" % ("tc.out")) print("\n--------------------------------------------------------\n") # # parse result files to exchange object # with open("tc.out", "r") as f: lines = f.readlines() # print output file # for line in lines: # print(line, end="") # remove returns lines = [line[:-1] for line in lines] harmonics_data = [] # separate numerical data from text floatlist = [] harmoniclist = [] txtlist = [] for line in lines: try: tmp = line.strip() if tmp.startswith("Harmonic"): harmonic_number = int(tmp.split("Harmonic")[1].strip()) if harmonic_number != self.HARMONIC_FROM: harmonics_data[-1][1] = harmoniclist harmoniclist = [] harmonics_data.append([harmonic_number, None]) tmp = float(line.strip()[0]) floatlist.append(line) harmoniclist.append(line) except: txtlist.append(line) harmonics_data[-1][1] = harmoniclist data = numpy.loadtxt(floatlist) for index in range(0, len(harmonics_data)): # print (harmonics_data[index][0], harmonics_data[index][1]) harmonics_data[index][1] = numpy.loadtxt(harmonics_data[index][1]) #send exchange calculated_data = DataExchangeObject( "XOPPY", self.get_data_exchange_widget_name()) try: calculated_data.add_content("xoppy_data", data) calculated_data.add_content("xoppy_data_harmonics", harmonics_data) calculated_data.add_content("plot_x_col", 1) calculated_data.add_content("plot_y_col", 2) except: pass try: calculated_data.add_content("labels", [ "Energy (eV) without emittance", "Energy (eV) with emittance", "Brilliance (ph/s/mrad^2/mm^2/0.1%bw)", "Ky", "Total Power (W)", "Power density (W/mr^2)" ]) except: pass try: calculated_data.add_content("info", txtlist) except: pass return calculated_data
if __name__ == "__main__": # create unulator_radiation xoppy exchange data from orangecontrib.xoppy.util.xoppy_undulators import xoppy_calc_undulator_radiation from oasys.widgets.exchange import DataExchangeObject e, h, v, p, code = xoppy_calc_undulator_radiation(ELECTRONENERGY=6.04,ELECTRONENERGYSPREAD=0.001,ELECTRONCURRENT=0.2,\ ELECTRONBEAMSIZEH=0.000395,ELECTRONBEAMSIZEV=9.9e-06,\ ELECTRONBEAMDIVERGENCEH=1.05e-05,ELECTRONBEAMDIVERGENCEV=3.9e-06,\ PERIODID=0.018,NPERIODS=222,KV=1.68,DISTANCE=30.0, SETRESONANCE=0,HARMONICNUMBER=1, GAPH=0.001,GAPV=0.001,\ HSLITPOINTS=41,VSLITPOINTS=41,METHOD=2, PHOTONENERGYMIN=7000,PHOTONENERGYMAX=8100,PHOTONENERGYPOINTS=20, USEEMITTANCES=1) # received_data = DataExchangeObject("XOPPY", "UNDULATOR_RADIATION") received_data = DataExchangeObject("XOPPY", "POWER3D") received_data.add_content("xoppy_data", [p, e, h, v]) received_data.add_content("xoppy_code", code) # app = QApplication(sys.argv) w = OWpower3D() w.acceptExchangeData(received_data) w.show() app.exec() w.saveSettings()
def submit(self): self.progressBarInit() self.setStatusMessage("Submitting Request") if platform.system() == 'Darwin': self.x0h_input.page().toHtml(self._callable_1) elif platform.system() == 'Linux': doc = self.x0h_input.page().mainFrame().documentElement() submit_btn = doc.findFirst("input[id=submit-btn]") try: response = "" #response = HttpManager.send_xray_server_request_POST(APPLICATION, parameters) response = self.clear_response(response) self.tabs_widget.setCurrentIndex(0) self.x0h_output.setHtml(response) data0, data1, data2 = self.extract_plots(response) exchange_data = DataExchangeObject("XRAYSERVER", "X0H") exchange_data.add_content("reflectivity", data0) exchange_data.add_content("reflectivity_units_to_degrees", 1.0) exchange_data.add_content("x-ray_diffraction_profile_sigma", data1) exchange_data.add_content( "x-ray_diffraction_profile_sigma_units_to_degrees", 0.000277777805) exchange_data.add_content("x-ray_diffraction_profile_pi", data2) exchange_data.add_content( "x-ray_diffraction_profile_pi_units_to_degrees", 0.000277777805) self.send("xrayserver_data", exchange_data) pass except urllib.error.HTTPError as e: self.x0h_output.setHtml( 'The server couldn\'t fulfill the request.\nError Code: ' + str(e.code) + "\n\n" + server.BaseHTTPRequestHandler.responses[e.code][1]) raise e except urllib.error.URLError as e: self.x0h_output.setHtml( 'We failed to reach a server.\nReason: ' + e.reason) raise e except XrayServerException as e: ShowHtmlDialog.show_html("X-ray Server Error", e.response, width=750, height=500, parent=self) raise e except Exception as e: self.x0h_output.setHtml( 'We failed to reach a server.\nReason: ' + str(e)) raise e self.setStatusMessage("") self.progressBarFinished()
def xoppy_calc_xfh(self): #TODO: remove I_ABSORP ILATTICE = self.ILATTICE HMILLER = self.HMILLER KMILLER = self.KMILLER LMILLER = self.LMILLER I_PLOT = self.I_PLOT TEMPER = self.TEMPER ENERGY = self.ENERGY ENERGY_END = self.ENERGY_END NPOINTS = self.NPOINTS descriptor = Crystal_GetCrystalsList()[ILATTICE] print("Using crystal descriptor: ",descriptor) bragg_dictionary = bragg_calc(descriptor=descriptor,hh=HMILLER,kk=KMILLER,ll=LMILLER,temper=TEMPER, emin=ENERGY,emax=ENERGY_END,estep=50.0,fileout="/dev/null") energy = numpy.linspace(ENERGY,ENERGY_END,NPOINTS) out = numpy.zeros((25,NPOINTS)) info = "" for i,ienergy in enumerate(energy): dic2 = crystal_fh(bragg_dictionary,ienergy) print("Energy=%g eV FH=(%g,%g)"%(ienergy,dic2["STRUCT"].real,dic2["STRUCT"].imag)) out[0,i] = ienergy out[1,i] = dic2["WAVELENGTH"]*1e10 out[2,i] = dic2["THETA"]*180/numpy.pi out[3,i] = dic2["F_0"].real out[4,i] = dic2["F_0"].imag out[5,i] = dic2["FH"].real out[6,i] = dic2["FH"].imag out[7,i] = dic2["FH_BAR"].real out[8,i] = dic2["FH_BAR"].imag out[9,i] = dic2["psi_0"].real out[10,i] = dic2["psi_0"].imag out[11,i] = dic2["psi_h"].real out[12,i] = dic2["psi_h"].imag out[13,i] = dic2["psi_hbar"].real out[14,i] = dic2["psi_hbar"].imag out[15,i] = dic2["STRUCT"].real out[16,i] = dic2["STRUCT"].imag out[17,i] = dic2["DELTA_REF"] out[18,i] = dic2["REFRAC"].real out[19,i] = dic2["REFRAC"].imag out[20,i] = dic2["ABSORP"] out[21,i] = 1e6 * dic2["ssr"] # in microrads out[22,i] = 1e6 * dic2["spr"] # in microrads out[23,i] = dic2["RATIO"] out[24,i] = dic2["psi_over_f"] info += "#\n#\n#\n" info += dic2["info"] #send exchange calculated_data = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name()) try: calculated_data.add_content("xoppy_data", out.T) calculated_data.add_content("plot_x_col",0) calculated_data.add_content("plot_y_col", I_PLOT) except: pass try: calculated_data.add_content("labels",self.plotOptionList()) except: pass try: calculated_data.add_content("info",info) except: pass return calculated_data
if __name__ == "__main__": from oasys.widgets.exchange import DataExchangeObject input_data_type = "POWER" if input_data_type == "POWER": # create fake UNDULATOR_FLUX xoppy exchange data e = numpy.linspace(1000.0, 10000.0, 100) source = e/10 received_data = DataExchangeObject("XOPPY", "POWER") received_data.add_content("xoppy_data", numpy.vstack((e,e,source)).T) received_data.add_content("xoppy_code", "US") elif input_data_type == "POWER3D": # create unulator_radiation xoppy exchange data from orangecontrib.xoppy.util.xoppy_undulators import xoppy_calc_undulator_radiation e, h, v, p, code = xoppy_calc_undulator_radiation(ELECTRONENERGY=6.04,ELECTRONENERGYSPREAD=0.001,ELECTRONCURRENT=0.2,\ ELECTRONBEAMSIZEH=0.000395,ELECTRONBEAMSIZEV=9.9e-06,\ ELECTRONBEAMDIVERGENCEH=1.05e-05,ELECTRONBEAMDIVERGENCEV=3.9e-06,\ PERIODID=0.018,NPERIODS=222,KV=1.68,DISTANCE=30.0, SETRESONANCE=0,HARMONICNUMBER=1, GAPH=0.001,GAPV=0.001,\ HSLITPOINTS=41,VSLITPOINTS=41,METHOD=0, PHOTONENERGYMIN=7000,PHOTONENERGYMAX=8100,PHOTONENERGYPOINTS=20,
def xoppy_calc_xpowder_fml(self): for file in ["xpowder_fml.par","xpowder_fml.ref","xpowder_fml.out"]: try: os.remove(os.path.join(locations.home_bin_run(),file)) except: pass with open("xoppy.inp", "wt") as f: f.write("%s\n"% (self.FILE)) f.write("%s\n"%(self.TITLE)) f.write("%g\n"%(self.LAMBDA)) f.write("%s\n"%(self.JOB)) f.write("%g\n"%(self.U)) f.write("%g\n"%(self.V)) f.write("%g\n"%(self.W)) f.write("%g\n"%(self.X)) f.write("%g\n"%(self.LS)) f.write("%g\n"%(self.THMIN)) f.write("%g\n"%(self.STEP)) f.write("%s\n"%(self.THMAX)) if platform.system() == "Windows": command = os.path.join(locations.home_bin(),'xpowder_fml.exe < xoppy.inp') else: command = "'" + os.path.join(locations.home_bin(), 'xpowder_fml') + "' < xoppy.inp" print("Running command '%s' in directory: %s "%(command, locations.home_bin_run())) print("\n--------------------------------------------------------\n") os.system(command) print("\n--------------------------------------------------------\n") print("Files written to disk:\n xpowder_fml.par (text output)\n xpowder_fml.ref (reflections)\n xpowder_fml.out (diffractogram)",) # # data = numpy.loadtxt("xpowder_fml.out",skiprows=3).T #send exchange calculated_data = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name()) try: calculated_data.add_content("xoppy_data", numpy.loadtxt("xpowder_fml.out", skiprows=3)) calculated_data.add_content("plot_x_col",0) calculated_data.add_content("plot_y_col",-1) except: pass try: calculated_data.add_content("labels",["TwoTheta[Deg]","Intensity[a.u.]"]) except: pass try: with open("xpowder_fml.par") as f: info = f.readlines() info = [line[:-1] for line in info] # remove "\n" calculated_data.add_content("info",info) except: pass return calculated_data
def xoppy_calc_mlayer(self): # copy the variable locally, so no more use of self. MODE = self.MODE SCAN = self.SCAN F12_FLAG = self.F12_FLAG SUBSTRATE = self.SUBSTRATE ODD_MATERIAL = self.ODD_MATERIAL EVEN_MATERIAL = self.EVEN_MATERIAL ENERGY = self.ENERGY THETA = self.THETA SCAN_STEP = self.SCAN_STEP NPOINTS = self.NPOINTS ODD_THICKNESS = self.ODD_THICKNESS EVEN_THICKNESS = self.EVEN_THICKNESS NLAYERS = self.NLAYERS FILE = self.FILE for file in ["mlayer.inp", "mlayer.par", "mlayer.f12"]: try: os.remove(os.path.join(locations.home_bin_run(), file)) except: pass # # write input file for Fortran mlayer: mlayer.inp # f = open('mlayer.inp', 'w') if SCAN == 0 and MODE == 0: a0 = 1 if SCAN == 1 and MODE == 0: a0 = 2 if SCAN == 0 and MODE == 1: a0 = 3 if SCAN == 1 and MODE == 1: a0 = 4 f.write("%d \n" % a0) f.write("N\n") f.write("%g\n" % (codata.h * codata.c / codata.e * 1e10 / ENERGY)) f.write("%g\n" % THETA) # if SCAN == 0: f.write("%g\n" % SCAN_STEP) a2 = codata.h * codata.c / codata.e * 1e10 / ENERGY a3 = codata.h * codata.c / codata.e * 1e10 / (ENERGY + SCAN_STEP) a4 = a3 - a2 if SCAN != 0: f.write("%g\n" % a4) # f.write("%d\n" % NPOINTS) if MODE == 0: f.write("%d\n" % NLAYERS) if MODE == 0: if a0 != 5: f.write("%g %g \n" % (ODD_THICKNESS, EVEN_THICKNESS)) else: for i in range(NLAYERS): f.write("%g %g \n" % (ODD_THICKNESS, EVEN_THICKNESS)) if MODE != 0: f1 = open(FILE, 'r') a5 = f1.read() f1.close() if MODE != 0: print("Number of layers in %s file is %d " % (FILE, NLAYERS)) f.write("%d\n" % NLAYERS) f.write(a5) f.write("mlayer.par\n") f.write("mlayer.dat\n") f.write("6\n") f.close() print('File written to disk: mlayer.inp') # # create f12 file # if F12_FLAG == 0: energy = numpy.arange(0, 500) elefactor = numpy.log10(10000.0 / 30.0) / 300.0 energy = 10.0 * 10**(energy * elefactor) f12_s = f1f2_calc(SUBSTRATE, energy) f12_e = f1f2_calc(EVEN_MATERIAL, energy) f12_o = f1f2_calc(ODD_MATERIAL, energy) f = open("mlayer.f12", 'w') f.write( '; File created by xoppy for materials [substrate=%s,even=%s,odd=%s]: \n' % (SUBSTRATE, EVEN_MATERIAL, ODD_MATERIAL)) f.write('; Atomic masses: \n') f.write( "%g %g %g \n" % (xraylib.AtomicWeight(xraylib.SymbolToAtomicNumber(SUBSTRATE)), xraylib.AtomicWeight( xraylib.SymbolToAtomicNumber(EVEN_MATERIAL)), xraylib.AtomicWeight( xraylib.SymbolToAtomicNumber(ODD_MATERIAL)))) f.write('; Densities: \n') f.write("%g %g %g \n" % (xraylib.ElementDensity( xraylib.SymbolToAtomicNumber(SUBSTRATE)), xraylib.ElementDensity( xraylib.SymbolToAtomicNumber(EVEN_MATERIAL)), xraylib.ElementDensity( xraylib.SymbolToAtomicNumber(ODD_MATERIAL)))) f.write('; Number of energy points: \n') f.write("%d\n" % (energy.size)) f.write( '; For each energy point, energy[eV], f1[substrate], f2[substrate], f1[even], f2[even], f1[odd], f2[odd]: \n' ) for i in range(energy.size): f.write("%g %g %g %g %g %g %g \n" % (energy[i], f12_s[0, i], f12_s[1, i], f12_e[0, i], f12_e[1, i], f12_o[0, i], f12_o[1, i])) f.close() print('File written to disk: mlayer.f12') # # run external program mlayer # if platform.system() == "Windows": command = os.path.join(locations.home_bin(), 'mlayer.exe < mlayer.inp') else: command = "'" + os.path.join(locations.home_bin(), 'mlayer') + "' < mlayer.inp" print("Running command '%s' in directory: %s " % (command, locations.home_bin_run())) print("\n--------------------------------------------------------\n") os.system(command) print("\n--------------------------------------------------------\n") #send exchange calculated_data = DataExchangeObject( "XOPPY", self.get_data_exchange_widget_name()) try: if SCAN == 0: calculated_data.add_content("xoppy_data", numpy.loadtxt("mlayer.dat")) calculated_data.add_content("plot_x_col", 0) calculated_data.add_content("plot_y_col", 3) elif SCAN == 1: # internal scan is in wavelength. Add a column with energy aa = numpy.loadtxt("mlayer.dat") photon_energy = (codata.h * codata.c / codata.e * 1e10) / aa[:, 0] bb = numpy.zeros((aa.shape[0], 1 + aa.shape[1])) bb[:, 0] = photon_energy bb[:, 1:] = aa calculated_data.add_content("xoppy_data", bb) calculated_data.add_content("plot_x_col", 0) calculated_data.add_content("plot_y_col", 4) calculated_data.add_content("units_to_degrees", 1.0) except: pass try: info = "ML %s(%3.2f A):%s(%3.2f A) %d pairs; E=%5.3f eV" % ( ODD_MATERIAL, ODD_THICKNESS, EVEN_MATERIAL, EVEN_THICKNESS, NLAYERS, ENERGY) calculated_data.add_content("info", info) except: pass return calculated_data
def xoppy_calc_xpower(self): # # prepare input for xpower_calc # Note that the input for xpower_calc accepts any number of elements. # substance = [self.EL1_FOR,self.EL2_FOR,self.EL3_FOR,self.EL4_FOR,self.EL5_FOR] thick = numpy.array( (self.EL1_THI,self.EL2_THI,self.EL3_THI,self.EL4_THI,self.EL5_THI)) angle = numpy.array( (self.EL1_ANG,self.EL2_ANG,self.EL3_ANG,self.EL4_ANG,self.EL5_ANG)) dens = [self.EL1_DEN,self.EL2_DEN,self.EL3_DEN,self.EL4_DEN,self.EL5_DEN] roughness = numpy.array( (self.EL1_ROU,self.EL2_ROU,self.EL3_ROU,self.EL4_ROU,self.EL5_ROU)) flags = numpy.array( (self.EL1_FLAG,self.EL2_FLAG,self.EL3_FLAG,self.EL4_FLAG,self.EL5_FLAG)) substance = substance[0:self.NELEMENTS+1] thick = thick[0:self.NELEMENTS+1] angle = angle[0:self.NELEMENTS+1] dens = dens[0:self.NELEMENTS+1] roughness = roughness[0:self.NELEMENTS+1] flags = flags[0:self.NELEMENTS+1] if self.SOURCE == 0: # energies = numpy.arange(0,500) # elefactor = numpy.log10(10000.0 / 30.0) / 300.0 # energies = 10.0 * 10**(energies * elefactor) # source = numpy.ones(energies.size) # tmp = numpy.vstack( (energies,source)) if self.input_spectrum is None: raise Exception("No input beam") else: energies = self.input_spectrum[0,:].copy() source = self.input_spectrum[1,:].copy() elif self.SOURCE == 1: energies = numpy.linspace(self.ENER_MIN,self.ENER_MAX,self.ENER_N) source = numpy.ones(energies.size) tmp = numpy.vstack( (energies,source)) self.input_spectrum = source elif self.SOURCE == 2: if self.SOURCE == 2: source_file = self.SOURCE_FILE # if self.SOURCE == 3: source_file = "SRCOMPE" # if self.SOURCE == 4: source_file = "SRCOMPF" try: tmp = numpy.loadtxt(source_file) energies = tmp[:,0] source = tmp[:,1] self.input_spectrum = source except: print("Error loading file %s "%(source_file)) raise if self.FILE_DUMP == 0: output_file = None else: output_file = "power.spec" out_dictionary = xpower_calc(energies=energies,source=source,substance=substance, flags=flags,dens=dens,thick=thick,angle=angle,roughness=roughness,output_file=output_file) try: print(out_dictionary["info"]) except: pass #send exchange calculated_data = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name()) try: calculated_data.add_content("xoppy_data", out_dictionary["data"].T) calculated_data.add_content("plot_x_col",0) calculated_data.add_content("plot_y_col",-1) except: pass try: # print(out_dictionary["labels"]) calculated_data.add_content("labels", out_dictionary["labels"]) except: pass try: calculated_data.add_content("info",out_dictionary["info"]) except: pass return calculated_data
def xoppy_calc_xfh(self): #TODO: remove I_ABSORP ILATTICE = self.ILATTICE HMILLER = self.HMILLER KMILLER = self.KMILLER LMILLER = self.LMILLER I_PLOT = self.I_PLOT TEMPER = self.TEMPER ENERGY = self.ENERGY ENERGY_END = self.ENERGY_END NPOINTS = self.NPOINTS descriptor = Crystal_GetCrystalsList()[ILATTICE] print("Using crystal descriptor: ", descriptor) bragg_dictionary = bragg_calc(descriptor=descriptor, hh=HMILLER, kk=KMILLER, ll=LMILLER, temper=TEMPER, emin=ENERGY, emax=ENERGY_END, estep=50.0, fileout=None) energy = numpy.linspace(ENERGY, ENERGY_END, NPOINTS) out = numpy.zeros((25, NPOINTS)) info = "" for i, ienergy in enumerate(energy): dic2 = crystal_fh(bragg_dictionary, ienergy) print("Energy=%g eV FH=(%g,%g)" % (ienergy, dic2["STRUCT"].real, dic2["STRUCT"].imag)) out[0, i] = ienergy out[1, i] = dic2["WAVELENGTH"] * 1e10 out[2, i] = dic2["THETA"] * 180 / numpy.pi out[3, i] = dic2["F_0"].real out[4, i] = dic2["F_0"].imag out[5, i] = dic2["FH"].real out[6, i] = dic2["FH"].imag out[7, i] = dic2["FH_BAR"].real out[8, i] = dic2["FH_BAR"].imag out[9, i] = dic2["psi_0"].real out[10, i] = dic2["psi_0"].imag out[11, i] = dic2["psi_h"].real out[12, i] = dic2["psi_h"].imag out[13, i] = dic2["psi_hbar"].real out[14, i] = dic2["psi_hbar"].imag out[15, i] = dic2["STRUCT"].real out[16, i] = dic2["STRUCT"].imag out[17, i] = dic2["DELTA_REF"] out[18, i] = dic2["REFRAC"].real out[19, i] = dic2["REFRAC"].imag out[20, i] = dic2["ABSORP"] out[21, i] = 1e6 * dic2["ssr"] # in microrads out[22, i] = 1e6 * dic2["spr"] # in microrads out[23, i] = dic2["RATIO"] out[24, i] = dic2["psi_over_f"] info += "#\n#\n#\n" info += dic2["info"] #send exchange calculated_data = DataExchangeObject( "XOPPY", self.get_data_exchange_widget_name()) try: calculated_data.add_content("xoppy_data", out.T) calculated_data.add_content("plot_x_col", 0) calculated_data.add_content("plot_y_col", I_PLOT) except: pass try: calculated_data.add_content("labels", self.plotOptionList()) except: pass try: calculated_data.add_content("info", info) except: pass if self.DUMP_TO_FILE: with open(self.FILE_NAME, "w") as file: try: file.write("#F %s\n" % self.FILE_NAME) file.write("\n#S 1 xoppy CrossSec results\n") file.write("#N %d\n" % (out.shape[0])) tmp = "#L" for item in self.plotOptionList(): tmp += " %s" % (item) tmp += "\n" file.write(tmp) for j in range(out.shape[1]): file.write( ("%19.12e " * out.shape[0] + "\n") % tuple(out[i, j] for i in range(out.shape[0]))) file.close() print("File written to disk: %s \n" % self.FILE_NAME) except: raise Exception( "CrossSec: The data could not be dumped onto the specified file!\n" ) return calculated_data
def calculate_total_filter(self): try: congruence.checkStrictlyPositiveNumber(self.energy_from, "Energy From") congruence.checkStrictlyPositiveNumber(self.energy_to, "Energy to") congruence.checkStrictlyPositiveNumber(self.energy_nr, "Nr. of energies") congruence.checkLessThan(self.energy_from, self.energy_to, "Energy From", "Energy to") energies = numpy.linspace(self.energy_from, self.energy_to, self.energy_nr) total_filter = numpy.ones((self.energy_nr, 2)) total_filter[:, 0] = energies self.__add_data_to_total_filter(total_filter, self.ref_1, self.n_ref_1, self.check_ref_1) self.__add_data_to_total_filter(total_filter, self.ref_2, self.n_ref_2, self.check_ref_2) self.__add_data_to_total_filter(total_filter, self.ref_3, self.n_ref_3, self.check_ref_3) self.__add_data_to_total_filter(total_filter, self.dif_1, self.n_dif_1, self.check_dif_1) self.__add_data_to_total_filter(total_filter, self.dif_2, self.n_dif_2, self.check_dif_2) self.__add_data_to_total_filter(total_filter, self.mul_1, self.n_mul_1, self.check_mul_1) self.__add_data_to_total_filter(total_filter, self.mul_2, self.n_mul_2, self.check_mul_2) self.__add_data_to_total_filter(total_filter, self.pow_1, 0, self.check_pow_1, absorbed=self.abs_tran == 0) total_filter[numpy.where(numpy.isnan(total_filter))] = 0.0 if not total_filter[:, 1].sum() == total_filter.shape[0]: self.filter_plot.clear() self.filter_plot.addCurve(total_filter[:, 0], total_filter[:, 1], replace=True, legend="Total Filter") self.filter_plot.setGraphXLabel("Energy [eV]") self.filter_plot.setGraphYLabel("Intensity Factor") self.filter_plot.setGraphTitle("Total Filter") calculated_data = DataExchangeObject("ShadowOui_Thermal", "TOTAL_FILTER") calculated_data.add_content("total_filter", total_filter) self.send("Total Filter", calculated_data) else: raise ValueError("Calculation not possibile: no input data") except Exception as e: QMessageBox.critical(self, "Error", str(e), QMessageBox.Ok) if self.IS_DEVELOP: raise e
def xoppy_calc_xcrystal(self): CRYSTAL_MATERIAL = self.CRYSTAL_MATERIAL MILLER_INDEX_H = self.MILLER_INDEX_H MILLER_INDEX_K = self.MILLER_INDEX_K MILLER_INDEX_L = self.MILLER_INDEX_L TEMPER = self.TEMPER MOSAIC = self.MOSAIC GEOMETRY = self.GEOMETRY SCAN = self.SCAN UNIT = self.UNIT SCANFROM = self.SCANFROM SCANTO = self.SCANTO SCANPOINTS = self.SCANPOINTS ENERGY = self.ENERGY ASYMMETRY_ANGLE = self.ASYMMETRY_ANGLE THICKNESS = self.THICKNESS MOSAIC_FWHM = self.MOSAIC_FWHM RSAG = self.RSAG RMER = self.RMER ANISOTROPY = self.ANISOTROPY POISSON = self.POISSON CUT = self.CUT FILECOMPLIANCE = self.FILECOMPLIANCE for file in ["diff_pat.dat","diff_pat.gle","diff_pat.par","diff_pat.xop","xcrystal.bra"]: try: os.remove(os.path.join(locations.home_bin_run(),file)) except: pass if (GEOMETRY == 1) or (GEOMETRY == 3): if ASYMMETRY_ANGLE == 0.0: print("xoppy_calc_xcrystal: WARNING: In xcrystal the asymmetry angle is the angle between Bragg planes and crystal surface,"+ "in BOTH Bragg and Laue geometries.") descriptor = Crystal_GetCrystalsList()[CRYSTAL_MATERIAL] if SCAN == 3: # energy scan emin = SCANFROM - 1 emax = SCANTO + 1 else: emin = ENERGY - 100.0 emax = ENERGY + 100.0 print("Using crystal descriptor: ",descriptor) bragg_dictionary = bragg_calc(descriptor=descriptor, hh=MILLER_INDEX_H,kk=MILLER_INDEX_K,ll=MILLER_INDEX_L, temper=float(TEMPER), emin=emin,emax=emax,estep=5.0,fileout="xcrystal.bra") with open("xoppy.inp", "wt") as f: f.write("xcrystal.bra\n") f.write("%d\n"%MOSAIC) f.write("%d\n"%GEOMETRY) if MOSAIC == 1: f.write("%g\n"%MOSAIC_FWHM) f.write("%g\n"%THICKNESS) else: f.write("%g\n"%THICKNESS) f.write("%g\n"%ASYMMETRY_ANGLE) scan_flag = 1 + SCAN f.write("%d\n"%scan_flag) f.write("%19.9f\n"%ENERGY) if scan_flag <= 3: f.write("%d\n"%UNIT) f.write("%g\n"%SCANFROM) f.write("%g\n"%SCANTO) f.write("%d\n"%SCANPOINTS) if MOSAIC > 1: # bent f.write("%g\n"%RSAG) f.write("%g\n"%RMER) f.write("0\n") if ( (descriptor == "Si") or (descriptor == "Si2") or (descriptor == "Si_NIST") or (descriptor == "Ge") or descriptor == "Diamond"): pass else: # not Si,Ge,Diamond if ((ANISOTROPY == 1) or (ANISOTROPY == 2)): raise Exception("Anisotropy data not available for this crystal. Either use isotropic or use external compliance file. Please change and run again'") f.write("%d\n"%ANISOTROPY) if ANISOTROPY == 0: f.write("%g\n"%POISSON) elif ANISOTROPY == 1: f.write("%d\n"%CRYSTAL_MATERIAL) f.write("%g\n"%ASYMMETRY_ANGLE) f.write("%d\n"%MILLER_INDEX_H) f.write("%d\n"%MILLER_INDEX_K) f.write("%d\n"%MILLER_INDEX_L) elif ANISOTROPY == 2: f.write("%d\n"%CRYSTAL_MATERIAL) f.write("%g\n"%ASYMMETRY_ANGLE) # TODO: check syntax for CUT: Cut syntax is: valong_X valong_Y valong_Z ; vnorm_X vnorm_Y vnorm_Z ; vperp_x vperp_Y vperp_Z f.write("%s\n"%CUT.split(";")[0]) f.write("%s\n"%CUT.split(";")[1]) f.write("%s\n"%CUT.split(";")[2]) elif ANISOTROPY == 3: f.write("%s\n"%FILECOMPLIANCE) command = "'" + os.path.join(locations.home_bin(), 'diff_pat') + "' < xoppy.inp" print("Running command '%s' in directory: %s "%(command, locations.home_bin_run())) print("\n--------------------------------------------------------\n") os.system(command) print("\n--------------------------------------------------------\n") #show calculated parameters in standard output txt_info = open("diff_pat.par").read() for line in txt_info: print(line,end="") calculated_data = DataExchangeObject("XOPPY", self.get_data_exchange_widget_name()) try: calculated_data.add_content("xoppy_data", numpy.loadtxt("diff_pat.dat", skiprows=5)) calculated_data.add_content("plot_x_col",0) calculated_data.add_content("plot_y_col",-1) calculated_data.add_content("units_to_degrees", self.get_units_to_degrees()) except Exception as e: raise Exception("Error loading diff_pat.dat :" + str(e)) try: calculated_data.add_content("labels", ["Th-ThB{in} [" + self.unit_combo.itemText(self.UNIT) + "]", "Th-ThB{out} [" + self.unit_combo.itemText(self.UNIT) + "]", "phase_p[rad]", "phase_s[rad]","Circ Polariz", "p-polarized reflectivity", "s-polarized reflectivity"]) except: pass try: with open("diff_pat.par") as f: info = f.readlines() calculated_data.add_content("info",info) except: pass return calculated_data
def _callable_2(self, html): try: self.x0h_input.loadFinished.disconnect() self.x0h_input.back() self.x0h_input.setHidden(False) response_1 = self.clear_response(html) response_2 = self.clear_response(html) self.tabs_widget.setCurrentIndex(0) self.x0h_output.setHtml(response_1) data0, data1, data2 = self.extract_plots(response_2) exchange_data = DataExchangeObject("XRAYSERVER", "X0H") exchange_data.add_content("reflectivity", data0) exchange_data.add_content("reflectivity_units_to_degrees", 1.0) exchange_data.add_content("x-ray_diffraction_profile_sigma", data1) exchange_data.add_content("x-ray_diffraction_profile_sigma_units_to_degrees", 0.000277777805) exchange_data.add_content("x-ray_diffraction_profile_pi", data2) exchange_data.add_content("x-ray_diffraction_profile_pi_units_to_degrees", 0.000277777805) self.send("xrayserver_data", exchange_data) except urllib.error.HTTPError as e: self.x0h_output.setHtml('The server couldn\'t fulfill the request.\nError Code: ' + str(e.code) + "\n\n" + server.BaseHTTPRequestHandler.responses[e.code][1]) except urllib.error.URLError as e: self.x0h_output.setHtml('We failed to reach a server.\nReason: ' + e.reason) except XrayServerException as e: ShowHtmlDialog.show_html("X-ray Server Error", e.response, width=750, height=500, parent=self) except Exception as e: self.x0h_output.setHtml('We failed to reach a server.\nReason: ' + str(e)) self.tabs_widget.setCurrentIndex(0) self.setStatusMessage("") self.progressBarFinished()