Exemplo n.º 1
0
    def __call__(self, imageset):
        """
        Override the parameters
        """
        from dxtbx.imageset import ImageSequence, ImageSetFactory
        from dxtbx.model import BeamFactory
        from dxtbx.model import DetectorFactory
        from dxtbx.model import GoniometerFactory
        from dxtbx.model import ScanFactory
        from copy import deepcopy

        if self.params.geometry.convert_sequences_to_stills:
            imageset = ImageSetFactory.imageset_from_anyset(imageset)
            for j in imageset.indices():
                imageset.set_scan(None, j)
                imageset.set_goniometer(None, j)
        if not isinstance(imageset, ImageSequence):
            if self.params.geometry.convert_stills_to_sequences:
                imageset = self.convert_stills_to_sequence(imageset)
        if isinstance(imageset, ImageSequence):
            beam = BeamFactory.from_phil(self.params.geometry, imageset.get_beam())
            detector = DetectorFactory.from_phil(
                self.params.geometry, imageset.get_detector(), beam
            )
            goniometer = GoniometerFactory.from_phil(
                self.params.geometry, imageset.get_goniometer()
            )
            scan = ScanFactory.from_phil(
                self.params.geometry, deepcopy(imageset.get_scan())
            )
            i0, i1 = scan.get_array_range()
            j0, j1 = imageset.get_scan().get_array_range()
            if i0 < j0 or i1 > j1:
                imageset = self.extrapolate_imageset(
                    imageset=imageset,
                    beam=beam,
                    detector=detector,
                    goniometer=goniometer,
                    scan=scan,
                )
            else:
                imageset.set_beam(beam)
                imageset.set_detector(detector)
                imageset.set_goniometer(goniometer)
                imageset.set_scan(scan)
        else:
            for i in range(len(imageset)):
                beam = BeamFactory.from_phil(self.params.geometry, imageset.get_beam(i))
                detector = DetectorFactory.from_phil(
                    self.params.geometry, imageset.get_detector(i), beam
                )
                goniometer = GoniometerFactory.from_phil(
                    self.params.geometry, imageset.get_goniometer(i)
                )
                scan = ScanFactory.from_phil(self.params.geometry, imageset.get_scan(i))
                imageset.set_beam(beam, i)
                imageset.set_detector(detector, i)
                imageset.set_goniometer(goniometer, i)
                imageset.set_scan(scan, i)
        return imageset
Exemplo n.º 2
0
  def __call__(self, imageset):
    '''
    Override the parameters

    '''
    from dxtbx.imageset import ImageSet
    from dxtbx.imageset import ImageSweep
    from dxtbx.model import BeamFactory
    from dxtbx.model import DetectorFactory
    from dxtbx.model import GoniometerFactory
    from dxtbx.model import ScanFactory
    from copy import deepcopy
    if self.params.geometry.convert_sweeps_to_stills:
      imageset = ImageSet(reader=imageset.reader())
    if not isinstance(imageset, ImageSweep):
      if self.params.geometry.convert_stills_to_sweeps:
        imageset = self.convert_stills_to_sweep(imageset)
    if isinstance(imageset, ImageSweep):
      beam = BeamFactory.from_phil(
        self.params.geometry,
        imageset.get_beam())
      detector = DetectorFactory.from_phil(
        self.params.geometry,
        imageset.get_detector(),
        beam)
      goniometer = GoniometerFactory.from_phil(
        self.params.geometry,
        imageset.get_goniometer())
      scan = ScanFactory.from_phil(
        self.params.geometry,
        deepcopy(imageset.get_scan()))
      i0, i1 = scan.get_array_range()
      j0, j1 = imageset.get_scan().get_array_range()
      imageset.set_beam(beam)
      imageset.set_detector(detector)
      imageset.set_goniometer(goniometer)
      imageset.set_scan(scan)
    else:
      for i in range(len(imageset)):
        beam = BeamFactory.from_phil(
          self.params.geometry,
          imageset.get_beam(i))
        detector = DetectorFactory.from_phil(
          self.params.geometry,
          imageset.get_detector(i),
          beam)
        goniometer = GoniometerFactory.from_phil(
          self.params.geometry,
          imageset.get_goniometer(i))
        scan = ScanFactory.from_phil(
          self.params.geometry,
          imageset.get_scan(i))
        imageset.set_beam(beam, i)
        imageset.set_detector(detector, i)
        imageset.set_goniometer(goniometer, i)
        imageset.set_scan(scan, i)
    return imageset
Exemplo n.º 3
0
def imagesweep_from_dict(d, check_format=True, directory=None):
    """Construct and image sweep from the dictionary."""
    # Get the template (required)
    template = load_path(str(d["template"]), directory=directory)

    # If the scan isn't set, find all available files
    scan_dict = d.get("scan")
    if scan_dict is None:
        image_range = None
    else:
        image_range = scan_dict.get("image_range")

    # Set the models with the exisiting models as templates
    beam = BeamFactory.from_dict(d.get("beam"))
    goniometer = GoniometerFactory.from_dict(d.get("goniometer"))
    detector = DetectorFactory.from_dict(d.get("detector"))
    scan = ScanFactory.from_dict(d.get("scan"))

    # Construct the sweep
    try:
        sweep = ImageSetFactory.from_template(
            template,
            image_range,
            beam=beam,
            detector=detector,
            goniometer=goniometer,
            scan=scan,
            check_format=check_format,
        )[0]
    except Exception:
        indices = range(image_range[0], image_range[1] + 1)
        sweep = ImageSetFactory.make_sweep(
            template,
            indices,
            beam=beam,
            detector=detector,
            goniometer=goniometer,
            scan=scan,
            check_format=check_format,
        )

    # Set some external lookups
    if "mask" in d and d["mask"] is not None and d["mask"] is not "":
        path = load_path(d["mask"], directory=directory)
        with open(path) as infile:
            sweep.external_lookup.mask.filename = path
            sweep.external_lookup.mask.data = ImageBool(pickle.load(infile))
    if "gain" in d and d["gain"] is not None and d["gain"] is not "":
        path = load_path(d["gain"], directory=directory)
        with open(path) as infile:
            sweep.external_lookup.gain.filename = path
            sweep.external_lookup.gain.data = ImageDouble(pickle.load(infile))
    if "pedestal" in d and d["pedestal"] is not None and d["pedestal"] is not "":
        path = load_path(d["pedestal"], directory=directory)
        with open(path) as infile:
            sweep.external_lookup.pedestal.filename = path
            sweep.external_lookup.pedestal.data = ImageDouble(pickle.load(infile))

    # Return the sweep
    return sweep
Exemplo n.º 4
0
 def detector(self):
     # monolithic camera description
     pixsize = self.pixel_size_mm
     im_shape = self.detpixels_fastslow
     fdet = self.fdet_vector
     sdet = self.sdet_vector
     origin = self.dials_origin_mm
     det_descr = {
         'panels': [{
             'fast_axis': fdet,
             'slow_axis': sdet,
             'gain': self.quantum_gain,
             'identifier': '',
             'image_size': im_shape,
             'mask': [],
             'material': '',  # TODO
             'mu': 0.0,  # TODO
             'name': 'Panel',
             'origin': origin,
             'pedestal': 0.0,
             'pixel_size': (pixsize, pixsize),
             'px_mm_strategy': {
                 'type': 'SimplePxMmStrategy'
             },
             'raw_image_offset': (0, 0),  # TODO
             'thickness': 0.0,  # TODO
             'trusted_range': (-1e3, 1e10),  # TODO
             'type': ''
         }]
     }
     detector = DetectorFactory.from_dict(det_descr)
     return detector
