Exemplo n.º 1
0
 def __init__(self,arg_module,phil_params,verbose=True):
   # support the many-image-in-one-H5-container paradigm
   if phil_params.distl.range is not None:  # range parameter only intended for H5 files
     assert len(self.filenames())==1 # can be only one H5 master file if there is a range of image indices
     if len(phil_params.distl.range)==1:  self.unrolled_range = phil_params.distl.range
     else:
       self.unrolled_range = range(phil_params.distl.range[0],phil_params.distl.range[1])
       self.filenames.FN = [self.filenames.FN[0]]*len(self.unrolled_range)
     self.frames = self.h5_frames
     self.imageindex = self.h5_imageindex
     self.imagepath = self.h5_imagepath
     import copy
     for indx,name in enumerate(self.filenames()):
       if indx==0:
         A = ImageFactory(name,optional_index=self.unrolled_range[indx])
         self.site_modifications(A,self.filenames.FN[indx])
         self.images.append(A)
       else:
         Acopy = copy.deepcopy(A)
         Acopy.img_number = self.unrolled_range[indx]
         self.images.append(Acopy)
   else:  # range is not present; normal behavior for non-H5 images
     for indx,name in enumerate(self.filenames()):
       A = ImageFactory(name)
       self.site_modifications(A,self.filenames.FN[indx])
       self.images.append(A)
Exemplo n.º 2
0
    def set_image(self,
                  file_name_or_data,
                  metrology_matrices=None,
                  get_raw_data=None):

        self.reset_the_cache()
        if file_name_or_data is None:
            self.raw_image = None
            return
        if type(file_name_or_data) is type(""):
            from iotbx.detectors import ImageFactory

            self.raw_image = ImageFactory(file_name_or_data)
            self.raw_image.read()
        else:
            try:
                self.raw_image = file_name_or_data._raw
            except AttributeError:
                self.raw_image = file_name_or_data
        # print "SETTING NEW IMAGE",self.raw_image.filename

        # XXX Since there doesn't seem to be a good way to refresh the
        # image (yet), the metrology has to be applied here, and not
        # in frame.py.

        detector = self.raw_image.get_detector()

        if len(detector) > 1 and metrology_matrices is not None:
            self.raw_image.apply_metrology_from_matrices(metrology_matrices)

        if get_raw_data is not None:
            self.raw_image.set_raw_data(get_raw_data(self.raw_image))
        raw_data = self.raw_image.get_raw_data()
        if not isinstance(raw_data, tuple):
            raw_data = (raw_data, )

        if len(detector) > 1:
            self.flex_image = _get_flex_image_multipanel(
                brightness=self.current_brightness / 100,
                panels=detector,
                show_untrusted=self.show_untrusted,
                raw_data=raw_data,
                beam=self.raw_image.get_beam(),
                color_scheme=self.current_color_scheme,
            )
        else:
            self.flex_image = _get_flex_image(
                brightness=self.current_brightness / 100,
                data=raw_data[0],
                saturation=self.raw_image.get_detector()
                [0].get_trusted_range()[1],
                vendortype=self.raw_image.get_vendortype(),
                show_untrusted=self.show_untrusted,
                color_scheme=self.current_color_scheme,
            )

        if self.zoom_level >= 0:
            self.flex_image.adjust(color_scheme=self.current_color_scheme)
Exemplo n.º 3
0
 def __init__ (self, file_name) :
   screen_params.__init__(self)
   # XXX major hack - Boost.Python doesn't really deal with Unicode strings
   if isinstance(file_name, unicode) :
     file_name = str(file_name)
   if isinstance(file_name, str) or isinstance(file_name, dict):
     self.file_name = file_name
     from iotbx.detectors import ImageFactory, ImageException
     try :
       img = ImageFactory(file_name)
     except ImageException, e :
       raise Sorry(str(e))
     img.read()
Exemplo n.º 4
0
 def __init__ (self, file_name) :
   screen_params.__init__(self)
   # XXX major hack - Boost.Python doesn't really deal with Unicode strings
   if isinstance(file_name, unicode) :
     file_name = str(file_name)
   if isinstance(file_name, str) or isinstance(file_name, dict):
     self.file_name = file_name
     from iotbx.detectors import ImageFactory, ImageException
     try :
       img = ImageFactory(file_name)
     except ImageException, e :
       raise Sorry(str(e))
     img.read()
Exemplo n.º 5
0
def run(img_in):
    im = ImageFactory(img_in)
    im.read()
    print dir(im)
    print im.size2, im.size1
    data = numpy.array(im.linearintdata, dtype=numpy.uint16).reshape(im.size2, im.size1)
    print data, data.dtype
    
    prefix = os.path.basename(img_in)
    of = h5py.File("%s_byteoffset.h5"%prefix, "w")
    grp = of.create_group("data")
    dset = grp.create_dataset(prefix, data.shape, dtype=data.dtype, compression=CBF_BYTE_OFFSET)
    dset[...] = data
    of.close()
Exemplo n.º 6
0
def read_cmos_image(f, read_data=True, fast=True):
    h = {}
    data = None

    get_after = lambda l: l[l.index("=") + 1:].rstrip(";\n ")
    if fast:
        for l in open(f):
            if "}" in l: break
            if l.startswith("SIZE1="):
                h["size1"] = int(get_after(l))
            elif l.startswith("SIZE2="):
                h["size2"] = int(get_after(l))
            elif l.startswith("TYPE="):
                assert "unsigned_short" in l
            elif l.startswith("PIXEL_SIZE="):
                h["pixel_size"] = float(get_after(l))
            elif l.startswith("DISTANCE="):
                h["distance"] = float(get_after(l))
            elif l.startswith("WAVELENGTH="):
                h["wavelength"] = float(get_after(l))
            elif l.startswith("BEAM_CENTER_X="):
                h["beamx"] = float(get_after(l))
            elif l.startswith("BEAM_CENTER_Y="):
                h["beamy"] = float(get_after(l))

        h["orgx"], h["orgy"] = h["beamx"] / h["pixel_size"], h["beamy"] / h[
            "pixel_size"]

        if read_data:
            ifs = open(f, "rb")
            ifs.seek(-h["size1"] * h["size2"] * 2, 2)
            data = numpy.fromfile(ifs, dtype=numpy.uint16).reshape(
                h["size2"], h["size1"])

    else:
        from iotbx.detectors import ImageFactory

        im = ImageFactory(f)
        h["orgx"], h[
            "orgy"] = im.beamx / im.pixel_size, im.beamy / im.pixel_size
        h["wavelength"] = im.wavelength
        h["distance"] = im.distance
        if read_data:
            im.read()
            data = numpy.array(im.linearintdata,
                               dtype=numpy.uint16).reshape(im.size2, im.size1)

    return h, data
Exemplo n.º 7
0
def get_detector_file(image):
    """
    Returns the RAPD detector file given an image file
    """

    # print "get_detector_file %s" % image
    try:
        i = ImageFactory(image)
        # print i.vendortype
        # print i.parameters["DETECTOR_SN"]
    except (IOError, AttributeError, RuntimeError):
        print error
        return False

    # print ">>>%s<<<" % i.vendortype
    # print ">>>%s<<<" % i.parameters["DETECTOR_SN"]

    v_type = i.vendortype.strip()
    sn = str(i.parameters["DETECTOR_SN"]).strip()

    # pprint(detector_list.DETECTORS)

    if (v_type, sn) in detector_list.DETECTORS:
        # print "%s: %s %s %s" % (image, detector_list.DETECTORS[(v_type, sn)], v_type, sn)
        return detector_list.DETECTORS[(v_type, sn)]
    else:
        return False
