test_tsio.py 40.6 KB
Newer Older
1
# coding: utf-8
2
from datetime import datetime, timedelta
3
from time import time
4
from dateutil import parser
5
import calendar
6

Aurélien Campéas's avatar
Aurélien Campéas committed
7
from pathlib2 import Path
8
9
import pandas as pd
import numpy as np
10
import pytest
11
from mock import patch
12

13
from tshistory.testutil import assert_group_equals, genserie, assert_df
14

15
DATADIR = Path(__file__).parent / 'data'
16

Aurélien Campéas's avatar
Aurélien Campéas committed
17

18
def test_changeset(engine, tsh):
19
    index = pd.date_range(start=datetime(2017, 1, 1), freq='D', periods=3)
20
    data = [1., 2., 3.]
21

22
23
    with patch('tshistory.tsio.datetime') as mock_date:
        mock_date.now.return_value = datetime(2020, 1, 1)
24
        with engine.connect() as cn:
25
            with tsh.newchangeset(cn, 'babar'):
26
                tsh.insert(cn, pd.Series(data, index=index), 'ts_values', author='WONTBEUSED')
27
                tsh.insert(cn, pd.Series(['a', 'b', 'c'], index=index), 'ts_othervalues')
28

29
30
31
        # bogus author won't show up
        assert tsh.log(engine)[0]['author'] == 'babar'

32
33
        g = tsh.get_group(engine, 'ts_values')
        g2 = tsh.get_group(engine, 'ts_othervalues')
34
        assert_group_equals(g, g2)
35

36
        with pytest.raises(AssertionError):
37
            tsh.insert(engine, pd.Series([2, 3, 4], index=index), 'ts_values')
38

39
        with engine.connect() as cn:
40
            data.append(data.pop(0))
41
42
            with tsh.newchangeset(cn, 'celeste'):
                tsh.insert(cn, pd.Series(data, index=index), 'ts_values')
43
                # below should be a noop
44
                tsh.insert(cn, pd.Series(['a', 'b', 'c'], index=index), 'ts_othervalues')
45

46
    g = tsh.get_group(engine, 'ts_values')
47
48
    assert ['ts_values'] == list(g.keys())

49
    assert_df("""
50
51
52
2017-01-01    2.0
2017-01-02    3.0
2017-01-03    1.0
53
""", tsh.get(engine, 'ts_values'))
54

55
    assert_df("""
56
57
58
2017-01-01    a
2017-01-02    b
2017-01-03    c
59
""", tsh.get(engine, 'ts_othervalues'))
60

61
    log = tsh.log(engine, names=['ts_values', 'ts_othervalues'])
62
63
64
65
    assert [
        {'author': 'babar',
         'rev': 1,
         'date': datetime(2020, 1, 1, 0, 0),
66
         'meta': {},
67
68
69
         'names': ['ts_values', 'ts_othervalues']},
        {'author': 'celeste',
         'rev': 2,
70
         'meta': {},
71
72
73
74
         'date': datetime(2020, 1, 1, 0, 0),
         'names': ['ts_values']}
    ] == log

75
    log = tsh.log(engine, names=['ts_othervalues'])
76
77
    assert len(log) == 1
    assert log[0]['rev'] == 1
78
    assert log[0]['names'] == ['ts_values', 'ts_othervalues']
79

80
    log = tsh.log(engine, fromrev=2)
81
82
    assert len(log) == 1

83
    log = tsh.log(engine, torev=1)
84
85
    assert len(log) == 1

86
    info = tsh.info(engine)
87
88
89
90
91
92
    assert {
        'changeset count': 2,
        'serie names': ['ts_othervalues', 'ts_values'],
        'series count': 2
    } == info

93

94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
def test_strip(engine, tsh):
    for i in range(1, 5):
        pubdate = datetime(2017, 1, i)
        ts = genserie(datetime(2017, 1, 10), 'H', 1 + i)
        with tsh.newchangeset(engine, 'babar', _insertion_date=pubdate):
            tsh.insert(engine, ts, 'xserie')
        # also insert something completely unrelated
        tsh.insert(engine, genserie(datetime(2018, 1, 1), 'D', 1 + i), 'yserie', 'celeste')

    csida = tsh.changeset_at(engine, 'xserie', datetime(2017, 1, 3))
    assert csida is not None
    csidb = tsh.changeset_at(engine, 'xserie', datetime(2017, 1, 3, 1), mode='before')
    csidc = tsh.changeset_at(engine, 'xserie', datetime(2017, 1, 3, 1), mode='after')
    assert csidb < csida < csidc

    log = tsh.log(engine, names=['xserie', 'yserie'])
    assert [(idx, l['author']) for idx, l in enumerate(log, start=1)
    ] == [
        (1, 'babar'),
        (2, 'celeste'),
        (3, 'babar'),
        (4, 'celeste'),
        (5, 'babar'),
        (6, 'celeste'),
        (7, 'babar'),
        (8, 'celeste')
    ]

    h = tsh.get_history(engine, 'xserie')
    assert_df("""
insertion_date  value_date         
2017-01-01      2017-01-10 00:00:00    0.0
                2017-01-10 01:00:00    1.0
2017-01-02      2017-01-10 00:00:00    0.0
                2017-01-10 01:00:00    1.0
                2017-01-10 02:00:00    2.0
2017-01-03      2017-01-10 00:00:00    0.0
                2017-01-10 01:00:00    1.0
                2017-01-10 02:00:00    2.0
                2017-01-10 03:00:00    3.0
2017-01-04      2017-01-10 00:00:00    0.0
                2017-01-10 01:00:00    1.0
                2017-01-10 02:00:00    2.0
                2017-01-10 03:00:00    3.0
                2017-01-10 04:00:00    4.0
""", h)

    csid = tsh.changeset_at(engine, 'xserie', datetime(2017, 1, 3))
    with engine.connect() as cn:
        tsh.strip(cn, 'xserie', csid)

    assert_df("""
insertion_date  value_date         
2017-01-01      2017-01-10 00:00:00    0.0
                2017-01-10 01:00:00    1.0
2017-01-02      2017-01-10 00:00:00    0.0
                2017-01-10 01:00:00    1.0
                2017-01-10 02:00:00    2.0
""", tsh.get_history(engine, 'xserie'))

    assert_df("""
2017-01-10 00:00:00    0.0
2017-01-10 01:00:00    1.0
2017-01-10 02:00:00    2.0
""", tsh.get(engine, 'xserie'))

    # internal structure is ok
    with engine.connect() as cn:
        cn.execute('set search_path to "{}.timeserie"'.format(tsh.namespace))
        df = pd.read_sql("select id, diff, snapshot from xserie order by id", cn)
        for attr in ('diff', 'snapshot'):
            df[attr] = df[attr].apply(lambda x: False if x is None else True)

    assert_df("""
id   diff  snapshot
0   1  False      True
1   2   True      True
""", df)

    log = tsh.log(engine, names=['xserie', 'yserie'])
    # 5 and 7 have disappeared
    assert [l['author'] for l in log
    ] == ['babar', 'celeste', 'babar', 'celeste', 'celeste', 'celeste']

    log = tsh.log(engine, stripped=True, names=['xserie', 'yserie'])
    assert [list(l['meta'].values())[0][:-1] + 'X' for l in log if l['meta']
    ] == [
        'got stripped from X',
        'got stripped from X'
    ]


