-
Notifications
You must be signed in to change notification settings - Fork 5
/
output.py
2550 lines (2208 loc) · 150 KB
/
output.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from dbApp.models import (DataSet, ReferenceSequence, DataSetSampleSequence, AnalysisType, DataSetSample,
DataAnalysis, DataSetSampleSequencePM, CladeCollectionType)
from multiprocessing import Queue as mp_Queue, Process, Manager, Lock as mp_Lock
from queue import Queue as mt_Queue
from threading import Thread, Lock as mt_Lock
import sys
from django import db
import os
import json
from collections import defaultdict
import pandas as pd
import numpy as np
import sp_config
import virtual_objects
from general import ThreadSafeGeneral
from exceptions import NoDataSetSampleSequencePMObjects
class OutputProfileCountTable:
def __init__(
self, num_proc, within_clade_cutoff, call_type, output_dir, html_dir, js_output_path_dict, date_time_str,
force_basal_lineage_separation,
data_set_uids_to_output=None, data_set_sample_uid_set_to_output=None,
data_analysis_obj=None, data_analysis_uid=None, virtual_object_manager=None):
self.force_basal_lineage_separation = force_basal_lineage_separation
self.thread_safe_general = ThreadSafeGeneral()
self.data_set_uid_set_to_output, self.data_set_sample_uid_set_to_output = self._init_dss_and_ds_uids(
data_set_sample_uid_set_to_output, data_set_uids_to_output)
self.data_analysis_obj = self._init_da_object(data_analysis_obj, data_analysis_uid)
# Need to pass in the passed attributes rather than the self. attributes so we know which one is None
self.virtual_object_manager = self._init_virtual_object_manager(
virtual_object_manager, data_set_uids_to_output, data_set_sample_uid_set_to_output,
num_proc, within_clade_cutoff)
self.vcc_uids_to_output = self._set_vcc_uids_to_output()
self.date_time_str = date_time_str
self.clades_of_output = set()
# A sorting of the vats of the output only by the len of the vccs of the output that they associate with
# i.e. before they are then sorted by clade. This will be used when calculating the order of the samples
self.overall_sorted_list_of_vats = None
# The above overall_sorted_list_of_vats is then ordered by clade to produce clade_sorted_list_of_vats_to_output
self.clade_sorted_list_of_vats_to_output = self._set_clade_sorted_list_of_vats_to_output()
self.sorted_list_of_vdss_uids_to_output = self._set_sorted_list_of_vdss_to_output()
self.number_of_samples = None
self.call_type = call_type
self.pre_headers = None
# the number of meta rows that have been added to the dataframe.
# This number will be used to remove the meta rows when making the abundance only dataframes
self.number_of_meta_rows_added = 0
# the number of header rows that have been added to the dataframe.
# This number will be used to remove the header rows when making the abundance only dataframes
# set of all of the species found in the vats
self.number_of_header_rows_added = 0
self.rel_abund_output_df, self.abs_abund_output_df = self._init_dfs()
self.additional_info_file_as_list = []
self.species_set = set()
self.species_ref_dict = self._set_species_ref_dict()
self.output_path_list = []
self.output_dir = output_dir
self.profiles_output_dir = os.path.join(self.output_dir, 'its2_type_profiles')
self.html_dir = html_dir
os.makedirs(self.output_dir, exist_ok=True)
os.makedirs(self.profiles_output_dir, exist_ok=True)
# dict that will hold the output file types and paths for the DataExplorer
self.js_output_path_dict = js_output_path_dict
self._init_output_paths()
self.output_path_list.extend([
self.path_to_relative_count_table_profiles_abund_and_meta,
self.path_to_absolute_count_table_profiles_abund_and_meta])
def _init_output_paths(self):
self.path_to_absolute_count_table_profiles_abund_and_meta = os.path.join(
self.profiles_output_dir, f'{self.data_analysis_obj.id}_'
f'{self.data_analysis_obj.name}_'
f'{self.date_time_str}.profiles.absolute.abund_and_meta.txt')
self.js_output_path_dict[
"profile_absolute_abund_meta_count"] = self.path_to_absolute_count_table_profiles_abund_and_meta
self.path_to_absolute_count_table_profiles_abund_only = os.path.join(
self.profiles_output_dir, f'{self.data_analysis_obj.id}_'
f'{self.data_analysis_obj.name}_'
f'{self.date_time_str}.profiles.absolute.abund_only.txt')
self.js_output_path_dict[
"profile_absolute_abund_only_count"] = self.path_to_absolute_count_table_profiles_abund_only
self.path_to_absolute_count_table_profiles_meta_only = os.path.join(
self.profiles_output_dir, f'{self.data_analysis_obj.id}_'
f'{self.data_analysis_obj.name}_'
f'{self.date_time_str}.profiles.meta_only.txt')
self.js_output_path_dict[
"profile_meta"] = self.path_to_absolute_count_table_profiles_meta_only
self.path_to_relative_count_table_profiles_abund_and_meta = os.path.join(
self.profiles_output_dir, f'{self.data_analysis_obj.id}_'
f'{self.data_analysis_obj.name}_'
f'{self.date_time_str}.profiles.relative.abund_and_meta.txt')
self.js_output_path_dict[
"profile_relative_abund_meta_count"] = self.path_to_relative_count_table_profiles_abund_and_meta
self.path_to_relative_count_table_profiles_abund_only = os.path.join(
self.profiles_output_dir, f'{self.data_analysis_obj.id}_'
f'{self.data_analysis_obj.name}_'
f'{self.date_time_str}.profiles.relative.abund_only.txt')
self.js_output_path_dict[
"profile_relative_abund_only_count"] = self.path_to_relative_count_table_profiles_abund_only
self.path_to_additional_info_file = os.path.join(self.profiles_output_dir, 'additional_info.txt')
self.js_output_path_dict[
"profile_additional_info_file"] = self.path_to_additional_info_file
def _set_vcc_uids_to_output(self):
list_of_sets_of_vcc_uids_in_vdss = [
self.virtual_object_manager.vdss_manager.vdss_dict[vdss_uid].set_of_cc_uids for vdss_uid in
self.data_set_sample_uid_set_to_output]
vcc_uids_to_output = list_of_sets_of_vcc_uids_in_vdss[0].union(*list_of_sets_of_vcc_uids_in_vdss[1:])
return vcc_uids_to_output
def output_types(self):
print('\n\nOutputting ITS2 type profile abundance count tables\n')
self._populate_main_body_of_dfs()
self._populate_sample_name_series()
self._populate_meta_info_of_dfs()
self._write_out_dfs()
def _populate_sample_name_series(self):
dss_name_ordered_list = [self.virtual_object_manager.vdss_manager.vdss_dict[vdss_uid].name for vdss_uid in self.sorted_list_of_vdss_uids_to_output]
sample_name_series_data = []
for _ in range(len(self.pre_headers)):
sample_name_series_data.append(np.nan)
for name in dss_name_ordered_list:
sample_name_series_data.append(name)
# add two nan for the remainder
for _ in range(len(self.abs_abund_output_df.index.tolist()) - (len(self.pre_headers) + len(dss_name_ordered_list))):
sample_name_series_data.append(np.nan)
sample_name_series = pd.Series(
name='sample_name',
data=sample_name_series_data,
index=self.abs_abund_output_df.index.tolist())
self.abs_abund_output_df.insert(loc=0, column='sample_name', value=sample_name_series)
self.rel_abund_output_df.insert(loc=0, column='sample_name', value=sample_name_series)
def _populate_meta_info_of_dfs(self):
self._add_species_info_to_addition_info_file()
if self.call_type == 'analysis':
self._append_meta_info_for_analysis_call_type()
else:
# call_type=='stand_alone'
self._append_meta_info_for_stand_alone_call_type()
def _write_out_dfs(self):
self._write_out_abund_and_meta_dfs_profiles()
abund_row_indices = self._write_out_abund_only_dfs_profiles()
prof_meta_only = self._write_out_meta_only_dfs_profiles(abund_row_indices)
self._write_out_js_profiles_data_file(prof_meta_only)
self._write_out_additional_info_profiles()
def _write_out_additional_info_profiles(self):
self.thread_safe_general.write_list_to_destination(destination=self.path_to_additional_info_file,
list_to_write=self.additional_info_file_as_list)
print(self.path_to_additional_info_file)
def _write_out_js_profiles_data_file(self, prof_meta_only):
"""Here we produce the javascript objects that return the data required for viewing in the DataExplorer.
We will produce the profile meta info object that will hold the meta information for each of the
resolved ITS2 type profiles. The first level of keys will be profile UIDs.
We will also output the data for drawing the rectangles, including the maximum sequence abundance of
an individual sample. And we will output a colour dictionary of profile UID to colour.
Finally we will output analysis meta information. We should also put out the corresponding data submission
meta information. These will both be displayed in the
."""
prof_colour_dict, sorted_profile_uids_by_local_abund = self._output_profile_meta_information(prof_meta_only)
self._make_profile_rect_array(prof_colour_dict, prof_meta_only, sorted_profile_uids_by_local_abund)
self._output_data_analysis_meta_info(prof_meta_only, sorted_profile_uids_by_local_abund)
def _output_data_analysis_meta_info(self, prof_meta_only, sorted_profile_uids_by_local_abund):
# Here output the DataAnalysis information for the DataExplorer
# Details that we would like to output
# UID
# NAME
# TIMESTAMP
# TOTAL SAMPLES IN ANALYSIS
# Number of unique profiles local
# number of profile instances local
# number of unique profiles total analysis
# number of profile instances total analysis
num_samples_in_analysis = len(DataSetSample.objects.filter(data_submission_from__in=[int(_) for _ in self.data_analysis_obj.list_of_data_set_uids.split(',')]))
total_local_abund = sum(prof_meta_only['ITS2 profile abundance local'].astype(int).values)
unique_types_in_analysis = list(AnalysisType.objects.filter(data_analysis_from=self.data_analysis_obj))
num_unique_profiles_in_analysis = len(unique_types_in_analysis)
num_profile_instances = len(self._chunk_query_cct_objs_from_at_objs(unique_types_in_analysis))
data_analysis_meta_info_dict = {
"uid": str(self.data_analysis_obj.id), "name": self.data_analysis_obj.name,
"time_stamp": self.data_analysis_obj.time_stamp,
"samples_in_output": len(self.data_set_sample_uid_set_to_output),
"samples_in_analysis": str(num_samples_in_analysis),
"unique_profile_local": str(len(sorted_profile_uids_by_local_abund)),
"instance_profile_local": str(total_local_abund),
"unique_profile_analysis": str(num_unique_profiles_in_analysis),
"instances_profile_analysis": str(num_profile_instances)}
da_meta_js_path = os.path.join(self.html_dir, 'study_data.js')
self.thread_safe_general.write_out_js_file_to_return_python_objs_as_js_objs(
[{'function_name': 'getDataAnalysisMetaInfo', 'python_obj': data_analysis_meta_info_dict}],
js_outpath=da_meta_js_path)
def _chunk_query_cct_objs_from_at_objs(self, da_obj_list):
cct_obj_list = []
for at_obj in self.thread_safe_general.chunks(da_obj_list):
cct_obj_list.extend(list(CladeCollectionType.objects.filter(analysis_type_of__in=at_obj)))
return cct_obj_list
def _output_profile_meta_information(self, prof_meta_only):
# js output path for profile meta
profile_meta_js_path = os.path.join(self.html_dir, 'study_data.js')
sorted_profile_uids_by_local_abund = prof_meta_only.sort_values(
'ITS2 profile abundance local', ascending=False).index.values.tolist()
# make color dict
prof_colour_dict = self._set_colour_dict(sorted_profile_uids_by_local_abund)
with open(os.path.join(self.html_dir, 'prof_color_dict.json'), 'w') as f:
json.dump(fp=f, obj=prof_colour_dict)
# first the meta information
genera_annotation_dict = {
'A': 'Symbiodinium', 'B': 'Breviolum', 'C': 'Cladocopium', 'D': 'Durusdinium',
'E': 'Effrenium', 'F': 'Clade F', 'G': 'Clade G', 'H': 'Clade H', 'I': 'Clade I'}
profile_meta_dict = {uid: {} for uid in prof_meta_only.index.values.tolist()}
for k in profile_meta_dict.keys():
profile_meta_dict[k]['uid'] = k
profile_meta_dict[k]['name'] = prof_meta_only.at[k, 'ITS2 type profile']
profile_meta_dict[k]['genera'] = genera_annotation_dict[prof_meta_only.at[k, 'Clade']]
profile_meta_dict[k]['maj_its2_seq'] = prof_meta_only.at[k, 'Majority ITS2 sequence']
profile_meta_dict[k]['assoc_species'] = prof_meta_only.at[k, 'Associated species']
profile_meta_dict[k]['local_abund'] = str(prof_meta_only.at[k, 'ITS2 profile abundance local'])
profile_meta_dict[k]['db_abund'] = str(prof_meta_only.at[k, 'ITS2 profile abundance DB'])
profile_meta_dict[k]['seq_uids'] = prof_meta_only.at[k, 'Sequence accession / SymPortal UID']
profile_meta_dict[k]['seq_abund_string'] = prof_meta_only.at[
k, 'Average defining sequence proportions and [stdev]']
profile_meta_dict[k]['color'] = prof_colour_dict[k]
self.thread_safe_general.write_out_js_file_to_return_python_objs_as_js_objs(
[{'function_name': 'getProfileMetaInfo', 'python_obj': profile_meta_dict}],
js_outpath=profile_meta_js_path)
return prof_colour_dict, sorted_profile_uids_by_local_abund
def _set_colour_dict(self, sorted_profile_uids_by_local_abund,):
colour_palette_pas = ['#%02x%02x%02x' % rgb_tup for rgb_tup in
self.thread_safe_general.create_colour_list(mix_col=(255, 255, 255), sq_dist_cutoff=1000, num_cols=50,
time_out_iterations=10000)]
grey_palette = ['#D0CFD4', '#89888D', '#4A4A4C', '#8A8C82', '#D4D5D0', '#53544F']
# We will use the col headers of the df as the its2 type profile order for plotting but we
# we should colour according to the abundance of the its2 type profiles
# as we don't want to run out of colours by the time we get to profiles that are very abundant.
# The sorted_type_prof_names_by_local_abund object has the names of the its2 type profile in order of abundance
# we will use the index order as the order of samples to plot
# create the colour dictionary that will be used for plotting by assigning a colour from the colour_palette
# to the most abundant seqs first and after that cycle through the grey_pallette assigning colours
colour_dict = {}
for i in range(len(sorted_profile_uids_by_local_abund)):
if i < len(colour_palette_pas):
colour_dict[sorted_profile_uids_by_local_abund[i]] = colour_palette_pas[i]
else:
grey_index = i % len(grey_palette)
colour_dict[sorted_profile_uids_by_local_abund[i]] = grey_palette[grey_index]
return colour_dict
def _make_profile_rect_array(self, prof_colour_dict, prof_meta_only, sorted_profile_uids_by_local_abund):
# get rid of the meta information at the top of the df
rows_to_keep_by_index = []
abundance_row_indices = list(range(self.number_of_header_rows_added, (
len(self.abs_abund_output_df.index.values.tolist()) - self.number_of_meta_rows_added)))
rows_to_keep_by_index += abundance_row_indices
absolute_df_abund_only = self.abs_abund_output_df.iloc[rows_to_keep_by_index, :]
relative_df_abund_only = self.rel_abund_output_df.iloc[rows_to_keep_by_index, :]
# now we need to create the rect array for the profiles
profile_rect_dict = {sample_uid: [] for sample_uid in absolute_df_abund_only.index.values.tolist()}
max_cumulative_abs = 0
for sample_uid in absolute_df_abund_only.index:
new_rect_list = []
abs_series = absolute_df_abund_only.loc[sample_uid]
rel_series = relative_df_abund_only.loc[sample_uid]
cumulative_count_abs = 0
cumulative_count_rel = 0
for profile_uid in sorted_profile_uids_by_local_abund:
prof_abund_abs = abs_series.at[profile_uid]
prof_abund_rel = rel_series.at[profile_uid]
if prof_abund_abs:
cumulative_count_abs += int(prof_abund_abs)
cumulative_count_rel += float(prof_abund_rel)
new_rect_list.append({
"profile_name": prof_meta_only.at[profile_uid, 'ITS2 type profile'],
"y_abs": cumulative_count_abs,
"y_rel": f'{cumulative_count_rel:.3f}',
"height_rel": f'{float(prof_abund_rel):.3f}',
"height_abs": int(prof_abund_abs),
})
profile_rect_dict[sample_uid] = new_rect_list
if cumulative_count_abs > max_cumulative_abs:
max_cumulative_abs = cumulative_count_abs
# now we have the dictionary that holds the rectangle arrays populated
# and we have the maximum abundance
# now write these out as js file and functions to return.
js_file_path = os.path.join(self.html_dir, 'study_data.js')
self.thread_safe_general.write_out_js_file_to_return_python_objs_as_js_objs(
[{'function_name': 'getRectDataProfileBySample', 'python_obj': profile_rect_dict},
{'function_name': 'getRectDataProfileBySampleMaxSeq', 'python_obj': max_cumulative_abs},
{'function_name': 'getProfColor', 'python_obj': prof_colour_dict}],
js_outpath=js_file_path)
def _write_out_meta_only_dfs_profiles(self, abundance_row_indices):
# now output the meta_only dfs
# delete the abundance info rows and drop the sample_name column
# then output the transposed matrix so that this is essentially the meta info for each of the
# ITS2 type profiles
rows_to_keep_by_index = list(range(self.number_of_header_rows_added))
rows_to_keep_by_index += list(range(self.number_of_header_rows_added + len(abundance_row_indices),
len(self.abs_abund_output_df.index.values.tolist())))
profile_meta_only = self.abs_abund_output_df.iloc[rows_to_keep_by_index, :]
profile_meta_only.drop(columns='sample_name', inplace=True)
profile_meta_only = profile_meta_only.T
profile_meta_only.to_csv(self.path_to_absolute_count_table_profiles_meta_only, sep="\t", header=True,
index=False)
print(self.path_to_absolute_count_table_profiles_meta_only)
# Make cols numerical
profile_meta_only['ITS2 profile abundance local'] = profile_meta_only['ITS2 profile abundance local'].astype(
int)
profile_meta_only['ITS2 profile abundance DB'] = profile_meta_only['ITS2 profile abundance DB'].astype(
int)
return profile_meta_only
def _write_out_abund_only_dfs_profiles(self):
# write out the abund_only dfs
# get rid of the header rows other than the profile uid that is the first row
# also get rid of all meta rows at the end
# also get rid of the sample_name column
rows_to_keep_by_index = [0]
abundance_row_indices = list(range(self.number_of_header_rows_added, (
len(self.abs_abund_output_df.index.values.tolist()) - self.number_of_meta_rows_added)))
rows_to_keep_by_index += abundance_row_indices
absolute_df_abund_only = self.abs_abund_output_df.iloc[rows_to_keep_by_index, :]
relative_df_abund_only = self.rel_abund_output_df.iloc[rows_to_keep_by_index, :]
absolute_df_abund_only.drop(columns='sample_name', inplace=True)
relative_df_abund_only.drop(columns='sample_name', inplace=True)
# replace the top item of the index with sample_uid rather than 'ITS2 type profile UID'
new_index = absolute_df_abund_only.index.values.tolist()
new_index[0] = 'sample_uid'
absolute_df_abund_only.index = new_index
relative_df_abund_only.index = new_index
absolute_df_abund_only.to_csv(self.path_to_absolute_count_table_profiles_abund_only, sep="\t", header=False)
relative_df_abund_only.to_csv(self.path_to_relative_count_table_profiles_abund_only, sep="\t", header=False)
print(self.path_to_absolute_count_table_profiles_abund_only)
print(self.path_to_relative_count_table_profiles_abund_only)
return abundance_row_indices
def _write_out_abund_and_meta_dfs_profiles(self):
# write out the abund_and_meta dfs
print('\n\nITS2 type profile count tables output to:')
self.abs_abund_output_df.to_csv(
self.path_to_absolute_count_table_profiles_abund_and_meta, sep="\t", header=False)
print(f'{self.path_to_absolute_count_table_profiles_abund_and_meta}\n\n')
self.rel_abund_output_df.to_csv(
self.path_to_relative_count_table_profiles_abund_and_meta, sep="\t", header=False)
print(self.path_to_relative_count_table_profiles_abund_and_meta)
def _append_meta_info_for_stand_alone_call_type(self):
data_sets_of_analysis = len(self.data_analysis_obj.list_of_data_set_uids.split(','))
if self.call_type == 'stand_alone_data_sets':
meta_info_string = self._make_stand_alone_data_set_meta_info_string(data_sets_of_analysis)
else:
meta_info_string = self._make_stand_alone_data_set_samples_meta_info_string(data_sets_of_analysis)
self._append_meta_info_summary_string_to_additional_info_file(meta_info_string)
self._append_data_set_info_to_additional_info()
def _append_meta_info_for_analysis_call_type(self):
meta_info_string_items = self._make_analysis_meta_info_string()
self._append_meta_info_summary_string_to_additional_info_file(meta_info_string_items)
self._append_data_set_info_to_additional_info()
def _add_species_info_to_addition_info_file(self):
# add a blank row with just the header Species reference
self.additional_info_file_as_list.append('Species references')
# now add the references for each of the associated species
# we put an NaN in the first column so that we can delete the sample_name column when making the
# meta only output table. If we put the species reference directly in that first column it would be deleted
# when deleting this column.
for species in self.species_set:
if species in self.species_ref_dict.keys():
self.additional_info_file_as_list.append(self.species_ref_dict[species])
def _append_data_set_info_to_additional_info(self):
ds_obj_list = self._chunk_query_ds_objs_from_ds_uids()
for data_set_object in ds_obj_list:
data_set_meta_str = f'Data_set ID: {data_set_object.id}; ' \
f'Data_set name: {data_set_object.name}; ' \
f'submitting_user: {data_set_object.submitting_user}; ' \
f'time_stamp: {data_set_object.time_stamp}'
self.additional_info_file_as_list.append(data_set_meta_str)
def _chunk_query_ds_objs_from_ds_uids(self):
ds_obj_list = []
for uid_list in self.thread_safe_general.chunks(self.data_set_uid_set_to_output):
ds_obj_list.extend(list(DataSet.objects.filter(id__in=uid_list)))
return ds_obj_list
def _make_analysis_meta_info_string(self):
meta_info_string_items = [
f'Output as part of data_analysis ID: {self.data_analysis_obj.id}; '
f'Number of data_set objects as part of analysis = {len(self.data_set_uid_set_to_output)}; '
f'submitting_user: {self.data_analysis_obj.submitting_user}; '
f'time_stamp: {self.data_analysis_obj.time_stamp}']
return meta_info_string_items
def _append_meta_info_summary_string_to_additional_info_file(self, meta_info_string_items):
self.additional_info_file_as_list.append(meta_info_string_items)
def _make_stand_alone_data_set_meta_info_string(self, data_sets_of_analysis):
meta_info_string = f'Stand_alone_data_sets output by {sp_config.user_name} on {self.date_time_str}; ' \
f'data_analysis ID: {self.data_analysis_obj.id}; ' \
f'Number of data_set objects as part of output = {len(self.data_set_uid_set_to_output)}; ' \
f'Number of data_set objects as part of analysis = {data_sets_of_analysis}'
return meta_info_string
def _make_stand_alone_data_set_samples_meta_info_string(self, data_sets_of_analysis):
# self.call_type == 'stand_alone_data_set_samples'
meta_info_string = f'Stand_alone_data_set_samples output by {sp_config.user_name} on {self.date_time_str}; ' \
f'data_analysis ID: {self.data_analysis_obj.id}; ' \
f'Number of data_set objects as part of output = {len(self.data_set_uid_set_to_output)}; ' \
f'Number of data_set objects as part of analysis = {data_sets_of_analysis}'
return meta_info_string
def _populate_main_body_of_dfs(self):
print('\nPopulating output dfs:')
for vat in self.clade_sorted_list_of_vats_to_output:
sys.stdout.write(f'\r{vat.name}')
tosp = self.TypeOutputSeriesPopulation(parent_output_type_count_table=self, vat=vat)
data_relative_list, data_absolute_list = tosp.make_output_series()
self.rel_abund_output_df[vat.id] = data_relative_list
self.abs_abund_output_df[vat.id] = data_absolute_list
if vat.species != 'None':
self.species_set.update(vat.species.split(','))
class TypeOutputSeriesPopulation:
"""will create a relative abundance and absolute abundance
output pandas series for a given VirtualAnalysisType
"""
def __init__(self, parent_output_type_count_table, vat):
self.output_type_count_table = parent_output_type_count_table
self.vat = vat
self.data_relative_list = []
self.data_absolute_list = []
def make_output_series(self):
"""type_uid"""
self._pop_type_uid()
self._pop_type_clade()
self._pop_maj_seq_str()
self._pop_species()
self._pop_type_local_and_global_abundances()
self._pop_type_name()
self._pop_type_abundances()
self._pop_vat_accession_name()
self._pop_av_and_stdev_abund()
return self.data_relative_list, self.data_absolute_list
def _pop_av_and_stdev_abund(self):
average_abund_and_sd_string = ''
for rs_id in list(self.vat.multi_modal_detection_rel_abund_df):
if average_abund_and_sd_string == '':
average_abund_and_sd_string = self._append_rel_abund_and_sd_str_for_rs(
average_abund_and_sd_string, rs_id)
else:
average_abund_and_sd_string = self._append_dash_or_slash_if_maj_seq(average_abund_and_sd_string,
rs_id)
average_abund_and_sd_string = self._append_rel_abund_and_sd_str_for_rs(
average_abund_and_sd_string, rs_id)
self.data_relative_list.append(average_abund_and_sd_string)
self.data_absolute_list.append(average_abund_and_sd_string)
def _append_dash_or_slash_if_maj_seq(self, average_abund_and_sd_string, rs_id):
if rs_id in self.vat.majority_reference_sequence_uid_set:
average_abund_and_sd_string += '/'
else:
average_abund_and_sd_string += '-'
return average_abund_and_sd_string
def _append_rel_abund_and_sd_str_for_rs(self, average_abund_and_sd_string, rs_id):
average_abund_str = "{0:.3f}".format(self.vat.multi_modal_detection_rel_abund_df[rs_id].mean())
std_dev_str = "{0:.3f}".format(self.vat.multi_modal_detection_rel_abund_df[rs_id].std())
average_abund_and_sd_string += f'{average_abund_str}[{std_dev_str}]'
return average_abund_and_sd_string
def _pop_vat_accession_name(self):
vat_accession_name = self.vat.generate_name(
at_df=self.vat.multi_modal_detection_rel_abund_df,
use_rs_ids_rather_than_names=True)
self.data_relative_list.append(vat_accession_name)
self.data_absolute_list.append(vat_accession_name)
def _pop_type_abundances(self):
# type abundances
temp_rel_abund_holder_list = []
temp_abs_abund_holder_list = []
for vdss_uid in self.output_type_count_table.sorted_list_of_vdss_uids_to_output:
count = 0
vdss_obj = self.output_type_count_table.virtual_object_manager.vdss_manager.vdss_dict[vdss_uid]
for vcc_uid in vdss_obj.set_of_cc_uids:
if vcc_uid in self.vat.type_output_rel_abund_series:
count += 1
temp_rel_abund_holder_list.append(self.vat.type_output_rel_abund_series[vcc_uid])
temp_abs_abund_holder_list.append(self.vat.type_output_abs_abund_series[vcc_uid])
if count == 0: # type not found in vdss
temp_rel_abund_holder_list.append(0)
temp_abs_abund_holder_list.append(0)
if count > 1: # more than one vcc from vdss associated with type
raise RuntimeError('More than one vcc of vdss matched vat in output')
self.data_relative_list.extend(temp_rel_abund_holder_list)
self.data_absolute_list.extend(temp_abs_abund_holder_list)
def _pop_type_name(self):
# name
self.data_absolute_list.append(self.vat.name)
self.data_relative_list.append(self.vat.name)
def _pop_type_local_and_global_abundances(self):
# local_output_type_abundance
# all analysis_type_abundance
vccs_of_type = self.vat.clade_collection_obj_set_profile_assignment
vccs_of_type_from_output = [vcc for vcc in vccs_of_type if
vcc.vdss_uid in self.output_type_count_table.sorted_list_of_vdss_uids_to_output]
abund_db = self.vat.grand_tot_num_instances_of_vat_in_analysis
self.data_absolute_list.extend([str(len(vccs_of_type_from_output)), str(abund_db)])
self.data_relative_list.extend([str(len(vccs_of_type_from_output)), str(abund_db)])
def _pop_species(self):
# species
self.data_absolute_list.append(self.vat.species)
self.data_relative_list.append(self.vat.species)
def _pop_maj_seq_str(self):
# majority sequences string e.g. C3/C3b
ordered_maj_seq_names = []
for rs_id in list(self.vat.multi_modal_detection_rel_abund_df):
for rs in self.vat.footprint_as_ref_seq_objs_set:
if rs.id == rs_id and rs in self.vat.majority_reference_sequence_obj_set:
ordered_maj_seq_names.append(rs.name)
maj_seq_str = '/'.join(ordered_maj_seq_names)
self.data_absolute_list.append(maj_seq_str)
self.data_relative_list.append(maj_seq_str)
def _pop_type_clade(self):
# clade
self.data_absolute_list.append(self.vat.clade)
self.data_relative_list.append(self.vat.clade)
def _pop_type_uid(self):
# Type uid
self.data_absolute_list.append(self.vat.id)
self.data_relative_list.append(self.vat.id)
def _init_da_object(self, data_analysis_obj, data_analysis_uid):
if data_analysis_uid:
self.data_analysis_obj = DataAnalysis.objects.get(id=data_analysis_uid)
else:
self.data_analysis_obj = data_analysis_obj
return self.data_analysis_obj
def _init_dfs(self):
self.pre_headers = ['ITS2 type profile UID', 'Clade', 'Majority ITS2 sequence',
'Associated species', 'ITS2 profile abundance local', 'ITS2 profile abundance DB', 'ITS2 type profile']
self.number_of_header_rows_added += len(self.pre_headers)
post_headers = ['Sequence accession / SymPortal UID', 'Average defining sequence proportions and [stdev]']
self.number_of_meta_rows_added += len(post_headers)
self.df_index = self.pre_headers + self.sorted_list_of_vdss_uids_to_output + post_headers
return pd.DataFrame(index=self.df_index), pd.DataFrame(index=self.df_index)
def _init_dss_and_ds_uids(self, data_set_sample_uid_set_to_output, data_set_uids_to_output):
if data_set_sample_uid_set_to_output:
self.data_set_sample_uid_set_to_output = data_set_sample_uid_set_to_output
temp_data_set_obj_list = self._chunk_query_distinct_dss_objs_from_dss_uids()
self.data_set_uid_set_to_output = [ds.id for ds in temp_data_set_obj_list]
else:
self.data_set_uid_set_to_output = data_set_uids_to_output
temp_data_set_sample_obj_list = self._chunk_query_dss_objs_from_ds_uids()
self.data_set_sample_uid_set_to_output = [dss.id for dss in temp_data_set_sample_obj_list]
return self.data_set_uid_set_to_output, self.data_set_sample_uid_set_to_output
def _chunk_query_dss_objs_from_ds_uids(self):
temp_data_set_sample_obj_list = []
for uid_list in self.thread_safe_general.chunks(self.data_set_uid_set_to_output):
temp_data_set_sample_obj_list.extend(list(DataSetSample.objects.filter(data_submission_from__in=uid_list)))
return temp_data_set_sample_obj_list
def _chunk_query_distinct_dss_objs_from_dss_uids(self):
temp_data_set_obj_set = set()
for uid_list in self.thread_safe_general.chunks(self.data_set_sample_uid_set_to_output):
temp_data_set_obj_set.update(list(DataSet.objects.filter(datasetsample__in=uid_list)))
temp_data_set_obj_list = list(temp_data_set_obj_set)
return temp_data_set_obj_list
def _init_virtual_object_manager(
self, virtual_object_manager, data_set_uids_to_output, data_set_sample_uid_set_to_output,
num_proc, within_clade_cutoff):
if virtual_object_manager:
return virtual_object_manager
else:
if data_set_uids_to_output:
self.virtual_object_manager = virtual_objects.VirtualObjectManager(
num_proc=num_proc, within_clade_cutoff=within_clade_cutoff,
list_of_data_set_uids=data_set_uids_to_output,
force_basal_lineage_separation=self.force_basal_lineage_separation)
else:
self.virtual_object_manager = virtual_objects.VirtualObjectManager(
num_proc=num_proc, within_clade_cutoff=within_clade_cutoff,
list_of_data_set_sample_uids=data_set_sample_uid_set_to_output,
force_basal_lineage_separation=self.force_basal_lineage_separation)
print('\nInstantiating VirtualAnalysisTypes')
temp_analysis_type_obj_list = self._chunk_query_distinct_at_obj_from_dss_uids()
for at in temp_analysis_type_obj_list:
sys.stdout.write(f'\r{at.name}')
self.virtual_object_manager.vat_manager.make_vat_post_profile_assignment_from_analysis_type(at)
self._associate_vat_to_vcc()
return self.virtual_object_manager
def _chunk_query_distinct_at_obj_from_dss_uids(self):
temp_analysis_type_obj_set = set()
for uid_list in self.thread_safe_general.chunks(self.data_set_sample_uid_set_to_output):
temp_analysis_type_obj_set.update(list(AnalysisType.objects.filter(
cladecollectiontype__clade_collection_found_in__data_set_sample_from__in=uid_list,
data_analysis_from=self.data_analysis_obj)))
temp_analysis_type_obj_list = list(temp_analysis_type_obj_set)
return temp_analysis_type_obj_list
def _associate_vat_to_vcc(self):
"""The CladeCollections held on disc have know info on which AnalysisTypes were found in them except
for by association with CladeCollectionTypes. As such we have to populate the
vcc.analysis_type_obj_to_representative_rel_abund_in_cc_dict manually from the vat."""
print('\nAssociating VirtualCladeCollections to VirtualAnalysisTypes')
for vat in self.virtual_object_manager.vat_manager.vat_dict.values():
for vcc in vat.clade_collection_obj_set_profile_assignment:
vcc_rel_abund_dict = vcc.ref_seq_id_to_rel_abund_dict
total_seq_rel_abund_for_cc = []
for rs_uid in vat.ref_seq_uids_set:
total_seq_rel_abund_for_cc.append(vcc_rel_abund_dict[rs_uid])
vcc.analysis_type_obj_to_representative_rel_abund_in_cc_dict[vat] = sum(total_seq_rel_abund_for_cc)
def _get_data_set_uids_of_data_sets(self):
vds_uid_set = set()
for vdss in [vdss for vdss in self.virtual_object_manager.vdss_manager.vdss_dict.values() if
vdss.uid in self.data_set_sample_uid_set_to_output]:
vds_uid_set.add(vdss.data_set_id)
return vds_uid_set
def _set_sorted_list_of_vdss_to_output(self):
"""Generate the list of dss uids that will be the order that we will use for the index
of the output dataframes. The samples will be ordered by the most abundant type profiles first, and for
each type profile the samples that had this profile as their most abundant type profile should be listed,
within this, they should additionally be sorted by the relative abundance at which the profiles were found
within the samples."""
sorted_vdss_uid_list = []
# a sanity checking set just to make sure we are not finding more vccs with more than one most abundant type
set_of_vcc_uids_already_added = set()
for vat in self.overall_sorted_list_of_vats:
temp_set_vcc_rel_abund_tups = set()
# For each vcc that had this profile found in it
for vcc in vat.clade_collection_obj_set_profile_assignment:
vdss_uid_of_vcc = vcc.vdss_uid
vdss_obj = self.virtual_object_manager.vdss_manager.vdss_dict[vdss_uid_of_vcc]
# if the clade of the vat is the most abundant clade in the vdss
sorted_clade_abundances_tups = [tup for tup in sorted(vdss_obj.cladal_abundances_dict.items(), key=lambda x:x[1], reverse=True)]
most_abund_clade, rel_abund_of_clade = sorted_clade_abundances_tups[0]
if not vat.clade == most_abund_clade:
continue
# this vcc is not part of the output
if not vdss_uid_of_vcc in self.data_set_sample_uid_set_to_output:
continue
# see if this vat was the most abundant vat of the vcc
# get sorted list of the vats
most_abundant_vat, within_clade_rel_abund = sorted(vcc.analysis_type_obj_to_representative_rel_abund_in_cc_dict.items(), key=lambda x: x[1], reverse=True)[0]
rel_abund_in_sample = within_clade_rel_abund * rel_abund_of_clade
# if this type was most abundant type of the vcc, add it to the profile
if most_abundant_vat == vat:
if vcc.id not in set_of_vcc_uids_already_added:
set_of_vcc_uids_already_added.add(vcc.id)
else:
raise RuntimeError('The vcc was already added to the list_of_vcc_uids_already_added')
if vdss_uid_of_vcc in self.data_set_sample_uid_set_to_output:
if vdss_uid_of_vcc not in sorted_vdss_uid_list:
temp_set_vcc_rel_abund_tups.add((vdss_uid_of_vcc, rel_abund_in_sample))
else:
pass
else:
raise RuntimeError('vdss associated with vcc seems to not be part of the output')
temp_set_vcc_rel_abund_tups = list(temp_set_vcc_rel_abund_tups)
temp_set_vcc_rel_abund_tups.sort(key=lambda x: x[0], reverse=True)
temp_set_vcc_rel_abund_tups.sort(key=lambda x: x[1], reverse=True)
sorted_vdss_uid_list.extend([tup[0] for tup in temp_set_vcc_rel_abund_tups])
# add the samples that didn't have a type associated to them in a specific order
samples_to_add = [dss_uid for dss_uid in self.data_set_sample_uid_set_to_output if dss_uid not in sorted_vdss_uid_list]
samples_to_add.sort(reverse=True)
sorted_vdss_uid_list.extend(samples_to_add)
return sorted_vdss_uid_list
def _set_clade_sorted_list_of_vats_to_output(self):
"""Get list of analysis type sorted by clade, and then by
len of the cladecollections associated to them from the output
"""
list_of_tup_vat_to_vccs_of_output = []
for vat in self.virtual_object_manager.vat_manager.vat_dict.values():
self.clades_of_output.add(vat.clade)
vccs_of_output_of_vat = []
for vcc in vat.clade_collection_obj_set_profile_assignment:
if vcc.vdss_uid in self.data_set_sample_uid_set_to_output:
vccs_of_output_of_vat.append(vcc)
list_of_tup_vat_to_vccs_of_output.append((vat, len(vccs_of_output_of_vat)))
self.overall_sorted_list_of_vats = [vat for vat, num_vcc_of_output in
sorted(list_of_tup_vat_to_vccs_of_output, key=lambda x: x[1], reverse=True) if num_vcc_of_output != 0]
clade_ordered_type_order = []
for clade in list('ABCDEFGHI'):
clade_ordered_type_order.extend([vat for vat in self.overall_sorted_list_of_vats if vat.clade == clade])
return clade_ordered_type_order
def _set_species_ref_dict(self):
return {
'S. microadriaticum': 'Freudenthal, H. D. (1962). Symbiodinium gen. nov. and Symbiodinium microadriaticum '
'sp. nov., a Zooxanthella: Taxonomy, Life Cycle, and Morphology. The Journal of '
'Protozoology 9(1): 45-52',
'S. pilosum': 'Trench, R. (2000). Validation of some currently used invalid names of dinoflagellates. '
'Journal of Phycology 36(5): 972-972.\tTrench, R. K. and R. J. Blank (1987). '
'Symbiodinium microadriaticum Freudenthal, S. goreauii sp. nov., S. kawagutii sp. nov. and '
'S. pilosum sp. nov.: Gymnodinioid dinoflagellate symbionts of marine invertebrates. '
'Journal of Phycology 23(3): 469-481.',
'S. natans': 'Hansen, G. and N. Daugbjerg (2009). Symbiodinium natans sp. nob.: A free-living '
'dinoflagellate from Tenerife (northeast Atlantic Ocean). Journal of Phycology 45(1): 251-263.',
'S. tridacnidorum': 'Lee, S. Y., H. J. Jeong, N. S. Kang, T. Y. Jang, S. H. Jang and T. C. Lajeunesse (2015). '
'Symbiodinium tridacnidorum sp. nov., a dinoflagellate common to Indo-Pacific giant clams,'
' and a revised morphological description of Symbiodinium microadriaticum Freudenthal, '
'emended Trench & Blank. European Journal of Phycology 50(2): 155-172.',
'S. linucheae': 'Trench, R. K. and L.-v. Thinh (1995). Gymnodinium linucheae sp. nov.: The dinoflagellate '
'symbiont of the jellyfish Linuche unguiculata. European Journal of Phycology 30(2): 149-154.',
'S. minutum': 'Lajeunesse, T. C., J. E. Parkinson and J. D. Reimer (2012). A genetics-based description of '
'Symbiodinium minutum sp. nov. and S. psygmophilum sp. nov. (dinophyceae), two dinoflagellates '
'symbiotic with cnidaria. Journal of Phycology 48(6): 1380-1391.',
'S. antillogorgium': 'Parkinson, J. E., M. A. Coffroth and T. C. LaJeunesse (2015). "New species of Clade B '
'Symbiodinium (Dinophyceae) from the greater Caribbean belong to different functional '
'guilds: S. aenigmaticum sp. nov., S. antillogorgium sp. nov., S. endomadracis sp. nov., '
'and S. pseudominutum sp. nov." Journal of phycology 51(5): 850-858.',
'S. pseudominutum': 'Parkinson, J. E., M. A. Coffroth and T. C. LaJeunesse (2015). "New species of Clade B '
'Symbiodinium (Dinophyceae) from the greater Caribbean belong to different functional '
'guilds: S. aenigmaticum sp. nov., S. antillogorgium sp. nov., S. endomadracis sp. nov., '
'and S. pseudominutum sp. nov." Journal of phycology 51(5): 850-858.',
'S. psygmophilum': 'Lajeunesse, T. C., J. E. Parkinson and J. D. Reimer (2012). '
'A genetics-based description of '
'Symbiodinium minutum sp. nov. and S. psygmophilum sp. nov. (dinophyceae), '
'two dinoflagellates '
'symbiotic with cnidaria. Journal of Phycology 48(6): 1380-1391.',
'S. muscatinei': 'No reference available',
'S. endomadracis': 'Parkinson, J. E., M. A. Coffroth and T. C. LaJeunesse (2015). "New species of Clade B '
'Symbiodinium (Dinophyceae) from the greater Caribbean belong to different functional '
'guilds: S. aenigmaticum sp. nov., S. antillogorgium sp. nov., S. endomadracis sp. nov., '
'and S. pseudominutum sp. nov." Journal of phycology 51(5): 850-858.',
'S. aenigmaticum': 'Parkinson, J. E., M. A. Coffroth and T. C. LaJeunesse (2015). "New species of Clade B '
'Symbiodinium (Dinophyceae) from the greater Caribbean belong to different functional '
'guilds: S. aenigmaticum sp. nov., S. antillogorgium sp. nov., S. endomadracis sp. nov., '
'and S. pseudominutum sp. nov." Journal of phycology 51(5): 850-858.',
'S. goreaui': 'Trench, R. (2000). Validation of some currently used invalid names of dinoflagellates. '
'Journal of Phycology 36(5): 972-972.\tTrench, R. K. and R. J. Blank (1987). '
'Symbiodinium microadriaticum Freudenthal, S. goreauii sp. nov., S. kawagutii sp. nov. and '
'S. pilosum sp. nov.: Gymnodinioid dinoflagellate symbionts of marine invertebrates. '
'Journal of Phycology 23(3): 469-481.',
'S. thermophilum': 'Hume, B. C. C., C. D`Angelo, E. G. Smith, J. R. Stevens, J. Burt and J. Wiedenmann (2015).'
' Symbiodinium thermophilum sp. nov., a thermotolerant symbiotic alga prevalent in corals '
'of the world`s hottest sea, the Persian/Arabian Gulf. Sci. Rep. 5.',
'S. glynnii': 'LaJeunesse, T. C., D. T. Pettay, E. M. Sampayo, N. Phongsuwan, B. Brown, D. O. Obura, O. '
'Hoegh-Guldberg and W. K. Fitt (2010). Long-standing environmental conditions, geographic '
'isolation and host-symbiont specificity influence the relative ecological dominance and '
'genetic diversification of coral endosymbionts in the genus Symbiodinium. Journal of '
'Biogeography 37(5): 785-800.',
'S. trenchii': 'LaJeunesse, T. C., D. C. Wham, D. T. Pettay, J. E. Parkinson, S. Keshavmurthy and C. A. Chen '
'(2014). Ecologically differentiated stress-tolerant endosymbionts in the dinoflagellate genus'
' Symbiodinium (Dinophyceae) Clade D are different species. Phycologia 53(4): 305-319.',
'S. eurythalpos': 'LaJeunesse, T. C., D. C. Wham, D. T. Pettay, J. E. Parkinson, '
'S. Keshavmurthy and C. A. Chen '
'(2014). Ecologically differentiated stress-tolerant '
'endosymbionts in the dinoflagellate genus'
' Symbiodinium (Dinophyceae) Clade D are different species. Phycologia 53(4): 305-319.',
'S. boreum': 'LaJeunesse, T. C., D. C. Wham, D. T. Pettay, J. E. Parkinson, S. Keshavmurthy and C. A. Chen '
'(2014). "Ecologically differentiated stress-tolerant endosymbionts in the dinoflagellate genus'
' Symbiodinium (Dinophyceae) Clade D are different species." Phycologia 53(4): 305-319.',
'S. voratum': 'Jeong, H. J., S. Y. Lee, N. S. Kang, Y. D. Yoo, A. S. Lim, M. J. Lee, H. S. Kim, W. Yih, H. '
'Yamashita and T. C. LaJeunesse (2014). Genetics and Morphology Characterize the Dinoflagellate'
' Symbiodinium voratum, n. sp., (Dinophyceae) as the Sole Representative of Symbiodinium Clade E'
'. Journal of Eukaryotic Microbiology 61(1): 75-94.',
'S. kawagutii': 'Trench, R. (2000). Validation of some currently used invalid names of dinoflagellates. '
'Journal of Phycology 36(5): 972-972.\tTrench, R. K. and R. J. Blank (1987). '
'Symbiodinium microadriaticum Freudenthal, S. goreauii sp. nov., S. kawagutii sp. nov. and '
'S. pilosum sp. nov.: Gymnodinioid dinoflagellate symbionts of marine invertebrates. '
'Journal of Phycology 23(3): 469-481.'
}
class SequenceCountTableCreator:
""" This is essentially broken into two parts. The first part goes through all of the DataSetSamples from
the DataSets of the output and collects abundance information. The second part then puts this abundance
information into a dataframe for both the absoulte and the relative abundance.
This seq output can be run in two ways:
1 - by providing DataSet uid lists
2 - by providing DataSetSample uid lists
Either way, after initial init, we will work on a sample by sample basis.
"""
def __init__(
self, symportal_root_dir, call_type, num_proc, html_dir, js_output_path_dict, date_time_str,
no_pre_med_seqs, multiprocess, dss_uids_output_str=None, ds_uids_output_str=None, output_dir=None,
sorted_sample_uid_list=None, analysis_obj=None):
self.multiprocess = multiprocess
self.thread_safe_general = ThreadSafeGeneral()
self._init_core_vars(
symportal_root_dir, analysis_obj, call_type, dss_uids_output_str, ds_uids_output_str, num_proc,
output_dir, sorted_sample_uid_list, date_time_str, html_dir)
self._init_seq_abundance_collection_objects()
self._init_vars_for_putting_together_the_dfs()
# dict that will hold the file type to file path of output files for the DataExplorer
self.js_output_path_dict = js_output_path_dict
self._init_output_paths()
# dataframes without the meta rows at the bottom for making the javascript objects
self.df_abs_no_meta_rows = None
self.df_rel_no_meta_rows = None
# variables to hold sample uid orders for the js output
self.profile_based_sample_ordered_uids = None
self.similarity_based_sample_ordered_uids = None
# False by default. If true do not output premed seq info
self.no_pre_med_seqs = no_pre_med_seqs
def _init_core_vars(self, symportal_root_dir, analysis_obj, call_type, dss_uids_output_str,
ds_uids_output_str, num_proc,
output_dir, sorted_sample_uid_list, date_time_str, html_dir):
self._check_either_dss_or_dsss_uids_provided(dss_uids_output_str, ds_uids_output_str)
if dss_uids_output_str:
dss_uids_for_query = [int(a) for a in dss_uids_output_str.split(',')]
self.list_of_dss_objects = self._chunk_query_set_dss_objs_from_dss_uids(dss_uids_for_query)
self.ds_objs_to_output = self._chunk_query_set_distinct_ds_objs_from_dss_objs()
elif ds_uids_output_str:
uids_of_data_sets_to_output = [int(a) for a in ds_uids_output_str.split(',')]
self.ds_objs_to_output = self._chunk_query_set_ds_objs_from_ds_uids(uids_of_data_sets_to_output)
self.list_of_dss_objects = self._chunk_query_set_dss_objs_from_ds_objs()
self.ref_seqs_in_datasets = self._chunk_query_set_rs_objs_from_dss_objs()
self.num_proc = num_proc
self.date_time_str = date_time_str
self._set_output_dirs(call_type, ds_uids_output_str, output_dir, symportal_root_dir, html_dir)
self.sorted_sample_uid_list = sorted_sample_uid_list
self.analysis_obj = analysis_obj
self.call_type = call_type
self.output_user = sp_config.user_name
self.clade_list = list('ABCDEFGHI')
set_of_clades_found = {ref_seq.clade for ref_seq in self.ref_seqs_in_datasets}
self.ordered_list_of_clades_found = [clade for clade in self.clade_list if clade in set_of_clades_found]
def _chunk_query_set_rs_objs_from_dss_objs(self):
temp_ref_seqs_in_datasets_set = set()
for uid_list in self.thread_safe_general.chunks(self.list_of_dss_objects):
temp_ref_seqs_in_datasets_set.update(
list(ReferenceSequence.objects.filter(datasetsamplesequence__data_set_sample_from__in=uid_list)))
return list(temp_ref_seqs_in_datasets_set)
def _chunk_query_set_dss_objs_from_ds_objs(self):
temp_list_of_dss_objects = []
for uid_list in self.thread_safe_general.chunks(self.ds_objs_to_output):
temp_list_of_dss_objects.extend(list(DataSetSample.objects.filter(data_submission_from__in=uid_list)))
return temp_list_of_dss_objects
def _chunk_query_set_ds_objs_from_ds_uids(self, uids_of_data_sets_to_output):
temp_ds_objs_to_output = []
for uid_list in self.thread_safe_general.chunks(uids_of_data_sets_to_output):
temp_ds_objs_to_output.extend(list(DataSet.objects.filter(id__in=uid_list)))
return temp_ds_objs_to_output
def _chunk_query_set_distinct_ds_objs_from_dss_objs(self):
temp_ds_objs_to_output_set = set()
for uid_list in self.thread_safe_general.chunks(self.list_of_dss_objects):
temp_ds_objs_to_output_set.update(list(DataSet.objects.filter(datasetsample__in=uid_list)))
return list(temp_ds_objs_to_output_set)
def _chunk_query_set_dss_objs_from_dss_uids(self, dss_uids_for_query):
temp_list_of_dss_objects = []
for uid_list in self.thread_safe_general.chunks(dss_uids_for_query):
temp_list_of_dss_objects.extend(list(DataSetSample.objects.filter(id__in=uid_list)))
return temp_list_of_dss_objects
@staticmethod
def _check_either_dss_or_dsss_uids_provided(data_set_sample_ids_to_output_string, data_set_uids_to_output_as_comma_sep_string):
if data_set_sample_ids_to_output_string is not None and data_set_uids_to_output_as_comma_sep_string is not None:
raise RuntimeError('Provide either dss uids or ds uids for outputing sequence count tables')
def _set_output_dirs(self, call_type, data_set_uids_to_output_as_comma_sep_string, output_dir, symportal_root_dir, html_dir):
"""Set both the standard output_dir where the count tables will be output and the directory to output
the resources for the browser based data explorer"""
if call_type == 'submission':
self.output_dir = os.path.abspath(os.path.join(
symportal_root_dir, 'outputs', 'loaded_data_sets', data_set_uids_to_output_as_comma_sep_string, self.date_time_str))
else: # call_type == 'analysis or call_type == 'stand_alone'
self.output_dir = output_dir
# the directory where all count tables and plots that are of the post-med seqs will be output.
self.post_med_output_dir = os.path.join(self.output_dir, 'post_med_seqs')
self.html_dir = html_dir
os.makedirs(self.post_med_output_dir, exist_ok=True)
os.makedirs(self.output_dir, exist_ok=True)
def _init_seq_abundance_collection_objects(self):
"""Output objects from first worker to be used by second worker"""
self.dss_id_to_list_of_dsss_objects_dict_mp_dict = None
self.dss_id_to_list_of_abs_and_rel_abund_of_contained_dsss_dicts_mp_dict = None
self.dss_id_to_list_of_abs_and_rel_abund_clade_summaries_of_noname_seqs_mp_dict = None
# this is the list that we will use the self.annotated_dss_name_to_cummulative_rel_abund_mp_dict to create
# it is a list of the ref_seqs_ordered first by clade then by abundance.
self.clade_abundance_ordered_ref_seq_list = []
def _init_vars_for_putting_together_the_dfs(self):
# variables concerned with putting together the dataframes
self.dss_id_to_pandas_series_results_list_dict = None
self.output_df_absolute_post_med = None
self.output_df_relative_post_med = None
self.output_df_relative_pre_med = None
self.additional_info_file = []
self.output_seqs_fasta_as_list = []
# the number of series (rows) that have been added to the dataframes.
# this number will be used to delete the appropriate number of rows when producing
# the abundance only tables.
self.number_of_meta_rows_added = 0
# the number of columns that are associated with meta data
# (including the sample names, qc data, no_name summaries and user supplied data)
# this number will be used to delete the appropriate number of columns when producing
# the abundance only tables.
self.number_of_meta_cols_added = 0
def _init_output_paths(self):
self.output_paths_list = []
if self.analysis_obj:
self._set_analysis_seq_table_output_paths()
else:
self._set_non_analysis_seq_table_output_paths()
self.pre_med_absolute_df_path = None
self.pre_med_relative_df_path = None
self.pre_med_fasta_out_path = None
def _set_non_analysis_seq_table_output_paths(self):
self._set_non_analysis_abs_count_tab_output_paths()