def test_cbf_writer(image_file, dials_regression, run_in_tmpdir):
    filename = os.path.join(dials_regression, image_file)
    datablock = DataBlockFactory.from_filenames([filename])[0]
    imageset = datablock.extract_imagesets()[0]

    FormatCBFMini.as_file(
        imageset.get_detector(),
        imageset.get_beam(),
        imageset.get_goniometer(),
        imageset.get_scan(),
        imageset.get_raw_data(0)[0],
        "image_0001.cbf",
    )

    assert datablock.format_class()

    datablock2 = DataBlockFactory.from_filenames(["image_0001.cbf"])[0]
    imageset2 = datablock2.extract_imagesets()[0]

    tolerance = tolerance_phil_scope.extract().tolerance

    diff = SweepDiff(tolerance)
    print("\n".join(diff(imageset, imageset2)))

    assert BeamComparison()(imageset.get_beam(), imageset2.get_beam())
    assert DetectorComparison(origin_tolerance=tolerance.detector.origin)(
        imageset.get_detector(), imageset2.get_detector())
    assert GoniometerComparison()(imageset.get_goniometer(),
                                  imageset2.get_goniometer())
    s1 = imageset.get_scan()
    s2 = imageset.get_scan()
    assert s1.get_exposure_times() == s2.get_exposure_times()
    assert s1.get_oscillation() == s2.get_oscillation()
    assert s1.get_image_range() == s2.get_image_range()
    assert imageset.get_raw_data(0) == imageset2.get_raw_data(0)
Esempio n. 2
0
def make_images(data, tag):
    pixel_size = 0.1  # mm/pixel
    detector = DetectorFactory.simple(
        'PAD', 100,
        (pixel_size * data.focus()[1] / 2, pixel_size * data.focus()[2] / 2),
        '+x', '-y', (pixel_size, pixel_size),
        (data.focus()[2], data.focus()[1]), (-1, 1e6 - 1), [], None)
    beam = BeamFactory.simple(1.0)
    sf = ScanFactory()
    scan = sf.make_scan(image_range=(1, 180),
                        exposure_times=0.1,
                        oscillation=(0, 1.0),
                        epochs=range(180),
                        deg=True)

    # write images in each of three directions
    for slice_id in [0, 1, 2]:
        for idx in xrange(data.focus()[slice_id]):
            if slice_id == 0:  # slow
                data_slice = data[idx:idx + 1, :, :]
                data_slice.reshape(flex.grid(data.focus()[1], data.focus()[2]))
                filename = "fft_frame_%s_mf_%04d.cbf" % (tag, idx)
            elif slice_id == 1:  # med
                data_slice = data[:, idx:idx + 1, :]
                data_slice.reshape(flex.grid(data.focus()[0], data.focus()[2]))
                filename = "fft_frame_%s_sf_%04d.cbf" % (tag, idx)
            elif slice_id == 2:  # fast
                data_slice = data[:, :, idx:idx + 1]
                data_slice.reshape(flex.grid(data.focus()[0], data.focus()[1]))
                filename = "fft_frame_%s_sm_%04d.cbf" % (tag, idx)
            print['slow', 'med', 'fast'][slice_id], idx
            FormatCBFMini.as_file(detector, beam, None, scan, data_slice,
                                  filename)