Exemplo n.º 5
0
def basic_imageset_from_dict(d):
    ''' Construct an ImageSet class from the dictionary.'''
    from dxtbx.model import BeamFactory, DetectorFactory
    from dxtbx.imageset import ImageSetFactory
    from dxtbx.serialize.filename import load_path

    # Get the filename list and create the imageset
    filenames = map(lambda p: load_path(p), map(str, d['filenames']))
    imageset = ImageSetFactory.new(filenames)[0]

    # Set some external lookups
    if 'mask' in d and d['mask'] is not None:
        with open(d['mask']) as infile:
            imageset.external_lookup.mask.filename = d['mask']
            imageset.external_lookup.mask.data = pickle.load(infile)
    if 'gain' in d and d['gain'] is not None:
        with open(d['gain']) as infile:
            imageset.external_lookup.gain.filename = d['gain']
            imageset.external_lookup.gain.data = pickle.load(infile)
    if 'pedestal' in d and d['pedestal'] is not None:
        with open(d['pedestal']) as infile:
            imageset.external_lookup.pedestal.filename = d['pedestal']
            imageset.external_lookup.pedestal.data = pickle.load(infile)

    # Get the existing models as dictionaries
    beam_dict = imageset.get_beam().to_dict()
    detector_dict = imageset.get_detector().to_dict()

    # Set models
    imageset.set_beam(BeamFactory.from_dict(d.get('beam'), beam_dict))
    imageset.set_detector(
        DetectorFactory.from_dict(d.get('detector'), detector_dict))

    # Return the imageset
    return imageset
Exemplo n.º 6
0
  def __init__(self, filename, experiment, HKL, i_sigi, measurements, params):
    from libtbx import adopt_init_args
    adopt_init_args(self, locals())
    self.stash_type = None
    self.stash_res_filter = None

    from dxtbx.model import DetectorFactory
    self.dummy_detector = DetectorFactory.simple(
      sensor = DetectorFactory.sensor("PAD"),
      distance = 100,
      beam_centre = [1000, 1000],
      fast_direction = "+x",
      slow_direction = "+y",
      pixel_size = [0.2,0.2],
      image_size = [2000,2000],
      )
Exemplo n.º 7
0
def experiment():
    beam = BeamFactory.make_beam(wavelength=0.97625, sample_to_source=(0, 0, 1))

    detector = DetectorFactory.simple(
        sensor="PAD",
        distance=265.27,
        beam_centre=(210.7602, 205.27684),
        fast_direction="+x",
        slow_direction="-y",
        pixel_size=(0.172, 0.172),
        image_size=(2463, 2527),
        trusted_range=(-1, 1e8),
    )

    goniometer = GoniometerFactory.single_axis()

    scan = ScanFactory.make_scan(
        image_range=(1, 20),
        exposure_times=0.067,
        oscillation=(82, 0.15),
        epochs=[0] * 20,
    )

    isetdata = ImageSetData(
        reader=Format.Reader(None, ["path"] * len(scan)), masker=None
    )
    iset = ImageSequence(
        isetdata, beam=beam, detector=detector, goniometer=goniometer, scan=scan
    )

    return Experiment(
        imageset=iset, beam=beam, detector=detector, goniometer=goniometer, scan=scan
    )
Exemplo n.º 8
0
def basic_imageset_from_dict(d, directory=None):
    """ Construct an ImageSet class from the dictionary."""
    # Get the filename list and create the imageset
    filenames = map(
        lambda p: load_path(p, directory=directory), map(str, d["filenames"])
    )
    imageset = ImageSetFactory.new(filenames)[0]

    # Set some external lookups
    if "mask" in d and d["mask"] is not None and d["mask"] is not "":
        path = load_path(d["mask"], directory=directory)
        with open(path) as infile:
            imageset.external_lookup.mask.filename = path
            imageset.external_lookup.mask.data = ImageBool(pickle.load(infile))
    if "gain" in d and d["gain"] is not None and d["gain"] is not "":
        path = load_path(d["gain"], directory=directory)
        with open(path) as infile:
            imageset.external_lookup.gain.filename = path
            imageset.external_lookup.gain.data = ImageDouble(pickle.load(infile))
    if "pedestal" in d and d["pedestal"] is not None and d["pedestal"] is not "":
        path = load_path(d["pedestal"], directory=directory)
        with open(path) as infile:
            imageset.external_lookup.pedestal.filename = path
            imageset.external_lookup.pedestal.data = ImageDouble(pickle.load(infile))

    # Get the existing models as dictionaries
    beam_dict = imageset.get_beam(0).to_dict()
    detector_dict = imageset.get_detector(0).to_dict()

    # Set models
    imageset.set_beam(BeamFactory.from_dict(d.get("beam"), beam_dict))
    imageset.set_detector(DetectorFactory.from_dict(d.get("detector"), detector_dict))

    # Return the imageset
    return imageset
    def __init__(self):
        # Let's say we have a scan of 100 images
        self.image_range = (1, 100)

        # Make a random P1 crystal
        a = random.uniform(10,50) * \
            self.random_direction_close_to(matrix.col((1, 0, 0)))
        b = random.uniform(10,50) * \
            self.random_direction_close_to(matrix.col((0, 1, 0)))
        c = random.uniform(10,50) * \
            self.random_direction_close_to(matrix.col((0, 0, 1)))
        self.xl = Crystal(a, b, c, space_group_symbol="P 1")

        # Make a beam with wavelength in the range 0.8--1.2 and s0 direction close
        # to 0,0,1
        s0 = random.uniform(0.8, 1.2) * \
            self.random_direction_close_to(matrix.col((0, 0, 1)))
        self.beam = Beam(s0)

        # Make a standard goniometer model along X
        self.goniometer = Goniometer((1, 0, 0))

        # Make a simple single panel detector
        d1 = matrix.col((1, 0, 0))
        d2 = matrix.col((0, -1, 0))
        npx_fast = 1475
        npx_slow = 1679
        pix_size_f = pix_size_s = 0.172
        from dxtbx.model import DetectorFactory
        self.detector = DetectorFactory.make_detector("PAD", d1, d2,
                                                      matrix.col((0, 0, -110)),
                                                      (pix_size_f, pix_size_s),
                                                      (npx_fast, npx_slow),
                                                      (0, 2e20))
    def __init__(self, test_nave_model=False):
        # Set up experimental models with regular geometry
        from dxtbx.model import BeamFactory, DetectorFactory, GoniometerFactory

        # Beam along the Z axis
        self.beam = BeamFactory.make_beam(unit_s0=matrix.col((0, 0, 1)), wavelength=1.0)

        # Goniometer (used only for index generation) along X axis
        self.goniometer = GoniometerFactory.known_axis(matrix.col((1, 0, 0)))

        # Detector fast, slow along X, -Y; beam in the centre, 200 mm distance
        dir1 = matrix.col((1, 0, 0))
        dir2 = matrix.col((0, -1, 0))
        centre = matrix.col((0, 0, 200))
        npx_fast = npx_slow = 1000
        pix_size = 0.2
        origin = centre - (
            0.5 * npx_fast * pix_size * dir1 + 0.5 * npx_slow * pix_size * dir2
        )
        self.detector = DetectorFactory.make_detector(
            "PAD",
            dir1,
            dir2,
            origin,
            (pix_size, pix_size),
            (npx_fast, npx_slow),
            (0, 1.0e6),
        )

        # Cubic 100 A^3 crystal
        a = matrix.col((100, 0, 0))
        b = matrix.col((0, 100, 0))
        c = matrix.col((0, 0, 100))

        if test_nave_model:
            from dxtbx.model import MosaicCrystalSauter2014

            self.crystal = MosaicCrystalSauter2014(a, b, c, space_group_symbol="P 1")
            self.crystal.set_half_mosaicity_deg(500)
            self.crystal.set_domain_size_ang(0.2)
        else:
            from dxtbx.model import Crystal

            self.crystal = Crystal(a, b, c, space_group_symbol="P 1")

        # Collect these models in an Experiment (ignoring the goniometer)
        from dxtbx.model.experiment_list import Experiment

        self.experiment = Experiment(
            beam=self.beam,
            detector=self.detector,
            goniometer=None,
            scan=None,
            crystal=self.crystal,
            imageset=None,
        )

        # Generate some reflections
        self.reflections = self.generate_reflections()
