/
core.py
1769 lines (1379 loc) · 61.1 KB
/
core.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
""" Schema to represent a knowledge base to build models
:Author: Balazs Szigeti <balazs.szigeti@mssm.edu>
:Author: Jonathan Karr <jonrkarr@gmail.com>
:Author: Bilal Shaikh <bilal.shaikh@columbia.edu>
:Date: 2018-02-07
:Copyright: 2018, Karr Lab
:License: MIT
TODO:
ProteinSpeciesType.get_seq() => cds=True (complete coding sequence) causes errors, talk to J
"""
from natsort import natsorted, ns
from wc_utils.util import chem
import abc
import Bio.SeqUtils
import enum
import math
import obj_model.abstract
import obj_model
import obj_model.extra_attributes
import openbabel
import pkg_resources
import re
import six
from obj_model import (BooleanAttribute, EnumAttribute, FloatAttribute, IntegerAttribute, PositiveIntegerAttribute,
RegexAttribute, SlugAttribute, StringAttribute, LongStringAttribute, UrlAttribute,
OneToOneAttribute, ManyToOneAttribute, ManyToManyAttribute,
InvalidModel, InvalidObject, InvalidAttribute, TabularOrientation)
from wc_utils.util.types import get_subclasses
with open(pkg_resources.resource_filename('wc_kb', 'VERSION'), 'r') as file:
wc_kb_version = file.read().strip()
#####################
#####################
# Enumeration classes
PolymerStrand = enum.Enum(value='PolymerStrand', names=[
('positive', 1),
('+', 1),
('negative', -1),
('-', -1), ])
class RnaType(enum.Enum):
""" Type of RNA """
mRna = 0
rRna = 1
sRna = 2
tRna = 3
mixed = 4
class GeneType(enum.Enum):
""" Type of gene """
mRna = 0
rRna = 1
sRna = 2
tRna = 3
class ComplexType(enum.Enum):
""" Type of gene """
tRnaSynthClassII = 0
FattyAcylAcp = 1
class ComplexFormationType(enum.Enum):
""" Type of gene """
process_ChromosomeCondensation = 0
process_FtsZPolymerization = 1
process_MacromolecularComplexation = 2
process_Metabolism = 3
process_ProteinModification = 4
process_Replication = 5
process_ReplicationInitiation = 6
process_RibosomeAssembly = 7
process_Transcription = 8
process_Translation = 9
#####################
#####################
# Attributes
class SubunitAttribute(ManyToManyAttribute):
""" Subunits """
def __init__(self, related_name='', verbose_name='', verbose_related_name='', help=''):
"""
Args:
related_name (:obj:`str`, optional): name of related attribute on `related_class`
verbose_name (:obj:`str`, optional): verbose name
verbose_related_name (:obj:`str`, optional): verbose related name
help (:obj:`str`, optional): help message
"""
super(SubunitAttribute, self).__init__('SpeciesCoefficient',
related_name=related_name,
verbose_name=verbose_name,
verbose_related_name=verbose_related_name,
help=help)
def serialize(self, participants, encoded=None):
""" Serialize related object
Args:
participants (:obj:`list` of `SpeciesCoefficient`): Python representation of reaction participants
encoded (:obj:`dict`, optional): dictionary of objects that have already been encoded
Returns:
:obj:`str`: simple Python representation
"""
if not participants:
return ''
comps = set([part.species.compartment for part in participants])
if len(comps) == 1:
global_comp = comps.pop()
else:
global_comp = None
if global_comp:
participants = natsorted(
participants, lambda part: part.species.species_type.id, alg=ns.IGNORECASE)
else:
participants = natsorted(participants, lambda part: (
part.species.species_type.id, part.species.compartment.id), alg=ns.IGNORECASE)
lhs = []
for part in participants:
lhs.append(part.serialize(
show_compartment=global_comp is None, show_coefficient_sign=False))
if global_comp:
return '[{}]: {}'.format(global_comp.get_primary_attribute(), ' + '.join(lhs))
else:
return '{}'.format(' + '.join(lhs))
def deserialize(self, value, objects, decoded=None):
parts = []
errors = []
id = '[a-z][a-z0-9_]*'
stoch = '\(((\d*\.?\d+|\d+\.)(e[\-\+]?\d+)?)\)'
gbl_part = '({} )*({})'.format(stoch, id)
lcl_part = '({} )*({}\[{}\])'.format(stoch, id, id)
gbl_side = '{}( \+ {})*'.format(gbl_part, gbl_part)
lcl_side = '{}( \+ {})*'.format(lcl_part, lcl_part)
gbl_pattern = '^\[({})\]: ({})$'.format(id, gbl_side)
lcl_pattern = '^({})$'.format(lcl_side)
global_match = re.match(gbl_pattern, value, flags=re.I)
local_match = re.match(lcl_pattern, value, flags=re.I)
if global_match:
if global_match.group(1) in objects[Compartment]:
global_comp = objects[Compartment][global_match.group(1)]
else:
global_comp = None
errors.append('Undefined compartment "{}"'.format(
global_match.group(1)))
subunits_str = global_match.group(2)
elif local_match:
global_comp = None
subunits_str = local_match.group(1)
else:
return (None, InvalidAttribute(self, ['Incorrectly formatted participants: {}'.format(value)]))
for part in re.findall('(\(((\d*\.?\d+|\d+\.)(e[\-\+]?\d+)?)\) )*([a-z][a-z0-9_]*)(\[([a-z][a-z0-9_]*)\])*',
subunits_str, flags=re.I):
species_type = None
for species_type_cls in get_subclasses(SpeciesType):
if species_type_cls in objects and part[4] in objects[species_type_cls]:
species_type = objects[species_type_cls][part[4]]
break
if not species_type:
errors.append('Undefined species type "{}"'.format(part[4]))
if global_comp:
compartment = global_comp
elif part[6] in objects[Compartment]:
compartment = objects[Compartment][part[6]]
else:
errors.append('Undefined compartment "{}"'.format(part[6]))
coefficient = float(part[1] or 1.)
if not errors:
spec_primary_attribute = Species.gen_id(
species_type.get_primary_attribute(), compartment.get_primary_attribute())
species, error = Species.deserialize(
self, spec_primary_attribute, objects)
if error:
raise ValueError('Invalid species "{}"'.format(
spec_primary_attribute))
# pragma: no cover # unreachable due to error checking above
if coefficient != 0:
if SpeciesCoefficient not in objects:
objects[SpeciesCoefficient] = {}
serialized_value = SpeciesCoefficient._serialize(
species, coefficient)
if serialized_value in objects[SpeciesCoefficient]:
rxn_part = objects[SpeciesCoefficient][serialized_value]
else:
rxn_part = SpeciesCoefficient(
species=species, coefficient=coefficient)
objects[SpeciesCoefficient][serialized_value] = rxn_part
parts.append(rxn_part)
if errors:
return (None, InvalidAttribute(self, errors))
return (parts, None)
class ReactionParticipantAttribute(ManyToManyAttribute):
""" Reaction participants """
def __init__(self, related_name='', verbose_name='', verbose_related_name='', help=''):
"""
Args:
related_name (:obj:`str`, optional): name of related attribute on `related_class`
verbose_name (:obj:`str`, optional): verbose name
verbose_related_name (:obj:`str`, optional): verbose related name
help (:obj:`str`, optional): help message
"""
super(ReactionParticipantAttribute, self).__init__('SpeciesCoefficient', related_name=related_name,
verbose_name=verbose_name,
verbose_related_name=verbose_related_name,
help=help)
def serialize(self, participants, encoded=None):
""" Serialize related object
Args:
participants (:obj:`list` of `SpeciesCoefficient`): Python representation of reaction participants
encoded (:obj:`dict`, optional): dictionary of objects that have already been encoded
Returns:
:obj:`str`: simple Python representation
"""
if not participants:
return ''
comps = set([part.species.compartment for part in participants])
if len(comps) == 1:
global_comp = comps.pop()
else:
global_comp = None
if global_comp:
participants = natsorted(
participants, lambda part: part.species.species_type.id, alg=ns.IGNORECASE)
else:
participants = natsorted(participants, lambda part: (
part.species.species_type.id, part.species.compartment.id), alg=ns.IGNORECASE)
lhs = []
rhs = []
for part in participants:
if part.coefficient < 0:
lhs.append(part.serialize(
show_compartment=global_comp is None, show_coefficient_sign=False))
elif part.coefficient > 0:
rhs.append(part.serialize(
show_compartment=global_comp is None, show_coefficient_sign=False))
if global_comp:
return '[{}]: {} ==> {}'.format(global_comp.get_primary_attribute(), ' + '.join(lhs), ' + '.join(rhs))
else:
return '{} ==> {}'.format(' + '.join(lhs), ' + '.join(rhs))
def deserialize(self, value, objects, decoded=None):
""" Deserialize value
Args:
value (:obj:`str`): String representation
objects (:obj:`dict`): dictionary of objects, grouped by model
decoded (:obj:`dict`, optional): dictionary of objects that have already been decoded
Returns:
:obj:`tuple` of `list` of `SpeciesCoefficient`, `InvalidAttribute` or `None`: tuple of cleaned value
and cleaning error
"""
errors = []
id = '[a-z][a-z0-9_]*'
stoch = '\(((\d*\.?\d+|\d+\.)(e[\-\+]?\d+)?)\)'
gbl_part = '({} )*({})'.format(stoch, id)
lcl_part = '({} )*({}\[{}\])'.format(stoch, id, id)
gbl_side = '{}( \+ {})*'.format(gbl_part, gbl_part)
lcl_side = '{}( \+ {})*'.format(lcl_part, lcl_part)
gbl_pattern = '^\[({})\]: ({}) ==> ({})$'.format(
id, gbl_side, gbl_side)
lcl_pattern = '^({}) ==> ({})$'.format(lcl_side, lcl_side)
global_match = re.match(gbl_pattern, value, flags=re.I)
local_match = re.match(lcl_pattern, value, flags=re.I)
if global_match:
if global_match.group(1) in objects[Compartment]:
global_comp = objects[Compartment][global_match.group(1)]
else:
global_comp = None
errors.append('Undefined compartment "{}"'.format(
global_match.group(1)))
lhs = global_match.group(2)
rhs = global_match.group(14)
elif local_match:
global_comp = None
lhs = local_match.group(1)
rhs = local_match.group(13)
else:
return (None, InvalidAttribute(self, ['Incorrectly formatted participants: {}'.format(value)]))
lhs_parts, lhs_errors = self.deserialize_side(
-1., lhs, objects, global_comp)
rhs_parts, rhs_errors = self.deserialize_side(
1., rhs, objects, global_comp)
parts = lhs_parts + rhs_parts
errors.extend(lhs_errors)
errors.extend(rhs_errors)
if errors:
return (None, InvalidAttribute(self, errors))
return (parts, None)
def deserialize_side(self, direction, value, objects, global_comp):
""" Deserialize the LHS or RHS of a reaction equation
Args:
direction (:obj:`float`): -1. indicates LHS, +1. indicates RHS
value (:obj:`str`): String representation
objects (:obj:`dict`): dictionary of objects, grouped by model
global_comp (:obj:`Compartment`): global compartment of the reaction
Returns:
:obj:`tuple`:
* :obj:`list` of :obj:`SpeciesCoefficient`: list of species coefficients
* :obj:`list` of :obj:`Exception`: list of errors
"""
parts = []
errors = []
for part in re.findall('(\(((\d*\.?\d+|\d+\.)(e[\-\+]?\d+)?)\) )*([a-z][a-z0-9_]*)(\[([a-z][a-z0-9_]*)\])*', value, flags=re.I):
part_errors = []
species_type = None
for species_type_cls in get_subclasses(SpeciesType):
if species_type_cls in objects and part[4] in objects[species_type_cls]:
species_type = objects[species_type_cls][part[4]]
break
if not species_type:
part_errors.append(
'Undefined species type "{}"'.format(part[4]))
if global_comp:
compartment = global_comp
elif part[6] in objects[Compartment]:
compartment = objects[Compartment][part[6]]
else:
part_errors.append(
'Undefined compartment "{}"'.format(part[6]))
coefficient = direction * float(part[1] or 1.)
if part_errors:
errors += part_errors
else:
spec_primary_attribute = Species.gen_id(species_type.get_primary_attribute(),
compartment.get_primary_attribute())
species, error = Species.deserialize(
self, spec_primary_attribute, objects)
if error:
raise ValueError('Invalid species "{}"'.format(
spec_primary_attribute))
# pragma: no cover # unreachable due to error checking above
if coefficient != 0:
if SpeciesCoefficient not in objects:
objects[SpeciesCoefficient] = {}
serialized_value = SpeciesCoefficient._serialize(
species, coefficient)
if serialized_value in objects[SpeciesCoefficient]:
rxn_part = objects[SpeciesCoefficient][serialized_value]
else:
rxn_part = SpeciesCoefficient(
species=species, coefficient=coefficient)
objects[SpeciesCoefficient][serialized_value] = rxn_part
parts.append(rxn_part)
return (parts, errors)
class ObservableSpeciesParticipantAttribute(ManyToManyAttribute):
""" Inline separated list of species and their weights of an observable
Attributes:
separator (:obj:`str`): list separator
"""
def __init__(self, related_class, separator=' + ', related_name='', verbose_name='', verbose_related_name='', help=''):
"""
Args:
related_class (:obj:`class`): related class
separator (:obj:`str`, optional): list separator
related_name (:obj:`str`, optional): name of related attribute on `related_class`
verbose_name (:obj:`str`, optional): verbose name
verbose_related_name (:obj:`str`, optional): verbose related name
help (:obj:`str`, optional): help message
"""
super(ObservableSpeciesParticipantAttribute, self).__init__(related_class, related_name=related_name,
verbose_name=verbose_name,
verbose_related_name=verbose_related_name,
help=help)
self.separator = separator
def serialize(self, spec_coeffs, encoded=None):
""" Serialize related object
Args:
spec_coeffs (:obj:`list` of `Model`): Python representation of species and their coefficients
encoded (:obj:`dict`, optional): dictionary of objects that have already been encoded
Returns:
:obj:`str`: simple Python representation
"""
if not spec_coeffs:
return ''
spec_coeff_strs = []
for spec_coeff_obj in spec_coeffs:
spec_coeff_str = spec_coeff_obj.serialize(
show_compartment=True, show_coefficient_sign=True)
spec_coeff_strs.append(spec_coeff_str)
return self.separator.join(spec_coeff_strs)
def deserialize(self, value, objects, decoded=None):
""" Deserialize value
Args:
value (:obj:`str`): String representation
objects (:obj:`dict`): dictionary of objects, grouped by model
decoded (:obj:`dict`, optional): dictionary of objects that have already been decoded
Returns:
:obj:`tuple` of `list` of `related_class`, `InvalidAttribute` or `None`: tuple of cleaned value
and cleaning error
"""
if not value:
return ([], None)
pat_id = '([a-z][a-z0-9_]*)'
pat_coeff = '\(((\d*\.?\d+|\d+\.)(e[\-\+]?\d+)?)\)'
pat_spec_coeff = '({} )*({}\[{}\])'.format(pat_coeff, pat_id, pat_id)
pat_observable = '^{}( \+ {})*$'.format(pat_spec_coeff, pat_spec_coeff)
if not re.match(pat_observable, value, flags=re.I):
return (None, InvalidAttribute(self, ['Incorrectly formatted observable: {}'.format(value)]))
spec_coeff_objs = []
errors = []
for spec_coeff_match in re.findall(pat_spec_coeff, value, flags=re.I):
spec_type_errors = []
spec_type_id = spec_coeff_match[5]
try:
if spec_type_id in objects[ProteinSpeciesType]:
spec_type = objects[ProteinSpeciesType][spec_type_id]
elif spec_type_id in objects[RnaSpeciesType]:
spec_type = objects[RnaSpeciesType][spec_type_id]
elif spec_type_id in objects[ComplexSpeciesType]:
spec_type = objects[ComplexSpeciesType][spec_type_id]
elif spec_type_id in objects[DnaSpeciesType]:
spec_type = objects[DnaSpeciesType][spec_type_id]
elif spec_type_id in objects[MetaboliteSpeciesType]:
spec_type = objects[MetaboliteSpeciesType][spec_type_id]
else:
spec_type_errors.append(
'Undefined species type "{}"'.format(spec_type_id))
except KeyError:
pass
compartment_id = spec_coeff_match[6]
if compartment_id in objects[Compartment]:
compartment = objects[Compartment][compartment_id]
else:
spec_type_errors.append(
'Undefined compartment "{}"'.format(compartment_id))
coefficient = float(spec_coeff_match[1] or 1.)
if spec_type_errors:
errors += spec_type_errors
elif coefficient != 0:
spec_id = Species.gen_id(
spec_type.get_primary_attribute(), compartment.get_primary_attribute())
obj, error = Species.deserialize(self, spec_id, objects)
if error:
raise ValueError('Invalid object "{}"'.format(spec_primary_attribute)
) # pragma: no cover # unreachable due to error checking above
if self.related_class not in objects:
objects[self.related_class] = {}
serialized_value = self.related_class._serialize(
obj, coefficient)
if serialized_value in objects[self.related_class]:
spec_coeff_obj = objects[self.related_class][serialized_value]
else:
spec_coeff_obj = self.related_class(
species=obj, coefficient=coefficient)
objects[self.related_class][serialized_value] = spec_coeff_obj
spec_coeff_objs.append(spec_coeff_obj)
if errors:
return (None, InvalidAttribute(self, errors))
return (spec_coeff_objs, None)
class ObservableObservableParticipantAttribute(ManyToManyAttribute):
""" Inline separated list of observables and their weights of an observable
Attributes:
separator (:obj:`str`): list separator
"""
def __init__(self, related_class, separator=' + ', related_name='', verbose_name='', verbose_related_name='', help=''):
"""
Args:
related_class (:obj:`class`): related class
separator (:obj:`str`, optional): list separator
related_name (:obj:`str`, optional): name of related attribute on `related_class`
verbose_name (:obj:`str`, optional): verbose name
verbose_related_name (:obj:`str`, optional): verbose related name
help (:obj:`str`, optional): help message
"""
super(ObservableObservableParticipantAttribute, self).__init__(related_class, related_name=related_name,
verbose_name=verbose_name,
verbose_related_name=verbose_related_name,
help=help)
self.separator = separator
def serialize(self, obs_coeffs, encoded=None):
""" Serialize related object
Args:
obs_coeffs (:obj:`list` of `Model`): Python representation of observables and their coefficients
encoded (:obj:`dict`, optional): dictionary of objects that have already been encoded
Returns:
:obj:`str`: simple Python representation
"""
if not obs_coeffs:
return ''
obs_coeff_strs = []
for obs_coeff_obj in obs_coeffs:
obs_coeff_str = obs_coeff_obj.serialize()
obs_coeff_strs.append(obs_coeff_str)
return self.separator.join(obs_coeff_strs)
def deserialize(self, value, objects, decoded=None):
""" Deserialize value
Args:
value (:obj:`str`): String representation
objects (:obj:`dict`): dictionary of objects, grouped by model
decoded (:obj:`dict`, optional): dictionary of objects that have already been decoded
Returns:
:obj:`tuple` of `list` of `related_class`, `InvalidAttribute` or `None`: tuple of cleaned value
and cleaning error
"""
if not value:
return ([], None)
pat_id = '([a-z][a-z0-9_]*)'
pat_coeff = '\(((\d*\.?\d+|\d+\.)(e[\-\+]?\d+)?)\)'
pat_obs_coeff = '({} )*({})'.format(pat_coeff, pat_id, pat_id)
pat_observable = '^{}( \+ {})*$'.format(pat_obs_coeff, pat_obs_coeff)
if not re.match(pat_observable, value, flags=re.I):
return (None, InvalidAttribute(self, ['Incorrectly formatted observable: {}'.format(value)]))
obs_coeff_objs = []
errors = []
for obs_coeff_match in re.findall(pat_obs_coeff, value, flags=re.I):
obs_errors = []
obs_id = obs_coeff_match[5]
if obs_id in objects[Observable]:
obs = objects[Observable][obs_id]
else:
obs_errors.append('Undefined observable "{}"'.format(obs_id))
coefficient = float(obs_coeff_match[1] or 1.)
if obs_errors:
errors += obs_errors
elif coefficient != 0:
if self.related_class not in objects:
objects[self.related_class] = {}
serialized_value = self.related_class._serialize(
obs, coefficient)
if serialized_value in objects[self.related_class]:
obs_coeff_obj = objects[self.related_class][serialized_value]
else:
obs_coeff_obj = self.related_class(
observable=obs, coefficient=coefficient)
objects[self.related_class][serialized_value] = obs_coeff_obj
obs_coeff_objs.append(obs_coeff_obj)
if errors:
return (None, InvalidAttribute(self, errors))
return (obs_coeff_objs, None)
#####################
#####################
# Base classes
class KnowledgeBaseObject(obj_model.Model):
""" Knowlege of a biological entity
Attributes:
id (:obj:`str`): identifier
name (:obj:`str`): name
comments (:obj:`str`): comments
"""
id = obj_model.StringAttribute(primary=True, unique=True)
name = obj_model.StringAttribute()
comments = obj_model.StringAttribute()
class KnowledgeBase(KnowledgeBaseObject):
""" A knowledge base
Attributes:
version (:obj:`str`): version
translation_table (:obj:`int`): translation table
version (:obj:`str`): version of the KB
url (:obj:`str`): url of the KB Git repository
branch (:obj:`str`): branch of the KB Git repository
revision (:obj:`str`): revision of the KB Git repository
wc_kb_version (:obj:`str`): version of ``wc_kb``
Related attributes:
cell (:obj:`Cell`): cell
"""
translation_table = obj_model.IntegerAttribute()
version = RegexAttribute(
min_length=1, pattern='^[0-9]+\.[0-9+]\.[0-9]+', flags=re.I)
url = obj_model.StringAttribute(verbose_name='URL')
branch = obj_model.StringAttribute()
revision = obj_model.StringAttribute()
wc_kb_version = RegexAttribute(min_length=1, pattern='^[0-9]+\.[0-9+]\.[0-9]+', flags=re.I,
default=wc_kb_version, verbose_name='wc_kb version')
class Meta(obj_model.Model.Meta):
attribute_order = ('id', 'name', 'translation_table', 'version',
'url', 'branch', 'revision', 'wc_kb_version', 'comments')
tabular_orientation = obj_model.TabularOrientation.column
class Cell(KnowledgeBaseObject):
""" Knowledge of a cell
Attributes:
knowledge_base (:obj:`KnowledgeBase`): knowledge base
Related attributes:
compartments (:obj:`list` of :obj:`Compartment`): compartments
species_types (:obj:`list` of :obj:`SpeciesType`): species types
observables (:obj:'list' or :obj: 'Observable') : observables
loci (:obj:`list` of :obj:`PolymerLocus`): locus
reactions (:obj:`list` of :obj:`Reaction`): reactions
"""
knowledge_base = obj_model.OneToOneAttribute(
KnowledgeBase, related_name='cell')
class Meta(obj_model.Model.Meta):
attribute_order = ('id', 'name', 'comments')
tabular_orientation = obj_model.TabularOrientation.column
class Compartment(KnowledgeBaseObject):
""" Knowledge of a subcellular compartment
Attributes:
cell (:obj:`Cell`): cell
volume (:obj:`float`): average volume at the begining of the cell cycle (L)
Related attributes:
reaction_participants (:obj:`list` of :obj:`ReactionParticipant`): reaction participants
"""
cell = obj_model.ManyToOneAttribute(Cell, related_name='compartments')
volume = obj_model.FloatAttribute(min=0)
class Meta(obj_model.Model.Meta):
attribute_order = ('id', 'name', 'volume', 'comments')
class SpeciesType(six.with_metaclass(obj_model.abstract.AbstractModelMeta, KnowledgeBaseObject)):
""" Knowledge of a molecular species
Attributes:
cell (:obj:`Cell`): cell
concentration (:obj:`float`): concentration (M)
half_life (:obj:`float`): half life (s)
Related attributes:
reaction_participants (:obj:`list` of :obj:`ReactionParticipant`): reaction participants
"""
cell = obj_model.ManyToOneAttribute(Cell, related_name='species_types')
concentration = obj_model.FloatAttribute(min=0)
half_life = obj_model.FloatAttribute(min=0)
class Meta(obj_model.Model.Meta):
attribute_order = ('id', 'name', 'concentration',
'half_life', 'comments')
@abc.abstractmethod
def get_empirical_formula(self):
""" Get the empirical formula
Returns:
:obj:`chem.EmpiricalFormula`: empirical formula
"""
pass # pragma: no cover
@abc.abstractmethod
def get_charge(self):
""" Get the charge
Returns:
:obj:`int`: charge
"""
pass # pragma: no cover
@abc.abstractmethod
def get_mol_wt(self):
""" Get the molecular weight
Returns:
:obj:`float`: molecular weight
"""
pass # pragma: no cover
class Species(obj_model.Model):
""" Species (tuple of species type, compartment)
Attributes:
species_type (:obj:`SpeciesType`): species type
compartment (:obj:`Compartment`): compartment
Related attributes:
species_coefficients (:obj:`list` of `SpeciesCoefficient`): participations in reactions and observables
"""
species_type = ManyToOneAttribute(
SpeciesType, related_name='species', min_related=1)
compartment = ManyToOneAttribute(
Compartment, related_name='species', min_related=1)
class Meta(obj_model.Model.Meta):
attribute_order = ('species_type', 'compartment')
frozen_columns = 1
tabular_orientation = TabularOrientation.inline
unique_together = (('species_type', 'compartment', ), )
ordering = ('species_type', 'compartment')
@staticmethod
def gen_id(species_type, compartment):
""" Generate a Species' primary identifier
Args:
species_type (:obj:`object`): a `SpeciesType`, or its id
compartment (:obj:`object`): a `Compartment`, or its id
Returns:
:obj:`str`: canonical identifier for a specie in a compartment, 'species_type_id[compartment_id]'
"""
if isinstance(species_type, SpeciesType):
species_type_id = species_type.get_primary_attribute()
elif isinstance(species_type, six.string_types):
species_type_id = species_type
else:
raise ValueError(
"gen_id: incorrect species type: {}".format(species_type))
if isinstance(compartment, Compartment):
compartment_id = compartment.get_primary_attribute()
elif isinstance(compartment, six.string_types):
compartment_id = compartment
else:
raise ValueError(
"gen_id: incorrect compartment type: {}".format(compartment))
return '{}[{}]'.format(species_type_id, compartment_id)
def id(self):
""" Provide a Species' primary identifier
Returns:
:obj:`str`: canonical identifier for a specie in a compartment, 'specie_id[compartment_id]'
"""
return self.serialize()
def serialize(self):
""" Provide a Species' primary identifier
Returns:
:obj:`str`: canonical identifier for a specie in a compartment, 'specie_id[compartment_id]'
"""
return self.gen_id(self.species_type, self.compartment)
@classmethod
def deserialize(cls, attribute, value, objects):
""" Deserialize value
Args:
attribute (:obj:`Attribute`): attribute
value (:obj:`str`): String representation
objects (:obj:`dict`): dictionary of objects, grouped by model
Returns:
:obj:`tuple` of `object`, `InvalidAttribute` or `None`: tuple of cleaned value and cleaning error
"""
if cls in objects and value in objects[cls]:
return (objects[cls][value], None)
match = re.match(
'^([a-z][a-z0-9_]*)\[([a-z][a-z0-9_]*)\]$', value, flags=re.I)
if match:
errors = []
species_type = None
for species_type_cls in get_subclasses(SpeciesType):
if species_type_cls in objects and match.group(1) in objects[species_type_cls]:
species_type = objects[species_type_cls][match.group(1)]
break
if not species_type:
errors.append(
'Species type "{}" is not defined'.format(match.group(1)))
if match.group(2) in objects[Compartment]:
compartment = objects[Compartment][match.group(2)]
else:
errors.append(
'Compartment "{}" is not defined'.format(match.group(2)))
if errors:
return (None, InvalidAttribute(attribute, errors))
else:
obj = cls(species_type=species_type, compartment=compartment)
if cls not in objects:
objects[cls] = {}
objects[cls][obj.serialize()] = obj
return (obj, None)
return (None, InvalidAttribute(attribute, ['Invalid species']))
class SpeciesCoefficient(obj_model.Model):
""" A tuple of a species and a coefficient
Attributes:
species (:obj:`Species`): species
coefficient (:obj:`float`): coefficient
Related attributes:
reaction (:obj:`Reaction`): reaction
"""
species = ManyToOneAttribute(Species, related_name='species_coefficients')
coefficient = FloatAttribute(nan=False)
class Meta(obj_model.Model.Meta):
attribute_order = ('species', 'coefficient')
frozen_columns = 1
tabular_orientation = TabularOrientation.inline
ordering = ('species',)
def serialize(self, show_compartment=True, show_coefficient_sign=True):
""" Serialize related object
Args:
show_compartment (:obj:`bool`, optional): if true, show compartment
show_coefficient_sign (:obj:`bool`, optional): if true, show coefficient sign
Returns:
:obj:`str`: string representation of a species and a coefficient
"""
return self._serialize(self.species, self.coefficient,
show_compartment=show_compartment,
show_coefficient_sign=show_coefficient_sign)
@staticmethod
def _serialize(species, coefficient, show_compartment=True, show_coefficient_sign=True):
""" Serialize values
Args:
species (:obj:`Species`): species
coefficient (:obj:`float`): coefficient
show_compartment (:obj:`bool`, optional): if true, show compartment
show_coefficient_sign (:obj:`bool`, optional): if true, show coefficient sign
Returns:
:obj:`str`: string representation of a species and a coefficient
"""
coefficient = float(coefficient)
if not show_coefficient_sign:
coefficient = abs(coefficient)
if coefficient == 1:
coefficient_str = ''
elif coefficient % 1 == 0 and abs(coefficient) < 1000:
coefficient_str = '({:.0f}) '.format(coefficient)
else:
coefficient_str = '({:e}) '.format(coefficient)
if show_compartment:
return '{}{}'.format(coefficient_str, species.serialize())
else:
return '{}{}'.format(coefficient_str, species.species_type.get_primary_attribute())
@classmethod
def deserialize(cls, attribute, value, objects, compartment=None):
""" Deserialize value
Args:
attribute (:obj:`Attribute`): attribute
value (:obj:`str`): String representation
objects (:obj:`dict`): dictionary of objects, grouped by model
compartment (:obj:`Compartment`, optional): compartment
Returns:
:obj:`tuple` of `list` of `SpeciesCoefficient`, `InvalidAttribute` or `None`: tuple of cleaned value
and cleaning error
"""
errors = []
if compartment:
pattern = '^(\(((\-?\d*\.?\d+|\d+\.)(e[\-\+]?\d+)?)\) )*([a-z][a-z0-9_]*)$'
else:
pattern = '^(\(((\-?\d*\.?\d+|\d+\.)(e[\-\+]?\d+)?)\) )*([a-z][a-z0-9_]*\[[a-z][a-z0-9_]*\])$'
match = re.match(pattern, value, flags=re.I)
if match:
errors = []
coefficient = float(match.group(2) or 1.)
if compartment:
species_id = Species.gen_id(match.group(
5), compartment.get_primary_attribute())
else:
species_id = match.group(5)
species, error = Species.deserialize(
attribute, species_id, objects)
if error:
return (None, error)
serial_val = cls._serialize(species, coefficient)
if cls in objects and serial_val in objects[cls]:
return (objects[cls][serial_val], None)
obj = cls(species=species, coefficient=coefficient)
if cls not in objects:
objects[cls] = {}
objects[cls][obj.serialize()] = obj
return (obj, None)
else:
attr = cls.Meta.attributes['species']
return (None, InvalidAttribute(attr, ['Invalid species coefficient']))
class PolymerSpeciesType(SpeciesType):
""" Knowledge of a polymer
Attributes:
circular (:obj:`bool`): is the polymer circular