186
def test_tstamp_roundtrip(engine, tsh):
187
188
    ts = genserie(datetime(2017, 10, 28, 23),
                  'H', 4, tz='UTC')
189
190
191
192
193
194
195
196
197
198
    ts.index = ts.index.tz_convert('Europe/Paris')

    assert_df("""
2017-10-29 01:00:00+02:00    0
2017-10-29 02:00:00+02:00    1
2017-10-29 02:00:00+01:00    2
2017-10-29 03:00:00+01:00    3
Freq: H
    """, ts)

199
200
    tsh.insert(engine, ts, 'tztest', 'Babar')
    back = tsh.get(engine, 'tztest')
201
202
203
204
205
206
207
208
209
210
211
212
213

    # though un localized we understand it's been normalized to utc
    assert_df("""
2017-10-28 23:00:00    0.0
2017-10-29 00:00:00    1.0
2017-10-29 01:00:00    2.0
2017-10-29 02:00:00    3.0
""", back)

    back.index = back.index.tz_localize('UTC')
    assert (ts.index == back.index).all()


214
def test_differential(engine, tsh):
215
    ts_begin = genserie(datetime(2010, 1, 1), 'D', 10)
216
    tsh.insert(engine, ts_begin, 'ts_test', 'test')
217

218
219
    assert tsh.exists(engine, 'ts_test')
    assert not tsh.exists(engine, 'this_does_not_exist')
220

221
    assert_df("""
222
223
224
225
226
227
228
229
230
231
2010-01-01    0.0
2010-01-02    1.0
2010-01-03    2.0
2010-01-04    3.0
2010-01-05    4.0
2010-01-06    5.0
2010-01-07    6.0
2010-01-08    7.0
2010-01-09    8.0
2010-01-10    9.0
232
""", tsh.get(engine, 'ts_test'))
233
234

    # we should detect the emission of a message
235
    tsh.insert(engine, ts_begin, 'ts_test', 'babar')
236

237
    assert_df("""
238
239
240
241
242
243
244
245
246
247
2010-01-01    0.0
2010-01-02    1.0
2010-01-03    2.0
2010-01-04    3.0
2010-01-05    4.0
2010-01-06    5.0
2010-01-07    6.0
2010-01-08    7.0
2010-01-09    8.0
2010-01-10    9.0
248
""", tsh.get(engine, 'ts_test'))
249
250
251
252

    ts_slight_variation = ts_begin.copy()
    ts_slight_variation.iloc[3] = 0
    ts_slight_variation.iloc[6] = 0
253
    tsh.insert(engine, ts_slight_variation, 'ts_test', 'celeste')
254

255
    assert_df("""
256
257
258
259
260
261
262
263
264
265
2010-01-01    0.0
2010-01-02    1.0
2010-01-03    2.0
2010-01-04    0.0
2010-01-05    4.0
2010-01-06    5.0
2010-01-07    0.0
2010-01-08    7.0
2010-01-09    8.0
2010-01-10    9.0
266
""", tsh.get(engine, 'ts_test'))
267

268
    ts_longer = genserie(datetime(2010, 1, 3), 'D', 15)
269
270
271
272
    ts_longer.iloc[1] = 2.48
    ts_longer.iloc[3] = 3.14
    ts_longer.iloc[5] = ts_begin.iloc[7]

273
    tsh.insert(engine, ts_longer, 'ts_test', 'test')
274

275
    assert_df("""
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
2010-01-01     0.00
2010-01-02     1.00
2010-01-03     0.00
2010-01-04     2.48
2010-01-05     2.00
2010-01-06     3.14
2010-01-07     4.00
2010-01-08     7.00
2010-01-09     6.00
2010-01-10     7.00
2010-01-11     8.00
2010-01-12     9.00
2010-01-13    10.00
2010-01-14    11.00
2010-01-15    12.00
2010-01-16    13.00
2010-01-17    14.00
293
""", tsh.get(engine, 'ts_test'))
294
295

    # start testing manual overrides
