def test_MultiDistPlans(fake_devices, calib_data, db): ai0 = pyFAI.AzimuthalIntegrator(dist=0) ai1 = pyFAI.AzimuthalIntegrator(dist=1) mdp = MultiDistPlans(fake_devices.motor1, 0, 1, db, fake_devices.motor2, calib_data, fake_devices.motor2) mdp.add_dist(0, "test0", ai0) mdp.add_dist(1, "test1", ai1) summarize_plan(mdp.count([fake_devices.det1], 2))
def configure_azimuthal_integrator(par_edf_hanldle): """ A wrapper around a pyFAI.AzimuthalIntegrator constructor and its setFit2D method that returns a properly configured integrator for a specific edf handle. The function assumes that the detector has no tilt and that the beam center is equal to the point of normal incidence. configure_azimuthal_integrator(edf_handle) -> AzimuthalIntegrator """ # Get header attributes and convert to numeric header = par_edf_hanldle.header centre1px = float(header['Center_1']) centre2px = float(header['Center_2']) pixel1m = float(header['PSize_1']) pixel2m = float(header['PSize_2']) distance_m = float(header['SampleDistance']) wavelength_m = float(header['WaveLength']) # First configuration my_azin = pyFAI.AzimuthalIntegrator(dist=distance_m, poni1=centre1px * pixel1m, poni2=centre2px * pixel2m, wavelength=wavelength_m) # Second configuration my_azin.setFit2D(directDist=distance_m * 1e3, centerX=centre1px, centerY=centre2px, tilt=0.0, tiltPlanRotation=0.0, pixelX=pixel1m * 1e6, pixelY=pixel2m * 1e6) return my_azin
def test_load_dict_from_poni(db, expect_qi): config = load_dict_from_poni(db["Ni_poni_file"]) ai = pyFAI.AzimuthalIntegrator() ai.set_config(config) q, i = ai.integrate1d(db['black_img'], 1024, safe=False) assert np.array_equal(q, expect_qi[0]) assert np.array_equal(i, expect_qi[1])
def integration_time(self, data_list): """ This method will integrate the 2D images into their appropriate data forms Parameters ---------- data_list : list of 2d arrays this should be the data that needs to be processed Returns ------- None """ if self.wl is None: self.set_integration_parameters() det = pyFAI.detectors.Perkin() ni = pyFAI.calibrant.ALL_CALIBRANTS("Ni") ni.set_wavelength(self.wl) ai = pyFAI.AzimuthalIntegrator(dist=self.dist, poni1=self.poni1, poni2=self.poni2, rot1=self.rot1, rot2=self.rot2, detector=det) ai.set_wavelength(self.wl) for data in data_list: x, y = ai.integrate1d(data, 1000, unit='q_A^-1') self.x_lists.append(x) self.y_lists.append(y)
def cakexintegrate(data, mask, AIdict, cut=None, color=[255, 255, 255], requestkey=None, qvrt=None, qpar=None): AI = pyFAI.AzimuthalIntegrator() AI.setPyFAI(**AIdict) if not mask.shape == data.shape: msg.logMessage("No mask match. Mask will be ignored.", msg.WARNING) mask = np.ones_like(data) msg.logMessage(('emptymask:', mask.shape), msg.DEBUG) if cut is not None: msg.logMessage(('cut:', cut.shape), msg.DEBUG) mask &= cut.astype(bool) chi = np.arange(-180, 180, 360 / config.settings['Integration Bins (χ)']) maskeddata = np.ma.masked_array(data, mask=1 - mask) xprofile = np.ma.average(maskeddata, axis=1) return chi.tolist(), xprofile.tolist(), color, requestkey
def data_reduction(self, d, Rot, tilt, lamda, x0, y0, pixelsize): """ The input is the raw file's name and calibration parameters return Q-chi (2D array) """ s1 = int(self.imArray.shape[0]) s2 = int(self.imArray.shape[1]) self.imArray = signal.medfilt(self.imArray, kernel_size=5) self.imArray = np.flipud(self.imArray) detector_mask = np.ones((s1, s2)) * (self.imArray <= 0) p = pyFAI.AzimuthalIntegrator(wavelength=lamda) # refer to http://pythonhosted.org/pyFAI/api/pyFAI.html for pyFAI parameters p.setFit2D(d, x0, y0, tilt, Rot, pixelsize, pixelsize) # the output unit for Q is angstrom-1. Always integrate all in 2D cake, Q, chi = p.integrate2d( self.imArray, 1000, 1000, #azimuth_range=azRange, radial_range=radRange, mask=detector_mask, polarization_factor=self.PP) # pyFAI output unit for Fit2D gemoetry incorrect. Multiply by 10e8 for correction Q = Q * 10e8 return Q, chi, cake
def getAI(self): """ :rtype : pyFAI.AzimuthalIntegrator """ # print(self.getDetector().MAX_SHAPE) AI = pyFAI.AzimuthalIntegrator(wavelength=self.getvalue('Wavelength')) # dist=self.getvalue('Detector Distance'), # poni1=self.getvalue('Pixel Size X') * (self.getvalue('Center Y')), # poni2=self.getvalue('Pixel Size Y') * (self.getvalue('Center X')), # rot1=0, # rot2=0, # rot3=0, # pixel1=self.getvalue('Pixel Size Y'), # pixel2=self.getvalue('Pixel Size X'), # detector=self.getDetector(), if self.fit2dstyle.isChecked(): AI.setFit2D( self.getvalue('Detector Distance') * 1000., self.getvalue('Center X'), self.getvalue('Center Y'), self.getvalue('Detector Tilt'), 360. - self.getvalue('Detector Rotation'), self.getvalue('Pixel Size Y') * 1.e6, self.getvalue('Pixel Size X') * 1.e6) elif self.wxdiffstyle.isChecked(): AI.setFit2D( self.getvalue('Detector Distance') * 1000., self.getvalue('Center X'), self.getvalue('Center Y'), self.getvalue('Detector Tilt') / 2. / np.pi * 360., 360. - (2 * np.pi - self.getvalue('Detector Rotation')) / 2. / np.pi * 360., self.getvalue('Pixel Size Y') * 1.e6, self.getvalue('Pixel Size X') * 1.e6) AI.set_wavelength(self.getvalue('Wavelength')) # print AI return AI
def data_reduction(imageFullname, d_in_pixel, Rot, tilt, lamda, x0, y0, PP): # open MARCCD tiff image im = Image.open(imageFullname) # change image object into an array imArray = np.array(im) s = int(imArray.shape[0]) imArray = signal.medfilt(imArray, kernel_size=5) im.close() detector_mask = np.ones((s, s)) * (imArray <= 0) pixelsize = 79 # measured in microns d = d_in_pixel * pixelsize * 0.001 # measured in milimeters p = pyFAI.AzimuthalIntegrator(wavelength=lamda) p.setFit2D(d, x0, y0, tilt, Rot, pixelsize, pixelsize) cake, Q, chi = p.integrate2d(imArray, 1000, 1000, mask=detector_mask, polarization_factor=PP) Q = Q * 10e8 chi = chi + 90 Qlist, IntAve = p.integrate1d(imArray, 1000, mask=detector_mask, polarization_factor=PP) Qlist = Qlist * 10e8 return Q, chi, cake, Qlist, IntAve
def remeshzintegrate(data, mask, AIdict, cut=None, color=[255, 255, 255], requestkey=None, qvrt=None, qpar=None): AI = pyFAI.AzimuthalIntegrator() AI.setPyFAI(**AIdict) if not mask.shape == data.shape: msg.logMessage("No mask match. Mask will be ignored.", msg.WARNING) mask = np.ones_like(data) msg.logMessage(('emptymask:', mask.shape), msg.DEBUG) if cut is not None: msg.logMessage(('cut:', cut.shape), msg.DEBUG) mask &= cut.astype(bool) center = np.where(np.abs(qvrt) == np.abs(qvrt).min()) qx = -qvrt[center[1][0]] / 10. maskeddata = np.ma.masked_array(data, mask=1 - mask) xprofile = np.ma.average(maskeddata, axis=0) return qx, xprofile, color, requestkey
def remeshchiintegrate(data, mask, AIdict, cut=None, color=[255, 255, 255], requestkey=None, qvrt=None, qpar=None): AI = pyFAI.AzimuthalIntegrator() AI.setPyFAI(**AIdict) alphai = config.activeExperiment.getvalue('Incidence Angle (GIXS)') msg.logMessage( 'Incoming angle applied to remeshed q integration: ' + str(alphai), msg.DEBUG) qsquared = qpar**2 + qvrt**2 remeshcenter = np.unravel_index(qsquared.argmin(), qsquared.shape) f2d = AI.getFit2D() f2d['centerX'] = remeshcenter[0] f2d['centerY'] = remeshcenter[1] AI.setFit2D(**f2d) AIdict = AI.getPyFAI() return chiintegratepyFAI(data, mask, AIdict, cut, color, requestkey, qvrt=None, qpar=None)
def data_reduction(imageFullname, d_in_pixel, Rot, tilt, lamda, x0, y0, PP): """ The input is the raw file's name and calibration parameters return Q-chi (2D array) and a spectrum (1D array) """ # open MARCCD tiff image im = Image.open(imageFullname) # input image object into an array imArray = np.array(im) s = int(imArray.shape[0]) im.close() detector_mask = np.ones((s, s)) * (imArray <= 0) pixelsize = 79 # measured in microns d = d_in_pixel * pixelsize * 0.001 # measured in milimeters p = pyFAI.AzimuthalIntegrator(wavelength=lamda) p.setFit2D(d, x0, y0, tilt, Rot, pixelsize, pixelsize) cake, Q, chi = p.integrate2d(imArray, 1000, 1000, mask=detector_mask, polarization_factor=PP) Q = Q * 10e8 chi = chi + 90 Qlist, IntAve = p.integrate1d(imArray, 1000, mask=detector_mask, polarization_factor=PP) Qlist = Qlist * 10e8 return Q, chi, cake, Qlist, IntAve
def zintegrate(data, mask, AIdict, cut=None, color=[255, 255, 255], requestkey=None, qvrt=None, qpar=None): if mask is not None: mask = mask.copy() msg.logMessage(('image:', data.shape), msg.DEBUG) msg.logMessage(('mask:', mask.shape), msg.DEBUG) if not mask.shape == data.shape: msg.logMessage("No mask match. Mask will be ignored.", msg.WARNING) mask = np.ones_like(data) msg.logMessage(('emptymask:', mask.shape), msg.DEBUG) if cut is not None: msg.logMessage(('cut:', cut.shape), msg.DEBUG) mask &= cut.astype(bool) # data *= cut maskeddata = np.ma.masked_array(data, mask=1 - mask) xprofile = np.ma.average(maskeddata, axis=0) AI = pyFAI.AzimuthalIntegrator() AI.setPyFAI(**AIdict) qz = AI.qArray(data.shape[::-1])[:, AI.getFit2D()['centerX']] / 10 qz[:qz.argmin()] *= -1 return qz, xprofile, color, requestkey
def cakezintegrate(data, mask, AIdict, cut=None, color=[255, 255, 255], requestkey=None, qvrt=None, qpar=None): AI = pyFAI.AzimuthalIntegrator() AI.setPyFAI(**AIdict) if not mask.shape == data.shape: msg.logMessage("No mask match. Mask will be ignored.", msg.WARNING) mask = np.ones_like(data) msg.logMessage(('emptymask:', mask.shape), msg.DEBUG) if cut is not None: msg.logMessage(('cut:', cut.shape), msg.DEBUG) mask &= cut.astype(bool) q = np.arange(1000) * np.max(qpar) / 10000. maskeddata = np.ma.masked_array(data, mask=1 - mask) zprofile = np.ma.average(maskeddata, axis=0) return q, zprofile, color, requestkey
def __init__(self, input_data=None): self.ai = pyFAI.AzimuthalIntegrator() self.input_data = input_data self.output_path = None self.output_format = None self.slow_dim = None self.fast_dim = None self.name = None self._sem = threading.Semaphore() QtGui.QWidget.__init__(self) try: uic.loadUi(UIC, self) except AttributeError as error: logger.error( "I looks like your installation suffers from this bug: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=697348" ) raise RuntimeError( "Please upgrade your installation of PyQt (or apply the patch)" ) # self.all_detectors = pyFAI.detectors.ALL_DETECTORS.keys() # self.all_detectors.sort() # self.detector.addItems([i.capitalize() for i in self.all_detectors]) # self.detector.setCurrentIndex(self.all_detectors.index("detector")) # # connect file selection windows # self.connect(self.file_poni, SIGNAL("clicked()"), self.select_ponifile) self.connect(self.choose_mask, SIGNAL("clicked()"), self.select_maskfile)
def data_reduction(imArray, d, Rot, tilt, lamda, x0, y0, PP, pixelsize): """ The input is the raw file's name and calibration parameters return Q-chi (2D array) and a spectrum (1D array) """ s1 = int(imArray.shape[0]) s2 = int(imArray.shape[1]) # refer to http://pythonhosted.org/pyFAI/api/pyFAI.html for pyFAI parameters detector_mask = np.ones((s1, s2)) * (imArray <= 0) p = pyFAI.AzimuthalIntegrator(wavelength=lamda) p.setFit2D(d, x0, y0, tilt, Rot, pixelsize, pixelsize) cake, Q, chi = p.integrate2d(imArray, 1000, 1000, mask=detector_mask, polarization_factor=PP) Q = Q * 10e8 # the pyFAI output unit for Fit2D gemoetry is not correct. Multiply by 10e8 for correction chi = chi + 90 Qlist, IntAve = p.integrate1d(imArray, 1000, mask=detector_mask, polarization_factor=PP) Qlist = Qlist * 10e8 return Q, chi, cake, Qlist, IntAve
def __init__(self, input_data=None): self.ai = pyFAI.AzimuthalIntegrator() self.input_data = input_data self._sem = threading.Semaphore() QtGui.QWidget.__init__(self) uic.loadUi('integration.ui', self) self.all_detectors = pyFAI.detectors.ALL_DETECTORS.keys() self.all_detectors.sort() self.detector.addItems([i.capitalize() for i in self.all_detectors]) self.detector.setCurrentIndex(self.all_detectors.index("detector")) #connect file selection windows self.connect(self.file_poni, SIGNAL("clicked()"), self.select_ponifile) self.connect(self.file_splinefile, SIGNAL("clicked()"), self.select_splinefile) self.connect(self.file_mask_file, SIGNAL("clicked()"), self.select_maskfile) self.connect(self.file_dark_current, SIGNAL("clicked()"), self.select_darkcurrent) self.connect(self.file_flat_field, SIGNAL("clicked()"), self.select_flatfield) # connect button bar self.okButton = self.buttonBox.button(QtGui.QDialogButtonBox.Ok) self.saveButton = self.buttonBox.button(QtGui.QDialogButtonBox.Save) self.resetButton = self.buttonBox.button(QtGui.QDialogButtonBox.Reset) self.connect(self.okButton, SIGNAL("clicked()"), self.proceed) self.connect(self.saveButton, SIGNAL("clicked()"), self.dump) self.connect(self.buttonBox, SIGNAL("helpRequested()"), self.help) self.connect(self.buttonBox, SIGNAL("rejected()"), self.die) self.connect(self.resetButton, SIGNAL("clicked()"), self.restore) self.connect(self.detector, SIGNAL("currentIndexChanged(int)"), self.detector_changed) self.connect(self.do_OpenCL, SIGNAL("clicked()"), self.openCL_changed) self.connect(self.platform, SIGNAL("currentIndexChanged(int)"), self.platform_changed) self.restore() self.progressBar.setValue(0)
def test_load_dict_from_poni(test_data, expect_qi): config = mod.load_dict_from_poni(test_data["Ni_poni_file"]) ai = pyFAI.AzimuthalIntegrator() ai.set_config(config) q, i = ai.integrate1d(test_data['white_img'], 1024, safe=False) assert np.array_equal(q, expect_qi[0]) assert np.array_equal(i, expect_qi[1])
def calibrate_images(import_X_ray_frames, frame_i, npt_row, npt_col, center_row, center_col, two_theta_center): try: ai = pyFAI.AzimuthalIntegrator() ai.pixel1 = float(import_X_ray_frames.pixel_size_1.get()) ai.pixel2 = float(import_X_ray_frames.pixel_size_2.get()) ai.dist = float(import_X_ray_frames.distance_calibration.get()) ai.poni1 = float(import_X_ray_frames.poni_1.get()) ai.poni2 = float(import_X_ray_frames.poni_2.get()) ai.rot1 = float(import_X_ray_frames.rotation_1.get()) ai.rot2 = float(import_X_ray_frames.rotation_2.get()) ai.rot3 = float(import_X_ray_frames.rotation_3.get()) ai.wavelength = float(import_X_ray_frames.wavelength_calibration.get()) except ValueError: showinfo( title="Error", message= "Please insert and verify all the calibration parameters is a number\nPlease use '.' instead of ',' to insert a number" ) return () else: frame_calibrate_i, two_theta, gamma = ai.integrate2d( np.asarray(frame_i), npt_row, npt_col, unit="2th_deg") gamma_i = np.asarray(gamma) - gamma[int(center_row)] if gamma_i[0] < gamma_i[len(gamma_i) - 1]: gamma_i = np.flip(gamma_i, axis=0) two_theta_i = np.asarray(two_theta) - two_theta_center + two_theta[int( center_col)] return (frame_calibrate_i, gamma_i, two_theta_i)
def initialize(self, wavelength=None, option=None, default_init=None): if default_init is not None: if wavelength is None: if 'wavelength' in default_init: wavelength = default_init['wavelength'] else: wavelength = '1.0' if option is None: self.LogInfo('alginte option: ' + str(option)) if 'option' in default_init: option = default_init['option'] else: option = '1D' self.LogInfo('2alginte option: ' + str(option)) else: if option is None: option = '1D' if wavelength is None: option = '1.0' self.wavelength = wavelength self.option = option.upper() self.data = self.get("DataStore").data() self.ai = pyFAI.AzimuthalIntegrator(wavelength=self.wavelength) if self.option == '1D': self.func = self.ai.integrate1d elif self.option == '2D': self.func = self.ai.integrate2d elif self.option == 'RADIAL': self.func = self.ai.integrate_radial else: self.func = self.ai.integrate1d #self.LogInfo("initialized, pyFAI AzimuthalIntegrator("+self.option+") with wavelength "+self.wavelength) return True
def __init__(self, azimuthalIntgrator=None, shapeIn=(2048, 2048), shapeOut=(360, 500), unit="r_mm"): """ @param azimuthalIntgrator: pyFAI.AzimuthalIntegrator instance @param shapeIn: image size in input @param shapeOut: Integrated size: can be (1,2000) for 1D integration @param unit: can be "2th_deg, r_mm or q_nm^-1 ... """ Core.Processlib.SinkTaskBase.__init__(self) if azimuthalIntgrator is None: self.ai = pyFAI.AzimuthalIntegrator() else: self.ai = azimuthalIntgrator self.nbpt_azim, self.nbpt_rad = shapeOut self.unit = pyFAI.units.to_unit(unit) self.polarization = None self.dummy = None self.delta_dummy = None self.correct_solid_angle = True self.dark_current_image = None self.flat_field_image = None self.mask_image = None self.subdir = "" self.extension = None self.do_poisson = None # self.do try: self.shapeIn = (camera.getFrameDim.getHeight(), camera.getFrameDim.getWidth()) except Exception as error: logger.error("default on shapeIn %s: %s" % (shapeIn, error)) self.shapeIn = shapeIn
def __init__(self, args, detector, mask): import pyFAI self.detector = detector self.mask = mask self.psx = self.detector.pixel1 self.psy = self.detector.pixel2 self.resolution = self.detector.shape self.distance = args['detector_distance'] / 1000. # Convert from meter (NPC) to mm (pyFAI) self.bcx = args['beam_x'] * self.psx self.bcy = args['beam_y'] * self.psy self.wl = args['wavelength'] self.ai = pyFAI.AzimuthalIntegrator(dist=self.distance, poni1=self.bcx, poni2=self.bcy, rot1=0, rot2=0, rot3=0, pixel1=self.psx, pixel2=self.psy, splineFile=None, detector=self.detector, wavelength=self.wl)
def preProcess(self, _edObject=None): EDPluginExec.preProcess(self) self.DEBUG("EDPluginExecPyFAIv1_0.preProcess") sdi = self.dataInput ai = pyFAI.AzimuthalIntegrator() if sdi.geometryFit2D is not None: xsGeometry = sdi.geometryFit2D detector = self.getDetector(xsGeometry.detector) d = {"direct": EDUtilsUnit.getSIValue(xsGeometry.distance) * 1000, #fit2D takes the distance in mm "centerX": xsGeometry.beamCentreInPixelsX.value , "centerY":xsGeometry.beamCentreInPixelsY.value , "tilt": xsGeometry.angleOfTilt.value, "tiltPlanRotation": xsGeometry.tiltRotation.value} d.update(detector.getFit2D()) ai.setFit2D(**d) elif sdi.geometryPyFAI is not None: xsGeometry = sdi.geometryPyFAI detector = self.getDetector(xsGeometry.detector) d = {"dist": EDUtilsUnit.getSIValue(xsGeometry.sampleDetectorDistance), "poni1": EDUtilsUnit.getSIValue(xsGeometry.pointOfNormalIncidence1), "poni2": EDUtilsUnit.getSIValue(xsGeometry.pointOfNormalIncidence2), "rot1": EDUtilsUnit.getSIValue(xsGeometry.rotation1), "rot2": EDUtilsUnit.getSIValue(xsGeometry.rotation2), "rot3": EDUtilsUnit.getSIValue(xsGeometry.rotation3)} d.update(detector.getPyFAI()) ai.setPyFAI(**d) else: strError = "Geometry definition in %s, not recognized as a valid geometry%s %s" % (sdi, os.linesep, sdi.marshal()) self.ERROR(strError) raise RuntimeError(strError) ######################################################################## # Choose the azimuthal integrator ######################################################################## with self.__class__._sem: if tuple(ai.param) in self.__class__._dictGeo: self.ai = self.__class__._dictGeo[tuple(ai.param)] else: self.__class__._dictGeo[tuple(ai.param)] = ai self.ai = ai self.data = EDUtilsArray.getArray(self.dataInput.input).astype(float) if sdi.dark is not None: self.data -= EDUtilsArray.getArray(sdi.dark) if sdi.flat is not None: self.data /= EDUtilsArray.getArray(sdi.flat) if sdi.mask is not None: self.mask = EDUtilsArray.getArray(sdi.mask) if sdi.wavelength is not None: self.ai.wavelength = EDUtilsUnit.getSIValue(sdi.wavelength) if sdi.output is not None: self.strOutputFile = sdi.output.path.value if sdi.dummy is not None: self.dummy = sdi.dummy.value if sdi.deltaDummy is not None: self.delta_dummy = sdi.deltaDummy.value if sdi.nbPt: self.nbPt = sdi.nbPt.value
def InitChild(self,data): fig=self.fig ax=self.ax ctrX,ctrY=self.center=FindCenter(data) self.ai = pyFAI.AzimuthalIntegrator(1.e3, ctrX, ctrY, 0.0, 0.0, 0.0, 1.e0, 1.e0) #canvas=self.canvas self.numPtTh=int(np.average(data.shape)/2.) out=self.ai.xrpd(data,self.numPtTh) self.hl=ax.plot(*out) ax.set_yscale('log')
def __init__(self, input_data=None): self.ai = pyFAI.AzimuthalIntegrator() self.input_data = input_data self.output_path = None self.output_format = None self.slow_dim = None self.fast_dim = None self.name = None self._sem = threading.Semaphore() QtGui.QWidget.__init__(self) try: uic.loadUi(UIC, self) except AttributeError as error: logger.error( "I looks like your installation suffers from this bug: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=697348" ) raise RuntimeError( "Please upgrade your installation of PyQt (or apply the patch)" ) self.all_detectors = pyFAI.detectors.ALL_DETECTORS.keys() self.all_detectors.sort() self.detector.addItems([i.capitalize() for i in self.all_detectors]) self.detector.setCurrentIndex(self.all_detectors.index("detector")) # connect file selection windows self.connect(self.file_poni, SIGNAL("clicked()"), self.select_ponifile) self.connect(self.file_splinefile, SIGNAL("clicked()"), self.select_splinefile) self.connect(self.file_mask_file, SIGNAL("clicked()"), self.select_maskfile) self.connect(self.file_dark_current, SIGNAL("clicked()"), self.select_darkcurrent) self.connect(self.file_flat_field, SIGNAL("clicked()"), self.select_flatfield) # connect button bar self.okButton = self.buttonBox.button(QtGui.QDialogButtonBox.Ok) self.saveButton = self.buttonBox.button(QtGui.QDialogButtonBox.Save) self.resetButton = self.buttonBox.button(QtGui.QDialogButtonBox.Reset) self.connect(self.okButton, SIGNAL("clicked()"), self.proceed) self.connect(self.saveButton, SIGNAL("clicked()"), self.dump) self.connect(self.buttonBox, SIGNAL("helpRequested()"), self.help) self.connect(self.buttonBox, SIGNAL("rejected()"), self.die) self.connect(self.resetButton, SIGNAL("clicked()"), self.restore) self.connect(self.detector, SIGNAL("currentIndexChanged(int)"), self.detector_changed) self.connect(self.do_OpenCL, SIGNAL("clicked()"), self.openCL_changed) self.connect(self.platform, SIGNAL("currentIndexChanged(int)"), self.platform_changed) self.restore() self.progressBar.setValue(0) self.hdf5_path = None
def run(self): fpath = self.inputs['wxd_file'] pxsz_um = self.inputs['pixel_size_um'] if fpath is None or pxsz_um is None: return pxsz_m = pxsz_um * 1E-6 fpolz = self.inputs['fpolz'] for line in open(fpath, 'r'): kv = line.strip().split('=') if kv[0] == 'detect_dist': d_px = float(kv[1]) # WXDIFF direct detector distance, # from sample to where beam axis intersects detector plane, in pixels. # Fit2D uses this input in mm to set its spatial scale, # so it has to be converted to distance units (mm for Fit2D). # Because this scales the spatial representation for Fit2D, # the other inputs can still be given in pixel units, # without converting between pixel sizes. d_m = d_px * pxsz_m d_mm = d_m * 1E3 if kv[0] == 'bcenter_x': bcx_px = float( kv[1] ) # WXDIFF x coord relative to 'bottom left' corner of detector # where beam axis intersects detector plane, in pixels # Fit2D centerX is also in pixels if kv[0] == 'bcenter_y': bcy_px = float( kv[1] ) # WXDIFF y coord relative to 'bottom left' corner of detector # where beam axis intersects detector plane, in pixels # Fit2D centerY is also in pixels if kv[0] == 'detect_tilt_alpha': rot_rad = float( kv[1]) # WXDIFF alpha is tilt plane rotation in rad # Fit2D tiltPlanRotation = 360-rot_rad*180/pi if kv[0] == 'detect_tilt_delta': tilt_rad = float(kv[1]) # WXDIFF delta is the tilt in rad if kv[0] == 'wavelenght': wl_A = float(kv[1]) # WXDIFF 'wavelenght' is in Angstroms # get wavelength in m wl_m = wl_A * 1E-10 # Mapping between Fit2D and WXDIFF originally contributed by Fang Ren. # TODO: Verify this mapping rot_deg = rot_rad * float(180) / np.pi rot_fit2d = float(360) - rot_deg tilt_deg = tilt_rad * float(180) / np.pi # use a pyFAI.AzimuthalIntegrator() to do the conversion p = pyFAI.AzimuthalIntegrator(wavelength=wl_m) p.setFit2D(d_mm, bcx_px, bcy_px, tilt_deg, rot_fit2d, pxsz_um, pxsz_um) poni_dict = p.getPyFAI() poni_dict['fpolz'] = fpolz self.outputs['poni_dict'] = poni_dict
def prepare(self): """ Called with prepareAcq() """ im = self._control.image() imdim = im.getImageDim().getSize() x = imdim.getWidth() y = imdim.getHeight() bin = im.getBin() binX = bin.getX() binY = bin.getY() lima_cfg = {"dimX": x, "dimY": y, "binX": binX, "binY": binY} saving = self._control.saving() sav_parms = saving.getParameters() lima_cfg["directory"] = sav_parms.directory lima_cfg["prefix"] = sav_parms.prefix lima_cfg["start_index"] = sav_parms.nextNumber lima_cfg["indexFormat"] = sav_parms.indexFormat # number of images ... acq = self._control.acquisition() lima_cfg["number_of_frames"] = acq.getAcqNbFrames() #to check. lima_cfg["exposure_time"] = acq.getAcqExpoTime() #ROI see: https://github.com/esrf-bliss/Lima/blob/master/control/include/CtAcquisition.h print("self._task._worker: %s" % self._task._worker) if (self._task._worker) is None: centerX = x // 2 centerY = y // 2 ai = pyFAI.AzimuthalIntegrator() ai.setFit2D(1000, centerX=centerX, centerY=centerY, pixelX=1, pixelY=1) worker = pyFAI.worker.Worker(ai) worker.unit = "r_mm" worker.method = "lut_ocl_gpu" worker.nbpt_azim = 360 worker.nbpt_rad = 500 worker.output = "numpy" print("Worker updated") self._task._worker = worker else: worker = self._task._worker worker.reconfig(shape=(y, x), sync=True) if self._task._writer: config = self._task._worker.get_config() self._task._writer.init(fai_cfg=config, lima_cfg=lima_cfg) self._task._writer.flush(worker.radial, worker.azimuthal)
def pre_process(self): """ This method is called after the plugin has been created by the pipeline framework as a pre-processing step :param parameters: A dictionary of the parameters for this plugin, or None if no customisation is required :type parameters: dict """ in_dataset, out_datasets = self.get_datasets() mData = self.get_in_meta_data()[0] in_d1 = in_dataset[0] ai = pyFAI.AzimuthalIntegrator() # get me an integrator object # prep the goemtry px_m = mData.get_meta_data('x_pixel_size') bc_m = [mData.get_meta_data("beam_center_x"), mData.get_meta_data("beam_center_y")] # in metres bc = bc_m / px_m # convert to pixels px = px_m*1e6 # convert to microns distance = mData.get_meta_data('distance')*1e3 # convert to mm wl = mData.get_meta_data('incident_wavelength')[...] # in m self.wl = wl yaw = -mData.get_meta_data("yaw") roll = mData.get_meta_data("roll") ai.setFit2D(distance, bc[0], bc[1], yaw, roll, px, px, None) ai.set_wavelength(wl) logging.debug(ai) sh = in_d1.get_shape() if (self.parameters["use_mask"]): mask = mData.get_meta_data("mask") else: mask = np.zeros((sh[-2], sh[-1])) # now integrate in radius (1D)print "hello" self.npts = self.get_parameters('num_bins') self.params = [mask, self.npts, mData, ai] # now set the axis values, we shouldn't do this in every slice axis, __remapped = \ ai.integrate1d(data=mask, npt=self.npts, unit='q_A^-1', correctSolidAngle=False) self.add_axes_to_meta_data(axis, mData)
def integrate(self): #with fabio.fabioutils.File(self.rawImage) as raw: img = fabio.open(self.rawImage) number_of_bins = self.number_of_bins or max(img.dim1, img.dim2) if "Date" in img.header: self.experimentSetup.timeOfFrame = XSDataTime( time.mktime( time.strptime(img.header["Date"], "%a %b %d %H:%M:%S %Y"))) new_integrator = pyFAI.AzimuthalIntegrator(detector=self.detector) new_integrator.setFit2D( self.experimentSetup.detectorDistance.value * 1000, self.experimentSetup.beamCenter_1.value, self.experimentSetup.beamCenter_2.value) new_integrator.wavelength = EDUtilsUnit.getSIValue( self.experimentSetup.wavelength) with self.__class__.semaphore: if (str(new_integrator) != str(self.integrator) or self.maskfile != self.experimentSetup.maskFile.path.value): self.screen("Resetting PyFAI integrator") new_integrator.detector.mask = self.calc_mask() self.__class__.integrator = new_integrator res_tuple = self.integrator.integrate1d( img.data, number_of_bins, correctSolidAngle=True, dummy=self.dummy, delta_dummy=self.delta_dummy, filename=None, error_model="poisson", radial_range=None, azimuth_range=None, polarization_factor=0.99, dark=None, flat=None, method=self.METHOD, unit="q_nm^-1", safe=False, normalization_factor=self.normalization_factor) self.lstExecutiveSummary.append( "Azimuthal integration of raw image '%s'-->'%s'." % (self.rawImage, self.integratedCurve)) valid_bins = abs(res_tuple.intensity - self.dummy) > self.delta_dummy short_tuple = res_tuple.__class__(res_tuple.radial[valid_bins], res_tuple.intensity[valid_bins], res_tuple.sigma[valid_bins]) return short_tuple
def __init__(self, parent, title, hid): HdfImageGLFrame.__init__(self, parent, title, hid) #HdfPyFAI1DFrame(self, title, hid) canvas=self.canvas raw=canvas.data ctrX,ctrY=FindCenter(raw) self.ai = pyFAI.AzimuthalIntegrator(1.e3, ctrX, ctrY, 0.0, 0.0, 0.0, 1.e0, 1.e0) raw self.numPtTh=int(np.average(raw.shape)/2.) self.numPtCh=360 imgPolar,theta,chi=self.ai.xrpd2(raw,self.numPtTh,self.numPtCh) canvas.data=imgPolar print (imgPolar.shape)
def __init__(self, azimuthalIntgrator=None, shapeIn=(966, 1296), shapeOut=(360, 500), unit="r_mm"): """ :param azimuthalIntgrator: pyFAI.AzimuthalIntegrator instance """ Core.Processlib.LinkTask.__init__(self) if azimuthalIntgrator is None: self.ai = pyFAI.AzimuthalIntegrator() else: self.ai = azimuthalIntgrator self.nbpt_azim, self.nbpt_rad = shapeOut self.unit = unit # this is just to force the integrator to initialize _ = self.ai.integrate2d(numpy.zeros(shapeIn, dtype=numpy.float32), self.nbpt_rad, self.nbpt_azim, method="lut", unit=self.unit,)