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

Source Code for Module fabio.marccdimage

  1  #!/usr/bin/env python 
  2  """ 
  3   
  4  Authors: Henning O. Sorensen & Erik Knudsen 
  5           Center for Fundamental Research: Metal Structures in Four Dimensions 
  6           Risoe National Laboratory 
  7           Frederiksborgvej 399 
  8           DK-4000 Roskilde 
  9           email:henning.sorensen@risoe.dk 
 10   
 11           + (mods for fabio) Jon Wright, ESRF 
 12  marccdimage can read MarCCD and MarMosaic images including header info. 
 13   
 14  JPW : Use a parser in case of typos (sorry?) 
 15   
 16  """ 
 17   
 18   
 19  # Base this on the tifimage (as marccd seems to be tiff with a  
 20  # special header  
 21   
 22  from tifimage import tifimage 
 23   
 24   
 25  # Now for the c definition (found on mar webpage) 
 26  # The following string is therefore copyrighted by Mar I guess 
 27   
 28  CDEFINITION = """ 
 29  typedef struct frame_header_type { 
 30           /* File/header format parameters (256 bytes) */ 
 31           UINT32        header_type;  /* flag for header type   
 32                                             (can be  used as magic number) */ 
 33           char header_name[16];           /* header name (MMX) */ 
 34           UINT32        header_major_version;   /* header_major_version  (n.) */ 
 35           UINT32        header_minor_version;   /* header_minor_version  (.n) */ 
 36           UINT32        header_byte_order;/* BIG_ENDIAN (Motorola,MIPS);   
 37                                              LITTLE_ENDIAN (DEC, Intel) */ 
 38           UINT32        data_byte_order;  /* BIG_ENDIAN (Motorola,MIPS);   
 39                                              LITTLE_ENDIAN (DEC, Intel) */ 
 40           UINT32        header_size;      /* in bytes                     */ 
 41           UINT32        frame_type;       /* flag for frame type */ 
 42           UINT32        magic_number;     /* to be used as a flag -  
 43                                              usually  to indicate new file */ 
 44           UINT32        compression_type; /* type of image compression    */ 
 45           UINT32        compression1;     /* compression parameter 1 */ 
 46           UINT32        compression2;     /* compression parameter 2 */ 
 47           UINT32        compression3;     /* compression parameter 3 */ 
 48           UINT32        compression4;     /* compression parameter 4 */ 
 49           UINT32        compression5;     /* compression parameter 4 */ 
 50           UINT32        compression6;     /* compression parameter 4 */ 
 51           UINT32        nheaders;         /* total number of headers      */ 
 52           UINT32        nfast;            /* number of pixels in one line */ 
 53           UINT32        nslow;            /* number of lines in image     */ 
 54           UINT32        depth;            /* number of bytes per pixel    */ 
 55           UINT32        record_length;    /* number of pixels between  
 56                                              succesive rows */ 
 57           UINT32        signif_bits;      /* true depth of data, in bits  */ 
 58           UINT32        data_type;        /* (signed,unsigned,float...) */ 
 59           UINT32        saturated_value;  /* value marks pixel as saturated */ 
 60           UINT32        sequence;         /* TRUE or FALSE */ 
 61           UINT32        nimages;          /* total number of images - size of  
 62                                              each is nfast*(nslow/nimages) */ 
 63           UINT32        origin;           /* corner of origin             */ 
 64           UINT32        orientation;      /* direction of fast axis       */ 
 65           UINT32        view_direction;   /* direction to view frame      */ 
 66           UINT32        overflow_location;/* FOLLOWING_HEADER,  FOLLOWING_DATA */ 
 67           UINT32        over_8_bits;      /* # of pixels with counts  255 */ 
 68           UINT32        over_16_bits;     /* # of pixels with count  65535 */ 
 69           UINT32        multiplexed;      /* multiplex flag */ 
 70           UINT32        nfastimages;      /* # of images in fast direction */ 
 71           UINT32        nslowimages;      /* # of images in slow direction */ 
 72           UINT32        background_applied;/* flags correction has been applied  
 73                                                hold magic number ? */ 
 74           UINT32        bias_applied;     /* flags correction has been applied 
 75                                               hold magic number ? */ 
 76           UINT32        flatfield_applied;/* flags correction has been applied - 
 77                                                hold magic number ? */ 
 78           UINT32        distortion_applied;/*flags correction has been applied -  
 79                                                hold magic number ? */ 
 80           UINT32        original_header_type;    /* Header/frame type from  file  
 81                                                      that frame is read from */ 
 82           UINT32        file_saved;         /* Flag that file has been  saved,  
 83                                                should be zeroed if modified */ 
 84           char reserve1[(64-40)*sizeof(INT32)-16]; 
 85   
 86           /* Data statistics (128) */ 
 87           UINT32        total_counts[2];  /* 64 bit integer range = 1.85E19*/ 
 88           UINT32        special_counts1[2]; 
 89           UINT32        special_counts2[2]; 
 90           UINT32        min; 
 91           UINT32        max; 
 92           UINT32        mean; 
 93           UINT32        rms; 
 94           UINT32        p10; 
 95           UINT32        p90; 
 96           UINT32        stats_uptodate; 
 97           UINT32        pixel_noise[MAXIMAGES]; /*1000*base noise value (ADUs) */ 
 98           char reserve2[(32-13-MAXIMAGES)*sizeof(INT32)]; 
 99   
100           /* More statistics (256) */ 
101           UINT16 percentile[128]; 
102   
103   
104           /* Goniostat parameters (128 bytes) */ 
105           INT32 xtal_to_detector;  /* 1000*distance in millimeters */ 
106           INT32 beam_x;            /* 1000*x beam position (pixels) */ 
107           INT32 beam_y;            /* 1000*y beam position (pixels) */ 
108           INT32 integration_time;  /* integration time in  milliseconds */ 
109           INT32 exposure_time;     /* exposure time in milliseconds */ 
110           INT32 readout_time;      /* readout time in milliseconds */ 
111           INT32 nreads;            /* number of readouts to get this  image */ 
112           INT32 start_twotheta;    /* 1000*two_theta angle */ 
113           INT32 start_omega;       /* 1000*omega angle */ 
114           INT32 start_chi;         /* 1000*chi angle */ 
115           INT32 start_kappa;       /* 1000*kappa angle */ 
116           INT32 start_phi;         /* 1000*phi angle */ 
117           INT32 start_delta;       /* 1000*delta angle */ 
118           INT32 start_gamma;       /* 1000*gamma angle */ 
119           INT32 start_xtal_to_detector; /* 1000*distance in mm (dist in um)*/ 
120           INT32 end_twotheta;           /* 1000*two_theta angle */ 
121           INT32 end_omega;              /* 1000*omega angle */ 
122           INT32 end_chi;                /* 1000*chi angle */ 
123           INT32 end_kappa;              /* 1000*kappa angle */ 
124           INT32 end_phi;                /* 1000*phi angle */ 
125           INT32 end_delta;              /* 1000*delta angle */ 
126           INT32 end_gamma;              /* 1000*gamma angle */ 
127           INT32 end_xtal_to_detector;   /* 1000*distance in mm (dist in um)*/ 
128           INT32 rotation_axis;          /* active rotation axis */ 
129           INT32 rotation_range;         /* 1000*rotation angle */ 
130           INT32 detector_rotx;          /* 1000*rotation of detector  around X */ 
131           INT32 detector_roty;          /* 1000*rotation of detector  around Y */ 
132           INT32 detector_rotz;          /* 1000*rotation of detector  around Z */ 
133           char reserve3[(32-28)*sizeof(INT32)]; 
134   
135           /* Detector parameters (128 bytes) */ 
136           INT32 detector_type;            /* detector type */ 
137           INT32 pixelsize_x;              /* pixel size (nanometers) */ 
138           INT32 pixelsize_y;              /* pixel size (nanometers) */ 
139           INT32 mean_bias;                        /* 1000*mean bias value */ 
140           INT32 photons_per_100adu;       /* photons / 100 ADUs */ 
141           INT32 measured_bias[MAXIMAGES];/* 1000*mean bias value for each image*/ 
142           INT32 measured_temperature[MAXIMAGES];  /* Temperature of each   
143                                                      detector in milliKelvins */ 
144           INT32 measured_pressure[MAXIMAGES]; /* Pressure of each  chamber  
145                                                 in microTorr */ 
146           /* Retired reserve4 when MAXIMAGES set to 9 from 16 and  
147              two fields removed, and temp and pressure added 
148            char reserve4[(32-(5+3*MAXIMAGES))*sizeof(INT32)] 
149           */ 
150   
151           /* X-ray source and optics parameters (128 bytes) */ 
152           /* X-ray source parameters (8*4 bytes) */ 
153           INT32 source_type;              /* (code) - target, synch. etc */ 
154           INT32 source_dx;                /* Optics param. - (size  microns) */ 
155           INT32 source_dy;                /* Optics param. - (size  microns) */ 
156           INT32 source_wavelength;        /* wavelength  (femtoMeters) */ 
157           INT32 source_power;             /* (Watts) */ 
158           INT32 source_voltage;           /* (Volts) */ 
159           INT32 source_current;           /* (microAmps) */ 
160           INT32 source_bias;              /* (Volts) */ 
161           INT32 source_polarization_x;    /* () */ 
162           INT32 source_polarization_y;    /* () */ 
163           char reserve_source[4*sizeof(INT32)]; 
164   
165           /* X-ray optics_parameters (8*4 bytes) */ 
166           INT32 optics_type;              /* Optics type (code)*/ 
167           INT32 optics_dx;                /* Optics param. - (size  microns) */ 
168           INT32 optics_dy;                /* Optics param. - (size  microns) */ 
169           INT32 optics_wavelength;        /* Optics param. - (size  microns) */ 
170           INT32 optics_dispersion;        /* Optics param. - (*10E6) */ 
171           INT32 optics_crossfire_x;       /* Optics param. - (microRadians) */ 
172           INT32 optics_crossfire_y;       /* Optics param. - (microRadians) */ 
173           INT32 optics_angle;             /* Optics param. - (monoch.   
174                                                      2theta - microradians) */ 
175           INT32 optics_polarization_x;    /* () */ 
176           INT32 optics_polarization_y;    /* () */ 
177           char reserve_optics[4*sizeof(INT32)]; 
178   
179           char reserve5[((32-28)*sizeof(INT32))]; 
180   
181           /* File parameters (1024 bytes) */ 
182           char filetitle[128];            /*  Title                  */ 
183           char filepath[128];             /* path name for data  file  */ 
184           char filename[64];              /* name of data  file  */ 
185           char acquire_timestamp[32];     /* date and time of  acquisition */ 
186           char header_timestamp[32];      /* date and time of header  update  */ 
187           char save_timestamp[32];        /* date and time file  saved */ 
188           char file_comments[512];        /* comments, use as desired   */ 
189           char reserve6[1024-(128+128+64+(3*32)+512)]; 
190   
191           /* Dataset parameters (512 bytes) */ 
192           char dataset_comments[512];     /* comments, used as desired   */ 
193           /* pad out to  3072 bytes */ 
194           char pad[3072-(256+128+256+(3*128)+1024+512)];      
195   
196           } frame_header; 
197  """ 
198   
199  import struct 
200   
201  # Convert mar c header file types to python struct module types 
202  C_TO_STRUCT = { 
203      "INT32"  : "i", 
204      "UINT32" : "I", 
205      "char"   : "c", 
206      "UINT16" : "H" 
207      } 
208   
209  # Sizes (bytes) of mar c header objects 
210  C_SIZES = { 
211      "INT32"  : 4, 
212      "UINT32" : 4, 
213      "char"   : 1, 
214      "UINT16" : 2 
215      } 
216   
217  # This was worked out by trial and error from a trial image I think 
218  MAXIMAGES = 9 
219   
220   
221 -def make_format(c_def_string):
222 """ 223 Reads the header definition in c and makes the format 224 string to pass to struct.unpack 225 """ 226 lines = c_def_string.split("\n") 227 fmt = "" 228 names = [] 229 expected = 0 230 for line in lines: 231 if line.find(";") == -1: 232 continue 233 decl = line.split(";")[0].lstrip().rstrip() 234 try: 235 [typ, name] = decl.split() 236 except ValueError: 237 #print "skipping:",line 238 continue 239 # print "type:",type," name:",name 240 241 if name.find("[") > -1: 242 # repeated ... times 243 try: 244 num = name.split("[")[1].split("]")[0] 245 num = num.replace("MAXIMAGES", str(MAXIMAGES)) 246 num = num.replace("sizeof(INT32)", "4") 247 times = eval(num) 248 except: 249 print "Please decode", decl 250 raise 251 else: 252 times = 1 253 try: 254 fmt += C_TO_STRUCT[typ] * times 255 names += [name] * times 256 expected += C_SIZES[typ] * times 257 except KeyError: 258 continue 259 return names, fmt
260 261 # Make these be compiled on loading module 262 HEADER_NAMES, HEADER_FORMAT = make_format(CDEFINITION) 263
264 -def interpret_header(header, fmt, names):
265 """ 266 given a format and header interpret it 267 """ 268 values = struct.unpack(fmt, header) 269 hdr = {} 270 i = 0 271 for name in names: 272 if hdr.has_key(name): 273 if type(values[i]) == type("string"): 274 hdr[name] = hdr[name] + values[i] 275 else: 276 try: 277 hdr[name].append(values[i]) 278 except AttributeError: 279 hdr[name] = [hdr[name], values[i]] 280 else: 281 hdr[name] = values[i] 282 i = i + 1 283 284 return hdr
285 286
287 -class marccdimage(tifimage):
288 """ Read in data in mar ccd format, also 289 MarMosaic images, including header info """ 290 291
292 - def _readheader(self, infile):
293 """ 294 Parser based approach 295 Gets all entries 296 """ 297 infile.seek(1024) 298 hstr = infile.read(3072) 299 self.header = interpret_header(hstr, HEADER_FORMAT, HEADER_NAMES)
300 301 302
303 - def _read(self, fname):
304 """ 305 inherited from tifimage 306 ... a marccd image *is a* tif image 307 just with a header 308 """ 309 return tifimage.read(self, fname)
310