-
Notifications
You must be signed in to change notification settings - Fork 889
/
Copy pathtest_es.py
2147 lines (1757 loc) · 67.6 KB
/
test_es.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
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
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import copy
import logging
import pickle
import re
from datetime import datetime
from unittest.mock import patch
import numpy as np
import pandas as pd
import pytest
from woodwork.logical_types import (
URL,
Boolean,
Categorical,
CountryCode,
Datetime,
Double,
EmailAddress,
Integer,
LatLong,
NaturalLanguage,
Ordinal,
PostalCode,
SubRegionCode,
)
from featuretools import Relationship
from featuretools.demo import load_retail
from featuretools.entityset import EntitySet
from featuretools.entityset.entityset import LTI_COLUMN_NAME, WW_SCHEMA_KEY
from featuretools.tests.testing_utils import get_df_tags
def test_normalize_time_index_as_additional_column(es):
error_text = "Not moving signup_date as it is the base time index column. Perhaps, move the column to the copy_columns."
with pytest.raises(ValueError, match=error_text):
assert "signup_date" in es["customers"].columns
es.normalize_dataframe(
base_dataframe_name="customers",
new_dataframe_name="cancellations",
index="cancel_reason",
make_time_index="signup_date",
additional_columns=["signup_date"],
copy_columns=[],
)
def test_normalize_time_index_as_copy_column(es):
assert "signup_date" in es["customers"].columns
es.normalize_dataframe(
base_dataframe_name="customers",
new_dataframe_name="cancellations",
index="cancel_reason",
make_time_index="signup_date",
additional_columns=[],
copy_columns=["signup_date"],
)
assert "signup_date" in es["customers"].columns
assert es["customers"].ww.time_index == "signup_date"
assert "signup_date" in es["cancellations"].columns
assert es["cancellations"].ww.time_index == "signup_date"
def test_normalize_time_index_as_copy_column_new_time_index(es):
assert "signup_date" in es["customers"].columns
es.normalize_dataframe(
base_dataframe_name="customers",
new_dataframe_name="cancellations",
index="cancel_reason",
make_time_index=True,
additional_columns=[],
copy_columns=["signup_date"],
)
assert "signup_date" in es["customers"].columns
assert es["customers"].ww.time_index == "signup_date"
assert "first_customers_time" in es["cancellations"].columns
assert "signup_date" not in es["cancellations"].columns
assert es["cancellations"].ww.time_index == "first_customers_time"
def test_normalize_time_index_as_copy_column_no_time_index(es):
assert "signup_date" in es["customers"].columns
es.normalize_dataframe(
base_dataframe_name="customers",
new_dataframe_name="cancellations",
index="cancel_reason",
make_time_index=False,
additional_columns=[],
copy_columns=["signup_date"],
)
assert "signup_date" in es["customers"].columns
assert es["customers"].ww.time_index == "signup_date"
assert "signup_date" in es["cancellations"].columns
assert es["cancellations"].ww.time_index is None
def test_cannot_re_add_relationships_that_already_exists(es):
warn_text = "Not adding duplicate relationship: " + str(es.relationships[0])
before_len = len(es.relationships)
rel = es.relationships[0]
with pytest.warns(UserWarning, match=warn_text):
es.add_relationship(relationship=rel)
with pytest.warns(UserWarning, match=warn_text):
es.add_relationship(
rel._parent_dataframe_name,
rel._parent_column_name,
rel._child_dataframe_name,
rel._child_column_name,
)
after_len = len(es.relationships)
assert before_len == after_len
def test_add_relationships_convert_type(es):
for r in es.relationships:
parent_df = es[r.parent_dataframe.ww.name]
child_df = es[r.child_dataframe.ww.name]
assert parent_df.ww.index == r._parent_column_name
assert "foreign_key" in r.child_column.ww.semantic_tags
assert str(parent_df[r._parent_column_name].dtype) == str(
child_df[r._child_column_name].dtype,
)
def test_add_relationship_diff_param_logical_types(es):
ordinal_1 = Ordinal(order=[0, 1, 2, 3, 4, 5, 6])
ordinal_2 = Ordinal(order=[0, 1, 2, 3, 4, 5])
es["sessions"].ww.set_types(logical_types={"id": ordinal_1})
log_2_df = es["log"].copy()
log_logical_types = {
"id": Integer,
"session_id": ordinal_2,
"product_id": Categorical(),
"datetime": Datetime,
"value": Double,
"value_2": Double,
"latlong": LatLong,
"latlong2": LatLong,
"zipcode": PostalCode,
"countrycode": CountryCode,
"subregioncode": SubRegionCode,
"value_many_nans": Double,
"priority_level": Ordinal(order=[0, 1, 2]),
"purchased": Boolean,
"comments": NaturalLanguage,
"url": URL,
"email_address": EmailAddress,
}
log_semantic_tags = {"session_id": "foreign_key", "product_id": "foreign_key"}
assert set(log_logical_types) == set(log_2_df.columns)
es.add_dataframe(
dataframe_name="log2",
dataframe=log_2_df,
index="id",
logical_types=log_logical_types,
semantic_tags=log_semantic_tags,
time_index="datetime",
)
assert "log2" in es.dataframe_dict
assert es["log2"].ww.schema is not None
assert isinstance(es["log2"].ww.logical_types["session_id"], Ordinal)
assert isinstance(es["sessions"].ww.logical_types["id"], Ordinal)
assert (
es["sessions"].ww.logical_types["id"]
!= es["log2"].ww.logical_types["session_id"]
)
warning_text = "Changing child logical type to match parent."
with pytest.warns(UserWarning, match=warning_text):
es.add_relationship("sessions", "id", "log2", "session_id")
assert isinstance(es["log2"].ww.logical_types["product_id"], Categorical)
assert isinstance(es["products"].ww.logical_types["id"], Categorical)
def test_add_relationship_different_logical_types_same_dtype(es):
log_2_df = es["log"].copy()
log_logical_types = {
"id": Integer,
"session_id": Integer,
"product_id": CountryCode,
"datetime": Datetime,
"value": Double,
"value_2": Double,
"latlong": LatLong,
"latlong2": LatLong,
"zipcode": PostalCode,
"countrycode": CountryCode,
"subregioncode": SubRegionCode,
"value_many_nans": Double,
"priority_level": Ordinal(order=[0, 1, 2]),
"purchased": Boolean,
"comments": NaturalLanguage,
"url": URL,
"email_address": EmailAddress,
}
log_semantic_tags = {"session_id": "foreign_key", "product_id": "foreign_key"}
assert set(log_logical_types) == set(log_2_df.columns)
es.add_dataframe(
dataframe_name="log2",
dataframe=log_2_df,
index="id",
logical_types=log_logical_types,
semantic_tags=log_semantic_tags,
time_index="datetime",
)
assert "log2" in es.dataframe_dict
assert es["log2"].ww.schema is not None
assert isinstance(es["log2"].ww.logical_types["product_id"], CountryCode)
assert isinstance(es["products"].ww.logical_types["id"], Categorical)
warning_text = "Logical type CountryCode for child column product_id does not match parent column id logical type Categorical. Changing child logical type to match parent."
with pytest.warns(UserWarning, match=warning_text):
es.add_relationship("products", "id", "log2", "product_id")
assert isinstance(es["log2"].ww.logical_types["product_id"], Categorical)
assert isinstance(es["products"].ww.logical_types["id"], Categorical)
assert "foreign_key" in es["log2"].ww.semantic_tags["product_id"]
def test_add_relationship_different_compatible_dtypes(es):
log_2_df = es["log"].copy()
log_logical_types = {
"id": Integer,
"session_id": Datetime,
"product_id": Categorical,
"datetime": Datetime,
"value": Double,
"value_2": Double,
"latlong": LatLong,
"latlong2": LatLong,
"zipcode": PostalCode,
"countrycode": CountryCode,
"subregioncode": SubRegionCode,
"value_many_nans": Double,
"priority_level": Ordinal(order=[0, 1, 2]),
"purchased": Boolean,
"comments": NaturalLanguage,
"url": URL,
"email_address": EmailAddress,
}
log_semantic_tags = {"session_id": "foreign_key", "product_id": "foreign_key"}
assert set(log_logical_types) == set(log_2_df.columns)
es.add_dataframe(
dataframe_name="log2",
dataframe=log_2_df,
index="id",
logical_types=log_logical_types,
semantic_tags=log_semantic_tags,
time_index="datetime",
)
assert "log2" in es.dataframe_dict
assert es["log2"].ww.schema is not None
assert isinstance(es["log2"].ww.logical_types["session_id"], Datetime)
assert isinstance(es["customers"].ww.logical_types["id"], Integer)
warning_text = "Logical type Datetime for child column session_id does not match parent column id logical type Integer. Changing child logical type to match parent."
with pytest.warns(UserWarning, match=warning_text):
es.add_relationship("customers", "id", "log2", "session_id")
assert isinstance(es["log2"].ww.logical_types["session_id"], Integer)
assert isinstance(es["customers"].ww.logical_types["id"], Integer)
def test_add_relationship_errors_child_v_index(es):
new_df = es["log"].ww.copy()
new_df.ww._schema.name = "log2"
es.add_dataframe(dataframe=new_df)
to_match = "Unable to add relationship because child column 'id' in 'log2' is also its index"
with pytest.raises(ValueError, match=to_match):
es.add_relationship("log", "id", "log2", "id")
def test_add_relationship_empty_child_convert_dtype(es):
relationship = Relationship(es, "sessions", "id", "log", "session_id")
empty_log_df = pd.DataFrame(columns=es["log"].columns)
es.add_dataframe(empty_log_df, "log")
assert len(es["log"]) == 0
# session_id will be Unknown logical type with dtype string
assert es["log"]["session_id"].dtype == "string"
es.relationships.remove(relationship)
assert relationship not in es.relationships
es.add_relationship(relationship=relationship)
assert es["log"]["session_id"].dtype == "int64"
def test_add_relationship_with_relationship_object(es):
relationship = Relationship(es, "sessions", "id", "log", "session_id")
es.add_relationship(relationship=relationship)
assert relationship in es.relationships
def test_add_relationships_with_relationship_object(es):
relationships = [Relationship(es, "sessions", "id", "log", "session_id")]
es.add_relationships(relationships)
assert relationships[0] in es.relationships
def test_add_relationship_error(es):
relationship = Relationship(es, "sessions", "id", "log", "session_id")
error_message = (
"Cannot specify dataframe and column name values and also supply a Relationship"
)
with pytest.raises(ValueError, match=error_message):
es.add_relationship(parent_dataframe_name="sessions", relationship=relationship)
def test_query_by_values_returns_rows_in_given_order():
data = pd.DataFrame(
{
"id": [1, 2, 3, 4, 5],
"value": ["a", "c", "b", "a", "a"],
"time": [1000, 2000, 3000, 4000, 5000],
},
)
es = EntitySet()
es = es.add_dataframe(
dataframe=data,
dataframe_name="test",
index="id",
time_index="time",
logical_types={"value": "Categorical"},
)
query = es.query_by_values("test", ["b", "a"], column_name="value")
assert np.array_equal(query["id"], [1, 3, 4, 5])
def test_query_by_values_secondary_time_index(es):
end = np.datetime64(datetime(2011, 10, 1))
all_instances = [0, 1, 2]
result = es.query_by_values("customers", all_instances, time_last=end)
for col in ["cancel_date", "cancel_reason"]:
nulls = result.loc[all_instances][col].isnull() == [False, True, True]
assert nulls.all(), "Some instance has data it shouldn't for column %s" % col
def test_query_by_id(es):
df = es.query_by_values("log", instance_vals=[0])
assert df["id"].values[0] == 0
def test_query_by_single_value(es):
df = es.query_by_values("log", instance_vals=0)
assert df["id"].values[0] == 0
def test_query_by_df(es):
instance_df = pd.DataFrame({"id": [1, 3], "vals": [0, 1]})
df = es.query_by_values("log", instance_vals=instance_df)
assert np.array_equal(df["id"], [1, 3])
def test_query_by_id_with_time(es):
df = es.query_by_values(
dataframe_name="log",
instance_vals=[0, 1, 2, 3, 4],
time_last=datetime(2011, 4, 9, 10, 30, 2 * 6),
)
assert list(df["id"].values) == [0, 1, 2]
def test_query_by_column_with_time(es):
df = es.query_by_values(
dataframe_name="log",
instance_vals=[0, 1, 2],
column_name="session_id",
time_last=datetime(2011, 4, 9, 10, 50, 0),
)
true_values = [i * 5 for i in range(5)] + [i * 1 for i in range(4)] + [0]
assert list(df["id"].values) == list(range(10))
assert list(df["value"].values) == true_values
def test_query_by_column_with_no_lti_and_training_window(es):
match = (
"Using training_window but last_time_index is not set for dataframe customers"
)
with pytest.warns(UserWarning, match=match):
df = es.query_by_values(
dataframe_name="customers",
instance_vals=[0, 1, 2],
column_name="cohort",
time_last=datetime(2011, 4, 11),
training_window="3d",
)
assert list(df["id"].values) == [1]
assert list(df["age"].values) == [25]
def test_query_by_column_with_lti_and_training_window(es):
es.add_last_time_indexes()
df = es.query_by_values(
dataframe_name="customers",
instance_vals=[0, 1, 2],
column_name="cohort",
time_last=datetime(2011, 4, 11),
training_window="3d",
)
df = df.reset_index(drop=True).sort_values("id")
assert list(df["id"].values) == [0, 1, 2]
assert list(df["age"].values) == [33, 25, 56]
def test_query_by_indexed_column(es):
df = es.query_by_values(
dataframe_name="log",
instance_vals=["taco clock"],
column_name="product_id",
)
df = df.reset_index(drop=True).sort_values("id")
assert list(df["id"].values) == [15, 16]
@pytest.fixture
def df():
return pd.DataFrame({"id": [0, 1, 2], "category": ["a", "b", "c"]})
def test_check_columns_and_dataframe(df):
# matches
logical_types = {"id": Integer, "category": Categorical}
es = EntitySet(id="test")
es.add_dataframe(
df,
dataframe_name="test_dataframe",
index="id",
logical_types=logical_types,
)
assert isinstance(
es.dataframe_dict["test_dataframe"].ww.logical_types["category"],
Categorical,
)
assert es.dataframe_dict["test_dataframe"].ww.semantic_tags["category"] == {
"category",
}
def test_make_index_any_location(df):
logical_types = {"id": Integer, "category": Categorical}
es = EntitySet(id="test")
es.add_dataframe(
dataframe_name="test_dataframe",
index="id1",
make_index=True,
logical_types=logical_types,
dataframe=df,
)
assert es.dataframe_dict["test_dataframe"].columns[0] == "id1"
assert es.dataframe_dict["test_dataframe"].ww.index == "id1"
def test_replace_dataframe_and_create_index(es):
df = pd.DataFrame({"ints": [3, 4, 5], "category": ["a", "b", "a"]})
final_df = df.copy()
final_df["id"] = [0, 1, 2]
needs_idx_df = df.copy()
logical_types = {"ints": Integer, "category": Categorical}
es.add_dataframe(
dataframe=df,
dataframe_name="test_df",
index="id",
make_index=True,
logical_types=logical_types,
)
assert es["test_df"].ww.index == "id"
# DataFrame that needs the index column added
assert "id" not in needs_idx_df.columns
es.replace_dataframe("test_df", needs_idx_df)
assert es["test_df"].ww.index == "id"
df = es["test_df"].sort_values(by="id")
assert all(df["id"] == final_df["id"])
assert all(df["ints"] == final_df["ints"])
def test_replace_dataframe_created_index_present(es):
df = pd.DataFrame({"ints": [3, 4, 5], "category": ["a", "b", "a"]})
logical_types = {"ints": Integer, "category": Categorical}
es.add_dataframe(
dataframe=df,
dataframe_name="test_df",
index="id",
make_index=True,
logical_types=logical_types,
)
# DataFrame that already has the index column
has_idx_df = es["test_df"].replace({0: 100})
has_idx_df.set_index("id", drop=False, inplace=True)
assert "id" in has_idx_df.columns
es.replace_dataframe("test_df", has_idx_df)
assert es["test_df"].ww.index == "id"
df = es["test_df"].sort_values(by="ints")
assert all(df["id"] == [100, 1, 2])
def test_index_any_location(df):
logical_types = {"id": Integer, "category": Categorical}
es = EntitySet(id="test")
es.add_dataframe(
dataframe_name="test_dataframe",
index="category",
logical_types=logical_types,
dataframe=df,
)
assert es.dataframe_dict["test_dataframe"].columns[1] == "category"
assert es.dataframe_dict["test_dataframe"].ww.index == "category"
def test_extra_column_type(df):
# more columns
logical_types = {"id": Integer, "category": Categorical, "category2": Categorical}
error_text = re.escape(
"logical_types contains columns that are not present in dataframe: ['category2']",
)
with pytest.raises(LookupError, match=error_text):
es = EntitySet(id="test")
es.add_dataframe(
dataframe_name="test_dataframe",
index="id",
logical_types=logical_types,
dataframe=df,
)
def test_add_parent_not_index_column(es):
error_text = "Parent column 'language' is not the index of dataframe régions"
with pytest.raises(AttributeError, match=error_text):
es.add_relationship("régions", "language", "customers", "région_id")
@pytest.fixture
def df2():
return pd.DataFrame({"category": [1, 2, 3], "category2": ["1", "2", "3"]})
def test_none_index(df2):
es = EntitySet(id="test")
copy_df = df2.copy()
copy_df.ww.init(name="test_dataframe")
error_msg = "Cannot add Woodwork DataFrame to EntitySet without index"
with pytest.raises(ValueError, match=error_msg):
es.add_dataframe(dataframe=copy_df)
warn_text = (
"Using first column as index. To change this, specify the index parameter"
)
with pytest.warns(UserWarning, match=warn_text):
es.add_dataframe(
dataframe_name="test_dataframe",
logical_types={"category": "Categorical"},
dataframe=df2,
)
assert es["test_dataframe"].ww.index == "category"
assert es["test_dataframe"].ww.semantic_tags["category"] == {"index"}
assert isinstance(es["test_dataframe"].ww.logical_types["category"], Categorical)
@pytest.fixture
def df3():
return pd.DataFrame({"category": [1, 2, 3]})
def test_unknown_index(df3):
warn_text = "index id not found in dataframe, creating new integer column"
es = EntitySet(id="test")
with pytest.warns(UserWarning, match=warn_text):
es.add_dataframe(
dataframe_name="test_dataframe",
dataframe=df3,
index="id",
logical_types={"category": "Categorical"},
)
assert es["test_dataframe"].ww.index == "id"
assert list(es["test_dataframe"]["id"]) == list(
range(3),
)
def test_doesnt_remake_index(df):
logical_types = {"id": "Integer", "category": "Categorical"}
error_text = "Cannot make index: column with name id already present"
with pytest.raises(RuntimeError, match=error_text):
es = EntitySet(id="test")
es.add_dataframe(
dataframe_name="test_dataframe",
index="id",
make_index=True,
dataframe=df,
logical_types=logical_types,
)
def test_bad_time_index_column(df3):
logical_types = {"category": "Categorical"}
error_text = "Specified time index column `time` not found in dataframe"
with pytest.raises(LookupError, match=error_text):
es = EntitySet(id="test")
es.add_dataframe(
dataframe_name="test_dataframe",
dataframe=df3,
index="category",
time_index="time",
logical_types=logical_types,
)
@pytest.fixture
def df4():
df = pd.DataFrame(
{
"id": [0, 1, 2],
"category": ["a", "b", "a"],
"category_int": [1, 2, 3],
"ints": ["1", "2", "3"],
"floats": ["1", "2", "3.0"],
},
)
df["category_int"] = df["category_int"].astype("category")
return df
def test_converts_dtype_on_init(df4):
logical_types = {"id": Integer, "ints": Integer, "floats": Double}
es = EntitySet(id="test")
df4.ww.init(name="test_dataframe", index="id", logical_types=logical_types)
es.add_dataframe(dataframe=df4)
df = es["test_dataframe"]
assert df["ints"].dtype.name == "int64"
assert df["floats"].dtype.name == "float64"
# this is infer from pandas dtype
df = es["test_dataframe"]
assert isinstance(df.ww.logical_types["category_int"], Categorical)
def test_converts_dtype_after_init(df4):
category_dtype = "category"
df4["category"] = df4["category"].astype(category_dtype)
es = EntitySet(id="test")
es.add_dataframe(
dataframe_name="test_dataframe",
index="id",
dataframe=df4,
logical_types=None,
)
df = es["test_dataframe"]
df.ww.set_types(logical_types={"ints": "Integer"})
assert isinstance(df.ww.logical_types["ints"], Integer)
assert df["ints"].dtype == "int64"
df.ww.set_types(logical_types={"ints": "Categorical"})
assert isinstance(df.ww.logical_types["ints"], Categorical)
assert df["ints"].dtype == category_dtype
df.ww.set_types(logical_types={"ints": Ordinal(order=[1, 2, 3])})
assert df.ww.logical_types["ints"] == Ordinal(order=[1, 2, 3])
assert df["ints"].dtype == category_dtype
df.ww.set_types(logical_types={"ints": "NaturalLanguage"})
assert isinstance(df.ww.logical_types["ints"], NaturalLanguage)
assert df["ints"].dtype == "string"
@pytest.fixture
def datetime1():
times = pd.date_range("1/1/2011", periods=3, freq="H")
time_strs = times.strftime("%Y-%m-%d")
return pd.DataFrame({"id": [0, 1, 2], "time": time_strs})
def test_converts_datetime(datetime1):
# string converts to datetime correctly
# This test fails without defining logical types.
# Entityset infers time column should be numeric type
logical_types = {"id": Integer, "time": Datetime}
es = EntitySet(id="test")
es.add_dataframe(
dataframe_name="test_dataframe",
index="id",
time_index="time",
logical_types=logical_types,
dataframe=datetime1,
)
pd_col = es["test_dataframe"]["time"]
assert isinstance(es["test_dataframe"].ww.logical_types["time"], Datetime)
assert type(pd_col[0]) == pd.Timestamp
@pytest.fixture
def datetime2():
datetime_format = "%d-%m-%Y"
actual = pd.Timestamp("Jan 2, 2011")
time_strs = [actual.strftime(datetime_format)] * 3
return pd.DataFrame(
{"id": [0, 1, 2], "time_format": time_strs, "time_no_format": time_strs},
)
def test_handles_datetime_format(datetime2):
# check if we load according to the format string
# pass in an ambiguous date
datetime_format = "%d-%m-%Y"
actual = pd.Timestamp("Jan 2, 2011")
logical_types = {
"id": Integer,
"time_format": (Datetime(datetime_format=datetime_format)),
"time_no_format": Datetime,
}
es = EntitySet(id="test")
es.add_dataframe(
dataframe_name="test_dataframe",
index="id",
logical_types=logical_types,
dataframe=datetime2,
)
col_format = es["test_dataframe"]["time_format"]
col_no_format = es["test_dataframe"]["time_no_format"]
# without formatting pandas gets it wrong
assert (col_no_format != actual).all()
# with formatting we correctly get jan2
assert (col_format == actual).all()
def test_handles_datetime_mismatch():
# can't convert arbitrary strings
df = pd.DataFrame({"id": [0, 1, 2], "time": ["a", "b", "tomorrow"]})
logical_types = {"id": Integer, "time": Datetime}
error_text = "Time index column must contain datetime or numeric values"
with pytest.raises(TypeError, match=error_text):
es = EntitySet(id="test")
es.add_dataframe(
df,
dataframe_name="test_dataframe",
index="id",
time_index="time",
logical_types=logical_types,
)
def test_dataframe_init(es):
df = pd.DataFrame(
{
"id": ["0", "1", "2"],
"time": [datetime(2011, 4, 9, 10, 31, 3 * i) for i in range(3)],
"category": ["a", "b", "a"],
"number": [4, 5, 6],
},
)
logical_types = {"id": Categorical, "time": Datetime}
es.add_dataframe(
df.copy(),
dataframe_name="test_dataframe",
index="id",
time_index="time",
logical_types=logical_types,
)
df_shape = df.shape
es_df_shape = es["test_dataframe"].shape
assert es_df_shape == df_shape
assert es["test_dataframe"].ww.index == "id"
assert es["test_dataframe"].ww.time_index == "time"
assert set([v for v in es["test_dataframe"].ww.columns]) == set(df.columns)
assert es["test_dataframe"]["time"].dtype == df["time"].dtype
assert set(es["test_dataframe"]["id"]) == set(df["id"])
@pytest.fixture
def bad_df():
return pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], 3: ["a", "b", "c"]})
def test_nonstr_column_names(bad_df):
es = EntitySet(id="Failure")
error_text = r"All column names must be strings \(Columns \[3\] are not strings\)"
with pytest.raises(ValueError, match=error_text):
es.add_dataframe(dataframe_name="str_cols", dataframe=bad_df, index="a")
bad_df.ww.init()
with pytest.raises(ValueError, match=error_text):
es.add_dataframe(dataframe_name="str_cols", dataframe=bad_df)
def test_sort_time_id():
transactions_df = pd.DataFrame(
{
"id": [1, 2, 3, 4, 5, 6],
"transaction_time": pd.date_range(start="10:00", periods=6, freq="10s")[
::-1
],
},
)
es = EntitySet(
"test",
dataframes={"t": (transactions_df.copy(), "id", "transaction_time")},
)
assert es["t"] is not transactions_df
times = list(es["t"].transaction_time)
assert times == sorted(list(transactions_df.transaction_time))
def test_already_sorted_parameter():
transactions_df = pd.DataFrame(
{
"id": [1, 2, 3, 4, 5, 6],
"transaction_time": [
datetime(2014, 4, 6),
datetime(2012, 4, 8),
datetime(2012, 4, 8),
datetime(2013, 4, 8),
datetime(2015, 4, 8),
datetime(2016, 4, 9),
],
},
)
es = EntitySet(id="test")
es.add_dataframe(
transactions_df.copy(),
dataframe_name="t",
index="id",
time_index="transaction_time",
already_sorted=True,
)
assert es["t"] is not transactions_df
times = list(es["t"].transaction_time)
assert times == list(transactions_df.transaction_time)
def test_concat_not_inplace(es):
first_es = copy.deepcopy(es)
for df in first_es.dataframes:
new_df = df.loc[[], :]
first_es.replace_dataframe(df.ww.name, new_df)
second_es = copy.deepcopy(es)
# set the data description
first_es.metadata
new_es = first_es.concat(second_es)
assert new_es == es
assert new_es._data_description is None
assert first_es._data_description is not None
def test_concat_inplace(es):
first_es = copy.deepcopy(es)
second_es = copy.deepcopy(es)
for df in first_es.dataframes:
new_df = df.loc[[], :]
first_es.replace_dataframe(df.ww.name, new_df)
# set the data description
es.metadata
es.concat(first_es, inplace=True)
assert second_es == es
assert es._data_description is None
def test_concat_with_lti(es):
first_es = copy.deepcopy(es)
for df in first_es.dataframes:
new_df = df.loc[[], :]
first_es.replace_dataframe(df.ww.name, new_df)
second_es = copy.deepcopy(es)
first_es.add_last_time_indexes()
second_es.add_last_time_indexes()
es.add_last_time_indexes()
new_es = first_es.concat(second_es)
assert new_es == es
first_es["stores"].ww.pop(LTI_COLUMN_NAME)
first_es["stores"].ww.metadata.pop("last_time_index")
second_es["stores"].ww.pop(LTI_COLUMN_NAME)
second_es["stores"].ww.metadata.pop("last_time_index")
assert not first_es.__eq__(es, deep=False)
assert not second_es.__eq__(es, deep=False)
assert LTI_COLUMN_NAME not in first_es["stores"]
assert LTI_COLUMN_NAME not in second_es["stores"]
new_es = first_es.concat(second_es)
assert new_es.__eq__(es, deep=True)
# stores will get last time index re-added because it has children that will get lti calculated
assert LTI_COLUMN_NAME in new_es["stores"]
def test_concat_errors(es):
# entitysets are not equal
copy_es = copy.deepcopy(es)
copy_es["customers"].ww.pop("phone_number")
error = (
"Entitysets must have the same dataframes, relationships" ", and column names"
)
with pytest.raises(ValueError, match=error):
es.concat(copy_es)
def test_concat_sort_index_with_time_index(es):
# only pandas dataframes sort on the index and time index
es1 = copy.deepcopy(es)
es1.replace_dataframe(
dataframe_name="customers",
df=es["customers"].loc[[0, 1], :],
already_sorted=True,
)
es2 = copy.deepcopy(es)
es2.replace_dataframe(
dataframe_name="customers",
df=es["customers"].loc[[2], :],
already_sorted=True,
)
combined_es_order_1 = es1.concat(es2)
combined_es_order_2 = es2.concat(es1)
assert list(combined_es_order_1["customers"].index) == [2, 0, 1]
assert list(combined_es_order_2["customers"].index) == [2, 0, 1]
assert combined_es_order_1.__eq__(es, deep=True)
assert combined_es_order_2.__eq__(es, deep=True)
assert combined_es_order_2.__eq__(combined_es_order_1, deep=True)
def test_concat_sort_index_without_time_index(es):
# Sorting is only performed on DataFrames with time indices
es1 = copy.deepcopy(es)
es1.replace_dataframe(
dataframe_name="products",
df=es["products"].iloc[[0, 1, 2], :],
already_sorted=True,
)
es2 = copy.deepcopy(es)
es2.replace_dataframe(
dataframe_name="products",
df=es["products"].iloc[[3, 4, 5], :],
already_sorted=True,
)
combined_es_order_1 = es1.concat(es2)
combined_es_order_2 = es2.concat(es1)
# order matters when we don't sort
assert list(combined_es_order_1["products"].index) == [
"Haribo sugar-free gummy bears",
"car",
"toothpaste",
"brown bag",
"coke zero",
"taco clock",
]
assert list(combined_es_order_2["products"].index) == [
"brown bag",
"coke zero",
"taco clock",