Esempio n. 3
0
def make_images(data, tag):
    pixel_size = 0.1
    detector = DetectorFactory.simple(
        'PAD', 100,
        (pixel_size * data.focus()[1] / 2, pixel_size * data.focus()[2] / 2),
        '+x', '-y', (pixel_size, pixel_size),
        (data.focus()[2], data.focus()[1]), (-1, 1e6 - 1), [], None)
    beam = BeamFactory.simple(1.0)

    for slice_id in [0, 1, 2]:
        for idx in xrange(data.focus()[slice_id]):
            if slice_id == 0:  # slow
                data_slice = data[idx:idx + 1, :, :]
                data_slice.reshape(flex.grid(data.focus()[1], data.focus()[2]))
                filename = "fft_frame_%s_mf_%04d.cbf" % (tag, idx)
            elif slice_id == 1:  # med
                data_slice = data[:, idx:idx + 1, :]
                data_slice.reshape(flex.grid(data.focus()[0], data.focus()[2]))
                filename = "fft_frame_%s_sf_%04d.cbf" % (tag, idx)
            elif slice_id == 2:  # fast
                data_slice = data[:, :, idx:idx + 1]
                data_slice.reshape(flex.grid(data.focus()[0], data.focus()[1]))
                filename = "fft_frame_%s_sm_%04d.cbf" % (tag, idx)
            print['slow', 'med', 'fast'][slice_id], idx
            FormatCBFMini.as_file(detector, beam, None, None, data_slice,
                                  filename)
 def _start(self):
     FormatCBFMini._start(self)
     self._array_size = (
         int(self._cif_header_dictionary["X-Binary-Size-Fastest-Dimension"]
             ),
         int(self._cif_header_dictionary["X-Binary-Size-Second-Dimension"]),
     )
 def _start(self):
   FormatCBFMini._start(self)
   try:
     from iotbx.detectors.pilatus_minicbf import PilatusImage
     self.detectorbase = PilatusImage(self._image_file)
     self.detectorbase.readHeader()
   except KeyError, e:
     pass
 def _start(self):
   FormatCBFMini._start(self)
   try:
     from iotbx.detectors.adsc_minicbf import ADSCHF4MImage
     self.detectorbase = ADSCHF4MImage(self._image_file)
     self.detectorbase.readHeader()
   except KeyError, e:
     pass
Esempio n. 7
0
  def __init__(self, image_file, **kwargs):
    '''Initialise the image structure from the given file, including a
    proper model of the experiment.'''

    assert(self.understand(image_file))

    FormatCBFMini.__init__(self, image_file, **kwargs)

    return
  def __init__(self, image_file):
    '''Initialise the image structure from the given file, including a
    proper model of the experiment.'''

    assert(self.understand(image_file))

    FormatCBFMini.__init__(self, image_file)

    return
 def as_file(detector,
             beam,
             gonio,
             scan,
             data,
             path,
             header_convention="PILATUS_1.2",
             det_type="PILATUS3 6M"):
     FormatCBFMini.as_file(detector, beam, gonio, scan, data, path,
                           header_convention, det_type)
    def __init__(self, image_file, **kwargs):
        """Initialise the image structure from the given file, including a
        proper model of the experiment."""

        from dxtbx import IncorrectFormatError

        if not self.understand(image_file):
            raise IncorrectFormatError(self, image_file)

        FormatCBFMini.__init__(self, image_file, **kwargs)
Esempio n. 11
0
def convert_to_cbf(imageset, template):
    from dxtbx.format.FormatCBFMini import FormatCBFMini

    for i in range(len(imageset)):
        print(template % (i + 1))
        FormatCBFMini.as_file(
            imageset.get_detector(),
            imageset.get_beam(),
            imageset.get_goniometer(),
            imageset.get_scan()[i],
            imageset.get_raw_data(i)[0],
            template % (i + 1),
        )
  def understand(image_file):
    '''Check to see if this looks like an Pilatus mini CBF format image,
    i.e. we can make sense of it.'''

    if 'ENABLE_PHOTON_FACTORY_TWO_EIGER' in os.environ:
      return False

    header = FormatCBFMini.get_cbf_header(image_file)

    for record in header.split('\n'):
      if '# Detector' in record and \
             'EIGER' in record.upper():
        return False

    for record in header.split('\n'):
      if '_array_data.header_convention' in record and \
             'PILATUS' in record:
        return True
      if '_array_data.header_convention' in record and \
             'SLS' in record:
        return True
      if '_array_data.header_convention' in record and \
             '?' in record:
        return True
      if '# Detector' in record and \
             'PILATUS' in record:  #CBFlib v0.8.0 allowed
        return True

    return False
    def understand(image_file):
        '''Check to see if this looks like an Pilatus mini CBF format image,
    i.e. we can make sense of it.'''

        if 'ENABLE_PHOTON_FACTORY_TWO_EIGER' in os.environ:
            return False

        header = FormatCBFMini.get_cbf_header(image_file)

        for record in header.split('\n'):
            if '# Detector' in record and \
                   'EIGER' in record.upper():
                return False

        for record in header.split('\n'):
            if '_array_data.header_convention' in record and \
                   'PILATUS' in record:
                return True
            if '_array_data.header_convention' in record and \
                   'SLS' in record:
                return True
            if '_array_data.header_convention' in record and \
                   '?' in record:
                return True
            if '# Detector' in record and \
                   'PILATUS' in record:  #CBFlib v0.8.0 allowed
                return True

        return False
