fabio.file_series

Package fabio :: Module file_series |
[hide private]
[frames] | no frames]

# Source Code for Module fabio.file_series

      1  #!/usr/bin/env python
      2
      3  """
      4
      5  Authors:
      6  ........
      7
      8  * Henning O. Sorensen & Erik Knudsen
      9    Center for Fundamental Research: Metal Structures in Four Dimensions
     10    Risoe National Laboratory
     11    Frederiksborgvej 399
     12    DK-4000 Roskilde
     13    email:erik.knudsen@risoe.dk
     14  * Jon Wright, ESRF
     15
     16  """
     17  import logging, sys
     18  logger = logging.getLogger("fileseries")
     19  import traceback as pytraceback
     20
     21  from fabioutils import FilenameObject, next_filename
     22
     23  from openimage import openimage
     24
     25
     26 -def new_file_series0(first_object, first=None, last=None, step=1):
     27      """
     28      Created from a fabio image
     29      first and last are file numbers
     30
     31      """
     32      im = first_object
     33      nimages = 0
     34      # for counting images
     35      if None in (first, last):
     36          step = 0
     37          total = 1
     38      else:
     39          total = last - first
     40
     41      yield im
     42      while nimages < total:
     43          nimages += step
     44          try:
     45              newim = im.next()
     46              im = newim
     47          except Exception, error:
     48              pytraceback.print_exc()
     49
     50              # Skip bad images
     51              logger.warning("Got a problem here: %s", error)
     52              try:
     53                  im.filename = next_filename(im.filename)
     54              except Exception, error:
     55                  # KE: This will not work and will throw an exception
     56                  # fabio.next_filename doesn't understand %nnnn on the end
     57                  logger.warning("Got another problem here: %s", error)
     58                  im.filename = next_filename(im.sequencefilename)
     59              yield None
     60          yield im
     61
     62
     63
     64 -def new_file_series(first_object, nimages=0, step=1, traceback=False):
     65      """
     66      A generator function that creates a file series starting from a a fabioimage.
     67      Iterates through all images in a file (if more than 1), then proceeds to
     68      the next file as determined by fabio.next_filename.
     69
     70      @param first_object: the starting fabioimage, which will be the first one yielded
     71          in the sequence
     72      @param nimages:  the maximum number of images to consider
     73          step: step size, will yield the first and every step'th image until nimages
     74          is reached.  (e.g. nimages = 5, step = 2 will yield 3 images (0, 2, 4)
     75      @param traceback: if True causes it to print a traceback in the event of an
     76          exception (missing image, etc.).  Otherwise the calling routine can handle
     77          the exception as it chooses
     78      @param yields: the next fabioimage in the series.
     79          In the event there is an exception, it yields the sys.exec_info for the
     80          exception instead.  sys.exec_info is a tuple:
     81          ( exceptionType, exceptionValue, exceptionTraceback )
     82          from which all the exception information can be obtained.
     83
     84      Suggested usage:
     85
     86      ::
     87
     88          for obj in new_file_series( ... ):
     89            if not isinstance(obj, fabio.fabioimage.fabioimage ):
     90              # deal with errors like missing images, non readable files, etc
     91              # e.g.
     92              traceback.print_exception(obj[0], obj[1], obj[2])
     93
     94      """
     95      im = first_object
     96      nprocessed = 0
     97      abort = False
     98      if nimages > 0:
     99          yield im
    100          nprocessed += 1
    101      while nprocessed < nimages:
    102          try:
    103              newim = im.next()
    104              im = newim
    105              retVal = im
    106          except Exception, ex:
    107              retVal = sys.exc_info()
    108              if(traceback):
    109                  pytraceback.print_exc()
    110                  # Skip bad images
    111                  logger.warning("Got a problem here: next() failed %s", ex)
    112              # Skip bad images
    113              try:
    114                  im.filename = next_filename(im.filename)
    115              except Exception, ex:
    116                  logger.warning("Got another problem here: next_filename(im.filename) %s", ex)
    117          if nprocessed % step == 0:
    118              yield retVal
    119              # Avoid cyclic references with exc_info ?
    120              retVal = None
    121              if abort: break
    122          nprocessed += 1
    123
    124
    125
    126 -class file_series(list):
    127      """
    128      Represents a series of files to iterate
    129      has an idea of a current position to do next and prev
    130
    131      You also get from the list python superclass:
    132         append
    133         count
    134         extend
    135         insert
    136         pop
    137         remove
    138         reverse
    139         sort
    140      """
    141 -    def __init__(self, list_of_strings):
    142          """
    143          Constructor:
    144
    145          @param list_of_strings: arg should be a list of strings which are filenames
    146
    147          """
    148          super(file_series, self).__init__(list_of_strings)
    149          # track current position in list
    150          self._current = 0
    151
    152
    153      # methods which return a filename
    154
    155 -    def first(self):
    156          """
    157          First image in series
    158
    159          """
    160          return self[0]
    161
    162 -    def last(self):
    163          """
    164          Last in series
    165
    166          """
    167          return self[-1]
    168
    169 -    def previous(self):
    170          """
    171          Prev in a sequence
    172
    173          """
    174          self._current -= 1
    175          return self[self._current]
    176
    177 -    def current(self):
    178          """Current position in a sequence
    179
    180          """
    181          return self[self._current]
    182
    183 -    def next(self):
    184          """
    185          Next in a sequence
    186
    187          """
    188          self._current += 1
    189          return self[self._current]
    190
    191 -    def jump(self, num):
    192          """
    193          Goto a position in sequence
    194
    195          """
    196          assert num < len(self) and num > 0, "num out of range"
    197          self._current = num
    198          return self[self._current]
    199
    200 -    def len(self):
    201          """
    202          Number of files
    203
    204          """
    205          return len(self)
    206
    207
    208      # Methods which return a fabioimage
    209
    210 -    def first_image(self):
    211          """
    212          First image in a sequence
    213
    214          @return: fabioimage
    215
    216          """
    217          return openimage(self.first())
    218
    219 -    def last_image(self):
    220          """
    221          Last image in a sequence
    222
    223          @return: fabioimage
    224
    225          """
    226          return openimage(self.last())
    227
    228 -    def next_image(self):
    229          """
    230          Return the next image
    231
    232          @return: fabioimage
    233
    234          """
    235          return openimage(self.next())
    236
    237 -    def previous_image(self):
    238          """
    239          Return the previous image
    240
    241          @return: fabioimage
    242
    243          """
    244          return openimage(self.previous())
    245
    246 -    def jump_image(self, num):
    247          """
    248          Jump to and read image
    249
    250          @return: fabioimage
    251
    252          """
    253          return openimage(self.jump(num))
    254
    255 -    def current_image(self):
    256          """
    257          Current image in sequence
    258
    259          @return: fabioimage
    260
    261          """
    262          return openimage(self.current())
    263
    264      # methods which return a file_object
    265
    266 -    def first_object(self):
    267          """
    268          First image in a sequence
    269
    270          @return: file_object
    271          """
    272          return FilenameObject(self.first())
    273
    274 -    def last_object(self):
    275          """
    276          Last image in a sequence
    277
    278          @return: file_object
    279
    280          """
    281          return FilenameObject(self.last())
    282
    283 -    def next_object(self):
    284          """
    285          Return the next image
    286
    287          @return: file_object
    288
    289          """
    290          return FilenameObject(self.next())
    291
    292 -    def previous_object(self):
    293          """
    294          Return the previous image
    295
    296          @return: file_object
    297
    298          """
    299          return FilenameObject(self.previous())
    300
    301 -    def jump_object(self, num):
    302          """
    303          Jump to and read image
    304
    305          @return: file_object
    306
    307          """
    308          return FilenameObject(self.jump(num))
    309
    310 -    def current_object(self):
    311          """
    312          Current image in sequence
    313
    314          @return: file_object
    315
    316          """
    317          return FilenameObject(self.current())
    318
    319
    320
    321
    322 -class numbered_file_series(file_series):
    323      """
    324      mydata0001.edf = "mydata" + 0001 + ".edf"
    325      mydata0002.edf = "mydata" + 0002 + ".edf"
    326      mydata0003.edf = "mydata" + 0003 + ".edf"
    327      """
    328 -    def __init__(self, stem, first, last, extension,
    329                   digits=4, padding='Y', step=1):
    330          """
    331          Constructor
    332
    333          @param stem: first part of the name
    334          @param step: in case of every nth file
    335          @param padding: possibility for specifying that numbers are not padded with zeroes up to digits
    336
    337          """
    338          if padding == 'Y':
    339              fmt = "%s%0" + str(digits) + "d%s"
    340          else:
    341              fmt = "%s%i%s"
    342
    343          super(numbered_file_series, self).__init__(
    344              [ fmt % (stem, i, extension) for i in range(first,
    345                                                            last + 1,
    346                                                            step) ])
    347
    348
    349 -class filename_series:
    350      """ Much like the others, but created from a string filename """
    351 -    def __init__(self, filename):
    352          """ create from a filename (String)"""
    353          self.obj = FilenameObject(filename)
    354
    355 -    def next(self):
    356          """ increment number """
    357          self.obj.num += 1
    358          return self.obj.tostring()
    359
    360 -    def previous(self):
    361          """ decrement number """
    362          self.obj.num -= 1
    363          return self.obj.tostring()
    364
    365 -    def current(self):
    366          """ return current filename string"""
    367          return self.obj.tostring()
    368
    369 -    def jump(self, num):
    370          """ jump to a specific number """
    371          self.obj.num = num
    372          return self.obj.tostring()
    373
    374      # image methods
    375 -    def next_image(self):
    376          """ returns the next image as a fabioimage """
    377          return openimage(self.next())
    378 -    def prev_image(self):
    379          """ returns the previos image as a fabioimage """
    380          return openimage(self.previous())
    381 -    def current_image(self):
    382          """ returns the current image as a fabioimage"""
    383          return openimage(self.current())
    384 -    def jump_image(self, num):
    385          """ returns the image number as a fabioimage"""
    386          return openimage(self.jump(num))
    387      # object methods
    388 -    def next_object(self):
    389          """ returns the next filename as a fabio.FilenameObject"""
    390          self.obj.num += 1
    391          return self.obj
    392 -    def previous_object(self):
    393          """ returns the previous filename as a fabio.FilenameObject"""
    394          self.obj.num -= 1
    395          return self.obj
    396 -    def current_object(self):
    397          """ returns the current filename as a fabio.FilenameObject"""
    398          return self.obj
    399 -    def jump_object(self, num):
    400          """ returns the filename num as a fabio.FilenameObject"""
    401          self.obj.num = num
    402          return self.obj
    403