-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdata_loading.py
More file actions
3321 lines (2934 loc) · 186 KB
/
Copy pathdata_loading.py
File metadata and controls
3321 lines (2934 loc) · 186 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
from dbApp.models import (
DataSet, ReferenceSequence, DataSetSample, DataSetSampleSequence,
CladeCollection, DataSetSampleSequencePM)
import sys
import os
import shutil
import subprocess
import pandas as pd
import json
from collections import Counter
from django import db
from multiprocessing import Queue as mp_Queue, Manager, Process, Lock as mp_Lock
from threading import Lock as mt_Lock, Thread, get_ident
from queue import Queue as mt_Queue
from general import ThreadSafeGeneral, file_as_blockiter, hash_bytestr_iter
from datetime import datetime
import distance
from plotting import DistScatterPlotterSamples, SeqStackedBarPlotter
from symportal_utils import BlastnAnalysis, MothurAnalysis, NucleotideSequence
from output import SequenceCountTableCreator
import ntpath
import math
from numpy import NaN
from collections import defaultdict
import itertools
import time
from shutil import which
import sp_config
from django_general import CreateStudyAndAssociateUsers
import logging
import hashlib
from general import check_lat_lon
import re
from calendar import month_abbr, month_name
from psycopg2 import InterfaceError
class DataLoading:
# The clades refer to the phylogenetic divisions of the Symbiodiniaceae. Most of them are represented at the genera
# level. E.g. All members of clade C belong to the genus Cladocopium.
clade_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
def __init__(
self, parent_work_flow_obj, user_input_path, datasheet_path,
screen_sub_evalue, num_proc,no_fig, no_ord, no_output,
distance_method, no_pre_med_seqs, multiprocess, start_time, date_time_str, is_cron_loading,
study_name=None, study_user_string=None,
debug=False):
self.parent = parent_work_flow_obj
self.is_cron_loading = is_cron_loading
self.thread_safe_general = ThreadSafeGeneral()
# check and generate the sample_meta_info_df first before creating the DataSet object
self.sample_meta_info_df = None
self.user_input_path = user_input_path
self.datasheet_path = datasheet_path
self._check_mothur_version()
if self.datasheet_path:
self._create_and_check_datasheet()
self.symportal_root_directory = os.path.abspath(os.path.dirname(__file__))
self.dataset_object = None
# the stability file generated here is used as the base of the initial mothur QC
self.list_of_samples_names = []
self.list_of_fastq_files_in_wkd = []
self.sample_fastq_pairs = None
if self.datasheet_path:
self._get_sample_names_and_create_new_dataset_object_with_datasheet()
else:
end_index = self._get_sample_names_and_create_new_dataset_object_without_datasheet()
self.num_proc = min(num_proc, len(self.list_of_samples_names))
self.temp_working_directory = self._setup_temp_working_directory()
self.date_time_str = date_time_str
self.output_directory = self._setup_output_directory()
logging.basicConfig(format='%(levelname)s:%(message)s',
filename=os.path.join(self.output_directory, f'{self.date_time_str}_log.log'), filemode='w',
level=logging.INFO)
logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
# directory for the data_explorer outputs
self.html_dir = os.path.join(self.output_directory, 'html')
self.js_file_path = os.path.join(self.html_dir, 'study_data.js')
os.makedirs(self.html_dir, exist_ok=True)
# dictionary that will hold the outputfile type to full path of the outputfile
self.js_output_path_dict = {}
if self.datasheet_path:
self._generate_stability_file_and_data_set_sample_objects_with_datasheet()
else:
# Dictionary where sample name is value and seq file full paths in fwd, rev order are in list
self.sample_name_to_seq_files_dict = dict()
self._generate_stability_file_and_data_set_sample_objects_without_datasheet(end_index)
self.list_of_dss_objects = DataSetSample.objects.filter(data_submission_from=self.dataset_object)
if sp_config.system_type == 'remote':
csaau = CreateStudyAndAssociateUsers(
date_time_str=self.date_time_str, ds=self.dataset_object,
list_of_dss_objects=self.list_of_dss_objects, is_cron_loading=self.is_cron_loading,
study_name=study_name, study_user_string=study_user_string
)
csaau.create_study_and_user_objects()
self.study = csaau.study
self.output_path_list = []
self.no_fig = no_fig
self.no_ord = no_ord
self.no_output = no_output
self.distance_method = distance_method
self.no_pre_med_seqs = no_pre_med_seqs
# this is the path of the file we will use to deposit a backup copy of the reference sequences
self.seq_dump_file_path = self._setup_sequence_dump_file_path()
self.dataset_object.working_directory = self.temp_working_directory
self.dataset_object.save()
# This is the directory that sequences that have undergone QC for each sample will be written out as
# .names and .fasta pairs BEFORE MED decomposition
# We will delete the directory if it already exists
self.pre_med_sequence_output_directory_path = self._create_pre_med_write_out_directory_path()
# directory that will contain sub directories for each sample. Each sub directory will contain a pair of
# .names and .fasta files of the non_symbiodiniaceae_sequences that were thrown out for that sample
self.non_symb_and_size_violation_base_dir_path = os.path.join(
self.output_directory, 'non_sym_and_size_violation_sequences'
)
os.makedirs(self.non_symb_and_size_violation_base_dir_path, exist_ok=True)
# data can be loaded either as paired fastq or fastq.gz files or as a single compressed file containing
# the afore mentioned paired files.
self.is_single_file_or_paired_input = self._determine_if_single_file_or_paired_input()
self.debug = debug
self.symclade_db_directory_path = os.path.abspath(os.path.join(
self.symportal_root_directory, 'symbiodiniaceaeDB'))
self.symclade_db_full_path = os.path.join(self.symclade_db_directory_path, 'symClade.fa')
self.path_to_mothur_batch_file_for_dot_file_creation = None
self.path_to_latest_mothur_batch_file = None
self.samples_that_caused_errors_in_qc_list = []
self.initial_mothur_handler = None
self.post_initial_qc_name_file_name = None
self.post_initial_qc_fasta_file_name = None
# args for the taxonomic screening
self.screen_sub_evalue = screen_sub_evalue
self.new_seqs_added_in_iteration = 0
self.new_seqs_added_running_total = 0
self.checked_samples_with_no_additional_symbiodiniaceae_sequences = []
self.taxonomic_screening_handler = None
self.sequences_to_screen_fasta_as_list = []
self.sequences_to_screen_fasta_path = os.path.join(
self.temp_working_directory, 'taxa_screening_seqs_to_screen.fa'
)
# file names used for writing out
self.non_sym_fasta_file_name_str = None
self.non_sym_name_file_name_str = None
self.sym_fasta_file_name_str = None
self.sym_name_file_name_str = None
self.sym_binary_clade_dict_name_str = None
# the number of samples that a sub evalue sequences must be
# found in for us to carry it through for taxonomic screening
self.required_sample_support_for_sub_evalue_sequencs = 3
# the number of sequences in the 10 matches that must be annotated as Symbiodinium or Symbiodiniaceae in order
# for a sequences to be added into the reference symClade database.
self.required_symbiodiniaceae_matches = 3
# med
self.list_of_med_output_directories = []
self.path_to_med_padding_executable = os.path.join(
self.symportal_root_directory, 'lib/med_decompose/o_pad_with_gaps.py')
self.path_to_med_decompose_executable = os.path.join(
self.symportal_root_directory, 'lib/med_decompose/decompose.py')
self.perform_med_handler_instance = None
# data set sample creation
self.data_set_sample_creator_handler_instance = None
# plotting sequence output from both post-med and pre-med seq outputs
self.seq_abundance_relative_output_path_post_med = None
self.seq_abundance_relative_output_path_pre_med = None
self.seq_abund_relative_df_post_med = None
self.seq_abund_relative_df_pre_med = None
# we will use this sequence count table creator when outputting the pre_MED seqs so that the df
# can be put in the same order
self.sequence_count_table_creator = None
# we will use this sequence stacked bar plotter when plotting the pre_MED seqs so that the plotting
# can be put in the same order
self.seq_stacked_bar_plotter = None
# path to executable for multithreading the checking pre-MED sequences against existing ReferenceSequences
self.path_to_seq_match_executable = os.path.join(
self.symportal_root_directory, 'seq_match.py')
# Timers
# The timers for meausring how long it takes to create the DataSetSampleSequencePM
self.pre_med_seq_start_time = None
self.pre_med_seq_stop_time = None
self.multiprocess = multiprocess
self.start_time = start_time
def load_data(self):
self._copy_and_decompress_input_files_to_temp_wkd()
self._if_symclade_binaries_not_present_remake_db()
self._do_initial_mothur_qc()
self._taxonomic_screening()
self._do_med_decomposition()
self._create_data_set_sample_sequences_from_med_nodes()
if not self.no_pre_med_seqs:
self._create_data_set_sample_sequence_pre_med_objs()
else:
print('\n\nSkipping generation of pre med seq objects at users request\n\n')
self._print_sample_successful_or_failed_summary()
self._perform_sequence_drop()
self._delete_temp_dir__log_files_and_pre_med_dir()
self._write_data_set_info_to_stdout()
if not self.no_output:
self._output_seqs_count_table()
self._write_sym_non_sym_and_size_violation_dirs_to_stdout()
self._output_seqs_stacked_bar_plots()
self._do_sample_ordination()
# finally write out the dict that holds the output file paths for the DataExplorer
# covert the full paths to relative paths and then write out dict
# https://stackoverflow.com/questions/8693024/how-to-remove-a-path-prefix-in-python
new_dict = {}
for k, v in self.js_output_path_dict.items():
new_dict[k] = os.path.relpath(v, self.output_directory)
self.thread_safe_general.write_out_js_file_to_return_python_objs_as_js_objs(
[{'function_name': 'getDataFilePaths', 'python_obj': new_dict}],
js_outpath=self.js_file_path)
print('\n\nDATA LOADING COMPLETE')
print(f'DataSet id: {self.dataset_object.id}')
print(f'DataSet name: {self.dataset_object.name}')
self.dataset_object.loading_complete_time_stamp = str(
datetime.utcnow()).split('.')[0].replace('-','').replace(' ','T').replace(':','')
self.dataset_object.save()
print(f'Loading completed in {time.time() - self.start_time}s')
print(f'DataSet loading_complete_time_stamp: {self.dataset_object.loading_complete_time_stamp}\n\n\n')
print(f"Log written to {os.path.join(self.output_directory, f'{self.date_time_str}_log.log')}")
def _check_mothur_version(self):
mothur_version_cmd = subprocess.run(
['mothur', '-v'], stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
for line in self.thread_safe_general.decode_utf8_binary_to_list(mothur_version_cmd.stdout):
if "1.43" in line:
return
raise RuntimeError('SymPortal currently uses version 1.43 of mothur.\nCheck your version.')
def _make_new_dataset_object(self):
self.dataset_object = DataSet(
name=self.parent.args.name, time_stamp=self.parent.date_time_str,
reference_fasta_database_used=self.parent.reference_db,
submitting_user=self.parent.submitting_user,
submitting_user_email=self.parent.submitting_user_email)
self.dataset_object.save()
self.parent.data_set_object = self.dataset_object
def _write_sym_non_sym_and_size_violation_dirs_to_stdout(self):
if not self.no_pre_med_seqs:
print(f'\nPre-MED Symbiodiniaceae sequences written out to:\n'
f'{self.pre_med_sequence_output_directory_path}')
print(f'\nNon-Symbiodiniaceae and size violation sequences written out to:\n'
f'{self.non_symb_and_size_violation_base_dir_path}')
def _do_sample_ordination(self):
if not self.no_ord:
self._do_sample_dist_and_pcoa()
self._plot_pcoa()
def _plot_pcoa(self):
if not self.no_fig:
if len(self.list_of_samples_names) > 1000:
print(f'Too many samples ({len(self.list_of_samples_names)}) to generate plots')
else:
for output_path in self.output_path_list:
if self.this_is_pcoa_path(output_path):
clade_of_output = os.path.dirname(output_path).split('/')[-1]
sys.stdout.write(f'\n\nGenerating between sample distance plot clade {clade_of_output}\n')
try:
dist_scatter_plotter_samples = DistScatterPlotterSamples(csv_path=output_path,
date_time_str=self.date_time_str)
dist_scatter_plotter_samples.make_sample_dist_scatter_plot()
except RuntimeError:
# The error message is printed to stdout at the source
continue
self.output_path_list.extend(dist_scatter_plotter_samples.output_path_list)
def _do_sample_dist_and_pcoa(self):
print('\nCalculating between sample pairwise distances')
if self.distance_method == 'both':
if self._check_if_required_packages_found_in_path():
self._do_unifrac_dist_pcoa()
self._do_braycurtis_dist_pcoa()
else:
print('Changing distance method to braycurtis as one or more of the required '
'packages could not be found in your PATH')
self.distance_method = 'braycurtis'
if self.distance_method == 'unifrac':
self._do_unifrac_dist_pcoa()
elif self.distance_method == 'braycurtis':
self._do_braycurtis_dist_pcoa()
def _check_if_required_packages_found_in_path(self):
"""For creating unifrac-derived distances we need
both iqtree and mafft to be install in the users PATH.
Here we will check for them. If either of them are not found we will return False"""
return which('iqtree') and which('mafft')
def _write_data_set_info_to_stdout(self):
print(f'\n\nData loading complete. DataSet UID: {self.dataset_object.id}; Name: {self.dataset_object.name}')
@staticmethod
def this_is_pcoa_path(output_path):
return 'PCoA_coords' in output_path
def _do_braycurtis_dist_pcoa(self):
braycurtis_dist_pcoa_creator = distance.SampleBrayCurtisDistPCoACreator(
date_time_str=self.date_time_str,
data_set_uid_list=[self.dataset_object.id],
output_dir=self.output_directory, html_dir=self.html_dir,
js_output_path_dict=self.js_output_path_dict)
braycurtis_dist_pcoa_creator.compute_braycurtis_dists_and_pcoa_coords()
self.output_path_list.extend(braycurtis_dist_pcoa_creator.output_path_list)
def _do_unifrac_dist_pcoa(self):
unifrac_dict_pcoa_creator = distance.SampleUnifracDistPCoACreator(
date_time_str=self.date_time_str, output_dir=self.output_directory,
data_set_uid_list=[self.dataset_object.id], num_processors=self.num_proc,
html_dir=self.html_dir, js_output_path_dict=self.js_output_path_dict)
unifrac_dict_pcoa_creator.compute_unifrac_dists_and_pcoa_coords()
self.output_path_list.extend(unifrac_dict_pcoa_creator.output_path_list)
def _output_seqs_stacked_bar_plots(self):
"""Plot up the post- and pre-MED seqs as both .png and .svg"""
if not self.no_fig:
if len(self.list_of_samples_names) > 1000:
print(f'Too many samples ({len(self.list_of_samples_names)}) to generate plots')
else:
sys.stdout.write('\nGenerating sequence count table figures\n')
self.seq_stacked_bar_plotter = SeqStackedBarPlotter(
output_directory=self.output_directory,
seq_relative_abund_count_table_path_post_med=self.seq_abundance_relative_output_path_post_med,
no_pre_med_seqs=self.no_pre_med_seqs,
ordered_seq_list=self.sequence_count_table_creator.clade_abundance_ordered_ref_seq_list,
date_time_str=self.date_time_str,
seq_relative_abund_df_pre_med=self.seq_abund_relative_df_pre_med
)
self.seq_stacked_bar_plotter.plot_stacked_bar_seqs()
self.output_path_list.extend(self.seq_stacked_bar_plotter.output_path_list)
def _output_seqs_count_table(self):
sys.stdout.write('\nGenerating count tables for post- and pre-MED sequence abundances\n')
self.sequence_count_table_creator = SequenceCountTableCreator(
symportal_root_dir=self.symportal_root_directory, call_type='submission',
no_pre_med_seqs=self.no_pre_med_seqs, ds_uids_output_str=str(self.dataset_object.id),
num_proc=self.num_proc, date_time_str=self.date_time_str,
html_dir=self.html_dir,
js_output_path_dict=self.js_output_path_dict, multiprocess=self.multiprocess)
self.sequence_count_table_creator.make_seq_output_tables()
self.seq_abund_relative_df_post_med = self.sequence_count_table_creator.output_df_relative_post_med
self.output_path_list.extend(self.sequence_count_table_creator.output_paths_list)
self._set_seq_abundance_relative_output_path(self.sequence_count_table_creator)
self.seq_abund_relative_df_pre_med = self.sequence_count_table_creator.output_df_relative_pre_med
self.seq_abundance_relative_output_path_pre_med = self.sequence_count_table_creator.pre_med_relative_df_path
def _set_seq_abundance_relative_output_path(self, sequence_count_table_creator):
for path in sequence_count_table_creator.output_paths_list:
if 'relative.abund_and_meta' in path:
self.seq_abundance_relative_output_path_post_med = path
def _delete_temp_dir__log_files_and_pre_med_dir(self):
if os.path.exists(self.temp_working_directory):
shutil.rmtree(self.temp_working_directory)
# Delete any log files that are found anywhere in the SymPortal directory
subprocess.run(f'find {self.symportal_root_directory} -name "*.logfile" -delete', shell=True, check=True)
# Delete the pre_med_seq directories holding the .fasta and .names pairs
# as this information is now stored in the database and output in a count table.
# This directory will be remade if outputs are being made
if os.path.exists(self.pre_med_sequence_output_directory_path):
shutil.rmtree(self.pre_med_sequence_output_directory_path)
def _perform_sequence_drop(self):
sequence_drop_file = self._generate_sequence_drop_file()
sys.stdout.write(f'\n\nBackup of named reference_sequences output to {self.seq_dump_file_path}\n')
self.thread_safe_general.write_list_to_destination(self.seq_dump_file_path, sequence_drop_file)
@staticmethod
def _generate_sequence_drop_file():
header_string = ','.join(['seq_name', 'seq_uid', 'seq_clade', 'seq_sequence'])
sequence_drop_list = [header_string]
for ref_seq in ReferenceSequence.objects.filter(has_name=True):
sequence_drop_list.append(','.join([ref_seq.name, str(ref_seq.id), ref_seq.clade, ref_seq.sequence]))
return sequence_drop_list
def _print_sample_successful_or_failed_summary(self):
logging.info('SAMPLE PROCESSING SUMMARY')
failed_count = 0
successful_count = 0
for data_set_sample in DataSetSample.objects.filter(data_submission_from=self.dataset_object):
if data_set_sample.error_in_processing:
failed_count += 1
logging.info(f'{data_set_sample.name}: Error in processing: {data_set_sample.error_reason}')
else:
successful_count += 1
logging.info(f'{data_set_sample.name}: Successful')
logging.info(f'\n\n{successful_count} out of {successful_count + failed_count} '
f'samples successfully passed QC.\n'
f'{failed_count} samples produced errors\n')
def _create_data_set_sample_sequences_from_med_nodes(self):
self.data_set_sample_creator_handler_instance = DataSetSampleCreatorHandler()
self.data_set_sample_creator_handler_instance.execute_data_set_sample_creation(
data_loading_list_of_med_output_directories=self.list_of_med_output_directories,
data_loading_debug=self.debug, data_loading_dataset_object=self.dataset_object)
self.dataset_object.currently_being_processed = False
self.dataset_object.save()
def _create_data_set_sample_sequence_pre_med_objs(self):
print('\n\nCreating DataSetSampleSequencePM objects')
self.pre_med_seq_start_time = time.time()
data_set_sample_pre_med_obj_creator = FastDataSetSampleSequencePMCreator(
dataset_object=self.dataset_object,
pre_med_sequence_output_directory_path=self.pre_med_sequence_output_directory_path,
num_proc=self.num_proc, path_to_seq_match_executable=self.path_to_seq_match_executable,
temp_working_directory=self.temp_working_directory)
data_set_sample_pre_med_obj_creator.make_data_set_sample_pm_objects()
self.pre_med_seq_stop_time = time.time()
print(f'\n\nCreation of DataSetSampleSequencePM objects took '
f'{self.pre_med_seq_stop_time-self.pre_med_seq_start_time}s')
def _do_med_decomposition(self):
self.perform_med_handler_instance = PerformMEDHandler(
data_loading_temp_working_directory=self.temp_working_directory,
data_loading_num_proc=self.num_proc,
multiprocess=self.multiprocess)
self.perform_med_handler_instance.execute_perform_med_worker(
data_loading_debug=self.debug,
data_loading_path_to_med_decompose_executable=self.path_to_med_decompose_executable,
data_loading_path_to_med_padding_executable=self.path_to_med_padding_executable)
self.list_of_med_output_directories = self.perform_med_handler_instance.list_of_med_result_dirs
if self.debug:
print('MED dirs:')
for med_output_directory in self.list_of_med_output_directories:
print(med_output_directory)
def _do_initial_mothur_qc(self):
if not self.sample_fastq_pairs:
self._exit_and_del_data_set_sample('Sample fastq pairs list empty')
self.initial_mothur_handler = InitialMothurHandler(data_loading_parent=self)
self.initial_mothur_handler.execute_worker_initial_mothur()
self.samples_that_caused_errors_in_qc_list = list(
self.initial_mothur_handler.samples_that_caused_errors_in_qc_mp_list)
def _taxonomic_screening(self):
"""
There are only two things to achieve as part of this taxonomy screening.
1 - identify the sequences that are Symbiodinium/Symbiodiniaceae in origin
2 - identify the sequences that are non-Symbiodinium/non-Symbiodiniaceae in origin.
This may sound very straight forwards: Blast each sequence against a reference database and if we get
a good enough match, consider this sequence symbiodiniaceae in origin. If not, not.
BUT, there is a catch. We cannot be sure that every new sequence that we receive is not symbiodiniaceae just
because we don't get a good match to our reference database. It may be that new diversity is not yet
represented in our reference database.
As a results of this we want to do an extra set of taxonomic screening and that is what this first part of code
concerns. We will run a blast against our reference symClade database. And then, any seuqences that return
a match to a member of this database, but does not meet the minimum threshold to be directly considered
Symbiodinium in origin (i.e. not similar enough to a reference sequence in the symClade database) will
be blasted against the NCBI nt blast database. For a sequence to be blasted against this database, and be
in contesion for being considered symbiodiniaceae in origin it must also be found in at least three samples.
We will use an iterative screening process to acheive this symbiodiniaceae identification. The sequences to be
screened will be referred to as subevalue sequences. Any of these sequences that we deem symbiodiniaceae in
origin after running against the nt database will be added back into the symClade reference database.
On the next iteration it will therefore be possible for differnt sequences to be matches given that additional
sequences may have been added to this reference database. This first part of screening will only be to run
the symClade blast, and to screen low identity matches. Non-symbiodiniaceae sequence matches will be made in
the second part of this screening.
To make this faster, rather than check every sample in every iteration we will keep track of when a sample
has been found to only contain sequences that are good matches to the symClade database.
This way we can skip these sequences in the iterative rounds of screening.
"""
if self.screen_sub_evalue:
if not len(self.samples_that_caused_errors_in_qc_list) == self.list_of_samples_names:
self._create_symclade_backup_incase_of_accidental_deletion_of_corruption()
while 1:
self.new_seqs_added_in_iteration = 0
# This method simply identifies whether there are sequences that need screening.
# Everytime that the execute_worker is run it pickles out the files needed for the next worker
self._make_fasta_of_sequences_that_need_taxa_screening()
if self.sequences_to_screen_fasta_as_list:
# Now do the screening
# The outcome of this will be an updated symClade.fa that we should then make a blastdb from it.
self._screen_sub_e_seqs()
if self.new_seqs_added_in_iteration == 0:
break
else:
break
else:
# if not doing the screening we can simply run the execute_worker_taxa_screening once.
# During its run it will have output all of the files we need to run the following workers.
# We can also run the generate_and_write_below_evalue_fasta_for_screening function to write out a
# fasta of sub_evalue sequences we can then report to the user using that object
self._make_fasta_of_sequences_that_need_taxa_screening()
self._do_sym_non_sym_tax_screening()
def _do_sym_non_sym_tax_screening(self):
self.sym_non_sym_tax_screening_handler = SymNonSymTaxScreeningHandler(
data_loading_list_of_samples_names=self.list_of_samples_names,
data_loading_num_proc=self.num_proc,
data_loading_samples_that_caused_errors_in_qc_mp_list=self.samples_that_caused_errors_in_qc_list,
multiprocess=self.multiprocess, data_loading_dataset_object=self.dataset_object
)
self.sym_non_sym_tax_screening_handler.execute_sym_non_sym_tax_screening(
data_loading_temp_working_directory=self.temp_working_directory,
data_loading_pre_med_sequence_output_directory_path=self.pre_med_sequence_output_directory_path,
non_symb_and_size_violation_base_dir_path=self.non_symb_and_size_violation_base_dir_path,
data_loading_debug=self.debug
)
self.samples_that_caused_errors_in_qc_list = list(
self.sym_non_sym_tax_screening_handler.samples_that_caused_errors_in_qc_mp_list
)
def _screen_sub_e_seqs(self):
"""This function screens a fasta file to see if the sequences are Symbiodinium in origin.
This fasta file contains the below_e_cutoff sequences that need to be screened.
These sequences are the sequences
that were found to have a match in the initial screening against the symClade.fa database but were below
the required evalue cut off. Here we run these sequences against the entire NCBI 'nt' database to verify if they
or of Symbiodinium origin of not.
The fasta we are screening only contains seuqences that were found in at least 3 samples.
We will call a sequence symbiodiniaceae if it has a match that covers at least 95% of its sequence
at a 60% or higher
identity. It must also have Symbiodinium or Symbiodiniaceae in the name. We will also require that a
sub_e_value seq has at least the required_sybiodinium_matches (3 at the moment) before we call it Symbiodinium.
"""
blastn_analysis_object = BlastnAnalysis(
input_file_path=self.sequences_to_screen_fasta_path,
output_file_path=os.path.join(self.temp_working_directory, 'blast.out'),
max_target_seqs=10,
num_threads=str(self.num_proc), pipe_stdout_sterr=(not self.debug)
)
blastn_analysis_object.execute_blastn_analysis()
blast_output_dict = blastn_analysis_object.return_blast_results_dict()
query_sequences_verified_as_symbiodiniaceae_list = self._get_list_of_seqs_in_blast_result_that_are_symbiodiniaceae(
blast_output_dict
)
self.new_seqs_added_in_iteration = len(query_sequences_verified_as_symbiodiniaceae_list)
self.new_seqs_added_running_total += self.new_seqs_added_in_iteration
if query_sequences_verified_as_symbiodiniaceae_list:
self._taxa_screening_update_symclade_db_with_new_symbiodiniaceae_seqs(
query_sequences_verified_as_symbiodiniaceae_list)
def _taxa_screening_update_symclade_db_with_new_symbiodiniaceae_seqs(
self, query_sequences_verified_as_symbiodiniaceae_list):
new_symclade_fasta_as_list = self._taxa_screening_make_new_fasta_of_screened_seqs_to_be_added_to_symclade_db(
query_sequences_verified_as_symbiodiniaceae_list
)
combined_fasta = self._taxa_screening_combine_new_symclade_seqs_with_current(new_symclade_fasta_as_list)
self._taxa_screening_make_new_symclade_db(combined_fasta)
def _taxa_screening_make_new_symclade_db(self, combined_fasta):
self.thread_safe_general.write_list_to_destination(self.symclade_db_full_path, combined_fasta)
self.thread_safe_general.make_new_blast_db(
input_fasta_to_make_db_from=self.symclade_db_full_path, db_title='symClade')
def _taxa_screening_combine_new_symclade_seqs_with_current(self, new_symclade_fasta_as_list):
old_symclade_fasta_as_list = self.thread_safe_general.read_defined_file_to_list(self.symclade_db_full_path)
combined_fasta = new_symclade_fasta_as_list + old_symclade_fasta_as_list
return combined_fasta
def _taxa_screening_make_new_fasta_of_screened_seqs_to_be_added_to_symclade_db(
self, query_sequences_verified_as_symbiodiniaceae_list):
screened_seqs_fasta_dict = self.thread_safe_general.create_dict_from_fasta(
fasta_path=self.sequences_to_screen_fasta_path
)
new_symclade_fasta_as_list = []
for name_of_symbiodiniaceae_sequence_to_add_to_symclade_db in query_sequences_verified_as_symbiodiniaceae_list:
new_symclade_fasta_as_list.extend(
[
f'>{name_of_symbiodiniaceae_sequence_to_add_to_symclade_db}',
f'{screened_seqs_fasta_dict[name_of_symbiodiniaceae_sequence_to_add_to_symclade_db]}'
]
)
return new_symclade_fasta_as_list
def _get_list_of_seqs_in_blast_result_that_are_symbiodiniaceae(self, blast_output_dict):
query_sequences_verified_as_symbiodiniaceae_list = []
for query_sequence_name, blast_result_list_for_query_sequence in blast_output_dict.items():
sym_count = 0
for result_str in blast_result_list_for_query_sequence:
if 'Symbiodinium' in result_str or 'Symbiodiniaceae' in result_str:
percentage_coverage = float(result_str.split('\t')[4])
percentage_identity_match = float(result_str.split('\t')[3])
if percentage_coverage > 95 and percentage_identity_match > 60:
sym_count += 1
if sym_count == self.required_symbiodiniaceae_matches:
query_sequences_verified_as_symbiodiniaceae_list.append(query_sequence_name)
break
return query_sequences_verified_as_symbiodiniaceae_list
def _make_fasta_of_seqs_found_in_more_than_two_samples_that_need_screening(self):
""" The below_e_cutoff_dict has nucleotide sequencs as the
key and the number of samples that sequences was found in as the value.
"""
sub_evalue_nuclotide_sequence_to_number_of_samples_found_in_dict = dict(
self.taxonomic_screening_handler.sub_evalue_sequence_to_num_sampes_found_in_mp_dict)
self.sequences_to_screen_fasta_as_list = []
sequence_number_counter = 0
for nucleotide_sequence, num_samples_found_in in \
sub_evalue_nuclotide_sequence_to_number_of_samples_found_in_dict.items():
if num_samples_found_in >= self.required_sample_support_for_sub_evalue_sequencs:
# then this is a sequences that was found in three or more samples
clade_of_sequence = self.taxonomic_screening_handler.sub_evalue_nucleotide_sequence_to_clade_mp_dict[
nucleotide_sequence
]
self.sequences_to_screen_fasta_as_list.extend(
[
f'>sub_e_seq_count_{sequence_number_counter}_'
f'{self.dataset_object.id}_{num_samples_found_in}_'
f'{clade_of_sequence}',
nucleotide_sequence
]
)
sequence_number_counter += 1
if self.sequences_to_screen_fasta_as_list:
self.thread_safe_general.write_list_to_destination(
self.sequences_to_screen_fasta_path, self.sequences_to_screen_fasta_as_list)
def _create_symclade_backup_incase_of_accidental_deletion_of_corruption(self):
back_up_dir = os.path.abspath(os.path.join(self.symportal_root_directory, 'symbiodiniaceaeDB', 'symClade_backup'))
os.makedirs(back_up_dir, exist_ok=True)
symclade_current_path = os.path.abspath(
os.path.join(self.symportal_root_directory, 'symbiodiniaceaeDB', 'symClade.fa'))
symclade_backup_path = os.path.join(back_up_dir, f'symClade_{self.date_time_str}.fa')
symclade_backup_readme_path = os.path.join(back_up_dir, f'symClade_{self.date_time_str}.readme')
# then write a copy to it.
shutil.copy(symclade_current_path, symclade_backup_path)
# Then write out a very breif readme
read_me = [
f'This is a symClade.fa backup created during datasubmission of data_set ID: {self.dataset_object.id}']
self.thread_safe_general.write_list_to_destination(symclade_backup_readme_path, read_me)
def _make_fasta_of_sequences_that_need_taxa_screening(self):
self._init_potential_sym_tax_screen_handler()
# the self.taxonomic_screening_handler.sub_evalue_sequence_to_num_sampes_found_in_mp_dict is populated here
self.taxonomic_screening_handler.execute_potential_sym_tax_screening(
data_loading_temp_working_directory=self.temp_working_directory,
data_loading_path_to_symclade_db=self.symclade_db_full_path,
data_loading_debug=self.debug
)
self._taxa_screening_update_checked_samples_list()
self._make_fasta_of_seqs_found_in_more_than_two_samples_that_need_screening()
def _taxa_screening_update_checked_samples_list(self):
self.checked_samples_with_no_additional_symbiodiniaceae_sequences = \
list(self.taxonomic_screening_handler.checked_samples_mp_list)
def _init_potential_sym_tax_screen_handler(self):
self.taxonomic_screening_handler = PotentialSymTaxScreeningHandler(
samples_that_caused_errors_in_qc_list=self.samples_that_caused_errors_in_qc_list,
checked_samples_list=self.checked_samples_with_no_additional_symbiodiniaceae_sequences,
list_of_samples_names=self.list_of_samples_names, num_proc=self.num_proc, multiprocess=self.multiprocess
)
def _if_symclade_binaries_not_present_remake_db(self):
list_of_binaries_that_should_exist = [
self.dataset_object.reference_fasta_database_used + extension for extension in ['.nhr', '.nin', '.nsq']
]
contents_of_symclade_directory = os.listdir(self.symclade_db_directory_path)
binary_count = 0
for item in contents_of_symclade_directory:
if item in list_of_binaries_that_should_exist:
binary_count += 1
if binary_count != 3:
# then some of the binaries are not present and we need to remake the blast dictionary
if not self.debug:
self.thread_safe_general.make_new_blast_db(
input_fasta_to_make_db_from=self.symclade_db_full_path,
db_title='symClade', pipe_stdout_sterr=True)
elif self.debug:
self.thread_safe_general.make_new_blast_db(
input_fasta_to_make_db_from=self.symclade_db_full_path,
db_title='symClade', pipe_stdout_sterr=False)
# now verify that the binaries have been successfully created
list_of_dir = os.listdir(self.symclade_db_directory_path)
binary_count = 0
for item in list_of_dir:
if item in list_of_binaries_that_should_exist:
binary_count += 1
if binary_count != 3:
self._exit_and_del_data_set_sample('Failure in creating blast binaries')
def _get_sample_names_and_create_new_dataset_object_without_datasheet(self):
for file in os.listdir(self.user_input_path):
if file.endswith('fastq') or file.endswith('fq') or file.endswith('fastq.gz') or file.endswith('fq.gz'):
self.list_of_fastq_files_in_wkd.append(file)
if len(self.list_of_fastq_files_in_wkd) < 3:
raise RuntimeError(
f'Cannot auto infer names from {len(self.list_of_fastq_files_in_wkd)} fastq files. '
f'Please use a datasheet.')
end_index = self._identify_sample_names_without_datasheet()
self._make_new_dataset_object()
return end_index
def _generate_stability_file_and_data_set_sample_objects_without_datasheet(self, end_index):
self.make_dot_stability_file_inferred(end_index)
self._create_data_set_sample_objects_in_bulk_without_datasheet()
def make_dot_stability_file_inferred(self, end_index):
"""Search for the fastq files that contain the inferred sample names. NB this is not so simple
as names that are subset of other names will match more than one set of fastq files.
After identifying the sample direction, write absolute paths of each of the seq files
as though they are coming from the temp_working_directory. This is where the raw sequencing files
will be copied over to."""
print('\nDeducing read direction for the inferred sample names')
sample_fastq_pairs = []
for sample_name in self.list_of_samples_names:
print(f'Sample {sample_name}')
temp_list = [sample_name.replace('-', '[dS]')]
fwd_file_path = None
rev_file_path = None
for file_path in self.thread_safe_general.return_list_of_file_paths_in_directory(self.user_input_path):
if sample_name == ntpath.basename(file_path)[:-end_index]:
# When here we know which sample the file_path belongs to
# but we still need to deduce whether this is the fwd or rev read
# If R1 or R2 are in the read, then that is relatively easy
# But it may be that there is only a 1 or a 2 in the read.
# To test for this we will parse through each of the 1's or 2's
# and see if the partner read exists
# First search for the simple case of R1 or R2 being present.
if 'R1' in file_path or 'R2' in file_path:
if 'R1' in file_path:
fwd_file_path = file_path
self._print_sample_direction_path(direction='fwd', file_path=file_path)
if 'R2' in file_path:
rev_file_path = file_path
self._print_sample_direction_path(direction='rev', file_path=file_path)
else:
seq_direction_result = self._check_seq_file_path_for_seq_direction(file_path=file_path)
if seq_direction_result == 'rev':
rev_file_path = file_path
self._print_sample_direction_path(direction='rev', file_path=file_path)
elif seq_direction_result == 'fwd':
fwd_file_path = file_path
self._print_sample_direction_path(direction='fwd', file_path=file_path)
else:
raise RuntimeError(f'Unable to deduce read direction of {file_path}')
# if we have already found a fwd_file_path and rev_file_path
# then we can break out of the search
if fwd_file_path and rev_file_path:
break
# Only add the files to the sample_fastq_pairs if they are above the minium size requirement
# Check that both files meet the required minimum file size
if os.path.getsize(fwd_file_path) > 300 and os.path.getsize(rev_file_path) > 300:
# If so, add them to the dictionary
self.sample_name_to_seq_files_dict[sample_name] = [fwd_file_path, rev_file_path]
# Change the current paths so that they don't originate from the temp_working_directory
# path but rather from the temp working directory
fwd_file_path = os.path.join(self.temp_working_directory, ntpath.basename(fwd_file_path))
rev_file_path = os.path.join(self.temp_working_directory, ntpath.basename(rev_file_path))
temp_list.append(fwd_file_path)
temp_list.append(rev_file_path)
if None in temp_list:
raise RuntimeError(f'Error in deducing directionality of {sample_name}')
sample_fastq_pairs.append('\t'.join(temp_list))
else:
print(f'WARNING: At least one of the seq files for sample {sample_name} is less than 300 bytes in size')
print(f'{sample_name} will not be included in the dataloading')
# Reinit the list_of_samples_names so from the sample_name_to_seq_files_dict so that
# the samples that had files that were below the 300 byte size threshold are removed form the list
self.list_of_samples_names = list(self.sample_name_to_seq_files_dict.keys())
self.thread_safe_general.write_list_to_destination(
r'{0}/stability.files'.format(self.temp_working_directory), sample_fastq_pairs)
self.sample_fastq_pairs = sample_fastq_pairs
@staticmethod
def _check_seq_file_path_for_seq_direction(file_path):
""" This will try to deduce whether a given sequencing file is of a given direction"""
file_name_list = list(ntpath.basename(file_path))
# for each of the either '1' or '2' s in the file name
# swap them out for the opposite number and check to see if this
# file exists. If it does, then we assume that this is the '1' or '2' that we
# are investigating is the indicator of seq direction
for char_index, char_element in enumerate(reversed(file_name_list)):
if char_element == '1':
search_list = list(reversed(file_name_list))
search_list[char_index] = '2'
search_filename = ''.join(reversed(search_list))
search_path = os.path.join(os.path.dirname(file_path), search_filename)
if os.path.exists(search_path):
return 'fwd'
elif char_element == '2':
search_list = list(reversed(file_name_list))
search_list[char_index] = '1'
search_filename = ''.join(reversed(search_list))
search_path = os.path.join(os.path.dirname(file_path), search_filename)
if os.path.exists(search_path):
return 'rev'
return False
@staticmethod
def _print_sample_direction_path(direction, file_path):
if direction == 'fwd':
print(f'R1 = {file_path}')
else:
print(f'R2 = {file_path}')
def _create_data_set_sample_objects_in_bulk_without_datasheet(self):
list_of_sample_objects = []
sys.stdout.write('\nCreating data_set_sample objects\n')
for sampleName in self.list_of_samples_names:
print('\rCreating data_set_sample {}'.format(sampleName))
# Create the data_set_sample objects in bulk.
# The cladal_seq_totals property of the data_set_sample object keeps track of the seq totals for the
# sample divided by clade. This is used in the output to keep track of sequences that are not
# included in cladeCollections
clade_zeroes_list = [0 for _ in self.clade_list]
empty_cladal_seq_totals = json.dumps(clade_zeroes_list)
dss = DataSetSample(name=sampleName, data_submission_from=self.dataset_object,
cladal_seq_totals=empty_cladal_seq_totals)
list_of_sample_objects.append(dss)
# http://stackoverflow.com/questions/18383471/django-bulk-create-function-example
for dss_chunk in self.thread_safe_general.chunks(list_of_sample_objects):
DataSetSample.objects.bulk_create(dss_chunk)
def _get_num_chars_in_common_with_fastq_names(self):
i = 1
while 1:
list_of_endings = set()
for file in self.list_of_fastq_files_in_wkd:
list_of_endings.add(file[-i:])
if len(list_of_endings) > 2:
break
else:
i += 1
# then this is one i too many and our magic i was i-1
end_index = i - 1
return end_index
def _get_sample_names_from_fastq_files_using_index(self, end_index):
list_of_names_non_unique = []
for file in self.list_of_fastq_files_in_wkd:
list_of_names_non_unique.append(file[:-end_index])
list_of_sample_names = list(set(list_of_names_non_unique))
if len(list_of_sample_names) != len(self.list_of_fastq_files_in_wkd) / 2:
warning_str = 'Error in automatic sample name extraction. ' \
'Please explicitly supply sample names using a data sheet ' \
'(https://github.com/didillysquat/SymPortal_framework/wiki/Running-SymPortal#loading-data)'
sys.exit(warning_str)
self.list_of_samples_names = list_of_sample_names
def _identify_sample_names_without_datasheet(self):
# I think the simplest way to get sample names is to find what parts are common between all samples
# well actually 50% of the samples so that we also remove the R1 and R2 parts.
end_index = self._get_num_chars_in_common_with_fastq_names()
self._get_sample_names_from_fastq_files_using_index(end_index)
return end_index
def _get_sample_names_and_create_new_dataset_object_with_datasheet(self):
self.list_of_samples_names = self.sample_meta_info_df.index.values.tolist()
self._make_new_dataset_object()
def _generate_stability_file_and_data_set_sample_objects_with_datasheet(self):
# if we are given a data_sheet then use the sample names given as the DataSetSample object names
self.make_dot_stability_file_datasheet()
self._create_data_set_sample_objects_in_bulk_with_datasheet()
def make_dot_stability_file_datasheet(self):
"""Create the .stability file that mothur will use to make contigs.
This file is the sample name a tab, the fwd full path, a tab, the rev full path.
The paths should refer to the files that will have been copied over to the temp_working_directory.
As such the file paths will be the file name of the current file path value in the info_df
joined with the temp_working_directory."""
sample_fastq_pairs = []
for sample_name in self.sample_meta_info_df.index.values.tolist():
temp_list = [sample_name.replace('-', '[dS]')]
temp_list.append(
os.path.join(
self.temp_working_directory,
ntpath.basename(self.sample_meta_info_df.loc[sample_name, 'fastq_fwd_file_name'])
)
)
temp_list.append(
os.path.join(
self.temp_working_directory,
ntpath.basename(self.sample_meta_info_df.loc[sample_name, 'fastq_rev_file_name'])
)
)
sample_fastq_pairs.append('\t'.join(temp_list))
self.thread_safe_general.write_list_to_destination(
os.path.join(self.temp_working_directory, 'stability.files'), sample_fastq_pairs)
self.sample_fastq_pairs = sample_fastq_pairs
def _create_data_set_sample_objects_in_bulk_with_datasheet(self):
"""
The proper formatting of the values in the df should already have been taken care of. However, I will
leave the code in below as a safe guard to make sure that the DataSetSample objects can still be successfuly
created.
"""
list_of_data_set_sample_objects = []
sys.stdout.write('\nCreating data_set_sample objects\n')
for sampleName in self.list_of_samples_names:
print('\rCreating data_set_sample {}'.format(sampleName))
# Create the data_set_sample objects in bulk.
# The cladal_seq_totals property of the data_set_sample object keeps track of the seq totals for the
# sample divided by clade. This is used in the output to keep track of sequences that are not
# included in cladeCollections
empty_cladal_seq_totals = json.dumps([0 for _ in self.clade_list])
try:
sample_type = str(self.sample_meta_info_df.loc[sampleName, 'sample_type'])
host_phylum = str(self.sample_meta_info_df.loc[sampleName, 'host_phylum'])
host_class = str(self.sample_meta_info_df.loc[sampleName, 'host_class'])
host_order = str(self.sample_meta_info_df.loc[sampleName, 'host_order'])
host_family = str(self.sample_meta_info_df.loc[sampleName, 'host_family'])
host_genus = str(self.sample_meta_info_df.loc[sampleName, 'host_genus'])
host_species = str(self.sample_meta_info_df.loc[sampleName, 'host_species'])
collection_depth = str(self.sample_meta_info_df.loc[sampleName, 'collection_depth'])
collection_date = str(self.sample_meta_info_df.loc[sampleName, 'collection_date'])
except:
sample_type = 'NoData'
host_phylum = 'NoData'
host_class = 'NoData'
host_order = 'NoData'
host_family = 'NoData'
host_genus = 'NoData'
host_species = 'NoData'
collection_depth = 'NoData'
collection_date = 'NoData'
try:
collection_latitude = float(self.sample_meta_info_df.loc[sampleName, 'collection_latitude'])
collection_longitude = float(self.sample_meta_info_df.loc[sampleName, 'collection_longitude'])
if math.isnan(collection_latitude) or math.isnan(collection_longitude):
collection_latitude = float(999)
print('conversion problem with collection_latitude or collection_longitude, converting both to 999')
collection_longitude = float(999)
except:
print('conversion problem with collection_latitude or collection_longitude, converting both to 999')
collection_latitude = float(999)
collection_longitude = float(999)
# get the sha256 hash of the fastq.gz files
fwd_hash = hash_bytestr_iter(file_as_blockiter(open(self.sample_meta_info_df.loc[sampleName, 'fastq_fwd_file_name'], 'rb')), hashlib.sha256(), True)
rev_hash = hash_bytestr_iter(file_as_blockiter(open(self.sample_meta_info_df.loc[sampleName, 'fastq_rev_file_name'], 'rb')), hashlib.sha256(), True)
dss = DataSetSample(name=sampleName, data_submission_from=self.dataset_object,
cladal_seq_totals=empty_cladal_seq_totals,
sample_type=sample_type,
host_phylum=host_phylum,
host_class=host_class,
host_order=host_order,
host_family=host_family,
host_genus=host_genus,
host_species=host_species,
collection_latitude=collection_latitude,
collection_longitude=collection_longitude,
collection_date=collection_date,
collection_depth=collection_depth,