Esempio n. 14
0
    def understand(image_file):
        """Check to see if this looks like an Pilatus mini CBF format image,
        i.e. we can make sense of it."""

        if "ENABLE_PHOTON_FACTORY_TWO_EIGER" in os.environ:
            return False

        header = FormatCBFMini.get_cbf_header(image_file)

        for record in header.split("\n"):
            if "# Detector" in record:
                if "EIGER" in record.upper():
                    return False
                if "TIMEPIX" in record.upper():
                    return False

        for record in header.split("\n"):
            if "_array_data.header_convention" in record and "PILATUS" in record:
                return True
            if "_array_data.header_convention" in record and "SLS" in record:
                return True
            if "_array_data.header_convention" in record and "?" in record:
                return True
            if "# Detector" in record and "PILATUS" in record:  # CBFlib v0.8.0 allowed
                return True

        return False
Esempio n. 15
0
    def remove_bragg_peaks(self, reference=None, write_lunus=None):

        start_cpu = time.clock()
        start_real = time.time()
        image = LunusDIFFIMAGE()
        image.set_image(self.raw_data)
        print 'Removing beamstop shadow from image'
        image.LunusPunchim(self.punchim_xmin, self.punchim_ymin, self.punchim_xmax, self.punchim_ymax)
        print 'Cleaning up edge of image'
        image.LunusWindim(self.windim_xmin, self.windim_ymin, self.windim_xmax, self.windim_ymax)
        print "Setting detection threshold"
        image.LunusThrshim(self.thrshim_min, self.thrshim_max)
        print "Removing Bragg peaks from image"
        image.LunusModeim(self.mode_filter_footprint)
        print "Mode filter finished."
        print "Correcting for beam polarization"
        image.LunusPolarim(self.beam_center_mm_x, self.beam_center_mm_y, self.detector_distance, self.polarization_fraction, self.polarization_offset, self.pixel_size)
        print "Solid-angle normalization of image"
        image.LunusNormim(self.beam_center_mm_x, self.beam_center_mm_y, self.detector_distance, self.cassette_x, self.cassette_y, self.pixel_size)
        
        self.lunus_data_scitbx = image.get_image();

        self.radial_avg = image.LunusRadialAvgim(self.beam_center_mm_x, self.beam_center_mm_y, self.pixel_size)
        self.lunus_data = self.lunus_data_scitbx.as_numpy_array()
        print("shape of lunus data at step 1: {}".format(self.lunus_data.shape))


        end_cpu = time.clock()
        end_real = time.time()
        print("%f Real Seconds" % (end_real - start_real))
        print("%f CPU seconds" % (end_cpu - start_cpu))


        ### write files, if desired
        if write_lunus:
            FormatCBFMini.as_file(self.detector,self.beam,self.gonio,self.scan,self.lunus_data_scitbx,self.lunus)
        else:
            pass

        if reference:
            np.savez("reference_radial_average", rad=self.radial_avg)
        else:
            pass

        return
    def _detector(self):
        '''Return a model for a simple detector, presuming no one has
    one of these on a two-theta stage. Assert that the beam centre is
    provided in the Mosflm coordinate frame.'''
        detector = FormatCBFMini._detector(self)

        for f0, s0, f1, s1 in determine_pilatus_mask(detector):
            detector[0].add_mask(f0, s0, f1, s1)

        return detector
Esempio n. 17
0
    def understand(image_file):

        header = FormatCBFMini.get_cbf_header(image_file)

        for record in header.split("\n"):
            if "# Detector" in record and "ADSC" in record and "HF-4M" in header:
                return True
            if "_array_data.header_convention" in record and "ADSC" in record:
                return True

        return False