Exemplo n.º 8
0
def print_detector_info(image):
    """
    Print out information on the detector given an image
    """

    image_basename = os.path.basename(image)

    try:
        i = ImageFactory(image)
    except IOError as e:
        if "no format support found for" in e.message:
            print "No format support for %s" % image_basename
            return False
        else:
            print e
            return False
    except AttributeError as e:
        if "object has no attribute 'detectorbase'" in e.message:
            print "No format support for %s" % image_basename
            return False
        else:
            print text.red + e.message + text.stop
            return False

    print "\nInformation from iotbx ImageFactory"
    print "====================================="
    print "%20s::%s" % ("image", image_basename)
    print "%20s::%s" % ("vendortype", str(i.vendortype))
    # print "%20s" % "Parameters"
    for key, val in i.parameters.iteritems():
        print "%20s::%s" % (key, val)
Exemplo n.º 9
0
 def __init__(self,arg_module,verbose=True):
   self.verbose = verbose
   self.filenames = file_names(arg_module)
   self.images = []
   for indx,name in enumerate(self.filenames()):
       A = ImageFactory(name)
       self.images.append(A)
Exemplo n.º 10
0
def run(img_in):
    im = ImageFactory(img_in)
    im.read()
    print dir(im)
    print im.size2, im.size1
    data = numpy.array(im.linearintdata,
                       dtype=numpy.uint16).reshape(im.size2, im.size1)
    print data, data.dtype

    prefix = os.path.basename(img_in)
    of = h5py.File("%s_byteoffset.h5" % prefix, "w")
    grp = of.create_group("data")
    dset = grp.create_dataset(prefix,
                              data.shape,
                              dtype=data.dtype,
                              compression=CBF_BYTE_OFFSET)
    dset[...] = data
    of.close()
Exemplo n.º 11
0
def main(filenames, map_file, npoints=192, max_resolution=6, reverse_phi=False):
    rec_range = 1 / max_resolution

    image = ImageFactory(filenames[0])
    panel = image.get_detector()[0]
    beam = image.get_beam()
    s0 = beam.get_s0()
    pixel_size = panel.get_pixel_size()
    
    xlim, ylim = image.get_raw_data().all()
    
    xy = recviewer.get_target_pixels(panel, s0, xlim, ylim, max_resolution)
    
    s1 = panel.get_lab_coord(xy * pixel_size[0]) # FIXME: assumed square pixel
    s1 = s1 / s1.norms() * (1 / beam.get_wavelength()) # / is not supported...
    S = s1 - s0
    
    grid = flex.double(flex.grid(npoints, npoints, npoints), 0)
    cnts = flex.int(flex.grid(npoints, npoints, npoints), 0)
    
    for filename in filenames:
        print "Processing image", filename
        try:
            fill_voxels(ImageFactory(filename), grid, cnts, S, xy, reverse_phi, rec_range)
        except:
            print " Failed to process. Skipped this."
        
    recviewer.normalize_voxels(grid, cnts)
    
    uc = uctbx.unit_cell((npoints, npoints, npoints, 90, 90, 90))
    ccp4_map.write_ccp4_map(map_file, uc, sgtbx.space_group("P1"), 
                            (0, 0, 0), grid.all(), grid, 
                            flex.std_string(["cctbx.miller.fft_map"]))
    return
    from scitbx import fftpack
    fft = fftpack.complex_to_complex_3d(grid.all())
    grid_complex = flex.complex_double(
                            reals=flex.pow2(grid),
                            imags=flex.double(grid.size(), 0))
    grid_transformed = flex.abs(fft.backward(grid_complex))
    print flex.max(grid_transformed), flex.min(grid_transformed), grid_transformed.all()
    ccp4_map.write_ccp4_map(map_file, uc, sgtbx.space_group("P1"), 
                            (0, 0, 0), grid.all(), grid_transformed,
                            flex.std_string(["cctbx.miller.fft_map"]))
Exemplo n.º 12
0
def read_cmos_image(f, read_data=True, fast=True):
    h = {}
    data = None

    get_after = lambda l: l[l.index("=")+1:].rstrip(";\n ")
    if fast:
        for l in open(f):
            if "}" in l: break
            if l.startswith("SIZE1="):
                h["size1"] = int(get_after(l))
            elif l.startswith("SIZE2="):
                h["size2"]= int(get_after(l))
            elif l.startswith("TYPE="):
                assert "unsigned_short" in l
            elif l.startswith("PIXEL_SIZE="):
                h["pixel_size"]= float(get_after(l))
            elif l.startswith("DISTANCE="):
                h["distance"]= float(get_after(l))
            elif l.startswith("WAVELENGTH="):
                h["wavelength"]= float(get_after(l))
            elif l.startswith("BEAM_CENTER_X="):
                h["beamx"]= float(get_after(l))
            elif l.startswith("BEAM_CENTER_Y="):
                h["beamy"]= float(get_after(l))

        h["orgx"], h["orgy"] = h["beamx"]/h["pixel_size"], h["beamy"]/h["pixel_size"]

        if read_data:
            ifs = open(f, "rb")
            ifs.seek(-h["size1"]*h["size2"]*2, 2)
            data = numpy.fromfile(ifs, dtype=numpy.uint16).reshape(h["size2"],h["size1"])

    else:
        from iotbx.detectors import ImageFactory

        im = ImageFactory(f)
        h["orgx"], h["orgy"] = im.beamx/im.pixel_size, im.beamy/im.pixel_size
        h["wavelength"] = im.wavelength
        h["distance"] = im.distance
        if read_data:
            im.read()
            data = numpy.array(im.linearintdata, dtype=numpy.uint16).reshape(im.size2, im.size1)

    return h, data
Exemplo n.º 13
0
 def __init__(self, arg_module, phil_params, verbose=True):
     self.verbose = verbose
     self.filenames = file_names(arg_module)
     self.phil_params = phil_params
     self.images = []
     for indx, name in enumerate(self.filenames()):
         A = ImageFactory(name)
         self.site_modifications(A, self.filenames.FN[indx])
         self.images.append(A)
     self.acceptable_use_tests_basic()
Exemplo n.º 14
0
    def set_image(self, file_name_or_data, metrology_matrices=None, get_raw_data=None):

        self.reset_the_cache()
        if file_name_or_data is None:
          self.raw_image = None
          return
        if type(file_name_or_data) is type(""):
          from iotbx.detectors import ImageFactory
          self.raw_image = ImageFactory(file_name_or_data)
          self.raw_image.read()
        else:
          try:
            self.raw_image = file_name_or_data._raw
          except AttributeError:
            self.raw_image = file_name_or_data
        #print "SETTING NEW IMAGE",self.raw_image.filename

        # XXX Since there doesn't seem to be a good way to refresh the
        # image (yet), the metrology has to be applied here, and not
        # in frame.py.

        detector = self.raw_image.get_detector()

        if len(detector) > 1 and metrology_matrices is not None:
          self.raw_image.apply_metrology_from_matrices(metrology_matrices)

        if get_raw_data is not None:
          self.raw_image.set_raw_data(get_raw_data(self.raw_image))
        raw_data = self.raw_image.get_raw_data()
        if not isinstance(raw_data, tuple):
          raw_data = (raw_data,)

        if len(detector) > 1:
          self.flex_image = _get_flex_image_multipanel(
            brightness=self.current_brightness / 100,
            panels=detector,
            show_untrusted=self.show_untrusted,
            raw_data=raw_data)
        else:
          self.flex_image = _get_flex_image(
            brightness=self.current_brightness / 100,
            data=raw_data[0],
            saturation=self.raw_image.get_detector()[0].get_trusted_range()[1],
            vendortype=self.raw_image.__class__.__name__,
            show_untrusted=self.show_untrusted
          )

        self.flex_image.adjust(color_scheme=self.current_color_scheme)