296
    ts_begin = genserie(datetime(2010, 1, 1), 'D', 5, initval=[2])
297
    ts_begin.loc['2010-01-04'] = -1
298
    tsh.insert(engine, ts_begin, 'ts_mixte', 'test')
299
300

    # -1 represents bogus upstream data
301
    assert_df("""
302
303
304
305
306
2010-01-01    2.0
2010-01-02    2.0
2010-01-03    2.0
2010-01-04   -1.0
2010-01-05    2.0
307
""", tsh.get(engine, 'ts_mixte'))
308
309

    # refresh all the period + 1 extra data point
310
    ts_more = genserie(datetime(2010, 1, 2), 'D', 5, [2])
311
    ts_more.loc['2010-01-04'] = -1
312
    tsh.insert(engine, ts_more, 'ts_mixte', 'test')
313

314
    assert_df("""
315
316
317
318
319
320
2010-01-01    2.0
2010-01-02    2.0
2010-01-03    2.0
2010-01-04   -1.0
2010-01-05    2.0
2010-01-06    2.0
321
""", tsh.get(engine, 'ts_mixte'))
322
323

    # just append an extra data point
324
325
    # with no intersection with the previous ts
    ts_one_more = genserie(datetime(2010, 1, 7), 'D', 1, [3])
326
    tsh.insert(engine, ts_one_more, 'ts_mixte', 'test')
327

328
    assert_df("""
329
330
331
332
333
334
335
2010-01-01    2.0
2010-01-02    2.0
2010-01-03    2.0
2010-01-04   -1.0
2010-01-05    2.0
2010-01-06    2.0
2010-01-07    3.0
336
""", tsh.get(engine, 'ts_mixte'))
337

338
    with engine.connect() as cn:
339
        cn.execute('set search_path to "{0}.timeserie", {0}, public'.format(tsh.namespace))
340
341
342
        hist = pd.read_sql('select id, parent from ts_test order by id',
                           cn)
        assert_df("""
343
344
345
346
   id  parent
0   1     NaN
1   2     1.0
2   3     2.0
347
""", hist)
348

349
350
351
        hist = pd.read_sql('select id, parent from ts_mixte order by id',
                           cn)
        assert_df("""
352
353
354
355
   id  parent
0   1     NaN
1   2     1.0
2   3     2.0
356
""", hist)
357

358
359
360
        allts = pd.read_sql("select name, table_name from registry "
                            "where name in ('ts_test', 'ts_mixte')",
                            cn)
361

362
363
        assert_df("""
name              table_name
364
365
366
0   ts_test   {0}.timeserie.ts_test
1  ts_mixte  {0}.timeserie.ts_mixte
""".format(tsh.namespace), allts)
367

368
        assert_df("""
369
370
371
372
373
374
375
2010-01-01    2.0
2010-01-02    2.0
2010-01-03    2.0
2010-01-04   -1.0
2010-01-05    2.0
2010-01-06    2.0
2010-01-07    3.0
376
""", tsh.get(cn, 'ts_mixte',
377
             revision_date=datetime.now()))
378
379


380
def test_bad_import(engine, tsh):
381
    # the data were parsed as date by pd.read_json()
Aurélien Campéas's avatar
Aurélien Campéas committed
382
    df_result = pd.read_csv(str(DATADIR / 'test_data.csv'))
383
384
385
    df_result['Gas Day'] = df_result['Gas Day'].apply(parser.parse, dayfirst=True, yearfirst=False)
    df_result.set_index('Gas Day', inplace=True)
    ts = df_result['SC']
386

387
388
    tsh.insert(engine, ts, 'SND_SC', 'test')
    result = tsh.get(engine, 'SND_SC')
389
    assert result.dtype == 'float64'
390
391
392

    # insertion of empty ts
    ts = pd.Series(name='truc', dtype='object')
393
394
    tsh.insert(engine, ts, 'empty_ts', 'test')
    assert tsh.get(engine, 'empty_ts') is None
395
396
397

    # nan in ts
    # all na
398
    ts = genserie(datetime(2010, 1, 10), 'D', 10, [np.nan], name='truc')
399
400
    tsh.insert(engine, ts, 'test_nan', 'test')
    assert tsh.get(engine, 'test_nan') is None
401
402
403
404
405

    # mixe na
    ts = pd.Series([np.nan] * 5 + [3] * 5,
                   index=pd.date_range(start=datetime(2010, 1, 10),
                                       freq='D', periods=10), name='truc')
406
407
    tsh.insert(engine, ts, 'test_nan', 'test')
    result = tsh.get(engine, 'test_nan')
408

409
410
    tsh.insert(engine, ts, 'test_nan', 'test')
    result = tsh.get(engine, 'test_nan')
411
    assert_df("""
412
413
414
415
416
2010-01-15    3.0
2010-01-16    3.0
2010-01-17    3.0
2010-01-18    3.0
2010-01-19    3.0
417
""", result)
418
419
420

    # get_ts with name not in database

421
    tsh.get(engine, 'inexisting_name', 'test')
422
423


424
def test_revision_date(engine, tsh):
425
426
427
428
429
430
431
432
433
434
435
    # we prepare a good joke for the end of the test
    ival = tsh._snapshot_interval
    tsh._snapshot_interval = 3

    for i in range(1, 5):
        with engine.connect() as cn:
            with tsh.newchangeset(cn, 'test',
                                  _insertion_date=datetime(2016, 1, i)):
                tsh.insert(cn, genserie(datetime(2017, 1, i), 'D', 3, [i]), 'revdate')

    # end of prologue, now some real meat