Exemplo n.º 11
0
    def __init__(self, override_fdp=None):

        # Set up detector
        distance = 100
        pixel_size = 0.1
        image_size = (1000, 1000)
        beam_centre_mm = (
            pixel_size * image_size[0] / 2,
            pixel_size * image_size[1] / 2,
        )
        self.detector = DetectorFactory().simple(
            "CCD",
            distance,
            beam_centre_mm,
            "+x",
            "-y",
            (pixel_size, pixel_size),
            image_size,
        )

        # Set up beam
        self.beam = BeamFactory().simple(wavelength=1)

        # Set up scan
        sequence_width = 90.0
        osc_start = 0.0
        image_width = 0.2
        oscillation = (osc_start, image_width)

        nframes = int(math.ceil(sequence_width / image_width))
        image_range = (1, nframes)
        exposure_times = 0.0
        epochs = [0] * nframes
        self.scan = ScanFactory().make_scan(image_range,
                                            exposure_times,
                                            oscillation,
                                            epochs,
                                            deg=True)

        # Set up goniometer
        self.goniometer = GoniometerFactory.known_axis(
            self.detector[0].get_fast_axis())

        # Set up simulated structure factors
        self.sfall = self.fcalc_from_pdb(resolution=1.6,
                                         algorithm="direct",
                                         override_fdp=override_fdp)

        # Set up crystal
        self.crystal = Crystal(
            real_space_a=(50, 0, 0),
            real_space_b=(0, 60, 0),
            real_space_c=(0, 0, 70),
            space_group_symbol="P1",
        )
        axis = matrix.col(elems=(-0.14480368275412925, -0.6202131724405818,
                                 -0.7709523423610766))
        self.crystal.set_U(
            axis.axis_and_angle_as_r3_rotation_matrix(angle=0.625126343998969))
Exemplo n.º 12
0
def imagesweep_from_dict(d, check_format=True):
    '''Construct and image sweep from the dictionary.'''
    from dxtbx.imageset import ImageSetFactory
    from dxtbx.model import BeamFactory, DetectorFactory, GoniometerFactory, ScanFactory
    from dxtbx.serialize.filename import load_path

    # Get the template (required)
    template = load_path(str(d['template']))

    # If the scan isn't set, find all available files
    scan_dict = d.get('scan')
    if scan_dict is None:
        image_range = None
    else:
        image_range = scan_dict.get('image_range')

    # Set the models with the exisiting models as templates
    beam = BeamFactory.from_dict(d.get('beam'))
    goniometer = GoniometerFactory.from_dict(d.get('goniometer'))
    detector = DetectorFactory.from_dict(d.get('detector'))
    scan = ScanFactory.from_dict(d.get('scan'))

    # Construct the sweep
    try:
        sweep = ImageSetFactory.from_template(template,
                                              image_range,
                                              beam=beam,
                                              detector=detector,
                                              goniometer=goniometer,
                                              scan=scan,
                                              check_format=check_format)[0]
    except Exception:
        indices = range(image_range[0], image_range[1] + 1)
        sweep = ImageSetFactory.make_sweep(template,
                                           indices,
                                           beam=beam,
                                           detector=detector,
                                           goniometer=goniometer,
                                           scan=scan,
                                           check_format=check_format)

    # Set some external lookups
    if 'mask' in d and d['mask'] is not None and d['mask'] is not "":
        with open(d['mask']) as infile:
            sweep.external_lookup.mask.filename = d['mask']
            sweep.external_lookup.mask.data = ImageBool(pickle.load(infile))
    if 'gain' in d and d['gain'] is not None and d['gain'] is not "":
        with open(d['gain']) as infile:
            sweep.external_lookup.gain.filename = d['gain']
            sweep.external_lookup.gain.data = ImageDouble(pickle.load(infile))
    if 'pedestal' in d and d['pedestal'] is not None and d[
            'pedestal'] is not "":
        with open(d['pedestal']) as infile:
            sweep.external_lookup.pedestal.filename = d['pedestal']
            sweep.external_lookup.pedestal.data = ImageDouble(
                pickle.load(infile))

    # Return the sweep
    return sweep
Exemplo n.º 13
0
 def expt_detector_maker(self):
   """Construct the detector object for the experiments file. This function generates a monolithic flattening of the
   CSPAD detector if not supplied with an image file."""
   self.distance = self.data['distance']
   self.xbeam, self.ybeam = self.data['xbeam'], self.data['ybeam']
   if len(self.img_location) > 0 and not dxtbx.load(self.img_location[0])._image_file.endswith("_00000.pickle"):
     self.detector = dxtbx.load(self.img_location[0])._detector()
   else:
     self.detector = DetectorFactory.simple('SENSOR_UNKNOWN',self.distance,(self.xbeam, self.ybeam),'+x','-y',
     (self.pixel_size, self.pixel_size),(1765,1765))
