Exemplo n.º 1
0
def optimize_with_new_images(h5file: File,
                             calibration: Calibration,
                             gonioref,
                             calibrant: pyFAI.calibrant.Calibrant,
                             indexes: Iterable[int],
                             pts_per_deg: float = 1) -> None:
    """This function adds new images to the pool of data used for the
    refinement.  A set of new control points are extractred and a
    refinement step is performed at each iteration The last image of
    the serie is displayed

    """
    sg = None
    for frame in gen_metadata_idx(h5file, calibration, indexes):
        print()
        if frame.label in gonioref.single_geometries:
            continue
        print(frame.label)
        sg = gonioref.new_geometry(frame.label,
                                   image=frame.image,
                                   metadata=frame,
                                   calibrant=calibrant)
        print(sg.extract_cp(pts_per_deg=pts_per_deg))
    print("*" * 50)
    gonioref.refine2()
    if sg:
        sg.geometry_refinement.set_param(
            gonioref.get_ai(sg.get_position()).param)  # noqa
        jupyter.display(sg=sg)
Exemplo n.º 2
0
def optimize_with_new_images(h5file: File,
                             calibration: Calibration,
                             gonioref,
                             calibrant: pyFAI.calibrant.Calibrant,
                             pts_per_deg: float=1) -> None:
    """This function adds new images to the pool of data used for the
    refinement.  A set of new control points are extractred and a
    refinement step is performed at each iteration The last image of
    the serie is displayed

    """
    sg = None
    for n, frame in enumerate(gen_metadata_all(h5file, calibration)):
        print()
        base = os.path.splitext(os.path.basename(calibration.filename))[0]

        label = base + "_%d" % (frame.idx,)
        if label in gonioref.single_geometries:
            continue
        print(label)
        sg = gonioref.new_geometry(label, image=frame.image, metadata=frame,
                                   calibrant=calibrant)
        print(sg.extract_cp(pts_per_deg=pts_per_deg))
    print("*"*50)
    gonioref.refine2()
    if sg:
        sg.geometry_refinement.set_param(gonioref.get_ai(sg.get_position()).param)  # noqa
        jupyter.display(sg=sg)
Exemplo n.º 3
0
def optimize_with_new_images(h5file: File,
                             calibration: Calibration,
                             gonioref,
                             calibrant: pyFAI.calibrant.Calibrant,
                             pts_per_deg: float = 1) -> None:
    """This function adds new images to the pool of data used for the
    refinement.  A set of new control points are extractred and a
    refinement step is performed at each iteration The last image of
    the serie is displayed

    """
    sg = None
    for _, frame in enumerate(gen_metadata_all(h5file, calibration)):
        print()
        base = os.path.splitext(os.path.basename(calibration.filename))[0]

        label = base + "_%d" % (frame.idx, )
        if label in gonioref.single_geometries:
            continue
        print(label)
        sg = gonioref.new_geometry(label,
                                   image=frame.image,
                                   metadata=frame,
                                   calibrant=calibrant)
        print(sg.extract_cp(pts_per_deg=pts_per_deg))
    print("*" * 50)
    gonioref.refine2()
    if sg:
        sg.geometry_refinement.set_param(
            gonioref.get_ai(sg.get_position()).param)  # noqa
        jupyter.display(sg=sg)
Exemplo n.º 4
0
    def show_pyfai_improvement(
        self,
        before_geometry: pfSingleGeometry,
        after_geometry: pfSingleGeometry,
        show: bool = True,
    ):
        fig, (ax1, ax2) = plt.subplots(1, 2)
        fig.set_size_inches(20, 8)
        pfjupyter.display(sg=before_geometry, label="Initial geometry", ax=ax1)
        pfjupyter.display(sg=after_geometry, label="After pyFAI fit", ax=ax2)

        if show:
            plt.show()
        else:
            fig.savefig(self.user_args.pyfai_improvement, bbox_inches="tight")
            plt.close(fig)
