/usr/lib/python3/dist-packages/fabio/OXDimage.py is in python3-fabio 0.6.0+dfsg-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 | # coding: utf-8
#
# Project: X-ray image reader
# https://github.com/silx-kit/fabio
#
#
# Copyright (C) European Synchrotron Radiation Facility, Grenoble, France
#
# Principal author: Jérôme Kieffer (Jerome.Kieffer@ESRF.eu)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE
"""Reads Oxford Diffraction Sapphire 3 images
Authors:
........
* Henning O. Sorensen & Erik Knudsen:
Center for Fundamental Research: Metal Structures in Four Dimensions;
Risoe National Laboratory;
Frederiksborgvej 399;
DK-4000 Roskilde;
email:erik.knudsen@risoe.dk
* Jon Wright, Jérôme Kieffer & Gaël Goret:
European Synchrotron Radiation Facility;
Grenoble (France)
"""
# Get ready for python3:
from __future__ import with_statement, print_function
__contact__ = "Jerome.Kieffer@esrf.fr"
__license__ = "MIT"
__copyright__ = "Jérôme Kieffer"
__date__ = "27/07/2017"
import time
import logging
import struct
logger = logging.getLogger(__name__)
import numpy
from .fabioimage import FabioImage
from .compression import decTY1, compTY1
from .fabioutils import to_str
from .utils.mathutils import rad2deg, deg2rad
DETECTOR_TYPES = {0: 'Sapphire/KM4CCD (1x1: 0.06mm, 2x2: 0.12mm)',
1: 'Sapphire2-Kodak (1x1: 0.06mm, 2x2: 0.12mm)',
2: 'Sapphire3-Kodak (1x1: 0.03mm, 2x2: 0.06mm, 4x4: 0.12mm)',
3: 'Onyx-Kodak (1x1: 0.06mm, 2x2: 0.12mm, 4x4: 0.24mm)',
4: 'Unknown Oxford diffraction detector',
7: 'Pilatus 300K-Dectris'}
DEFAULT_HEADERS = {'Header Version': 'OD SAPPHIRE 3.0',
'Compression': "TY1",
'Header Size In Bytes': 5120,
"ASCII Section size in Byte": 256,
"General Section size in Byte": 512,
"Special Section size in Byte": 768,
"KM4 Section size in Byte": 1024,
"Statistic Section in Byte": 512,
"History Section in Byte": 2048,
'NSUPPLEMENT': 0
}
class OxdImage(FabioImage):
"""
Oxford Diffraction Sapphire 3 images reader/writer class
Note: We assume the binary format is alway little-endian, is this True ?
"""
DESCRIPTION = "Oxford Diffraction Sapphire 3 file format"
DEFAULT_EXTENSIONS = ["img"]
def _readheader(self, infile):
infile.seek(0)
# Ascii header part 256 byes long
self.header['Header Version'] = to_str(infile.readline()[:-2])
block = infile.readline()
self.header['Compression'] = to_str(block[12:15])
block = infile.readline()
self.header['NX'] = int(block[3:7])
self.header['NY'] = int(block[11:15])
self.header['OI'] = int(block[19:26])
self.header['OL'] = int(block[30:37])
block = infile.readline()
self.header['Header Size In Bytes'] = int(block[8:15])
self.header['General Section size in Byte'] = int(block[19:26])
self.header['Special Section size in Byte'] = int(block[30:37])
self.header['KM4 Section size in Byte'] = int(block[41:48])
self.header['Statistic Section in Byte'] = int(block[52:59])
self.header['History Section in Byte'] = int(block[63:])
block = infile.readline()
self.header['NSUPPLEMENT'] = int(block[12:19])
block = infile.readline()
self.header['Time'] = to_str(block[5:29])
header_version = float(self.header['Header Version'].split()[2])
if header_version < 4.0:
# for all our test files with header version 3.0
# ascii_section_size == 256
# but that's a legacy code
ascii_section_size = self.header['Header Size In Bytes'] - (
self.header['General Section size in Byte'] +
self.header['Special Section size in Byte'] +
self.header['KM4 Section size in Byte'] +
self.header['Statistic Section in Byte'] +
self.header['History Section in Byte'])
else:
ascii_section_size = DEFAULT_HEADERS["ASCII Section size in Byte"]
self.header["ASCII Section size in Byte"] = ascii_section_size
# Skip to general section (NG) 512 byes long <<<<<<"
infile.seek(self.header["ASCII Section size in Byte"])
block = infile.read(self.header['General Section size in Byte'])
self.header['Binning in x'] = struct.unpack("<H", block[0:2])[0]
self.header['Binning in y'] = struct.unpack("<H", block[2:4])[0]
self.header['Detector size x'] = struct.unpack("<H", block[22:24])[0]
self.header['Detector size y'] = struct.unpack("<H", block[24:26])[0]
self.header['Pixels in x'] = struct.unpack("<H", block[26:28])[0]
self.header['Pixels in y'] = struct.unpack("<H", block[28:30])[0]
self.header['No of pixels'] = struct.unpack("<I", block[36:40])[0]
# Speciel section (NS) 768 bytes long
block = infile.read(self.header['Special Section size in Byte'])
self.header['Gain'] = struct.unpack("<d", block[56:64])[0]
self.header['Overflows flag'] = struct.unpack("<h", block[464:466])[0]
self.header['Overflow after remeasure flag'] = struct.unpack("<h", block[466:468])[0]
self.header['Overflow threshold'] = struct.unpack("<i", block[472:476])[0]
self.header['Exposure time in sec'] = struct.unpack("<d", block[480:488])[0]
self.header['Overflow time in sec'] = struct.unpack("<d", block[488:496])[0]
self.header['Monitor counts of raw image 1'] = struct.unpack("<i", block[528:532])[0]
self.header['Monitor counts of raw image 2'] = struct.unpack("<i", block[532:536])[0]
self.header['Monitor counts of overflow raw image 1'] = struct.unpack("<i", block[536:540])[0]
self.header['Monitor counts of overflow raw image 2'] = struct.unpack("<i", block[540:544])[0]
self.header['Unwarping'] = struct.unpack("<i", block[544:548])[0]
self.header['Detector type'] = DETECTOR_TYPES[struct.unpack("<i", block[548:552])[0]]
self.header['Real pixel size x (mm)'] = struct.unpack("<d", block[568:576])[0]
self.header['Real pixel size y (mm)'] = struct.unpack("<d", block[576:584])[0]
# KM4 goniometer section (NK) 1024 bytes long
block = infile.read(self.header['KM4 Section size in Byte'])
# Spatial correction file
self.header['Spatial correction file'] = to_str(block[26:272].strip(b"\x00"))
self.header['Spatial correction file date'] = to_str(block[0:26].strip(b"\x00"))
# Angles are in steps due to stepper motors - conversion factor RAD
# angle[0] = omega, angle[1] = theta, angle[2] = kappa, angle[3] = phi,
start_angles_step = numpy.fromstring(block[284:304], numpy.int32)
end_angles_step = numpy.fromstring(block[324:344], numpy.int32)
step2rad = numpy.fromstring(block[368:408], numpy.float)
zero_correction_soft_step = numpy.fromstring(block[512:532], numpy.int32)
if not numpy.little_endian:
start_angles_step.byteswap(True)
end_angles_step.byteswap(True)
step2rad.byteswap(True)
zero_correction_soft_step.byteswap(True)
step_angles_deg = rad2deg(step2rad)
# calc angles
start_angles_deg = start_angles_step * step_angles_deg
end_angles_deg = end_angles_step * step_angles_deg
self.header['Omega start in deg'] = start_angles_deg[0]
self.header['Theta start in deg'] = start_angles_deg[1]
self.header['Kappa start in deg'] = start_angles_deg[2]
self.header['Phi start in deg'] = start_angles_deg[3]
self.header['Omega end in deg'] = end_angles_deg[0]
self.header['Theta end in deg'] = end_angles_deg[1]
self.header['Kappa end in deg'] = end_angles_deg[2]
self.header['Phi end in deg'] = end_angles_deg[3]
self.header['Omega step in deg'] = step_angles_deg[0]
self.header['Theta step in deg'] = step_angles_deg[1]
self.header['Kappa step in deg'] = step_angles_deg[2]
self.header['Phi step in deg'] = step_angles_deg[3]
zero_correction_soft_deg = zero_correction_soft_step * step_angles_deg
self.header['Omega zero corr. in deg'] = zero_correction_soft_deg[0]
self.header['Theta zero corr. in deg'] = zero_correction_soft_deg[1]
self.header['Kappa zero corr. in deg'] = zero_correction_soft_deg[2]
self.header['Phi zero corr. in deg'] = zero_correction_soft_deg[3]
# Beam rotation about e2,e3
self.header['Beam rot in deg (e2)'] = struct.unpack("<d", block[552:560])[0]
self.header['Beam rot in deg (e3)'] = struct.unpack("<d", block[560:568])[0]
# Wavelenghts alpha1, alpha2, beta
self.header['Wavelength alpha1'] = struct.unpack("<d", block[568:576])[0]
self.header['Wavelength alpha2'] = struct.unpack("<d", block[576:584])[0]
self.header['Wavelength alpha'] = struct.unpack("<d", block[584:592])[0]
self.header['Wavelength beta'] = struct.unpack("<d", block[592:600])[0]
# Detector tilts around e1,e2,e3 in deg
self.header['Detector tilt e1 in deg'] = struct.unpack("<d", block[640:648])[0]
self.header['Detector tilt e2 in deg'] = struct.unpack("<d", block[648:656])[0]
self.header['Detector tilt e3 in deg'] = struct.unpack("<d", block[656:664])[0]
# Beam center
self.header['Beam center x'] = struct.unpack("<d", block[664:672])[0]
self.header['Beam center y'] = struct.unpack("<d", block[672:680])[0]
# Angle (alpha) between kappa rotation axis and e3 (ideally 50 deg)
self.header['Alpha angle in deg'] = struct.unpack("<d", block[680:688])[0]
# Angle (beta) between phi rotation axis and e3 (ideally 0 deg)
self.header['Beta angle in deg'] = struct.unpack("<d", block[688:696])[0]
# Detector distance
self.header['Distance in mm'] = struct.unpack("<d", block[712:720])[0]
# Statistics section (NS) 512 bytes long
block = infile.read(self.header['Statistic Section in Byte'])
self.header['Stat: Min '] = struct.unpack("<i", block[0:4])[0]
self.header['Stat: Max '] = struct.unpack("<i", block[4:8])[0]
self.header['Stat: Average '] = struct.unpack("<d", block[24:32])[0]
self.header['Stat: Stddev '] = numpy.sqrt(struct.unpack("<d", block[32:40])[0])
self.header['Stat: Skewness '] = struct.unpack("<d", block[40:48])[0]
# History section (NH) 2048 bytes long
block = infile.read(self.header['History Section in Byte'])
self.header['Flood field image'] = to_str(block[99:126].strip(b"\x00"))
def read(self, fname, frame=None):
"""
Read in header into self.header and
the data into self.data
"""
self.header = self.check_header()
self.resetvals()
with self._open(fname) as infile:
self._readheader(infile)
infile.seek(self.header['Header Size In Bytes'])
# Compute image size
try:
self.dim1 = int(self.header['NX'])
self.dim2 = int(self.header['NY'])
except (ValueError, KeyError):
raise IOError("Oxford file %s is corrupted, cannot read it" % str(fname))
if self.header['Compression'] == 'TY1':
logger.debug("Compressed with the KM4CCD compression")
raw8 = infile.read(self.dim1 * self.dim2)
raw16 = None
raw32 = None
if self.header['OI'] > 0:
raw16 = infile.read(self.header['OI'] * 2)
if self.header['OL'] > 0:
raw32 = infile.read(self.header['OL'] * 4)
# endianess is handled at the decompression level
raw_data = decTY1(raw8, raw16, raw32)
bytecode = raw_data.dtype
elif self.header['Compression'] == 'TY5':
logger.info("Compressed with the TY5 compression")
bytecode = numpy.int8
self.bpp = 1
raw8 = infile.read(self.dim1 * self.dim2)
raw_data = numpy.fromstring(raw8, bytecode)
if self.header['OI'] > 0:
self.raw16 = infile.read(self.header['OI'] * 2)
else:
self.raw16 = b""
if self.header['OL'] > 0:
self.raw32 = infile.read(self.header['OL'] * 4)
else:
self.raw32 = b""
self.rest = infile.read()
self.blob = raw8 + self.raw16 + self.raw32 + self.rest
raw_data = self.dec_TY5(raw8 + self.raw16 + self.raw32)
else:
bytecode = numpy.int32
self.bpp = len(numpy.array(0, bytecode).tostring())
nbytes = self.dim1 * self.dim2 * self.bpp
raw_data = numpy.fromstring(infile.read(nbytes), bytecode)
# Always assume little-endian on the disk
if not numpy.little_endian:
raw_data.byteswap(True)
# infile.close()
logger.debug('OVER_SHORT2: %s', raw_data.dtype)
logger.debug("%s" % (raw_data < 0).sum())
logger.debug("BYTECODE: %s", bytecode)
self.data = raw_data.reshape((self.dim2, self.dim1))
self.bytecode = self.data.dtype.type
self.pilimage = None
return self
def _writeheader(self):
"""
:return: a string containing the header for Oxford images
"""
linesep = "\r\n"
for key in DEFAULT_HEADERS:
if key not in self.header:
self.header[key] = DEFAULT_HEADERS[key]
if "NX" not in self.header.keys() or "NY" not in self.header.keys():
self.header['NX'] = self.dim1
self.header['NY'] = self.dim2
ascii_headers = [self.header['Header Version'],
"COMPRESSION=%s (%5.1f)" % (self.header["Compression"], self.getCompressionRatio()),
"NX=%4i NY=%4i OI=%7i OL=%7i " % (self.header["NX"], self.header["NY"], self.header["OI"], self.header["OL"]),
"NHEADER=%7i NG=%7i NS=%7i NK=%7i NS=%7i NH=%7i" % (self.header['Header Size In Bytes'],
self.header['General Section size in Byte'],
self.header['Special Section size in Byte'],
self.header['KM4 Section size in Byte'],
self.header['Statistic Section in Byte'],
self.header['History Section in Byte']),
"NSUPPLEMENT=%7i" % (self.header["NSUPPLEMENT"])]
if "Time" in self.header:
ascii_headers.append("TIME=%s" % self.header["Time"])
else:
ascii_headers.append("TIME=%s" % time.ctime())
header = (linesep.join(ascii_headers)).ljust(256).encode("ASCII")
NG = Section(self.header['General Section size in Byte'], self.header)
NG.setData('Binning in x', 0, numpy.uint16)
NG.setData('Binning in y', 2, numpy.uint16)
NG.setData('Detector size x', 22, numpy.uint16)
NG.setData('Detector size y', 24, numpy.uint16)
NG.setData('Pixels in x', 26, numpy.uint16)
NG.setData('Pixels in y', 28, numpy.uint16)
NG.setData('No of pixels', 36, numpy.uint32)
header += NG.__repr__()
NS = Section(self.header['Special Section size in Byte'], self.header)
NS.setData('Gain', 56, numpy.float)
NS.setData('Overflows flag', 464, numpy.int16)
NS.setData('Overflow after remeasure flag', 466, numpy.int16)
NS.setData('Overflow threshold', 472, numpy.int32)
NS.setData('Exposure time in sec', 480, numpy.float)
NS.setData('Overflow time in sec', 488, numpy.float)
NS.setData('Monitor counts of raw image 1', 528, numpy.int32)
NS.setData('Monitor counts of raw image 2', 532, numpy.int32)
NS.setData('Monitor counts of overflow raw image 1', 536, numpy.int32)
NS.setData('Monitor counts of overflow raw image 2', 540, numpy.int32)
NS.setData('Unwarping', 544, numpy.int32)
if 'Detector type' in self.header:
for key, value in DETECTOR_TYPES.items():
if value == self.header['Detector type']:
NS.setData(None, 548, numpy.int32, default=key)
NS.setData('Real pixel size x (mm)', 568, numpy.float)
NS.setData('Real pixel size y (mm)', 576, numpy.float)
header += NS.__repr__()
KM = Section(self.header['KM4 Section size in Byte'], self.header)
KM.setData('Spatial correction file date', 0, "|S26")
KM.setData('Spatial correction file', 26, "|S246")
# Angles are in steps due to stepper motors - conversion factor RAD
# angle[0] = omega, angle[1] = theta, angle[2] = kappa, angle[3] = phi,
if self.header.get('Omega step in deg', None):
KM.setData(None, 368, numpy.float64, deg2rad(self.header["Omega step in deg"]))
if self.header.get('Omega start in deg', None):
KM.setData(None, 284, numpy.int32, self.header["Omega start in deg"] / self.header["Omega step in deg"])
if self.header.get('Omega end in deg', None):
KM.setData(None, 324, numpy.int32, self.header["Omega end in deg"] / self.header["Omega step in deg"])
if self.header.get('Omega zero corr. in deg', None):
KM.setData(None, 512, numpy.int32, self.header['Omega zero corr. in deg'] / self.header["Omega step in deg"])
if self.header.get('Theta step in deg', None):
KM.setData(None, 368 + 8, numpy.float64, deg2rad(self.header["Theta step in deg"]))
if self.header.get('Theta start in deg', None):
KM.setData(None, 284 + 4, numpy.int32, self.header["Theta start in deg"] / self.header["Theta step in deg"])
if self.header.get('Theta end in deg', None):
KM.setData(None, 324 + 4, numpy.int32, self.header["Theta end in deg"] / self.header["Theta step in deg"])
if self.header.get('Theta zero corr. in deg', None):
KM.setData(None, 512 + 4, numpy.int32, self.header['Theta zero corr. in deg'] / self.header["Theta step in deg"])
if self.header.get('Kappa step in deg', None):
KM.setData(None, 368 + 16, numpy.float64, deg2rad(self.header["Kappa step in deg"]))
if self.header.get('Kappa start in deg', None):
KM.setData(None, 284 + 8, numpy.int32, self.header["Kappa start in deg"] / self.header["Kappa step in deg"])
if self.header.get('Kappa end in deg', None):
KM.setData(None, 324 + 8, numpy.int32, self.header["Kappa end in deg"] / self.header["Kappa step in deg"])
if self.header.get('Kappa zero corr. in deg', None):
KM.setData(None, 512 + 8, numpy.int32, self.header['Kappa zero corr. in deg'] / self.header["Kappa step in deg"])
if self.header.get('Phi step in deg', None):
KM.setData(None, 368 + 24, numpy.float64, deg2rad(self.header["Phi step in deg"]))
if self.header.get('Phi start in deg', None):
KM.setData(None, 284 + 12, numpy.int32, self.header["Phi start in deg"] / self.header["Phi step in deg"])
if self.header.get('Phi end in deg', None):
KM.setData(None, 324 + 12, numpy.int32, self.header["Phi end in deg"] / self.header["Phi step in deg"])
if self.header.get('Phi zero corr. in deg', None):
KM.setData(None, 512 + 12, numpy.int32, self.header['Phi zero corr. in deg'] / self.header["Phi step in deg"])
# Beam rotation about e2,e3
KM.setData('Beam rot in deg (e2)', 552, numpy.float64)
KM.setData('Beam rot in deg (e3)', 560, numpy.float64)
# Wavelenghts alpha1, alpha2, beta
KM.setData('Wavelength alpha1', 568, numpy.float64)
KM.setData('Wavelength alpha2', 576, numpy.float64)
KM.setData('Wavelength alpha', 584, numpy.float64)
KM.setData('Wavelength beta', 592, numpy.float64)
# Detector tilts around e1,e2,e3 in deg
KM.setData('Detector tilt e1 in deg', 640, numpy.float64)
KM.setData('Detector tilt e2 in deg', 648, numpy.float64)
KM.setData('Detector tilt e3 in deg', 656, numpy.float64)
# Beam center
KM.setData('Beam center x', 664, numpy.float64)
KM.setData('Beam center y', 672, numpy.float64)
# Angle (alpha) between kappa rotation axis and e3 (ideally 50 deg)
KM.setData('Alpha angle in deg', 680, numpy.float64)
# Angle (beta) between phi rotation axis and e3 (ideally 0 deg)
KM.setData('Beta angle in deg', 688, numpy.float64)
# Detector distance
KM.setData('Distance in mm', 712, numpy.float64)
header += KM.__repr__()
SS = Section(self.header['Statistic Section in Byte'], self.header)
SS.setData('Stat: Min ', 0, numpy.int32)
SS.setData('Stat: Max ', 4, numpy.int32)
SS.setData('Stat: Average ', 24, numpy.float64)
if self.header.get('Stat: Stddev ', None):
SS.setData(None, 32, numpy.float64, self.header['Stat: Stddev '] ** 2)
SS.setData('Stat: Skewness ', 40, numpy.float64)
header += SS.__repr__()
HS = Section(self.header['History Section in Byte'], self.header)
HS.setData('Flood field image', 99, "|S27")
header += HS.__repr__()
return header
def write(self, fname):
"""Write Oxford diffraction images: this is still beta
Only TY1 compressed images is currently possible
:param fname: output filename
"""
if self.header.get("Compression") != "TY1":
logger.warning("Enforce TY1 compression")
self.header["Compression"] = "TY1"
datablock8, datablock16, datablock32 = compTY1(self.data)
self.header["OI"] = len(datablock16) / 2
self.header["OL"] = len(datablock32) / 4
with self._open(fname, mode="wb") as outfile:
outfile.write(self._writeheader())
outfile.write(datablock8)
outfile.write(datablock16)
outfile.write(datablock32)
def getCompressionRatio(self):
"calculate the compression factor obtained vs raw data"
return 100.0 * (self.data.size + 2 * self.header["OI"] + 4 * self.header["OL"]) / (self.data.size * 4)
@staticmethod
def checkData(data=None):
if data is None:
return None
else:
return data.astype(int)
def dec_TY5(self, stream):
"""
Attempt to decode TY5 compression scheme
:param stream: input stream
:return: 1D array with data
"""
logger.info("TY5 decompression is slow for now")
array_size = self.dim1 * self.dim2
stream_size = len(stream)
data = numpy.zeros(array_size)
raw = numpy.fromstring(stream, dtype="uint8")
pos_inp = pos_out = current = ex1 = ex2 = 0
while pos_inp < stream_size and pos_out < array_size:
if pos_out % self.dim2 == 0:
last = 0
else:
last = current
value = raw[pos_inp]
if value < 254:
# this is the normal case
# 1 bytes encode one pixel
current = last + value - 127
pos_inp += 1
elif value == 254:
ex1 += 1
# this is the special case 1:
# if the marker 254 is found the next 2 bytes encode one pixel
value = raw[pos_inp + 1:pos_inp + 3].view("int16")
if not numpy.little_endian:
value = value.byteswap(True)
current = last + value[0]
pos_inp += 3
elif value == 255:
# this is the special case 2:
# if the marker 255 is found the next 4 bytes encode one pixel
ex2 += 1
logger.info('special case 32 bits.')
value = raw[pos_inp + 1:pos_inp + 5].view("int32")
if not numpy.little_endian:
value = value.byteswap(True)
current = last + value[0]
pos_inp += 5
data[pos_out] = current
pos_out += 1
logger.info("TY5: Exception: 16bits: %s, 32bits: %s", ex1, ex2)
return data
OXDimage = OxdImage
class Section(object):
"""
Small helper class for writing binary headers
"""
def __init__(self, size, dictHeader):
"""
:param size: size of the header section in bytes
:param dictHeader: headers of the image
"""
self.size = size
self.header = dictHeader
self.lstChr = bytearray(size)
self._dictSize = {}
def __repr__(self):
return bytes(self.lstChr)
def getSize(self, dtype):
if dtype not in self._dictSize:
self._dictSize[dtype] = len(numpy.zeros(1, dtype=dtype).tostring())
return self._dictSize[dtype]
def setData(self, key, offset, dtype, default=None):
"""
:param offset: int, starting position in the section
:param key: name of the header key
:param dtype: type of the data to insert (defines the size!)
"""
if key in self.header:
value = self.header[key]
elif key in DEFAULT_HEADERS:
value = DEFAULT_HEADERS[key]
else:
value = default
if value is None:
value = b"\x00" * self.getSize(dtype)
elif numpy.little_endian:
value = numpy.array(value).astype(dtype).tostring()
else:
value = numpy.array(value).astype(dtype).byteswap().tostring()
self.lstChr[offset:offset + self.getSize(dtype)] = value
|