Esempio n. 18
0
    def understand(image_file):
        """Check to see if this looks like an Eiger mini CBF format image,
        i.e. we can make sense of it."""

        header = FormatCBFMini.get_cbf_header(image_file)

        for record in header.split("\n"):
            if "# detector" in record.lower() and "eiger" in record.lower():
                return True

        return False
  def understand(image_file):
    '''Check to see if this looks like an Eiger mini CBF format image,
    i.e. we can make sense of it.'''

    header = FormatCBFMini.get_cbf_header(image_file)

    for record in header.split('\n'):
      if '# Detector' in record and \
             'EIGER' in record:
        return True

    return False
    def understand(image_file):
        '''Check to see if this looks like an Eiger mini CBF format image,
    i.e. we can make sense of it.'''

        header = FormatCBFMini.get_cbf_header(image_file)

        for record in header.split('\n'):
            if '# detector' in record.lower() and \
                   'eiger' in record.lower():
                return True

        return False
  def understand(image_file):

    header = FormatCBFMini.get_cbf_header(image_file)

    for record in header.split('\n'):
      if '# Detector' in record and \
             'ADSC' in record and 'HF-4M' in header:
        return True
      if '_array_data.header_convention' in record and \
             'ADSC' in record:
        return True

    return False
Esempio n. 22
0
    def understand(image_file):

        header = FormatCBFMini.get_cbf_header(image_file)

        for record in header.split('\n'):
            if '# Detector' in record and \
                   'ADSC' in record and 'HF-4M' in header:
                return True
            if '_array_data.header_convention' in record and \
                   'ADSC' in record:
                return True

        return False
    def understand(image_file):
        """Check to see if this looks like a Timepix mini CBF format image,
        i.e. we can make sense of it."""

        header = FormatCBFMini.get_cbf_header(image_file)

        # Look for 'TIMEPIX' string. The headers also contain 'S/N 24-0109-F'
        # but this may not be trustworthy and anyway we want to recognise all
        # Timepix CBFs here
        for record in header.split("\n"):
            if "# Detector" in record and "TIMEPIX" in record:
                return True

        return False
    def understand(image_file):
        """Check to see if this looks like a Timepix mini CBF format image,
        i.e. we can make sense of it."""
        mime_header = ""
        in_binary_format_section = False
        for record in FormatCBFMini.open_file(image_file, "rb"):
            if "--CIF-BINARY-FORMAT-SECTION--" in record:
                in_binary_format_section = True
            elif in_binary_format_section and record[0] == "X":
                mime_header += record
            if in_binary_format_section and len(record.strip()) == 0:
                # http://sourceforge.net/apps/trac/cbflib/wiki/ARRAY_DATA%20Category
                #    In an imgCIF file, the encoded binary data begins after
                #    the empty line terminating the header.
                break

        # Look for 1032 pixels
        for record in mime_header.split("\n"):
            if ("-Binary-Size-Fastest-Dimension:" in record
                    and int(record.split()[1]) == 1032):
                return True

        return False
Esempio n. 25
0
def process_one_glob():

    from dxtbx.imageset import ImageSetFactory
    from dxtbx.model.experiment_list import Experiment, ExperimentList
    from dxtbx.serialize import dump

    imnum = 1

    metrolist = glob.glob(metro_glob)
    metrolist.sort()

    filelist = glob.glob(image_glob)
    filelist.sort()

    if (rotation_series):
        experiments = ExperimentListFactory.from_json_file(metrolist[0],
                                                           check_format=False)
        x = get_experiment_xvectors(experiments)
        npx = np.asarray(x)

    Isize1, Isize2 = experiments[0].detector[0].get_image_size()

    #    cf = correction_factor(Isize1,Isize2,experiments,x[0])

    for i in range(len(filelist)):
        print("{0}...".format(i), )
        sys.stdout.flush()

        if (not rotation_series):
            experiments = ExperimentListFactory.from_json_file(
                metrolist[i], check_format=False)
            x = get_experiment_xvectors(experiments)
            npx = np.asarray(x)

        imgname = filelist[i]
        img = dxtbx.load(imgname)
        #      data = img.get_raw_data()

        #      print "min of data = ",flex.min(data)
        #      print "max of data = ",flex.max(data)

        beam = img.get_beam()
        detector = img.get_detector()

        crystal = copy.deepcopy(experiments.crystals()[0])

        scan = img.get_scan()
        start_angle, delta_angle = scan.get_oscillation()

        gonio = img.get_goniometer()
        axis = gonio.get_rotation_axis()

        pixel_values = flex.int(range(Isize1 * Isize2))
        pixel_values.reshape(flex.grid(Isize2, Isize1))

        if (rotation_series):
            crystal.rotate_around_origin(axis,
                                         start_angle + (delta_angle / 2),
                                         deg=True)

        from scitbx import matrix

        A_matrix = matrix.sqr(crystal.get_A()).inverse()

        diffim = procimg_single(Isize1, Isize2, scale, lattice_mask_tag,
                                A_matrix, npx[0], experiments, D)

        # Apply correction factor for polarization and solid angle

        # Scale pixel values

        dmin = np.amin(diffim)

        print("dmin = ", dmin)

        #  s = 256./(dmax-dmin)

        for i in range(len(diffim)):
            for j in range(len(diffim[i])):
                if (diffim[i][j] != image_mask_tag):
                    diffim[i][j] = diffim[i][j] * scale
        if (shift_min):
            for i in range(len(diffim)):
                for j in range(len(diffim[i])):
                    if (diffim[i][j] != image_mask_tag):
                        diffim[i][j] -= dmin * scale