Exemplo n.º 15
0
def main(filenames,
         map_file,
         npoints=192,
         max_resolution=6,
         reverse_phi=False):
    rec_range = 1 / max_resolution

    image = ImageFactory(filenames[0])
    panel = image.get_detector()[0]
    beam = image.get_beam()
    s0 = beam.get_s0()
    pixel_size = panel.get_pixel_size()

    xlim, ylim = image.get_raw_data().all()

    xy = recviewer.get_target_pixels(panel, s0, xlim, ylim, max_resolution)

    s1 = panel.get_lab_coord(xy * pixel_size[0])  # FIXME: assumed square pixel
    s1 = s1 / s1.norms() * (1 / beam.get_wavelength())  # / is not supported...
    S = s1 - s0

    grid = flex.double(flex.grid(npoints, npoints, npoints), 0)
    cnts = flex.int(flex.grid(npoints, npoints, npoints), 0)

    for filename in filenames:
        print "Processing image", filename
        try:
            fill_voxels(ImageFactory(filename), grid, cnts, S, xy, reverse_phi,
                        rec_range)
        except:
            print " Failed to process. Skipped this."

    recviewer.normalize_voxels(grid, cnts)

    uc = uctbx.unit_cell((npoints, npoints, npoints, 90, 90, 90))
    ccp4_map.write_ccp4_map(map_file, uc, sgtbx.space_group("P1"), (0, 0, 0),
                            grid.all(), grid,
                            flex.std_string(["cctbx.miller.fft_map"]))
    return
    from scitbx import fftpack
    fft = fftpack.complex_to_complex_3d(grid.all())
    grid_complex = flex.complex_double(reals=flex.pow2(grid),
                                       imags=flex.double(grid.size(), 0))
    grid_transformed = flex.abs(fft.backward(grid_complex))
    print flex.max(grid_transformed), flex.min(
        grid_transformed), grid_transformed.all()
    ccp4_map.write_ccp4_map(map_file, uc, sgtbx.space_group("P1"), (0, 0, 0),
                            grid.all(), grid_transformed,
                            flex.std_string(["cctbx.miller.fft_map"]))
Exemplo n.º 16
0
    def __init__(self, file_name):
        screen_params.__init__(self)
        # XXX major hack - Boost.Python doesn't really deal with Unicode strings
        if isinstance(file_name, unicode):
            file_name = str(file_name)
        if isinstance(file_name, str) or isinstance(file_name, dict):
            self.file_name = file_name
            from iotbx.detectors import ImageFactory, ImageException
            try:
                img = ImageFactory(file_name)
            except ImageException as e:
                raise Sorry(str(e))
            img.read()
        else:
            img = file_name  # assume it's already been read

        self._raw = img
        try:
            img.show_header()
        except Exception:
            pass  # intentional

        detector = self._raw.get_detector()
        if len(detector) == 1:
            # Image size only makes sense for monolithic detectors.
            image_size = detector[0].get_image_size()
            self.set_image_size(w=image_size[0], h=image_size[1])

        pixel_size = detector[0].get_pixel_size()
        for panel in detector:
            pstest = panel.get_pixel_size()
            assert pixel_size[0] == pixel_size[1] == pstest[0] == pstest[1]
        self.set_detector_resolution(pixel_size[0])

        try:
            from spotfinder.command_line.signal_strength import master_params
            params = master_params.extract()
            self._raw.initialize_viewer_properties(params)
        except Exception:
            pass  # intentional

        self._beam_center = None
        self._integration = None
        self._spots = None
        self._color_scheme = None
