database.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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.timestamps.fill(datetime.now())
  13. self.rowIndex = 0
  14. def reset(self):
  15. self.rows.fill(float('NaN'))
  16. self.rowIndex = 0
  17. def rowIdToOffset(self, id):
  18. return self.nRows - (id % self.nRows) - 1
  19. def addRow(self, values):
  20. offset = self.rowIdToOffset(self.rowIndex)
  21. self.rows[offset] = values
  22. self.timestamps[offset] = datetime.now()
  23. self.rowIndex += 1
  24. def getLastRows(self, n):
  25. nRead = min(n, self.nRows)
  26. readStart = self.rowIdToOffset(self.rowIndex - 1)
  27. readEnd = self.rowIdToOffset(self.rowIndex - nRead - 1)
  28. if readEnd > readStart:
  29. return self.rows[readStart:readEnd]
  30. else:
  31. return np.concatenate((self.rows[readStart:], self.rows[:readEnd]), axis=0)
  32. def getLastTimestamps(self, n):
  33. nRead = min(n, self.nRows)
  34. readStart = self.rowIdToOffset(self.rowIndex - 1)
  35. readEnd = self.rowIdToOffset(self.rowIndex - nRead - 1)
  36. if readEnd > readStart:
  37. return self.timestamps[readStart:readEnd]
  38. else:
  39. return np.concatenate((self.timestamps[readStart:], self.timestamps[:readEnd]), axis=0)
  40. def getLastValues(self, n, column):
  41. col = self.columnNames.index(column)
  42. if col > 0:
  43. return self.getLastRows(n)[:,col-1]
  44. else:
  45. return self.getLastTimestamps(n)
  46. def getLastValue(self, column):
  47. return self.getLastValues(1, column)[0]
  48. def saveAsCsv(self, fd):
  49. csvWriter = csv.writer(fd,delimiter=',')
  50. csvWriter.writerow(self.columnNames)
  51. timestamps = self.getLastTimestamps(self.rowIndex)
  52. for ts, vals in zip(self.getLastTimestamps(self.rowIndex), self.getLastRows(self.rowIndex)):
  53. csvWriter.writerow([ts] + list(vals))
  54. if __name__ == "__main__":
  55. t = Table(["col1", "col2"])
  56. for i in range(99):
  57. t.addRow([i, 2])
  58. print(t.getLastRows(100))
  59. t.addRow([3, 4])
  60. print(t.getLastRows(1))
  61. t.saveAsCsv('test.csv')