# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# ## Save ECG records on 16 bits binary representation

import numpy as np
import wfdb


def packBytes(narray):
    packed = []
    buff = ''
    tmp = 0
    for n in range(len(narray)):
        value = narray[n]
        #Get 3 most significant bits
        msb = bin((value >> 8) & 0xFF) 
        if len(msb)<5:
            #pad with zeroes
            msb = '0'*(5-len(msb))+msb[2:] 
        else:
            msb = msb[-3:]
        #print("parsed: "+msb)
        if n%2:
            #Store 3 most significant bits
            buff = buff + "00" + msb
            #print(buff)
            packed.append(int(buff, 2))
            packed.append(value)
        else:
            #Store 8 less significant bits
            packed.append(value & 0xFF) 
            #tmp = value >> (8) & 0xff
            if(n==len(narray)-1):
                packed.append(int(msb+"00000", 2))
            buff = msb 
            #print("buffer without parsing: "+bin((value >> 8) & 0xff))
            #print("buffer after parsing: "+buff)
    return np.array(packed, dtype='uint8')


#Save array to binary file
def saveBinaryFile(file_name, darray):
    file_name = file_name + '.txt'
    fh = open(file_name, "bw")
    darray.tofile(fh, format="%08b")


# +
'''
Read ECG record data. Each sample is given in a 'int16' data type holding the corresponding decimal value 
stored on the 11 bits register of the ADC register. 
'''
record = 201#221
digital_record = wfdb.rdrecord(str(record), physical=False, return_res=16)

#Get np array containing digital signal
d_signal = digital_record.d_signal

#Choose one of the channels 
channel = 0
signal = d_signal[:, channel].astype('uint16')
#signal = d_signal[:, channel]
# -

#Compress signal
arr = packBytes(signal)

#Save binary file
saveBinaryFile(str(record)+"C", arr)

StarcoderdataJupyterScriptsDedupFiltered