Exemplo n.º 14
0
    def build_detector(self):

        assert self._params.detector.directions.method in ["close_to", "exactly"]

        if self._params.detector.directions.method == "close_to":

            temp = self._params.detector.directions.close_to.dir1
            dir1 = random_vector_close_to(
                temp, sd=self._params.detector.directions.close_to.sd
            )

            n = random_vector_close_to(
                self._params.detector.directions.close_to.norm,
                sd=self._params.detector.directions.close_to.sd,
            )

        elif self._params.detector.directions.method == "exactly":

            temp = self._params.detector.directions.exactly.dir1
            dir1 = matrix.col(temp)

            n = matrix.col(self._params.detector.directions.exactly.norm)

        dir2 = n.cross(dir1).normalize()

        assert self._params.detector.centre.method in ["close_to", "exactly"]

        if self._params.detector.centre.method == "close_to":

            centre = random_vector_close_to(
                self._params.detector.centre.close_to.value,
                sd=self._params.detector.centre.close_to.sd,
            )

        elif self._params.detector.centre.method == "exactly":

            temp = self._params.detector.centre.exactly.value
            centre = matrix.col(temp)

        origin = centre - (
            0.5 * self._params.detector.npx_fast * self._params.detector.pix_size * dir1
            + 0.5
            * self._params.detector.npx_slow
            * self._params.detector.pix_size
            * dir2
        )
        self.detector = DetectorFactory.make_detector(
            "PAD",
            dir1,
            dir2,
            origin,
            (self._params.detector.pix_size, self._params.detector.pix_size),
            (self._params.detector.npx_fast, self._params.detector.npx_slow),
            (0, 1.0e6),
        )
    def prepare_dxtbx_models(self, setting_specific_ai, sg, isoform=None):

        from dxtbx.model import BeamFactory
        beam = BeamFactory.simple(wavelength=self.inputai.wavelength)

        from dxtbx.model import DetectorFactory
        detector = DetectorFactory.simple(
            sensor=DetectorFactory.sensor("PAD"),
            distance=setting_specific_ai.distance(),
            beam_centre=[
                setting_specific_ai.xbeam(),
                setting_specific_ai.ybeam()
            ],
            fast_direction="+x",
            slow_direction="+y",
            pixel_size=[self.pixel_size, self.pixel_size],
            image_size=[self.inputpd['size1'], self.inputpd['size1']],
        )

        direct = matrix.sqr(
            setting_specific_ai.getOrientation().direct_matrix())
        from dxtbx.model import Crystal
        crystal = Crystal(
            real_space_a=matrix.row(direct[0:3]),
            real_space_b=matrix.row(direct[3:6]),
            real_space_c=matrix.row(direct[6:9]),
            space_group_symbol=sg,
        )
        crystal.set_mosaicity(setting_specific_ai.getMosaicity())
        if isoform is not None:
            newB = matrix.sqr(isoform.fractionalization_matrix()).transpose()
            crystal.set_B(newB)

        from dxtbx.model import Experiment, ExperimentList
        experiments = ExperimentList()
        experiments.append(
            Experiment(beam=beam, detector=detector, crystal=crystal))

        print beam
        print detector
        print crystal
        return experiments
Exemplo n.º 16
0
def import_geometry(xds_inp=None, dials_json=None):
    assert (xds_inp, dials_json).count(None) == 1

    geom_kwds = set([
        "DIRECTION_OF_DETECTOR_X-AXIS",
        "DIRECTION_OF_DETECTOR_Y-AXIS",
        "DETECTOR_DISTANCE",
        "ORGX",
        "ORGY",
        "ROTATION_AXIS",  # "X-RAY_WAVELENGTH",
        "INCIDENT_BEAM_DIRECTION",
        "SEGMENT",
        "DIRECTION_OF_SEGMENT_X-AXIS",
        "DIRECTION_OF_SEGMENT_Y-AXIS",
        "SEGMENT_DISTANCE",
        "SEGMENT_ORGX",
        "SEGMENT_ORGY"
    ])

    # FIXME in case of multi-segment detector..

    if xds_inp:
        inp = get_xdsinp_keyword(xds_inp)
        inp = filter(lambda x: x[0] in geom_kwds, inp)
        return map(lambda x: "%s= %s" % x, inp)
    elif dials_json:
        import dxtbx.imageset
        from dxtbx.serialize.load import _decode_dict
        from dxtbx.model import BeamFactory
        from dxtbx.model import DetectorFactory
        from dxtbx.model import GoniometerFactory
        from dxtbx.model import ScanFactory
        from dxtbx.serialize.xds import to_xds
        j = json.loads(open(dials_json).read(), object_hook=_decode_dict)
        # dummy
        sweep = dxtbx.imageset.ImageSetFactory.from_template(
            "####", image_range=[1, 1], check_format=False)[0]
        sweep.set_detector(DetectorFactory.from_dict(j["detector"][0]))
        sweep.set_beam(BeamFactory.from_dict(j["beam"][0]))
        sweep.set_goniometer(GoniometerFactory.from_dict(j["goniometer"][0]))
        sweep.set_scan(
            ScanFactory.make_scan(image_range=[1, 1],
                                  exposure_times=[1],
                                  oscillation=[1, 2],
                                  epochs=[0]))  # dummy
        sio = cStringIO.StringIO()
        to_xds(sweep).XDS_INP(sio)
        inp = get_xdsinp_keyword(inp_str=sio.getvalue())
        inp = filter(lambda x: x[0] in geom_kwds, inp)
        return map(lambda x: "%s= %s" % x, inp)

    return []
Exemplo n.º 17
0
def test_dps_single_panel_labelit_input_optimal_origin(process_dictionary,data,phil_set):
    from rstbx.indexing_api.lattice import DPS_primitive_lattice
    from scitbx.matrix import col

    sample_to_beamspot = col((0.,0.,float(process_dictionary['distance'])))
    detector_d1 = col((1., 0., 0.))
    detector_d2 = col((0., 1., 0.))
    detector_origin = sample_to_beamspot - \
      detector_d1 * float(process_dictionary['xbeam']) - \
      detector_d2 * float(process_dictionary['ybeam'])
    assert detector_d1.length() == 1.0
    assert detector_d2.length() == 1.0
    assert detector_d1.dot(detector_d2) == 0.0

    from dxtbx.model import DetectorFactory
    detector = DetectorFactory.make_detector(
      stype = "indexing",
      fast_axis = detector_d1,
      slow_axis = detector_d2,
      origin = detector_origin,
      pixel_size = (float(process_dictionary['pixel_size']),
                    float(process_dictionary['pixel_size'])),
      image_size = (int(process_dictionary['size1']),
                    int(process_dictionary['size2']))
      )

    beam_vector = sample_to_beamspot.normalize() * (
                  1./float(process_dictionary['wavelength']))
    rot_axis = col(process_dictionary["endstation"].rot_axi) - col((0.0,0.0,0.0)) # coerce to float type

    DPS = DPS_primitive_lattice(max_cell = float(process_dictionary['ref_maxcel']),
          recommended_grid_sampling_rad = process_dictionary['recommended_grid_sampling'],
          horizon_phil = phil_set)
    DPS.set_beam_vector(beam = -beam_vector)
    DPS.set_rotation_axis(axis = rot_axis)
    DPS.set_detector(detector)

    DPS.index(raw_spot_input = data)
    #L = DPS.get_basis_general() # can skip this first time around
    new_detector = DPS.optimize_origin_offset_local_scope()

    DPS2= DPS_primitive_lattice(max_cell = float(process_dictionary['ref_maxcel']),
        recommended_grid_sampling_rad = process_dictionary['recommended_grid_sampling'],
        horizon_phil = phil_set)
    DPS2.set_beam_vector(beam = -beam_vector)
    DPS2.set_rotation_axis(axis = rot_axis)
    DPS2.set_detector(new_detector)
    DPS2.index(raw_spot_input = data)
    L = DPS2.get_basis_general()
Exemplo n.º 18
0
 def load_models(obj):
   try:
     beam = BeamFactory.from_dict(blist[obj['beam']])
   except Exception:
     beam = None
   try:
     dobj = dlist[obj['detector']]
     detector = DetectorFactory.from_dict(dobj)
   except Exception:
     detector = None
   try:
     gonio = GoniometerFactory.from_dict(glist[obj['goniometer']])
   except Exception:
     gonio = None
   try:
     scan = ScanFactory.from_dict(slist[obj['scan']])
   except Exception:
     scan = None
   return beam, detector, gonio, scan
