forked from langchain-ai/langchain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sampleText2.txt
2353 lines (1912 loc) · 105 KB
/
sampleText2.txt
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
# ffffffffffffffffffffffffffffffffffffffff
# synthMD.py
# ffffffffffffffffffffffffffffffffffffffff
##=======================================================================================
# Create Synthetic data set
# Read the input statistics and generate rare disease synthetic data
##=======================================================================================
# if this script called directly,
if __name__ == "__main__":
print("------------------- SynthMD")
# ffffffffffffffffffffffffffffffffffffffff
# MDutils.py
# ffffffffffffffffffffffffffffffffffffffff
import os, sys, csv, random, datetime, json
from us import states
from scipy import special
import numpy as np
from faker import Faker
fake = Faker()
#--------------- Read Input Files-----------
def readInputFiles(cfgPath):
"""
Read configuration, rare disease and USA statistics from files:
cfgPath: path to the configuration file
rdsPath: path to the RDs data file
"""
# Read configuration and rare disease data from files:
cfg = json.load(open(cfgPath))
rdsPath = os.path.join(*list(cfg["paths"]["rdsPath"]))
usaRaceDataPath = os.path.join(*list(cfg["paths"]["usaRaceDataPath"]))
usaAgeSexDataFilesPath= os.path.join(*list(cfg["paths"]["usaAgeSexDataFilePath"]))
resultsFolderPath= os.path.join(*list(cfg["paths"]["resultsFolderPath"]))
age_sex_catigories = list(cfg["age_sex_catigories"])
usaAgeSexDataFilesPath = [usaAgeSexDataFilesPath+x for x in age_sex_catigories]
RDsData = json.load(open(rdsPath))
RDsData = RDsData["RDs"]
# USA states populations per race
# 51 x 6
# ID State African-American European-American Others Total
raceData = [row for row in csv.reader(open(usaRaceDataPath), delimiter=",", quotechar='"')]
raceData = [ [int(x[0]), x[1], int(x[2]),int(x[3]),int(x[4]),int(x[5]) ] for x in raceData[1:]]
# reade the prepared data:
usaAgeSexData = [ [ [int(x[0]), x[1]] +[int(y) for y in x[2:] ] for x in [row for row in csv.reader(open(fnm+"_ext.csv"), delimiter=",", quotechar='"')]] for fnm in usaAgeSexDataFilesPath]
usaAgeSexGroupData = [ [ [int(x[0]), x[1]] +[int(y) for y in x[2:] ] for x in [row for row in csv.reader(open(fnm+"_grp.csv"), delimiter=",", quotechar='"')]] for fnm in usaAgeSexDataFilesPath]
# USA states populations per sex and age
# 51 x 96
# ID State Age_0,...,Age_maxAge
usaAgeSexMaleData = [x[2:] for x in usaAgeSexData[0]]
usaAgeSexFemaleData = [x[2:] for x in usaAgeSexData[1]]
usaAgeSexBothData = [x[2:] for x in usaAgeSexData[2]]
usaAgeSexData = [usaAgeSexMaleData, usaAgeSexFemaleData, usaAgeSexBothData]
# 51 x 7
# ID State AgeGroup_0,...,AgeGroup_6
usaStatesAgeSexGroupMale = [x[2:] for x in usaAgeSexGroupData[0]]
usaStatesAgeSexGroupFemale = [x[2:] for x in usaAgeSexGroupData[1]]
usaStatesAgeSexGroupBoth = [x[2:] for x in usaAgeSexGroupData[2]]
usaAgeSexGroupData = [usaStatesAgeSexGroupMale, usaStatesAgeSexGroupFemale, usaStatesAgeSexGroupBoth]
return cfg, RDsData, raceData, usaAgeSexData, usaAgeSexGroupData, [usaAgeSexDataFilesPath, resultsFolderPath]
def getRaceData(raceData, RDsData):
# raceData: ID State African-American European-American Others Total
# African-American (AA), European-American (EA), and others (OA) populations of each state
total_AA_Population = sum([x[2] for x in raceData])
total_EA_Population = sum([x[3] for x in raceData])
total_OA_Population = sum([x[4] for x in raceData])
racePopulations =[total_AA_Population, total_EA_Population, total_OA_Population]
# total race for each state
# raceData: ID State African-American European-American Others Total
AA_PopulationsSt = [x[2] for x in raceData]
EA_PopulationsSt = [x[3] for x in raceData]
OA_PopulationsSt = [x[4] for x in raceData]
racePopulationsSt = [[x,y,z] for x,y,z in zip(AA_PopulationsSt, EA_PopulationsSt, OA_PopulationsSt)]
total_USA_Population_From_Race = sum([sum(x) for x in racePopulationsSt])
# How many patients per race AA,EA,OA
# Notes: SCD affect AA moastly
# CF affects EA moastly
raceWeights = [list(rd['race_percentage']['races'].values()) for rd in RDsData]
actual_number_of_patients = [int(rd['number_of_patients']['nump_value']) for rd in RDsData]
# RD: prevalence
# SCD value is conflicting with total number of patients
# Total number of patients should be around:
# 100000, 32100, 55241
prevalenceLst = [float(rd['prevalence']['pr_value']) for rd in RDsData]
# fix missing values, sometimes prevalence or number of patients are missing
prevalenceLst = [ actual_number_of_patients[i]/total_USA_Population_From_Race if x==0 else x for i,x in enumerate(prevalenceLst)]
prevalenceRaceLst = [ [(prevalence * total_USA_Population_From_Race * rw / 100) / rp for rw,rp in zip(raceWeight, racePopulations)]
for raceWeight, prevalence in zip(raceWeights, prevalenceLst)]
return raceWeights, total_USA_Population_From_Race, prevalenceRaceLst, racePopulations, racePopulationsSt
#--------------------------Functions for generating data--------------------------
# get death rate based on age, race, sex statitics
def getStatesDeathRateDists(s, rdDeathRates, numberOfPatientsForAgeGroups):
# Find dead patients based on age
statePatientsDead = [ round((x/100.0) * y) for x,y in zip(rdDeathRates, numberOfPatientsForAgeGroups) ]
statePatientsAlive = [ x - y for x,y in zip(numberOfPatientsForAgeGroups, statePatientsDead)]
# generate alive/dead distribution for all age groups of the current state
deathRateAgeDists = [ [False]*x + [True]*y for x,y in zip(statePatientsDead, statePatientsAlive)]
return deathRateAgeDists
def getRandomTime(inputDate):
# add random time hours minutes seconds
randomHours = random.randint(0,24)
randomMinutes = random.randint(0,60)
randomSeconds = random.randint(0,60)
randomHours = str(randomHours) if randomHours>9 else "0" + str(randomHours)
randomMinutes = str(randomMinutes) if randomMinutes>9 else "0" + str(randomMinutes)
randomSeconds = str(randomSeconds) if randomSeconds>9 else "0" + str(randomSeconds)
randomTime = " " + randomHours + ":" + randomMinutes + ":"+ randomSeconds
outDateTime = str(inputDate) + randomTime
return outDateTime
#------------------- Create death date --------------------
# Create a random death date based on the patient age and probablity of death
# The patient will be died at the input age. The patient born after 1.1.1900
# def getDeathDate(inputAge, ageDeathRate, birthDate, diagDate, ageDiagFactor):
def getDeathDate(inputAge, birthDate, diagDate, ageDiagFactor, addTimeToDates):
deathDateS = None
# update the birthdate and the diagnostic date relativly to the death date
# the age now means the age when the patient died
startDate = datetime.date(1920,1,1)
endDate = datetime.date(2023-inputAge,1,1)
birthDate = fake.date_time_between(start_date=startDate, end_date=endDate)
diagDate = str(birthDate.date() + datetime.timedelta(days=ageDiagFactor))
deathDate = str(birthDate.date() + datetime.timedelta(days=inputAge * 365))
# remove the time from the date
birthDate = str(birthDate)[:10]
if addTimeToDates:
birthDate = getRandomTime(birthDate)
diagDate = getRandomTime(diagDate)
deathDate = getRandomTime(deathDate)
return birthDate, diagDate, deathDate
#------------------- Create a distribution to sample from --------------------
def getGroupDistriution(labelLst, countLst):
# check if we have large numbers, reduce them
countLst = [round(x) for x in countLst]
if countLst[0]>1000:
countLst = [int(x/1000) for x in countLst]
dist = [[x]*y for x,y in zip(labelLst, countLst)]
# Flatten list
dist = [item for sublist in dist for item in sublist]
# shuffle
random.shuffle(dist)
return dist
# #-------------------- create age distribution ----------------------
def getAgeDistribution(stData, numPST, rdAgeGroupsLst, total_number_of_patients):
stateAgeDist = []
dataLabels=list(range(len(stData)))
# total population of this state
stTotal = sum(stData)
# create age ratio for each age
stateAgeRatio = [ round( stData[x] / stTotal ,5) for x in range(len(stData)) ]
# Number of patients per age for this state
stateAgeRates = [ round( stateAgeRatio[x] * numPST ) for x in range(len(dataLabels)) ]
# repeat for each age
for k in range(len(dataLabels)):
ageDist = []
for r in range (stateAgeRates[k]):
ageDist.append(k)
stateAgeDist.append(ageDist)
# Collect age distribution into age groups
finalStateAgeDist = []
for g, ag in enumerate(rdAgeGroupsLst):
minAge,maxAge = getAgeRangeFromAgeGroup(g, dataLabels[-1])
stateAgeGroupDist = [stateAgeDist[k] for k in range(len(stateAgeDist)) if minAge<=k and k<maxAge]
#flatten
stateAgeGroupDist = [item for sublet in stateAgeGroupDist for item in sublet]
finalStateAgeDist.append(stateAgeGroupDist)
return finalStateAgeDist
#------------------- Sample from a normal distribution --------------------
# based on minimum, maximum values. mean = (min + max)/2, std = mean/2
# Ref: https://stackoverflow.com/questions/62364477/python-random-number-generator-within-a-normal-distribution-with-min-and-max-val
# https://www.thoughtco.com/range-rule-for-standard-deviation-3126231
def sampleFromNormalDistribution(minVal, maxVal, sampleSize=10000):
# TODO BUG: if the range is large samples ma not look like normally distributed
mean = (minVal + maxVal) / 2.0
std = (maxVal - minVal) / 4.0
random_uniform_data = np.random.uniform(special.erf( (minVal - mean) / std),
special.erf( (maxVal - mean) / std),
sampleSize)
random_gaussianized_data = (special.erfinv(random_uniform_data) * std) + mean
return random_gaussianized_data
#--------------- get state names ----------------
def getUSAstateNames(isDCIncluded=None):
"""
Return list of USA states IDs, long and short names
Args:
isDCIncluded (int): 1: to include or 0: to exclude Washington DC from the list
Returns:
List of lists: states IDS (int), states short names (str), state long names (str)
debends on isDCIncluded, the returned size may be 3x51 or 3x52
"""
isDCIncluded = 1 if isDCIncluded is None else isDCIncluded
usaFIPS = [int(states.STATES[x].fips) for x in range(len(states.STATES))]
usaLNames = [states.STATES[x].name for x in range(len(states.STATES))]
usaSNames = [states.STATES[x].abbr for x in range(len(states.STATES))]
if isDCIncluded:
# add Washington DC
usaFIPS.append(11)
usaFIPS = sorted(usaFIPS)
usaLNames.insert(usaFIPS.index(11),"District of Columbia")
usaSNames.insert(usaFIPS.index(11),"DC")
usaNames = [usaFIPS, usaSNames, usaLNames]
## check if the list is sorted
## print(all(usaFIPS[i] <= usaFIPS[i+1] for i in range(len(usaFIPS) - 1)))
return usaNames
#------------------- Get index of age group --------------------
def getAgeGroupIndex(age):
if age < 5:
ageG = 0
elif 5 <= age and age <= 14:
ageG = 1
elif 15 <= age and age <= 19:
ageG = 2
elif 20 <= age and age <= 24:
ageG = 3
elif 25 <= age and age <= 39:
ageG = 4
elif 40 <= age and age <= 60:
ageG = 5
elif 60 < age:
ageG = 6
return ageG
#--------------- find range of each age group ----------------
def getAgeRangeFromAgeGroup(ageGroupIndex, maxAge):
ageStart = None; ageEnd= None
if ageGroupIndex == 0:
ageStart = 0; ageEnd= 5
elif ageGroupIndex == 1:
ageStart = 5; ageEnd= 15
elif ageGroupIndex == 2:
ageStart = 15; ageEnd= 20
elif ageGroupIndex == 3:
ageStart = 20; ageEnd= 25
elif ageGroupIndex == 4:
ageStart = 25; ageEnd= 40
elif ageGroupIndex == 5:
ageStart = 40; ageEnd= 61
elif ageGroupIndex == 6:
# print("maxAge : ",maxAge)
ageStart = 61; ageEnd= maxAge + 1
return ageStart, ageEnd
#-------------------------------- readingCSVdata ----------------
# used in charting
def readingCSVdata(csvFnm, maxUSAAge=None):
with open(csvFnm) as dataFile:
dataReader = csv.reader(dataFile, delimiter=";", quotechar='"')
data = [row for row in dataReader]
dataLabels = data[0]
dataArray = data[1:]
newDataArray = []
if (maxUSAAge is None) or (maxUSAAge == 0):
maxUSAAge = np.max([int(x[1]) for x in dataArray])
dataArray = [[row[0]] + [ (x) for x in row[1:] ] for row in dataArray]
for row in dataArray:
for i,col in enumerate(row):
if i in [0,1]:
row[i] = int(col)
elif i in [9,10]:
row[i] = float(col)
elif i in [6,7,8]: # Dates to years
row[i] = int(col[:4]) if not col=="" else 0
newDataArray.append(row)
newDataArray = dataArray if newDataArray ==[] else newDataArray
return maxUSAAge, dataLabels, newDataArray
def RDGetFiles(directory, string):
# Traverse the directory structure
filesLst = []
for root, dirs, files in os.walk(directory):
for filename in files:
# Check if the desired string is in the filename
if string in filename:
filesLst.append(os.path.join(root, filename))
return filesLst
# if this script called directly
if __name__ == "__main__":
# testing
if len(sys.argv) > 1:
print("input: ", sys.argv)
# ffffffffffffffffffffffffffffffffffffffff
# MDprepare.py
# ffffffffffffffffffffffffffffffffffffffff
##=============================================================
# The script:
# - reads the output files from import
# - convert them to usable csv and data lists
# - generates input data charts
##=====================================================
import csv, json, sys, os, time
import numpy as np
from scipy.optimize import minimize
from synthMD import MDutils, MDcharts
def getRaceData(cfg, raceDataFilePath):
print("Reading race data: ", raceDataFilePath)
#-------- race data for each state
raceData = [row for row in csv.reader(open(raceDataFilePath), delimiter=",", quotechar='"')]
raceData[1:] = [ [s.strip("[]'") for s in x[0].split(', ')] for x in raceData[1:]]
# get race names
rdsPath = cfg["paths"]["rdsPath"]
rdsPath = os.path.join(*rdsPath)
RDsData = json.load(open(rdsPath))["RDs"]
raceNamesLst = [x.split(",")[0] for x in list(RDsData[0]["race_percentage"]["races"].keys())]
# restructure labels and data
raceData[0] = [ raceData[0][4], raceData[0][0], raceNamesLst[0], raceNamesLst[1],raceNamesLst[2], raceData[0][1] ]
raceData[1:] = [ [int(x[4]), x[0], int(x[3]), int(x[2]), int(x[1])- int(x[2])-int(x[3]) ,int(x[1])] for x in raceData[1:]]
# save to csv file
csv.writer(open(raceDataFilePath[:-4]+"_ext.csv", 'w', newline='')).writerows(raceData)
return raceData
#-------------------------------- Extract Age Sex Data from usaAgeSexDataFolderPath into 4 files
# usaAgeSexDataFilePath: all useful extratced data
# usaAgeSexMaleDataFilePath, usaAgeSexFemaleDataFilePath, usaAgeSexTotalDataFilePath: data of male, female and both
def getAgeSexData(usaAgeSexDataFolderPath, usaAgeSexDataFilePath, usaAgeSexMaleDataFilePath, usaAgeSexFemaleDataFilePath, usaAgeSexTotalDataFilePath):
ageSexData=[]
if not os.path.exists(usaAgeSexDataFilePath):
print("Reading age sex data files from: ", usaAgeSexDataFolderPath)
fnms = os.listdir(usaAgeSexDataFolderPath)
fnms = sorted([x for x in fnms if ".csv" in x ])
# read each file
for fnm in fnms:
print("reading : ", fnm)
#TODO: add columns config to config.json
# get state and id from filename
id = int(fnm[-9:-7])
state = fnm[-6:-4]
# read the file into list
dataReader = csv.reader(open(os.path.join(usaAgeSexDataFolderPath,fnm)), delimiter=",", quotechar='"')
fileData = [row for row in dataReader]
# restructure and convert to numbers
dataArray = [[x[0], x[2], x[3], x[1]] for x in fileData[6:92]]
dataArray = [[ i, x[1], x[2], x[3]] for i, x in enumerate(dataArray)]
dataArray.insert(0,[id,state])
# flatten to 345 elements
dataArray = [item for sublist in dataArray for item in sublist]
# add to list of all states
ageSexData.append(dataArray)
# restructure
#ageSexData: 51 x id, state, age, male, female, total,...,age, male female total
labels = ["id", "state"]
labels.extend(["age","male","female","total"]* 86)
allData = []
allData.append(labels)
for x in ageSexData:
allData.append(x)
numStates = len(ageSexData)
# for each ages, we have 4 fields age, m,f,t
numAges = int((len(ageSexData[0])-2)/4)
# male population for each age for each state
ageStateMaleLst =[]
# female population for each age for each state
ageStateFemaleLst =[]
# population for each age for each state
ageStateTotalLst =[]
# create 3 large tables 51 rows x 2+86 columns
# id state age_0-age_85
# for each state
for i in range(numStates):
# for each state, get Male, Female, and Total population of current age
# add id and state to each row
rowM=[int(ageSexData[i][0]), ageSexData[i][1]]
rowF=[int(ageSexData[i][0]), ageSexData[i][1]]
rowT=[int(ageSexData[i][0]), ageSexData[i][1]]
# for each age
for j in range(numAges):
# add population of each age
idx = (3*j + 3 + j)-1
rowM.append(int(ageSexData[i][idx+1]))
rowF.append(int(ageSexData[i][idx+2]))
rowT.append(int(ageSexData[i][idx+3]))
ageStateMaleLst.append(rowM)
ageStateFemaleLst.append(rowF)
ageStateTotalLst.append(rowT)
labels = ["id","state"]
labels.extend(["age_"+str(x) for x in range(numAges)])
ageStateMaleLst.insert(0,labels)
ageStateFemaleLst.insert(0,labels)
ageStateTotalLst.insert(0,labels)
# create csv files from the lists
data2Save = [allData, ageStateMaleLst, ageStateFemaleLst, ageStateTotalLst]
fnms = [usaAgeSexDataFilePath, usaAgeSexMaleDataFilePath, usaAgeSexFemaleDataFilePath, usaAgeSexTotalDataFilePath]
for fnm, fData in zip(fnms, data2Save):
csv.writer(open(fnm, 'w', newline='')).writerows(fData)
else:
print("getAgeSexData(): files are already exist : ", usaAgeSexDataFilePath)
data2Read = []
fnms = [usaAgeSexMaleDataFilePath, usaAgeSexFemaleDataFilePath, usaAgeSexTotalDataFilePath]
for fnm in fnms:
# read csv files into lists
fData = [row for row in csv.reader(open(fnm), delimiter=",", quotechar='"')]
# convert to integers
fData[1:] = [ [int(x) if i>1 else x for i, x in enumerate(y) ] for y in fData[1:]]
data2Read.append(fData)
ageStateMaleLst, ageStateFemaleLst, ageStateTotalLst = data2Read
ageSexData = [ageStateMaleLst,ageStateFemaleLst,ageStateTotalLst]
return ageSexData
# Get initial list as linear distribution
def getLinearValue(x,x1,y1,x2,y2):
# create linear distribution y = m*x + b
m = (y2-y1)/(x2-x1)
y = m*(x-x1) + y1
return int(y)
# Reduce the error using optimisation
def minimizeError(estimated_population, estimation_sum):
def func(x):
return abs(np.sum(x) - estimation_sum)
# Initialize the list
x0 = estimated_population
# Define the constraints
constraints = [
{'type': 'ineq', 'fun': lambda x: estimation_sum - np.sum(x)},
{'type': 'ineq', 'fun': lambda x: x-5}, # values must be >=5
]
# Minimize the absolute difference
result = minimize(func, x0, constraints=constraints, method='SLSQP')
return [int(z) for z in result.x]
# Create a new estimated list for missing ages
# we distributed the last age value on the missing ages
def getEstimatedList(ages_population, maxInputAge=None, maxEstimatedAge=None, maxError=None):
maxInputAge = 84 if maxInputAge is None else maxInputAge
maxEstimatedAge = 96 if maxEstimatedAge is None else maxEstimatedAge -1
maxError = 100 if maxError is None else maxError
estimation_sum = ages_population[-1]
startElement = ages_population[-2]
endElement = 1
estimated_population = [ getLinearValue(x,maxInputAge,startElement,maxEstimatedAge,endElement) for x in range(maxInputAge,maxEstimatedAge+1)]
estimated_population = minimizeError(estimated_population, estimation_sum)
final_error = abs(estimation_sum-sum(estimated_population))
# check for negative values
hasNegative = any(x < 0 for x in estimated_population)
if hasNegative:
print("Error: Negative values")
for i,x in enumerate(estimated_population):
print(i+85,x)
sys.exit()
# check if we havee large error
largeError = final_error>maxError
if largeError:
print("Error: Large error")
for i,x in enumerate(estimated_population):
print(i+85,x)
print("final_error : ",final_error)
sys.exit()
return estimated_population
def getFixAgeSexData(ageSexData=None, maxAge=None, fnmPath=None, usaAgeSexDataFilesPath=None, catlabels=None):
# first check if the files exist
fixedFilePaths = [x[:-4]+"_ext.csv" for x in usaAgeSexDataFilesPath]
## This is computed only when the files are created
optimizationError=[]
if not all([os.path.exists(x) for x in fixedFilePaths]):
maxAge = 95 if maxAge is None else maxAge
# fix the ageSexData
fixedAgeSexData = [[ statePop[:-1] +
sorted(getEstimatedList(statePop[2:], maxInputAge=len(statePop)-3, maxEstimatedAge=maxAge + 1, maxError=100),reverse=True)
for statePop in cat[1:]] for i, cat in enumerate(ageSexData)]
# save the result to csv files
for c in range(3):
csv.writer(open(fixedFilePaths[c], 'w', newline='')).writerows(fixedAgeSexData[c])
## plot the result and save the charts
Y0 = [ sum([ x[i+2] for x in ageSexData[c][1:] ]) for i in range(86)]
Y1 = [ sum([ x[i+2] for x in fixedAgeSexData[c]]) for i in range(maxAge+1)]
errCount = Y0[-1]-sum(Y1[85:])
errPercentage =format(errCount/sum(Y0)*100, ".10f")
print("total "+catlabels[c]+" error: ", errCount, errPercentage)
optimizationError.append([errCount,errPercentage])
fnm1 = os.path.join("datasets","usa","chart_usa-2020-states-age-sex-"+catlabels[c]+".png")
fnm2 = os.path.join("datasets","usa","chart_usa-2020-states-age-sex-"+catlabels[c]+"_ext.png")
MDcharts.plotData(Y0, figTitle=catlabels[c]+" Age Before", XticksLabelsLst=None, isPercentageOutput=None, doShow=0, chartFnmPath=fnm1)
MDcharts.plotData(Y1, figTitle=catlabels[c]+" Age After, error count: "+str(errCount)+" error: "+errPercentage+"%", XticksLabelsLst=None, isPercentageOutput=None, doShow=0, chartFnmPath=fnm2)
else:
# read the file and return the data:
print("Fixed: usaAgeSexData files exist: ", fixedFilePaths[0])
fixedAgeSexData= [[ [int(x[0]), x[1]] +[int(y) for y in x[2:] ] for x in
[row for row in
csv.reader(open(fixedFilePaths[c]), delimiter=",", quotechar='"')]]
for c in range(3)]
return fixedAgeSexData
# Regroup into 7 groups
# output should be 51 states x 7 age groups
def getGroupedAgeSexData(ageSexData=None, rdsAgeGroups=None, maxAge=None, usaAgeSexDataFilesPath=None, catlabels=None):
# first check if the files exist
groupedFilePaths = [x[:-4]+"_grp.csv" for x in usaAgeSexDataFilesPath]
groupedAgeSexData = []
if not all([os.path.exists(x) for x in groupedFilePaths]):
for c in range(3): # for each catigory
cStates= []
for st in ageSexData[c]: # for each state
cStAge = st[2:]
cState = [st[0],st[1]]
for i,lbl in enumerate(rdsAgeGroups): # for each age group
ageStart, ageEnd = MDutils.getAgeRangeFromAgeGroup(i, maxAge)
# print("a,b : ", ageStart,ageEnd)
# find population of this age group
sumAgeGroup = 0
s = 0
for a, age in enumerate(cStAge):
s += age
if (ageStart<= a) and (a<ageEnd):
# put in this age group
sumAgeGroup += age
cState = cState + [sumAgeGroup]
cStates.append(cState)
groupedAgeSexData.append(cStates)
## save the result to csv files
statesIDs, statesSName, statesLName = MDutils.getUSAstateNames()
for c in range(3):
csv.writer(open(groupedFilePaths[c], 'w', newline='')).writerows(groupedAgeSexData[c])
# population of each state
Y = [ sum(groupedAgeSexData[c][s][2:]) for s in range(len(groupedAgeSexData[c])) ]
fnm = os.path.join("datasets","usa","chart_usa-2020-states-age-sex-"+catlabels[c]+"_state.png")
figTitle = catlabels[c]+" population per state"
MDcharts.plotData(Y, figTitle=figTitle, XticksLabelsLst=statesSName, isPercentageOutput=None, doShow=0, chartFnmPath=fnm)
print("------------------- Create Maps -------------------------")
# Initialize an empty dictionary to store the counts of persons per state
state_counts = {state: val for state, val in zip(statesLName,Y)}
#print(state_counts)
fnm = os.path.join("datasets","usa","chart_usa-2020-states-age-sex-"+catlabels[c]+"_state_map.png")
cfg = { "shapefile_path": "datasets/usa/map/cb_2018_us_state_20m.shp",
"xylim": [-130, -60, 20, 55],
"fontsize": 6,
"figsize":(15,10),
"cmap":"magma",
"outputFnmPath": fnm,
"doSave":1,
"doShow":0,
"mapTitle": figTitle,
"mapName":"NAME",
"dataName":"state"
}
MDcharts.plotMap(state_counts, cfg)
Y = [sum(groupedAgeSexData[c][s][g+2] for s in range(len(groupedAgeSexData[c]))) for g in range(len(groupedAgeSexData[c][0])-2)]
print("Total age Groups Populations "+catlabels[c],Y)
fnm = os.path.join("datasets","usa","chart_usa-2020-states-age-sex-"+catlabels[c]+"_grp.png")
MDcharts.plotData(Y, figTitle=catlabels[c]+" Age grouped", XticksLabelsLst=rdsAgeGroups, isPercentageOutput=None, doShow=0, chartFnmPath=fnm)
else:
print("Grouped: usaAgeSexData files exist: ", groupedFilePaths[0])
groupedAgeSexData = [ [ [int(x[0]), x[1]] +[int(y) for y in x[2:] ] for x in [row
for row in csv.reader(open(groupedFilePaths[c]), delimiter=",", quotechar='"')]]
for c in range(3)]
return groupedAgeSexData
def getPreparedData(cfg, usaRaceDataPath, usaAgeSexDataFolderPath, usaAgeSexDataFilePath, usaAgeSexMaleDataFilePath, usaAgeSexFemaleDataFilePath, usaAgeSexTotalDataFilePath, catlabels):
prepTimeStart = time.time()
maxAge = cfg["maxAge"]["max-age-value"]
## rdAgeGroupsLst = [ "<5" ,"5-14" ,"15-19" ,"20-24" ,"25-39" ,"40-60" ,">60"]
rdAgeGroupsLst = cfg["rdAgeGroupsLst"]
## get race data and use labels from config file
raceData = getRaceData(cfg, usaRaceDataPath)
## collect data from all files into one file
ageSexData = getAgeSexData(usaAgeSexDataFolderPath, usaAgeSexDataFilePath, usaAgeSexMaleDataFilePath, usaAgeSexFemaleDataFilePath, usaAgeSexTotalDataFilePath)
usaAgeSexDataFilesPath = [usaAgeSexMaleDataFilePath,usaAgeSexFemaleDataFilePath,usaAgeSexTotalDataFilePath]
## add missing ages 85:maxAge
fixedAgeSexData = getFixAgeSexData(ageSexData, maxAge=maxAge, usaAgeSexDataFilesPath=usaAgeSexDataFilesPath, catlabels=catlabels)
groupedAgeSexData = getGroupedAgeSexData(fixedAgeSexData,rdAgeGroupsLst, maxAge=maxAge, usaAgeSexDataFilesPath=usaAgeSexDataFilesPath, catlabels=catlabels)
prepTimeEnd = time.time() - prepTimeStart
print("Prepared data took ", prepTimeEnd, " seconds")
# if this script called directly
if __name__ == "__main__":
# testing
if len(sys.argv) > 1:
print("input: ", sys.argv)
# ffffffffffffffffffffffffffffffffffffffff
# MDimport.py
# ffffffffffffffffffffffffffffffffffffffff
# #=============================================================
# The script:
# - imports USA states information using us lib
# - imports USA census race data using API and save to csv file
# - downloads USA census age and sex excel tables and convert them to csv
# - pip install census --proxy http://8.8.8.8/
#
# Requirements:
# - install us and census (note census lib is not used, it seems out of date)
# pip3 install census us
# - getting api key from here: https://api.census.gov/data/key_signup.html
# after that they key will be submitted to the email and needs activation
# Important note: some census variables may need update, check the census website for details
# #=============================================================
import os, sys, csv, json, requests, urllib, time
import pandas as pd
from synthMD import MDutils
## ------------------------- Get Race populations using USA census API
def getUSACensusDataRace(censusAPIKey, censusQueryYear=None, censusXLSXYear=None, forceDownload=None,
usaIDs=None,race_data_path=None, doSave=None, proxies=None):
proxies= {} if proxies is None else proxies
usaIDs = [ "0" + str(id) if id <10 else str(id) for id in usaIDs]
## Get states race
## Total, white, black: Ref: https://api.census.gov/data/2020/dec/pl/variables.html
censusVars = "NAME,P1_001N,P1_003N,P1_004N"
dataset_acronym = "/dec/pl"
stateIDs = "*" # we can also get one or more specific states e.g. 01,02,06
query_url_race = "https://api.census.gov/data/"+str(censusQueryYear)+dataset_acronym+"?get="+censusVars+"&for=state:"+stateIDs+"&key=" + censusAPIKey
# Use requests package to call out to the API
response = requests.get(query_url_race) if not proxies else requests.get(query_url_race, proxies=proxies)
print(response.text)
## Convert the Response to text and print the result
labels=["State","Total","White", "Black", "ID"]
## save the data as csv
race_data = [ [x for x in json.loads(response.text)[1:] if id==x[4] ] for id in usaIDs]
race_data.insert(0, labels)
## Open a new CSV file
csv.writer(open(race_data_path, 'w', newline='')).writerows(race_data)
## -------------- Get USA census age sex data using excel tables
def getUSACensusDataAgeSex(censusAPIKey=None, censusQueryYear=None, censusXLSXYear=None, forceDownload=None,
usaIDs=None, usaSNames=None, usaAgeFolderPath=None, doSave=None, proxies=None):
"""
Calculates the area of a circle with the given radius.
Args:
radius (float): The radius of the circle.
Returns:
float: The area of the circle.
"""
proxies= {} if proxies is None else proxies
forceDownload = 0 if forceDownload is None else forceDownload
### Note: this query 2020 and 2021 age sex (does not cover details)
## query_url = "https://api.census.gov/data/2016/acs/acs1?get=group(B01001)&for=us:*&key=" + censusAPIKey
# The required data are available as xlxs for download
query_url_age_sex = "https://www2.census.gov/programs-surveys/popest/tables/" + censusXLSXYear + "/state/asrh/sc-est2021-syasex-"
# download all files and convert to csvs
if not os.path.exists(usaAgeFolderPath):
os.mkdir(usaAgeFolderPath)
for i,id in enumerate(usaIDs):
id = "0" + str(id) if id <10 else str(id)
fnm = id + ".xlsx"
webLink = query_url_age_sex + fnm
xlsxPath = os.path.join(usaAgeFolderPath,"usa-age-sex-"+censusXLSXYear+"-"+id+"-"+usaSNames[i]+".xlsx")
csvPath = xlsxPath[:-4]+"csv"
# download only if file does not exist, to force download anyway use forceDownload=1
if forceDownload or not os.path.exists(csvPath):
try:
print("downloading : ", csvPath)
if proxies:
# Define the proxy information
proxy_handler = urllib.request.ProxyHandler(proxies)
opener = urllib.request.build_opener(proxy_handler)
urllib.request.install_opener(opener)
urllib.request.urlretrieve(webLink, xlsxPath)
#print("convert xlsx to csv ....")
# read the excel file into a pandas dataframe
df = pd.read_excel(xlsxPath, engine='openpyxl')
# write the dataframe to a csv file
df.to_csv(csvPath, index=False)
#print("removing old xlsx file ....")
#os.remove(xlsxPath)
except Exception as e:
print(e)
else:
print("age-sex data file exist: ", csvPath)
## --------------------------------- Get USA Census Data
def getUSACensusData(censusAPIKey, datasetFolder, censusQueryYear=None, censusXLSXYear=None, getAgeSexData=None, getRaceData=None,forceDownload=None, doSave=None, proxies=None):
print("=========================== Getting USA Census DATA ================================")
if censusAPIKey==None:
print("please get your API key from here: https://api.census.gov/data/key_signup.html")
sys.exit(0)
impTimeStart = time.time()
proxies = {} if proxies is None else proxies
censusQueryYear = 2020 if censusQueryYear is None else censusQueryYear
censusXLSXYear = "2020-2021" if censusXLSXYear is None else censusXLSXYear
doSave = 0 if doSave is None else doSave
forceDownload = 0 if forceDownload is None else forceDownload
getAgeSexData = 1 if getAgeSexData is None else getAgeSexData
getRaceData = 1 if getRaceData is None else getRaceData
# storage paths
# TODO: get from config file, also add using optional arguments from terminal
usaAgeFolderPath = os.path.join(datasetFolder,"usaAge"+censusXLSXYear)
race_data_path = os.path.join(datasetFolder,"usa-"+str(censusQueryYear)+"-states-race.csv")
# get USA states IDs, long and short names
# IDs and short names are useful to work with API and other libs
usaFIPS, usaSNames, usaLNames = MDutils.getUSAstateNames()
if getRaceData and not os.path.exists(race_data_path):
getUSACensusDataRace(censusAPIKey,censusQueryYear, censusXLSXYear, forceDownload,usaFIPS,race_data_path,
doSave, proxies=proxies)
else:
print("race data file exists: ", race_data_path)
if getAgeSexData:
getUSACensusDataAgeSex(censusAPIKey,censusQueryYear, censusXLSXYear, forceDownload,
usaFIPS, usaSNames,usaAgeFolderPath, doSave, proxies=proxies)
impTimeEnd = time.time() - impTimeStart
print("Import time process took: ", impTimeEnd, " seconds")
# if this script called directly
if __name__ == "__main__":
# testing
if len(sys.argv) > 1:
print("input arguments: ", sys.argv)
# ffffffffffffffffffffffffffffffffffffffff
# MDevaluate.py
# ffffffffffffffffffffffffffffffffffffffff
##=======================================================================================
# Evaluate the results
# Compare the statistics of the output synthetic dataset to the input statistics
##=======================================================================================
import sys, os, time, re
import numpy as np
from fractions import Fraction as frac
from synthMD import MDutils, MDcharts
#----------------- Printing with exception handling ----------------------
def tryPrint(txt, L, dx, vs=None, roundPlaces=None):
logLine = ""
roundPlaces = 2 if roundPlaces is None else roundPlaces
try:
x1 = round((len(L)/dx)*100,5)
logLine =txt + " : " + str(f"{ str(x1):<10} vs {str(vs)} \n")
except Exception as e:
logLine= str(e)+"\n"
print(logLine)
return logLine
## ------------------------------------- getAgeGroupsEvaluation -------------------------------------
def getRaceSexEvaluation(i, RDnamesLst, outputData, totalNumberOfPatients, sexWeights, raceWeights, raceNamesLst, clinicalParsLst,
agePopulationsStatesAll, processingTime, logLines):
roundPlaces = 2
# for all states for all 7 age groups
# size: 51 x 7
agePopulations = agePopulationsStatesAll[2]
totalUSA = sum([sum(s) for s in agePopulations])
logLine = "=========================( "+ RDnamesLst[i] +" )========================\n"
logLines.append(logLine)
print(logLine)
logLine = " processing time in seconds: " +str(processingTime)+" \n"
logLines.append(logLine)
print(logLine)
logLine = "USA population: "+ str(totalUSA) +"\n"
logLines.append(logLine)
print(logLine)
pAll = len(outputData) -1
## ----------------------------- total number of patients
logLine = "Total patients: result vs expected: "+ str(pAll) + " , "+ str(totalNumberOfPatients) +"\n"
logLines.append(logLine )
print(logLine)
## ----------------------------- Sex and Race Ratios
logLine = "----------- Ratios: sex, AA, EA, OA, Death \n"
logLines.append(logLine )
print(logLine)
# 0 1 2 3 4 5 6 7 8
# pData = [pCount, pAge, usStateNames[s] ,pZipCode, pSex, pRace, pBirthDate, pDiagDate, pDeathDate]
numF = ([x for x in outputData[1:] if x[4]=='f'])
numM = ([x for x in outputData[1:] if x[4]=='m'])
logLine = "number of male patients : "+ str(len(numM)) +"\n"
logLines.append(logLine )
print(logLine)
logLine = "number of female patients: "+ str(len(numF)) +"\n"
logLines.append(logLine )
print(logLine)
logLine = tryPrint("Female ratio : ", numF , pAll, sexWeights[i] , roundPlaces )
logLines.append(logLine )
logLine = tryPrint("AA ratio : ", [x for x in outputData[1:] if x[5]==raceNamesLst[0]], pAll, raceWeights[i][0], roundPlaces )
logLines.append(logLine )
logLine = tryPrint("AE ratio : ", [x for x in outputData[1:] if x[5]==raceNamesLst[1]], pAll, raceWeights[i][1], roundPlaces )
logLines.append(logLine )
logLine = tryPrint("AO ratio : ", [x for x in outputData[1:] if x[5]==raceNamesLst[2]], pAll, raceWeights[i][2], roundPlaces )
logLines.append(logLine )
## ----------------------------- Clinical Parameters Ratios
pCP1 = [x[9] for x in outputData[1:]]
try:
logLine = "ClinicalPar1 Mean STD: "+ str(round(np.mean(pCP1),2)) + "\t" + str(round(np.std(pCP1),2))+ "\n"
logLines.append(logLine )
print(logLine)
logLine = "ClinicalPar1 Min Max : "+str(round(np.min(pCP1),2))+ "\t"+ str(round(np.max(pCP1),2))+"\t vs \t" +str(clinicalParsLst[i][0][2])+"\t"+str(clinicalParsLst[i][0][3])+ "\n"
logLines.append(logLine )
print(logLine)
except Exception as e:
print(e)
if len(outputData[0])==11:
pCP2= [x[10] for x in outputData[1:]]
try:
logLine = "ClinicalPar2 Mean STD: " + str(round(np.mean(pCP2),2)) + "\t" + str(round(np.std(pCP2),2)) + "\n"
logLines.append(logLine )
print(logLine)
logLine = "ClinicalPar2 Min Max : " + str(round(np.min(pCP2),2)) + "\t" + str(round(np.max(pCP2),2)) +"\t vs \t" + str(clinicalParsLst[i][1][2])+"\t"+str(clinicalParsLst[i][1][3]) + "\n"
logLines.append(logLine )
print(logLine)
except Exception as e:
print(e)
return logLines
def getAgeGroupsEvaluation(i, outputData, agePopulationsStatesAll, pAll,totalUSA, rdAgeGroupsLst,roundPlaces, logLines):
mAgePopulations, fAgePopulations, agePopulations = agePopulationsStatesAll
logLine = " Age group percentages:------------ \n"
logLines.append(logLine )
print(logLine)
agePopulationsSum = [ sum(s)for s in zip(*agePopulations)]
for k in range(len(rdAgeGroupsLst)):
L = [x for x in outputData[1:] if MDutils.getAgeGroupIndex(x[1])==k ]
logLine = tryPrint(" Age groups "+rdAgeGroupsLst[k]+"\t" , L , pAll, round((agePopulationsSum[k]/totalUSA)*100, roundPlaces) , roundPlaces )
logLines.append(logLine )
logLine = " Age groups Female:------------ \n"
logLines.append(logLine )
print(logLine)
agePopulationsFSum = [ sum(s)for s in zip(*fAgePopulations)]
for k in range(len(rdAgeGroupsLst)):
L = [x for x in outputData[1:] if MDutils.getAgeGroupIndex(x[1])==k and x[4]=='f']
logLine = tryPrint(" Age groups "+rdAgeGroupsLst[k]+"\t" , L , pAll, round((agePopulationsFSum[k]/totalUSA)*100, roundPlaces) , roundPlaces )
logLines.append(logLine )
logLine = " Age groups Male :------------ \n"
logLines.append(logLine )
print(logLine)
agePopulationsMSum = [ sum(s)for s in zip(*mAgePopulations)]
for k in range(len(rdAgeGroupsLst)):
L = [x for x in outputData[1:] if MDutils.getAgeGroupIndex(x[1])==k and x[4]=='m']
logLine = tryPrint(" Age groups "+rdAgeGroupsLst[k]+"\t" , L , pAll, round((agePopulationsMSum[k]/totalUSA)*100, roundPlaces) , roundPlaces )
logLines.append(logLine )
return logLines, agePopulationsSum
def getDeathGroupsEvaluation(i, outputData, deathRates, statePatientsDeads, statePatientsAlives, rdAgeGroupsLst,agePopulationsSum, logLines):
print(" Age groups Deaths: ")
# numberOfPatientsAges 51 x 7
# print(fix dead patients number vs ground truth and check for other diseases)
statePatientsDeadsSum = [sum(s) for s in zip(*statePatientsDeads) ]
statePatientsAlivesSum = [sum(s) for s in zip(*statePatientsAlives)]