You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

375 lines
14 KiB

  1. # -*- coding: utf-8 -*-
  2. import nilmdb.server
  3. import nilmdb.client
  4. import nilmdb.client.numpyclient
  5. from nilmdb.utils.printf import *
  6. from nilmdb.utils import timestamper
  7. from nilmdb.client import ClientError, ServerError
  8. import datetime_tz
  9. from nose.plugins.skip import SkipTest
  10. from nose.tools import *
  11. from nose.tools import assert_raises
  12. import itertools
  13. import distutils.version
  14. from testutil.helpers import *
  15. import numpy as np
  16. testdb = "tests/numpyclient-testdb"
  17. testurl = "http://localhost:32180/"
  18. def setup_module():
  19. global test_server, test_db
  20. # Clear out DB
  21. recursive_unlink(testdb)
  22. # Start web app on a custom port
  23. test_db = nilmdb.utils.serializer_proxy(nilmdb.server.NilmDB)(
  24. testdb, bulkdata_args = { "file_size" : 16384,
  25. "files_per_dir" : 3 } )
  26. test_server = nilmdb.server.Server(test_db, host = "127.0.0.1",
  27. port = 32180, stoppable = False,
  28. fast_shutdown = True,
  29. force_traceback = True)
  30. test_server.start(blocking = False)
  31. def teardown_module():
  32. global test_server, test_db
  33. # Close web app
  34. test_server.stop()
  35. test_db.close()
  36. class TestNumpyClient(object):
  37. def test_numpyclient_01_basic(self):
  38. # Test basic connection
  39. client = nilmdb.client.numpyclient.NumpyClient(url = testurl)
  40. version = client.version()
  41. eq_(distutils.version.LooseVersion(version),
  42. distutils.version.LooseVersion(test_server.version))
  43. # Verify subclassing
  44. assert(isinstance(client, nilmdb.client.Client))
  45. # Layouts
  46. for layout in "int8_t", "something_8", "integer_1":
  47. with assert_raises(ValueError):
  48. for x in client.stream_extract_numpy("/foo", layout=layout):
  49. pass
  50. for layout in "int8_1", "uint8_30", "int16_20", "float64_100":
  51. with assert_raises(ClientError) as e:
  52. for x in client.stream_extract_numpy("/foo", layout=layout):
  53. pass
  54. in_("No such stream", str(e.exception))
  55. with assert_raises(ClientError) as e:
  56. for x in client.stream_extract_numpy("/foo"):
  57. pass
  58. in_("can't get layout for path", str(e.exception))
  59. client.close()
  60. def test_numpyclient_02_extract(self):
  61. client = nilmdb.client.numpyclient.NumpyClient(url = testurl)
  62. # Insert some data as text
  63. client.stream_create("/newton/prep", "float32_8")
  64. testfile = "tests/data/prep-20120323T1000"
  65. start = nilmdb.utils.time.parse_time("20120323T1000")
  66. rate = 120
  67. data = timestamper.TimestamperRate(testfile, start, rate)
  68. result = client.stream_insert("/newton/prep", data,
  69. start, start + 119999777)
  70. # Extract Numpy arrays
  71. array = None
  72. pieces = 0
  73. for chunk in client.stream_extract_numpy("/newton/prep", maxrows=1000):
  74. pieces += 1
  75. if array is not None:
  76. array = np.vstack((array, chunk))
  77. else:
  78. array = chunk
  79. eq_(array.shape, (14400, 9))
  80. eq_(pieces, 15)
  81. # Try structured
  82. s = list(client.stream_extract_numpy("/newton/prep", structured = True))
  83. assert(np.array_equal(np.c_[s[0]['timestamp'], s[0]['data']], array))
  84. # Compare. Will be close but not exact because the conversion
  85. # to and from ASCII was lossy.
  86. data = timestamper.TimestamperRate(testfile, start, rate)
  87. data_str = b" ".join(data).decode('utf-8', errors='backslashreplace')
  88. actual = np.fromstring(data_str, sep=' ').reshape(14400, 9)
  89. assert(np.allclose(array, actual))
  90. client.close()
  91. def test_numpyclient_03_insert(self):
  92. client = nilmdb.client.numpyclient.NumpyClient(url = testurl)
  93. # Limit _max_data just to get better coverage
  94. old_max_data = nilmdb.client.numpyclient.StreamInserterNumpy._max_data
  95. nilmdb.client.numpyclient.StreamInserterNumpy._max_data = 100000
  96. client.stream_create("/test/1", "uint16_1")
  97. client.stream_insert_numpy("/test/1",
  98. np.array([[0, 1],
  99. [1, 2],
  100. [2, 3],
  101. [3, 4]]))
  102. # Wrong number of dimensions
  103. with assert_raises(ValueError) as e:
  104. client.stream_insert_numpy("/test/1",
  105. np.array([[[0, 1],
  106. [1, 2]],
  107. [[3, 4],
  108. [4, 5]]]))
  109. in_("wrong number of dimensions", str(e.exception))
  110. # Wrong number of fields
  111. with assert_raises(ValueError) as e:
  112. client.stream_insert_numpy("/test/1",
  113. np.array([[0, 1, 2],
  114. [1, 2, 3],
  115. [3, 4, 5],
  116. [4, 5, 6]]))
  117. in_("wrong number of fields", str(e.exception))
  118. # Unstructured
  119. client.stream_create("/test/2", "float32_8")
  120. client.stream_insert_numpy(
  121. "/test/2",
  122. client.stream_extract_numpy(
  123. "/newton/prep", structured = False, maxrows = 1000))
  124. # Structured, and specifying layout
  125. client.stream_create("/test/3", "float32_8")
  126. client.stream_insert_numpy(
  127. path = "/test/3", layout = "float32_8",
  128. data = client.stream_extract_numpy(
  129. "/newton/prep", structured = True, maxrows = 1000))
  130. # Structured, specifying wrong layout
  131. client.stream_create("/test/4", "float32_8")
  132. with assert_raises(ValueError) as e:
  133. client.stream_insert_numpy(
  134. "/test/4", layout = "uint16_1",
  135. data = client.stream_extract_numpy(
  136. "/newton/prep", structured = True, maxrows = 1000))
  137. in_("wrong dtype", str(e.exception))
  138. # Unstructured, and specifying wrong layout
  139. client.stream_create("/test/5", "float32_8")
  140. with assert_raises(ClientError) as e:
  141. client.stream_insert_numpy(
  142. "/test/5", layout = "uint16_8",
  143. data = client.stream_extract_numpy(
  144. "/newton/prep", structured = False, maxrows = 1000))
  145. # timestamps will be screwy here, because data will be parsed wrong
  146. in_("error parsing input data", str(e.exception))
  147. # Make sure the /newton/prep copies are identical
  148. a = np.vstack(list(client.stream_extract_numpy("/newton/prep")))
  149. b = np.vstack(list(client.stream_extract_numpy("/test/2")))
  150. c = np.vstack(list(client.stream_extract_numpy("/test/3")))
  151. assert(np.array_equal(a,b))
  152. assert(np.array_equal(a,c))
  153. # Make sure none of the files are greater than 16384 bytes as
  154. # we configured with the bulkdata_args above.
  155. datapath = os.path.join(testdb, "data")
  156. for (dirpath, dirnames, filenames) in os.walk(datapath):
  157. for f in filenames:
  158. fn = os.path.join(dirpath, f)
  159. size = os.path.getsize(fn)
  160. if size > 16384:
  161. raise AssertionError(sprintf("%s is too big: %d > %d\n",
  162. fn, size, 16384))
  163. nilmdb.client.numpyclient.StreamInserterNumpy._max_data = old_max_data
  164. client.close()
  165. def test_numpyclient_04_context(self):
  166. # Like test_client_context, but with Numpy data
  167. client = nilmdb.client.numpyclient.NumpyClient(testurl)
  168. client.stream_create("/context/test", "uint16_1")
  169. with client.stream_insert_numpy_context("/context/test") as ctx:
  170. # override _max_rows to trigger frequent server updates
  171. ctx._max_rows = 2
  172. ctx.insert([[1000, 1]])
  173. ctx.insert([[1010, 1], [1020, 1], [1030, 1]])
  174. ctx.insert([[1040, 1], [1050, 1]])
  175. ctx.finalize()
  176. ctx.insert([[1070, 1]])
  177. ctx.update_end(1080)
  178. ctx.finalize()
  179. ctx.update_start(1090)
  180. ctx.insert([[1100, 1]])
  181. ctx.insert([[1110, 1]])
  182. ctx.send()
  183. ctx.insert([[1120, 1], [1130, 1], [1140, 1]])
  184. ctx.update_end(1160)
  185. ctx.insert([[1150, 1]])
  186. ctx.update_end(1170)
  187. ctx.insert([[1160, 1]])
  188. ctx.update_end(1180)
  189. ctx.insert([[1170, 123456789.0]])
  190. ctx.finalize()
  191. ctx.insert(np.zeros((0,2)))
  192. with assert_raises(ClientError):
  193. with client.stream_insert_numpy_context("/context/test",
  194. 1000, 2000) as ctx:
  195. ctx.insert([[1180, 1]])
  196. with assert_raises(ClientError):
  197. with client.stream_insert_numpy_context("/context/test",
  198. 2000, 3000) as ctx:
  199. ctx._max_rows = 2
  200. ctx.insert([[3180, 1]])
  201. ctx.insert([[3181, 1]])
  202. with client.stream_insert_numpy_context("/context/test",
  203. 2000, 3000) as ctx:
  204. # make sure our override wasn't permanent
  205. ne_(ctx._max_rows, 2)
  206. ctx.insert([[2250, 1]])
  207. ctx.finalize()
  208. with assert_raises(ClientError):
  209. with client.stream_insert_numpy_context("/context/test",
  210. 3000, 4000) as ctx:
  211. ctx.insert([[3010, 1]])
  212. ctx.insert([[3020, 2]])
  213. ctx.insert([[3030, 3]])
  214. ctx.insert([[3040, 4]])
  215. ctx.insert([[3040, 4]]) # non-monotonic after a few lines
  216. ctx.finalize()
  217. eq_(list(client.stream_intervals("/context/test")),
  218. [ [ 1000, 1051 ],
  219. [ 1070, 1080 ],
  220. [ 1090, 1180 ],
  221. [ 2000, 3000 ] ])
  222. client.stream_remove("/context/test")
  223. client.stream_destroy("/context/test")
  224. client.close()
  225. def test_numpyclient_05_emptyintervals(self):
  226. # Like test_client_emptyintervals, with insert_numpy_context
  227. client = nilmdb.client.numpyclient.NumpyClient(testurl)
  228. client.stream_create("/empty/test", "uint16_1")
  229. def info():
  230. result = []
  231. for interval in list(client.stream_intervals("/empty/test")):
  232. result.append((client.stream_count("/empty/test", *interval),
  233. interval))
  234. return result
  235. eq_(info(), [])
  236. # Insert a region with just a few points
  237. with client.stream_insert_numpy_context("/empty/test") as ctx:
  238. ctx.update_start(100)
  239. ctx.insert([[140, 1]])
  240. ctx.insert([[150, 1]])
  241. ctx.insert([[160, 1]])
  242. ctx.update_end(200)
  243. ctx.finalize()
  244. eq_(info(), [(3, [100, 200])])
  245. # Delete chunk, which will leave one data point and two intervals
  246. client.stream_remove("/empty/test", 145, 175)
  247. eq_(info(), [(1, [100, 145]),
  248. (0, [175, 200])])
  249. # Try also creating a completely empty interval from scratch,
  250. # in a few different ways.
  251. client.stream_insert("/empty/test", b"", 300, 350)
  252. client.stream_insert("/empty/test", [], 400, 450)
  253. with client.stream_insert_numpy_context("/empty/test", 500, 550):
  254. pass
  255. # If enough timestamps aren't provided, empty streams won't be created.
  256. client.stream_insert("/empty/test", [])
  257. with client.stream_insert_numpy_context("/empty/test"):
  258. pass
  259. client.stream_insert("/empty/test", [], start = 600)
  260. with client.stream_insert_numpy_context("/empty/test", start = 700):
  261. pass
  262. client.stream_insert("/empty/test", [], end = 850)
  263. with client.stream_insert_numpy_context("/empty/test", end = 950):
  264. pass
  265. # Equal start and end is OK as long as there's no data
  266. with assert_raises(ClientError) as e:
  267. with client.stream_insert_numpy_context("/empty/test",
  268. start=9, end=9) as ctx:
  269. ctx.insert([[9, 9]])
  270. ctx.finalize()
  271. in_("have data to send, but invalid start/end times", str(e.exception))
  272. with client.stream_insert_numpy_context("/empty/test",
  273. start=9, end=9) as ctx:
  274. pass
  275. # reusing a context object is bad
  276. with assert_raises(Exception) as e:
  277. ctx.insert([[9, 9]])
  278. # Try various things that might cause problems
  279. with client.stream_insert_numpy_context("/empty/test",
  280. 1000, 1050) as ctx:
  281. ctx.finalize() # inserts [1000, 1050]
  282. ctx.finalize() # nothing
  283. ctx.finalize() # nothing
  284. ctx.insert([[1100, 1]])
  285. ctx.finalize() # inserts [1100, 1101]
  286. ctx.update_start(1199)
  287. ctx.insert([[1200, 1]])
  288. ctx.update_end(1250)
  289. ctx.finalize() # inserts [1199, 1250]
  290. ctx.update_start(1299)
  291. ctx.finalize() # nothing
  292. ctx.update_end(1350)
  293. ctx.finalize() # nothing
  294. ctx.update_start(1400)
  295. ctx.insert(np.zeros((0,2)))
  296. ctx.update_end(1450)
  297. ctx.finalize()
  298. ctx.update_start(1500)
  299. ctx.insert(np.zeros((0,2)))
  300. ctx.update_end(1550)
  301. ctx.finalize()
  302. ctx.insert(np.zeros((0,2)))
  303. ctx.insert(np.zeros((0,2)))
  304. ctx.insert(np.zeros((0,2)))
  305. ctx.finalize()
  306. # Check everything
  307. eq_(info(), [(1, [100, 145]),
  308. (0, [175, 200]),
  309. (0, [300, 350]),
  310. (0, [400, 450]),
  311. (0, [500, 550]),
  312. (0, [1000, 1050]),
  313. (1, [1100, 1101]),
  314. (1, [1199, 1250]),
  315. (0, [1400, 1450]),
  316. (0, [1500, 1550]),
  317. ])
  318. # Clean up
  319. client.stream_remove("/empty/test")
  320. client.stream_destroy("/empty/test")
  321. client.close()