SUBANGKAR

ppg-in-batch

Dec 4th, 2020
432
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import numpy as np
  2. import pandas as pd
  3. import os
  4. import torch
  5. from torch.nn import functional as F
  6. from models.deepbeat_bayesian import Bayesian_Deepbeat
  7. import math
  8.  
  9.  
  10. def sliding_window(x, w=800, o=400):
  11.     """
  12.    x: 1D numpy array
  13.    w: size of each window
  14.    o: min len of overlapping
  15.    """    
  16.     st = 0
  17.     en = 0
  18.     ranges = []
  19.     while en < len(x):
  20.         en = st+w
  21.         if en > len(x):
  22.             en = len(x)
  23.             st = len(x)-w
  24.         ranges.append((st, en))
  25.         # print(st, en)
  26.         st = en-o
  27.     X = np.zeros(shape=(len(ranges),w))
  28.     for r in range(len(ranges)):
  29.         X[r]=x[ranges[r][0]:ranges[r][1]]
  30.     return X
  31.  
  32.  
  33. def run_model(model_path, ppg_signals):
  34.     ppg = ppg_signals
  35.     ppg = (ppg-ppg.min())/(ppg.max()-ppg.min())
  36.  
  37.     batches = sliding_window(ppg, w=800, o=400) #np.zeros((len(ppg)//800, 1, 800))
  38.     batches = batches.reshape(batches.shape[0], 1, batches.shape[1])
  39.  
  40.     model = Bayesian_Deepbeat()
  41.     model.load_state_dict(torch.load(model_path)['state_dict'])
  42.     model.eval()
  43.  
  44.     outputs = None
  45.     batches = torch.Tensor(batches)    
  46.     with torch.no_grad():
  47.         outputs, _ = model(batches)
  48.         outputs = F.log_softmax(outputs, dim=1)
  49.         outputs = torch.exp(outputs)
  50.     return outputs.numpy()
  51.  
  52.  
  53. # reading csv file
  54. # 0-NonAF, 1-AF
  55. def input_preprocessing(model_path, csv_filepath):
  56.     """
  57.    Following program takes csv_directory as input, does necessary operations and then outputs another csv in same directory.
  58.    :param csv_filepath // path where all csv files will be stored
  59.    :return:
  60.    """
  61.  
  62.     df = pd.read_csv(csv_filepath, engine='python', header=None)
  63.     df = df[df[0]>40]
  64.     ppg = df[1].to_numpy()
  65.     # return ppg
  66.     # return df[1].to_numpy().shape
  67.     return np.argmax(run_model(model_path, ppg), axis=1)
  68.  
  69. out = input_preprocessing('./bayesbeat_cpu.pt', './uncle_Mar4.csv')
  70.  
  71. csv_filepath='./uncle_Mar4.csv'
  72. model_path='./bayesbeat_cpu.pt'
  73.  
  74.  
  75. # plt.plot(ppg)
  76. # batches.shape
  77. # outputs
  78. # x=np.array([1,2,3,4, 5,6,7,8,9,10,11,12])
  79. # window(x, w=8, o=4)
  80. out
RAW Paste Data