Exemplo n.º 5
0
def optimize_with_new_images_mars_tx_tz(h5file: File,
                                        calibration: CalibrationMarsTxTz,
                                        gonioref,
                                        calibrant: pyFAI.calibrant.Calibrant,
                                        indexes: Iterable[int],
                                        pts_per_deg: float = 1) -> None:
    """This function adds new images to the pool of data used for the
    refinement.  A set of new control points are extractred and a
    refinement step is performed at each iteration The last image of
    the serie is displayed

    """
    sg = None
    for frame in gen_metadata_idx_mars_tx_tz(h5file, calibration, indexes):
        print()
        if frame.label in gonioref.single_geometries:
            continue
        print(frame.label)
        sg = gonioref.new_geometry(frame.label,
                                   image=frame.image,
                                   metadata=frame,
                                   calibrant=calibrant)
        print(
            sg.extract_cp(max_rings=calibration.max_rings,
                          pts_per_deg=pts_per_deg))

        # filter the cp to remove unwanted values.
        cp = sg.control_points
        cp.pop(0)

        sg.geometry_refinement.data = numpy.asarray(cp.getList(),
                                                    dtype=numpy.float64)
        sg.control_points = cp

    print("*" * 50)
    gonioref.refine2()
    if sg:
        sg.geometry_refinement.set_param(
            gonioref.get_ai(sg.get_position()).param)  # noqa
        jupyter.display(sg=sg)
Exemplo n.º 6
0
 def set_up_figure(self):
     """
     Add title and label axes
     """
     fig, ax = plt.subplots()
     ax = pfjupyter.display(
         self.image,
         label="Calibrant overlay on experimental image",
         ax=ax,
     )
     ax.set_xlabel("slow position [pixels]")
     ax.set_ylabel("fast position [pixels]")
     fig.set_size_inches(10, 10)
     return fig, ax
Exemplo n.º 7
0
def calibration(json: str,
                params: Calibration,
                indexes: Optional[Iterable[int]] = None) -> None:
    """Do a calibration with a bunch of images"""

    # Definition of the geometry refinement: the parameter order is
    # the same as the param_names
    calibrant = get_calibrant(params.calibrant, params.wavelength)
    detector = get_detector(params.detector)

    (functions, initial_parameters) = params.functions
    parameters = {p.name: p.value for p in initial_parameters}
    bounds = {p.name: p.bounds for p in initial_parameters}
    param_names = [p.name for p in initial_parameters]

    # Let's refine poni1 and poni2 also as function of the distance:

    trans_function = GeometryTransformation(param_names=param_names,
                                            pos_names=["delta"],
                                            dist_expr=functions.distance,
                                            poni1_expr=functions.poni1,
                                            poni2_expr=functions.poni2,
                                            rot1_expr=functions.rot1,
                                            rot2_expr=functions.rot2,
                                            rot3_expr=functions.rot3)

    def pos_function(frame: CalibrationFrame) -> Tuple[float]:
        """Definition of the function reading the detector position from the
        header of the image."""
        return (frame.delta, )

    gonioref = GoniometerRefinement(
        parameters,  # initial guess
        bounds=bounds,
        pos_function=pos_function,
        trans_function=trans_function,
        detector=detector,
        wavelength=params.wavelength)

    print("Empty refinement object:")
    print(gonioref)

    # Let's populate the goniometer refinement object with the know poni

    with File(params.filename, mode='r') as h5file:
        for frame in gen_metadata_idx(h5file, params, params.idxs):
            base = os.path.basename(params.filename)
            control_points = os.path.join(
                params.basedir, base + "_{:02d}.npt".format(frame.idx))  # noqa
            ai = pyFAI.load(
                os.path.join(params.basedir,
                             base + "_{:02d}.poni".format(frame.idx)))  # noqa
            print(ai)

            gonioref.new_geometry(frame.label, frame.image, frame,
                                  control_points, calibrant, ai)

        print("Filled refinement object:")
        print(gonioref)
        print(os.linesep + "\tlabel \t tx")
        for k, v in gonioref.single_geometries.items():
            print(k, v.get_position())

        for g in gonioref.single_geometries.values():
            ai = gonioref.get_ai(g.get_position())
            print(ai)

        for sg in gonioref.single_geometries.values():
            jupyter.display(sg=sg)

        gonioref.refine2()

    for multi in [params]:
        with File(multi.filename, mode='r') as h5file:
            optimize_with_new_images(h5file,
                                     multi,
                                     gonioref,
                                     calibrant,
                                     indexes,
                                     pts_per_deg=10)

    for idx, sg in enumerate(gonioref.single_geometries.values()):
        sg.geometry_refinement.set_param(
            gonioref.get_ai(sg.get_position()).param)  # noqa
        jupyter.display(sg=sg)

    gonioref.save(json)