#      diffim *= scale

        int_mask_tag = int(image_mask_tag)

        for j in range(Isize2):
            for i in range(Isize1):
                pixel_values[j, i] = np.int(diffim[i, j])
                if (pixel_values[j, i] == int_mask_tag):
                    pixel_values[j, i] = -1

        outname = prefout + "_%05d.cbf" % (imnum)

        FormatCBFMini.as_file(detector, beam, gonio, scan, pixel_values,
                              outname)

        imnum = imnum + 1

    print()
 def _start(self):
     FormatCBFMini._start(self)
Esempio n. 27
0
scan = img.get_scan()

A = LunusDIFFIMAGE()
data = img.get_raw_data()
A.set_image(data)
deck = '''
#lunus input deck
punchim_xmin=1203
punchim_ymin=1250
punchim_xmax=2459
punchim_ymax=1314
windim_xmin=100
windim_ymin=100
windim_xmax=2362
windim_ymax=2426
thrshim_min=0
thrshim_max=50
modeim_bin_size=1
modeim_kernel_width=20

'''
A.LunusSetparamsim(deck)
A.LunusPunchim()
A.LunusWindim()
A.LunusThrshim()
A.LunusModeim()
print "Mode filter finished."
data2 = A.get_image();
#dxtbx.format.FormatCBFMini.FormatCBFMini.as_file(detector,beam,gonio,scan,data,path,header_convention="GENERIC_MINI",det_type="GENERIC")
FormatCBFMini.as_file(detector,beam,gonio,scan,data2,"g150aich_274_6_1_lunus_00001.cbf")
Esempio n. 28
0
A = LunusDIFFIMAGE()
data = img.get_raw_data()
print data[0]
A.set_image(data)
deck = '''
#lunus input deck
punchim_xmin=1203
punchim_ymin=1250
punchim_xmax=2459
punchim_ymax=1314
windim_xmin=100
windim_ymin=100
windim_xmax=2362
windim_ymax=2426
thrshim_min=0
thrshim_max=50
modeim_bin_size=1
modeim_kernel_width=20

'''
A.LunusSetparamsim(deck)
A.LunusPunchim()
A.LunusWindim()
A.LunusThrshim()
A.LunusModeim()
print "Mode filter finished."
data2 = A.get_image()
#dxtbx.format.FormatCBFMini.FormatCBFMini.as_file(detector,beam,gonio,scan,data,path,header_convention="GENERIC_MINI",det_type="GENERIC")
FormatCBFMini.as_file(detector, beam, gonio, scan, data2, out_name)
def run_sim2smv(fileout):
    SIM = nanoBragg(detpixels_slowfast=(1000, 1000),
                    pixel_size_mm=0.1,
                    Ncells_abc=(5, 5, 5),
                    verbose=9)
    import sys
    if len(sys.argv) > 2:
        SIM.seed = -int(sys.argv[2])
        print "GOTHERE seed=", SIM.seed
    if len(sys.argv) > 1:
        if sys.argv[1] == "random": SIM.randomize_orientation()
    SIM.distance_mm = 100
    #SIM = nanoBragg(detpixels_slowfast=(2527,2463),pixel_size_mm=0.172,Ncells_abc=(5,5,5),verbose=9)
    #SIM.distance_mm=200
    # get same noise each time this test is run
    SIM.seed = 1
    SIM.oversample = 1
    SIM.wavelength_A = 1
    SIM.polarization = 1
    #SIM.unit_cell_tuple=(50,50,50,90,90,90)
    print "unit_cell_Adeg=", SIM.unit_cell_Adeg
    print "unit_cell_tuple=", SIM.unit_cell_tuple
    # this will become F000, marking the beam center
    SIM.default_F = 100
    #SIM.missets_deg= (10,20,30)
    print "mosaic_seed=", SIM.mosaic_seed
    print "seed=", SIM.seed
    print "calib_seed=", SIM.calib_seed
    print "missets_deg =", SIM.missets_deg
    sfall = fcalc_from_pdb(resolution=1.6,
                           algorithm="direct",
                           wavelength=SIM.wavelength_A)
    # use crystal structure to initialize Fhkl array
    SIM.Fhkl = sfall
    # fastest option, least realistic
    SIM.xtal_shape = shapetype.Tophat
    # only really useful for long runs
    SIM.progress_meter = False
    # prints out value of one pixel only.  will not render full image!
    #SIM.printout_pixel_fastslow=(500,500)
    #SIM.printout=True
    SIM.show_params()
    # flux is always in photons/s
    SIM.flux = 1e12
    # assumes round beam
    SIM.beamsize_mm = 0.1
    SIM.exposure_s = 0.1
    temp = SIM.Ncells_abc
    print "Ncells_abc=", SIM.Ncells_abc
    SIM.Ncells_abc = temp
    print "Ncells_abc=", SIM.Ncells_abc
    print "xtal_size_mm=", SIM.xtal_size_mm
    print "unit_cell_Adeg=", SIM.unit_cell_Adeg
    print "unit_cell_tuple=", SIM.unit_cell_tuple
    print "missets_deg=", SIM.missets_deg
    print "Amatrix=", SIM.Amatrix
    print "beam_center_mm=", SIM.beam_center_mm
    print "XDS_ORGXY=", SIM.XDS_ORGXY
    print "detector_pivot=", SIM.detector_pivot
    print "xtal_shape=", SIM.xtal_shape
    print "beamcenter_convention=", SIM.beamcenter_convention
    print "fdet_vector=", SIM.fdet_vector
    print "sdet_vector=", SIM.sdet_vector
    print "odet_vector=", SIM.odet_vector
    print "beam_vector=", SIM.beam_vector
    print "polar_vector=", SIM.polar_vector
    print "spindle_axis=", SIM.spindle_axis
    print "twotheta_axis=", SIM.twotheta_axis
    print "distance_meters=", SIM.distance_meters
    print "distance_mm=", SIM.distance_mm
    print "close_distance_mm=", SIM.close_distance_mm
    print "detector_twotheta_deg=", SIM.detector_twotheta_deg
    print "detsize_fastslow_mm=", SIM.detsize_fastslow_mm
    print "detpixels_fastslow=", SIM.detpixels_fastslow
    print "detector_rot_deg=", SIM.detector_rot_deg
    print "curved_detector=", SIM.curved_detector
    print "pixel_size_mm=", SIM.pixel_size_mm
    print "point_pixel=", SIM.point_pixel
    print "polarization=", SIM.polarization
    print "nopolar=", SIM.nopolar
    print "oversample=", SIM.oversample
    print "region_of_interest=", SIM.region_of_interest
    print "wavelength_A=", SIM.wavelength_A
    print "energy_eV=", SIM.energy_eV
    print "fluence=", SIM.fluence
    print "flux=", SIM.flux
    print "exposure_s=", SIM.exposure_s
    print "beamsize_mm=", SIM.beamsize_mm
    print "dispersion_pct=", SIM.dispersion_pct
    print "dispsteps=", SIM.dispsteps
    print "divergence_hv_mrad=", SIM.divergence_hv_mrad
    print "divsteps_hv=", SIM.divsteps_hv
    print "divstep_hv_mrad=", SIM.divstep_hv_mrad
    print "round_div=", SIM.round_div
    print "phi_deg=", SIM.phi_deg
    print "osc_deg=", SIM.osc_deg
    print "phisteps=", SIM.phisteps
    print "phistep_deg=", SIM.phistep_deg
    print "detector_thick_mm=", SIM.detector_thick_mm
    print "detector_thicksteps=", SIM.detector_thicksteps
    print "detector_thickstep_mm=", SIM.detector_thickstep_mm
    print "mosaic_spread_deg=", SIM.mosaic_spread_deg
    print "mosaic_domains=", SIM.mosaic_domains
    print "indices=", SIM.indices
    print "amplitudes=", SIM.amplitudes
    print "Fhkl_tuple=", SIM.Fhkl_tuple
    print "default_F=", SIM.default_F
    print "interpolate=", SIM.interpolate
    print "integral_form=", SIM.integral_form
    # now actually burn up some CPU
    SIM.add_nanoBragg_spots()
    # simulated crystal is only 125 unit cells (25 nm wide)
    # amplify spot signal to simulate physical crystal of 4000x larger: 100 um (64e9 x the volume)
    SIM.raw_pixels *= 64e9
    SIM.to_smv_format(fileout="intimage_001.img")
    # rough approximation to water: interpolation points for sin(theta/lambda) vs structure factor
    bg = flex.vec2_double([(0, 2.57), (0.0365, 2.58), (0.07, 2.8), (0.12, 5),
                           (0.162, 8), (0.2, 6.75),
                           (0.18, 7.32), (0.216, 6.75), (0.236, 6.5),
                           (0.28, 4.5), (0.3, 4.3), (0.345, 4.36),
                           (0.436, 3.77), (0.5, 3.17)])
    SIM.Fbg_vs_stol = bg
    SIM.amorphous_sample_thick_mm = 0.1
    SIM.amorphous_density_gcm3 = 1
    SIM.amorphous_molecular_weight_Da = 18
    SIM.flux = 1e12
    SIM.beamsize_mm = 0.1
    SIM.exposure_s = 0.1
    SIM.add_background()
    SIM.to_smv_format(fileout="intimage_002.img")
    # rough approximation to air
    bg = flex.vec2_double([(0, 14.1), (0.045, 13.5), (0.174, 8.35),
                           (0.35, 4.78), (0.5, 4.22)])
    SIM.Fbg_vs_stol = bg
    SIM.amorphous_sample_thick_mm = 35  # between beamstop and collimator
    SIM.amorphous_density_gcm3 = 1.2e-3
    SIM.amorphous_sample_molecular_weight_Da = 28  # nitrogen = N2
    print "amorphous_sample_size_mm=", SIM.amorphous_sample_size_mm
    print "amorphous_sample_thick_mm=", SIM.amorphous_sample_thick_mm
    print "amorphous_density_gcm3=", SIM.amorphous_density_gcm3
    print "amorphous_molecular_weight_Da=", SIM.amorphous_molecular_weight_Da
    SIM.add_background()
    # set this to 0 or -1 to trigger automatic radius.  could be very slow with bright images
    SIM.detector_psf_kernel_radius_pixels = 5
    SIM.detector_psf_fwhm_mm = 0.08
    SIM.detector_psf_type = shapetype.Fiber
    #SIM.apply_psf()
    print SIM.raw_pixels[500000]
    SIM.to_smv_format(fileout="intimage_003.img")
    #SIM.detector_psf_fwhm_mm=0
    print "quantum_gain=", SIM.quantum_gain
    print "adc_offset_adu=", SIM.adc_offset_adu
    print "detector_calibration_noise_pct=", SIM.detector_calibration_noise_pct
    print "flicker_noise_pct=", SIM.flicker_noise_pct
    print "readout_noise_adu=", SIM.readout_noise_adu
    print "detector_psf_type=", SIM.detector_psf_type
    print "detector_psf_fwhm_mm=", SIM.detector_psf_fwhm_mm
    print "detector_psf_kernel_radius_pixels=", SIM.detector_psf_kernel_radius_pixels
    SIM.add_noise()

    #fileout = "intimage_001.img"
    print "raw_pixels=", SIM.raw_pixels
    SIM.to_smv_format(fileout="noiseimage_001.img", intfile_scale=1)

    # try to write as CBF
    import dxtbx
    from dxtbx.format.FormatCBFMini import FormatCBFMini
    img = dxtbx.load("noiseimage_001.img")
    print img
    FormatCBFMini.as_file(detector=img.get_detector(),
                          beam=img.get_beam(),
                          gonio=img.get_goniometer(),
                          scan=img.get_scan(),
                          data=img.get_raw_data(),
                          path=fileout)
    SIM.free_all()
 def _start(self):
   FormatCBFMini._start(self)
