-
Notifications
You must be signed in to change notification settings - Fork 38
/
model.py
3073 lines (2735 loc) · 135 KB
/
model.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
"""
Model objects for storing study design settings, for consumption by
function or factory to create ISA model objects.
"""
from __future__ import absolute_import
import datetime
import itertools
import json
import re
from collections import OrderedDict, Iterable
from copy import deepcopy
import copy
import logging
from numbers import Number
from abc import ABC
from math import factorial
import os
import yaml
import uuid
import networkx as nx
from isatools.create import errors
from isatools.create.constants import (
SCREEN, RUN_IN, WASHOUT, FOLLOW_UP, ELEMENT_TYPES, INTERVENTIONS,
DURATION_FACTOR, BASE_FACTORS, SOURCE, SAMPLE, EXTRACT, LABELED_EXTRACT,
DATA_FILE, GROUP_PREFIX, SUBJECT_PREFIX, SAMPLE_PREFIX,
ASSAY_GRAPH_PREFIX,
RUN_ORDER, STUDY_CELL, assays_opts,
DEFAULT_SOURCE_TYPE, SOURCE_QC_SOURCE_NAME, QC_SAMPLE_NAME,
QC_SAMPLE_TYPE_PRE_RUN, QC_SAMPLE_TYPE_POST_RUN,
QC_SAMPLE_TYPE_INTERSPERSED, ZFILL_WIDTH, DEFAULT_PERFORMER
)
from isatools.model import (
StudyFactor,
FactorValue,
OntologyAnnotation,
OntologySource,
Characteristic,
Study,
Sample,
Assay,
Protocol,
Process,
ProtocolParameter,
ParameterValue,
Source,
Material,
DataFile,
RawDataFile,
RawSpectralDataFile,
FreeInductionDecayDataFile,
ArrayDataFile,
DerivedDataFile,
DerivedSpectralDataFile,
DerivedArrayDataFile,
ProteinAssignmentFile,
PeptideAssignmentFile,
DerivedArrayDataMatrixFile,
PostTranslationalModificationAssignmentFile,
AcquisitionParameterDataFile,
Extract,
LabeledExtract,
plink
)
from isatools.utils import urlify, n_digits
log = logging.getLogger('isatools')
log.setLevel(logging.INFO)
__author__ = 'massi'
def intersperse(lst, item):
"""
Utility method to intersperse an item in a list
:param lst:
:param item: the item to be interspersed
:return:
"""
result = [item] * (len(lst) * 2 - 1)
result[0::2] = lst
return result
class Element(ABC):
"""
Element is the building block of a study design
The Element class is abstract and has two implementations:
- NonTreatment
- Treatment
"""
def __init__(self):
self.__type = None
def __repr__(self):
return 'Element(type={0})'.format(self.type)
def __str__(self):
return repr(self)
def __hash__(self):
return hash(repr(self))
def __eq__(self, other):
return isinstance(other, Element) and self.type == other.type
def __ne__(self, other):
return not self == other
@property
def type(self):
return self.__type
@type.setter
def type(self, element_type):
self.__type = element_type
@property
def factor_values(self):
return set()
@property
def duration(self):
return 0
def update_duration(self, duration_value, duration_unit=None):
pass
class NonTreatment(Element):
"""
A NonTreatment is defined only by 1 factor values specifying its duration
and a type. Allowed types are SCREEN, RUN-IN, WASHOUT and FOLLOW-UP.
A NonTreatment is an extension of the basic Element
"""
def __init__(self, element_type=ELEMENT_TYPES['SCREEN'], duration_value=0.0, duration_unit=None):
super(NonTreatment, self).__init__()
if element_type not in ELEMENT_TYPES.values():
raise ValueError('element treatment type provided: ')
self.__type = element_type
if not isinstance(duration_value, Number):
raise ValueError('duration_value must be a Number. Value provided is {0}'.format(duration_value))
self.__duration = FactorValue(factor_name=DURATION_FACTOR, value=duration_value, unit=duration_unit)
def __repr__(self):
return '{0}.{1}(type={2}, duration={3})'.format(
self.__class__.__module__, self.__class__.__name__, repr(self.type), repr(self.duration)
)
def __str__(self):
return """{0}(
type={1},
duration={2}
)""".format(self.__class__.__name__, repr(self.type), repr(self.duration))
def __hash__(self):
return hash(repr(self))
def __eq__(self, other):
return isinstance(other, NonTreatment) and self.type == other.type and self.duration == other.duration
def __ne__(self, other):
return not self == other
@property
def type(self):
return self.__type
@type.setter
def type(self, element_type):
if element_type in ELEMENT_TYPES.values():
self.__type = element_type
else:
raise ValueError('invalid treatment type provided: ')
@property
def factor_values(self):
return {self.__duration}
@property
def duration(self):
return self.__duration
def update_duration(self, duration_value, duration_unit=None):
if not isinstance(duration_value, Number):
raise ValueError('duration_value must be a Number. Value provided is {0}'.format(duration_value))
self.__duration.value = duration_value
self.__duration.unit = duration_unit
class Treatment(Element):
"""
A Treatment is defined as a set of factor values (as defined in the ISA
model v1) and a treatment type
A Treatment is an extension of the basic Element
"""
def __init__(self, element_type=INTERVENTIONS['CHEMICAL'],
factor_values=None):
"""
Creates a new Treatment
:param element_type: treatment type
:param factor_values: set of isatools.model.v1.FactorValue
"""
super(Treatment, self).__init__()
if not isinstance(element_type, (str, OntologyAnnotation)):
raise ValueError('intervention_type must be string or OntologyAnnotation. {} was provided.'.format(
element_type
))
self.__type = element_type
if factor_values is None:
self.__factor_values = set()
else:
self.factor_values = factor_values
def __repr__(self):
return '{0}.{1}(type={2}, factor_values={3})'.format(
self.__class__.__module__, self.__class__.__name__,
self.type, sorted(self.factor_values, key=lambda x: repr(x)))
def __str__(self):
return """"{0}
(type={1},
factor_values={2})
""".format(
self.__class__.__name__,
self.type, sorted(self.factor_values, key=lambda x: repr(x)))
def __hash__(self):
return hash(repr(self))
def __eq__(self, other):
return isinstance(other, Treatment) \
and self.type == other.type \
and self.factor_values == other.factor_values
def __ne__(self, other):
return not self == other
@property
def type(self):
return self.__type
@type.setter
def type(self, treatment_type):
if treatment_type in INTERVENTIONS.values():
self.__type = treatment_type
else:
raise ValueError('invalid treatment type provided: ')
@property
def factor_values(self):
return self.__factor_values
@factor_values.setter
def factor_values(self, factor_values=()):
if isinstance(factor_values, (tuple, list, set)) \
and all([isinstance(factor_value, FactorValue)
for factor_value in factor_values]):
self.__factor_values = set(factor_values)
else:
raise AttributeError('Data supplied is not correctly formatted for Treatment')
@property
def duration(self):
return next(factor_value for factor_value in self.factor_values
if factor_value.factor_name == DURATION_FACTOR)
def update_duration(self, duration_value, duration_unit=None):
pass # TODO
class StudyCell(object):
"""
A StudyCell consists of a set of Elements who can be Treatment or NonTreatment Elements
Under the current design all elements in a a cell are intended to be concomitant
PROBLEM: what if different concomitant treatments within a cell have different durations?
ANSWER: this must not be allowed
PROBLEM: only allow concomitant treatments: concomitant non-treatments make no sense
"""
def __init__(self, name, elements=None):
self.__name = name if isinstance(name, str) else None # FIXME can we allow name to be none?
self.__elements = list()
if elements is not None:
self.elements = elements
def __repr__(self):
return '{0}.{1}(' \
'name={name}, ' \
'elements={elements}, ' \
')'.format(self.__class__.__module__, self.__class__.__name__, name=self.name, elements=[
sorted(el, key=lambda e: hash(e)) if isinstance(el, set) else el for el in self.elements
])
def __str__(self):
return """{0}(
name={name},
elements={elements_count} items,
)""".format(self.__class__.__name__, name=self.name,
elements_count=len(self.elements))
def __hash__(self):
return hash(repr(self))
def __eq__(self, other):
return isinstance(other, StudyCell) and self.name == other.name and self.elements == other.elements
def __ne__(self, other):
return not self == other
@property
def name(self):
return self.__name
@name.setter
def name(self, name):
if not isinstance(name, str):
raise AttributeError('StudyCell name must be a string')
self.__name = name
@property
def elements(self):
return self.__elements
@elements.setter
def elements(self, x):
if not isinstance(x, (Element, list, tuple)):
raise AttributeError('elements must be an Element, a list of Elements, or a tuple of Elements')
self.__elements.clear()
try:
if isinstance(x, Element):
self.insert_element(x)
else:
for element in x:
self.insert_element(element)
except ValueError as e:
raise AttributeError(e)
@staticmethod
def _non_treatment_check(previous_elements, new_element, insertion_index=None):
"""
Private method, to be called within insert_element()
:param previous_elements: the list of previous elements
:param new_element: the element to insert in the list of previous elements
:param insertion_index: the position in the list where the new element will be inserted
:return: bool
"""
if insertion_index is None:
insertion_index = len(previous_elements)
def check_screen():
if len(previous_elements) > 1:
return False
if len(previous_elements) == 1:
if previous_elements[0].type == RUN_IN and insertion_index == 0:
return True
else:
return False
return True
def check_run_in():
if len(previous_elements) > 1:
return False
if len(previous_elements) == 1:
if previous_elements[0].type == SCREEN and abs(insertion_index) == 1:
return True
else:
return False
return True
def check_washout():
next_element = previous_elements[insertion_index] if insertion_index < len(previous_elements) else None
previous_element = previous_elements[insertion_index - 1] if insertion_index > 0 else None
if isinstance(next_element, NonTreatment) or isinstance(previous_element, NonTreatment):
return False
return True
def check_follow_up():
return not bool(len(previous_elements))
switcher = {
SCREEN: check_screen,
RUN_IN: check_run_in,
WASHOUT: check_washout,
FOLLOW_UP: check_follow_up
}
func = switcher.get(new_element.type, lambda: False)
# lines = inspect.getsource(func)
return func()
@staticmethod
def _treatment_check(previous_elements):
"""
:param previous_elements: the list of previous elements
:return: bool
"""
not_allowed_elements = filter(lambda el: getattr(el, 'type', None) in [SCREEN, RUN_IN, FOLLOW_UP],
previous_elements)
return not bool(len(list(not_allowed_elements)))
def _concomitant_treatments_check(self, element_set):
"""
This method checks that the duration value and unit are the same for all treatments within
the provided element_set
:param element_set: set
:return: bool
"""
if not self._treatment_check(self.elements):
return False
if any(not isinstance(el, Treatment) for el in element_set):
return False
duration_set = {el.duration for el in element_set}
return True if len(duration_set) == 1 else False
def insert_element(self, element, element_index=None):
"""
Add an Element object to a StudyCell
:param element: an Element or a set of Treatments (to represent concomitant treatments)
:param element_index (int)
Rules to insert an element or a set of elements:
- Screen NonTreatments must either be in a 1-element StudyCell or in a 2-element if followed by a Run-in
- Run-in NonTreatments must either be in a 1-element StudyCell or in a 2-element if preceded by a Screen
- A Follow-up NonTreatment must be in a 1-element StudyCell
- WAshout NonTreatments cannot be chained one after the other
- Concomitant Treatments (if provided in a set) must have the same duration
:return:
"""
index = len(self.elements) if not isinstance(element_index, int) else \
element_index if abs(element_index) < len(self.elements) else len(self.elements)
if not isinstance(element, (Element, set)):
raise ValueError('element must be either an Element or a set of treatments')
is_valid = self._non_treatment_check(self.elements, element, index) if isinstance(element, NonTreatment) else \
self._treatment_check(self.elements) if isinstance(element, Treatment) else \
self._concomitant_treatments_check(element) if isinstance(element, set) else False
if is_valid:
self.__elements.insert(index, element)
else:
raise ValueError('Element is not valid')
def contains_non_treatment_element_by_type(self, non_treatment_type):
"""
Evaluates whether the current cell contains a NonTreatment of a specific type
:param non_treatment_type: str - specifies whether it is a SCREEN, RUN-IN, WASHOUT, or FOLLOW-UP
:return: bool
"""
return any(el for el in self.elements if isinstance(el, NonTreatment) and el.type == non_treatment_type)
def get_all_elements(self):
all_elements = []
for el in self.elements:
if isinstance(el, Element):
all_elements.append(el)
elif isinstance(el, set):
for concomitant_el in el:
all_elements.append(concomitant_el)
return all_elements
@property
def duration(self):
# TODO recompute as sum of durations
return None
class OntologyAnnotationEncoder(json.JSONEncoder):
@staticmethod
def ontology_source(obj):
if isinstance(obj, str):
return obj
if isinstance(obj, OntologySource):
res = {
"name": obj.name
}
if obj.file:
res["file"] = obj.file
if obj.version:
res["version"] = obj.version
if obj.description:
res["description"] = obj.description
return res
def ontology_annotation(self, obj):
if isinstance(obj, str):
return obj
if isinstance(obj, OntologyAnnotation):
res = {
"term": obj.term
}
if obj.term_accession:
res["termAccession"] = obj.term_accession
if obj.term_source:
res["termSource"] = self.ontology_source(obj.term_source)
return res
def default(self, obj):
return self.ontology_annotation(obj)
class CharacteristicEncoder(json.JSONEncoder):
@staticmethod
def characteristic(obj):
onto_encoder = OntologyAnnotationEncoder()
if isinstance(obj, Characteristic):
res = dict(
category=onto_encoder.ontology_annotation(obj.category)
if isinstance(obj.category, OntologyAnnotation) else obj.category,
value=onto_encoder.ontology_annotation(obj.value)
if isinstance(obj.value, OntologyAnnotation) else obj.value,
)
if obj.unit:
res['unit'] = onto_encoder.ontology_annotation(obj.unit) \
if isinstance(obj.unit, OntologyAnnotation) else obj.unit
return res
def default(self, obj):
return self.characteristic(obj)
class CharacteristicDecoder(object):
@staticmethod
def loads_ontology_annotation(ontology_annotation_dict):
term_source = None
if isinstance(ontology_annotation_dict.get("termSource", None), dict):
term_source = OntologySource(**ontology_annotation_dict["termSource"])
return OntologyAnnotation(
term=ontology_annotation_dict["term"], term_accession=ontology_annotation_dict["termAccession"],
term_source=term_source
)
def loads_characteristic(self, characteristic_dict):
characteristic = Characteristic(
category=self.loads_ontology_annotation(characteristic_dict["category"]) if isinstance(
characteristic_dict["category"], dict
) else characteristic_dict['category'],
value=self.loads_ontology_annotation(characteristic_dict["value"]) if isinstance(
characteristic_dict["value"], dict
) else characteristic_dict['value']
)
if 'unit' in characteristic_dict:
characteristic.unit = self.loads_ontology_annotation(characteristic_dict["unit"]) if isinstance(
characteristic_dict["unit"], dict
) else characteristic_dict["unit"] if isinstance(
characteristic_dict["unit"], str
) else None
return characteristic
def loads(self, json_text):
return self.loads_characteristic(json.loads(json_text))
class StudyCellEncoder(json.JSONEncoder):
@staticmethod
def study_factor(obj):
if isinstance(obj, StudyFactor):
onto_encoder = OntologyAnnotationEncoder()
return {
"name": onto_encoder.ontology_annotation(obj.name),
"type": onto_encoder.ontology_annotation(obj.factor_type)
}
def factor_value(self, obj):
if isinstance(obj, FactorValue):
onto_encoder = OntologyAnnotationEncoder()
res = {
"factor": self.study_factor(obj.factor_name),
"value": obj.value if isinstance(obj.value, Number) else onto_encoder.ontology_annotation(obj.value)
}
if obj.unit:
res["unit"] = onto_encoder.ontology_annotation(obj.unit)
return res
def element(self, obj):
if isinstance(obj, Treatment):
return {
"isTreatment": True,
"type": obj.type,
"factorValues": [self.factor_value(fv) for fv in obj.factor_values]
}
if isinstance(obj, NonTreatment):
return {
"isTreatment": False,
"type": obj.type,
"factorValues": [self.factor_value(fv) for fv in obj.factor_values]
}
if isinstance(obj, set):
return [self.element(el) for el in obj]
def default(self, obj):
if isinstance(obj, StudyCell):
return {
"name": obj.name,
"elements": [self.element(el) for el in obj.elements]
}
class StudyCellDecoder(object):
def __init__(self):
pass
@staticmethod
def loads_factor_value(factor_value_dict):
unit = OntologyAnnotation(term=factor_value_dict["unit"]["term"]) if "unit" in factor_value_dict else None
study_factor_type = OntologyAnnotation(term=factor_value_dict["factor"]["type"]["term"])
study_factor = StudyFactor(name=factor_value_dict["factor"]["name"], factor_type=study_factor_type)
return FactorValue(factor_name=study_factor, value=factor_value_dict["value"], unit=unit)
def loads_element(self, element_struct):
log.debug(element_struct)
if isinstance(element_struct, list):
# if element_stuct is a list it means that all the element in the list are concomitant
return {self.loads_element(el_dict) for el_dict in element_struct}
try:
if element_struct["isTreatment"] is True:
factor_values = [self.loads_factor_value(factor_value_dict)
for factor_value_dict in element_struct["factorValues"]]
return Treatment(element_type=element_struct["type"], factor_values=factor_values)
else:
duration_unit = OntologyAnnotation(**element_struct["factorValues"][0]["unit"]) \
if type(element_struct["factorValues"][0]["unit"]) == dict \
else element_struct["factorValues"][0]["unit"]
return NonTreatment(element_type=element_struct["type"],
duration_value=element_struct["factorValues"][0]["value"],
duration_unit=duration_unit)
except KeyError as ke:
# missing 'isTreatment' property
if len(element_struct["factorValues"]) == 1:
pass # non-treatment
elif len(element_struct["factorValues"]) == 3:
pass # treatment
else:
pass # raise error
log.debug('Element has no \'isTreatment\' property: {}'.format(element_struct))
raise ke
def loads_cells(self, json_dict):
cell = StudyCell(name=json_dict["name"])
for element in json_dict["elements"]:
try:
cell.insert_element(self.loads_element(element))
except ValueError as e:
log.error('Element triggers error: {0}'.format(element))
raise e
return cell
def loads(self, json_text):
json_dict = json.loads(json_text)
return self.loads_cells(json_dict)
class SequenceNode(ABC):
pass
class ProtocolNode(SequenceNode, Protocol):
"""
These class is a subclass of isatools.model.Protocol
It represents a node in the AssayGraph which is a to create a Protocol
"""
def __init__(self, id_=str(uuid.uuid4()), name='', protocol_type=None, uri='',
description='', version='', parameter_values=None, replicates=None):
"""
:param id_:
:param name: the name of the protocol
:param protocol_type: the type of the protocol
:param uri: a uri pointing to a resource describing the protocol
:param description: a textual description of the protocol
:param version:
:param parameter_values: the values to be supplied to the Protocol Parameters
:param replicates: int - the number of replicates (biological or technical) for this Protocol step. Must be a
positive integer (>= 1)
"""
Protocol.__init__(self, id_=id_, name=name, protocol_type=protocol_type,
uri=uri, description=description, version=version)
SequenceNode.__init__(self)
self.__parameter_values = []
self.__replicates = 1
if parameter_values is not None:
self.parameter_values = parameter_values
if replicates:
self.replicates = replicates
@property
def parameter_values(self):
return self.__parameter_values
@parameter_values.setter
def parameter_values(self, parameter_values):
if not isinstance(parameter_values, Iterable) or \
not all(isinstance(parameter_value, ParameterValue) for parameter_value in parameter_values):
raise AttributeError(errors.PARAMETER_VALUES_ERROR.format(parameter_values))
self.__parameter_values = list(parameter_values)
def add_parameter_value(self, protocol_parameter, value, unit=None):
if isinstance(protocol_parameter, str):
protocol_parameter = ProtocolParameter(parameter_name=protocol_parameter)
parameter_value = ParameterValue(category=protocol_parameter, value=value, unit=unit)
self.__parameter_values.append(parameter_value)
@property
def replicates(self):
return self.__replicates or 1
@replicates.setter
def replicates(self, replicates):
if not isinstance(replicates, int) or replicates < 1:
raise AttributeError(errors.REPLICATES_ERROR.format(replicates))
self.__replicates = replicates
@property
def parameters(self):
return [parameter_value.category for parameter_value in self.parameter_values]
@parameters.setter
def parameters(self, parameters):
raise AttributeError(errors.PARAMETERS_CANNOT_BE_SET_ERROR)
@property
def components(self):
return [] # FIXME check if empty list works None triggers an error
@components.setter
def components(self, components):
raise AttributeError(errors.COMPONENTS_CANNOT_BE_SET_ERROR)
def __repr__(self):
return '{0}.{1}(id={2.id}, name={2.name}, protocol_type={2.protocol_type}, ' \
'uri={2.uri}, description={2.description}, version={2.version}, ' \
'parameter_values={2.parameter_values})'.format(self.__class__.__module__,
self.__class__.__name__, self)
def __str__(self):
return """{0}(
id={1.id},
name={1.name},
protocol_type={1.protocol_type},
uri={1.uri},
description={1.description},
version={1.version},
parameter_values={1.parameter_values})
""".format(self.__class__.__name__, self)
def __hash__(self):
return hash(repr(self))
def __eq__(self, other):
return isinstance(other, ProtocolNode) and self.id == other.id and self.name == other.name \
and self.protocol_type == other.protocol_type and self.uri == other.uri \
and self.description == other.description and self.version == other.version \
and self.parameter_values == other.parameter_values
def __ne__(self, other):
return not self == other
class ProductNode(SequenceNode):
"""
A ProductNode caputres information about the inputs or outputs of a process.
It can contain info about a source, a sample (or its derivatives), or a data file
"""
ALLOWED_TYPES = {SOURCE, SAMPLE, EXTRACT, LABELED_EXTRACT, DATA_FILE}
def __init__(self, id_=str(uuid.uuid4()), node_type=SOURCE, name='', characteristics=[], size=0):
super().__init__()
self.__id = id_
self.__type = None
self.__name = None
self.__characteristics = []
self.__size = None
self.type = node_type
self.name = name
self.characteristics = characteristics
self.size = size
def __repr__(self):
return '{0}.{1}(id={2.id}, type={2.type}, name={2.name}, ' \
'characteristics={2.characteristics}, size={2.size})'.format(
self.__class__.__module__, self.__class__.__name__, self)
def __str__(self):
return """{0}(
id={1.id},
type={1.type},
name={1.name},
characteristics={1.characteristics},
size={1.size}
)""".format(self.__class__.__name__, self)
def __hash__(self):
return hash(repr(self))
def __eq__(self, other):
return isinstance(other, ProductNode) and self.id == other.id and self.type == other.type \
and self.name == other.name and self.characteristics == other.characteristics \
and self.size == other.size
def __ne__(self, other):
return not self == other
@property
def id(self):
return self.__id
@property
def type(self):
return self.__type
@type.setter
def type(self, node_type):
if node_type not in self.ALLOWED_TYPES:
raise AttributeError(errors.NOT_ALLOWED_TYPE_ERROR.format(self.ALLOWED_TYPES))
self.__type = node_type
@property
def name(self):
return self.__name
@name.setter
def name(self, name):
if not isinstance(name, str):
raise AttributeError(errors.PRODUCT_NODE_NAME_ERROR.format(name, type(name)))
self.__name = name
@property
def characteristics(self):
return self.__characteristics
@characteristics.setter
def characteristics(self, characteristics):
self.__characteristics = []
try:
for characteristic in characteristics:
self.add_characteristic(characteristic)
except TypeError as e:
raise AttributeError(e)
def add_characteristic(self, characteristic):
if not isinstance(characteristic, (str, Characteristic)):
raise TypeError(errors.CHARACTERISTIC_TYPE_ERROR.format(type(characteristic)))
if isinstance(characteristic, Characteristic):
self.__characteristics.append(characteristic)
if isinstance(characteristic, str):
self.__characteristics.append(Characteristic(value=characteristic))
@property
def size(self):
return self.__size
@size.setter
def size(self, size):
if not isinstance(size, int) or size < 0:
raise AttributeError(errors.SIZE_ERROR)
self.__size = size
class QualityControlSource(Source):
pass
class QualityControlSample(Sample):
ALLOWED_QC_SAMPLE_TYPES = [QC_SAMPLE_TYPE_PRE_RUN, QC_SAMPLE_TYPE_INTERSPERSED, QC_SAMPLE_TYPE_POST_RUN]
def __init__(self, **kwargs):
log.debug('KWARGS are: {0}'.format(kwargs))
qc_sample_type = kwargs.get('qc_sample_type', None)
_kwargs = {key: val for key, val in kwargs.items() if key != 'qc_sample_type'}
super(QualityControlSample, self).__init__(**_kwargs)
self.__qc_sample_type = None
if qc_sample_type:
self.qc_sample_type = qc_sample_type
@property
def qc_sample_type(self):
return self.__qc_sample_type
@qc_sample_type.setter
def qc_sample_type(self, qc_sample_type):
if qc_sample_type not in self.ALLOWED_QC_SAMPLE_TYPES:
raise AttributeError(errors.QC_SAMPLE_TYPE_ERROR.format(self.ALLOWED_QC_SAMPLE_TYPES))
self.__qc_sample_type = qc_sample_type
class QualityControl(object):
"""
This class captures information about a Quality Control Check. It comes attached to an Assay Graph object
"""
def __init__(self, pre_run_sample_type=None, post_run_sample_type=None, interspersed_sample_type=None):
self.__pre_run_sample_type = None
self.__post_run_sample_type = None
self.__interspersed_sample_types = []
if pre_run_sample_type:
self.pre_run_sample_type = pre_run_sample_type
if post_run_sample_type:
self.post_run_sample_type = post_run_sample_type
if interspersed_sample_type:
self.interspersed_sample_types = interspersed_sample_type
def __repr__(self):
return '{0}.{1}(pre_run_sample_type={2.pre_run_sample_type}, post_run_sample_type={2.post_run_sample_type}, ' \
'interspersed_sample_types={2.interspersed_sample_types})'.format(
self.__class__.__module__, self.__class__.__name__, self
)
def __str__(self):
return """{0}(
pre_run_sample_type={1}
post_run_sample_type={2}
interspersed_sample_types={3}
)""".format(
self.__class__.__name__,
self.pre_run_sample_type.id if self.pre_run_sample_type else None,
self.post_run_sample_type.id if self.post_run_sample_type else None,
[(elem.id, n) for elem, n in self.interspersed_sample_types]
)
def __hash__(self):
return hash(repr(self))
def __eq__(self, other):
return isinstance(other, QualityControl) and \
self.pre_run_sample_type == other.pre_run_sample_type and \
self.post_run_sample_type == other.post_run_sample_type and \
self.interspersed_sample_types == other.interspersed_sample_types
def __ne__(self, other):
return not self == other
@property
def pre_run_sample_type(self):
return self.__pre_run_sample_type
@pre_run_sample_type.setter
def pre_run_sample_type(self, pre_run_sample_type):
if not isinstance(pre_run_sample_type, ProductNode):
raise AttributeError(errors.PRE_BATCH_ATTRIBUTE_ERROR)
self.__pre_run_sample_type = pre_run_sample_type
@property
def post_run_sample_type(self):
return self.__post_run_sample_type
@post_run_sample_type.setter
def post_run_sample_type(self, post_run_sample_type):
if not isinstance(post_run_sample_type, ProductNode):
raise AttributeError(errors.POST_BATCH_ATTRIBUTE_ERROR)
self.__post_run_sample_type = post_run_sample_type
@property
def interspersed_sample_types(self):
return self.__interspersed_sample_types
@interspersed_sample_types.setter
def interspersed_sample_types(self, interspersed_sample_types):
try:
for sample_type, interspersing_interval in interspersed_sample_types:
self.add_interspersed_sample_type(sample_type, interspersing_interval)
except (TypeError, ValueError) as e:
raise AttributeError(e)
def add_interspersed_sample_type(self, sample_type, interspersing_interval=10):
if not isinstance(sample_type, ProductNode):
raise TypeError(errors.INTERSPERSED_SAMPLE_TYPE_NODE_ERROR)
if not isinstance(interspersing_interval, int):
raise TypeError(errors.INTERSPERSED_SAMPLE_TYPE_INTERVAL_TYPE_ERROR)
if interspersing_interval < 1:
raise ValueError(errors.INTERSPERSED_SAMPLE_TYPE_INTERVAL_VALUE_ERROR)
self.__interspersed_sample_types.append((sample_type, interspersing_interval))
class AssayGraph(object):
"""
The AssayGraph captures the structure and information of an assay workflow
(e.g sample derivatives extraction, labelling, and the instrument analysis itself)
This information is stored in a graph (a directed tree, more correctly) of ProductNodes and
ProcessNodes. Each ProcessNode has ProductNodes as outputs and potentially as inputs.
"""
def __init__(self, measurement_type, technology_type, id_=str(uuid.uuid4()), nodes=None, links=None,
quality_control=None):
"""
initializes an AssayGraph object
If no dictionary or None is given,
an empty dictionary will be used
"""
self.__id = id_
self.__measurement_type = None
self.__technology_type = None
self.__graph_dict = {}
self.__quality_control = None