436
437
438
439
440
441
442
    idate0 = datetime(2015, 1, 1, 0, 0, 0)
    with tsh.newchangeset(engine, 'test', _insertion_date=idate0):

        ts = genserie(datetime(2010, 1, 4), 'D', 4, [0], name='truc')
        tsh.insert(engine, ts, 'ts_through_time')
        assert idate0 == tsh.latest_insertion_date(engine, 'ts_through_time')

443
    idate1 = datetime(2015, 1, 1, 15, 43, 23)
444
    with tsh.newchangeset(engine, 'test', _insertion_date=idate1):
445

446
        ts = genserie(datetime(2010, 1, 4), 'D', 4, [1], name='truc')
447
448
        tsh.insert(engine, ts, 'ts_through_time')
        assert idate1 == tsh.latest_insertion_date(engine, 'ts_through_time')
449

450
    idate2 = datetime(2015, 1, 2, 15, 43, 23)
451
    with tsh.newchangeset(engine, 'test', _insertion_date=idate2):
452

453
        ts = genserie(datetime(2010, 1, 4), 'D', 4, [2], name='truc')
454
455
        tsh.insert(engine, ts, 'ts_through_time')
        assert idate2 == tsh.latest_insertion_date(engine, 'ts_through_time')
456

457
    idate3 = datetime(2015, 1, 3, 15, 43, 23)
458
    with tsh.newchangeset(engine, 'test', _insertion_date=idate3):
459

460
        ts = genserie(datetime(2010, 1, 4), 'D', 4, [3], name='truc')
461
462
        tsh.insert(engine, ts, 'ts_through_time')
        assert idate3 == tsh.latest_insertion_date(engine, 'ts_through_time')
463

464
    ts = tsh.get(engine, 'ts_through_time')
465

466
    assert_df("""
467
468
469
470
2010-01-04    3.0
2010-01-05    3.0
2010-01-06    3.0
2010-01-07    3.0
471
""", ts)
472

473
    ts = tsh.get(engine, 'ts_through_time',
Aurélien Campéas's avatar
Aurélien Campéas committed
474
                 revision_date=datetime(2015, 1, 2, 18, 43, 23))
475

476
    assert_df("""
477
478
479
480
2010-01-04    2.0
2010-01-05    2.0
2010-01-06    2.0
2010-01-07    2.0
481
""", ts)
482

483
    ts = tsh.get(engine, 'ts_through_time',
484
                 revision_date=datetime(2015, 1, 1, 18, 43, 23))
485

486
    assert_df("""
487
488
489
490
2010-01-04    1.0
2010-01-05    1.0
2010-01-06    1.0
2010-01-07    1.0
491
""", ts)
492

493
    ts = tsh.get(engine, 'ts_through_time',
494
                 revision_date=datetime(2014, 1, 1, 18, 43, 23))
495
496
497

    assert ts is None

498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
    # epilogue: back to the revdate issue
    assert_df("""
2017-01-01    1.0
2017-01-02    2.0
2017-01-03    3.0
2017-01-04    4.0
2017-01-05    4.0
2017-01-06    4.0
""", tsh.get(engine, 'revdate'))

    bogus = tsh.get(engine, 'revdate', revision_date=datetime(2016, 1, 2))
    assert_df("""
2017-01-01    1.0
2017-01-02    2.0
2017-01-03    3.0
2017-01-04    4.0
2017-01-05    4.0
2017-01-06    4.0
""", bogus)  # oops, looks like we didn't pick the right data

    tsh._snapshot_interval = ival

520

521
def test_snapshots(engine, tsh):
522
    baseinterval = tsh._snapshot_interval
523
    tsh._snapshot_interval = 4
524

525
    with engine.connect() as cn:
526
        for tscount in range(1, 11):
527
            ts = genserie(datetime(2015, 1, 1), 'D', tscount, [1])
528
            diff = tsh.insert(cn, ts, 'growing', 'babar')
529
530
            assert diff.index[0] == diff.index[-1] == ts.index[-1]

531
    diff = tsh.insert(engine, ts, 'growing', 'babar')
532
    assert diff is None
533

534
    with engine.connect() as cn:
535
        cn.execute('set search_path to "{}.timeserie"'.format(tsh.namespace))
536
537
538
        df = pd.read_sql("select id from growing where snapshot is not null",
                         cn)
        assert_df("""
539
540
   id
0   1
541
542
543
1   4
2   8
3  10
544
""", df)
545

546
547
        ts = tsh.get(cn, 'growing')
        assert_df("""
548
549
550
551
552
553
554
555
556
557
2015-01-01    1.0
2015-01-02    1.0
2015-01-03    1.0
2015-01-04    1.0
2015-01-05    1.0
2015-01-06    1.0
2015-01-07    1.0
2015-01-08    1.0
2015-01-09    1.0
2015-01-10    1.0
558
""", ts)
559

560
561
562
        df = pd.read_sql("select id, diff, snapshot from growing order by id", cn)
        for attr in ('diff', 'snapshot'):
            df[attr] = df[attr].apply(lambda x: 0 if x is None else len(x))
563

564
        assert_df("""
565
566
567
568
569
570
571
572
573
574
575
id  diff  snapshot
0   1     0        35
1   2    36         0
2   3    36         0
3   4    36        47
4   5    36         0
5   6    36         0
6   7    36         0
7   8    36        59
8   9    36         0
9  10    36        67
576
""", df)
577

578
579
    table = tsh._get_ts_table(engine, 'growing')
    snapid, snap = tsh._find_snapshot(engine, table, ())