Exemplo n.º 19
0
def test():
    # set the random seed to make the test reproducible
    random.seed(1337)

    # set up a simple detector frame with directions aligned with
    # principal axes and sensor origin located on the z-axis at -110
    d1 = matrix.col((1, 0, 0))
    d2 = matrix.col((0, -1, 0))
    # lim = (0,50)
    npx_fast = 1475
    npx_slow = 1679
    pix_size_f = pix_size_s = 0.172
    detector = DetectorFactory.make_detector(
        "PAD",
        d1,
        d2,
        matrix.col((0, 0, -110)),
        (pix_size_f, pix_size_s),
        (npx_fast, npx_slow),
        (0, 2e20),
    )

    dp = DetectorParameterisationSinglePanel(detector)
    beam = BeamFactory().make_beam(
        sample_to_source=-1 * (matrix.col((0, 0, -110)) + 10 * d1 + 10 * d2),
        wavelength=1.0,
    )

    # Test change of parameters
    # =========================

    # 1. shift detector plane so that the z-axis intercepts its centre
    # at a distance of 100 along the initial normal direction. As the
    # initial normal is along -z, we expect the frame to intercept the
    # z-axis at -100.

    p_vals = dp.get_param_vals()
    p_vals[0:3] = [100.0, 0.0, 0.0]
    dp.set_param_vals(p_vals)
    detector = dp._model
    assert len(detector) == 1
    panel = detector[0]
    v1 = matrix.col(panel.get_origin())
    v2 = matrix.col((0.0, 0.0, 1.0))
    assert approx_equal(v1.dot(v2), -100.0)

    # 2. rotate frame around its initial normal by +90 degrees. Only d1
    # and d2 should change. As we rotate clockwise around the initial
    # normal (-z direction) then d1 should rotate onto the original
    # direction d2, and d2 should rotate to negative of the original
    # direction d1

    p_vals[3] = 1000.0 * pi / 2  # set tau1 value
    dp.set_param_vals(p_vals)

    detector = dp._model
    assert len(detector) == 1
    panel = detector[0]
    assert approx_equal(
        matrix.col(panel.get_fast_axis()).dot(dp._initial_state["d1"]), 0.0)
    assert approx_equal(
        matrix.col(panel.get_slow_axis()).dot(dp._initial_state["d2"]), 0.0)
    assert approx_equal(
        matrix.col(panel.get_normal()).dot(dp._initial_state["dn"]), 1.0)

    # 3. no rotation around initial normal, +10 degrees around initial
    # d1 direction and +10 degrees around initial d2. Check d1 and d2
    # match paper calculation

    p_vals[3] = 0.0  # tau1
    p_vals[4] = 1000.0 * pi / 18  # tau2
    p_vals[5] = 1000.0 * pi / 18  # tau3
    dp.set_param_vals(p_vals)

    # paper calculation values
    v1 = matrix.col((cos(pi / 18), 0, sin(pi / 18)))
    v2 = matrix.col((
        sin(pi / 18)**2,
        -cos(pi / 18),
        sqrt((2 * sin(pi / 36) * sin(pi / 18))**2 - sin(pi / 18)**4) -
        sin(pi / 18),
    ))

    detector = dp._model
    assert len(detector) == 1
    panel = detector[0]
    assert approx_equal(matrix.col(panel.get_fast_axis()).dot(v1), 1.0)
    assert approx_equal(matrix.col(panel.get_slow_axis()).dot(v2), 1.0)

    # 4. Test fixing and unfixing of parameters
    p_vals = [
        100.0, 0.0, 0.0, 1000.0 * pi / 18, 1000.0 * pi / 18, 1000.0 * pi / 18
    ]
    dp.set_param_vals(p_vals)
    f = dp.get_fixed()
    f[0:3] = [True] * 3
    dp.set_fixed(f)
    p_vals2 = [0.0, 0.0, 0.0]
    dp.set_param_vals(p_vals2)
    assert dp.get_param_vals(only_free=False) == [
        100.0, 0.0, 0.0, 0.0, 0.0, 0.0
    ]

    an_ds_dp = dp.get_ds_dp()
    assert len(an_ds_dp) == 3

    f[0:3] = [False] * 3
    dp.set_fixed(f)
    p_vals = dp.get_param_vals()
    p_vals2 = [a + b for a, b in zip(p_vals, [-10.0, 1.0, 1.0, 0.0, 0.0, 0.0])]
    dp.set_param_vals(p_vals2)
    assert dp.get_param_vals() == [90.0, 1.0, 1.0, 0.0, 0.0, 0.0]

    # 5. Tests of the calculation of derivatives

    # Now using parameterisation in mrad

    # random initial orientations with a random parameter shift at each
    attempts = 100
    for i in range(attempts):

        # create random initial position
        det = Detector(random_panel())
        dp = DetectorParameterisationSinglePanel(det)

        # apply a random parameter shift
        p_vals = dp.get_param_vals()
        p_vals = random_param_shift(
            p_vals,
            [10, 10, 10, 1000.0 * pi / 18, 1000.0 * pi / 18, 1000.0 * pi / 18])
        dp.set_param_vals(p_vals)

        # compare analytical and finite difference derivatives.
        an_ds_dp = dp.get_ds_dp(multi_state_elt=0)
        fd_ds_dp = get_fd_gradients(dp, [1.0e-6] * 3 + [1.0e-4 * pi / 180] * 3)

        for j in range(6):
            assert approx_equal(
                (fd_ds_dp[j] - an_ds_dp[j]),
                matrix.sqr((0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)),
                eps=1.0e-6,
            ), textwrap.dedent("""\
        Failure comparing analytical with finite difference derivatives.
        Failure in try {i}
        failure for parameter number {j}
        of the orientation parameterisation
        with fd_ds_dp =
        {fd}
        and an_ds_dp =
        {an}
        so that difference fd_ds_dp - an_ds_dp =
        {diff}
        """).format(i=i,
                    j=j,
                    fd=fd_ds_dp[j],
                    an=an_ds_dp[j],
                    diff=fd_ds_dp[j] - an_ds_dp[j])

    # 5. Test a multi-panel detector with non-coplanar panels.

    # place a beam at the centre of the single panel detector (need a
    # beam to initialise the multi-panel detector parameterisation)
    lim = det[0].get_image_size_mm()
    shift1 = lim[0] / 2.0
    shift2 = lim[1] / 2.0
    beam_centre = (matrix.col(det[0].get_origin()) +
                   shift1 * matrix.col(det[0].get_fast_axis()) +
                   shift2 * matrix.col(det[0].get_slow_axis()))
    beam = BeamFactory().make_beam(sample_to_source=-1.0 * beam_centre,
                                   wavelength=1.0)

    multi_panel_detector = make_multi_panel(det)

    # parameterise this detector
    dp = DetectorParameterisationMultiPanel(multi_panel_detector, beam)

    # ensure the beam still intersects the central panel
    intersection = multi_panel_detector.get_ray_intersection(beam.get_s0())
    assert intersection[0] == 4

    # record the offsets and dir1s, dir2s
    offsets_before_shift = dp._offsets
    dir1s_before_shift = dp._dir1s
    dir2s_before_shift = dp._dir2s

    # apply a random parameter shift (~10 mm distances, ~50 mrad angles)
    p_vals = dp.get_param_vals()
    p_vals = random_param_shift(p_vals, [10, 10, 10, 50, 50, 50])

    # reparameterise the detector
    dp = DetectorParameterisationMultiPanel(multi_panel_detector, beam)

    # record the offsets and dir1s, dir2s
    offsets_after_shift = dp._offsets
    dir1s_after_shift = dp._dir1s
    dir2s_after_shift = dp._dir2s

    # ensure the offsets, dir1s and dir2s are the same. This means that
    # each panel in the detector moved with the others as a rigid body
    for a, b in zip(offsets_before_shift, offsets_after_shift):
        assert approx_equal(a, b, eps=1.0e-10)

    for a, b in zip(dir1s_before_shift, dir1s_after_shift):
        assert approx_equal(a, b, eps=1.0e-10)

    for a, b in zip(dir2s_before_shift, dir2s_after_shift):
        assert approx_equal(a, b, eps=1.0e-10)

    attempts = 5
    for i in range(attempts):

        multi_panel_detector = make_multi_panel(det)

        # parameterise this detector
        dp = DetectorParameterisationMultiPanel(multi_panel_detector, beam)
        p_vals = dp.get_param_vals()

        # apply a random parameter shift
        p_vals = random_param_shift(
            p_vals,
            [10, 10, 10, 1000.0 * pi / 18, 1000.0 * pi / 18, 1000.0 * pi / 18])
        dp.set_param_vals(p_vals)

        # compare analytical and finite difference derivatives
        # get_fd_gradients will implicitly only get gradients for the
        # 1st panel in the detector, so explicitly get the same for the
        # analytical gradients

        for j in range(9):

            an_ds_dp = dp.get_ds_dp(multi_state_elt=j)
            fd_ds_dp = get_fd_gradients(dp, [1.0e-7] * dp.num_free(),
                                        multi_state_elt=j)

            for k in range(6):
                assert approx_equal(
                    (fd_ds_dp[k] - matrix.sqr(an_ds_dp[k])),
                    matrix.sqr((0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)),
                    eps=1.0e-5,
                    out=None,
                ), textwrap.dedent("""\
        Failure comparing analytical with finite difference derivatives.
        Failure in try {i}
        for panel number {j]
        failure for parameter number {k}
        of the orientation parameterisation
        with fd_ds_dp =
        {fd}
        and an_ds_dp =
        {an}
        so that difference fd_ds_dp - an_ds_dp =
        {diff}
        """).format(
                    i=i,
                    j=j,
                    k=k,
                    fd=fd_ds_dp[k],
                    an=an_ds_dp[k],
                    diff=fd_ds_dp[k] - matrix.sqr(an_ds_dp[k]),
                )
 def _detector_from_dict(obj):
     ''' Get the detector from a dictionary. '''
     from dxtbx.model import DetectorFactory
     return DetectorFactory.from_dict(obj)
