-
Notifications
You must be signed in to change notification settings - Fork 4
/
proppa.py
1272 lines (1098 loc) · 51.9 KB
/
proppa.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 -*-
"""
ProPPA - Probabilistic Programming Process Algebra
Usage:
proppa.py <model_file> [options]
proppa.py <model_file> infer [options]
Options:
-o FILE --out FILE Output file (default: <model_file>_out)
--seed SEED Seed for the random number generator
-h --help Show this help message
"""
""" Copyright notice:
A lot of this, especially the parsing, has been ported from the pepapot
repository, written by Allan Clark, and subsequently modified and adapted.
See the LICENSE file for more information.
"""
import itertools
import functools
import operator
import math
import os.path
import pyparsing
from pyparsing import Combine,Or,Optional,Literal,Suppress,MatchFirst,delimitedList
import numpy as np
import scipy as sp
from docopt import docopt
import model_utilities as mu
import samplers
# See pepapot comment on why this is useful (also:
# http://pyparsing.wikispaces.com/share/view/26068641?replyId=26084853 ,
# http://pyparsing.sourcearchive.com/documentation/1.4.7/
# classpyparsing_1_1ParserElement_81dd508823f0bf29dce996d788b1eeff.html )
pyparsing.ParserElement.enablePackrat()
def make_identifier_grammar(start_characters):
identifier_start = pyparsing.Word(start_characters, exact=1)
identifier_remainder = Optional(pyparsing.Word(pyparsing.alphanums + "_"))
identifier_grammar = identifier_start + identifier_remainder
return pyparsing.Combine(identifier_grammar)
lower_identifier = make_identifier_grammar("abcdefghijklmnopqrstuvwxyz")
upper_identifier = make_identifier_grammar("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
identifier = make_identifier_grammar(pyparsing.alphas)
plusorminus = Literal('+') | Literal('-')
number_grammar = pyparsing.Word(pyparsing.nums)
integer_grammar = Combine(Optional(plusorminus) + number_grammar)
decimal_fraction = Literal('.') + number_grammar
scientific_enotation = pyparsing.CaselessLiteral('E') + integer_grammar
floatnumber = Combine(integer_grammar + Optional(decimal_fraction) +
Optional(scientific_enotation))
def evaluate_function_app(name, arg_values):
""" Used in the evaluation of expressions. This evaluates the application
of a function.
"""
# pylint: disable=too-many-return-statements
# pylint: disable=too-many-branches
def check_num_arguments(expected_number):
""" For some of the functions we evaluate below they have a fixed
number of arguments, here we check that they have been supplied
the correct number.
"""
if len(arg_values) != expected_number:
if expected_number == 1:
message = "'" + name + "' must have exactly one argument."
else:
message = ("'" + name + "' must have exactly " +
str(expected_number) + " arguments.")
raise ValueError(message)
if name == "plus" or name == "+":
return sum(arg_values)
elif name == "times" or name == "*":
return functools.reduce(operator.mul, arg_values, 1)
elif name == "minus" or name == "-":
# What should we do if there is only one argument, I think we
# should treat '(-) x' the same as '0 - x'.
if not arg_values:
return 0
elif len(arg_values) == 1:
return 0 - arg_values[0]
else:
return functools.reduce(operator.sub, arg_values)
elif name == "divide" or name == "/":
if arg_values:
return functools.reduce(operator.truediv, arg_values)
else:
return 1
elif name == "power" or name == "**":
# power is interesting because it associates to the right
# counts downwards from the last index to the 0.
# As an example, consider power(3,2,3), the answer should be
# 3 ** (2 ** 3) = 3 ** 8 = 6561, not (3 ** 2) ** 3 = 9 ** 3 = 81
# going through our loop here we have
# exp = 1
# exp = 3 ** exp = 3
# exp = 2 ** exp = 2 ** 3 = 8
# exp = 3 ** exp = 3 ** 8 = 6561
exponent = 1
for i in range(len(arg_values) - 1, -1, -1):
exponent = arg_values[i] ** exponent
return exponent
elif name == "exp":
check_num_arguments(1)
return math.exp(arg_values[0])
elif name == "floor":
check_num_arguments(1)
return math.floor(arg_values[0])
elif name == "H" or name == "heaviside":
check_num_arguments(1)
# H is typically not actually defined for 0, here we have defined
# H(0) to be 0. Generally it won't matter much.
return 1 if arg_values[0] > 0 else 0
else:
raise ValueError("Unknown function name: " + name)
class Expression:
""" A new simpler representation of expressions in which we only have
one kind of expression. The idea is that reduce and get_value can be
coded as in terms of a single recursion.
"""
def __init__(self):
self.name = None
self.number = None
self.arguments = []
def __eq__(self, other):
return (isinstance(other, self.__class__) and
self.name == other.name and
self.number == other.number and
self.arguments == other.arguments)
@classmethod
def num_expression(cls, number):
expression = cls()
expression.number = number
return expression
@classmethod
def name_expression(cls, name):
expression = cls()
expression.name = name
return expression
@classmethod
def apply_expression(cls, name, arguments):
expression = cls()
expression.name = name
expression.arguments = arguments
return expression
@classmethod
def addition(cls, left, right):
return cls.apply_expression("+", [left, right])
@classmethod
def subtract(cls, left, right):
return cls.apply_expression("-", [left, right])
@classmethod
def multiply(cls, left, right):
return cls.apply_expression("*", [left, right])
@classmethod
def divide(cls, left, right):
return cls.apply_expression("/", [left, right])
@classmethod
def power(cls, left, right):
return cls.apply_expression("**", [left, right])
def used_names(self):
names = set()
# For now we do not add function names to the list of used rate names
# This seems correct, but if we did allow user-defined functions then
# obviously we might wish to know which ones are used.
if self.name and not self.arguments:
names.add(self.name)
for arg in self.arguments:
names.update(arg.used_names())
return names
def get_value(self, environment=None):
""" Returns the value of an expression in the given environment if
any. Raises an assertion error if the expression cannot be reduced
to a value.
"""
reduced_expression = self.reduce_expr(environment=environment)
assert reduced_expression.number is not None
return reduced_expression.number
def reduce_expr(self, environment=None):
if self.number is not None:
return self
if not self.arguments:
# We have a name expression so if the environment is None or
# or the name is not in the environment then we cannot reduce
# any further so just return the current expression.
if not environment or self.name not in environment:
return self
expression = environment[self.name]
return expression.reduce_expr(environment=environment)
# If we get here then we have an application expression, so we must
# first reduce all the arguments and then we may or may not be able
# to reduce the entire expression to a number or not.
arguments = [a.reduce_expr(environment)
for a in self.arguments]
arg_values = [a.number for a in arguments]
if any(v is None for v in arg_values):
return Expression.apply_expression(self.name, arguments)
else:
result_number = evaluate_function_app(self.name, arg_values)
return Expression.num_expression(result_number)
def differentiate(self,diff_variable):
if self.number is not None:
return Expression.num_expression(0)
if not self.arguments: #this is a name expression
#if it is the variable (species) wrt which we are differentiating:
if self.name == diff_variable:
return Expression.num_expression(1)
else: # if a different species or a parameter:
return Expression.num_expression(0)
# otherwise, we have an apply expression
diff_args = [a.differentiate(diff_variable) for a in self.arguments]
if self.name == '+':
return Expression.apply_expression('+',diff_args)
if self.name == '-':
return Expression.apply_expression('-',diff_args)
if self.name == '*':
term1 = Expression.multiply(diff_args[0],self.arguments[1])
term2 = Expression.multiply(self.arguments[0],diff_args[1])
return Expression.addition(term1,term2)
if self.name == '/':
term1 = Expression.multiply(diff_args[0],self.arguments[1])
term2 = Expression.multiply(diff_args[1],self.arguments[0])
numerator = Expression.subtract(term1,term2)
denominator = Expression.power(self.arguments[1],
Expression.num_expression(2))
return Expression.divide(numerator,denominator)
if self.name == '**':
# assuming exponents are constants (not species) for the time being
factor = self.arguments[1]
base = self.arguments[0]
expon = Expression.subtract(self.arguments[1],
Expression.num_expression(1))
return Expression.multiply(factor,Expression.power(base,expon))
raise ValueError("""Could not construct an expression of the derivative.
Are you using a strange operator?""")
# A helper to create grammar element which must be surrounded by parentheses
# but you then wish to ignore the parentheses
def parenthetical_grammar(element_grammar):
return Suppress("(") + element_grammar + Suppress(")")
def create_expression_grammar(identifier_grammar):
this_expr_grammar = pyparsing.Forward()
def num_expr_parse_action(tokens):
return Expression.num_expression(float(tokens[0]))
num_expr = floatnumber.copy()
num_expr.setParseAction(num_expr_parse_action)
def apply_expr_parse_action(tokens):
if len(tokens) == 1:
return Expression.name_expression(tokens[0])
else:
return Expression.apply_expression(tokens[0], tokens[1:])
arg_expr_list = pyparsing.delimitedList(this_expr_grammar)
opt_arg_list = Optional(parenthetical_grammar(arg_expr_list))
apply_expr = identifier_grammar + opt_arg_list
apply_expr.setParseAction(apply_expr_parse_action)
atom_expr = Or([num_expr, apply_expr])
multop = pyparsing.oneOf('* /')
plusop = pyparsing.oneOf('+ -')
def binop_parse_action(tokens):
elements = tokens[0]
operators = elements[1::2]
exprs = elements[::2]
assert len(exprs) - len(operators) == 1
exprs_iter = iter(exprs)
result_expr = next(exprs_iter)
# Note: iterating in this order would not be correct if the binary
# operator associates to the right, as with **, since for
# [2, ** , 3, ** 2] we would get build up the apply expression
# corresponding to (2 ** 3) ** 2, which is not what we want. However,
# pyparsing seems to do the correct thing and give this function
# two separate calls one for [3, **, 2] and then again for
# [2, ** , Apply(**, [3,2])].
for oper, expression in zip(operators, exprs_iter):
args = [result_expr, expression]
result_expr = Expression.apply_expression(oper, args)
return result_expr
precedences = [("**", 2, pyparsing.opAssoc.RIGHT, binop_parse_action),
(multop, 2, pyparsing.opAssoc.LEFT, binop_parse_action),
(plusop, 2, pyparsing.opAssoc.LEFT, binop_parse_action),
]
# pylint: disable=expression-not-assigned
this_expr_grammar << pyparsing.operatorPrecedence(atom_expr, precedences)
return this_expr_grammar
lower_expr_grammar = create_expression_grammar(lower_identifier)
expr_grammar = create_expression_grammar(identifier)
class DistributionTerm(object):
def to_distribution(self):
raise NotImplementedError
class GaussianTerm(DistributionTerm):
def __init__(self,mean,var):
self.mean = float(mean)
self.var = float(var)
grammar = (Literal("Normal") | Literal("Gaussian")) + "(" + \
floatnumber.setResultsName("mean") + "," + \
floatnumber.setResultsName("variance") + ")"
@classmethod
def from_tokens(cls,tokens):
return cls(tokens[2],tokens[4])
def to_distribution(self):
return sp.stats.norm(self.mean,self.var)
class UniformTerm(DistributionTerm):
def __init__(self,lower,upper):
self.lower = float(lower)
self.upper = float(upper)
grammar = Literal("Uniform") + "(" + \
floatnumber("lower") + "," + \
floatnumber("upper") + ")"
@classmethod
def from_tokens(cls,tokens):
return cls(tokens["lower"],tokens["upper"])
def to_distribution(self):
return sp.stats.uniform(self.lower,self.upper-self.lower)
class GammaTerm(DistributionTerm):
def __init__(self,shape,rate):
self.shape = float(shape)
self.rate = float(rate)
grammar = Literal("Gamma") + "(" + \
floatnumber("shape") + "," + \
floatnumber("rate") + ")"
@classmethod
def from_tokens(cls,tokens):
return cls(tokens["shape"],tokens["rate"])
def to_distribution(self):
return sp.stats.gamma(self.shape,scale=1/self.rate)
class ExponentialTerm(DistributionTerm):
def __init__(self,rate):
self.rate = float(rate)
grammar = Literal("Exponential") + "(" + floatnumber("rate") + ")"
@classmethod
def from_tokens(cls,tokens):
return cls(tokens["rate"])
def to_distribution(self):
return sp.stats.expon(scale=1/self.rate)
dist_terms = [GaussianTerm,UniformTerm,GammaTerm,ExponentialTerm]
for d in dist_terms:
d.grammar.setParseAction(d.from_tokens)
dist_grammar = MatchFirst([d.grammar for d in dist_terms])
class ConstantDefinition(object):
def __init__(self, lhs, rhs):
self.lhs = lhs
self.rhs = rhs
grammar = identifier + "=" + (dist_grammar|expr_grammar) + ";"
list_grammar = pyparsing.Group(pyparsing.ZeroOrMore(grammar))
@classmethod
def from_tokens(cls, tokens):
return cls(tokens[0], tokens[2])
ConstantDefinition.grammar.setParseAction(ConstantDefinition.from_tokens)
class DistributionDefinition(object):
def __init__(self,lhs,rhs):
self.lhs = lhs
self.rhs = rhs
grammar = identifier + "=" + dist_grammar + ";"
list_grammar = pyparsing.Group(pyparsing.ZeroOrMore(grammar))
@classmethod
def from_tokens(cls,tokens):
return cls(tokens[0], tokens[2])
DistributionDefinition.grammar.setParseAction(DistributionDefinition.from_tokens)
class DefaultDictKey(dict):
# pylint: disable=too-few-public-methods
""" The standard library provides the defaultdict class which
is useful, but sometimes the value that we wish to produce
depends upon the key. This class provides that functionality
"""
def __init__(self, factory):
super(DefaultDictKey, self).__init__()
self.factory = factory
def __missing__(self, key):
self[key] = self.factory(key)
return self[key]
class RateDefinition(object):
# pylint: disable=too-few-public-methods
""" A class representing a rate definition in a ProPPA model. It will
look like: "kineticLawOf r : expr;"
Where 'r' is the rate being definined and "expr" is an arbitrary
expression, usually involving the reactants of the reaction 'r'.
"""
def __init__(self, lhs, rhs):
self.lhs = lhs
self.rhs = rhs
grammar = "kineticLawOf" + identifier + ":" + expr_grammar + ";"
list_grammar = pyparsing.Group(pyparsing.OneOrMore(grammar))
@classmethod
def from_tokens(cls, tokens):
""" The parser method for ProPPA rate definitions."""
return cls(tokens[1], tokens[3])
RateDefinition.grammar.setParseAction(RateDefinition.from_tokens)
class Behaviour(object):
""" A class representing a behaviour. Species definitions consist of a list
of behaviours that the species are involved in. This class represents
one element of such a list. So for example "(a, 1) >> E" or a shorthand
version of that "a >>"
"""
def __init__(self, reaction, stoich, role, species):
self.reaction_name = reaction
self.stoichiometry = stoich
self.role = role
self.species = species
# If the stoichiometry is 1, then instead of writing "(r, 1)" we allow
# the modeller to simply write "r".
# TODO: Consider making the parentheses optional in any case, and then
# we can simply make the comma-stoich optional.
prefix_identifier = identifier.copy()
prefix_identifier.setParseAction(lambda tokens: (tokens[0], 1))
full_prefix_grammar = "(" + identifier + "," + integer_grammar + ")"
full_prefix_parse_action = lambda tokens: (tokens[1], int(tokens[3]))
full_prefix_grammar.setParseAction(full_prefix_parse_action)
prefix_grammar = Or([prefix_identifier, full_prefix_grammar])
op_strings = ["<<", ">>", "(+)", "(-)", "(.)"]
role_grammar = Or([Literal(op) for op in op_strings])
# The true syntax calls for (a,r) << P; where P is the name of the process
# being updated by the behaviour. However since this is (in the absence
# of locations) always the same as the process being defined, it is
# permitted to simply omit it.
process_update_identifier = Optional(identifier, default=None)
grammar = prefix_grammar + role_grammar + process_update_identifier
@classmethod
def from_tokens(cls, tokens):
""" The parser action method for a species behaviour. """
return cls(tokens[0][0], tokens[0][1], tokens[1], tokens[2])
def get_population_precondition(self):
""" Returns the pre-condition to fire this behaviour in a discrete
simulation. So for example a reactant with stoichiometry 2 will
require a population of at least 2.
"""
# TODO: Not quite sure what to do with general modifier here?
if self.role in ["<<", "(+)"]:
return self.stoichiometry
else:
return 0
def get_population_modifier(self):
""" Returns the effect this behaviour has on the associated population
if the behaviour were to be 'fired' once. So for example a
reactant with stoichiometry 2, will return a population modifier
of -2.
"""
if self.role == "<<":
return -1 * self.stoichiometry
elif self.role == ">>":
return 1 * self.stoichiometry
else:
return 0
def get_expression(self, kinetic_laws):
""" Return the expression that would be used in an ordinary
differential equation for the associated species. In other words
the rate of change in the given species population due to this
behaviour.
"""
modifier = self.get_population_modifier()
expr = kinetic_laws[self.reaction_name]
if modifier == 0:
expr = Expression.num_expression(0.0)
elif modifier != 1:
modifier_expr = Expression.num_expression(modifier)
expr = Expression.multiply(modifier_expr, expr)
return expr
Behaviour.grammar.setParseAction(Behaviour.from_tokens)
class Reaction(object):
# pylint: disable=too-few-public-methods
""" Represents a reaction in a biological system. This does not necessarily
have to be a reaction which is produced by parsing and processing a
Bio-PEPA model, but the definition is here because we wish to be able
to compute the set of all reactions defined by a Bio-PEPA model.
"""
def __init__(self, name):
self.name = name
self.reactants = []
self.activators = []
self.products = []
self.inhibitors = []
self.modifiers = []
def format(self):
""" Format the reaction as a string """
def format_name(behaviour):
""" format a name within the reaction as a string."""
if behaviour.stoichiometry == 1:
species = behaviour.species
else:
species = ("(" + behaviour.species + "," +
str(behaviour.stoichiometry) + ")")
if behaviour.role == "(+)":
prefix = "+"
elif behaviour.role == "(-)":
prefix = "-"
elif behaviour.role == "(.)":
prefix = "."
else:
prefix = ""
return prefix + species
pre_arrows = itertools.chain(self.reactants, self.activators,
self.inhibitors, self.modifiers)
pre_arrow = ", ".join(format_name(b) for b in pre_arrows)
post_arrow = ", ".join(format_name(b) for b in self.products)
return " ".join([self.name + ":", pre_arrow, "-->", post_arrow])
class SpeciesDefinition(object):
# pylint: disable=too-few-public-methods
""" Class that represents a ProPPA species definition. We store the name
and the right hand side of the definition which is a list of behaviours
the species is involved in.
"""
def __init__(self, lhs, rhs):
self.lhs = lhs
self.rhs = rhs
behaviours = pyparsing.delimitedList(Behaviour.grammar, delim="+")
grammar = identifier + "=" + pyparsing.Group(behaviours) + ";"
list_grammar = pyparsing.Group(pyparsing.OneOrMore(grammar))
@classmethod
def from_tokens(cls, tokens):
""" The parser action method for ProPPA species definition."""
species_name = tokens[0]
behaviours = tokens[2]
for behaviour in behaviours:
if behaviour.species is None:
behaviour.species = species_name
return cls(species_name, behaviours)
SpeciesDefinition.grammar.setParseAction(SpeciesDefinition.from_tokens)
class Observable(object):
def __init__(self, lhs, rhs):
self.lhs = lhs
self.rhs = rhs
grammar = "observable" + identifier + "=" + expr_grammar + ";"
list_grammar = pyparsing.Group(pyparsing.OneOrMore(grammar))
@classmethod
def from_tokens(cls, tokens):
""" The parser method for ProPPA rate definitions."""
return cls(tokens[1], tokens[3])
Observable.grammar.setParseAction(Observable.from_tokens)
class Population(object):
# pylint: disable=too-few-public-methods
""" Represents a ProPPA population. This is a process in the main
system equation, such as "E[100]"
"""
def __init__(self, species, amount):
self.species_name = species
self.amount = amount
grammar = identifier + "[" + expr_grammar + "]"
@classmethod
def from_tokens(cls, tokens):
""" The parser action method for a ProPPA population. """
return cls(tokens[0], tokens[2])
Population.grammar.setParseAction(Population.from_tokens)
system_grammar = pyparsing.delimitedList(Population.grammar,
delim="<*>")
filename_characters = pyparsing.alphanums + "." + "_" + "/"
observe_grammar = (Literal("observe") + "(" +
pyparsing.Word(filename_characters)("file") +
")" + ";")
infalg_grammar = Literal("infer") + "(" + identifier("alg") + ")" + ";"
conf_grammar = Literal("configure") + \
"(" + pyparsing.Word(filename_characters)("file") + ")" + ";"
class ParsedModel(object):
""" Class representing a parsed ProPPA model. It contains the grammar
description for a model.
"""
def __init__(self, constants, kinetic_laws, species, populations,
obsfile, algorithm, conffile, observables):
self.constants, self.uncertain = self.split_constants(constants)
self.kinetic_laws = kinetic_laws
self.species_defs = species
self.populations = populations
self.obsfile = obsfile
self.algorithm = algorithm
self.conffile = conffile
self.observables = observables
# Note, this parser does not insist on the end of the input text.
# Which means in theory you could have something *after* the model text,
# which might indeed be what you are wishing for.
grammar = (ConstantDefinition.list_grammar('constants') +
RateDefinition.list_grammar('rates') +
SpeciesDefinition.list_grammar('species') +
Optional(Observable.list_grammar('observables')) +
pyparsing.Group(system_grammar)('populations') +
pyparsing.OneOrMore(pyparsing.Group(observe_grammar))('obsfile') +
infalg_grammar('algorithm') +
Optional(conf_grammar('conffile')) )
whole_input_grammar = grammar + pyparsing.StringEnd()
whole_input_grammar.ignore(pyparsing.dblSlashComment)
@classmethod
def from_tokens(cls, tokens):
""" The parser action method for a ProPPA model. """
return cls(tokens['constants'], tokens['rates'],
tokens['species'], tokens['populations'],
[t['file'] for t in tokens['obsfile']],
tokens['algorithm']['alg'],
tokens['conffile']['file'] if 'conffile' in tokens else None,
tokens['observables'] if 'observables' in tokens else [])
@staticmethod
def split_constants(constants):
fixed = []
uncertain = []
for c in constants:
if isinstance(c.rhs,DistributionTerm):
uncertain.append(c)
else:
fixed.append(c)
return fixed,uncertain
@staticmethod
def remove_rate_laws(expression, multipliers):
""" Given an expression we remove calls to the rate laws methods.
Currently this only includes the fMA method, or law of mass action.
This means that within a given expression whenever the
sub-expression fMA(e) appears it is replaced by (e * R1 .. * Rn)
where R1 to Rn are the reactants and activators of the given
reaction.
"""
if not expression.arguments:
return expression
arguments = [ParsedModel.remove_rate_laws(arg, multipliers)
for arg in expression.arguments]
if expression.name and expression.name == "fMA":
# TODO: If there are no reactants? I think just the rate
# expression, which is what this does.
assert len(arguments) == 1
result_expr = arguments[0]
for (species, stoich) in multipliers:
species_expr = Expression.name_expression(species)
if stoich != 1:
# If the stoichiometry is not 1, then we have to raise the
# speices to the power of the stoichiometry. So if we have
# fMA(1.0), on a reaction X + Y -> ..., where X has
# stoichiometry 2, then we get fMA(1.0) = X^2 * Y * 1.0
stoich_expr = Expression.num_expression(stoich)
species_expr = Expression.power(species_expr, stoich_expr)
result_expr = Expression.multiply(result_expr, species_expr)
return result_expr
else:
# So we return a new expression with the new arguments. If we were
# doing this inplace, we could just replace the original
# expression's arguments.
return Expression.apply_expression(expression.name, arguments)
def expand_rate_laws(self):
""" A method to expand the rate laws which are simple convenience
functions for the user. So we wish to turn:
kineticLawOf r : fMA(x);
into
kineticLawOf r : x * A * B;
Assuming that A and B are reactants or activators for the
reaction r
"""
reaction_dict = self.get_reactions()
for kinetic_law in self.kinetic_laws:
reaction = reaction_dict[kinetic_law.lhs]
multipliers = [(b.species, b.stoichiometry)
for b in reaction.reactants + reaction.activators]
new_expr = self.remove_rate_laws(kinetic_law.rhs, multipliers)
kinetic_law.rhs = new_expr
def get_reactions(self):
""" Returns a list of reactions from the parsed model. """
reactions = DefaultDictKey(Reaction)
for species_def in self.species_defs:
behaviours = species_def.rhs
for behaviour in behaviours:
reaction = reactions[behaviour.reaction_name]
if behaviour.role == "<<":
reaction.reactants.append(behaviour)
elif behaviour.role == ">>":
reaction.products.append(behaviour)
elif behaviour.role == "(+)":
reaction.activators.append(behaviour)
elif behaviour.role == "(-)":
reaction.inhibitors.append(behaviour)
elif behaviour.role == "(.)":
reaction.modifiers.append(behaviour)
return reactions
def configure(self,sampler):
self.config = mu.read_configuration(self.conffile)
def numerize(self):
# Gather species names in alphabetical order:
self.species_order = [s.lhs for s in self.species_defs]
self.species_order.sort()
# Read observations from file; if there is a species order mentioned
# there, enforce it for the rest of the model:
if len(self.obsfile) > 1:
raise mu.ProPPAException("""Only one observations file can be
provided with this solver.""")
obs_filename = os.path.join(self.location,self.obsfile[0])
self.obs, self.obs_order = mu.load_observations(obs_filename)
if self.obs_order is None: # if observations don't label species
if len(self.obs[0]) - 1 != len(self.species_order): # if some are missing
raise mu.ProPPAException("""Only some species are observed ---
I cannot figure out which ones.""")
self.observed_species = [i for i in range(len(self.species_order))]
else: # rearrange the observations to match alphabetical order
rearrange = [0] + [self.obs_order.index(name)+1 for name in self.species_order
if name in self.obs_order]
self.obs = [[o[index] for index in rearrange] for o in self.obs]
self.observed_species = [i for i in range(len(self.species_order))
if self.species_order[i] in self.obs_order]
# Updates (stoichiometry matrix):
self.updates,self.react_order = mu.get_updates(self,self.species_order)
# Initial state:
d = dict([(p.species_name,p.amount.number) for p in self.populations])
self.init_state = tuple(d[s_name] for s_name in self.species_order)
# Reorder reactions too:
d = dict([(r.lhs,r) for r in self.kinetic_laws])
self.kinetic_laws = [d[r_name] for r_name in self.react_order]
# self.kinetic_laws.sort(key=lambda r: self.react_order.index(r.lhs))
# Concrete parameters:
self.concrete = [(c.lhs,c.rhs.get_value()) for c in self.constants]
#should maybe change this in case of references to other variables?
def numerize_enhanced(self):
# Gather species names in alphabetical order:
self.species_order = [s.lhs for s in self.species_defs]
self.species_order.sort()
# Read observations from file; if there is a species order mentioned
# there, enforce it for the rest of the model:
self.obs = []
for file in self.obsfile:
### Here we are making a big assumption! (which should be checked)
# that the species/observables are the same in every file, and in
# the same order.
#TODO enforce this check, or at least provide a warning
obs_filename = os.path.join(self.location,file)
exp_obs, self.obs_order = mu.load_observations(obs_filename)
if self.obs_order is None: # if observations don't label species
if len(exp_obs[0]) - 1 != len(self.species_order): # if some are missing
raise mu.ProPPAException("""Only some species are observed ---
I cannot figure out which ones.""")
self.species_mapping = [(i,i) for i in range(len(self.species_order))]
self.obs_names = []
self.observed_species = [i for i in range(len(self.species_order))]
else:
self.species_mapping,self.obs_mapping = mu.split_indices(
self.obs_order,
self.species_order)
self.observed_species = [self.species_order[i] for (i,v) in self.species_mapping]
self.obs.append(exp_obs)
# Updates (stoichiometry matrix):
self.updates,self.react_order = mu.get_updates(self,self.species_order)
# Initial state:
d = {p.species_name : p.amount.number for p in self.populations}
self.init_state = tuple(d[s_name] for s_name in self.species_order)
# Reorder reactions too:
d = {r.lhs : r for r in self.kinetic_laws}
self.kinetic_laws = [d[r_name] for r_name in self.react_order]
# self.kinetic_laws.sort(key=lambda r: self.react_order.index(r.lhs))
# Concrete parameters:
self.concrete = [(c.lhs,c.rhs.get_value()) for c in self.constants]
#should maybe change this in case of references to other variables?
def observation_mapping(self):
n = len(self.obs_order)
mapping = [None] * n
# map the species components to the right element of the state
for (i,index) in self.species_mapping:
mapping[i] = lambda p,index=index : (lambda s : s[index])
obs_evaluator = self.get_observables()
for (i,name) in self.obs_mapping:
mapping[i] = obs_evaluator[name]
return mapping
def reaction_functions(self):
return self.reaction_functions4()
def reaction_functions5(self):
"""Using the reduce_expr() method of Expression objects.
Slower than reaction_functions3/4."""
param_names = [p.lhs for p in self.uncertain]
def apply_state(expr,state):
env = {name : Expression.num_expression(value)
for name,value in zip(self.species_order,state)}
return expr.reduce_expr(env).number
def apply_parameters(expr,params):
env = {name : Expression.num_expression(value)
for name,value in zip(param_names,params)}
return lambda state: apply_state(expr.reduce_expr(env),state)
return [lambda p,rf=rf: apply_parameters(rf.rhs,p)
for rf in self.kinetic_laws]
def reaction_functions3(self):
""" Much faster! """
species_names = list(self.species_order)
param_names = [p.lhs for p in self.uncertain]
conc_names = [c.lhs for c in self.constants]
conc_vals = [float(mu.as_string(c.rhs)) for c in self.constants]
args_list = ",".join(conc_names+param_names+species_names)
kinetic_funcs = []
scope = {}
exec("from math import exp, floor", scope)
for (i,r) in enumerate(self.kinetic_laws):
exec("""def kinetic_func_{0}({1}):
return {2}""".format(i,args_list,mu.as_string(r.rhs)),
scope)
kinetic_funcs.append(scope['kinetic_func_'+str(i)])
def part_eval(f,part_args):
return lambda more_args: f(*tuple(part_args+more_args))
# For numerized models, kinetic law expressions will be sorted already
# so we can just assume the order is correct
# NB: the f=f named argument part is necessary to avoid problems with
# closures, so for the time being it stays even though it's ugly/weird
return [lambda p,f=f: part_eval(f,conc_vals+p) for f in kinetic_funcs]
def reaction_functions4(self):
""" For solvers which definitely use numpy arrays """
species_names = list(self.species_order)
param_names = [p.lhs for p in self.uncertain]
conc_names = [c[0] for c in self.concrete]
conc_vals = [c[1] for c in self.concrete]
# if len(self.concrete) > 0:
# conc_names, conc_vals = zip(*self.concrete)
# else:
# conc_names = conc_vals = []
args_list = ",".join(conc_names+param_names+species_names)
kinetic_funcs = []
scope = {}
exec("from math import exp, floor", scope)
for (i,r) in enumerate(self.kinetic_laws):
exec("""def kinetic_func_{0}({1}):
return {2}""".format(i,args_list,mu.as_string(r.rhs)),
scope)
kinetic_funcs.append(scope['kinetic_func_'+str(i)])
def part_eval(f,part_args):
#return lambda more_args: f(*tuple(numpy.hstack((part_args,more_args))))
return lambda more_args: f(*tuple(list(part_args) + list(more_args)))
# For numerized models, kinetic law expressions will be sorted already
# so we can just assume the order is correct
# NB: the f=f named argument part is necessary to avoid problems with
# closures, so for the time being it stays even though it's ugly/weird
return [lambda p,f=f: part_eval(f,list(conc_vals)+list(p)) for f in kinetic_funcs]
def reaction_functions2(self):
""" Slower than reaction_functions (at least as written) """
class FormatDict(dict):
def __missing__(self,key):
return '{' + key + '}'
species_names = self.species_order
param_names = [p.lhs for p in self.uncertain]
def text_eval_part(s,names,values):
return s.format_map(FormatDict(zip(names,values)))
# return s.format(**FormatDict(zip(names,values)))
# for (n,v) in zip(names,values):
# s = s.replace('{' + n +'}',v)
# return s
def text_eval_full(s,names,values):
return eval(s.format(**dict(zip(names,values))))
def make_func_of_state(t,param_values):
t2 = text_eval_part(t,param_names,param_values)
return lambda state: text_eval_full(t2,species_names,state)
def make_func_of_param(expr):
t = mu.as_string2(expr)
return lambda param_values: make_func_of_state(t,param_values)
# For numerized models, kinetic law expressions will be sorted already
# so we can just assume the order is correct
return [make_func_of_param(e.rhs) for e in self.kinetic_laws]
def reaction_functions1(self,order=None):
"""Constructs a list of functions that evaluate the kinetic laws.
Returns a list of functions, each of which takes a parameter vector
as input. The result of that call is another function which takes
a state vector as input, and returns the rate of that reaction for
the given parameterisation and state.
This makes sense on a deep level. Very deep.
"""
species_names = self.species_order
if order is None:
order = self.react_order
param_names = [p.lhs for p in self.uncertain]
def apply_params(params,expr):
env = {}
for i in range(len(params)):
env[param_names[i]] = Expression.num_expression(params[i])
def f(state):
def apply_state_inner(state,species_names,expr):
#env2 = {} # is it better to have a second dictionary?