580
581
    assert snapid == 10
    assert (ts == snap).all()
582
    tsh._snapshot_interval = baseinterval
583
584


585
def test_deletion(engine, tsh):
586
587
    ts_begin = genserie(datetime(2010, 1, 1), 'D', 11)
    ts_begin.iloc[-1] = np.nan
588
    tsh.insert(engine, ts_begin, 'ts_del', 'test')
589

590
    ts = tsh._build_snapshot_upto(engine, tsh._get_ts_table(engine, 'ts_del'))
591
    assert ts.iloc[-1] == 9.0
592

593
    ts_begin.iloc[0] = np.nan
594
    ts_begin.iloc[3] = np.nan
595

596
    tsh.insert(engine, ts_begin, 'ts_del', 'test')
597

598
    assert_df("""
599
600
601
602
603
604
605
2010-01-02    1.0
2010-01-03    2.0
2010-01-05    4.0
2010-01-06    5.0
2010-01-07    6.0
2010-01-08    7.0
2010-01-09    8.0
606
2010-01-10    9.0
607
""", tsh.get(engine, 'ts_del'))
608

609
    ts2 = tsh.get(engine, 'ts_del',
610
611
                 # force snapshot reconstruction feature
                 revision_date=datetime(2038, 1, 1))
612
    assert (tsh.get(engine, 'ts_del') == ts2).all()
613

614
615
616
    ts_begin.iloc[0] = 42
    ts_begin.iloc[3] = 23

617
    tsh.insert(engine, ts_begin, 'ts_del', 'test')
618

619
    assert_df("""
620
621
622
623
624
625
626
627
628
2010-01-01    42.0
2010-01-02     1.0
2010-01-03     2.0
2010-01-04    23.0
2010-01-05     4.0
2010-01-06     5.0
2010-01-07     6.0
2010-01-08     7.0
2010-01-09     8.0
629
2010-01-10     9.0
630
""", tsh.get(engine, 'ts_del'))
631
632
633

    # now with string!

634
    ts_string = genserie(datetime(2010, 1, 1), 'D', 10, ['machin'])
635
    tsh.insert(engine, ts_string, 'ts_string_del', 'test')
636
637
638
639

    ts_string[4] = None
    ts_string[5] = None

640
    tsh.insert(engine, ts_string, 'ts_string_del', 'test')
641
    assert_df("""
642
643
644
645
646
647
648
649
2010-01-01    machin
2010-01-02    machin
2010-01-03    machin
2010-01-04    machin
2010-01-07    machin
2010-01-08    machin
2010-01-09    machin
2010-01-10    machin
650
""", tsh.get(engine, 'ts_string_del'))
651
652
653
654

    ts_string[4] = 'truc'
    ts_string[6] = 'truc'

655
    tsh.insert(engine, ts_string, 'ts_string_del', 'test')
656
    assert_df("""
657
658
659
660
661
662
663
664
2010-01-01    machin
2010-01-02    machin
2010-01-03    machin
2010-01-04    machin
2010-01-05      truc
2010-01-07      truc
2010-01-08    machin
2010-01-09    machin
665
2010-01-10    machin
666
""", tsh.get(engine, 'ts_string_del'))
667

668
    ts_string[ts_string.index] = np.nan
669
    tsh.insert(engine, ts_string, 'ts_string_del', 'test')
670

671
    erased = tsh.get(engine, 'ts_string_del')
672
673
    assert len(erased) == 0

674
675
    # first insertion with only nan

676
    ts_begin = genserie(datetime(2010, 1, 1), 'D', 10, [np.nan])
677
    tsh.insert(engine, ts_begin, 'ts_null', 'test')
678

679
    assert tsh.get(engine, 'ts_null') is None
680

681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
    # exhibit issue with nans handling
    ts_repushed = genserie(datetime(2010, 1, 1), 'D', 11)
    ts_repushed[0:3] = np.nan

    assert_df("""
2010-01-01     NaN
2010-01-02     NaN
2010-01-03     NaN
2010-01-04     3.0
2010-01-05     4.0
2010-01-06     5.0
2010-01-07     6.0
2010-01-08     7.0
2010-01-09     8.0
2010-01-10     9.0
2010-01-11    10.0
Freq: D
""", ts_repushed)

700
701
    tsh.insert(engine, ts_repushed, 'ts_repushed', 'test')
    diff = tsh.insert(engine, ts_repushed, 'ts_repushed', 'test')
702
703
    assert diff is None

704
    # there is no difference
705
    assert 0 == len(tsh._compute_diff(ts_repushed, ts_repushed))
706
707
708
709
710

    ts_add = genserie(datetime(2010, 1, 1), 'D', 15)
    ts_add.iloc[0] = np.nan
    ts_add.iloc[13:] = np.nan
    ts_add.iloc[8] = np.nan
711
    diff = tsh._compute_diff(ts_repushed, ts_add)
712
713
714
715
716
717

    assert_df("""
2010-01-02     1.0
2010-01-03     2.0
2010-01-09     NaN
2010-01-12    11.0
718
2010-01-13    12.0""", diff.sort_index())
719
720
721
722
    # value on nan => value
    # nan on value => nan
    # nan on nan => Nothing
    # nan on nothing=> Nothing
723

Aurélien Campéas's avatar
Aurélien Campéas committed
724
    # full erasing
725
726
    # numeric
    ts_begin = genserie(datetime(2010, 1, 1), 'D', 4)
727
    tsh.insert(engine, ts_begin, 'ts_full_del', 'test')
728