Exemplo n.º 21
0
if __name__ == '__main__':

  # set the random seed to make the test reproducible
  random.seed(1337)

  # set up a simple detector frame with directions aligned with
  # principal axes and sensor origin located on the z-axis at -110
  d1 = matrix.col((1, 0, 0))
  d2 = matrix.col((0, -1, 0))
  #lim = (0,50)
  npx_fast = 1475
  npx_slow = 1679
  pix_size_f = pix_size_s = 0.172
  detector = DetectorFactory.make_detector("PAD", d1, d2,
      matrix.col((0, 0, -110)), (pix_size_f, pix_size_s),
      (npx_fast, npx_slow), (0, 2e20))

  dp = DetectorParameterisationSinglePanel(detector)
  beam = BeamFactory().make_beam(
          sample_to_source=-1*(matrix.col((0, 0, -110)) + 10 * d1 + 10 * d2),
          wavelength=1.0)

  # Test change of parameters
  # =========================

  # 1. shift detector plane so that the z-axis intercepts its centre
  # at a distance of 100 along the initial normal direction. As the
  # initial normal is along -z, we expect the frame to intercept the
  # z-axis at -100.
Exemplo n.º 22
0
    def __init__(self, params):
        import cPickle as pickle
        from dxtbx.model import BeamFactory
        from dxtbx.model import DetectorFactory
        from dxtbx.model.crystal import crystal_model
        from cctbx.crystal_orientation import crystal_orientation, basis_type
        from dxtbx.model import Experiment, ExperimentList
        from scitbx import matrix
        self.experiments = ExperimentList()
        self.unique_file_names = []

        self.params = params
        data = pickle.load(
            open(self.params.output.prefix + "_frame.pickle", "rb"))
        frames_text = data.split("\n")

        for item in frames_text:
            tokens = item.split(' ')
            wavelength = float(tokens[order_dict["wavelength"]])

            beam = BeamFactory.simple(wavelength=wavelength)

            detector = DetectorFactory.simple(
                sensor=DetectorFactory.sensor(
                    "PAD"),  # XXX shouldn't hard code for XFEL
                distance=float(tokens[order_dict["distance"]]),
                beam_centre=[
                    float(tokens[order_dict["beam_x"]]),
                    float(tokens[order_dict["beam_y"]])
                ],
                fast_direction="+x",
                slow_direction="+y",
                pixel_size=[self.params.pixel_size, self.params.pixel_size],
                image_size=[1795,
                            1795],  # XXX obviously need to figure this out
            )

            reciprocal_matrix = matrix.sqr([
                float(tokens[order_dict[k]]) for k in [
                    'res_ori_1', 'res_ori_2', 'res_ori_3', 'res_ori_4',
                    'res_ori_5', 'res_ori_6', 'res_ori_7', 'res_ori_8',
                    'res_ori_9'
                ]
            ])
            ORI = crystal_orientation(reciprocal_matrix, basis_type.reciprocal)
            direct = matrix.sqr(ORI.direct_matrix())
            crystal = crystal_model(
                real_space_a=matrix.row(direct[0:3]),
                real_space_b=matrix.row(direct[3:6]),
                real_space_c=matrix.row(direct[6:9]),
                space_group_symbol=self.params.target_space_group.type().
                lookup_symbol(),
                mosaicity=float(tokens[order_dict["half_mosaicity_deg"]]),
            )
            crystal.domain_size = float(tokens[order_dict["domain_size_ang"]])
            #if isoform is not None:
            #  newB = matrix.sqr(isoform.fractionalization_matrix()).transpose()
            #  crystal.set_B(newB)

            self.experiments.append(
                Experiment(
                    beam=beam,
                    detector=None,  #dummy for now
                    crystal=crystal))
            self.unique_file_names.append(
                tokens[order_dict["unique_file_name"]])

        self.show_summary()
