def scan_Fit2D(self, width=1.0, points=10, axis="tilt", dx=0.1): """ ??? @param width: ??? @type width: float ??? @param points: ??? @type points: int ??? @param axis: ??? @type axis: str ??? @param dx: ??? @type dx: float ??? @return: ??? @rtype: ??? """ logger.info("Scanning along axis %s" % axis) f = self.ai.getFit2D() out = [] meas_pts = numpy.linspace(f[axis] - width / 2.0, f[axis] + width / 2.0, points) for x in meas_pts: ax = AzimuthalIntegrator() fx = f.copy() fx[axis] = x ax.setFit2D(**fx) ref = Refinment2D(self.img, ax) res = ref.diff_Fit2D(axis=axis, dx=dx) print "x= %.3f mean= %e" % (x, res) out.append(res) return meas_pts, out
def diff_tth_X(self, dx=0.1): """ Jerome peux-tu décrire de quoi il retourne ??? @param dx: ??? @type: float ??? @return: ??? @rtype: ??? """ f = self.ai.getFit2D() fp = f.copy() fm = f.copy() fm["centerX"] -= dx / 2.0 fp["centerX"] += dx / 2.0 ap = AzimuthalIntegrator() am = AzimuthalIntegrator() ap.setFit2D(**fp) am.setFit2D(**fm) dtthX = (ap.twoThetaArray(self.shape) - am.twoThetaArray(self.shape))\ / dx tth, I = self.ai.xrpd(self.img, max(self.shape)) dI = SGModule.getSavitzkyGolay(I, npoints=5, degree=2, order=1)\ / (tth[1] - tth[0]) dImg = self.reconstruct(tth, dI) return (dtthX * dImg).sum()
class test_saxs(unittest.TestCase): saxsPilatus = "1492/bsa_013_01.edf" maskFile = "1491/Pcon_01Apr_msk.edf" maskRef = "1490/bioSaxsMaskOnly.edf" maskDummy = "1488/bioSaxsMaskDummy.edf" poniFile = "1489/bioSaxs.poni" ai = None tmp_dir = os.environ.get("PYFAI_TEMPDIR", os.path.join(os.path.dirname(os.path.abspath(__file__)), "tmp")) def setUp(self): self.edfPilatus = UtilsTest.getimage(self.__class__.saxsPilatus) self.maskFile = UtilsTest.getimage(self.__class__.maskFile) self.poniFile = UtilsTest.getimage(self.__class__.poniFile) self.maskRef = UtilsTest.getimage(self.__class__.maskRef) self.maskDummy = UtilsTest.getimage(self.__class__.maskDummy) self.ai = AzimuthalIntegrator() self.ai.load(self.poniFile) if not os.path.isdir(self.tmp_dir): os.mkdir(self.tmp_dir) def test_mask(self): """test the generation of mask""" print self.edfPilatus data = fabio.open(self.edfPilatus).data mask = fabio.open(self.maskFile).data assert abs(self.ai.makeMask(data, mask=mask).astype(int) - fabio.open(self.maskRef).data).max() == 0 assert abs(self.ai.makeMask(data, mask=mask, dummy= -2, delta_dummy=1.1).astype(int) - fabio.open(self.maskDummy).data).max() == 0
class test_setter(unittest.TestCase): tmp_dir = os.environ.get("PYFAI_TEMPDIR", os.path.join(os.path.dirname(os.path.abspath(__file__)), "tmp")) def setUp(self): self.ai = AzimuthalIntegrator() shape = (10, 15) self.rnd1 = numpy.random.random(shape).astype(numpy.float32) self.rnd2 = numpy.random.random(shape).astype(numpy.float32) if not os.path.isdir(self.tmp_dir): os.mkdir(self.tmp_dir) fd, self.edf1 = tempfile.mkstemp(".edf", "testAI1", self.tmp_dir) os.close(fd) fd, self.edf2 = tempfile.mkstemp(".edf", "testAI2", self.tmp_dir) os.close(fd) fabio.edfimage.edfimage(data=self.rnd1).write(self.edf1) fabio.edfimage.edfimage(data=self.rnd2).write(self.edf2) def tearDown(self): if os.path.exists(self.edf1): os.unlink(self.edf1) if os.path.exists(self.edf2): os.unlink(self.edf2) def test_flat(self): self.ai.set_flatfiles((self.edf1,self.edf2), method="mean") self.assert_(self.ai.flatfiles == "%s(%s,%s)" % ("mean", self.edf1, self.edf2), "flatfiles string is OK") self.assert_(abs(self.ai.flatfield-0.5*(self.rnd1+self.rnd2)).max() == 0, "Flat array is OK") def test_dark(self): self.ai.set_darkfiles((self.edf1, self.edf2), method="mean") self.assert_(self.ai.darkfiles == "%s(%s,%s)" % ("mean", self.edf1, self.edf2), "darkfiles string is OK") self.assert_(abs(self.ai.darkcurrent-0.5*(self.rnd1+self.rnd2)).max() == 0, "Dark array is OK")
class TestSetter(unittest.TestCase): def setUp(self): self.ai = AzimuthalIntegrator() shape = (10, 15) self.rnd1 = numpy.random.random(shape).astype(numpy.float32) self.rnd2 = numpy.random.random(shape).astype(numpy.float32) if not os.path.isdir(tmp_dir): os.mkdir(tmp_dir) fd, self.edf1 = tempfile.mkstemp(".edf", "testAI1", tmp_dir) os.close(fd) fd, self.edf2 = tempfile.mkstemp(".edf", "testAI2", tmp_dir) os.close(fd) fabio.edfimage.edfimage(data=self.rnd1).write(self.edf1) fabio.edfimage.edfimage(data=self.rnd2).write(self.edf2) def tearDown(self): recursive_delete(tmp_dir) def test_flat(self): self.ai.set_flatfiles((self.edf1, self.edf2), method="mean") self.assert_(self.ai.flatfiles == "%s(%s,%s)" % ("mean", self.edf1, self.edf2), "flatfiles string is OK") self.assert_(abs(self.ai.flatfield - 0.5 * (self.rnd1 + self.rnd2)).max() == 0, "Flat array is OK") def test_dark(self): self.ai.set_darkfiles((self.edf1, self.edf2), method="mean") self.assert_(self.ai.darkfiles == "%s(%s,%s)" % ("mean", self.edf1, self.edf2), "darkfiles string is OK") self.assert_(abs(self.ai.darkcurrent - 0.5 * (self.rnd1 + self.rnd2)).max() == 0, "Dark array is OK")
def __init__(self, data, dist=1, poni1=None, poni2=None, rot1=0, rot2=0, rot3=0, pixel1=None, pixel2=None, splineFile=None, detector=None, wavelength=None, dSpacing=None): """ @param data: ndarray float64 shape = n, 3 col0: pos in dim0 (in pixels) col1: pos in dim1 (in pixels) col2: ring index in dSpacing file @param dist: guessed sample-detector distance (optional, in m) @param poni1: guessed PONI coordinate along the Y axis (optional, in m) @param poni2: guessed PONI coordinate along the X axis (optional, in m) @param rot1: guessed tilt of the detector around the Y axis (optional, in rad) @param rot2: guessed tilt of the detector around the X axis (optional, in rad) @param rot3: guessed tilt of the detector around the incoming beam axis (optional, in rad) @param pixel1: Pixel size along the vertical direction of the detector (in m), almost mandatory @param pixel2: Pixel size along the horizontal direction of the detector (in m), almost mandatory @param splineFile: file describing the detector as 2 cubic splines. Replaces pixel1 & pixel2 @param detector: name of the detector or Detector instance. Replaces splineFile, pixel1 & pixel2 @param wavelength: wavelength in m (1.54e-10) @param dSpacing: filename or list or array or vector containing the d-spacing (in Angstrom) """ self.data = numpy.array(data, dtype="float64") assert self.data.ndim == 2 assert self.data.shape[1] == 3 assert self.data.shape[0]>0 if (pixel1 is None) and (pixel2 is None) and (splineFile is None) and (detector is None): raise RuntimeError("Setting up the geometry refinement without knowing the detector makes little sense") AzimuthalIntegrator.__init__(self, dist, 0, 0, rot1, rot2, rot3, pixel1, pixel2, splineFile, detector, wavelength=wavelength) if (poni1 is None) or (poni2 is None): self.guess_poni() else: self.poni1 = float(poni1) self.poni2 = float(poni2) self._dist_min = 0 self._dist_max = 10 self._poni1_min = -10000 * self.pixel1 self._poni1_max = 15000 * self.pixel1 self._poni2_min = -10000 * self.pixel2 self._poni2_max = 15000 * self.pixel2 self._rot1_min = -pi self._rot1_max = pi self._rot2_min = -pi self._rot2_max = pi self._rot3_min = -pi self._rot3_max = pi self._wavelength_min = 1e-15 self._wavelength_max = 100.e-10 if dSpacing is not None: if type(dSpacing) in types.StringTypes: self.dSpacing = numpy.loadtxt(dSpacing) else: self.dSpacing = numpy.array(dSpacing, dtype=numpy.float64) else: self.dSpacing = numpy.array([])
def diff_Fit2D(self, axis="all", dx=0.1): """ ??? @param axis: ??? @type axis: ??? @param dx: ??? @type dx: ??? @return: ??? @rtype: ??? """ tth, I = self.ai.xrpd(self.img, max(self.shape)) dI = SGModule.getSavitzkyGolay(I, npoints=5, degree=2, order=1) / (tth[1] - tth[0]) dImg = self.reconstruct(tth, dI) f = self.ai.getFit2D() tth2d_ref = self.ai.twoThetaArray(self.shape) # useless variable ??? keys = ["centerX", "centerY", "tilt", "tiltPlanRotation"] if axis != "all": keys = [i for i in keys if i == axis] grad = {} for key in keys: fp = f.copy() fp[key] += dx ap = AzimuthalIntegrator() ap.setFit2D(**fp) dtth = (ap.twoThetaArray(self.shape) - self.ai.twoThetaArray(self.shape)) / dx grad[key] = (dtth * dImg).sum() if axis == "all": return grad else: return grad[axis]
def scan_tilt(self, width=1.0, points=10): """ ??? @param width: ??? @type width: float ??? @param points: ??? @type points: int ??? @return: ??? @rtype: ??? """ f = self.ai.getFit2D() out = [] for x in numpy.linspace(f["tilt"] - width / 2.0, f["tilt"] + width / 2.0, points): ax = AzimuthalIntegrator() fx = f.copy() fx["tilt"] = x ax.setFit2D(**fx) # print ax ref = Refinment2D(self.img, ax) res = ref.diff_tth_tilt() print "x= %.3f mean= %e" % (x, res) out.append(res) return numpy.linspace(f["tilt"] - width / 2.0, f["tilt"] + width / 2.0, points), out
def scan_Fit2D(self, width=1.0, points=10, axis="tilt", dx=0.1): """ ??? @param width: ??? @type width: float ??? @param points: ??? @type points: int ??? @param axis: ??? @type axis: str ??? @param dx: ??? @type dx: float ??? @return: ??? @rtype: ??? """ logger.info("Scanning along axis %s" % axis) f = self.ai.getFit2D() out = [] meas_pts = numpy.linspace(f[axis] - width / 2.0, f[axis] + width / 2.0, points) for x in meas_pts: ax = AzimuthalIntegrator() fx = f.copy() fx[axis] = x ax.setFit2D(**fx) ref = Refinment2D(self.img, ax) res = ref.diff_Fit2D(axis=axis, dx=dx) print("x= %.3f mean= %e" % (x, res)) out.append(res) return meas_pts, out
def setUp(self): # defining geometry image_shape = [2048, 2048] # pixel detector_distance = 200 # mm wavelength = 0.31 # angstrom center_x = 1024 # pixel center_y = 1024 # pixel self.tilt = 0 # degree self.rotation = 0 # degree pixel_size = 79 # um dummy_tth = np.linspace(0, 35, 2000) dummy_int = np.ones(dummy_tth.shape) self.geometry = AzimuthalIntegrator() self.geometry.setFit2D(directDist=detector_distance, centerX=center_x, centerY=center_y, tilt=self.tilt, tiltPlanRotation=self.rotation, pixelX=pixel_size, pixelY=pixel_size) self.geometry.wavelength = wavelength / 1e10 self.dummy_img = self.geometry.calcfrom1d(dummy_tth, dummy_int, shape=image_shape, correctSolidAngle=True) self.tth_array = self.geometry.twoThetaArray(image_shape) self.azi_array = self.geometry.chiArray(image_shape)
def diff_Fit2D(self, axis="all", dx=0.1): """ ??? @param axis: ??? @type axis: ??? @param dx: ??? @type dx: ??? @return: ??? @rtype: ??? """ tth, I = self.ai.xrpd(self.img, max(self.shape)) dI = SGModule.getSavitzkyGolay(I, npoints=5, degree=2, order=1)\ / (tth[1] - tth[0]) dImg = self.reconstruct(tth, dI) f = self.ai.getFit2D() tth2d_ref = self.ai.twoThetaArray(self.shape) # useless variable ??? keys = ["centerX", "centerY", "tilt", "tiltPlanRotation"] if axis != "all": keys = [i for i in keys if i == axis] grad = {} for key in keys: fp = f.copy() fp[key] += dx ap = AzimuthalIntegrator() ap.setFit2D(**fp) dtth = (ap.twoThetaArray(self.shape) - self.ai.twoThetaArray(self.shape)) / dx grad[key] = (dtth * dImg).sum() if axis == "all": return grad else: return grad[axis]
def scan_tilt(self, width=1.0, points=10): """ ??? @param width: ??? @type width: float ??? @param points: ??? @type points: int ??? @return: ??? @rtype: ??? """ f = self.ai.getFit2D() out = [] for x in numpy.linspace(f["tilt"] - width / 2.0, f["tilt"] + width / 2.0, points): ax = AzimuthalIntegrator() fx = f.copy() fx["tilt"] = x ax.setFit2D(**fx) # print ax ref = Refinment2D(self.img, ax) res = ref.diff_tth_tilt() print("x= %.3f mean= %e" % (x, res)) out.append(res) return numpy.linspace(f["tilt"] - width / 2.0, f["tilt"] + width / 2.0, points), out
def load_from_h5(self, file): """Loads data from hdf5 file and sets attributes. args: file: h5py file or group object returns: None """ with self.file_lock: with self.arch_lock: if str(self.idx) not in file: print("No data can be found") grp = file[str(self.idx)] lst_attr = [ "map_raw", "mask", "map_norm", "map_q", "xyz", "tcr", "qchi", "scan_info", "ai_args" ] pawstools.h5_to_attributes(self, grp, lst_attr) pawstools.h5_to_attributes(self.int_1d, grp['int_1d']) pawstools.h5_to_attributes(self.int_2d, grp['int_2d']) self.poni = PONI.from_yamdict(pawstools.h5_to_dict( grp['poni'])) self.integrator = AzimuthalIntegrator( dist=self.poni.dist, poni1=self.poni.poni1, poni2=self.poni.poni2, rot1=self.poni.rot1, rot2=self.poni.rot2, rot3=self.poni.rot3, wavelength=self.poni.wavelength, detector=self.poni.detector, **self.ai_args)
def _update_integrator(self): if self._integrator is None: self._integrator = AzimuthalIntegrator(dist=self._sample_dist, pixel1=self._pixel1, pixel2=self._pixel2, poni1=self._poni1, poni2=self._poni2, rot1=0, rot2=0, rot3=0, wavelength=self._wavelength) else: if self._integrator.dist != self._sample_dist \ or self._integrator.wavelength != self._wavelength \ or self._integrator.poni1 != self._poni1 \ or self._integrator.poni2 != self._poni2: # dist, poni1, poni2, rot1, rot2, rot3, wavelength self._integrator.set_param( (self._sample_dist, self._poni1, self._poni2, 0, 0, 0, self._wavelength)) try: # 1/nm -> 1/A self._q_map = 0.1 * self._integrator._cached_array["q_center"] except KeyError: pass return self._integrator
def _update_integrator(self): constant = 1e-3 * constants.c * constants.h / constants.e self._wavelength = constant / self._ai_params["energy"] self._distance = self._ai_params["distance"] self._poni1 = \ self._ai_params["centery"] * self._ai_params["pixel_size"] self._poni2 = \ self._ai_params["centerx"] * self._ai_params["pixel_size"] if self._ai_integrator is None: self._ai_integrator = AzimuthalIntegrator( dist=self._ai_params["distance"], pixel1=self._ai_params["pixel_size"], pixel2=self._ai_params["pixel_size"], poni1=self._poni1, poni2=self._poni2, rot1=0, rot2=0, rot3=0, wavelength=self._wavelength) else: if self._ai_integrator.dist != self._distance \ or self._ai_integrator.wavelength != self._wavelength \ or self._ai_integrator.poni1 != self._poni1 \ or self._ai_integrator.poni2 != self._poni2: self._ai_integrator.set_param( (self._distance, self._poni1, self._poni2, 0, 0, 0, self._wavelength)) return self._ai_integrator
def setUp(self): """Download files""" self.fit2dFile = UtilsTest.getimage(self.__class__.fit2dFile) self.halfFrelon = UtilsTest.getimage(self.__class__.halfFrelon) self.splineFile = UtilsTest.getimage(self.__class__.splineFile) poniFile = UtilsTest.getimage(self.__class__.poniFile) with open(poniFile) as f: data = [] for line in f: if line.startswith("SplineFile:"): data.append("SplineFile: " + self.splineFile) else: data.append(line.strip()) self.poniFile = os.path.join(self.tmp_dir, os.path.basename(poniFile)) if not os.path.isdir(self.tmp_dir): os.makedirs(self.tmp_dir) with open(self.poniFile, "w") as f: f.write(os.linesep.join(data)) self.fit2d = numpy.loadtxt(self.fit2dFile) self.ai = AzimuthalIntegrator() self.ai.load(self.poniFile) self.data = fabio.open(self.halfFrelon).data for tmpfile in self.tmpfiles.values(): if os.path.isfile(tmpfile): os.unlink(tmpfile)
def set_geometry(distance: float = 1, center_x: float = 0, center_y: float = 0, tilt: float = 0.0, tilt_plane_rotation: float = 0.0): ai = AzimuthalIntegrator() ai.setFit2D(distance, center_x, center_y, tilt, tilt_plane_rotation) return ai
def setup_calibration(self, calib): """set up calibration from calibration dict""" if self.image.rot90 in (1, 3): calib['rot3'] = np.pi / 2.0 self.calib = calib if HAS_PYFAI: self.integrator = AzimuthalIntegrator(**calib) self.show1d_btn.Enable()
def update_ai(self, center=None, nbins=1000): if center is None: center = self.center ai = AzimuthalIntegrator(detector=self.detector, dist=self.distance) ai.setFit2D(self.distance * 1000, center[0], center[1]) ai.wavelength = self.wavelength * 1e-10 return ai
def setUp(self): self.edfPilatus = UtilsTest.getimage(self.__class__.saxsPilatus) self.maskFile = UtilsTest.getimage(self.__class__.maskFile) self.poniFile = UtilsTest.getimage(self.__class__.poniFile) self.maskRef = UtilsTest.getimage(self.__class__.maskRef) self.maskDummy = UtilsTest.getimage(self.__class__.maskDummy) self.ai = AzimuthalIntegrator() self.ai.load(self.poniFile) if not os.path.isdir(self.tmp_dir): os.mkdir(self.tmp_dir)
def run(self): ai = AzimuthalIntegrator(dist=self.__distance, poni1=self.__poni1, poni2=self.__poni2, rot1=self.__rotation1, rot2=self.__rotation2, rot3=self.__rotation3, detector=self.__detector, wavelength=self.__wavelength) # FIXME error model, method self.__result1d = ai.integrate1d( data=self.__image, npt=self.__nPointsRadial, unit=self.__radialUnit, mask=self.__mask, polarization_factor=self.__polarizationFactor) self.__result2d = ai.integrate2d( data=self.__image, npt_rad=self.__nPointsRadial, npt_azim=self.__nPointsAzimuthal, unit=self.__radialUnit, mask=self.__mask, polarization_factor=self.__polarizationFactor) try: self.__directDist = ai.getFit2D()["directDist"] except Exception: # The geometry could not fit this param _logger.debug("Backtrace", exc_info=True) self.__directDist = None if self.__calibrant: rings = self.__calibrant.get_2th() try: rings = utils.from2ThRad(rings, self.__radialUnit, self.__wavelength, self.__directDist) except ValueError: message = "Convertion to unit %s not supported. Ring marks ignored" _logger.warning(message, self.__radialUnit) rings = [] # Filter the rings which are not part of the result rings = filter( lambda x: self.__result1d.radial[0] <= x <= self.__result1d. radial[-1], rings) rings = list(rings) else: rings = [] self.__ringAngles = rings self.__ai = ai
def test_get_extent(self): dect = Detector(pixel1=1e-4, pixel2=1e-4) ai = AzimuthalIntegrator(detector=dect, dist=0.1) ai.setFit2D(directDist=1000, centerX=50.5, centerY=50.5) extent = _get_radial_extent(ai=ai, shape=(100, 100), unit="2th_rad") max_rad = 50 * np.sqrt(2) calc_extent = np.arctan(max_rad * 1e-4 / 1) np.testing.assert_almost_equal( extent[1], calc_extent, )
def azimuthal_integrate( z, origin, detector_distance, detector, wavelength, size_1d, unit, kwargs_for_integrator, kwargs_for_integrate1d, ): """Calculate the azimuthal integral of z around a determined origin. This method is used for signals where the origin is iterated, compared to azimuthal_integrate_fast which is used when the origin in the data is constant. Parameters ---------- z : np.array() Two-dimensional data array containing the signal. origin : np.array() A size 2 numpy array containing the position of the origin. detector_distance : float Detector distance in meters passed to pyFAI AzimuthalIntegrator. detector : pyFAI.detectors.Detector object A pyFAI detector used for the AzimuthalIntegrator. wavelength : float The electron wavelength in meters. Used by pyFAI AzimuthalIntegrator. size_1d : int The size of the returned 1D signal. (i.e. number of pixels in the 1D azimuthal integral.) unit : str The unit for for PyFAI integrate1d. *args : Arguments to be passed to AzimuthalIntegrator. **kwargs : Keyword arguments to be passed to AzimuthalIntegrator. Returns ------- tth : np.array() One-dimensional scattering vector axis of z. I : np.array() One-dimensional azimuthal integral of z. """ p1, p2 = origin[0] * detector.pixel1, origin[1] * detector.pixel2 ai = AzimuthalIntegrator(dist=detector_distance, poni1=p1, poni2=p2, detector=detector, wavelength=wavelength, **kwargs_for_integrator) tth, I = ai.integrate1d(z, size_1d, unit=unit, **kwargs_for_integrate1d) return tth, I
def addDevice(self, device): if device: try: self.setSilence(True) devicechild = DeviceParameter(device) self.addChild(devicechild) ai = AzimuthalIntegrator(wavelength=self['Wavelength']) ai.detector = detectors.Pilatus2M() self.AIs[device] = ai self.multiAI.ais = list(self.AIs.values()) finally: self.setSilence(False)
def __init__(self, img, ai=None): """ @param img: raw image we are working on @type img: ndarray @param ai: azimuhal integrator we are working on @type ai: pyFAI.azimuthalIntegrator.AzimutalIntegrator """ self.img = img if ai is None: self.ai = AzimuthalIntegrator() else: self.ai = ai
def q_conversion_gisaxs(integrator: AzimuthalIntegrator, data: np.ndarray) -> np.ndarray: chi = integrator.chiArray() twotheta = integrator.twoThetaArray() # TODO: Doble check what is chi = 0 q_x = 2 * np.pi / integrator.getvalue('Wavelength') * np.sin( twotheta) * np.sin(chi) q_z = 2 * np.pi / integrator.getvalue('Wavelength') * np.sin( twotheta) * np.cos(chi) return q_x, q_z
def openPoniFile(self, file=None): """ Select and imports the calibration file """ if file is None: self.poniFile = QFileDialog.getOpenFileName( self, 'Select calibration file', directory=self.curDir, filter='Calibration file (*.poni)')[0] self.poniFileLineEdit.setText(self.poniFile) else: self.poniFile = file if os.path.exists(self.poniFile): self.setup_dict['poniFile'] = self.poniFile json.dump(self.setup_dict, open('./SetupData/reducer_setup.txt', 'w')) fh = open(self.poniFile, 'r') lines = fh.readlines() self.calib_data = {} for line in lines: if line[0] != '#': key, val = line.split(': ') self.calib_data[key] = float(val) self.dist = self.calib_data['Distance'] self.pixel1 = self.calib_data['PixelSize1'] self.pixel2 = self.calib_data['PixelSize2'] self.poni1 = self.calib_data['Poni1'] self.poni2 = self.calib_data['Poni2'] self.rot1 = self.calib_data['Rot1'] self.rot2 = self.calib_data['Rot2'] self.rot3 = self.calib_data['Rot3'] self.wavelength = self.calib_data['Wavelength'] self.ai = AzimuthalIntegrator(dist=self.dist, poni1=self.poni1, poni2=self.poni2, pixel1=self.pixel1, pixel2=self.pixel2, rot1=self.rot1, rot2=self.rot2, rot3=self.rot3, wavelength=self.wavelength) #pos=[self.poni2/self.pixel2,self.poni1/self.pixel1] #self.roi=cake(pos,movable=False) #self.roi.sigRegionChangeStarted.connect(self.endAngleChanged) #self.imageView.addItem(self.roi) else: QMessageBox.warning( self, 'File error', 'The calibration file ' + self.poniFile + ' doesnot exists.', QMessageBox.Ok)
class TestAzimPilatus(unittest.TestCase): img = UtilsTest.getimage("1884/Pilatus6M.cbf") def setUp(self): """Download files""" self.data = fabio.open(self.img).data self.ai = AzimuthalIntegrator(detector="pilatus6m") self.ai.setFit2D(300, 1326, 1303) def test_separate(self): maxi = self.data.max() mini = self.data.min() bragg, amorphous = self.ai.separate(self.data) self.assert_(amorphous.max()<bragg.max(), "bragg is more intense than amorphous")
class TestAzimPilatus(unittest.TestCase): img = UtilsTest.getimage("1884/Pilatus6M.cbf") def setUp(self): """Download files""" self.data = fabio.open(self.img).data self.ai = AzimuthalIntegrator(detector="pilatus6m") self.ai.setFit2D(300, 1326, 1303) def test_separate(self): bragg, amorphous = self.ai.separate(self.data) self.assert_(amorphous.max() < bragg.max(), "bragg is more intense than amorphous") self.assert_(amorphous.std() < bragg.std(), "bragg is more variatic than amorphous")
def test_AzimuthalIntegrator_pickle(): import dill import numpy as np from pyFAI.azimuthalIntegrator import AzimuthalIntegrator det = pyFAI.detectors.detector_factory('pilatus2m') ai = AzimuthalIntegrator(detector=det) ai.set_wavelength(.1) spectra = ai.integrate1d(np.ones(det.shape), 1000) # force lut generation dump = dumps(ai) newai = loads(dump) assert np.array_equal(newai.integrate1d(np.ones(det.shape), 1000), spectra) assert newai.detector.shape == (1679, 1475)
def create_cake_geometry(self): self.cake_geometry = AzimuthalIntegrator() pyFAI_parameter = self.pattern_geometry.getPyFAI() pyFAI_parameter['wavelength'] = self.pattern_geometry.wavelength self.cake_geometry.setPyFAI(dist=pyFAI_parameter['dist'], poni1=pyFAI_parameter['poni1'], poni2=pyFAI_parameter['poni2'], rot1=pyFAI_parameter['rot1'], rot2=pyFAI_parameter['rot2'], rot3=pyFAI_parameter['rot3'], pixel1=pyFAI_parameter['pixel1'], pixel2=pyFAI_parameter['pixel2']) self.cake_geometry.wavelength = pyFAI_parameter['wavelength']
def naive_sdd(data: np.ndarray, mask: np.ndarray, calibrant: calibrant.Calibrant, azimuthal_integrator: AzimuthalIntegrator, npts: int = 2000) -> AzimuthalIntegrator: # Un-calibrated azimuthal integration r, radialprofile = azimuthal_integrator.integrate1d(data, npts, unit='r_mm', mask=mask) # find peaks peaks = np.array(find_peaks(np.arange(len(radialprofile)), radialprofile)).T # get best peak bestpeak = None for peak in peaks: if peak[0] > 15 and not np.isinf( peak[1] ): ####This thresholds the minimum sdd which is acceptable bestpeak = peak[0] # print peak break # identify order of selected peak best_order = (0, 0) for i in range(1, 6): peak_ratios = ((peaks[:, 0] / (np.arange(len(peaks)))) / (bestpeak / (i + 1))) order = np.sum(np.logical_and(peak_ratios < 1.1, 0.9 < peak_ratios)) if order > best_order[0]: best_order = (order, i) calibrant1stpeak = calibrant.dSpacing[best_order[1]] # Calculate sample to detector distance for lowest q peak tth = 2 * np.arcsin( 0.5 * azimuthal_integrator.wavelength / calibrant1stpeak / 1.e-10) tantth = np.tan(tth) sdd = r[int(round(bestpeak))] / tantth # set sdd back on azimuthal integrator fit2dcal = azimuthal_integrator.getFit2D() fit2dcal['directDist'] = sdd azimuthal_integrator.setFit2D(**fit2dcal) return azimuthal_integrator
def setUp(self): self.ai = AzimuthalIntegrator() shape = (10, 15) self.rnd1 = numpy.random.random(shape).astype(numpy.float32) self.rnd2 = numpy.random.random(shape).astype(numpy.float32) testdir = os.path.join(os.path.dirname(__file__), "tmp") if not os.path.isdir(testdir): os.makedirs(testdir) fd, self.edf1 = tempfile.mkstemp(".edf", "testAI1", testdir) os.close(fd) fd, self.edf2 = tempfile.mkstemp(".edf", "testAI2", testdir) os.close(fd) fabio.edfimage.edfimage(data=self.rnd1).write(self.edf1) fabio.edfimage.edfimage(data=self.rnd2).write(self.edf2)
def load(self, filename): """ Loads a calibration file and and sets all the calibration parameter. :param filename: filename for a *.poni calibration file """ self.pattern_geometry = AzimuthalIntegrator() self.pattern_geometry.load(filename) self.orig_pixel1 = self.pattern_geometry.pixel1 self.orig_pixel2 = self.pattern_geometry.pixel2 self.calibration_name = get_base_name(filename) self.filename = filename self.is_calibrated = True self.create_cake_geometry() self.set_supersampling()
def setUp(self): self.ai = AzimuthalIntegrator() shape = (10, 15) self.rnd1 = numpy.random.random(shape).astype(numpy.float32) self.rnd2 = numpy.random.random(shape).astype(numpy.float32) if not os.path.isdir(self.tmp_dir): os.mkdir(self.tmp_dir) fd, self.edf1 = tempfile.mkstemp(".edf", "testAI1", self.tmp_dir) os.close(fd) fd, self.edf2 = tempfile.mkstemp(".edf", "testAI2", self.tmp_dir) os.close(fd) fabio.edfimage.edfimage(data=self.rnd1).write(self.edf1) fabio.edfimage.edfimage(data=self.rnd2).write(self.edf2)
def setUp(self): """Download files""" self.fit2dFile = UtilsTest.getimage(self.__class__.fit2dFile) self.halfFrelon = UtilsTest.getimage(self.__class__.halfFrelon) self.splineFile = UtilsTest.getimage(self.__class__.splineFile) poniFile = UtilsTest.getimage(self.__class__.poniFile) with open(poniFile) as f: data = [] for line in f: if line.startswith("SplineFile:"): data.append("SplineFile: " + self.splineFile) else: data.append(line.strip()) self.poniFile = os.path.join(self.tmp_dir, os.path.basename(poniFile)) with open(self.poniFile, "w") as f: f.write(os.linesep.join(data)) self.fit2d = numpy.loadtxt(self.fit2dFile) self.ai = AzimuthalIntegrator() self.ai.load(self.poniFile) self.data = fabio.open(self.halfFrelon).data if not os.path.isdir(self.tmp_dir): os.makedirs(self.tmp_dir) for tmpfile in self.tmpfiles.values(): if os.path.isfile(tmpfile): os.unlink(tmpfile)
def image_test_rings(): rings = 10 mod = 50 detector = detector_factory("Titan") sigma = detector.pixel1 * 4 shape = detector.max_shape ai = AzimuthalIntegrator(detector=detector) ai.setFit2D(1000, 1000, 1000) r = ai.rArray(shape) r_max = r.max() chi = ai.chiArray(shape) img = numpy.zeros(shape) modulation = (1 + numpy.sin(5 * r + chi * mod)) for radius in numpy.linspace(0, r_max, rings): img += numpy.exp(-(r - radius) ** 2 / (2 * (sigma * sigma))) return img * modulation
def __init__(self, img_model=None): """ :param img_model: :type img_model: ImgModel """ self.img_model = img_model self.points = [] self.points_index = [] self.spectrum_geometry = AzimuthalIntegrator() self.cake_geometry = None self.calibrant = Calibrant() self.start_values = {'dist': 200e-3, 'wavelength': 0.3344e-10, 'pixel_width': 79e-6, 'pixel_height': 79e-6, 'polarization_factor': 0.99} self.orig_pixel1 = 79e-6 self.orig_pixel2 = 79e-6 self.fit_wavelength = False self.fit_distance = True self.is_calibrated = False self.use_mask = False self.filename = '' self.calibration_name = 'None' self.polarization_factor = 0.99 self.supersampling_factor = 1 self._calibrants_working_dir = os.path.dirname(calibrants.__file__) self.cake_img = np.zeros((2048, 2048)) self.tth = np.linspace(0, 25) self.int = np.sin(self.tth) self.num_points = len(self.int) self.peak_search_algorithm = None
class ObliqueAngleDetectorAbsorptionCorrectionTest(unittest.TestCase): def setUp(self): # defining geometry image_shape = [2048, 2048] # pixel detector_distance = 200 # mm wavelength = 0.31 # angstrom center_x = 1024 # pixel center_y = 1024 # pixel self.tilt = 0 # degree self.rotation = 0 # degree pixel_size = 79 # um dummy_tth = np.linspace(0, 35, 2000) dummy_int = np.ones(dummy_tth.shape) self.geometry = AzimuthalIntegrator() self.geometry.setFit2D(directDist=detector_distance, centerX=center_x, centerY=center_y, tilt=self.tilt, tiltPlanRotation=self.rotation, pixelX=pixel_size, pixelY=pixel_size) self.geometry.wavelength = wavelength / 1e10 self.dummy_img = self.geometry.calcfrom1d(dummy_tth, dummy_int, shape=image_shape, correctSolidAngle=True) self.tth_array = self.geometry.twoThetaArray(image_shape) self.azi_array = self.geometry.chiArray(image_shape) def tearDown(self): del self.azi_array del self.tth_array del self.dummy_img del self.geometry gc.collect() def test_that_it_is_correctly_calculating(self): oblique_correction = ObliqueAngleDetectorAbsorptionCorrection( tth_array=self.tth_array, azi_array=self.azi_array, detector_thickness=40, absorption_length=465.5, tilt=self.tilt, rotation=self.rotation ) oblique_correction_data = oblique_correction.get_data() self.assertGreater(np.sum(oblique_correction_data), 0) self.assertEqual(oblique_correction_data.shape, self.dummy_img.shape) del oblique_correction
class CbnCorrectionTest(unittest.TestCase): def setUp(self): # defining geometry image_shape = [2048, 2048] # pixel detector_distance = 200 # mm wavelength = 0.31 # angstrom center_x = 1024 # pixel center_y = 1024 # pixel tilt = 0 # degree rotation = 0 # degree pixel_size = 79 # um dummy_tth = np.linspace(0, 35, 2000) dummy_int = np.ones(dummy_tth.shape) self.geometry = AzimuthalIntegrator() self.geometry.setFit2D(directDist=detector_distance, centerX=center_x, centerY=center_y, tilt=tilt, tiltPlanRotation=rotation, pixelX=pixel_size, pixelY=pixel_size) self.geometry.wavelength = wavelength / 1e10 self.dummy_img = self.geometry.calcfrom1d(dummy_tth, dummy_int, shape=image_shape, correctSolidAngle=True) self.tth_array = self.geometry.twoThetaArray(image_shape) self.azi_array = self.geometry.chiArray(image_shape) def tearDown(self): del self.tth_array del self.azi_array del self.dummy_img del self.geometry gc.collect() def test_that_it_is_calculating_correctly(self): cbn_correction = CbnCorrection(self.tth_array, self.azi_array, diamond_thickness=2.2, seat_thickness=5.3, small_cbn_seat_radius=0.4, large_cbn_seat_radius=1.95, tilt=0, tilt_rotation=0) cbn_correction.update() cbn_correction_data = cbn_correction.get_data() self.assertGreater(np.sum(cbn_correction_data), 0) self.assertEqual(cbn_correction_data.shape, self.dummy_img.shape)
def test_splitBBox(self): data = numpy.ones((2000, 2000), dtype="float64") ai = AzimuthalIntegrator(0.1, 1e-2, 1e-2, pixel1=1e-5, pixel2=1e-5) I = ai.xrpd2_splitBBox(data, 2048, 2048, correctSolidAngle=False, dummy= -1.0)[0] # I = ai.xrpd2(data, 2048, 2048, correctSolidAngle=False, dummy= -1.0) if logger.getEffectiveLevel() == logging.DEBUG: logging.info("Plotting results") fig = pylab.figure() fig.suptitle('cacking of a flat image: SplitBBox') sp = fig.add_subplot(111) sp.imshow(I, interpolation="nearest") fig.show() raw_input("Press enter to quit") I[I == -1.0] = 1.0 assert abs(I.min() - 1.0) < self.epsilon assert abs(I.max() - 1.0) < self.epsilon
def setup_calibration(self, calib): """set up calibration from calibration dict""" if self.image.rot90 in (1, 3): calib['rot3'] = np.pi/2.0 self.calib = calib if HAS_PYFAI: self.integrator = AzimuthalIntegrator(**calib) self.show1d_btn.Enable()
def run(self): ai = AzimuthalIntegrator( dist=self.__distance, poni1=self.__poni1, poni2=self.__poni2, rot1=self.__rotation1, rot2=self.__rotation2, rot3=self.__rotation3, detector=self.__detector, wavelength=self.__wavelength) numberPoint1D = 1024 numberPointRadial = 400 numberPointAzimuthal = 360 # FIXME error model, method self.__result1d = ai.integrate1d( data=self.__image, npt=numberPoint1D, unit=self.__radialUnit, mask=self.__mask, polarization_factor=self.__polarizationFactor) self.__result2d = ai.integrate2d( data=self.__image, npt_rad=numberPointRadial, npt_azim=numberPointAzimuthal, unit=self.__radialUnit, mask=self.__mask, polarization_factor=self.__polarizationFactor) if self.__calibrant: rings = self.__calibrant.get_2th() rings = filter(lambda x: x <= self.__result1d.radial[-1], rings) rings = list(rings) try: rings = utils.from2ThRad(rings, self.__radialUnit, self.__wavelength, ai) except ValueError: message = "Convertion to unit %s not supported. Ring marks ignored" _logger.warning(message, self.__radialUnit) rings = [] else: rings = [] self.__ringAngles = rings
def __init__(self, data, dist=1, poni1=None, poni2=None, rot1=0, rot2=0, rot3=0, pixel1=None, pixel2=None, splineFile=None, detector=None, wavelength=None, dSpacing=None): """ @param data: ndarray float64 shape = n, 3 col0: pos in dim0 (in pixels) col1: pos in dim1 (in pixels) col2: associated tth value (in rad) @param detector: name of the detector or Detector instance. """ self.data = numpy.array(data, dtype="float64") AzimuthalIntegrator.__init__(self, dist, 0, 0, rot1, rot2, rot3, pixel1, pixel2, splineFile, detector, wavelength=wavelength) if (poni1 is None) or (poni2 is None): self.guess_poni() else: self.poni1 = float(poni1) self.poni2 = float(poni2) self._dist_min = 0 self._dist_max = 10 self._poni1_min = -10000 * self.pixel1 self._poni1_max = 15000 * self.pixel1 self._poni2_min = -10000 * self.pixel2 self._poni2_max = 15000 * self.pixel2 self._rot1_min = -pi self._rot1_max = pi self._rot2_min = -pi self._rot2_max = pi self._rot3_min = -pi self._rot3_max = pi self._wavelength_min = 1e-15 self._wavelength_max = 100.e-10 if dSpacing is not None: if type(dSpacing) in types.StringTypes: self.dSpacing = numpy.loadtxt(dSpacing) else: self.dSpacing = numpy.array(dSpacing, dtype=numpy.float64) else: self.dSpacing = numpy.array([])
def load(self, filename): self.spectrum_geometry = AzimuthalIntegrator() self.spectrum_geometry.load(filename) self.orig_pixel1 = self.spectrum_geometry.pixel1 self.orig_pixel2 = self.spectrum_geometry.pixel2 self.calibration_name = get_base_name(filename) self.filename = filename self.is_calibrated = True self.create_cake_geometry() self.set_supersampling()
def image_test_rings(): "Creating a test image containing gaussian spots on several rings" rings = 10 mod = 50 detector = detector_factory("Titan") sigma = detector.pixel1 * 4 shape = detector.max_shape ai = AzimuthalIntegrator(detector=detector) ai.setFit2D(1000, 1000, 1000) r = ai.rArray(shape) r_max = r.max() chi = ai.chiArray(shape) img = numpy.zeros(shape) modulation = (1 + numpy.sin(5 * r + chi * mod)) for radius in numpy.linspace(0, r_max, rings): img += numpy.exp(-(r - radius) ** 2 / (2 * (sigma * sigma))) img *= modulation img = add_noise(img, 0.0) return img
def load(self, filename): """ Loads a calibration file and and sets all the calibration parameter. :param filename: filename for a *.poni calibration file """ self.spectrum_geometry = AzimuthalIntegrator() self.spectrum_geometry.load(filename) self.orig_pixel1 = self.spectrum_geometry.pixel1 self.orig_pixel2 = self.spectrum_geometry.pixel2 self.calibration_name = get_base_name(filename) self.filename = filename self.is_calibrated = True self.create_cake_geometry() self.set_supersampling()
def setup_calibration(self, ponifile): """set up calibration from PONI file""" calib = read_poni(ponifile) # if self.image.rot90 in (1, 3): # calib['rot3'] = np.pi/2.0 self.calib = calib if HAS_PYFAI: self.integrator = AzimuthalIntegrator(**calib) self.show1d_btn.Enable() else: self.write('Warning: PyFAI is not installed') if self.scandb is not None: _, calname = os.path.split(ponifile) self.scandb.set_detectorconfig(calname, json.dumps(calib)) self.scandb.set_info('xrd_calibration', calname)
def setUp(self): unittest.TestCase.setUp(self) self.data = fabio.open(UtilsTest.getimage("1788/moke.tif")).data self.lst_data = [self.data[:250, :300], self.data[250:, :300], self.data[:250, 300:], self.data[250:, 300:]] self.det = Detector(1e-4, 1e-4) self.det.max_shape = (500, 600) self.sub_det = Detector(1e-4, 1e-4) self.sub_det.max_shape = (250, 300) self.ai = AzimuthalIntegrator(0.1, 0.03, 0.03, detector=self.det) self.range = (0, 23) self.ais = [AzimuthalIntegrator(0.1, 0.030, 0.03, detector=self.sub_det), AzimuthalIntegrator(0.1, 0.005, 0.03, detector=self.sub_det), AzimuthalIntegrator(0.1, 0.030, 0.00, detector=self.sub_det), AzimuthalIntegrator(0.1, 0.005, 0.00, detector=self.sub_det), ] self.mg = MultiGeometry(self.ais, radial_range=self.range, unit="2th_deg") self.N = 390
def calibrate(self): self.spectrum_geometry = GeometryRefinement(self.create_point_array(self.points, self.points_index), dist=self.start_values['dist'], wavelength=self.start_values['wavelength'], pixel1=self.start_values['pixel_width'], pixel2=self.start_values['pixel_height'], calibrant=self.calibrant) self.orig_pixel1 = self.start_values['pixel_width'] self.orig_pixel2 = self.start_values['pixel_height'] self.refine() self.create_cake_geometry() self.is_calibrated = True self.calibration_name = 'current' self.set_supersampling() # reset the integrator (not the geometric parameters) self.spectrum_geometry.reset()