Aurélien Campéas's avatar
Aurélien Campéas committed
729
    ts_begin.iloc[:] = np.nan
730
    tsh.insert(engine, ts_begin, 'ts_full_del', 'test')
731
732

    ts_end = genserie(datetime(2010, 1, 1), 'D', 4)
733
    tsh.insert(engine, ts_end, 'ts_full_del', 'test')
734
735
736
737

    # string

    ts_begin = genserie(datetime(2010, 1, 1), 'D', 4, ['text'])
738
    tsh.insert(engine, ts_begin, 'ts_full_del_str', 'test')
739
740

    ts_begin.iloc[:] = np.nan
741
    tsh.insert(engine, ts_begin, 'ts_full_del_str', 'test')
742
743

    ts_end = genserie(datetime(2010, 1, 1), 'D', 4, ['text'])
744
    tsh.insert(engine, ts_end, 'ts_full_del_str', 'test')
745

Aurélien Campéas's avatar
Aurélien Campéas committed
746

747
def test_multi_index(engine, tsh):
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
    appdate_0 = pd.DatetimeIndex(start=datetime(2015, 1, 1),
                                 end=datetime(2015, 1, 2),
                                 freq='D').values
    pubdate_0 = [pd.datetime(2015, 1, 11, 12, 0, 0)] * 2
    insertion_date_0 = [pd.datetime(2015, 1, 11, 12, 30, 0)] * 2

    multi = [
        appdate_0,
        np.array(pubdate_0),
        np.array(insertion_date_0)
    ]

    ts_multi = pd.Series(range(2), index=multi)
    ts_multi.index.rename(['b', 'c', 'a'], inplace=True)

763
    tsh.insert(engine, ts_multi, 'ts_multi_simple', 'test')
764

765
    ts = tsh.get(engine, 'ts_multi_simple')
766
767
768
    assert_df("""
                                                    ts_multi_simple
a                   b          c                                   
769
770
2015-01-11 12:30:00 2015-01-01 2015-01-11 12:00:00              0.0
                    2015-01-02 2015-01-11 12:00:00              1.0
771
772
""", pd.DataFrame(ts))

773
    diff = tsh.insert(engine, ts_multi, 'ts_multi_simple', 'test')
774
775
776
777
778
    assert diff is None

    ts_multi_2 = pd.Series([0, 2], index=multi)
    ts_multi_2.index.rename(['b', 'c', 'a'], inplace=True)

779
780
    tsh.insert(engine, ts_multi_2, 'ts_multi_simple', 'test')
    ts = tsh.get(engine, 'ts_multi_simple')
781
782
783
784

    assert_df("""
                                                    ts_multi_simple
a                   b          c                                   
785
786
2015-01-11 12:30:00 2015-01-01 2015-01-11 12:00:00              0.0
                    2015-01-02 2015-01-11 12:00:00              2.0
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
""", pd.DataFrame(ts))

    # bigger ts
    appdate_0 = pd.DatetimeIndex(start=datetime(2015, 1, 1),
                                 end=datetime(2015, 1, 4),
                                 freq='D').values
    pubdate_0 = [pd.datetime(2015, 1, 11, 12, 0, 0)] * 4
    insertion_date_0 = [pd.datetime(2015, 1, 11, 12, 30, 0)] * 4

    appdate_1 = pd.DatetimeIndex(start=datetime(2015, 1, 1),
                                 end=datetime(2015, 1, 4),
                                 freq='D').values

    pubdate_1 = [pd.datetime(2015, 1, 21, 12, 0, 0)] * 4
    insertion_date_1 = [pd.datetime(2015, 1, 21, 12, 30, 0)] * 4

    multi = [
        np.concatenate([appdate_0, appdate_1]),
        np.array(pubdate_0 + pubdate_1),
        np.array(insertion_date_0 + insertion_date_1)
    ]

    ts_multi = pd.Series(range(8), index=multi)
    ts_multi.index.rename(['a', 'c', 'b'], inplace=True)

812
813
    tsh.insert(engine, ts_multi, 'ts_multi', 'test')
    ts = tsh.get(engine, 'ts_multi')
814
815
816
817

    assert_df("""
                                                    ts_multi
a          b                   c                            
818
819
820
821
822
823
824
825
2015-01-01 2015-01-11 12:30:00 2015-01-11 12:00:00       0.0
           2015-01-21 12:30:00 2015-01-21 12:00:00       4.0
2015-01-02 2015-01-11 12:30:00 2015-01-11 12:00:00       1.0
           2015-01-21 12:30:00 2015-01-21 12:00:00       5.0
2015-01-03 2015-01-11 12:30:00 2015-01-11 12:00:00       2.0
           2015-01-21 12:30:00 2015-01-21 12:00:00       6.0
2015-01-04 2015-01-11 12:30:00 2015-01-11 12:00:00       3.0
           2015-01-21 12:30:00 2015-01-21 12:00:00       7.0
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
    """, pd.DataFrame(ts.sort_index()))
    # Note: the columnns are returned according to the alphabetic order

    appdate_2 = pd.DatetimeIndex(start=datetime(2015, 1, 1),
                                 end=datetime(2015, 1, 4),
                                 freq='D').values
    pubdate_2 = [pd.datetime(2015, 1, 31, 12, 0, 0)] * 4
    insertion_date_2 = [pd.datetime(2015, 1, 31, 12, 30, 0)] * 4

    multi_2 = [
        np.concatenate([appdate_1, appdate_2]),
        np.array(pubdate_1 + pubdate_2),
        np.array(insertion_date_1 + insertion_date_2)
    ]

    ts_multi_2 = pd.Series([4] * 8, index=multi_2)
    ts_multi_2.index.rename(['a', 'c', 'b'], inplace=True)

    # A second ts is inserted with some index in common with the first
    # one: appdate_1, pubdate_1,and insertion_date_1. The value is set
    # at 4, which matches the previous value of the "2015-01-01" point.

