-
Notifications
You must be signed in to change notification settings - Fork 37
/
isatab.py
7011 lines (6259 loc) · 303 KB
/
isatab.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
# -*- coding: utf-8 -*-
"""Functions for reading, writing and validating ISA-Tab.
Functions for reading and writing ISA-Tab. ISA content is loaded into an
in-memory representation using the ISA Data Model implemented in the
isatools.model package.
"""
from __future__ import absolute_import
import csv
import glob
import io
import json
import logging
import math
import os
import re
import shutil
import tempfile
from bisect import bisect_left, bisect_right
from io import StringIO
from itertools import tee, zip_longest
import iso8601
import networkx as nx
import numpy as np
import pandas as pd
from pandas.io.parsers import ParserError
from progressbar import ETA, Bar, ProgressBar, SimpleProgress
from isatools import logging as isa_logging
from isatools.io import isatab_configurator
from isatools.model import (
Assay,
Characteristic,
Comment,
DataFile,
FactorValue,
Investigation,
Material,
OntologyAnnotation,
OntologySource,
ParameterValue,
Person,
Process,
Protocol,
ProtocolParameter,
Publication,
Sample,
Source,
Study,
StudyFactor,
plink,
)
from isatools.utils import utf8_text_file_open
log = logging.getLogger('isatools')
def xml_config_contents(filename):
"""Gets the contents of a ISA Configuration XML file
:param filename: ISA Configuration XML filename
:return: String content of the configuration file
"""
config_filepath = os.path.join(
os.path.dirname(__file__),
'resources',
'config',
'xml',
filename,
)
with open(config_filepath) as f:
return f.read()
STUDY_SAMPLE_XML_CONFIG = xml_config_contents('studySample.xml')
NUMBER_OF_STUDY_GROUPS = 'Comment[Number of Study Groups]'
class _Defaults(object):
"""An internal object to hold defaults for ISA-Tab features"""
def __init__(self):
self._tab_options = {
# read cell quotes as part of cell values
'readCellQuotes': False,
# write out cell values enclosed with quotes
'writeCellQuotes': True,
'forceFitColumns': True,
'validateBeforeRead': False,
'validateAfterWrite': False
}
self._show_progressbar = False
self._log_level = logging.WARNING
def set_tab_option(self, optname, optvalue):
self._tab_options[optname] = optvalue
def set_defaults(self, show_progressbar=None, log_level=None):
if show_progressbar is not None:
self._show_progressbar = show_progressbar
if log_level is not None:
self._log_level = log_level
@property
def tab_options(self):
return self._tab_options
@property
def show_progressbar(self):
return self._show_progressbar
@property
def log_level(self):
return self._log_level
defaults = _Defaults()
def set_defaults(show_progressbar=None, log_level=None):
"""Set the default ISA-Tab options
:param show_progressbar: Boolean flag on whether to show progressbar in
standard outputs
:param log_level: Logging level (INFO, WARN, DEBUG) as standard Python
logging levels.
:return: None
"""
defaults.set_defaults(show_progressbar, log_level)
def set_tab_option(optname, optvalue):
"""Set the default value for one of the options that gets passed into the
IsaTabParser or IsaTabWriter constructor.
:param optname: Option name as a string
:param optvalue: Option value
:return: None
"""
defaults.tab_options[optname] = optvalue
class TransposedTabParser(object):
"""
Parser for transposed tables, such as the ISA-Tab investigation table,
or the MAGE-TAB IDF table. The headings are in column 0 with values,
perhaps multiple, reading in columns towards the right. These tables do
not necessarily have an even shape (row lengths may differ).
This reads the transposed table into a dictionary where key is heading and
value is a list of cell values for the heading. No relations between
headings is assumed and the order of values is implied by the order of the
cell value lists.
Does not allow duplicate labels.
"""
def __init__(
self, tab_options=None, show_progressbar=None, log_level=None):
if tab_options is None:
self.tab_options = defaults.tab_options
else:
self.tab_options = tab_options
if show_progressbar is None:
self.show_progressbar = defaults.show_progressbar
else:
self.show_progressbar = show_progressbar
if log_level is None:
self.log_level = defaults.log_level
else:
if not isinstance(tab_options, dict):
raise TypeError(
'tab_options must be dict, not {tab_options_type}'
.format(tab_options_type=type(tab_options))
)
self.log_level = log_level
self._ttable_dict = dict(header=list(), table=dict())
def parse(self, filename):
"""Parse a transposed table into a dictionary for further processing
downstream
:param filename: Path to a table file to parse
:return: A dictionary with the table contents indexed with keys
corresponding to the column headers
"""
try:
with utf8_text_file_open(filename) as unicode_file:
ttable_reader = csv.reader(
filter(lambda r: r[0] != '#', unicode_file),
dialect='excel-tab')
for row in ttable_reader:
if len(row) > 0:
key = get_squashed(key=row[0])
self._ttable_dict['header'].append(key)
self._ttable_dict['table'][key] = row[1:]
except UnicodeDecodeError:
with open(filename, encoding='ISO8859-2') as latin2_file:
ttable_reader = csv.reader(
filter(lambda r: r[0] != '#', latin2_file),
dialect='excel-tab')
for row in ttable_reader:
if len(row) > 0:
key = get_squashed(key=row[0])
self._ttable_dict['header'].append(key)
self._ttable_dict['table'][key] = row[1:]
return self._ttable_dict
validator_errors = []
validator_warnings = []
validator_info = []
# REGEXES
_RX_I_FILE_NAME = re.compile(r'i_(.*?)\.txt')
_RX_DATA = re.compile(r'data\[(.*?)\]')
_RX_COMMENT = re.compile(r'Comment\[(.*?)\]')
_RX_DOI = re.compile(r'(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?![%"#? ])\\S)+)')
_RX_PMID = re.compile(r'[0-9]{8}')
_RX_PMCID = re.compile(r'PMC[0-9]{8}')
_RX_CHARACTERISTICS = re.compile(r'Characteristics\[(.*?)\]')
_RX_PARAMETER_VALUE = re.compile(r'Parameter Value\[(.*?)\]')
_RX_FACTOR_VALUE = re.compile(r'Factor Value\[(.*?)\]')
_RX_INDEXED_COL = re.compile(r'(.*?)\.\d+')
# column labels
_LABELS_MATERIAL_NODES = ['Source Name', 'Sample Name', 'Extract Name',
'Labeled Extract Name']
_LABELS_DATA_NODES = ['Raw Data File', 'Raw Spectral Data File',
'Derived Spectral Data File', 'Derived Array Data File',
'Array Data File', 'Protein Assignment File',
'Peptide Assignment File',
'Post Translational Modification Assignment File',
'Acquisition Parameter Data File',
'Free Induction Decay Data File',
'Derived Array Data Matrix File', 'Image File',
'Derived Data File', 'Metabolite Assignment File']
_LABELS_ASSAY_NODES = ['Assay Name', 'MS Assay Name',
'Hybridization Assay Name', 'Scan Name',
'Data Transformation Name', 'Normalization Name']
def dump(isa_obj, output_path, i_file_name='i_investigation.txt',
skip_dump_tables=False, write_factor_values_in_assay_table=False):
"""Serializes ISA objects to ISA-Tab
:param isa_obj: An ISA Investigation object
:param output_path: Path to write the ISA-Tab files to
:param i_file_name: Overrides the default name for the investigation file
:param skip_dump_tables: Boolean flag on whether or not to write the
study sample table files and assay table files
:param write_factor_values_in_assay_table: Boolean flag indicating whether
or not to write Factor Values in the assay table files
:return: None
"""
def build_comments(some_isa_study_object, some_associated_data_frame):
"""Build comments if multiple comments
:param some_isa_study_object: Any of the Commentable ISA objects
:param some_associated_data_frame: the data frames associated to the object (if implemented that ways)
:return: the 2 input parameters augmented with the relevant information
"""
if some_isa_study_object.comments is not None:
for this_comment in sorted(some_isa_study_object.comments, key=lambda x: x.name):
field = "Comment[" + this_comment.name + "]"
some_associated_data_frame[field] = this_comment.value
return some_isa_study_object, some_associated_data_frame
def _build_roles_str(roles):
"""Build roles strings if multiple roles
:param roles: A list of OntologyAnnotation objects describing the roles
:return: Lists of strings corresponding to the list of role names,
accession numbers and term source references.
"""
log.debug('building roles from: %s', roles)
if roles is None:
roles = list()
roles_names = ''
roles_accession_numbers = ''
roles_source_refs = ''
for role in roles:
roles_names += (role.term if role.term else '') + ';'
roles_accession_numbers += \
(role.term_accession if role.term_accession else '') + ';'
roles_source_refs += \
(role.term_source.name if role.term_source else '') + ';'
if len(roles) > 0:
roles_names = roles_names[:-1]
roles_accession_numbers = roles_accession_numbers[:-1]
roles_source_refs = roles_source_refs[:-1]
log.debug('role_names: %s', roles)
log.debug('roles_accession_numbers: %s', roles)
log.debug('roles_source_refs: %s', roles)
return roles_names, roles_accession_numbers, roles_source_refs
def _build_ontology_reference_section(ontologies=list()):
"""Build ontology reference section DataFrame
:param prefix: Section prefix - ''
:param ontologies: List of Ontology objects describing the section's
Ontology Resource
:return: DataFrame corresponding to the ONTOLOGY REFERENCE section
"""
log.debug('building ontology resource reference from: %s', ontologies)
ontology_source_references_df_cols = ['Term Source Name',
'Term Source File',
'Term Source Version',
'Term Source Description']
seen_comments = {}
# step1: going over each object and pulling associated comments to build a full list of those
for ontology in ontologies:
for comment in ontology.comments:
if comment.name in seen_comments.keys():
seen_comments[comment.name].append(comment.value)
else:
seen_comments[comment.name] = [comment.value]
# step2: based on the list of unique Comments, create the relevant ISA headers
for comment_name in seen_comments.keys():
ontology_source_references_df_cols.append('Comment[' + comment_name + ']')
ontology_source_references_df = pd.DataFrame(columns=tuple(ontology_source_references_df_cols))
for i, ontology in enumerate(ontologies):
log.debug('%s iteration, item=%s', i, ontology)
ontology_source_references_df_row = [
ontology.name,
ontology.file,
ontology.version,
ontology.description
]
# for j, _ in enumerate(max_comment):
# log.debug('%s iteration, item=%s', j, _)
# try:
# if 'Comment[' + ontology.comments[j].name + ']' in ontology_source_references_df_cols:
# ontology_source_references_df_row.append(ontology.comments[j].value)
# else:
# ontology_source_references_df_row.append('')
# except IndexError:
# ontology_source_references_df_row.append('')
common_names = []
for comment in ontology.comments:
common_names.append(comment.name)
# now check which comments are associated to it out of the full possible range of Comments
# if a match is found, get the value and add it to the record
for key in seen_comments.keys():
if key in common_names:
for element in ontology.comments:
if element.name == key:
ontology_source_references_df_row.append(element.value)
else:
ontology_source_references_df_row.append("")
log.debug('row=%s', ontology_source_references_df_row)
ontology_source_references_df.loc[i] = ontology_source_references_df_row
return ontology_source_references_df.set_index('Term Source Name').T
def _build_contacts_section_df(prefix='Investigation', contacts=list()):
"""Build contacts section DataFrame
:param prefix: Section prefix - Investigation or Study
:param contacts: List of Person objects describing the section's
contacts
:return: DataFrame corresponding to the CONTACTS section
"""
log.debug('building contacts from: %s', contacts)
contacts_df_cols = [prefix + ' Person Last Name',
prefix + ' Person First Name',
prefix + ' Person Mid Initials',
prefix + ' Person Email',
prefix + ' Person Phone',
prefix + ' Person Fax',
prefix + ' Person Address',
prefix + ' Person Affiliation',
prefix + ' Person Roles',
prefix + ' Person Roles Term Accession Number',
prefix + ' Person Roles Term Source REF']
seen_comments = {}
# step1: going over each object and pulling associated comments to build a full list of those
for contact in contacts:
for comment in contact.comments:
if comment.name in seen_comments.keys():
seen_comments[comment.name].append(comment.value)
else:
seen_comments[comment.name] = [comment.value]
# step2: based on the list of unique Comments, create the relevant ISA headers
for comment_name in seen_comments.keys():
contacts_df_cols.append('Comment[' + comment_name + ']')
contacts_df = pd.DataFrame(columns=tuple(contacts_df_cols))
for i, contact in enumerate(contacts):
log.debug('%s iteration, item=%s', i, contact)
roles_names, roles_accession_numbers, roles_source_refs = \
_build_roles_str(contact.roles)
contacts_df_row = [
contact.last_name,
contact.first_name,
contact.mid_initials,
contact.email,
contact.phone,
contact.fax,
contact.address,
contact.affiliation,
roles_names,
roles_accession_numbers,
roles_source_refs
]
# for j, _ in enumerate(max_comment.comments):
# log.debug('%s iteration, item=%s', j, _)
# try:
# contacts_df_row.append(contact.comments[j].value)
# except IndexError:
# contacts_df_row.append('')
common_names = []
for comment in contact.comments:
common_names.append(comment.name)
# now check which comments are associated to it out of the full possible range of Comments
# if a match is found, get the value and add it to the record
for key in seen_comments.keys():
if key in common_names:
for element in contact.comments:
if element.name == key:
contacts_df_row.append(element.value)
else:
contacts_df_row.append("")
log.debug('row=%s', contacts_df_row)
contacts_df.loc[i] = contacts_df_row
return contacts_df.set_index(prefix + ' Person Last Name').T
def _build_publications_section_df(prefix='Investigation', publications=list()):
"""Build contacts section DataFrame
:param prefix: Section prefix - Investigation or Study
:param publications: List of Publications objects describing the
section's publications
:return: DataFrame corresponding to the PUBLICATIONS section
"""
log.debug('building contacts from: %s', publications)
publications_df_cols = [
prefix + ' PubMed ID',
prefix + ' Publication DOI',
prefix + ' Publication Author List',
prefix + ' Publication Title',
prefix + ' Publication Status',
prefix + ' Publication Status Term Accession Number',
prefix + ' Publication Status Term Source REF']
seen_comments = {}
# step1: going over each object and pulling associated comments to build a full list of those
for publication in publications:
for comment in publication.comments:
if comment.name in seen_comments.keys():
seen_comments[comment.name].append(comment.value)
else:
seen_comments[comment.name] = [comment.value]
# step2: based on the list of unique Comments, create the relevant ISA headers
for comment_name in seen_comments.keys():
publications_df_cols.append('Comment[' + comment_name + ']')
this_publications_df = pd.DataFrame(columns=tuple(publications_df_cols))
for i, publication in enumerate(publications):
log.debug('%s iteration, item=%s', i, publication)
if publication.status is not None:
status_term = publication.status.term
status_term_accession = publication.status.term_accession
if publication.status.term_source is not None:
status_term_source_name = \
publication.status.term_source.name
else:
status_term_source_name = ''
else:
status_term = ''
status_term_accession = ''
status_term_source_name = ''
publications_df_row = [
publication.pubmed_id,
publication.doi,
publication.author_list,
publication.title,
status_term,
status_term_accession,
status_term_source_name,
]
# for j, _ in enumerate(max_comment):
# log.debug('%s iteration, item=%s', j, _)
# try:
# if 'Comment[' + publication.comments[j].name + ']' in publications_df_cols:
# publications_df_row.append(publication.comments[j].value)
# else:
# publications_df_row.append('')
# except IndexError:
# publications_df_row.append('')
# here, given an object, we create a list comments fields associated to it
common_names = []
for comment in publication.comments:
common_names.append(comment.name)
# now check which comments are associated to it out of the full possible range of Comments
# if a match is found, get the value and add it to the record
for key in seen_comments.keys():
if key in common_names:
for element in publication.comments:
if element.name == key:
publications_df_row.append(element.value)
else:
publications_df_row.append("")
log.debug('row=%s', publications_df_row)
this_publications_df.loc[i] = publications_df_row
return this_publications_df.set_index(prefix + ' PubMed ID').T
def _build_protocols_section_df(protocols=list()):
"""Build Protocol section DataFrame
:param prefix: Section prefix - Investigation or Study
:param protocols: List of Publications objects describing the
section's protocols
:return: DataFrame corresponding to the PROTOCOLS section
"""
log.debug('building contacts from: %s', protocols)
study_protocols_df_cols = [
'Study Protocol Name',
'Study Protocol Type',
'Study Protocol Type Term Accession Number',
'Study Protocol Type Term Source REF',
'Study Protocol Description',
'Study Protocol URI',
'Study Protocol Version',
'Study Protocol Parameters Name',
'Study Protocol Parameters Name Term Accession Number',
'Study Protocol Parameters Name Term Source REF',
'Study Protocol Components Name',
'Study Protocol Components Type',
'Study Protocol Components Type Term Accession Number',
'Study Protocol Components Type Term Source REF',
]
seen_comments = {}
# step1: going over each object and pulling associated comments to build a full list of those
for protocol in protocols:
for comment in protocol.comments:
if comment.name in seen_comments.keys():
seen_comments[comment.name].append(comment.value)
else:
seen_comments[comment.name] = [comment.value]
# step2: based on the list of unique Comments, create the relevant ISA headers
for comment_name in seen_comments.keys():
study_protocols_df_cols.append('Comment[' + comment_name + ']')
this_study_protocols_df = pd.DataFrame(columns=tuple(study_protocols_df_cols))
protocol_type_term = ''
protocol_type_term_accession = ''
protocol_type_term_source_name = ''
for i, protocol in enumerate(protocols):
parameters_names = ''
parameters_accession_numbers = ''
parameters_source_refs = ''
for parameter in protocol.parameters:
parameters_names += parameter.parameter_name.term + ';'
parameters_accession_numbers \
+= (parameter.parameter_name.term_accession
if parameter.parameter_name.term_accession is not None
else '') + ';'
parameters_source_refs \
+= (parameter.parameter_name.term_source.name
if parameter.parameter_name.term_source else '') + ';'
if len(protocol.parameters) > 0:
parameters_names = parameters_names[:-1]
parameters_accession_numbers = \
parameters_accession_numbers[:-1]
parameters_source_refs = parameters_source_refs[:-1]
component_names = ''
component_types = ''
component_types_accession_numbers = ''
component_types_source_refs = ''
for component in protocol.components:
component_names += component.name + ';'
component_types += component.component_type.term + ';'
component_types_accession_numbers += \
component.component_type.term_accession + ';'
component_types_source_refs += \
component.component_type.term_source.name \
if component.component_type.term_source else '' + ';'
if len(protocol.components) > 0:
component_names = component_names[:-1]
component_types = component_types[:-1]
component_types_accession_numbers = \
component_types_accession_numbers[:-1]
component_types_source_refs = component_types_source_refs[:-1]
if protocol.protocol_type is not None:
protocol_type_term = protocol.protocol_type.term
protocol_type_term_accession = protocol.protocol_type.term_accession
if protocol.protocol_type.term_source:
protocol_type_term_source_name = protocol.protocol_type.term_source.name
study_protocols_df_row = [
protocol.name,
protocol_type_term,
protocol_type_term_accession,
protocol_type_term_source_name,
protocol.description,
protocol.uri,
protocol.version,
parameters_names,
parameters_accession_numbers,
parameters_source_refs,
component_names,
component_types,
component_types_accession_numbers,
component_types_source_refs
]
# here, given an object, we create a list comments fields associated to it
common_names = []
for comment in protocol.comments:
common_names.append(comment.name)
# now check which comments are associated to it out of the full possible range of Comments
# if a match is found, get the value and add it to the record
for key in seen_comments.keys():
if key in common_names:
for element in protocol.comments:
if element.name == key:
study_protocols_df_row.append(element.value)
else:
study_protocols_df_row.append("")
log.debug('row=%s', study_protocols_df_row)
this_study_protocols_df.loc[i] = study_protocols_df_row
return this_study_protocols_df.set_index('Study Protocol Name').T
def _build_assays_section_df(assays=list()):
"""Build Factors section DataFrame
:param assays: List of Study Assay objects describing the
section's assays
:return: DataFrame corresponding to the STUDY ASSAY section
"""
log.debug('building contacts from: %s', assays)
study_assays_df_cols = [
'Study Assay File Name',
'Study Assay Measurement Type',
'Study Assay Measurement Type Term Accession Number',
'Study Assay Measurement Type Term Source REF',
'Study Assay Technology Type',
'Study Assay Technology Type Term Accession Number',
'Study Assay Technology Type Term Source REF',
'Study Assay Technology Platform'
]
seen_comments = {}
# step1: going over each object and pulling associated comments to build a full list of those
for assay in assays:
for comment in assay.comments:
if comment.name in seen_comments.keys():
seen_comments[comment.name].append(comment.value)
else:
seen_comments[comment.name] = [comment.value]
# step2: based on the list of unique Comments, create the relevant ISA headers
for comment_name in seen_comments.keys():
study_assays_df_cols.append('Comment[' + comment_name + ']')
this_study_assays_df = pd.DataFrame(columns=tuple(study_assays_df_cols))
for i, assay in enumerate(assays):
study_assays_df_row = [
assay.filename,
assay.measurement_type.term,
assay.measurement_type.term_accession,
assay.measurement_type.term_source.name
if assay.measurement_type.term_source else '',
assay.technology_type.term,
assay.technology_type.term_accession,
assay.technology_type.term_source.name
if assay.technology_type.term_source else '',
assay.technology_platform
]
# here, given an object, we create a list comments fields associated to it
common_names = []
for comment in assay.comments:
common_names.append(comment.name)
# now check which comments are associated to it out of the full possible range of Comments
# if a match is found, get the value and add it to the record
for key in seen_comments.keys():
if key in common_names:
for element in assay.comments:
if element.name == key:
study_assays_df_row.append(element.value)
else:
study_assays_df_row.append("")
log.debug('row=%s', study_assays_df_row)
this_study_assays_df.loc[i] = study_assays_df_row
return this_study_assays_df.set_index('Study Assay File Name').T
def _build_factors_section_df(factors=list()):
"""Build Factors section DataFrame
:param factors: List of Study Factor objects describing the
section's factor
:return: DataFrame corresponding to the STUDY FACTORS section
"""
log.debug('building contacts from: %s', factors)
study_factors_df_cols = ['Study Factor Name',
'Study Factor Type',
'Study Factor Type Term Accession Number',
'Study Factor Type Term Source REF']
seen_comments = {}
# step1: going over each object and pulling associated comments to build a full list of those
for factor in factors:
for comment in factor.comments:
if comment.name in seen_comments.keys():
seen_comments[comment.name].append(comment.value)
else:
seen_comments[comment.name] = [comment.value]
# step2: based on the list of unique Comments, create the relevant ISA headers
for comment_name in seen_comments.keys():
study_factors_df_cols.append('Comment[' + comment_name + ']')
this_study_factors_df = pd.DataFrame(columns=tuple(study_factors_df_cols))
# step4: for each object, create a record
for i, factor in enumerate(factors):
if factor.factor_type is not None:
factor_type_term = factor.factor_type.term
factor_type_term_accession = factor.factor_type.term_accession
if factor.factor_type.term_source is not None:
factor_type_term_term_source_name = \
factor.factor_type.term_source.name
else:
factor_type_term_term_source_name = ''
else:
factor_type_term = ''
factor_type_term_accession = ''
factor_type_term_term_source_name = ''
study_factors_df_row = [
factor.name,
factor_type_term,
factor_type_term_accession,
factor_type_term_term_source_name
if factor.factor_type.term_source else ''
]
# here, given an object, we create a list comments fields associated to it
common_names = []
for comment in factor.comments:
common_names.append(comment.name)
# now check which comments are associated to it out of the full possible range of Comments
# if a match is found, get the value and add it to the record
for key in seen_comments.keys():
if key in common_names:
for element in factor.comments:
if element.name == key:
study_factors_df_row.append(element.value)
else:
study_factors_df_row.append("")
log.debug('row=%s', study_factors_df_row)
this_study_factors_df.loc[i] = study_factors_df_row
return this_study_factors_df.set_index('Study Factor Name').T
def _build_design_descriptors_section(design_descriptors=list()):
study_design_descriptors_df_cols = ['Study Design Type',
'Study Design Type Term Accession Number',
'Study Design Type Term Source REF']
seen_comments = {}
# step1: going over each object and pulling associated comments to build a full list of those
for design_descriptor in design_descriptors:
for comment in design_descriptor.comments:
if comment.name in seen_comments.keys():
seen_comments[comment.name].append(comment.value)
else:
seen_comments[comment.name] = [comment.value]
# step2: based on the list of unique Comments, create the relevant ISA headers
for comment_name in seen_comments.keys():
study_design_descriptors_df_cols.append('Comment[' + comment_name + ']')
# step3: build a data frame based on the headers available from step 2
this_study_design_descriptors_df = pd.DataFrame(columns=tuple(study_design_descriptors_df_cols))
# step4: for each object, create a record
for i, design_descriptor in enumerate(design_descriptors):
study_design_descriptors_df_row = [
design_descriptor.term,
design_descriptor.term_accession,
design_descriptor.term_source.name
if design_descriptor.term_source else ''
]
# here, given an object, we create a list comments fields associated to it
common_names = []
for comment in design_descriptor.comments:
common_names.append(comment.name)
# now check which comments are associated to it out of the full possible range of Comments
# if a match is found, get the value and add it to the record
for key in seen_comments.keys():
if key in common_names:
for element in design_descriptor.comments:
if element.name == key:
study_design_descriptors_df_row.append(element.value)
else:
study_design_descriptors_df_row.append("")
log.debug('row=%s', study_design_descriptors_df_row)
this_study_design_descriptors_df.loc[i] = study_design_descriptors_df_row
return this_study_design_descriptors_df.set_index('Study Design Type').T
if not _RX_I_FILE_NAME.match(i_file_name):
log.debug('investigation filename=', i_file_name)
raise NameError('Investigation file must match pattern i_*.txt, got {}'
.format(i_file_name))
if os.path.exists(output_path):
fp = open(os.path.join(
output_path, i_file_name), 'w', encoding='utf-8')
else:
log.debug('output_path=', i_file_name)
raise FileNotFoundError("Can't find " + output_path)
if not isinstance(isa_obj, Investigation):
log.debug('object type=', type(isa_obj))
raise NotImplementedError("Can only dump an Investigation object")
# Process Investigation object first to write the investigation file
investigation = isa_obj
# Write ONTOLOGY SOURCE REFERENCE section
ontology_source_references_df =_build_ontology_reference_section(ontologies=investigation.ontology_source_references)
fp.write('ONTOLOGY SOURCE REFERENCE\n')
# Need to set index_label as top left cell
ontology_source_references_df.to_csv(
path_or_buf=fp, mode='a', sep='\t', encoding='utf-8',
index_label='Term Source Name')
# Write INVESTIGATION section
inv_df_cols = ['Investigation Identifier',
'Investigation Title',
'Investigation Description',
'Investigation Submission Date',
'Investigation Public Release Date']
for comment in sorted(investigation.comments, key=lambda x: x.name):
inv_df_cols.append('Comment[' + comment.name + ']')
investigation_df = pd.DataFrame(columns=tuple(inv_df_cols))
inv_df_rows = [
investigation.identifier,
investigation.title,
investigation.description,
investigation.submission_date,
investigation.public_release_date
]
for comment in sorted(investigation.comments, key=lambda x: x.name):
inv_df_rows.append(comment.value)
investigation_df.loc[0] = inv_df_rows
investigation_df = investigation_df.set_index('Investigation Identifier').T
fp.write('INVESTIGATION\n')
investigation_df.to_csv(
path_or_buf=fp, mode='a', sep='\t', encoding='utf-8',
index_label='Investigation Identifier')
# Write INVESTIGATION PUBLICATIONS section
investigation_publications_df = _build_publications_section_df(prefix='Investigation',
publications=investigation.publications)
fp.write('INVESTIGATION PUBLICATIONS\n')
investigation_publications_df.to_csv(
path_or_buf=fp, mode='a', sep='\t', encoding='utf-8',
index_label='Investigation PubMed ID')
# Write INVESTIGATION CONTACTS section
investigation_contacts_df = _build_contacts_section_df(
contacts=investigation.contacts)
fp.write('INVESTIGATION CONTACTS\n')
investigation_contacts_df.to_csv(
path_or_buf=fp, mode='a', sep='\t', encoding='utf-8',
index_label='Investigation Person Last Name')
# Write STUDY sections
for study in investigation.studies:
study_df_cols = ['Study Identifier',
'Study Title',
'Study Description',
'Study Submission Date',
'Study Public Release Date',
'Study File Name']
if study.comments is not None:
for comment in sorted(study.comments, key=lambda x: x.name):
study_df_cols.append('Comment[' + comment.name + ']')
study_df = pd.DataFrame(columns=tuple(study_df_cols))
study_df_row = [
study.identifier,
study.title,
study.description,
study.submission_date,
study.public_release_date,
study.filename
]
if study.comments is not None:
for comment in sorted(study.comments, key=lambda x: x.name):
study_df_row.append(comment.value)
study_df.loc[0] = study_df_row
study_df = study_df.set_index('Study Identifier').T
fp.write('STUDY\n')
study_df.to_csv(path_or_buf=fp, mode='a', sep='\t', encoding='utf-8',
index_label='Study Identifier')
# Write STUDY DESIGN DESCRIPTORS section
# study_design_descriptors_df = pd.DataFrame(
# columns=('Study Design Type',
# 'Study Design Type Term Accession Number',
# 'Study Design Type Term Source REF'))
# for i, design_descriptor in enumerate(study.design_descriptors):
# study_design_descriptors_df.loc[i] = [
# design_descriptor.term,
# design_descriptor.term_accession,
# design_descriptor.term_source.name
# if design_descriptor.term_source else ''
# ]
#
# build_comments(design_descriptor, study_design_descriptors_df.loc[i])
#
# study_design_descriptors_df = \
# study_design_descriptors_df.set_index('Study Design Type').
study_design_descriptors_df = _build_design_descriptors_section(design_descriptors=study.design_descriptors)
fp.write('STUDY DESIGN DESCRIPTORS\n')
study_design_descriptors_df.to_csv(
path_or_buf=fp, mode='a', sep='\t', encoding='utf-8',
index_label='Study Design Type')
# Write STUDY PUBLICATIONS section
study_publications_df = _build_publications_section_df(
prefix='Study', publications=study.publications)
fp.write('STUDY PUBLICATIONS\n')
study_publications_df.to_csv(
path_or_buf=fp, mode='a', sep='\t', encoding='utf-8',
index_label='Study PubMed ID')
# Write STUDY FACTORS section
study_factors_df = _build_factors_section_df(factors=study.factors)
fp.write('STUDY FACTORS\n')
study_factors_df.to_csv(
path_or_buf=fp, mode='a', sep='\t', encoding='utf-8',
index_label='Study Factor Name')
# Write STUDY ASSAYS section
# study_assays_df = pd.DataFrame(
# columns=(
# 'Study Assay File Name',
# 'Study Assay Measurement Type',
# 'Study Assay Measurement Type Term Accession Number',
# 'Study Assay Measurement Type Term Source REF',
# 'Study Assay Technology Type',