Exemplo n.º 17
0
class _Tiles(object):
    # maximum number of tiles held in each level cache
    MaxTileList = 512

    def __init__(self, filename):
        (self.tile_size_x, self.tile_size_y) = (256,256)
        self.levels = [-3,-2,-1,0,1,2,3,4,5]

        # set min and max tile levels
        self.min_level = -3
        self.max_level = 5
        self.extent = (-180.0, 180., -166.66 , 166.66) #longitude & latitude limits
        self.set_image(filename)
        self.current_brightness = 1.0
        self.current_color_scheme = 0
        self.user_requests_antialiasing = False

        self.show_untrusted = False

    def set_image(self, file_name_or_data, metrology_matrices=None, get_raw_data=None):

        self.reset_the_cache()
        if file_name_or_data is None:
          self.raw_image = None
          return
        if type(file_name_or_data) is type(""):
          from iotbx.detectors import ImageFactory
          self.raw_image = ImageFactory(file_name_or_data)
          self.raw_image.read()
        else:
          try:
            self.raw_image = file_name_or_data._raw
          except AttributeError:
            self.raw_image = file_name_or_data
        #print "SETTING NEW IMAGE",self.raw_image.filename

        # XXX Since there doesn't seem to be a good way to refresh the
        # image (yet), the metrology has to be applied here, and not
        # in frame.py.

        detector = self.raw_image.get_detector()

        if len(detector) > 1 and metrology_matrices is not None:
          self.raw_image.apply_metrology_from_matrices(metrology_matrices)

        if get_raw_data is not None:
          self.raw_image.set_raw_data(get_raw_data(self.raw_image))
        raw_data = self.raw_image.get_raw_data()
        if not isinstance(raw_data, tuple):
          raw_data = (raw_data,)

        if len(detector) > 1:
          self.flex_image = _get_flex_image_multipanel(
            brightness=self.current_brightness / 100,
            panels=detector,
            show_untrusted=self.show_untrusted,
            raw_data=raw_data)
        else:
          self.flex_image = _get_flex_image(
            brightness=self.current_brightness / 100,
            data=raw_data[0],
            saturation=self.raw_image.get_detector()[0].get_trusted_range()[1],
            vendortype=self.raw_image.__class__.__name__,
            show_untrusted=self.show_untrusted
          )

        self.flex_image.adjust(color_scheme=self.current_color_scheme)

    def set_image_data(self, raw_image_data):
      self.reset_the_cache()
      # XXX Since there doesn't seem to be a good way to refresh the
      # image (yet), the metrology has to be applied here, and not
      # in frame.py.

      detector = self.raw_image.get_detector()
      self.raw_image.set_raw_data(raw_image_data)
      if len(detector) == 1 and len(raw_image_data) == 1:
        raw_image_data = raw_image_data[0]

      if len(detector) > 1:
        self.flex_image = _get_flex_image_multipanel(
          brightness=self.current_brightness / 100,
          panels=detector,
          raw_data=raw_image_data)
      else:
        self.flex_image = _get_flex_image(
          brightness=self.current_brightness / 100,
          data=raw_image_data,
          saturation=self.raw_image.get_detector()[0].get_trusted_range()[1],
          vendortype=self.raw_image.__class__.__name__,
          show_untrusted=self.show_untrusted
        )

      self.flex_image.adjust(color_scheme=self.current_color_scheme)

    def update_brightness(self,b,color_scheme=0):
        raw_data = self.raw_image.get_raw_data()
        if not isinstance(raw_data, tuple):
          raw_data = (raw_data,)

        if len(self.raw_image.get_detector()) > 1:
          # XXX Special-case read of new-style images until multitile
          # images are fully supported in dxtbx.
          self.flex_image = _get_flex_image_multipanel(
            brightness=b / 100,
            panels=self.raw_image.get_detector(),
            show_untrusted=self.show_untrusted,
            raw_data=raw_data)
        else:
          self.flex_image = _get_flex_image(
            brightness=b / 100,
            data=raw_data[0],
            saturation=self.raw_image.get_detector()[0].get_trusted_range()[1],
            vendortype=self.raw_image.__class__.__name__,
            show_untrusted=self.show_untrusted
          )

        self.update_color_scheme(color_scheme)
        self.current_brightness = b

    def update_color_scheme(self,color_scheme=0):
        self.flex_image.adjust(color_scheme)
        self.reset_the_cache()
        self.UseLevel(self.zoom_level)
        self.current_color_scheme = color_scheme

    def reset_the_cache(self):

        # setup the tile caches and Least Recently Used lists
        self.cache = {}
        self.lru = {}
        for l in self.levels:
            self.cache[l] = {}
            self.lru[l] = []

    def flex_image_get_tile(self,x,y):
      # The supports_rotated_tiles_antialiasing_recommended flag in
      # the C++ FlexImage class indicates whether the underlying image
      # instance supports tilted readouts.  Anti-aliasing only makes
      # sense if it does.
      if self.raw_image is not None and \
        self.zoom_level >=2 and \
        self.flex_image.supports_rotated_tiles_antialiasing_recommended and \
        self.user_requests_antialiasing:
        # much more computationally intensive to prepare nice-looking pictures of tilted readout
        self.flex_image.setZoom(self.zoom_level+1)
        fraction = 512./self.flex_image.size1()/(2**(self.zoom_level+1))
        self.flex_image.setWindowCart(  y, x, fraction )
        self.flex_image.prep_string()
        w,h = self.flex_image.ex_size2(), self.flex_image.ex_size1()
        assert w==512
        assert h==512
        wx_image = wx.EmptyImage(w/2,h/2)
        import Image
        I = Image.fromstring("RGB",(512,512),self.flex_image.export_string)
        J = I.resize((256,256),Image.ANTIALIAS)
        wx_image.SetData(J.tostring())
        return wx_image.ConvertToBitmap()
      elif self.raw_image is not None:
        self.flex_image.setZoom(self.zoom_level)
        fraction = 256./self.flex_image.size1()/(2**self.zoom_level)
        self.flex_image.setWindowCart(  y, x, fraction )
        self.flex_image.prep_string()
        w,h = self.flex_image.ex_size2(), self.flex_image.ex_size1()
        assert w==256
        assert h==256
        wx_image = wx.EmptyImage(w,h)
        wx_image.SetData(self.flex_image.export_string)
        return wx_image.ConvertToBitmap()
      else:
        wx_image = wx.EmptyImage(256,256)
        return wx_image.ConvertToBitmap()

    def get_binning(self):
      if self.zoom_level>=0: return 1.
      return 2.**-self.zoom_level

    def UseLevel(self, n):
        """Prepare to serve tiles from the required level.

        n  The required level

        Returns a tuple (map_width, map_height, ppd_x, ppd_y) if succesful,
        else None.  The width/height values are pixels.  The ppd_? values are
        pixels-per-degree values for X and Y direction.
        """
        # try to get cache for this level, no cache means no level
        #print "IN USE LEVEL",n
        try:
            self.tile_cache = self.cache[n]
            self.tile_list = self.lru[n]
        except KeyError:
            return None
        self.zoom_level = n
        if self.raw_image is None: #dummy values if there is no image
          self.center_x_lon = self.center_y_lat = 500.
          return (1024,1024,1.,1.)
        self.num_tiles_x = int(math.ceil((self.flex_image.size1()*(2**self.zoom_level))/256.))
        self.num_tiles_y = int(math.ceil((self.flex_image.size2()*(2**self.zoom_level))/256.))
        self.ppd_x = 2.**self.zoom_level
        self.ppd_y = 2.**self.zoom_level
        #print "USELEVEL %d # tiles: %d %d"%(n,self.num_tiles_x,self.num_tiles_y)
        #print "USELEVEL %d returning"%n,(self.tile_size_x * self.num_tiles_x,
        #        self.tile_size_y * self.num_tiles_y,
        #        self.ppd_x, self.ppd_y)
        # The longitude & latitude coordinates at the image center:
        self.center_x_lon = self.extent[0] + (1./self.ppd_x) * (0 +
          self.flex_image.size2() * (2**self.zoom_level) / 2.
          )
        self.center_y_lat = self.extent[3] - (1./self.ppd_y) * (0 +
          self.flex_image.size1() * (2**self.zoom_level) / 2.
          )
        # The 2+num_tiles is just a trick to get PySlip to think the map is
        # slightly larger, allowing zoom level -3 to be properly framed:
        # ....for larger display sizes it is necessary to increase this...
        # ....can tile_generator get the display size & figure it out?
        return (self.tile_size_x * (2+self.num_tiles_x),
                self.tile_size_y * (2+self.num_tiles_y),
                self.ppd_x, self.ppd_y)

    def get_initial_instrument_centering_within_picture_as_lon_lat(self):
      import sys
      detector = self.raw_image.get_detector()
      if sys.platform.lower().find("linux") >= 0:
        if len(detector) > 1:
          return 0.,0.
        else:
          return self.center_x_lon-self.extent[0], self.center_y_lat-self.extent[3]
      else:
        if len(detector) > 1:
          return self.extent[0], self.extent[3]
        else:
          return self.center_x_lon, self.center_y_lat

    def GetTile(self, x, y):
        #from libtbx.development.timers import Timer
        #T = Timer("get tile")
        """Get bitmap for tile at tile coords (x, y).

        x  X coord of tile required (tile coordinates)
        y  Y coord of tile required (tile coordinates)

        Returns bitmap object containing the tile image.
        Tile coordinates are measured from map top-left.
        """
        try:
            # if tile in cache, return it from there
            pic = self.tile_cache[(x, y)]
            index = self.tile_list.index((x, y))
            del self.tile_list[index]
        except KeyError:
            pic = self.flex_image_get_tile(x,y)
            self.tile_cache[(x, y)] = pic

        self.tile_list.insert(0, (x, y))
        if len(self.tile_cache)>=self.MaxTileList:
          del self.tile_cache[self.tile_list[-1]]
          del self.tile_list[-1]
        return pic

    def get_flex_pixel_coordinates(self, lon, lat):
      fast_picture_coord_pixel_scale, slow_picture_coord_pixel_scale = \
        self.lon_lat_to_picture_fast_slow(lon,lat)
      if self.flex_image.supports_rotated_tiles_antialiasing_recommended: # for generic_flex_image
        tilted = self.flex_image.picture_to_readout(
          slow_picture_coord_pixel_scale,fast_picture_coord_pixel_scale)
        return tilted
      else: # standard flex_image
        return slow_picture_coord_pixel_scale,fast_picture_coord_pixel_scale

    def lon_lat_to_picture_fast_slow(self,longitude,latitude):
      # input latitude and longitude in degrees (conceptually)
      # output fast and slow picture coordinates in units of detector pixels
      # slow is pointing down (x).  fast is pointing right (y).

      detector = self.raw_image.get_detector()
      if len(detector) == 1:
        (size2, size1) = detector[0].get_image_size()
      else:
        # XXX Special-case until multitile detectors fully supported.
        (size1, size2) = (self.flex_image.size1(), self.flex_image.size2())

      return \
        (size2/2.) - (self.center_x_lon - longitude),  \
        (size1/2.) - (latitude - self.center_y_lat)

    def picture_fast_slow_to_lon_lat(self,pic_fast_pixel,pic_slow_pixel):
      # inverse of the preceding function

      detector = self.raw_image.get_detector()
      if detector.num_panels() == 1:
        (size1, size2) = detector.get_image_size()
      else:
        # XXX Special-case until multitile detectors fully supported.
        (size1, size2) = (self.flex_image.size1(), self.flex_image.size2())

      return \
        (size2/2.) - self.center_x_lon - pic_fast_pixel, \
        (size1/2.) + self.center_y_lat - pic_slow_pixel

    def picture_fast_slow_to_map_relative(self,pic_fast_pixel,pic_slow_pixel):
      #return up/down, left/right map relative coords for pyslip layers
      return pic_fast_pixel+self.extent[0],-pic_slow_pixel+self.extent[3]

    def map_relative_to_picture_fast_slow(self, map_rel_vert, map_rel_horiz):
      # return fast, slow picture coords
      return map_rel_vert-self.extent[0],-map_rel_horiz+self.extent[3]

    def vec_picture_fast_slow_to_map_relative(self,vector):
      value = []
      for vec in vector:
        value.append(self.picture_fast_slow_to_map_relative(vec[0],vec[1]))
      return value

    def get_spotfinder_data(self, params):

      pointdata = []
      test_pattern = False
      if test_pattern is True and self.raw_image.__class__.__name__.find("CSPadDetector") >= 0:
        key_count = -1
        for key, asic in self.raw_image._tiles.iteritems():
          key_count += 1
          focus = asic.focus()
          for slow in xrange(0,focus[0],20):
            for fast in xrange(0,focus[1],20):
              slowpic,fastpic = self.flex_image.tile_readout_to_picture(key_count,slow,fast)
              mr1,mr2 = self.picture_fast_slow_to_map_relative(fastpic,slowpic)
              pointdata.append((mr1,mr2,{"data":key}))

      elif (self.raw_image.__class__.__name__.find("CSPadDetector") >= 0):
        from cxi_xdr_xes.cftbx.spotfinder.speckfinder import spotfind_readout

        key_count = -1
        for key, asic in self.raw_image._tiles.iteritems():
          key_count += 1
          indexing = spotfind_readout(
              readout=asic,
              peripheral_margin=params.spotfinder.peripheral_margin)

          for spot in indexing:
            slow = int(round(spot[0]))
            fast = int(round(spot[1]))

            slowpic,fastpic = self.flex_image.tile_readout_to_picture(key_count,slow,fast)
            mr1,mr2 = self.picture_fast_slow_to_map_relative(fastpic,slowpic)
            pointdata.append((mr1,mr2,{"data":key}))

      else:
        from spotfinder.command_line.signal_strength import master_params
        working_params = master_params.fetch(sources = []) #placeholder for runtime mods
        working_params.show(expert_level=1)
        distl_params = working_params.extract()

        spotfinder,frameno = self.raw_image.get_spotfinder(distl_params)
        spots = spotfinder.images[frameno]["spots_total"]
        for spot in spots:
          mr = self.picture_fast_slow_to_map_relative(
              spot.max_pxl_y() + 0.5, spot.max_pxl_x() + 0.5)
