-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.py
1965 lines (1650 loc) · 66.1 KB
/
script.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
# Jason Tran, William Martin, Caleb Choy, Jared Weinblatt, Sean James, Austin Luo, Noe Durocher
# I pledge my honor that I have abided by the Stevens Honor System
import sys
import re
import pandas as pd
import unittest
import numpy as np
from datetime import datetime
from datetime import date
from datetime import timedelta
from dateutil.relativedelta import relativedelta
from prettytable import PrettyTable
import operator
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
#---------------------### VARIABLES & CONSTANTS ###---------------------#
#List of valid tags that should have Y for valid
VALID_TAGS = [
'INDI',
'NAME',
'SEX',
'BIRT',
'DEAT',
'FAMC',
'FAMS',
'FAM',
'MARR',
'HUSB',
'WIFE',
'CHIL',
'DIV',
'DATE',
'HEAD',
'TRLR',
'NOTE'
]
#List of tags where the tag is the third token in a line
THIRD_TOKEN_TAGS =[
'INDI',
'FAM'
]
Colors = {
"red": "\033[91m{}\033[00m",
"red bold": "\033[1m\033[91m{}\033[00m",
"green": "\033[92m{}\033[00m",
"yellow": "\033[93m{}\033[00m",
"yellow bold": "\033[1m\033[93m{}\033[00m",
"light purple": "\033[94m{}\033[00m",
"purple": "\033[95m{}\033[00m",
"cyan": "\033[96m{}\033[00m",
"cyan bold":"\033[1m\033[96m{}\033[00m",
"light gray": "\033[97m{}\033[00m",
"black": "\033[98m{}\033[00m"
}
indiList = [] #will hold all individuals
famList = [] #will hold all families
indiLineInfo ={}
famLineInfo ={}
#---------------------### HELPER FUNCTIONS ###---------------------#
#Colors!!
def printColor(color, str, end="\n"):
print(Colors[color].format(str), end=end)
#Given an id and an attribute of intrest, returns the value of the attribute desired ex lookup("birthday", "I343628")
def lookup(attr, id):
for indi in indiList: #loop over all individuals
if id == indi['ID']: #if we find id
return indi[attr] #return the individual's data that we desire
#Given an id,an attribute of intrest, and a list returns the value of the attribute desired ex lookup("birthday", "I343628", indiList)
def modified_lookup(attr, id, inputlist):
for indi in inputlist: #loop over all individuals
if id == indi['ID']: #if we find id
return indi.get(attr, None) #return the individual's data that we desire
#Calculate age difference fot get_parents_not_too_old() function
def get_age_difference(parent_age, child_age):
age = parent_age - child_age
return age
def getIndiLine(pid, tag):
try:
stri = str((indiLineInfo.get(pid)).get(tag))
except:
stri = ""
return stri
def getFamLine(pid, tag):
try:
stri = str(famLineInfo[pid][tag])
except:
stri = ""
return stri
#Return the difference of two dates in months
def diffMonth(d1, d2):
if d1 is None or d2 is None:
return None
date1 = dateToCompare(d1)
date2 = dateToCompare(d2)
return (date1.year - date2.year) * 12 + date1.month - date2.month
#Calculate age given two dates. If death not supplied assume not dead
def calculateAge(born, death=False):
if born is None:
return 0
born = datetime.strptime(born, "%d %b %Y")
endDate = datetime.strptime(death, "%d %b %Y") if death else date.today() #if death is set, set end date as death. Otherwise, set end date as today
return endDate.year - born.year - ((endDate.month, endDate.day) < (born.month, born.day))
#Returns true if date1 is before or equals date2,
def check_dateOrder(date1, date2):
if (date1 is None):
if(date2 is None):
return True
return False
date1 = datetime.strptime(date1, "%d %b %Y")
date2 = datetime.strptime(date2, "%d %b %Y") if date2 else None
if date2 is None or date1 <= date2:
return True
else:
return False
#Convert to datetime object
def dateToCompare(date):
return datetime.strptime(date, "%d %b %Y")
#check age difference for a parent and a child
def get_age_difference(parent_age, child_age):
try:
return parent_age - child_age
except:
pass
#function to replace the children id(s) with their actual data
def replace_id_with_children_data(children_arr):
new_arr = []
for i in range(len(children_arr)):
new_arr.append(look_for_child_by(children_arr[i]))
return new_arr
# return all family ids to a record
def find_family_ids(fam_list):
records = []
for record in fam_list:
records.append(record['ID'])
return records
#return all married people to a record
def get_married_list(famList):
fam_records = []
fam_id_records = find_family_ids(famList)
for id in fam_id_records:
husband_name = modified_lookup('Husband Name', id, famList)
wife_name = modified_lookup('Wife Name', id, famList)
divorce_date = modified_lookup('Divorced', id, famList)
if (divorce_date is None):
fam_records.append([husband_name,wife_name])
return fam_records
#---------------------### USER STORY FUNCTIONS ###---------------------#
#US12: Parents not too old | ND Sprint 1
#(father not 80 yrs older, and mother not 60 yrs older than child) ****start
#function to print father, mother and children data and display if parents are too hold to be a child's parent
def get_parents_not_too_old(famList):
family = []
table_arr = []
father_age_limit = 80
mother_age_limit = 60
#loop to retrieve father, mother and children data from family record
for i in range(len(famList)):
#append specific data from famList to the family list
family.append({'Husband_ID':famList[i]['Husband ID'], 'Wife_ID':famList[i]['Wife ID'],
'Husband Name':famList[i]['Husband Name'], 'Wife Name':famList[i]['Wife Name'],
'Husband Age': lookup('Age', famList[i]['Husband ID']), 'Wife Age': lookup('Age', famList[i]['Wife ID']),
'Children': replace_id_with_children_data(famList[i]['Children'])})
# loop to build list to hold father, mother and children data
for j in range(len(family)):
for k in range(len(family[j]['Children'])):
#check to see if father is not 80 yrs older than children or if mother is not 60 yrs older than children
father = 0 if family[j]['Husband Age'] is None else family[j]['Husband Age']
mother = 0 if family[j]['Wife Age'] is None else family[j]['Wife Age']
child = 0 if family[j]['Children'][k]['Age'] is None else family[j]['Children'][k]['Age']
father_too_old = 'Yes' if get_age_difference(father, child) > father_age_limit else "No"
mother_too_old = 'Yes' if get_age_difference(mother, child) > mother_age_limit else "No"
#check to see if parents are older than children then if so append to table_arr
if(father > child):
table_arr.append([family[j]['Husband Name'],"Father", family[j]['Husband Age'],
family[j]['Children'][k]['Name'], family[j]['Children'][k]['Gender'], family[j]['Children'][k]['Age'], father_too_old])
if(mother > child):
table_arr.append([family[j]['Wife Name'], "Mother", family[j]['Wife Age'],
family[j]['Children'][k]['Name'], family[j]['Children'][k]['Gender'], family[j]['Children'][k]['Age'], mother_too_old])
#bring list to a prettytable structure
x = PrettyTable()
x.field_names = ['Parent Name', 'Relationship', 'Parent Age', 'Child Name', 'Sex', 'Child Age', 'Parents too old']
for n in range(len(table_arr)):
x.add_row([table_arr[n][0], table_arr[n][1], table_arr[n][2],
table_arr[n][3], table_arr[n][4], table_arr[n][5], table_arr[n][6]])
print(x)
return 1, x
#US20: Aunts and uncles | CC Sprint 3
# Aunts and uncles should not marry their nieces or nephews
def veifyNoAuntUncleMarrNieceNephew(indiList, famList):
count = 0
for family in famList:
husbID = family["Husband ID"]
wifeID = family["Wife ID"]
husbGParents = getGrandparents(husbID, indiList, famList)
wifeGParents = getGrandparents(wifeID, indiList, famList)
husbParents = getParents(husbID, indiList, famList)
wifeParents = getParents(wifeID, indiList, famList)
auntMarriages = set(husbGParents) & set(wifeParents)
uncleMarriages = set(wifeGParents) & set(husbParents)
uncleMarriages.discard(None)
auntMarriages.discard(None)
if len(uncleMarriages) > 0: #if we have elements remaining in the intersection, this means an unlce married his niece
count += 1
printColor("yellow bold", "WARN: FAM: US20: {}: Uncle {} {} married his niece {} {}"\
.format(family["ID"], husbID, family["Husband Name"], wifeID, family["Wife Name"]))
if len(auntMarriages) > 0: #if we have elements remaining in the intersection, this means an aunt married her nephew
count += 1
printColor("yellow bold", "WARN: FAM: US20: {}: Aunt {} {} married hew nephew {} {}"\
.format(family["ID"], wifeID, family["Wife Name"], husbID, family["Husband Name"]))
if count == 0:
printColor("green", "INFO: GEN: US20: No Aunts marrying their Nephews or Uncles marrying their Nieces")
return count
#US21 | JT Sprint 2
# Checks the family list to ensure that all wives are female and all husbands are male
def check_gender_roles(famList):
for family in famList:
husbandGender = lookup("Gender" ,family["Husband ID"])
wifeGender = lookup("Gender" ,family["Wife ID"])
if husbandGender != "M":
print("WARN: IND: US21: L{}: All husbands must be males".format(getIndiLine(family["Husband ID"], "SEX")))
return False
if wifeGender != "F":
print("WARN: IND: US21: L{}: All wives must be female".format(getIndiLine(family["Wife ID"], "SEX")))
return False
print("INFO: GEN: US21: Gender roles are OK")
return True
#US25 | JT Sprint 2
# Checks the family list to ensure that each family only has one child with the same name and birthday
def check_unique_child(famList):
for family in famList:
childrenList = {}
for child in family["Children"]:
name = lookup("Name", child)
birthday = lookup("Birthday", child)
if name in childrenList and birthday == childrenList[name]:
print("WARN: FAM: US25: No more than one child with the same name and birth date should appear in a family")
return False
else:
childrenList[name] = birthday
print("INFO: GEN: US25: All Unique first names in families")
return True
#US26: Corresponding entries | CC Sprint 3
#All family roles (spouse, child) specified in an individual record should have corresponding entries in the corresponding family records.
#Likewise, all individual roles (spouse, child) specified in family records should have corresponding entries in the corresponding individual's records.
#I.e. the information in the individual and family records should be consistent.
def verifyCorrespondingEntries_ind(indiList, famList):
count = 0
for indi in indiList:
indiID = indi["ID"]
childOfFamID = indi.get("Child", None)
spouseOfFamIDArray = indi.get("Spouse", None)
#now check that indiID appears in the child array of the family ID
if (childOfFamID is not None) and (indiID not in modified_lookup("Children", childOfFamID, famList)):
count += 1
printColor("yellow bold", "WARN: FAM: US26: L{}: {}: {} {}'s individual record says they are a child in {}, but no corresponding family entry found"\
.format(getIndiLine(indiID, "FAMC"), childOfFamID, indiID, indi["Name"], childOfFamID))
for spouseOfFamID in spouseOfFamIDArray:
if (spouseOfFamID is not None) and (indiID not in (modified_lookup("Husband ID", spouseOfFamID, famList), modified_lookup("Wife ID", spouseOfFamID, famList))):
count += 1
printColor("yellow bold", "WARN: FAM: US26: L{}: {}: {} {}'s individual record says they are a spouse in {}, but no corresponding family entry found"\
.format(getIndiLine(indiID, "FAMC"), spouseOfFamID, indiID, indi["Name"], spouseOfFamID))
return count
def verifyCorrespondingEntries_fam(indiList, famList):
count = 0
for fam in famList:
famID = fam["ID"]
husbID = fam["Husband ID"]
wifeID = fam["Wife ID"]
childrenIDArray = fam["Children"]
husbFamilies = modified_lookup("Spouse", husbID, indiList)
if husbID != "" and (husbFamilies is None or famID not in husbFamilies):
count += 1
printColor("yellow bold", "WARN: IND: US26: {}: family record {} has {} {} as husband, but his inividual record does not have corresponding spouse entry"\
.format(husbID, famID, husbID, fam["Husband Name"]))
wifeFamilies = modified_lookup("Spouse", wifeID, indiList)
if wifeID != "" and (wifeFamilies is None or famID not in wifeFamilies):
count += 1
printColor("yellow bold", "WARN: IND: US26: {}: family record {} has {} {} as wife, but her inividual record does not have corresponding spouse entry"\
.format(wifeID, famID, wifeID, fam["Wife Name"]))
for childID in childrenIDArray:
if famID != modified_lookup("Child", childID, indiList):
count += 1
printColor("yellow bold", "WARN: IND: US26: {}: family record {} has {} as child, but their inividual record does not have corresponding child entry"\
.format(childID, famID, childID))
return count
def verifyCorrespondingEntries(indiList, famList):
return {
"ind": verifyCorrespondingEntries_ind(indiList, famList),
"fam": verifyCorrespondingEntries_fam(indiList, famList)
}
#US29: Deceased list | ND Sprint 1
def get_deceased_records(indList):
decease_list = []
records = ""
for record in indList:
if (record['Alive'] == False):
records = [record['ID'],record['Name'], record['Gender'], record['Birthday'], record['Age'],
record['Death']]
decease_list.append(records)
#df = pd.DataFrame(decease_list, columns = ['ID', 'Name', 'Gender', 'Birthday', 'Age', 'Death'])
#print(df)
return 1, decease_list
#***************************************************************************end
def print_age_qualification(indiList):
#person = get_person_record()
#one_hundred_and_thirty = get_exactly_130_years_of_age()
each_person = []
isQualified = ""
for i in indiList:
one_hundred_thirty = 130
if (type(i['Age']) == int) :
name_arr = i['Name']
birth_day = i['Birthday']
name = ""
for j in range(len(name_arr)):
name += name_arr[j].strip("/")
if(i['Age'] <= one_hundred_thirty):
isQualified = 'Yes'
each_person.append([name, birth_day, isQualified])
else:
isQualified = 'No'
each_person.append([name, birth_day, isQualified])
return each_person
def print_data(indiList):
person_record = print_age_qualification(indiList)
n_arr = []
b_arr = []
q_arr = []
person_data = {}
for i in range(len(person_record)):
n_arr.append(person_record[i][0])
b_arr.append(person_record[i][1])
q_arr.append(person_record[i][2])
person_data['Name'] = n_arr
person_data['Birth Date'] = b_arr
person_data['Qualified'] = q_arr
df = pd.DataFrame(person_data, columns = ['Name', 'Birth Date','Qualified'])
return df
#Austin Luo
def marriageAge(indiList, famList):
for family in famList:
husbandID = family['Husband ID']
wifeID = family['Wife ID']
husbandBirthday = modified_lookup('Birthday', husbandID, indiList)
wifeBirthday = modified_lookup('Birthday', wifeID, indiList)
marriageDate = family['Married']
husbandMarriageAge = calculateAge(husbandBirthday, marriageDate)
wifeMarriageAge = calculateAge(wifeBirthday, marriageDate)
if husbandMarriageAge < 14:
print("WARN: IND: US10: " + husbandID + ": Husband married before 14 years old, married at " + str(husbandMarriageAge) + "yrs old")
if wifeMarriageAge < 14:
print("WARN: IND: US10: " + wifeID + ": Wife married before 14 years old, married at " + str(wifeMarriageAge) + "yrs old")
def realBirthday(indiList, famList):
count = 0
for family in famList:
if 'Children' in family.keys():
for childID in family["Children"]:
childBirthday = modified_lookup("Birthday", childID, indiList)
wifeDeath = modified_lookup("Death", family['Wife ID'], indiList)
husbDeath = modified_lookup("Death", family['Husband ID'], indiList)
if (check_dateOrder(childBirthday, wifeDeath) == False):
print("ERRO: IND: US09: " + childID + ": Child was born on " + childBirthday + ", mother died on " + wifeDeath)
count += 1
monthDifference = diffMonth(husbDeath, childBirthday)
if((monthDifference is not None) and monthDifference < -9):
print("WARN: IND: US09: " + childID + ": Child was born on " + childBirthday + ", father died on " + husbDeath)
count += 1
return count
#US15 AL
def multipleSiblings(indiList, famList):
for family in famList:
if 'Children' in family.keys():
if len(family['Children']) >= 15:
print("WARN: FAM: US15: {} doesn't have less than 15 children".format(family["ID"]))
return False
print("INFO: FAM: US15: ALl families have fewer than 15 children")
return True
#US14 AL
def multipleBirths(indiList, famList):
for family in famList:
if 'Children' in family.keys():
if len(family["Children"]) > 5:
birthdays =[]
for childID in family["Children"]:
birthdays.append(modified_lookup("Birthday", childID, indiList))
birthdays = list(dict.fromkeys(birthdays))
if len(birthdays) <= (len(family["Children"]) / 6):
print("WARN: FAM: US14: More than 5 Children in {} were born on the same day".format(family["Children"]))
return False
print("INFO: FAM: US14: No more than 5 children born at the same time")
return True
# if len(famList[individual]['Children']) >= 5:
# for firstchild in famList[individual]['Children']:
# counter = 1
# date = indiList[firstchild]['Birthday']
# for secondchild in famList [individual]['Children']:
# if(indiList[secondchild]['Birthday'] == date):
# counter += 1
# if(counter > 5):
# return False
# return True
def correctName(indiList):
for individual in indiList:
if 'Name'.isdigit():
contains_digit = False
return True
def largestName(famList):
for family in famList:
for famID in family:
familyIdentification = modified_lookup('ID', famList)
"""
###########################
for family in famList:
childrenList = {}
for child in family["Children"]:
identification = lookup("ID", child)
if identification > 5:
print("No more than five children are allowed to be born at once.")
return False
print("All couples have five children or less.")
return True
"""
def tooOld(indiList):
for individual in indiList:
individualAge = lookup("Age", individual)
if individualAge > 130:
print("No individuals allowed to be older 130 years old.")
return False
return True
# def multipleBirths(famList):
# for family in famList:
# childrenList = {}
# childrenID = lookup("Children", family)
# for children in family["Children"]:
# print(childrenID)
# return True
# return False
# print("This perseon does not have a child.")
#Checks date argument to see if that date is not after today's date
def validDate(arguments):
current_date = date.today()
try:
date_arg = datetime.strptime(arguments, "%d %b %Y").date()
except ValueError:
raise ValueError("Incorrect data format, should be YYYY-MM-DD")
if date_arg > current_date:
return False
return True
#function to find the children data
def getChildren_and_age(id):
name = lookup('Name', id)
age = lookup('Age', id)
gender = lookup('Gender', id)
birthday = lookup('Birthday', id)
return {'Name': name, 'Age':age, 'Gender':gender, 'Birthday':birthday}
#function to replace the children id(s) with their actual data
def replace_id_with_children_data(children_arr):
new_arr = []
for i in range(len(children_arr)):
new_arr.append(getChildren_and_age(children_arr[i]))
return new_arr
#US03: Birth before death | CC Sprint 1:
#Verify that all death dates are after birth dates. Returns 0 if no offenders. If offenders detected, returns the number of them
def verifyBirthDeathDateOrder(indiList):
for individual in indiList:
if 'Child' in individual.keys():
indiID = individual['ID']
childBirthday = lookup("Birthday", indiID)
childFamilyID = lookup("Child", indiID)
warningList = []
for indi in indiList: #loop over all individuals
if (check_dateOrder(indi.get('Birthday', None), indi.get('Death', None)) == False): #using check_dateOrder, if Birthday is after Death append the offender to warningList
warningList.append(indi)
if len(warningList) < 1: #if warningList is empty
printColor("green", "INFO: GEN: US03: No Deaths before Births")
else:
def verifyBirthDeathDateOrderPrint(x):
printColor("yellow bold", "ERRO: IND: US03: L{}: {}: {} died on {}, before their birthday of {}"\
.format(getIndiLine(x['ID'], "DEAT"), x['ID'], x['Name'], x['Death'], x['Birthday']))
pd.DataFrame(warningList).apply(lambda x: verifyBirthDeathDateOrderPrint(x), axis=1)
return len(warningList)
#US04: Marriage before divorce | CC Sprint 1
#Verify that all divorce dates are after marriage dates. Returns 0 if no offenders. If offenders detected, returns the number of them
def verifyMarriageDivorceOrder(famList):
warningList = []
for f in famList: #loop over all families
if (check_dateOrder(f.get('Married', None), f.get('Divorced', None)) == False): #using check_dateOrder, if Married is after Divorced append the offender to warningList
warningList.append(f)
if len(warningList) < 1: #if warningList is empty
printColor("green", "INFO: GEN: US04: No Divorces before Marriages")
else:
def verifyMarriageDivorceOrderPrint(x):
printColor("yellow bold", "ERRO: FAM: US04: L{}: {}: {} and {} divorced on {}, before their marriage on {}"\
.format(getFamLine(x['ID'], "DIV"), x['ID'], x['Husband Name'], x['Wife Name'], x['Divorced'], x['Married']))
pd.DataFrame(warningList).apply(lambda x: verifyMarriageDivorceOrderPrint(x), axis=1)
return len(warningList)
#US13 | SJ Sprint 1
#Sibling Spacing birth dates of siblings must be 8 months or more apart from each other or less than 2 days for twins
def SiblingSpacing(indiDF, famList, indiList):
birthday = ''
for fam in famList:
childrenList = fam['Children']
birthdays = list()
for id in childrenList:
birthday = modified_lookup("Birthday", id,indiList)
birthdays.append(birthday)
for index in range(0, len(birthdays) - 1):
birthday_1 = birthdays[index]
birthday_2 = birthdays[index + 1]
date_1 = datetime.strptime(birthday_1, "%d %b %Y").date()
date_2 = datetime.strptime(birthday_2, "%d %b %Y").date()
# print("DEBUG")
# print(date_1)
# print(date_2)
dayDifference = abs((date_1 - date_2).days)
if dayDifference > 240 or dayDifference < 2:
print('INFO: IND: US13: Day difference = ' + str(dayDifference))
else:
print('ERR: IND: US13: Siblings must be born at least 8 months apart or less than 2 days for twins')
return False
return True
#US16 | SJ Sprint 1
def maleLastNames(indiDF, famList):
lastNamesEqual = False
childrenName = '' #init child / husb name and childrenID
husbandName = ''
childrenID = ''
malesList = indiDF[(indiDF['Gender'] == 'M')] #created list of males
for fam in famList:
# print(fam)
husbandName = fam['Husband Name'] #for each family stor the husb name
lastName = re.findall("\/(.*)\/", str(husbandName))
if len(lastName) > 0:
lastName = lastName[0]
else:
lastName = ""
childrenID = fam['Children'] #get the childrenid
# print('children ids', str(childrenID))
# print('husband Last name' , str(lastName))
for id in childrenID: #for all ids in childrenID
#print('\n', str(id))
childFirstName = ""
childLastName = ""
malesID = malesList['ID'].to_list()
if (id in malesID): #if child is in male list
childrenName_bad = str(malesList.loc[malesList['ID'] == id, ['Name']])
x = re.findall("\s*(\S*) \/(.*)\/", childrenName_bad)[0]
childFirstName = x[0]
childLastName = x[1]
#print('Childs name is ' + childFirstName + ' ' + childLastName)
else:
#print ('Gender is ' + indiDF.loc[indiDF['ID'] == id, ['Gender'] ] + ' So do not check ')
#Because it is a female so it does not matter what the last name is
lastNamesEqual =True
if(lastName == childLastName or childLastName == ""): #if the childs name contains the husbands name its true otherwise false
#print('Family name is ' + lastName)
lastNamesEqual = True
else:
print("WARN: IND: US16: All male members of family should have same last name. Last name: {}. Child's name: {} {}".format(lastName, childFirstName, childLastName))
return False
return lastNamesEqual
#US13 SJ Sibling Spacing birth dates of siblings must be 8 months or more apart from each other or less than 2 days for twins
def SiblingSpacing(indiDF, famList):
birthday = ''
SiblingSpacing = True
for fam in famList:
i = 0
childrenList = fam['Children']
birthdays = list()
for id in childrenList:
birthday = lookup("Birthday", id)
birthdays.append(birthday)
# print('birthday ' + str(birthdays))
for index in range(0, len(birthdays)):
birthday_1 = birthdays[index]
for j in range(index + 1, len(birthdays)):
birthday_2 = birthdays[j]
date_1 = datetime.strptime(birthday_1, "%d %b %Y").date()
date_2 = datetime.strptime(birthday_2, "%d %b %Y").date()
dayDifference = abs((date_1 - date_2).days)
if dayDifference > 240 or dayDifference < 2:
print('INFO: IND: US13: Day difference = ' + str(dayDifference))
else:
print('ERR: IND: US13: Siblings must be born at least 8 months apart or less than 2 days for twins')
return False
return SiblingSpacing
#US19: First cousins should not marry | CC Sprint 2
#First cousins should not marry one another
def getParents(indiID, indiList, famList):
familyID = modified_lookup("Child", indiID, indiList)
fatherID = modified_lookup("Husband ID", familyID, famList)
motherID = modified_lookup("Wife ID", familyID, famList)
return [fatherID, motherID]
def getGrandparents(indiID, indiList, famList):
familyID = modified_lookup("Child", indiID, indiList)
parentsID_arr = getParents(indiID, indiList, famList)
grandParentsID_arr = []
for parentID in parentsID_arr:
grandParentsID_arr.extend(getParents(parentID, indiList, famList))
return grandParentsID_arr
# fatherID = modified_lookup("Husband ID", familyID, famList)
# motherID = modified_lookup("Wife ID", familyID, famList)
# fatherFamilyID = modified_lookup("Child", fatherID, indiList)
# motherFamilyID = modified_lookup("Child", motherID, indiList)
# fatherFatherID = modified_lookup("Husband ID", fatherFamilyID, famList)
# fatherMotherID = modified_lookup("Wife ID", fatherFamilyID, famList)
# motherFatherID = modified_lookup("Husband ID", motherFamilyID, famList)
# motherMotherID = modified_lookup("Wife ID", motherFamilyID, famList)
# return [fatherFatherID, fatherMotherID, motherFatherID, motherMotherID]
def verifyNoFirstCousinMarr(indiList, famList):
warningList = []
for family in famList:
husbID = family["Husband ID"]
wifeID = family["Wife ID"]
husbGParents = getGrandparents(husbID, indiList, famList)
wifeGParents = getGrandparents(wifeID, indiList, famList)
for i in husbGParents:
if i is not None and i in wifeGParents:
warningList.append(family)
break
if len(warningList) < 1:
printColor("green", "INFO: GEN: US19: No First Cousins married")
else:
printColor("yellow bold", "WARN: FAM: US19: First Cousins Marriages found:")
print(pd.DataFrame(warningList), end="\n\n")
return len(warningList)
# Sean James - US22 all IDs must be unique
def uniqueID(indiList):
id_List = list()
for i in range(len(indiList)):
id = indiList[i]['ID']
id_List.append(id)
id_Set = set(id_List)
unique_ids = len(id_Set) == len(id_List)
return unique_ids
# Sean James US23 all names and Birthdates must be different
def uniqueNameAndBirthday(indiList):
name_List = list()
birthdate_List = list()
for i in range(len(indiList)):
name = indiList[i]['Name']
name_List.append(name)
birthdate = indiList[i]['Birthday']
birthdate_List.append(birthdate)
name_Set = set(name_List)
birthdate_Set = set(birthdate_List)
if (len(name_List) == len(name_Set)) and (len(birthdate_List) == len(birthdate_Set)):
unique_NameAndBirthday = True
else:
unique_NameAndBirthday = False
return unique_NameAndBirthday
# JW US07 - Checks age argument to ensure it is less than 150 years
def validAge(indiList):
for person in indiList:
age=person["Age"]
if age >= 150:
print("ERROR: INDIVIDUAL: US07: L" + getIndiLine(person["ID"], "BIRT") + " " + str(person["ID"]) + ": More than 150 years old - Birth Date: " + str(person["Birthday"]))
return False
return True
#US02 | JT Sprint 1
def birthBeforeMarriage(famList):
for family in famList:
for childId in family["Children"]:
marriageDate = dateToCompare(family['Married'])
if childId != "NaN":
birthday = dateToCompare(lookup("Birthday", childId))
if marriageDate > birthday:
return False
return True
#US8 | JW Sprint 1
def birthBeforeMarriage2(famList, individualListName):
for family in famList:
for childId in family["Children"]:
marriageDate = dateToCompare(family['Married'])
if childId != "NaN":
birthday = dateToCompare(modified_lookup("Birthday", childId, individualListName))
if family.get("Divorced") != None:
divorceDate = dateToCompare(family['Divorced'])
divorceNineMonths = divorceDate + relativedelta(months=+9)
if birthday > divorceNineMonths:
print("ERROR: FAMILY: US46:", family["ID"] + ": Child " + str(childId) + " born " + str(birthday) + " after divorce on " + str(divorceDate))
return False
if marriageDate > birthday:
print("ERROR: FAMILY: US46:", family["ID"] + ": Child " + str(childId) + " born " + str(birthday) + " before marriage on " + str(marriageDate))
return False
return True
#US11: No bigamy | CC Sprint 2:
#Marriage should not occur during marriage to another spouse
def getAnomaliesBigamy(remarriedSet, famDF, indiDF, maritalPosition):
#Set up variables
anomalyBigamyDF = pd.DataFrame()
if maritalPosition == "Husband":
maritalPositionID = "Husband ID"
spousePositionID = "Wife ID"
spouseName = "Wife Name"
else:
maritalPositionID = "Wife ID"
spousePositionID = "Husband ID"
spouseName = "Husband Name"
#loop over every personID in the remarried Set
for personID in remarriedSet:
marrInfoDF = famDF.loc[ #Make a dataframe based on the famDF, but here all rows are related to personID
(famDF[maritalPositionID] == personID), #This line specifies the query
['ID', 'Husband ID', 'Husband Name', 'Wife ID', 'Wife Name', 'Married', 'Divorced'] #This line specifies what columns our output contains. Is independent from the above line
]
marrInfoDF.dropna(subset=['Husband Name', 'Wife Name'], inplace = True)
print(marrInfoDF)
#Merge data from indiDF into our newly created marrInfoDF table. We are intrested in getting Death dates from indiDF
marrInfoDF = marrInfoDF.merge(indiDF[["ID", "Death"]], how="left", left_on=spousePositionID, right_on="ID")
marrInfoDF.drop('ID_y', axis=1, inplace=True) #drop the ID column as we dont need it
marrInfoDF.rename(columns={"Death": "Spouse Death", "ID_x": "ID"}, inplace=True) #Rename death to spouse death just to be more descriptive
#Convert all dates to datetime so we can easily compare dates
marrInfoDF['Married'] = pd.to_datetime(marrInfoDF['Married'], format='%d %b %Y', errors='coerce')
marrInfoDF['Divorced'] = pd.to_datetime(marrInfoDF['Divorced'], format='%d %b %Y', errors='coerce')
marrInfoDF['Spouse Death'] = pd.to_datetime(marrInfoDF['Spouse Death'], format='%d %b %Y', errors='coerce')
#sort the table by Married, so we get the earliest marriage first
marrInfoDF.sort_values(by=['Married'], inplace=True)
marrInfoDF.reset_index(inplace=True, drop="Index")
#Create four new columns that hold the previous row's info using .shift(), which copies Divorced, Spouse Death, Huband Name, and Husband ID from row 1 to row 2, from row 2 to row 3, etc.
#This way when we look at one row, we also have information of the previous row in our own row.
marrInfoDF[['prev_divorced', 'prev_spouseDeath', 'prev_spouseName', 'prev_spouseID']] = marrInfoDF[['Divorced', 'Spouse Death', spouseName, spousePositionID]].shift()
#set the previous marriage end date to the previous divorce. If that doesnt exist, set it to the previous spouse's death date. if that didnt exist it will be NaT
marrInfoDF['prev_marriageEndDate'] = np.where(pd.isnull(marrInfoDF['prev_divorced']), marrInfoDF['prev_spouseDeath'], marrInfoDF['prev_divorced'])
marrInfoDF = marrInfoDF.iloc[1:] #We don't care about the first row, because we can't tell if a bigamy is happening if we just have one entry for married
#make a table for entries that have bigamy. This is the case when the Married date comes before the previous marriage's end date
offendingEntriesDF = marrInfoDF.loc[
~(marrInfoDF['Married'] > marrInfoDF['prev_marriageEndDate']) #~ means not. We have to do "not greater than" because any date < NaT returns false. But we want true so we flip
]
#Concatonate our findings to a table that has all bigamies
anomalyBigamyDF = pd.concat([anomalyBigamyDF, offendingEntriesDF])
return anomalyBigamyDF
#returns the number of offenders who commit bigamy. Prints any offenders.
def verifyBigamy(famList, famDF, indiDF):
husbID_list = famDF["Husband ID"].to_list() #list of all husband IDs, duplicates included
wifeID_list = famDF["Wife ID"].to_list()
remarriedSet_male = set([])
remarriedSet_female = set([])
#identify all posssible cases
for families in famList: #loop through all families
husbID = families["Husband ID"] #grab this row's husband ID
wifeID = families["Wife ID"]
if(husbID_list.count(husbID) > 1): #Check if this row's husb ID appears more than once in the husbID list
remarriedSet_male.add(husbID)
if(wifeID_list.count(wifeID) > 1): #Check if this row's wife ID appears more than once in the wifeID list
remarriedSet_female.add(wifeID)
maleBigamyDF = getAnomaliesBigamy(remarriedSet_male, famDF, indiDF, "Husband")
femaleBigamyDF = getAnomaliesBigamy(remarriedSet_female, famDF, indiDF, "Wife")
numOffenders = len(maleBigamyDF) + len(femaleBigamyDF)
if numOffenders > 0: #Print offending entries if either dataframe has entries
def maleBigamyPrint(x):
printColor("yellow bold", "WARN: FAM: US11: {}: Husband {} married {} on {}, but he was still married to {}"\
.format(x["ID"], x["Husband Name"], x["Wife Name"], x["Married"].date(), x["prev_spouseName"]), end="")
if pd.isnull(x['prev_marriageEndDate']):
printColor("yellow bold", ".")
else:
printColor("yellow bold", " until {}.".format(x["prev_marriageEndDate"].date()))
def femaleBigamyPrint(x):
printColor("yellow bold", "WARN: FAM: US11: {}: Wife {} married {} on {}, but she was still married to {}"\
.format(x["ID"], x["Wife Name"], x["Husband Name"], x["Married"].date(), x["prev_spouseName"]), end="")
if pd.isnull(x['prev_marriageEndDate']):
printColor("yellow bold", ".")
else:
printColor("yellow bold", " until {}.".format(x["prev_marriageEndDate"].date()))
maleBigamyDF.apply(lambda x: maleBigamyPrint(x), axis=1)
femaleBigamyDF.apply(lambda x: femaleBigamyPrint(x), axis=1)
else:
printColor("green", "INFO: GEN: US11: No Bigamy")
return numOffenders
#US44: Grandparents | CC Sprint 4
#Grandparents should not marry their grandchildren
def verifyNoGrandparentMarrGranchild(indiList, famList):
count = 0
for family in famList:
husbID = family["Husband ID"]
wifeID = family["Wife ID"]
husbGParents = getGrandparents(husbID, indiList, famList)
wifeGParents = getGrandparents(wifeID, indiList, famList)
if husbID in wifeGParents:
count += 1
printColor("yellow bold", "WARN: FAM: US44: {}: Grandpa {} {} married his granddaughter {} {}"\
.format(family["ID"], husbID, family["Husband Name"], wifeID, family["Wife Name"]))
if wifeID in husbGParents:
count += 1
printColor("yellow bold", "WARN: FAM: US44: {}: Grandma {} {} married her grandson {} {}"\
.format(family["ID"], wifeID, family["Wife Name"], husbID, family["Husband Name"]))
if count == 0:
printColor("green", "INFO: GEN: US44: No Grandparents marrying their Grandchildren")
return count
#US45 JW - Siblings < 35 year age difference
def siblingAgeDiff(famList, individualListName):
for family in famList:
if len(family["Children"]) > 1:
dlow = dateToCompare(modified_lookup("Birthday", family["Children"][0],individualListName))
dhigh = dateToCompare(modified_lookup("Birthday", family["Children"][0], individualListName))
lowid=family["Children"][0]
highid=birthday=family["Children"][0]
for childId in family["Children"]:
birthday = dateToCompare(modified_lookup("Birthday", childId, individualListName))
if birthday < dlow:
dlow=birthday
lowid=childId
if birthday > dhigh:
dhigh=birthday
highid=childId
ageDiff = dhigh.year - dlow.year - ((dhigh.month, dhigh.day) < (dlow.month, dlow.day))
if ageDiff >= 35:
print("ERROR: FAMILY: US45:", family["ID"] + ": Age difference between older sibling (" + str(lowid) + ") and younger sibling ("+ str(highid)+ ") is", ageDiff, "which is not less than 35 years")
return False
return True
#US46 JW - Children>15 yr age difference parents
def childParentAgeDiff(famList, individualListName):
for family in famList:
dhus = dateToCompare(modified_lookup("Birthday", family["Husband ID"],individualListName))
dwife = dateToCompare(modified_lookup("Birthday", family["Wife ID"], individualListName))
dlow = dhus
parid = family["Husband ID"]
if dwife > dhus:
parid = family["Wife ID"]
dlow = dwife
for childId in family["Children"]:
birthday = dateToCompare(modified_lookup("Birthday", childId, individualListName))
ageDiff = birthday.year - dlow.year - ((birthday.month, birthday.day) < (dlow.month, dlow.day))
if ageDiff <= 15:
print("ERROR: FAMILY: US46:", family["ID"] + ": Age difference between child (" + str(childId) + ") and parent ("+ str(parid)+ ") is", ageDiff, "which is not more than 15 years")
return False
return True
#US51 JW - List family with most members
def largestFamily(famList):
if(len(famList)==0): return "N/A"
largest_size = 0
largest_id = ""
for family in famList:
size=2+len(family["Children"])
if(size>largest_size):
largest_size=size
largest_id = family["ID"]
print("STATS: FAMILY: US51: The largest family is " + str(largest_id) + " with size " + str(largest_size) + " (living or deceased)")