Exemplo n.º 8
0
def calibration(json: str, params: Calibration) -> None:
    """Do a calibration with a bunch of images"""

    # Definition of the geometry refinement: the parameter order is
    # the same as the param_names
    calibrant = get_calibrant(params.calibrant,
                              params.wavelength)
    detector = get_detector(params.detector)

    parameters = {p.name: p.value for p in params.initial_parameters}
    bounds = {p.name: p.bounds for p in params.initial_parameters}
    param_names = [p.name for p in params.initial_parameters]

    # Let's refine poni1 and poni2 also as function of the distance:

    trans_function = GeometryTransformation(param_names=param_names,
                                            pos_names=["delta"],
                                            dist_expr="dist",
                                            poni1_expr="poni1",  # noqa
                                            poni2_expr="poni2",  # noqa
                                            rot1_expr="rot1",
                                            rot2_expr="rot2_scale * delta + rot2_offset",  # noqa
                                            rot3_expr="rot3")

    def pos_function(frame: CalibrationFrame) -> Tuple[float]:
        """Definition of the function reading the detector position from the
        header of the image."""
        return (frame.delta,)

    gonioref = GoniometerRefinement(parameters,  # initial guess
                                    bounds=bounds,
                                    pos_function=pos_function,
                                    trans_function=trans_function,
                                    detector=detector,
                                    wavelength=params.wavelength)

    print("Empty refinement object:")
    print(gonioref)

    # Let's populate the goniometer refinement object with the know poni

    with File(params.filename, mode='r') as h5file:
        for frame in gen_metadata_idx(h5file, params):
            base = os.path.splitext(os.path.basename(params.filename))[0]

            label = base + "_%d" % (frame.idx,)
            control_points = params.filename + "_{:02d}.npt".format(frame.idx)
            ai = pyFAI.load(params.filename + "_{:02d}.poni".format(frame.idx))
            print(ai)

            gonioref.new_geometry(label, frame.image, frame,
                                  control_points, calibrant, ai)

        print("Filled refinement object:")
        print(gonioref)
        print(os.linesep + "\tlabel \t tx")
        for k, v in gonioref.single_geometries.items():
            print(k, v.get_position())

        for g in gonioref.single_geometries.values():
            ai = gonioref.get_ai(g.get_position())
            print(ai)

        for sg in gonioref.single_geometries.values():
            jupyter.display(sg=sg)

        gonioref.refine2()

    for multi in [params]:
        with File(multi.filename, mode='r') as h5file:
            optimize_with_new_images(h5file, multi, gonioref, calibrant)

    for idx, sg in enumerate(gonioref.single_geometries.values()):
        sg.geometry_refinement.set_param(gonioref.get_ai(sg.get_position()).param)  # noqa
        jupyter.display(sg=sg)

    gonioref.save(json)
import time
from matplotlib.pyplot import subplots
from pyFAI.gui import jupyter
import pyFAI
import fabio
from pyFAI.test.utilstest import UtilsTest
from pyFAI.calibrant import CALIBRANT_FACTORY
from pyFAI.goniometer import SingleGeometry
print(pyFAI.version)
start_time = time.perf_counter()
# %%
# In this example, we will re-use one of the image used int the test-suite
filename = '/Users/rbelisle/Desktop/LaB6_det315_3s_01221009_0001.tif'
frame = fabio.open(filename).data
# and now display the image
ax = jupyter.display(frame)
# %%
# This allow to measure approximatively the position of the beam center ...
x = 1500  # x-coordinate of the beam-center in pixels
y = 2750  # y-coordinate of the beam-center in pixels
d = 315  # This is the distance in mm (unit used by Fit2d)
wl = 0.9762e-10  # The wavelength is 1 Å
# %%
# Definition of the detector and of the calibrant:
pilatus = pyFAI.detectors.Detector(pixel1=73.242e-6,
                                   pixel2=73.242e-6,
                                   max_shape=(.225, .225))
behenate = CALIBRANT_FACTORY("LaB6")
behenate.wavelength = wl
behenate
# %%