Esempio n. 31
0
    def _detector(self):
        """Return a model for a simple detector, presuming no one has
        one of these on a two-theta stage. Assert that the beam centre is
        provided in the Mosflm coordinate frame."""

        if not self._multi_panel:
            detector = FormatCBFMini._detector(self)
            for f0, f1, s0, s1 in determine_pilatus_mask(detector):
                detector[0].add_mask(f0 - 1, s0 - 1, f1, s1)
            return detector

        # got to here means 60-panel version
        d = Detector()

        distance = float(
            self._cif_header_dictionary["Detector_distance"].split()[0])

        beam_xy = (self._cif_header_dictionary["Beam_xy"].replace(
            "(", "").replace(")", "").replace(",", "").split()[:2])

        beam_x, beam_y = map(float, beam_xy)

        wavelength = float(
            self._cif_header_dictionary["Wavelength"].split()[0])

        pixel_xy = (self._cif_header_dictionary["Pixel_size"].replace(
            "m", "").replace("x", "").split())

        pixel_x, pixel_y = map(float, pixel_xy)

        thickness = float(
            self._cif_header_dictionary["Silicon"].split()[2]) * 1000.0

        nx = int(
            self._cif_header_dictionary["X-Binary-Size-Fastest-Dimension"])
        ny = int(self._cif_header_dictionary["X-Binary-Size-Second-Dimension"])

        overload = int(self._cif_header_dictionary["Count_cutoff"].split()[0])
        underload = -1

        # take into consideration here the thickness of the sensor also the
        # wavelength of the radiation (which we have in the same file...)
        table = attenuation_coefficient.get_table("Si")
        mu = table.mu_at_angstrom(wavelength) / 10.0
        t0 = thickness

        # FIXME would also be very nice to be able to take into account the
        # misalignment of the individual modules given the calibration...

        # single detector or multi-module detector

        pixel_x *= 1000.0
        pixel_y *= 1000.0
        distance *= 1000.0

        beam_centre = matrix.col((beam_x * pixel_x, beam_y * pixel_y, 0))

        fast = matrix.col((1.0, 0.0, 0.0))
        slow = matrix.col((0.0, -1.0, 0.0))
        s0 = matrix.col((0, 0, -1))
        origin = (distance * s0) - (fast * beam_centre[0]) - (slow *
                                                              beam_centre[1])

        root = d.hierarchy()
        root.set_local_frame(fast.elems, slow.elems, origin.elems)

        det = _DetectorDatabase["Pilatus"]

        # Edge dead areas not included, only gaps between modules matter
        n_fast, remainder = divmod(nx, det.module_size_fast)
        assert (n_fast - 1) * det.gap_fast == remainder

        n_slow, remainder = divmod(ny, det.module_size_slow)
        assert (n_slow - 1) * det.gap_slow == remainder

        mx = det.module_size_fast
        my = det.module_size_slow
        dx = det.gap_fast
        dy = det.gap_slow

        xmins = [(mx + dx) * i for i in range(n_fast)]
        xmaxes = [mx + (mx + dx) * i for i in range(n_fast)]
        ymins = [(my + dy) * i for i in range(n_slow)]
        ymaxes = [my + (my + dy) * i for i in range(n_slow)]

        self.coords = {}

        fast = matrix.col((1.0, 0.0, 0.0))
        slow = matrix.col((0.0, 1.0, 0.0))
        panel_idx = 0
        for ymin, ymax in zip(ymins, ymaxes):
            for xmin, xmax in zip(xmins, xmaxes):
                xmin_mm = xmin * pixel_x
                ymin_mm = ymin * pixel_y

                origin_panel = fast * xmin_mm + slow * ymin_mm

                panel_name = "Panel%d" % panel_idx
                panel_idx += 1

                p = d.add_panel()
                p.set_type("SENSOR_PAD")
                p.set_name(panel_name)
                p.set_raw_image_offset((xmin, ymin))
                p.set_image_size((xmax - xmin, ymax - ymin))
                p.set_trusted_range((underload, overload))
                p.set_pixel_size((pixel_x, pixel_y))
                p.set_thickness(thickness)
                p.set_material("Si")
                p.set_mu(mu)
                p.set_px_mm_strategy(ParallaxCorrectedPxMmStrategy(mu, t0))
                p.set_local_frame(fast.elems, slow.elems, origin_panel.elems)
                p.set_raw_image_offset((xmin, ymin))
                self.coords[panel_name] = (xmin, ymin, xmax, ymax)

        return d