-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsql_database_uploader.py
More file actions
1866 lines (1641 loc) · 100 KB
/
sql_database_uploader.py
File metadata and controls
1866 lines (1641 loc) · 100 KB
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 warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
warnings.simplefilter(action='ignore', category=UserWarning)
import email.utils
import yaml
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import json
import boto3
import re
import os
from dateutil.parser import parse
import datetime
import numpy as np
import itertools
#from import_loader_v2 import pd, np, pd_s3, boto3, datetime, os, re
#from import_loader_v2 import get_box_data_v2, parse, pathlib
#import mysql.connector
import copy
import pathlib
import urllib3
from decimal import Decimal
import pandas as pd
import sqlalchemy as sd
#import get_box_data_v2
error_msg = list()
success_msg = list()
def lambda_handler(event, context):
global error_msg
global success_msg
error_msg.clear()
success_msg.clear()
#print(error_msg)
#print(success_msg)
# TODO implement
s3_client = boto3.client("s3")
ssm = boto3.client("ssm")
http = urllib3.PoolManager()
host_client = ssm.get_parameter(Name="db_host", WithDecryption=True).get("Parameter").get("Value")
user_name = ssm.get_parameter(Name="lambda_db_username", WithDecryption=True).get("Parameter").get("Value")
user_password =ssm.get_parameter(Name="lambda_db_password", WithDecryption=True).get("Parameter").get("Value")
bucket_name = event['Records'][0]['s3']['bucket']['name']
sub_folder = "Vaccine Response Submissions"
#set up parameters base on the event
Update_Assay_Data = False
Update_Study_Design = False
Update_BSI_Tables = False
Add_Blinded_Results = False
update_CDC_tables = False
key_list = []
db_name = "seronetdb-Vaccine_Response"
for record in event['Records']:
key_list.append(record['s3']['object']['key'])
if any('Serology_Data_Files/Reference_Panel_Files/Reference_Panel_Submissions/' in key for key in key_list):
Add_Blinded_Results = True
if any('CBC_Folders/Assay_Data/' in key for key in key_list):
Update_Assay_Data = True
if any('Vaccine_Respone_Study_Design/' in key for key in key_list):
Update_Study_Design = True
if any('Serology_Data_Files/biorepository_id_map/' in key for key in key_list):
Update_BSI_Tables = True
if any('Reference+Panel+Submissions' in key for key in key_list):
sub_folder = 'Reference Panel Submissions'
db_name = "seronetdb-Validated"
try:
connection_tuple = connect_to_sql_db(host_client, user_name, user_password, db_name)
kwargs = {'Update_Assay_Data': Update_Assay_Data, 'Update_Study_Design': Update_Study_Design, 'Update_BSI_Tables': Update_BSI_Tables, 'Add_Blinded_Results': Add_Blinded_Results, "update_CDC_tables": update_CDC_tables}
file_key = key_list[0]
sql_table_dict, all_submissions = Db_loader_main(file_key, sub_folder, connection_tuple, s3_client, bucket_name, **kwargs)
if db_name == "seronetdb-Vaccine_Response" and len(all_submissions) > 0:
TopicArn_make_time_line = ssm.get_parameter(Name="TopicArn_make_time_line", WithDecryption=True).get("Parameter").get("Value")
res=sns_publisher("make_time_line",TopicArn_make_time_line)
except Exception as e:
error_msg.append(str(e))
display_error_line(e)
#raise(e)
#finally:
#delete_data_files(bucket_name, file_key)
''''''
email_host = "email-smtp.us-east-1.amazonaws.com"
email_port = 587
USERNAME_SMTP = ssm.get_parameter(Name="USERNAME_SMTP", WithDecryption=True).get("Parameter").get("Value")
PASSWORD_SMTP = ssm.get_parameter(Name="PASSWORD_SMTP", WithDecryption=True).get("Parameter").get("Value")
SENDER = ssm.get_parameter(Name="sender-email", WithDecryption=True).get("Parameter").get("Value")
RECIPIENT_RAW = ssm.get_parameter(Name="SQL_Database_Uploader_Recipents", WithDecryption=True).get("Parameter").get("Value")
RECIPIENT = RECIPIENT_RAW.replace(" ", "")
RECIPIENT_LIST = RECIPIENT.split(",")
SUBJECT = 'SQL Database Uploader'
SENDERNAME = 'SeroNet Data Team (Data Curation)'
if len(error_msg) > len(all_submissions):
message_slack_fail = ""
for error_message in error_msg:
message_slack_fail = message_slack_fail + '\n'+ error_message
failure = ssm.get_parameter(Name="failure_hook_url", WithDecryption=True).get("Parameter").get("Value")
message_slack_fail = message_slack_fail + '\n'+ 'The data was failed to be uploaded into the database'
print('The data was failed to be uploaded into the database')
data={"text": message_slack_fail}
r=http.request("POST", failure, body=json.dumps(data), headers={"Content-Type":"application/json"})
for recipient in RECIPIENT_LIST:
msg_text = message_slack_fail
msg = MIMEMultipart('alternative')
msg['Subject'] = SUBJECT
msg['From'] = email.utils.formataddr((SENDERNAME, SENDER))
part1 = MIMEText(msg_text, "plain")
msg.attach(part1)
msg['To'] = recipient
send_email_func(email_host, email_port, USERNAME_SMTP, PASSWORD_SMTP, SENDER, recipient, msg)
#send the message to slack channel
else:
message_slack_success = ""
for success_message in success_msg:
message_slack_success = message_slack_success + '\n'+ success_message
#send the message to slack channel
message_slack_success = message_slack_success + '\n' + 'The data was successfully uploaded into the database'
print('The data was successfully uploaded into the database')
data={"text": message_slack_success}
success = ssm.get_parameter(Name="success_hook_url", WithDecryption=True).get("Parameter").get("Value")
r=http.request("POST", success, body=json.dumps(data), headers={"Content-Type":"application/json"})
for recipient in RECIPIENT_LIST:
msg_text = message_slack_success
msg = MIMEMultipart('alternative')
msg['Subject'] = SUBJECT
msg['From'] = email.utils.formataddr((SENDERNAME, SENDER))
part1 = MIMEText(msg_text, "plain")
msg.attach(part1)
msg['To'] = recipient
send_email_func(email_host, email_port, USERNAME_SMTP, PASSWORD_SMTP, SENDER, recipient, msg)
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
def connect_to_sql_db(host_client, user_name, user_password, file_dbname):
global error_msg
#host_client = "Host Client"
#user_name = "User Name"
#user_password = "User Password"
#file_dbname = "Name of database"
sql_column_df = pd.DataFrame(columns=["Table_Name", "Column_Name", "Var_Type", "Primary_Key", "Autoincrement",
"Foreign_Key_Table", "Foreign_Key_Column"])
creds = {'usr': user_name, 'pwd': user_password, 'hst': host_client, "prt": 3306, 'dbn': file_dbname}
connstr = "mysql+mysqlconnector://{usr}:{pwd}@{hst}:{prt}/{dbn}"
engine = sd.create_engine(connstr.format(**creds))
engine = engine.execution_options(autocommit=False)
conn = engine.connect()
metadata = sd.MetaData()
metadata.reflect(engine)
for t in metadata.tables:
try:
curr_table = metadata.tables[t]
curr_table = curr_table.columns.values()
for curr_row in range(len(curr_table)):
curr_dict = {"Table_Name": t, "Column_Name": str(curr_table[curr_row].name),
"Var_Type": str(curr_table[curr_row].type),
"Primary_Key": str(curr_table[curr_row].primary_key),
"Autoincrement": False,
"Foreign_Key_Count": 0,
"Foreign_Key_Table": 'None',
"Foreign_Key_Column": 'None'}
curr_dict["Foreign_Key_Count"] = len(curr_table[curr_row].foreign_keys)
if curr_table[curr_row].autoincrement is True:
curr_dict["Autoincrement"] = True
if len(curr_table[curr_row].foreign_keys) == 1:
key_relation = list(curr_table[curr_row].foreign_keys)[0].target_fullname
key_relation = key_relation.split(".")
curr_dict["Foreign_Key_Table"] = key_relation[0]
curr_dict["Foreign_Key_Column"] = key_relation[1]
sql_column_df = pd.concat([sql_column_df, pd.DataFrame.from_records([curr_dict])])
except Exception as e:
error_msg.append(str(e))
display_error_line(e)
print("## Sucessfully Connected to " + file_dbname + " ##")
sql_column_df.reset_index(inplace=True, drop=True)
return sql_column_df, engine, conn
def send_email_func(HOST, PORT, USERNAME_SMTP, PASSWORD_SMTP, SENDER, recipient, msg):
server = smtplib.SMTP(HOST, PORT)
server.ehlo()
server.starttls()
#stmplib docs recommend calling ehlo() before & after starttls()
server.ehlo()
server.login(USERNAME_SMTP, PASSWORD_SMTP)
server.sendmail(SENDER, recipient, msg.as_string())
server.close()
def Db_loader_main(file_key, sub_folder, connection_tuple, s3_client, bucket_name, **kwargs):
global error_msg
global success_msg
"""main function that will import data from s3 bucket into SQL database"""
pd.options.mode.chained_assignment = None
#s3_client = boto3.client('s3', aws_access_key_id=aws_creds_prod.aws_access_id, aws_secret_access_key=aws_creds_prod.aws_secret_key,region_name='us-east-1')
#bucket_name = "nci-cbiit-seronet-submissions-passed"
#bucket_name = "seronet-demo-submissions-passed"
data_release = "2.0.0"
if sub_folder == "Reference Panel Submissions":
sql_table_dict = get_sql_dict_ref(s3_client, bucket_name)
elif sub_folder == "Vaccine Response Submissions":
sql_table_dict = get_sql_dict_vacc(s3_client, bucket_name)
else:
return
Update_Assay_Data = get_kwarg_parms("Update_Assay_Data", kwargs)
Update_Study_Design = get_kwarg_parms("Update_Study_Design", kwargs)
Update_BSI_Tables = get_kwarg_parms("Update_BSI_Tables", kwargs)
loading_result = ''
############################################################################################################################
try:
conn = connection_tuple[2]
engine = connection_tuple[1]
sql_column_df = connection_tuple[0]
done_submissions = pd.read_sql(("SELECT * FROM Submission"), conn) # list of all submissions previously done in db
done_submissions.drop_duplicates("Submission_S3_Path", inplace=True)
all_submissions = [] # get list of all submissions by CBC
cbc_code = []
all_submissions, cbc_code = get_all_submissions(s3_client, bucket_name, sub_folder, "Feinstein_CBC01", 41, all_submissions, cbc_code)
all_submissions, cbc_code = get_all_submissions(s3_client, bucket_name, sub_folder, "UMN_CBC02", 27, all_submissions, cbc_code)
all_submissions, cbc_code = get_all_submissions(s3_client, bucket_name, sub_folder, "ASU_CBC03", 32, all_submissions, cbc_code)
all_submissions, cbc_code = get_all_submissions(s3_client, bucket_name, sub_folder, "Mt_Sinai_CBC04", 14, all_submissions, cbc_code)
#all_submissions = [os.path.dirname(file_key)]
file_key = os.path.dirname(file_key)
file_key = file_key.replace("+", " ").replace("%28","(").replace("%29",")")
all_submissions = [i for i in all_submissions if file_key in i]
time_stamp = [i.split("/")[2] for i in all_submissions]
for i in time_stamp:
if i[2] == '-':
time_stamp[time_stamp.index(i)] = datetime.datetime.strptime(i, "%H-%M-%S-%m-%d-%Y")
else:
time_stamp[time_stamp.index(i)] = datetime.datetime.strptime(i, "%Y-%m-%d-%H-%M-%S")
# sort need to work by date time
all_submissions = [x for _, x in sorted(zip(time_stamp, all_submissions))] # sort submission list by time submitted
cbc_code = [x for _, x in sorted(zip(time_stamp, cbc_code))] # sort submission list by time submitted
all_submissions = [i for i in enumerate(zip(all_submissions, cbc_code))]
# Filter list by submissions already done
all_submissions = [i for i in all_submissions if i[1][0] not in done_submissions["Submission_S3_Path"].tolist()]
#print(all_submissions)
# all_submissions = [i for i in all_submissions if "CBC02" in i[1][0]]
except Exception as e:
all_submissions = []
error_msg.append(str(e))
#display_error_line(e)
raise(e)
############################################################################################################################
master_dict = {} # dictionary for all submissions labeled as create
update_dict = {} # dictionary for all submissions labeled as update
# all_submissions = [(99, done_submissions["Submission_S3_Path"].tolist()[99])]
# all_submissions = all_submissions[-5:]
try:
i = 1
for curr_sub in all_submissions:
try:
#index = curr_sub[0]# + 1
index = max(done_submissions["Submission_Index"].tolist()) + i
i += 1
except Exception as e:
error_msg.append(str(e))
display_error_line(e)
folder_path, folder_tail = os.path.split(curr_sub[1][0])
file_name = curr_sub[1][0].split("/")
folders = s3_client.list_objects_v2(Bucket=bucket_name, Prefix=folder_path)["Contents"]
print(f"\nWorking on Submision #{index}: {file_name[1]}: {file_name[2]} \n {file_name[3]}")
success_msg.append(f"Working on Submision #{index}: {file_name[1]}: {file_name[2]} {file_name[3]}")
error_msg.append(f"Working on Submision #{index}: {file_name[1]}: {file_name[2]} {file_name[3]}")
upload_date, intent, sub_name = get_upload_info(s3_client, bucket_name, curr_sub, sub_folder) # get submission info
if intent == "Create":
master_dict = get_tables_to_load(s3_client, bucket_name, folders, curr_sub, conn, sub_name, index, upload_date, intent, master_dict, data_release)
elif intent == "Update":
update_dict = get_tables_to_load(s3_client, bucket_name, folders, curr_sub, conn, sub_name, index, upload_date, intent, update_dict, data_release)
else:
print(f"Submission Intent: {intent} is not valid")
master_dict = fix_aliquot_ids(master_dict, "last", sql_column_df)
update_dict = fix_aliquot_ids(update_dict, "last", sql_column_df)
master_data_dict = get_master_dict(master_dict, update_dict, sql_column_df, sql_table_dict)
#if "baseline_visit_date.csv" in master_data_dict and "baseline.csv" in master_data_dict:
# x = master_data_dict["baseline_visit_date.csv"]["Data_Table"]
# x.rename(columns={"Sunday_Of_Week": "Sunday_Prior_To_First_Visit"}, inplace=True)
# x["Sunday_Prior_To_First_Visit"] = pd.to_datetime(x["Sunday_Prior_To_First_Visit"])#
#
# for curr_part in x.index:
# sql_qry = (f"update Participant set Sunday_Prior_To_First_Visit = '{x['Sunday_Prior_To_First_Visit'][curr_part].date()}' " +
# f"where Research_Participant_ID = '{x['Research_Participant_ID'][curr_part]}'")
# engine.execute(sql_qry)
# conn.connection.commit()
#
# y = master_data_dict["baseline.csv"]
# y = master_data_dict["baseline.csv"]["Data_Table"]
# master_data_dict["baseline.csv"]["Data_Table"] = y.merge(x[["Research_Participant_ID","Sunday_Prior_To_First_Visit"]])
# master_data_dict = {"baseline.csv": master_data_dict["baseline.csv"]}
if "baseline.csv" in master_data_dict:
master_data_dict = update_obesity_values(master_data_dict)
x = master_dict['baseline.csv']["Data_Table"]
#x = x.query("Age > 0")
master_dict['baseline.csv']["Data_Table"] = x.drop_duplicates('Research_Participant_ID')
if "covid_vaccination_status.csv" in master_data_dict:
x = master_dict["covid_vaccination_status.csv"]["Data_Table"]
x.sort_values(["Research_Participant_ID", "Vaccination_Status", "Submission_Index"], inplace=True)
# x = x.query("Age > 0")
master_dict["covid_vaccination_status.csv"]["Data_Table"] = x
if "treatment_history.csv" in master_data_dict and "treatment_history_prov.csv" in master_data_dict:
tbase = master_dict["treatment_history.csv"]["Data_Table"]
tprov = master_dict["treatment_history_prov.csv"]["Data_Table"]
tbase.replace("Baseline(1)", "1", inplace=True)
tprov.replace("Baseline(1)", "1", inplace=True)
tprov.drop(["Comments", "Submission_Index", "Submission_CBC"], axis=1, inplace=True)
tbase = tbase.merge(tprov, how="left")
tbase.drop_duplicates(inplace=True)
master_dict["treatment_history.csv"]["Data_Table"] = tbase
if "cancer_cohort.csv" in master_data_dict and "cancer_cohort_prov.csv" in master_data_dict:
cbase = master_dict["cancer_cohort.csv"]["Data_Table"]
cprov = master_dict["cancer_cohort_prov.csv"]["Data_Table"]
cbase.replace("Baseline(1)", "1", inplace=True)
cprov.replace("Baseline(1)", "1", inplace=True)
cprov = cprov[['Research_Participant_ID', 'Cohort', 'Visit_Number', 'Cancer_Provenance']]
cbase = cbase.merge(cprov, how="left")
cbase.drop_duplicates(inplace=True)
master_dict["cancer_cohort.csv"]["Data_Table"] = cbase
#if study_type == "Vaccine_Response":
# cohort_file = r"C:\Users\breadsp2\Downloads\Release_1.0.0_by_cohort.xlsx"
# x = pd.read_excel(cohort_file)
# visit_table = pd.read_sql(("SELECT * FROM `seronetdb-Vaccine_Response`.Participant_Visit_Info;"), sql_tuple[1])
# x.drop("CBC", axis=1, inplace=True)
# visit_table.rename(columns={"Cohort": "CBC_Grouping"}, inplace=True)
# y = visit_table.merge(x)
# update_tables(conn, engine, ["Visit_Info_ID"], y, "Participant_Visit_Info")
if Update_Assay_Data is True:
master_data_dict = upload_assay_data(master_data_dict, bucket_name, s3_client)
if Update_Study_Design is True:
master_data_dict["study_design.csv"] = {"Data_Table": []}
#master_data_dict["study_design.csv"]["Data_Table"] = get_box_data_v2.get_study_design()
master_data_dict["study_design.csv"]["Data_Table"] = get_study_design(s3_client, bucket_name)
if Update_BSI_Tables is True:
master_data_dict = get_bsi_files(s3_client, bucket_name, sub_folder, master_data_dict)
if "secondary_confirmation_test_result.csv" in master_data_dict:
master_data_dict = update_secondary_confirm(master_data_dict, sql_column_df)
if "Add_Blinded_Results" in kwargs:
eval_data = []
if kwargs["Add_Blinded_Results"] is True:
success_msg.append("## The blinded result data has been updated")
#bucket = "nci-cbiit-seronet-submissions-passed"
bucket = bucket_name
key = "Serology_Data_Files/Reference_Panel_Files/Reference_Panel_Submissions/"
resp = s3_client.list_objects_v2(Bucket=bucket, Prefix=key)
for curr_file in resp["Contents"]:
try:
if "blinded_validation_panel_results_example" in curr_file["Key"]: #testing file, ignore
continue
elif ".xlsx" in curr_file["Key"]:
obj = s3_client.get_object(Bucket=bucket, Key= curr_file["Key"])
x = pd.read_excel(obj['Body'].read(), engine='openpyxl') # 'Body' is a key word
#x = pd_s3.get_df_from_keys(s3_client, bucket, curr_file["Key"], suffix="xlsx",
#format="xlsx", na_filter=False, output_type="pandas")
elif ".csv" in curr_file["Key"]:
obj = s3_client.get_object(Bucket=bucket, Key= curr_file["Key"])
x = pd.read_csv(obj['Body'])
#x = pd_s3.get_df_from_keys(s3_client, bucket, curr_file["Key"], suffix="csv",
#format="csv", na_filter=False, output_type="pandas")
else:
continue
if len(eval_data) == 0:
eval_data = x
else:
eval_data = pd.concat([eval_data, x])
except Exception as e:
error_msg.append(str(e))
display_error_line(e)
eval_data.reset_index(inplace=True, drop=True)
sub_id = eval_data.loc[eval_data['Subaliquot_ID'].str.contains('FD|FS')]
bsi_id = eval_data.loc[~eval_data['Subaliquot_ID'].str.contains('FD|FS')]
sub_id.rename(columns={'Subaliquot_ID': "CGR_Aliquot_ID"}, inplace=True)
child_data = pd.read_sql(("SELECT Biorepository_ID, Subaliquot_ID, CGR_Aliquot_ID FROM BSI_Child_Aliquots"), conn)
eval_data = pd.concat([sub_id.merge(child_data), bsi_id.merge(child_data)])
master_data_dict = add_assay_to_dict(master_data_dict, "Blinded_Evaluation_Panels.csv", eval_data)
if "update_CDC_tables" in kwargs:
if kwargs["update_CDC_tables"] is True:
#bucket = "nci-cbiit-seronet-submissions-passed"
bucket = bucket_name
key = "Serology_Data_Files/CDC_Confirmation_Results/"
resp = s3_client.list_objects_v2(Bucket=bucket, Prefix=key)
CDC_data_IgG = pd.DataFrame()
CDC_data_IgM = pd.DataFrame()
for curr_file in resp["Contents"]:
# curr_file = get_recent_date(resp["Contents"])
try:
if ".xlsx" in curr_file["Key"]:
file_date = curr_file["Key"][-13:-5]
CDC_data_IgG = create_CDC_data(s3_client, bucket, curr_file, "IgG", CDC_data_IgG, file_date)
CDC_data_IgM = create_CDC_data(s3_client, bucket, curr_file, "IgM", CDC_data_IgM, file_date)
except Exception as e:
error_msg.append(str(e))
display_error_line(e)
CDC_Data = pd.concat([CDC_data_IgM, CDC_data_IgG])
CDC_Data["BSI_Parent_ID"] = [i[:7] + " 0001" for i in CDC_Data["Patient ID"].tolist()]
master_data_dict = add_assay_to_dict(master_data_dict, "CDC_Data.csv", CDC_Data)
if len(master_data_dict) > 0:
valid_files = [i for i in sql_table_dict if "_sql.csv" not in i]
valid_files = [i for i in valid_files if i in master_data_dict]
filtered_tables = [value for key, value in sql_table_dict.items() if key in valid_files]
tables_to_check = list(set([item for sublist in filtered_tables for item in sublist]))
#print(master_data_dict['assay_data.csv']['Data_Table'].keys())
# master_data_dict = {"submission.csv": master_data_dict["submission.csv"]}
if "covid_history.csv" in master_data_dict:
master_data_dict = check_decision_tree(master_data_dict)
error_length = len(error_msg)
add_tables_to_database(engine, conn, sql_table_dict, sql_column_df, master_data_dict, tables_to_check, [])
if len(error_msg) == error_length: #if the function does not generate new errors
conn.connection.commit()
else:
print("roll back")
conn.connection.rollback()
except Exception as e:
display_error_line(e)
error_msg.append(str(e))
# update_norm_cancer(conn, engine)
return sql_table_dict, all_submissions
def create_CDC_data(s3_client, bucket, curr_file, sheet, df, file_date):
obj = s3_client.get_object(Bucket=bucket, Key= curr_file["Key"])
x = pd.read_excel(obj['Body'].read(), sheet_name=sheet, engine='openpyxl')
#x = pd_s3.get_df_from_keys(s3_client, bucket, curr_file["Key"], suffix="xlsx",
#format="xlsx", na_filter=False, output_type="pandas", sheet_name=sheet)
x["file_date"] = file_date
x["Measurand_Antibody"] = sheet
x["Patient ID"] = [i.replace(" 9002", "") for i in x["Patient ID"]]
df = pd.concat([df, x])
df.drop_duplicates(["Patient ID"], inplace=True, keep='last')
return df
def display_error_line(ex):
trace = []
tb = ex.__traceback__
while tb is not None:
trace.append({"filename": tb.tb_frame.f_code.co_filename,
"name": tb.tb_frame.f_code.co_name,
"lineno": tb.tb_lineno})
tb = tb.tb_next
print(str({'type': type(ex).__name__, 'message': str(ex), 'trace': trace}))
def get_recent_date(files):
curr_date = (files[0]["LastModified"]).replace(tzinfo=None)
index = -1
for file in files:
index = index + 1
if (file["LastModified"]).replace(tzinfo=None) > curr_date:
curr_date = (file["LastModified"]).replace(tzinfo=None)
curr_value = index
return files[curr_value]["Key"]
def get_kwarg_parms(update_str, kwargs):
if update_str in kwargs:
Update_Table = kwargs[update_str]
else:
Update_Table = False
return Update_Table
def check_decision_tree(master_data_dict):
data_table = master_data_dict["covid_history.csv"]["Data_Table"]
data_table.replace("No COVID Event Reported", "No COVID event reported", inplace=True)
no_covid_data = data_table.query("COVID_Status in ['No COVID event reported', 'No COVID data collected']")
pos_data = data_table[data_table["COVID_Status"].str.contains("Positive")] # samples that contain at least 1 positive
neg_data = data_table[data_table["COVID_Status"].str.contains("Negative")]
neg_data = neg_data[~neg_data["COVID_Status"].str.contains("Positive")] # samples that are all negative
no_covid_data = set_col_vals(no_covid_data, "N/A", "N/A", "N/A", 'Not Reported', 'N/A')
neg_data = set_col_vals(neg_data, "N/A", "N/A", "N/A", 0, 'N/A')
pos_data["SARS-CoV-2_Variant"] = pos_data["SARS-CoV-2_Variant"].replace("Unavailable", "Unknown")
pos_data["SARS-CoV-2_Variant"] = pos_data["SARS-CoV-2_Variant"].replace("N/A", "Unknown")
pos_yes_sys = pos_data.query("Symptomatic_COVID == 'Yes'")
pos_no_sys = pos_data.query("Symptomatic_COVID == 'No'")
pos_ukn_sys = pos_data.query("Symptomatic_COVID == 'Unknown'")
pos_no_sys = set_col_vals(pos_no_sys, True, True, "No", 1, 'N/A') # value of true means keep same
pos_ukn_sys = set_col_vals(pos_ukn_sys, True, True, "Unknown", True, 'No symptoms reported') # value of true means keep same
data_table_2 = pd.concat([pos_yes_sys, pos_no_sys, pos_ukn_sys, neg_data, no_covid_data])
master_data_dict["covid_history.csv"]["Data_Table"] = data_table_2
return master_data_dict
def set_col_vals(df_data, breakthrough, variant, covid, disease, symptoms):
if breakthrough is not True:
df_data["Breakthrough_COVID"] = breakthrough
if variant is not True:
df_data["SARS-CoV-2_Variant"] = variant
if covid is not True:
df_data["Symptomatic_COVID"] = covid
if disease is not True:
df_data["Disease_Severity"] = disease
if symptoms is not True:
df_data["Symptoms"] = symptoms
return df_data
def get_all_submissions(s3_client, bucket_name, sub_folder, cbc_name, cbc_id, all_submissions, cbc_code):
global error_msg
""" scans the buceket name and provides a list of all files paths found """
uni_submissions = []
Prefix=sub_folder + "/" + cbc_name
try:
key_list = s3_client.list_objects(Bucket=bucket_name, Prefix=sub_folder + "/" + cbc_name)
if 'Contents' in key_list:
key_list = key_list["Contents"]
key_list = [i["Key"] for i in key_list if ("UnZipped_Files" in i["Key"])]
file_parts = [os.path.split(i)[0] for i in key_list]
file_parts = [i for i in file_parts if "test/" not in i[0:5]]
file_parts = [i for i in file_parts if "Submissions_in_Review" not in i]
uni_submissions = list(set(file_parts))
else:
uni_submissions = [] # no submissions found for given cbc
except Exception as e:
error_msg.append(str(e))
print("Erorr found")
finally:
cbc_code = cbc_code + [str(cbc_id)]*len(uni_submissions)
return all_submissions + uni_submissions, cbc_code
def get_cbc_id(conn, cbc_name):
cbc_table = pd.read_sql("Select * FROM CBC", conn)
cbc_table = cbc_table.query("CBC_Name == @cbc_name")
cbc_id = cbc_table["CBC_ID"].tolist()
return cbc_id[0]
def get_sql_info(conn, sql_table, sql_column_df):
col_names = sql_column_df.query("Table_Name==@sql_table")
prim_key = col_names.query("Primary_Key == 'True' and Var_Type not in ['INTEGER', 'FLOAT']")
sql_df = pd.read_sql(f"Select * FROM {sql_table}", conn)
sql_df = sql_timestamp(sql_df, sql_column_df)
primary_keys = prim_key["Column_Name"].tolist()
return primary_keys, col_names, sql_df
def clean_tube_names(curr_table):
curr_cols = curr_table.columns.tolist()
curr_cols = [i.replace("Collection_Tube", "Tube") for i in curr_cols]
curr_cols = [i.replace("Aliquot_Tube", "Tube") for i in curr_cols]
# curr_cols = [i.replace("Tube_Type_Expiration_", "Tube_Lot_Expiration_") for i in curr_cols]
curr_cols = [i.replace("Biospecimen_Company", "Biospecimen_Collection_Company") for i in curr_cols]
curr_table.columns = curr_cols
curr_table["Tube_Type_Lot_Number"] = [str(i) for i in curr_table["Tube_Type_Lot_Number"]]
curr_table["Tube_Type_Catalog_Number"] = [str(i) for i in curr_table["Tube_Type_Catalog_Number"]]
return curr_table
def get_upload_info(s3_client, bucket_name, curr_sub, sub_folder):
# read the submission.csv and return info
file_sep = os.path.sep
if sub_folder in curr_sub[1][0]:
sub_obj = s3_client.list_objects_v2(Bucket=bucket_name, Prefix=curr_sub[1][0])
else:
sub_obj = s3_client.list_objects_v2(Bucket=bucket_name, Prefix=sub_folder + file_sep + curr_sub[1][0])
try:
upload_date = sub_obj["Contents"][0]["LastModified"]
upload_date = upload_date.replace(tzinfo=None) # removes timezone element from aws
except Exception:
upload_date = 0
submission_file = [i["Key"] for i in sub_obj["Contents"] if "submission.csv" in i["Key"]]
submission_file = submission_file[0]
obj = s3_client.get_object(Bucket=bucket_name, Key = submission_file)
curr_table = pd.read_csv(obj['Body'])
#curr_table = pd_s3.get_df_from_keys(s3_client, bucket_name, submission_file, suffix="csv", format="csv", na_filter=False, output_type="pandas")
intent = curr_table.iloc[3][1]
sub_name = curr_table.columns[1]
return upload_date, intent, sub_name
def get_tables_to_load(s3_client, bucket, folders, curr_sub, conn, sub_name, index, upload_date, intent, master_dict, data_release):
"""Takes current submission and gets all csv files into pandas tables """
files = [i["Key"] for i in folders if curr_sub[1][0] in i["Key"]]
files = [i for i in files if ".csv" in i]
data_dict = get_data_dict(s3_client, bucket, files, conn, curr_sub, sub_name, index, upload_date, intent, data_release)
if len(data_dict) > 0:
master_dict = combine_dictionaries(master_dict, data_dict)
return master_dict
def get_data_dict(s3_client, bucket, files, conn, curr_sub, sub_name, index, upload_date, intent, data_release):
data_dict = {}
global error_msg
for curr_file in files:
split_path = os.path.split(curr_file)
try:
if "study_design" in split_path[1]:
continue
elif "submission" in split_path[1]:
curr_table = populate_submission(conn, curr_sub, sub_name, index, upload_date, intent, data_dict)
else:
obj = s3_client.get_object(Bucket=bucket, Key = curr_file)
curr_table = pd.read_csv(obj['Body'])
#curr_table = pd_s3.get_df_from_keys(s3_client, bucket, split_path[0], suffix=split_path[1],
#format="csv", na_filter=False, output_type="pandas")
if "Age" in curr_table.columns:
err_idx = curr_table.query("Research_Participant_ID in ['14_M95508'] and Age in ['93', 93] or " +
"Research_Participant_ID in ['14_M80341'] and Age in ['96', 96]")
curr_table["Data_Release_Version"] = data_release
if len(err_idx) > 0:
curr_table = curr_table.drop(err_idx.index)
curr_table["Submission_Index"] = str(index)
curr_table = curr_table.loc[~(curr_table == '').all(axis=1)]
curr_table.rename(columns={"Cohort": "CBC_Classification"})
remove_ids = ['27_300089','27_300106','27_300168','27_300537','27_400094']
if 'Research_Participant_ID' in curr_table.columns:
curr_table = curr_table[curr_table["Research_Participant_ID"].str.contains('|'.join(remove_ids)) == False]
curr_table = curr_table.query("Research_Participant_ID != '' and Research_Participant_ID == Research_Participant_ID")
if 'Biospecimen_ID' in curr_table.columns:
curr_table = curr_table[curr_table["Biospecimen_ID"].str.contains('|'.join(remove_ids)) == False]
curr_table = curr_table.query("Biospecimen_ID != '' and Biospecimen_ID == Biospecimen_ID")
if 'Aliquot_ID' in curr_table.columns:
curr_table = curr_table[curr_table["Aliquot_ID"].str.contains('|'.join(remove_ids)) == False]
if "Cohort" in curr_table.columns:
curr_table["Cohort"].replace("Organ_Transplant", "Transplant", inplace=True)
curr_table["Cohort"].replace("Healthy_Control", "Healthy Control", inplace=True)
except Exception as e:
error_msg.append(str(e))
display_error_line(e)
#if split_path[1] == "northwell_treatment.csv" or split_path[1] == "treatment.csv":
# split_path = (split_path[0], "treatment_history.csv")
#if split_path[1] == "treatment.csv":
# split_path = (split_path[0], "treatment_history.csv")
if split_path[1] == "followup.csv":
split_path = (split_path[0], "follow_up.csv")
elif split_path[1] == "consumables.csv":
split_path = (split_path[0], "consumable.csv")
elif split_path[1] == "cancer_cohort.csv":
#some cancer durations were ogroanly reported in days then later converted to years
try:
curr_table["new_index"] = [ 0 if i == "Not Reported" else float(i) for i in curr_table["Year_Of_Diagnosis_Duration_From_Index"]]
except Exception as e:
print(e)
# curr_table = curr_table.query("new_index >= -50")
curr_table = clean_up_tables(curr_table)
curr_table["Submission_CBC"] = curr_sub[1][1]
if "secondary_confirmation" in split_path[1]:
data_dict["secondary_confirmation_test_result.csv"] = {"Data_Table": []}
data_dict["secondary_confirmation_test_result.csv"]["Data_Table"] = curr_table
else:
data_dict[split_path[1]] = {"Data_Table": []}
# curr_table.dropna(inplace=True)
data_dict[split_path[1]]["Data_Table"] = curr_table
return data_dict
def update_obesity_values(master_data_dict):
global error_msg
baseline = master_data_dict["baseline.csv"]["Data_Table"]
try:
baseline["BMI"] = baseline["BMI"].replace("Not Reported", -1e9)
baseline["BMI"] = baseline["BMI"].replace("N/A", -1e9)
baseline["BMI"] = [float(i) for i in baseline["BMI"]]
baseline.loc[baseline.query("BMI < 0").index, "Obesity"] = "Not Reported"
baseline.loc[baseline.query("BMI < 18.5 and BMI > 0").index, "Obesity"] = "Underweight"
baseline.loc[baseline.query("BMI >= 18.5 and BMI <= 24.9").index, "Obesity"] = "Normal Weight"
baseline.loc[baseline.query("BMI >= 25.0 and BMI <= 29.9").index, "Obesity"] = "Overweight"
baseline.loc[baseline.query("BMI >= 30.0 and BMI <= 34.9").index, "Obesity"] = "Class 1 Obesity"
baseline.loc[baseline.query("BMI >= 35.0 and BMI <= 39.9").index, "Obesity"] = "Class 2 Obesity"
baseline.loc[baseline.query("BMI >= 40").index, "Obesity"] = "Class 3 Obesity"
baseline["BMI"] = baseline["BMI"].replace(-1e9, np.nan)
except Exception as e:
error_msg.append(str(e))
display_error_line(e)
master_data_dict["baseline.csv"]["Data_Table"] = baseline
return master_data_dict
def add_error_flags(curr_table, err_idx):
if len(err_idx) > 0:
curr_table.loc[err_idx.index, "Error_Flag"] = "Yes"
return curr_table
def get_master_dict(master_data_dict, master_data_update, sql_column_df, sql_table_dict):
global error_msg
for key in master_data_dict.keys():
try:
table = sql_table_dict[key]
primary_key = sql_column_df.query(f"Table_Name == {table} and Primary_Key == 'True'")["Column_Name"].tolist()
except Exception:
primary_key = "Biospecimen_ID"
if key in ['shipping_manifest.csv']:
primary_key = 'Current Label'
if "Test_Result" in primary_key:
primary_key[primary_key.index("Test_Result")] = 'SARS_CoV_2_PCR_Test_Result'
if isinstance(primary_key, str):
primary_key = [primary_key]
if "Biospecimens_Collected" in primary_key:
primary_key.remove("Biospecimens_Collected")
if key in master_data_update.keys() | master_data_dict.keys():
try:
if key in master_data_dict and key in master_data_update:
x = pd.concat([master_data_dict[key]["Data_Table"], master_data_update[key]["Data_Table"]])
elif key in master_data_dict:
x = master_data_dict[key]["Data_Table"]
elif key in master_data_update:
x = master_data_update[key]["Data_Table"]
x.reset_index(inplace=True, drop=True)
x = correct_var_types(x, sql_column_df, table)
if "Cohort" in x.columns:
x = x.query("Cohort not in ('nan')")
part_list = list(set(x["Research_Participant_ID"]))
for curr_part in part_list:
if curr_part[:2] in ['41']:
pass
else:
test_id = x.query("Research_Participant_ID == @curr_part")
if len(list(set(test_id["Cohort"]))) == 1:
pass
else:
test_id["Submission_Index"] = [int(i) for i in test_id['Submission_Index']]
last_index = max([float(i) for i in test_id['Submission_Index']])
correct_cohort = list(set(test_id.query("Submission_Index == @last_index")["Cohort"]))
x["Cohort"][test_id.index] = correct_cohort[0]
if "Visit_Info_ID" in primary_key and "Visit_Info_ID" not in x.columns:
x, primary_key = add_visit_info(x, key, primary_key)
if key not in ["submission.csv"]:
primary_key = [i for i in primary_key if i in x.columns]
primary_key = list(set(primary_key))
if len(primary_key) > 0:
x["Submission_Index"] = [int(i) for i in x["Submission_Index"]]
x = x.sort_values(primary_key + ["Submission_Index"])
if key in ['shipping_manifest.csv']:
x = x.drop_duplicates(primary_key, keep='last')
else:
first_data = x.drop_duplicates(primary_key, keep='first')
last_data = x.drop_duplicates(primary_key, keep='last')
last_data.drop("Submission_Index", axis=1, inplace=True)
x = last_data.merge(first_data[primary_key + ["Submission_Index"]])
master_data_dict[key]["Data_Table"] = x
except Exception as e:
error_msg.append(str(e))
display_error_line(e)
for key in master_data_update.keys(): # key only in update
if key not in master_data_dict.keys():
master_data_dict[key] = master_data_update[key]
return master_data_dict
def add_visit_info(df, curr_file, primary_key):
if curr_file == "baseline.csv":
df['Type_Of_Visit'] = "Baseline"
df['Visit_Number'] = "1"
df['Unscheduled_Visit'] = "No"
#df['Type_Of_Visit'] = "MISPA"
#df['Visit_Number'] = "-1"
#df['Unscheduled_Visit'] = "Yes"
elif curr_file == "follow_up.csv":
df['Type_Of_Visit'] = "Follow_up"
base = df.query("Baseline_Visit == 'Yes'")
if len(base) > 0:
df.loc[base.index, "Type_Of_Visit"] = "Baseline"
else:
primary_key.append("Research_Participant_ID")
primary_key.append("Cohort")
primary_key.append("Visit_Number")
return df, primary_key
list_of_visits = list(range(1,20)) + [str(i) for i in list(range(1,20))] + [-1, '-1']
df["Visit_Info_ID"] = (df["Research_Participant_ID"] + " : " + [i[0] for i in df["Type_Of_Visit"]] +
["%02d" % (int(i),) if i in list_of_visits else i for i in df['Visit_Number']])
return df, primary_key
def convert_data_type(v, var_type):
if isinstance(v, datetime.datetime) and var_type.lower() == "datetime":
return v
if isinstance(v, datetime.date) and var_type.lower() == "date":
return v
if isinstance(v, datetime.time) and var_type.lower() == "time":
return v
if var_type == "VARCHAR(255)":
return v
if v == "Baseline(1)":
v = 1
if str(v).find('_') > 0:
return v
try:
float(v) # value is a number
if (float(v) * 10) % 10 == 0 or (float(v) * 10) % 10 == 0.0:
return int(float(v))
else:
return round(float(v), 5)
except ValueError:
try:
if var_type.lower() == "datetime":
return parse(v)
elif var_type.lower() == "date":
return parse(v).date()
except ValueError:
return v
def correct_var_types(data_table, sql_column_df, curr_table):
col_names = data_table.columns
for curr_col in col_names:
if "Derived_Result" in data_table.columns:
data_table = updated_derived(data_table)
z = sql_column_df.query("Column_Name == @curr_col and Table_Name == @curr_table").drop_duplicates("Column_Name")
if len(z) > 0:
var_type = z.iloc[0]["Var_Type"]
else:
var_type = "VARCHAR(255)"
if var_type in ['INTEGER', 'FLOAT', 'DOUBLE']:
data_table[curr_col].replace("N/A", np.nan, inplace=True)
if curr_col in ["Age", "Storage_Time_in_Mr_Frosty", "Biospecimen_Collection_to_Test_Duration", "BMI", "Derived_Result"]:
data_table = round_data(data_table, curr_col, 1)
if curr_col in ["Derived_Result"]:
data_table = round_data(data_table, curr_col, 3)
elif curr_col in ["Sample_Dilution"] and "Subaliquot_ID" in data_table.columns: # special formating for reference panel testing
data_table[curr_col].replace("none", "1", inplace=True) #no dilution is same as 1:1 dilution
data_table[curr_col] = [str(f"{Decimal(i):.2E}") for i in data_table[curr_col]]
elif "varchar" in var_type.lower():
data_table[curr_col] = [str(i) for i in data_table[curr_col]]
else:
data_table[curr_col] = [convert_data_type(c, var_type) for c in data_table[curr_col]]
return data_table
def round_data(data_table, test_col, round_unit):
for x in data_table.index:
try:
if data_table.loc[x, test_col] == "90+":
data_table.loc[x, test_col] = 90
curr_data = round(float(data_table.loc[x, test_col]), round_unit)
if (curr_data * 10) % 10 == 0.0:
curr_data = int(curr_data)
data_table.loc[x, test_col] = float(curr_data)
except Exception:
data_table.loc[x, test_col] = str(data_table.loc[x, test_col])
return data_table
def clean_up_tables(curr_table):
if "Submission_Index" in curr_table.columns:
x = curr_table.drop("Submission_Index", axis=1)
x.replace("", float("NaN"), inplace=True)
#x.dropna(axis=0, how="all", thresh=None, subset=None, inplace=True)
x.dropna(axis=0, how="all", subset=None, inplace=True)
z = curr_table["Submission_Index"].to_frame()
curr_table = x.merge(z, left_index=True, right_index=True)
else:
curr_table.dropna(axis=0, how="all", thresh=None, subset=None, inplace=True)
if len(curr_table) > 0:
missing_logic = curr_table.eq(curr_table.iloc[:, 0], axis=0).all(axis=1)
curr_table = curr_table[[i is not True for i in missing_logic]]
curr_table = curr_table.loc[:, ~curr_table .columns.str.startswith('Unnamed')]
for iterC in curr_table.columns:
try:
curr_table[iterC] = curr_table[iterC].apply(lambda x: x.replace('–', '-'))
except Exception:
pass
if "Comments" in curr_table.columns:
curr_table = curr_table.query("Comments not in ['Invalid data entry; do not include']")
return curr_table
def sql_timestamp(sql_df, sql_column_df):
new_list = sql_column_df.query("Var_Type == 'TIME'")
for i in new_list["Column_Name"].tolist():
if i in sql_df.columns.tolist():
curr_col = sql_df[i]
for iterC in curr_col.index:
if (sql_df[i][iterC] == sql_df[i][iterC]) and (isinstance(sql_df[i][iterC], pd.Timedelta)):
hours = int((sql_df[i][iterC].seconds/60)/60)
minutes = int((sql_df[i][iterC].seconds % 3600)/60)
seconds = sql_df[i][iterC].seconds - (hours*3600 + minutes*60)
sql_df[i][iterC] = datetime.time(hours, minutes, seconds)
return sql_df
def populate_submission(conn, curr_sub, sub_name, index, upload_date, intent, data_dict):
x_name = pathlib.PurePath(curr_sub[1][0])
part_list = x_name.parts
try:
curr_time = datetime.datetime.strptime(part_list[2], "%H-%M-%S-%m-%d-%Y")
except Exception: # time stamp was corrected
curr_time = datetime.datetime.strptime(part_list[2], "%Y-%m-%d-%H-%M-%S")
cbc_id = get_cbc_id(conn, sub_name)
file_name = re.sub("submission_[0-9]{3}_", "", part_list[3])
sql_df = pd.DataFrame([[index, cbc_id, curr_time, sub_name, file_name, curr_sub[1][0], upload_date, intent]],
columns=["Submission_Index", "Submission_CBC_ID", "Submission_Time",
"Submission_CBC_Name", "Submission_File_Name", "Submission_S3_Path",
"Date_Submission_Validated", "Submission_Intent"])
return sql_df
def add_submission_data(data_dict, conn, csv_sheet):
sub_data = data_dict["submission.csv"]["Data_Table"]
curr_table = data_dict[csv_sheet]["Data_Table"]
curr_table["Submission_CBC"] = get_cbc_id(conn, sub_data.columns[1])
return curr_table
def combine_dictionaries(master_data_dict, data_dict):
global error_msg
for curr_file in data_dict:
try:
if curr_file not in master_data_dict:
master_data_dict[curr_file] = {"Data_Table": data_dict[curr_file]["Data_Table"]}
else:
x = pd.concat([master_data_dict[curr_file]["Data_Table"], data_dict[curr_file]["Data_Table"]],
axis=0, ignore_index=True).reset_index(drop=True)
master_data_dict[curr_file]["Data_Table"] = x
except Exception as e:
error_msg.append(str(e))
display_error_line(e)
return master_data_dict
def fix_aliquot_ids(master_data_dict, keep_order, sql_column_df):
if "aliquot.csv" in master_data_dict:
z = master_data_dict["aliquot.csv"]["Data_Table"]["Aliquot_ID"].tolist()
master_data_dict["aliquot.csv"]["Data_Table"]["Aliquot_ID"] = zero_pad_ids(z)
z = master_data_dict["aliquot.csv"]["Data_Table"]["Aliquot_Volume"].tolist()
z = [(i.replace("N/A", "0")) if isinstance(i, str) else i for i in z]
master_data_dict["aliquot.csv"]["Data_Table"]["Aliquot_Volume"] = z
z = master_data_dict["aliquot.csv"]["Data_Table"]
z.sort_values("Submission_Index", axis=0, ascending=True, inplace=True)
#z.drop_duplicates("Aliquot_ID", keep=keep_order, inplace=True)
master_data_dict["aliquot.csv"]["Data_Table"] = correct_var_types(z, sql_column_df, "Aliquot")
if "shipping_manifest.csv" in master_data_dict:
z = master_data_dict["shipping_manifest.csv"]["Data_Table"]
z['Current Label'] = z['Current Label'].fillna(value="0")
master_data_dict["shipping_manifest.csv"]["Data_Table"] = z.query("`Current Label` not in ['0']")
z = master_data_dict["shipping_manifest.csv"]["Data_Table"]["Current Label"].tolist()
master_data_dict["shipping_manifest.csv"]["Data_Table"]["Current Label"] = zero_pad_ids(z)
z = master_data_dict["shipping_manifest.csv"]["Data_Table"]["Volume"].tolist()
z = [(i.replace("N/A", "0")) if isinstance(i, str) else i for i in z]
master_data_dict["shipping_manifest.csv"]["Data_Table"]["Volume"] = z
z = master_data_dict["shipping_manifest.csv"]["Data_Table"]
z.sort_values("Submission_Index", axis=0, ascending=True, inplace=True)
#z.drop_duplicates("Current Label", keep=keep_order, inplace=True)
master_data_dict["shipping_manifest.csv"]["Data_Table"] = correct_var_types(z, sql_column_df, "Shipping_Manifest")
return master_data_dict
def zero_pad_ids(data_list):
global error_msg
try: