adamreeve / npTDMS

NumPy based Python module for reading TDMS files produced by LabView

Home Page:http://nptdms.readthedocs.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Read data with specific numpy floating dtype

snowtechblog opened this issue · comments

Hi,
I have the need to read in the channel data of my 20Gb Tdms file in lower precision than float64, e.g. in float32 or even in float16, to reduce my memory consumption. I could not find an nice inbuild solution to that, so I fiddled my own little function that I would like to share and potentially raise as a feature request. (I am not so familiar with the module structure and structure of Tdms files in general to implement such feature via a pull request...)

import numpy as np
from nptdms import TdmsFile

def read_tdms_channel_dtyped(tdms_channel, float_dtype='float32'):
    # unscaled data is int16
    data = tdms_channel.read_data(scaled=False)[0]
    # but when setting the polynomial coefficients to float32 or float64
    c = np.asarray(tdms_channel._scaling.scalings[1].coefficients, dtype=float_dtype)
    # the resulting scaled version is of that same dtype
    # but apply np.astype again to support float16
    return np.polynomial.polynomial.polyval(data, c).astype(float_dtype)

tdms_channel = TdmsFile.open(<file>)[<group>][<channel>]
data = read_tdms_channel_dtyped(tdms_channel)

This function is motivated from the scale method in class PolynomialScaling(object) (line 61 in scaling.py).