Exemplo n.º 23
0
def imagesweep_from_dict(d, check_format=True):
    '''Construct and image sweep from the dictionary.'''
    from dxtbx.imageset import ImageSetFactory
    from dxtbx.model import BeamFactory, DetectorFactory, GoniometerFactory, ScanFactory
    from dxtbx.serialize.filename import load_path

    # Get the template (required)
    template = load_path(str(d['template']))

    # If the scan isn't set, find all available files
    scan_dict = d.get('scan')
    if scan_dict is None:
        image_range = None
    else:
        image_range = scan_dict.get('image_range')

    # Construct the sweep
    try:
        sweep = ImageSetFactory.from_template(template,
                                              image_range,
                                              check_format=check_format)[0]

        # Get the existing models as dictionaries
        beam_dict = sweep.get_beam().to_dict()
        gonio_dict = sweep.get_goniometer().to_dict()
        detector_dict = sweep.get_detector().to_dict()
        scan_dict = sweep.get_scan().to_dict()
    except Exception:
        indices = range(image_range[0], image_range[1] + 1)
        sweep = ImageSetFactory.make_sweep(template,
                                           indices,
                                           check_format=False)
        beam_dict = None
        gonio_dict = None
        detector_dict = None
        scan_dict = None

    # Set some external lookups
    if 'mask' in d and d['mask'] is not None:
        with open(d['mask']) as infile:
            sweep.external_lookup.mask.filename = d['mask']
            sweep.external_lookup.mask.data = pickle.load(infile)
    if 'gain' in d and d['gain'] is not None:
        with open(d['gain']) as infile:
            sweep.external_lookup.gain.filename = d['gain']
            sweep.external_lookup.gain.data = pickle.load(infile)
    if 'pedestal' in d and d['pedestal'] is not None:
        with open(d['pedestal']) as infile:
            sweep.external_lookup.pedestal.filename = d['pedestal']
            sweep.external_lookup.pedestal.data = pickle.load(infile)

    # Set the models with the exisiting models as templates
    sweep.set_beam(BeamFactory.from_dict(d.get('beam'), beam_dict))
    sweep.set_goniometer(
        GoniometerFactory.from_dict(d.get('goniometer'), gonio_dict))
    sweep.set_detector(
        DetectorFactory.from_dict(d.get('detector'), detector_dict))
    sweep.set_scan(ScanFactory.from_dict(d.get('scan'), scan_dict))

    # Return the sweep
    return sweep
Exemplo n.º 24
0
def test_experiment():
    d = {
        "__id__":
        "crystal",
        "real_space_a":
        [14.963210089244596, -22.599814679318, 51.02946725220764],
        "real_space_b":
        [-19.963976860932235, -51.503385430151205, -16.955728379753463],
        "real_space_c":
        [135.29560393219694, -34.371677531924206, -54.89475471853507],
        "space_group_hall_symbol":
        " P 4",
        "A_at_scan_points": [[
            0.004481726844090139,
            -0.005980612987053365,
            0.006013325470974739,
            -0.006768741824936281,
            -0.015428970379357122,
            -0.0015280122438480544,
            0.01528745348419002,
            -0.005078101688718203,
            -0.0024394384982453095,
        ]],
    }

    crystal = CrystalFactory.from_dict(d)

    beam_d = {
        "direction": [-2.4882593300783137e-06, -0.0, 0.9999999999969044],
        "transmission": 1.0,
        "polarization_normal": [0.0, 1.0, 0.0],
        "divergence": 0.0,
        "polarization_fraction": 0.999,
        "flux": 0.0,
        "sigma_divergence": 0.0,
        "wavelength": 0.9762499999999994,
    }

    beam = BeamFactory.from_dict(beam_d)
    scan = Scan(image_range=[0, 1], oscillation=[0.0, 0.01])

    detector_dict = {
        "hierarchy": {
            "origin": [0.0, 0.0, 0.0],
            "fast_axis": [1.0, 0.0, 0.0],
            "name": "",
            "raw_image_offset": [0, 0],
            "slow_axis": [0.0, 1.0, 0.0],
            "material": "",
            "mask": [],
            "thickness": 0.0,
            "mu": 0.0,
            "gain": 1.0,
            "trusted_range": [0.0, 0.0],
            "image_size": [0, 0],
            "px_mm_strategy": {
                "type": "SimplePxMmStrategy"
            },
            "identifier": "",
            "type": "",
            "children": [{
                "panel": 0
            }],
            "pixel_size": [0.0, 0.0],
        },
        "panels": [{
            "origin":
            [-210.66631009735772, 205.7063614421482, -263.8386975038205],
            "fast_axis": [
                0.9999973940105483,
                -0.0016357501034268717,
                -0.0015925745544149894,
            ],
            "name":
            "Panel",
            "raw_image_offset": [0, 0],
            "slow_axis": [
                -0.0016426481736367285,
                -0.999989234013669,
                -0.004339765400707805,
            ],
            "material":
            "Si",
            "mask": [
                [488, 1, 494, 2527],
                [982, 1, 988, 2527],
                [1476, 1, 1482, 2527],
                [1970, 1, 1976, 2527],
                [1, 196, 2463, 212],
                [1, 408, 2463, 424],
                [1, 620, 2463, 636],
                [1, 832, 2463, 848],
                [1, 1044, 2463, 1060],
                [1, 1256, 2463, 1272],
                [1, 1468, 2463, 1484],
                [1, 1680, 2463, 1696],
                [1, 1892, 2463, 1908],
                [1, 2104, 2463, 2120],
                [1, 2316, 2463, 2332],
            ],
            "thickness":
            0.32,
            "mu":
            3.9220322752480934,
            "gain":
            1.0,
            "trusted_range": [-1.0, 161977.0],
            "image_size": [2463, 2527],
            "px_mm_strategy": {
                "type": "ParallaxCorrectedPxMmStrategy"
            },
            "identifier":
            "",
            "type":
            "SENSOR_PAD",
            "pixel_size": [0.17200000000000001, 0.17200000000000001],
        }],
    }

    detector = DetectorFactory.from_dict(detector_dict)

    expt = Experiment(beam=beam, crystal=crystal, scan=scan, detector=detector)
    return expt
def run(args):

    distance = 125
    centre = (97.075, 97.075)
    pix_size = (0.11, 0.11)
    image_size = (1765, 1765)
    wavelength = args.w or 1.0
    # 1. Make a dummy detector
    detector = DetectorFactory.simple(
        'SENSOR_UNKNOWN',  # Sensor
        distance,
        centre,
        '+x',
        '-y',  # fast/slow direction
        pix_size,
        image_size)

    # 2. Get the miller array!
    mill_array = process_mtz(args.mtzfile[0]).as_intensity_array()
    ortho = sqr(mill_array.crystal_symmetry().unit_cell().reciprocal() \
              .orthogonalization_matrix())

    # 3.Create some image_pickle dictionairies that contain 'full' intensities,
    # but are otherwise complete.
    im = 0
    while im < args.n:
        im += 1
        A = sqr(flex.random_double_r3_rotation_matrix()) * ortho
        orientation = crystal_orientation(A, basis_type.reciprocal)
        pix_coords, miller_set = get_pix_coords(wavelength, A, mill_array,
                                                detector)
        if len(miller_set) > 10:  # at least 10 reflections
            miller_set = cctbx.miller.set(mill_array.crystal_symmetry(),
                                          miller_set,
                                          anomalous_flag=False)
            obs = mill_array.common_set(miller_set)
            temp_dict = {
                'observations': [obs],
                'mapped_predictions': [pix_coords],
                'pointgroup': None,
                'current_orientation': [orientation],
                'xbeam': centre[0],
                'ybeam': centre[1],
                'wavelength': wavelength
            }
            old_node = ImageNode(dicti=temp_dict, scale=False)
            # Remove all reflection that are not at least p partial
            partial_sel = (old_node.partialities > p_threshold)

            temp_dict['full_observations'] = [obs.select(partial_sel)]
            temp_dict['observations'] = [
                obs.select(partial_sel) *
                old_node.partialities.select(partial_sel)
            ]
            temp_dict['mapped_predictions'] = \
                        [temp_dict['mapped_predictions'][0].select(partial_sel)]

            if logging.Logger.root.level <= logging.DEBUG:  # debug!
                before = temp_dict['full_observations'][0]
                after = temp_dict['observations'][0] / old_node.partialities
                assert sum(abs(before.data() - after.data())) < eps

            if args.r:
                partials = list(temp_dict['observations'][0].data())
                jiggled_partials = flex.double(
                    [random.gauss(obs, args.r * obs) for obs in partials])
                temp_dict['observations'][0] = temp_dict['observations'][0] \
                                            .customized_copy(data=jiggled_partials)

            pkl_name = "simulated_data_{0:04d}.pickle".format(im)
            with (open(pkl_name, 'wb')) as pkl:
                pickle.dump(temp_dict, pkl)
            ''' Only works with no noise:
Exemplo n.º 26
0
def run(args):
  # read in phil files (detector and crystal)
  d_params = detector_phil_scope.fetch(parse(file_name = args[0])).extract()
  detector = DetectorFactory.from_phil(d_params.geometry)
  print(detector)
  assert len(detector) == 1; panel = detector[0]

  c_params = crystal_scope.fetch(parse(file_name = args[1])).extract()
  unit_cell = c_params.unit_cell
  sg_info = c_params.space_group
  a = sqr(unit_cell.orthogonalization_matrix()) * col((1,0,0))
  b = sqr(unit_cell.orthogonalization_matrix()) * col((0,1,0))
  c = sqr(unit_cell.orthogonalization_matrix()) * col((0,0,1))
  crystal = Crystal(a,b,c,sg_info.group())
  print(crystal)

  # load additional parameters
  user_phil = []
  for arg in args[2:]:
    user_phil.append(parse(arg))
  params = phil_scope.fetch(sources=user_phil).extract()

  energy = float(params.energy)
  wavelength = 12398.4/energy
  s0 = col((0,0,-1/wavelength))
  if params.bandpass is not None:
    wavelength1 = 12398.4/(energy-(params.bandpass/2))
    wavelength2 = 12398.4/(energy+(params.bandpass/2))
  vals = []
  print("Reference reflections 1 and 2, resolutions, two theta (deg) 1 and 2:")
  for axis in range(3):
    m1 = [0,0,0]; m1[axis] += params.reference_reflection
    m2 = [0,0,0]; m2[axis] += params.reference_reflection+1

    # n Lambda = 2dsin(theta)
    d = unit_cell.d(flex.miller_index([m1, m2]))
    try:
      if params.bandpass:
        tt_1 = math.asin(wavelength1/(2*d[0])) * 2
        tt_2 = math.asin(wavelength2/(2*d[1])) * 2
      else:
        tt_1 = math.asin(wavelength/(2*d[0])) * 2
        tt_2 = math.asin(wavelength/(2*d[1])) * 2
    except ValueError: # domain error if resolution is too high
      continue

    # Compute two s1 vectors
    s1_1 = s0.rotate(col((0,1,0)), -tt_1)
    s1_2 = s0.rotate(col((0,1,0)), -tt_2)

    print(m1, m2, list(d), tt_1*180/math.pi, tt_2*180/math.pi)

    # Get panel intersections and compute spacing
    v1 = col(panel.get_ray_intersection_px(s1_1))
    v2 = col(panel.get_ray_intersection_px(s1_2))
    vals.append((v1-v2).length())

  print("Spot separations:", vals)
  print("Smallest spot separation: %7.1f px"%(min(vals)))

  # Hack for quick tests
  assert len(detector)==1
  panel = detector[0]
  fast, slow = panel.get_image_size()
  f = fast//2; s = slow//2
  print("Inscribed resolution, assuming single panel centered detector %.3f:"% \
    min([panel.get_resolution_at_pixel(s0, p) for p in [(f,0),(fast,s),(f,slow),(0,s)]]))

  print("Computing pixel resolutions...")
  resolutions = []
  for panel in detector:
    fast, slow = panel.get_image_size()
    resolutions.append(flex.double(flex.grid(slow, fast)))

    for s in range(slow):
      for f in range(fast):
        resolutions[-1][s,f] = panel.get_resolution_at_pixel(s0, (f, s))

  print("Done")

  d_max = params.d_min * 1.1
  in_range = 0; total = 0
  for r in resolutions:
    in_range += len(r.as_1d().select((r.as_1d()>=params.d_min) & (r.as_1d() <= d_max)))
    total += len(r)

  print("%d of %d pixels between %.2f and %.2f angstroms (%.1f%%)"%(in_range, total, params.d_min, d_max, 100*in_range/total))
  two_theta_d_min = math.asin(wavelength/(2*params.d_min))*2
  d_min_radius_mm = math.tan(two_theta_d_min)*panel.get_distance()
  d_min_radius_px = d_min_radius_mm / panel.get_pixel_size()[0]
  possible_coverage_d_min = math.pi*d_min_radius_px**2
  two_theta_d_max = math.asin(wavelength/(2*d_max))*2
  d_max_radius_mm = math.tan(two_theta_d_max)*panel.get_distance()
  d_max_radius_px = d_max_radius_mm / panel.get_pixel_size()[0]
  possible_coverage_d_max = math.pi*d_max_radius_px**2
  possible_coverage = possible_coverage_d_min - possible_coverage_d_max
  print("Ideal detector would include %d pixels between %.2f-%.2f angstroms"%(possible_coverage, params.d_min, d_max))
  print("Coverage: %d/%d = %.1f%%"%(in_range, possible_coverage, 100*in_range/possible_coverage))

  two_theta_values = flex.double()
  step = (two_theta_d_max - two_theta_d_min)/10
  for i in range(11):
    two_theta_values.append(two_theta_d_max + (step*i))
  s0 = flex.vec3_double(len(two_theta_values), (0,0,-1))
  v = s0.rotate_around_origin((0,1,0), two_theta_values)
  all_v = flex.vec3_double()
  for i in range(720):
    i = i/2
    all_v.extend(v.rotate_around_origin((0,0,-1), i*math.pi/180))

  intersecting_rays = flex.bool()

  for i in range(len(all_v)):
    try:
      panel, mm = detector.get_ray_intersection(all_v[i])
    except RuntimeError:
      intersecting_rays.append(False)
    else:
      intersecting_rays.append(panel >=0 and panel < len(detector))

  print("%d rays out of %d projected between %f and %f intersected the detector (%.1f%%)"% \
    (intersecting_rays.count(True), len(intersecting_rays), params.d_min, d_max, intersecting_rays.count(True)*100/len(intersecting_rays)))

  resolutions[0].set_selected(resolutions[0] > 50, 50)
  plt.imshow(resolutions[0].as_numpy_array(), cmap='gray')
  plt.colorbar()

  plt.figure()
  r = resolutions[0]
  sel = (r.as_1d()>=params.d_min) & (r.as_1d() <= d_max)
  r.as_1d().set_selected(~sel, 0)
  plt.imshow(r.as_numpy_array(), cmap='gray')
  plt.colorbar()

  plt.show()
Exemplo n.º 27
0
 def _detector_from_dict(obj):
     """ Get the detector from a dictionary. """
     return DetectorFactory.from_dict(obj)