848
    diff = tsh.insert(engine, ts_multi_2, 'ts_multi', 'test')
849
850
851
852
853
854
855
856
857
858
859
860
861
862
    assert_df("""
                                                    ts_multi
a          b                   c                            
2015-01-01 2015-01-31 12:30:00 2015-01-31 12:00:00       4.0
2015-01-02 2015-01-21 12:30:00 2015-01-21 12:00:00       4.0
           2015-01-31 12:30:00 2015-01-31 12:00:00       4.0
2015-01-03 2015-01-21 12:30:00 2015-01-21 12:00:00       4.0
           2015-01-31 12:30:00 2015-01-31 12:00:00       4.0
2015-01-04 2015-01-21 12:30:00 2015-01-21 12:00:00       4.0
           2015-01-31 12:30:00 2015-01-31 12:00:00       4.0
        """, pd.DataFrame(diff.sort_index()))
    # the differential skips a value for "2015-01-01"
    # which does not change from the previous ts

863
    ts = tsh.get(engine, 'ts_multi')
864
865
866
    assert_df("""
                                                    ts_multi
a          b                   c                            
867
868
869
870
871
872
873
874
875
876
877
878
2015-01-01 2015-01-11 12:30:00 2015-01-11 12:00:00       0.0
           2015-01-21 12:30:00 2015-01-21 12:00:00       4.0
           2015-01-31 12:30:00 2015-01-31 12:00:00       4.0
2015-01-02 2015-01-11 12:30:00 2015-01-11 12:00:00       1.0
           2015-01-21 12:30:00 2015-01-21 12:00:00       4.0
           2015-01-31 12:30:00 2015-01-31 12:00:00       4.0
2015-01-03 2015-01-11 12:30:00 2015-01-11 12:00:00       2.0
           2015-01-21 12:30:00 2015-01-21 12:00:00       4.0
           2015-01-31 12:30:00 2015-01-31 12:00:00       4.0
2015-01-04 2015-01-11 12:30:00 2015-01-11 12:00:00       3.0
           2015-01-21 12:30:00 2015-01-21 12:00:00       4.0
           2015-01-31 12:30:00 2015-01-31 12:00:00       4.0
879
880
881
        """, pd.DataFrame(ts.sort_index()))

    # the result ts have now 3 values for each point in 'a'
882
883


884
def test_get_history(engine, tsh):
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
    for numserie in (1, 2, 3):
        with engine.connect() as cn:
            with tsh.newchangeset(cn, 'aurelien.campeas@pythonian.fr',
                                  _insertion_date=datetime(2017, 2, numserie)):
                tsh.insert(cn, genserie(datetime(2017, 1, 1), 'D', numserie), 'smallserie')

    ts = tsh.get(engine, 'smallserie')
    assert_df("""
2017-01-01    0.0
2017-01-02    1.0
2017-01-03    2.0
""", ts)

    logs = tsh.log(engine, names=['smallserie'])
    assert [
        {'author': 'aurelien.campeas@pythonian.fr',
901
         'meta': {},
902
903
904
905
         'date': datetime(2017, 2, 1, 0, 0),
         'names': ['smallserie']
        },
        {'author': 'aurelien.campeas@pythonian.fr',
906
         'meta': {},
907
908
909
910
         'date': datetime(2017, 2, 2, 0, 0),
         'names': ['smallserie']
        },
        {'author': 'aurelien.campeas@pythonian.fr',
911
         'meta': {},
912
913
914
915
916
917
         'date': datetime(2017, 2, 3, 0, 0),
         'names': ['smallserie']
        }
    ] == [{k: v for k, v in log.items() if k != 'rev'}
          for log in logs]
    histts = tsh.get_history(engine, 'smallserie')
918
    assert histts.name == 'smallserie'
919
920
921
922
923
924
925
926
927
928
929

    assert_df("""
insertion_date  value_date
2017-02-01      2017-01-01    0.0
2017-02-02      2017-01-01    0.0
                2017-01-02    1.0
2017-02-03      2017-01-01    0.0
                2017-01-02    1.0
                2017-01-03    2.0
""", histts)

930
931
932
933
934
935
936
937
    diffs = tsh.get_history(engine, 'smallserie', diffmode=True)
    assert_df("""
insertion_date  value_date
2017-02-01      2017-01-01    0.0
2017-02-02      2017-01-02    1.0
2017-02-03      2017-01-03    2.0
""", diffs)

938
    for idate in histts.index.get_level_values('insertion_date').unique():
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
        with engine.connect() as cn:
            with tsh.newchangeset(cn, 'aurelien.campeas@pythonian.f',
                                  _insertion_date=idate):
                tsh.insert(cn, histts[idate], 'smallserie2')

    # this is perfectly round-tripable
    assert (tsh.get(engine, 'smallserie2') == ts).all()
    assert (tsh.get_history(engine, 'smallserie2') == histts).all()

    # get history ranges
    tsa = tsh.get_history(engine, 'smallserie',
                          from_insertion_date=datetime(2017, 2, 2))
    assert_df("""
insertion_date  value_date
2017-02-02      2017-01-01    0.0
                2017-01-02    1.0
2017-02-03      2017-01-01    0.0
                2017-01-02    1.0
                2017-01-03    2.0
""", tsa)

    tsb = tsh.get_history(engine, 'smallserie',
                          to_insertion_date=datetime(2017, 2, 2))
    assert_df("""
insertion_date  value_date
2017-02-01      2017-01-01    0.0
2017-02-02      2017-01-01    0.0
                2017-01-02    1.0
""", tsb)

    tsc = tsh.get_history(engine, 'smallserie',
                          from_insertion_date=datetime(2017, 2, 2),
                          to_insertion_date=datetime(2017, 2, 2))
    assert_df("""
insertion_date  value_date
2017-02-02      2017-01-01    0.0
                2017-01-02    1.0
""", tsc)

