database.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import numpy as np
  2. from datetime import datetime
  3. import csv
  4. class Table:
  5. def __init__(self, columns, nRows = 2**16):
  6. self.columnNames = ['datetime'] + columns
  7. self.nCols = len(columns)
  8. self.nRows = nRows
  9. self.rows = self.ys = np.ndarray(shape=(self.nRows, self.nCols), dtype=float)
  10. self.rows.fill(float('NaN'))
  11. self.timestamps = np.ndarray(shape=(self.nRows), dtype='datetime64[ns]')
  12. self.rowIndex = 0
  13. def rowIdToOffset(self, id):
  14. return self.nRows - (id % self.nRows) - 1
  15. def addRow(self, values):
  16. offset = self.rowIdToOffset(self.rowIndex)
  17. self.rows[offset] = values
  18. self.timestamps[offset] = datetime.now()
  19. self.rowIndex += 1
  20. def getLastRows(self, n):
  21. nRead = min(n, self.nRows)
  22. readStart = self.rowIdToOffset(self.rowIndex - 1)
  23. readEnd = self.rowIdToOffset(self.rowIndex - nRead - 1)
  24. if readEnd > readStart:
  25. return self.rows[readStart:readEnd]
  26. else:
  27. return np.concatenate((self.rows[readStart:], self.rows[:readEnd]), axis=0)
  28. def getLastTimestamps(self, n):
  29. nRead = min(n, self.nRows)
  30. readStart = self.rowIdToOffset(self.rowIndex - 1)
  31. readEnd = self.rowIdToOffset(self.rowIndex - nRead - 1)
  32. if readEnd > readStart:
  33. return self.timestamps[readStart:readEnd]
  34. else:
  35. return np.concatenate((self.timestamps[readStart:], self.timestamps[:readEnd]), axis=0)
  36. def getLastValues(self, n, column):
  37. col = self.columnNames.index(column)
  38. if col > 0:
  39. return self.getLastRows(n)[:,col-1]
  40. else:
  41. return self.getLastTimestamps(n)
  42. def getLastValue(self, column):
  43. return self.getLastValues(1, column)[0]
  44. def saveAsCsv(self, filename):
  45. with open(filename,"w+", newline='') as my_csv:
  46. csvWriter = csv.writer(my_csv,delimiter=',')
  47. csvWriter.writerow(self.columnNames)
  48. timestamps = self.getLastTimestamps(self.rowIndex)
  49. for ts, vals in zip(self.getLastTimestamps(self.rowIndex), self.getLastRows(self.rowIndex)):
  50. csvWriter.writerow([ts] + list(vals))
  51. if __name__ == "__main__":
  52. t = Table(["col1", "col2"])
  53. for i in range(99):
  54. t.addRow([i, 2])
  55. print(t.getLastRows(100))
  56. t.addRow([3, 4])
  57. print(t.getLastRows(1))
  58. t.saveAsCsv('test.csv')