#             spot.ctr_mass_y() + 0.5, spot.ctr_mass_x() + 0.5)
          pointdata.append(mr)
      return pointdata

    def get_effective_tiling_data(self, params):
      box_data = []
      text_data = []
      if hasattr(self.raw_image, 'get_tile_manager'):
        IT = self.raw_image.get_tile_manager(params).effective_tiling_as_flex_int()
        for i in xrange(len(IT) // 4):
          tile = IT[4*i:4*i+4]
          attributes = {'color': '#0000FFA0', 'width': 1, 'closed': False}
          box_data.append(
              ((self.picture_fast_slow_to_map_relative(tile[1], tile[0]),
                self.picture_fast_slow_to_map_relative(tile[1], tile[2])),
               attributes))
          box_data.append(
              ((self.picture_fast_slow_to_map_relative(tile[1], tile[0]),
                self.picture_fast_slow_to_map_relative(tile[3], tile[0])),
               attributes))
          box_data.append(
              ((self.picture_fast_slow_to_map_relative(tile[1], tile[2]),
                self.picture_fast_slow_to_map_relative(tile[3], tile[2])),
               attributes))
          box_data.append(
              ((self.picture_fast_slow_to_map_relative(tile[3], tile[0]),
                self.picture_fast_slow_to_map_relative(tile[3], tile[2])),
               attributes))
          txt_x, txt_y = self.picture_fast_slow_to_map_relative(
              (tile[1]+tile[3])//2, (tile[0]+tile[2])//2)
          text_data.append((txt_x, txt_y, "%i" %i))
      return box_data, text_data

    def get_resolution (self, x, y, readout=None) :
        """
        Determine the resolution of a pixel.
        Arguments are in image pixel coordinates (starting from 1,1).
        """

        d_min = None
        detector = self.raw_image.get_detector()
        beam = self.raw_image.get_beam()
        if detector is None or beam is None:
          return None
        beam = beam.get_s0()

        if len(detector) > 1:
          if readout is None:
            return None

          panel = detector[readout]

        else:
          panel = detector[0]

        if abs(panel.get_distance()) > 0:
          return panel.get_resolution_at_pixel(beam, (x, y))
        else:
          return None

    def get_detector_distance (self) :
        detector = self.raw_image.get_detector()
        if len(detector) == 1:
          dist = abs(detector[0].get_distance())
        else:
          # XXX Special-case until multitile detectors fully
          # supported.
          dist = self.raw_image.distance
        twotheta = self.get_detector_2theta()
        if (twotheta == 0.0) :
            return dist
        else :
            return dist / math.cos(twotheta)

    def get_detector_2theta (self) :
        from scitbx.matrix import col

        detector = self.raw_image.get_detector()
        if len(detector) == 1:
          n = col(detector[0].get_normal())
          s0 = col(self.raw_image.get_beam().get_unit_s0())
          two_theta = s0.angle(n, deg=False)
        else:
          # XXX Special-case until multitile detectors fully
          # supported.
          try:
            two_theta = self.raw_image.twotheta * math.pi / 180
          except AttributeError:
            two_theta = 0

        return two_theta
Exemplo n.º 18
0
def createInput(image_dir, site, logger):
    logger.debug('createInput')
    #import glob
    from iotbx.detectors import ImageFactory
    try:
        img_site_id, img_site, c_site, imgs = site
        l1 = []
        l2 = []
        d = {}
        pids = []
        vendortype = ImageFactory(imgs[0]).vendortype
        if vendortype == 'ADSC-HF4M':
            from detectors.rapd_adsc import Hf4mReadHeader as readHeader
        elif vendortype == 'Pilatus-6M':
            from detectors.rapd_pilatus import pilatus_read_header as readHeader
        elif vendortype == 'ADSC':
            from detectors.rapd_adsc import Q315ReadHeader as readHeader
        else:
            from detectors.mar import MarReadHeader as readHeader
        l = [p for p in imgs if p.count('priming_shot') == False
             ]  #Remove priming shot (NE-CAT ONLY)
        for x in range(2):
            for i in l:
                if x == 0:
                    #Get headers first
                    header = readHeader(i)
                    #Send images to ImageFactory to read the header (TODO).
                    #Send images to RAM on all cluster nodes first.
                    if RAM == True:
                        image_path = os.path.join(
                            '/dev/shm',
                            os.path.basename(header.get('fullname')))
                        command = 'cp %s %s' % (header.get('fullname'),
                                                image_path)
                        #ONLY work at NE-CAT
                        job = Process(target=Utils.rocksCommand,
                                      args=(command, logger))
                        job.start()
                        pids.append(job)
                    else:
                        image_path = header.get('fullname')
                    x1, y1 = calc_beamcenter(round(header.get('distance')))
                    l1.append({#'beam_center_x' : round(header.get('beam_center_x'),3),
                        #'beam_center_y' : round(header.get('beam_center_y'),3),
                        #'beam_center_x' : 150.049, #BM
                        #'beam_center_y' : 151.148, #BM
                        #'beam_center_x' : 151.186, #ID
                        #'beam_center_y' : 144.821, #ID
                        #'beam_center_x' : 150.31, #BM
                        #'beam_center_y' : 149.53, #BM
                        'beam_center_x' : x1, #BM
                        'beam_center_y' : y1, #BM
                        'spacegroup'    : SPACEGROUP,
                                      'fullname'      : image_path,
                                      'distance'      : round(header.get('distance')),
                                      'vendortype'    : vendortype,
                                     })
                else:
                    #Then sort by distance for input
                    l3 = []
                    if os.path.basename(i) not in (l2):
                        for y in range(2):
                            for z in range(len(l1)):
                                if y == 0:
                                    if os.path.basename(i) == os.path.basename(
                                            l1[z].get('fullname')):
                                        dist = l1[z].get('distance')
                                        l3.append(l1[z])
                                        l2.append(
                                            os.path.basename(
                                                l1[z].get('fullname')))
                                elif l1[z].get('distance') == dist:
                                    if os.path.basename(
                                            l1[z].get('fullname')) not in l2:
                                        l3.append(l1[z])
                                        l2.append(
                                            os.path.basename(
                                                l1[z].get('fullname')))
                        d[str(dist)] = tuple(l3[:2])
        #wait for images to be copied to RAM.
        if RAM == True:
            while len(pids) != 0:
                for job in pids:
                    if job.is_alive() == False:
                        pids.remove(job)
                time.sleep(1)

        inp = {
            'directories': {
                'work': WORK_DIR
            },
            'info': d,
            'command': 'INDEX+STRATEGY',
            'preferences': {
                "sample_type": "Protein",
                "beam_flip": "False",
                "multiprocessing": "True",
                "a": 0.0,
                "b": 0.0,
                "c": 0.0,
                "alpha": 0.0,
                "beta": 0.0,
                "gamma": 0.0
            },
            'site_parameters': {
                'img_site_id': img_site_id,
                'img_site': img_site,
                'cluster_site': c_site
            },
            'return_address': ("127.0.0.1", 50000)
        }
        Utils.pp(inp)
        return (inp)

    except:
        logger.exception('**Error in Handler.postprocess**')
        print 'Could not create input script from folder specified!'
        return (None)
Exemplo n.º 19
0
 def _try_as_img(self):
     from iotbx.detectors import ImageFactory
     img = ImageFactory(self.file_name)
     img.read()
     self._file_type = "img"
     self._file_object = img
Exemplo n.º 20
0
class _Tiles(object):
    # maximum number of tiles held in each level cache
    MaxTileList = 512

    def __init__(self, filename):
        (self.tile_size_x, self.tile_size_y) = (256, 256)
        self.levels = [-3, -2, -1, 0, 1, 2, 3, 4, 5]

        # set min and max tile levels
        self.min_level = -3
        self.max_level = 5
        self.extent = (-180.0, 180.0, -166.66, 166.66
                       )  # longitude & latitude limits
        self.set_image(filename)
        self.current_brightness = 1.0
        self.current_color_scheme = 0
        self.user_requests_antialiasing = False

        self.show_untrusted = False

    def set_image(self,
                  file_name_or_data,
                  metrology_matrices=None,
                  get_raw_data=None):
        self.reset_the_cache()
        if file_name_or_data is None:
            self.raw_image = None
            return
        if isinstance(file_name_or_data, six.string_types):
            from iotbx.detectors import ImageFactory

            self.raw_image = ImageFactory(file_name_or_data)
            self.raw_image.read()
        else:
            try:
                self.raw_image = file_name_or_data._raw
            except AttributeError:
                self.raw_image = file_name_or_data
        # print "SETTING NEW IMAGE",self.raw_image.filename

        # XXX Since there doesn't seem to be a good way to refresh the
        # image (yet), the metrology has to be applied here, and not
        # in frame.py.

        detector = self.raw_image.get_detector()

        if len(detector) > 1 and metrology_matrices is not None:
            self.raw_image.apply_metrology_from_matrices(metrology_matrices)

        if get_raw_data is not None:
            self.raw_image.set_raw_data(get_raw_data(self.raw_image))
        raw_data = self.raw_image.get_raw_data()
        if not isinstance(raw_data, tuple):
            raw_data = (raw_data, )

        if len(detector) > 1:
            self.flex_image = _get_flex_image_multipanel(
                brightness=self.current_brightness / 100,
                panels=detector,
                show_untrusted=self.show_untrusted,
                raw_data=raw_data,
                beam=self.raw_image.get_beam(),
                color_scheme=self.current_color_scheme,
            )
        else:
            self.flex_image = _get_flex_image(
                brightness=self.current_brightness / 100,
                data=raw_data[0],
                saturation=self.raw_image.get_detector()
                [0].get_trusted_range()[1],
                vendortype=self.raw_image.get_vendortype(),
                show_untrusted=self.show_untrusted,
                color_scheme=self.current_color_scheme,
            )

        if self.zoom_level >= 0:
            self.flex_image.adjust(color_scheme=self.current_color_scheme)

    def set_image_data(self, raw_image_data):
        self.reset_the_cache()
        # XXX Since there doesn't seem to be a good way to refresh the
        # image (yet), the metrology has to be applied here, and not
        # in frame.py.

        detector = self.raw_image.get_detector()
        self.raw_image.set_raw_data(raw_image_data)
        if len(detector) == 1 and len(raw_image_data) == 1:
            raw_image_data = raw_image_data[0]

        if len(detector) > 1:
            self.flex_image = _get_flex_image_multipanel(
                brightness=self.current_brightness / 100,
                panels=detector,
                raw_data=raw_image_data,
                beam=self.raw_image.get_beam(),
            )
        else:
            self.flex_image = _get_flex_image(
                brightness=self.current_brightness / 100,
                data=raw_image_data,
                saturation=self.raw_image.get_detector()
                [0].get_trusted_range()[1],
                vendortype=self.raw_image.get_vendortype(),
                show_untrusted=self.show_untrusted,
            )

        self.flex_image.adjust(color_scheme=self.current_color_scheme)

    def update_brightness(self, b, color_scheme=0):
        raw_data = self.raw_image.get_raw_data()
        if not isinstance(raw_data, tuple):
            raw_data = (raw_data, )

        if len(self.raw_image.get_detector()) > 1:
            # XXX Special-case read of new-style images until multitile
            # images are fully supported in dxtbx.
            self.flex_image = _get_flex_image_multipanel(
                brightness=b / 100,
                panels=self.raw_image.get_detector(),
                show_untrusted=self.show_untrusted,
                raw_data=raw_data,
                beam=self.raw_image.get_beam(),
                color_scheme=color_scheme,
            )
        else:
            self.flex_image = _get_flex_image(
                brightness=b / 100,
                data=raw_data[0],
                saturation=self.raw_image.get_detector()
                [0].get_trusted_range()[1],
                vendortype=self.raw_image.get_vendortype(),
                show_untrusted=self.show_untrusted,
                color_scheme=color_scheme,
            )

        self.reset_the_cache()
        self.UseLevel(self.zoom_level)
        self.current_color_scheme = color_scheme
        self.current_brightness = b
        self.flex_image.adjust(color_scheme)

    def update_color_scheme(self, color_scheme=0):
        self.flex_image.adjust(color_scheme)
        self.reset_the_cache()
        self.UseLevel(self.zoom_level)
        self.current_color_scheme = color_scheme

    def reset_the_cache(self):
        # setup the tile caches and Least Recently Used lists
        self.cache = {}
        self.lru = {}
        for l in self.levels:
            self.cache[l] = {}
            self.lru[l] = []

    def flex_image_get_tile(self, x, y):
        # The supports_rotated_tiles_antialiasing_recommended flag in
        # the C++ FlexImage class indicates whether the underlying image
        # instance supports tilted readouts.  Anti-aliasing only makes
        # sense if it does.
        if (self.raw_image is not None and self.zoom_level >= 2 and
                self.flex_image.supports_rotated_tiles_antialiasing_recommended
                and self.user_requests_antialiasing):
            # much more computationally intensive to prepare nice-looking pictures of tilted readout
            self.flex_image.setZoom(self.zoom_level + 1)
            fraction = 512.0 / self.flex_image.size1() / (2**(self.zoom_level +
                                                              1))
            self.flex_image.setWindowCart(y, x, fraction)
            self.flex_image.prep_string()
            w, h = self.flex_image.ex_size2(), self.flex_image.ex_size1()
            assert w == 512
            assert h == 512
            wx_image = wx.EmptyImage(w / 2, h / 2)
            import PIL.Image as Image

            I = Image.frombytes("RGB", (512, 512), self.flex_image.as_bytes())
            J = I.resize((256, 256), Image.ANTIALIAS)
            wx_image.SetData(J.tostring())
            return wx_image.ConvertToBitmap()
        elif self.raw_image is not None:
            self.flex_image.setZoom(self.zoom_level)
            fraction = 256.0 / self.flex_image.size1() / (2**self.zoom_level)
            self.flex_image.setWindowCart(y, x, fraction)
            self.flex_image.prep_string()
            w, h = self.flex_image.ex_size2(), self.flex_image.ex_size1()
            assert w == 256
            assert h == 256
            wx_image = wx.EmptyImage(w, h)
            wx_image.SetData(self.flex_image.as_bytes())
            return wx_image.ConvertToBitmap()
        else:
            wx_image = wx.EmptyImage(256, 256)
            return wx_image.ConvertToBitmap()

    def get_binning(self):
        if self.zoom_level >= 0:
            return 1.0
        return 2.0**-self.zoom_level

    def UseLevel(self, n):
        """Prepare to serve tiles from the required level.

        n  The required level

        Returns a tuple (map_width, map_height, ppd_x, ppd_y) if successful,
        else None.  The width/height values are pixels.  The ppd_? values are
        pixels-per-degree values for X and Y direction.
        """
        # try to get cache for this level, no cache means no level
        # print "IN USE LEVEL",n
        try:
            self.tile_cache = self.cache[n]
            self.tile_list = self.lru[n]
        except KeyError:
            return None
        self.zoom_level = n
        if self.raw_image is None:  # dummy values if there is no image
            self.center_x_lon = self.center_y_lat = 500.0
            return (1024, 1024, 1.0, 1.0)
        self.num_tiles_x = int(
            math.ceil(
                (self.flex_image.size1() * (2**self.zoom_level)) / 256.0))
        self.num_tiles_y = int(
            math.ceil(
                (self.flex_image.size2() * (2**self.zoom_level)) / 256.0))
        self.ppd_x = 2.0**self.zoom_level
        self.ppd_y = 2.0**self.zoom_level
        # print "USELEVEL %d # tiles: %d %d"%(n,self.num_tiles_x,self.num_tiles_y)
        # print "USELEVEL %d returning"%n,(self.tile_size_x * self.num_tiles_x,
        #        self.tile_size_y * self.num_tiles_y,
        #        self.ppd_x, self.ppd_y)
        # The longitude & latitude coordinates at the image center:
        self.center_x_lon = self.extent[0] + (1.0 / self.ppd_x) * (
            0 + self.flex_image.size2() * (2**self.zoom_level) / 2.0)
        self.center_y_lat = self.extent[3] - (1.0 / self.ppd_y) * (
            0 + self.flex_image.size1() * (2**self.zoom_level) / 2.0)
        # The 2+num_tiles is just a trick to get PySlip to think the map is
        # slightly larger, allowing zoom level -3 to be properly framed:
        # ....for larger display sizes it is necessary to increase this...
        # ....can tile_generator get the display size & figure it out?
        return (
            self.tile_size_x * (2 + self.num_tiles_x),
            self.tile_size_y * (2 + self.num_tiles_y),
            self.ppd_x,
            self.ppd_y,
        )

    def get_initial_instrument_centering_within_picture_as_lon_lat(self):
        import sys

        detector = self.raw_image.get_detector()
        if sys.platform.lower().find("linux") >= 0:
            if len(detector) > 1:
                return 0.0, 0.0
            else:
                return (
                    self.center_x_lon - self.extent[0],
                    self.center_y_lat - self.extent[3],
                )
        else:
            if len(detector) > 1:
                return self.extent[0], self.extent[3]
            else:
                return self.center_x_lon, self.center_y_lat

    def GetTile(self, x, y):
        # from libtbx.development.timers import Timer
        # T = Timer("get tile")
        """Get bitmap for tile at tile coords (x, y).

        x  X coord of tile required (tile coordinates)
        y  Y coord of tile required (tile coordinates)

        Returns bitmap object containing the tile image.
        Tile coordinates are measured from map top-left.
        """
        try:
            # if tile in cache, return it from there
            pic = self.tile_cache[(x, y)]
            index = self.tile_list.index((x, y))
            del self.tile_list[index]
        except KeyError:
            pic = self.flex_image_get_tile(x, y)
            self.tile_cache[(x, y)] = pic

        self.tile_list.insert(0, (x, y))
        if len(self.tile_cache) >= self.MaxTileList:
            del self.tile_cache[self.tile_list[-1]]
            del self.tile_list[-1]
        return pic

    def get_flex_pixel_coordinates(self, lon, lat):
        fast_picture_coord_pixel_scale, slow_picture_coord_pixel_scale = self.lon_lat_to_picture_fast_slow(
            lon, lat)
        if (self.flex_image.supports_rotated_tiles_antialiasing_recommended
            ):  # for generic_flex_image
            tilted = self.flex_image.picture_to_readout(
                slow_picture_coord_pixel_scale, fast_picture_coord_pixel_scale)
            return tilted
        else:  # standard flex_image
            return slow_picture_coord_pixel_scale, fast_picture_coord_pixel_scale

    def lon_lat_to_picture_fast_slow(self, longitude, latitude):
        # input latitude and longitude in degrees (conceptually)
        # output fast and slow picture coordinates in units of detector pixels
        # slow is pointing down (x).  fast is pointing right (y).

        detector = self.raw_image.get_detector()
        if len(detector) == 1:
            (size2, size1) = detector[0].get_image_size()
        else:
            # XXX Special-case until multitile detectors fully supported.
            (size1, size2) = (self.flex_image.size1(), self.flex_image.size2())

        return (
            (size2 / 2.0) - (self.center_x_lon - longitude),
            (size1 / 2.0) - (latitude - self.center_y_lat),
        )

    def picture_fast_slow_to_lon_lat(self, pic_fast_pixel, pic_slow_pixel):
        # inverse of the preceding function

        detector = self.raw_image.get_detector()
        if detector.num_panels() == 1:
            (size1, size2) = detector.get_image_size()
        else:
            # XXX Special-case until multitile detectors fully supported.
            (size1, size2) = (self.flex_image.size1(), self.flex_image.size2())

        return (
            (size2 / 2.0) - self.center_x_lon - pic_fast_pixel,
            (size1 / 2.0) + self.center_y_lat - pic_slow_pixel,
        )

    def picture_fast_slow_to_map_relative(self, pic_fast_pixel,
                                          pic_slow_pixel):
        # return up/down, left/right map relative coords for pyslip layers
        return pic_fast_pixel + self.extent[0], -pic_slow_pixel + self.extent[3]

    def map_relative_to_picture_fast_slow(self, map_rel_vert, map_rel_horiz):
        # return fast, slow picture coords
        return map_rel_vert - self.extent[0], -map_rel_horiz + self.extent[3]

    def vec_picture_fast_slow_to_map_relative(self, vector):
        value = []
        for vec in vector:
            value.append(self.picture_fast_slow_to_map_relative(
                vec[0], vec[1]))
        return value

    def get_spotfinder_data(self, params):

        pointdata = []
        test_pattern = False
        if (test_pattern is True and
                self.raw_image.__class__.__name__.find("CSPadDetector") >= 0):
            key_count = -1
            for key, asic in self.raw_image._tiles.items():
                key_count += 1
                focus = asic.focus()
                for slow in range(0, focus[0], 20):
                    for fast in range(0, focus[1], 20):
                        slowpic, fastpic = self.flex_image.tile_readout_to_picture(
                            key_count, slow, fast)
                        mr1, mr2 = self.picture_fast_slow_to_map_relative(
                            fastpic, slowpic)
                        pointdata.append((mr1, mr2, {"data": key}))

        elif self.raw_image.__class__.__name__.find("CSPadDetector") >= 0:
            from cxi_xdr_xes.cftbx.spotfinder.speckfinder import spotfind_readout

            key_count = -1
            for key, asic in self.raw_image._tiles.items():
                key_count += 1
                indexing = spotfind_readout(
                    readout=asic,
                    peripheral_margin=params.spotfinder.peripheral_margin)

                for spot in indexing:
                    slow = int(round(spot[0]))
                    fast = int(round(spot[1]))

                    slowpic, fastpic = self.flex_image.tile_readout_to_picture(
                        key_count, slow, fast)
                    mr1, mr2 = self.picture_fast_slow_to_map_relative(
                        fastpic, slowpic)
                    pointdata.append((mr1, mr2, {"data": key}))

        else:
            from spotfinder.command_line.signal_strength import master_params

            working_params = master_params.fetch(
                sources=[])  # placeholder for runtime mods
            working_params.show(expert_level=1)
            distl_params = working_params.extract()

            spotfinder, frameno = self.raw_image.get_spotfinder(distl_params)
            spots = spotfinder.images[frameno]["spots_total"]
            for spot in spots:
                mr = self.picture_fast_slow_to_map_relative(
                    spot.max_pxl_y() + 0.5,
                    spot.max_pxl_x() + 0.5)
                #             spot.ctr_mass_y() + 0.5, spot.ctr_mass_x() + 0.5)
                pointdata.append(mr)
        return pointdata

    def get_effective_tiling_data(self, params):
        box_data = []
        text_data = []
        if hasattr(self.raw_image, "get_tile_manager"):
            IT = self.raw_image.get_tile_manager(
                params).effective_tiling_as_flex_int()
            for i in range(len(IT) // 4):
                tile = IT[4 * i:4 * i + 4]
                attributes = {
                    "color": "#0000FFA0",
                    "width": 1,
                    "closed": False
                }
                box_data.append((
                    (
                        self.picture_fast_slow_to_map_relative(
                            tile[1], tile[0]),
                        self.picture_fast_slow_to_map_relative(
                            tile[1], tile[2]),
                    ),
                    attributes,
                ))
                box_data.append((
                    (
                        self.picture_fast_slow_to_map_relative(
                            tile[1], tile[0]),
                        self.picture_fast_slow_to_map_relative(
                            tile[3], tile[0]),
                    ),
                    attributes,
                ))
                box_data.append((
                    (
                        self.picture_fast_slow_to_map_relative(
                            tile[1], tile[2]),
                        self.picture_fast_slow_to_map_relative(
                            tile[3], tile[2]),
                    ),
                    attributes,
                ))
                box_data.append((
                    (
                        self.picture_fast_slow_to_map_relative(
                            tile[3], tile[0]),
                        self.picture_fast_slow_to_map_relative(
                            tile[3], tile[2]),
                    ),
                    attributes,
                ))
                txt_x, txt_y = self.picture_fast_slow_to_map_relative(
                    (tile[1] + tile[3]) // 2, (tile[0] + tile[2]) // 2)
                text_data.append((txt_x, txt_y, "%i" % i))
        return box_data, text_data

    def get_resolution(self, x, y, readout=None):
        """
        Determine the resolution of a pixel.
        Arguments are in image pixel coordinates (starting from 1,1).
        """

        detector = self.raw_image.get_detector()
        beam = self.raw_image.get_beam()
        if detector is None or beam is None:
            return None
        beam = beam.get_s0()

        if len(detector) > 1:
            if readout is None:
                return None

            panel = detector[readout]

        else:
            panel = detector[0]

        if abs(panel.get_distance()) > 0:
            return panel.get_resolution_at_pixel(beam, (x, y))
        else:
            return None

    def get_detector_distance(self):
        detector = self.raw_image.get_detector()
        if len(detector) == 1:
            dist = abs(detector[0].get_distance())
        else:
            # XXX Special-case until multitile detectors fully
            # supported.
            dist = self.raw_image.distance
        twotheta = self.get_detector_2theta()
        if twotheta == 0.0:
            return dist
        else:
            return dist / math.cos(twotheta)

    def get_detector_2theta(self):
        from scitbx.matrix import col

        detector = self.raw_image.get_detector()
        if len(detector) == 1:
            n = col(detector[0].get_normal())
            s0 = col(self.raw_image.get_beam().get_unit_s0())
            two_theta = s0.angle(n, deg=False)
        else:
            # XXX Special-case until multitile detectors fully
            # supported.
            try:
                two_theta = self.raw_image.twotheta * math.pi / 180
            except AttributeError:
                two_theta = 0

        return two_theta
Exemplo n.º 21
0
from __future__ import division
from __future__ import print_function
import sys
import numpy
from iotbx.detectors import ImageFactory
from matplotlib import pyplot as plt

image = ImageFactory(sys.argv[1])
image.read()

nfast = image.parameters["SIZE1"]
nslow = image.parameters["SIZE2"]

data = image.get_raw_data()
print("here 1")
data2d = numpy.reshape(numpy.array(data, dtype=float), (nfast, nslow))
print("here 2")
data2dsmoth = numpy.zeros(nfast * nslow, dtype=float).reshape(nfast, nslow)
diffdata2d = numpy.zeros(nfast * nslow, dtype=float).reshape(nfast, nslow)

print("nslow, nfast =", nslow, nfast)

print("max(data2d) =", numpy.max(data2d))
print("min(data2d) =", numpy.min(data2d))

for f in range(1, nfast - 1):
    for s in range(1, nslow - 1):
        pscan = float(numpy.sum(data2d[f - 1 : f + 1, s - 1 : s + 1]) / 9.0)
        data2dsmoth[f, s] = pscan

print("max(data2dsmoth) =", numpy.max(data2dsmoth))
Exemplo n.º 22
0
from __future__ import division
import sys
import numpy
from iotbx.detectors import ImageFactory
from matplotlib import pyplot as plt

image = ImageFactory( sys.argv[1] )
image.read()

nfast = image.parameters['SIZE1']
nslow = image.parameters['SIZE2']

data = image.get_raw_data()
print 'here 1'
data2d = numpy.reshape( numpy.array( data, dtype = float ), ( nfast , nslow ) )
print 'here 2'
data2dsmoth = numpy.zeros( nfast * nslow, dtype = float ).reshape( nfast, nslow )
diffdata2d = numpy.zeros( nfast * nslow, dtype = float ).reshape( nfast, nslow )

print "nslow, nfast =", nslow, nfast

print "max(data2d) =", numpy.max( data2d )
print "min(data2d) =", numpy.min( data2d )

for f in range( 1, nfast - 1 ):
  for s in range( 1, nslow - 1 ):
    pscan = float( numpy.sum( data2d[f - 1:f + 1, s - 1:s + 1] ) / 9.0 )
    data2dsmoth[f, s] = pscan

print "max(data2dsmoth) =", numpy.max( data2dsmoth )
print "min(data2dsmoth) =", numpy.min( data2dsmoth )
Exemplo n.º 23
0
 def _try_as_img (self) :
   from iotbx.detectors import ImageFactory
   img = ImageFactory(self.file_name)
   img.read()
   self._file_type = "img"
   self._file_object = img