978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
    tsc = tsh.get_history(engine, 'smallserie',
                          from_insertion_date=datetime(2017, 2, 4),
                          to_insertion_date=datetime(2017, 2, 4))
    assert tsc is None

    tsc = tsh.get_history(engine, 'smallserie',
                          from_insertion_date=datetime(2016, 2, 1),
                          to_insertion_date=datetime(2017, 2, 2))
    assert_df("""
insertion_date  value_date
2017-02-01      2017-01-01    0.0
2017-02-02      2017-01-01    0.0
                2017-01-02    1.0
""", tsc)

    tsc = tsh.get_history(engine, 'smallserie',
                          from_insertion_date=datetime(2016, 2, 1),
                          to_insertion_date=datetime(2016, 12, 31))
    assert tsc is None

998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
    # restrictions on value dates
    tsc = tsh.get_history(engine, 'smallserie',
                          from_value_date=datetime(2017, 1, 1),
                          to_value_date=datetime(2017, 1, 2))
    assert_df("""
insertion_date  value_date
2017-02-01      2017-01-01    0.0
2017-02-02      2017-01-01    0.0
                2017-01-02    1.0
2017-02-03      2017-01-01    0.0
                2017-01-02    1.0
""", tsc)

1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
    diffs = tsh.get_history(engine, 'smallserie',
                            diffmode=True,
                            from_value_date=datetime(2017, 1, 1),
                            to_value_date=datetime(2017, 1, 2))
    assert_df("""
insertion_date  value_date
2017-02-01      2017-01-01    0.0
2017-02-02      2017-01-02    1.0
""", diffs)

1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
    tsc = tsh.get_history(engine, 'smallserie',
                          from_value_date=datetime(2017, 1, 2))
    assert_df("""
insertion_date  value_date
2017-02-02      2017-01-02    1.0
2017-02-03      2017-01-02    1.0
                2017-01-03    2.0
""", tsc)

    tsc = tsh.get_history(engine, 'smallserie',
                          to_value_date=datetime(2017, 1, 2))
    assert_df("""
insertion_date  value_date
2017-02-01      2017-01-01    0.0
2017-02-02      2017-01-01    0.0
                2017-01-02    1.0
2017-02-03      2017-01-01    0.0
                2017-01-02    1.0
""", tsc)

1041

1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
def test_nr_gethistory(engine, tsh):
    s0 = pd.Series([-1, 0, 0, -1],
                   index=pd.DatetimeIndex(start=datetime(2016, 12, 29),
                                          end=datetime(2017, 1, 1),
                                          freq='D'))
    tsh.insert(engine, s0, 'foo', 'zogzog')

    s1 = pd.Series([1, 0, 0, 1],
                   index=pd.DatetimeIndex(start=datetime(2017, 1, 1),
                                          end=datetime(2017, 1, 4),
                                          freq='D'))
    idate = datetime(2016, 1, 1)
    for i in range(5):
        with engine.connect() as cn:
            with tsh.newchangeset(cn, 'aurelien.campeas@pythonian.f',
                                  _insertion_date=idate + timedelta(days=i)):
                tsh.insert(cn, s1 * i, 'foo')

    df = tsh.get_history(engine, 'foo',
                         datetime(2016, 1, 3),
                         datetime(2016, 1, 4),
                         datetime(2017, 1, 1),
                         datetime(2017, 1, 4))

    assert_df("""
insertion_date  value_date
2016-01-03      2017-01-01    2.0
1069
1070
                2017-01-02    0.0
                2017-01-03    0.0
1071
1072
                2017-01-04    2.0
2016-01-04      2017-01-01    3.0
1073
1074
                2017-01-02    0.0
                2017-01-03    0.0
1075
1076
1077
1078
                2017-01-04    3.0
""", df)


1079
def test_add_na(engine, tsh):
1080
1081
1082
1083
1084
    # a serie of NaNs won't be insert in base
    # in case of first insertion
    ts_nan = genserie(datetime(2010, 1, 1), 'D', 5)
    ts_nan[[True] * len(ts_nan)] = np.nan

1085
    diff = tsh.insert(engine, ts_nan, 'ts_add_na', 'test')
1086
    assert diff is None
1087
    result = tsh.get(engine, 'ts_add_na')
1088
1089
1090
1091
    assert result is None

    # in case of insertion in existing data
    ts_begin = genserie(datetime(2010, 1, 1), 'D', 5)
1092
    tsh.insert(engine, ts_begin, 'ts_add_na', 'test')
1093
1094
1095
1096
1097

    ts_nan = genserie(datetime(2010, 1, 6), 'D', 5)
    ts_nan[[True] * len(ts_nan)] = np.nan
    ts_nan = pd.concat([ts_begin, ts_nan])

1098
    diff = tsh.insert(engine, ts_nan, 'ts_add_na', 'test')
1099
1100
    assert diff is None

1101
    result = tsh.get(engine, 'ts_add_na')
1102
    assert len(result) == 5
1103
1104


1105
def test_dtype_mismatch(engine, tsh):
1106
    tsh.insert(engine,