Skip to content

Instantly share code, notes, and snippets.

@mgaitan
Created February 1, 2018 04:17
Show Gist options
  • Save mgaitan/53ea9f5ff47781f34c153c433474ea51 to your computer and use it in GitHub Desktop.
Save mgaitan/53ea9f5ff47781f34c153c433474ea51 to your computer and use it in GitHub Desktop.
Nicolet's spa format parser of Fourier Transform infrared spectroscopy (FTIR) data
from collections import namedtuple
from itertools import count
from struct import unpack
import numpy as np
SpaData = namedtuple('SpaData', 'title, wavenumbers, intensities')
def spa(file):
with open(file, 'rb') as spa:
r = spa.read()
def _flag_pos(start, flag):
_flag = 0
for i in count(start, 2):
_flag = unpack('<H', r[i:i + 2])[0]
if _flag == flag:
return i + 2
title = r[30:255].strip(b'\x00').decode('utf8')
points = unpack('i', r[564:568])[0]
f_max, f_min = unpack('ff', r[576:584])
# The Wavenumber values are assumed to be linearly spaced between
# the Min and Max values. The array needs to be flipped
# around to get the order lined up with the absorbance data
wavenumbers = np.flip(np.linspace(f_min, f_max, points), 0)
# The starting byte location of the absorbance data is stored in the header.
# It immediately follows a flag value of 3:
i = _flag_pos(288, 3)
absor_pos = unpack('H', r[i:i + 2])[0]
intensities = np.fromstring(r[absor_pos:absor_pos + points * 4], dtype=np.float32)
# i = _flag_pos(288, 4)
# comment_pos = unpack('<H', r[i:i + 2])
#print(comment_pos)
return SpaData(title, wavenumbers, intensities)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment