-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmira_manual_examples.json
1920 lines (1920 loc) · 313 KB
/
mira_manual_examples.json
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
[
{
"origination_source_type": "code_file",
"origination_source": "mira_library",
"origination_method": "extract_from_library_manual",
"code": "```Code : ```from mira.metamodel import ControlledConversion, NaturalConversion, Concept, Template\n\n infected = Concept(name='infected population', identifiers={'ido': '0000511'})\n susceptible = Concept(name='susceptible population', identifiers={'ido': '0000514'})\n immune = Concept(name='immune population', identifiers={'ido': '0000592'})\n\n t1 = ControlledConversion(\n controller=infected,\n subject=susceptible,\n outcome=infected,\n )\n t2 = NaturalConversion(subject=infected, outcome=immune)\n Template.from_json(t1.dict())\n from mira.metamodel import TemplateModel\n sir_model = TemplateModel(templates=[t1, t2])```\n```",
"description": "Can you instantiate a SIR model using the metamodel template?"
},
{
"origination_source_type": "code_file",
"origination_source": "mira_library",
"origination_method": "extract_from_library_manual",
"code": "```Code : ```from mira.metamodel import ControlledConversion, NaturalConversion, Concept, Template\nexposed = Concept(name='exposed population', identifiers={'genepio': '0001538'})\ndeceased = Concept(name='deceased population', identifiers={'ncit': 'C28554'})\ns1 = ControlledConversion(\n controller=infected,\n subject=susceptible,\n outcome=exposed\n)\ns2 = NaturalConversion(\n subject=exposed,\n outcome=infected\n)\ns3 = NaturalConversion(\n subject=infected,\n outcome=deceased\n)\nM1 = TemplateModel(templates=[s1, s2, s3, t2])\nt2 = NaturalConversion(subject=infected, outcome=immune)\nu1 = ControlledConversion(\n controller=exposed,\n subject=susceptible,\n outcome=exposed\n)\nM2 = TemplateModel(templates=M1.templates + [u1])\nunreported = Concept(name='immune unreported population', identifiers={'ido': '0000592'},\n context={'status': 'unreported'})\n\nv1 = NaturalConversion(\n subject=exposed,\n outcome=unreported\n)\nM3 = TemplateModel(templates=M2.templates + [v1])\nw1 = NaturalConversion(\n subject=immune,\n outcome=susceptible\n)\nM4 = TemplateModel(templates=M2.templates + [w1])\nTemplateModel.from_json(M4.dict())```\n ```",
"description": "Create a more complicated SIRD style model using templates"
},
{
"origination_source_type": "code_file",
"origination_source": "mira_library",
"origination_method": "extract_from_library_manual",
"code": "```Code : ```import numpy\nimport matplotlib.pyplot as plt\n\nfrom mira.metamodel import *\nfrom mira.modeling import Model\nfrom mira.modeling.ode import OdeModel, simulate_ode_model\ntemplate_model = TemplateModel(\ntemplates=[\n NaturalConversion(\n subject=Concept(name='infected'),\n outcome=Concept(name='recovered')\n ),\n ControlledConversion(\n subject=Concept(name='susceptible'),\n outcome=Concept(name='infected'),\n controller=Concept(name='infected')\n )\n]\n)\nmodel = Model(template_model)\node_model = OdeModel(model)```",
"description": "Generate a sir model and then create an ode model from that model"
},
{
"origination_source_type": "code_file",
"origination_source": "mira_library",
"origination_method": "extract_from_library_manual",
"code": "```Code : ```times = numpy.linspace(0, 25, 100)\n\nres = simulate_ode_model(\node_model=ode_model,\ninitials=numpy.array([0.01, 0, 0.99]),\nparameters={('infected', 'recovered', 'NaturalConversion', 'rate'): 0.5,\n ('susceptible', 'infected', 'infected', 'ControlledConversion', 'rate'): 1.1},\ntimes=times\n)\ninfected, recovered, susceptible = plt.plot(times, res)\ninfected.set_color('blue')\nrecovered.set_color('orange')\nsusceptible.set_color('green')\nplt.show()```",
"description": "simulate my model ode_model using some default conditions then plot the results"
},
{
"origination_source_type": "code_file",
"origination_source": "mira_library",
"origination_method": "extract_from_library_manual",
"code": "```Code : ```from mira.sources.biomodels import get_template_model\ntemplate_model = get_template_model('BIOMD0000000956')```",
"description": "Get template model \"BIOMD0000000956\""
},
{
"origination_source_type": "code_file",
"origination_source": "mira_library",
"origination_method": "extract_from_library_manual",
"code": "```Code : ```import requests\nsir_template_model_dict = sir_template_model.dict()\nrest_url = \"http://34.230.33.149:8771\"\nres = requests.post(rest_url + \"/api/stratify\", json={\"template_model\": sir_template_model_dict, \"key\": \"city\", \"strata\": [\"Boston\", \"New York City\"]})\nprint(res.json())```",
"description": "Stratify my sir template model by 2 different cities"
},
{
"origination_source_type": "code_file",
"origination_source": "mira_library",
"origination_method": "extract_from_library_manual",
"code": "```Code : ```import requests\nfrom mira.metamodel import Concept, ControlledConversion, NaturalConversion, TemplateModel\n\n# Example TemplateModel\ninfected = Concept(name=\"infected population\", identifiers={\"ido\": \"0000511\"})\nsusceptible = Concept(name=\"susceptible population\", identifiers={\"ido\": \"0000514\"})\nimmune = Concept(name=\"immune population\", identifiers={\"ido\": \"0000592\"})\ncontrolled_conversion = ControlledConversion(\ncontroller=infected,\nsubject=susceptible,\noutcome=infected,\n)\nnatural_conversion = NaturalConversion(subject=infected, outcome=immune)\nsir_template_model = TemplateModel(templates=[controlled_conversion, natural_conversion])\nsir_template_model_dict = sir_template_model.dict()\nprint(sir_template_model.json())```",
"description": "Create a SIR model"
},
{
"origination_source_type": "code_file",
"origination_source": "mira_library",
"origination_method": "extract_from_library_manual",
"code": "```from mira.metamodel import ControlledConversion, NaturalConversion,TemplateModel\n# SIR Model\ninfection = ControlledConversion(\nsubject=susceptible,\noutcome=infected,\ncontroller=infected,\n)\nrecovery = NaturalConversion(\nsubject=infected,\noutcome=recovered,\n)\nsir = TemplateModel(\ntemplates=[\n infection,\n recovery,\n],\n)```",
"description": "create an sir model for me"
},
{
"origination_source_type": "code_file",
"origination_source": "mira_library",
"origination_method": "extract_from_library_manual",
"code": "```from mira.metamodel import ControlledConversion, NaturalConversion,TemplateModel,Parameter,Initial,safe_parse_expr\nimport sympy\nfrom copy import deepcopy as _d\nfrom mira.examples.concepts import susceptible, infected, recovered\nsir_parameterized = TemplateModel(\ntemplates=[\n ControlledConversion(\n subject=_d(susceptible),\n outcome=_d(infected),\n controller=_d(infected),\n rate_law=safe_parse_expr(\n 'beta * susceptible_population * infected_population',\n local_dict={'beta': sympy.Symbol('beta')}\n )\n ),\n NaturalConversion(\n subject=_d(infected),\n outcome=_d(recovered),\n rate_law=safe_parse_expr(\n 'gamma * infected_population',\n local_dict={'gamma': sympy.Symbol('gamma')}\n )\n )\n],\nparameters={\n 'beta': Parameter(name='beta', value=0.1),\n 'gamma': Parameter(name='gamma', value=0.2)\n},\ninitials={\n 'susceptible_population': Initial(concept=_d(susceptible), expression=sympy.Integer('1')),\n 'infected_population': Initial(concept=_d(infected), expression=sympy.Integer('2')),\n 'immune_population': Initial(concept=_d(recovered), expression=sympy.Integer('3')),\n}\n)```",
"description": "create an sir model for me with parameters"
},
{
"origination_source_type": "code_file",
"origination_source": "mira_library",
"origination_method": "extract_from_library_manual",
"code": "```from mira.metamodel import ControlledConversion, NaturalConversion,TemplateModel\nimport sympy\nfrom mira.examples.concepts import susceptible, infected, recovered\ncities = [\n\"geonames:5128581\", # NYC\n\"geonames:4930956\", # boston\n]\ninfection = ControlledConversion(\nsubject=susceptible,\noutcome=infected,\ncontroller=infected,\n)\nrecovery = NaturalConversion(\nsubject=infected,\noutcome=recovered,\n)\nsusceptible_nyc, susceptible_boston = (susceptible.with_context(city=city) for city in cities)\ninfected_nyc, infected_boston = (infected.with_context(city=city) for city in cities)\nrecovered_nyc, recovered_boston = (recovered.with_context(city=city) for city in cities)\ninfection_nyc, infection_boston = (infection.with_context(city=city) for city in cities)\nrecovery_nyc, recovery_boston = (recovery.with_context(city=city) for city in cities)\nsusceptible_nyc_to_boston = NaturalConversion(subject=susceptible_nyc, outcome=susceptible_boston)\nsusceptible_boston_to_nyc = NaturalConversion(subject=susceptible_boston, outcome=susceptible_nyc)\ninfected_nyc_to_boston = NaturalConversion(subject=infected_nyc, outcome=infected_boston)\ninfected_boston_to_nyc = NaturalConversion(subject=infected_boston, outcome=infected_nyc)\nrecovered_nyc_to_boston = NaturalConversion(subject=recovered_nyc, outcome=recovered_boston)\nrecovered_boston_to_nyc = NaturalConversion(subject=recovered_boston, outcome=recovered_nyc)\nsir_2_city = TemplateModel(\ntemplates=[\n infection_nyc,\n infection_boston,\n recovery_nyc,\n recovery_boston,\n susceptible_nyc_to_boston,\n susceptible_boston_to_nyc,\n infected_nyc_to_boston,\n infected_boston_to_nyc,\n recovered_nyc_to_boston,\n recovered_boston_to_nyc,\n],\n)```",
"description": "create an sir model for me with 2 strata, each for a different city, new york city and boston"
},
{
"origination_source_type": "code_file",
"origination_source": "mira_library",
"origination_method": "extract_from_library_manual",
"code": "```from mira.metamodel import Concept, ControlledConversion, NaturalConversion, TemplateModel\ninfected = Concept(name='infected population', identifiers={'ido': '0000511'})\nsusceptible = Concept(name='susceptible population', identifiers={'ido': '0000514'}) \nrecovered = Concept(name='recovered population', identifiers={'ido': '0000592'}) \ninfection = ControlledConversion(subject=susceptible,outcome=infected,controller=infected)\nrecovery = NaturalConversion(subject=infected,outcome=recovered) \nsir_model=TemplateModel(templates=[infection,recovery])\n\n# Output the model with parameters to inspect it\nfrom mira.metamodel import Parameter, safe_parse_expr\nimport sympy\n\n# Define parameters for the SIR model\nbeta = Parameter(name='beta', value=0.1)\ngamma = Parameter(name='gamma', value=0.2)\n\n# Update the transitions with rate laws using symbolic expressions\ninfection.rate_law = safe_parse_expr('beta * susceptible_population * infected_population', local_dict={'beta': sympy.Symbol('beta')})\nrecovery.rate_law = safe_parse_expr('gamma * infected_population', local_dict={'gamma': sympy.Symbol('gamma')})\n\n# Add parameters to the model\nsir_model.parameters = {'beta': beta, 'gamma': gamma}\nfrom mira.modeling import Model\nfrom mira.modeling.ode import OdeModel\n\n# Assuming sir_model is already defined and correctly instantiated with parameters\n\n# Convert the TemplateModel to a Model\nsir_model_converted = Model(sir_model)\n\n# Create an ODE model from the converted model, setting initialized to True\node_model = OdeModel(sir_model_converted, initialized=True)```",
"description": "Create an sir model for me then convert it to an ODE model"
},
{
"origination_source_type": "code_file",
"origination_source": "mira_library",
"origination_method": "extract_from_library_manual",
"code": "```# Assuming 'sir_model' and 'seirdh_model' are already defined in the user's environment\n# and are instances of TemplateModel.\n\nfrom mira.metamodel import get_dkg_refinement_closure\nrc = get_dkg_refinement_closure()\n\n# Compare the models\nmodel_comparison = TemplateModelComparison([sir_model, seirdh_model], refinement_func=rc.is_ontological_child)\n\n# Visualize the comparison\n# This will generate a graph which we can then display\n\ntm = model_comparison.template_models\nTemplateModelDelta.for_jupyter(tm[0], tm[1], rc.is_ontological_child, args=\"-Grankdir=TB\")```",
"description": "Structural comparison of two or more models with visualization"
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/concepts.py",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import Concept\nfrom mira.metamodel import Concept\n\n__all__ = [\n\"susceptible\",\n\"infected\",\n\"infected_asymptomatic\",\n\"infected_symptomatic\",\n\"recovered\",\n\"exposed\",\n\"dead\",\n\"hospitalized\",\n\"vaccinated\",```",
"description": "Declaration of the concept list"
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/concepts.py",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import Concept\nsusceptible = Concept(name=\"susceptible_population\", identifiers={\"ido\": \"0000514\"})\ninfected = Concept(name=\"infected_population\", identifiers={\"ido\": \"0000511\"})\ninfected_symptomatic = infected.with_context(status=\"symptomatic\")\ninfected_asymptomatic = infected.with_context(status=\"asymptomatic\")\nrecovered = Concept(name=\"immune_population\", identifiers={\"ido\": \"0000592\"})\nexposed = susceptible.with_context(property=\"ido:0000597\")\ndead = Concept(name=\"dead\", identifiers={\"ncit\": \"C28554\"})\nhospitalized = Concept(name=\"hospitalized\", identifiers={\"ncit\": \"C25179\"})```",
"description": "Defining various health status concepts with the Mira library"
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/web_client.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.dkg.web_client import ground_web\n# To ground an entity, provide `ground_web` with at least the text to be grounded:\n\n# In[10]:\n\n\nground_res = ground_web(text=\"Infected Population\")\n# ground_web returns a GroundResults model from mira.dkg.grounding\nprint(ground_res.__class__)\nprint('--')\nfor grounding_result in ground_res.results:\nprint(grounding_result)```",
"description": "This example demonstrates how to ground an entity using the `ground_web` function by providing the text to be grounded. It then prints the class of the returned `GroundResults` model followed by each grounding result."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/web_client.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.dkg.web_client import get_entity_web\n# To get more information about an entity, provide its curie to the `get_entity_web` function:\n\n# In[3]:\n\n\nentity = get_entity_web(curie=\"ido:0000511\")```",
"description": "This example shows how to retrieve details about an entity using its curie with the `get_entity_web` function. The retrieved entity information is then printed."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/web_client.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.dkg.web_client import get_relations_web\nfrom mira.dkg.api import RelationQuery\n# To query for relations, use the `get_relations_web` function:\n\n# In[4]:\n\n\nrelation_query = RelationQuery(target_curie=\"ncbitaxon:10090\", relations=\"vo:0001243\")\nrelations = get_relations_web(relations_model=relation_query)```",
"description": "This example highlights how to query for relations using the `get_relations_web` function. It prepares a relation query with a target curie and a relation, and then retrieves and prints the first five relation results."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/DKG RDF Demo.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\nimport rdflib\nimport pystow\n\nget_ipython().system('python -m pip install rdflib pystow')\n\n\n# In[11]:\n\n\nimport rdflib\nimport pystow\nfrom tabulate import tabulate\nimport pandas as pd\n\n\n# In[8]:\n\n\ndomain = \"epi\"\nversion = \"2023-02-13\"\nurl = f\"https://askem-mira.s3.amazonaws.com/dkg/{domain}/build/{version}/dkg.ttl.gz\"\n\n\n# In[9]:\n\n\ngraph = rdflib.Graph()\n\nwith pystow.ensure_open_gz(\"mira\", domain, version, url=url) as file:```",
"description": "This section demonstrates how to install necessary libraries and prepare a graph by loading RDF data from a gzipped Turtle file."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/DKG RDF Demo.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import rdflib\nimport pandas as pd\nfrom rdflib import Graph\ngraph = Graph()\n\n# Use SPARQL to get all distinct predicates\n\n# In[13]:\n\n\nresults = graph.query(\"\"\"\\\nSELECT DISTINCT ?p\nWHERE {\n?s ?p ?o\n}\n\"\"\")\n\npredicates_df = pd.DataFrame(results, columns=[\"predicate\"])```",
"description": "Using SPARQL to retrieve all distinct predicates from the knowledge graph and display them in a DataFrame."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/DKG RDF Demo.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import rdflib\nimport pandas as pd\nfrom rdflib import Graph\ngraph = Graph()\n\n# Use SPARQL to get all parent-child relationships (using `rdfs:subClassOf` as predicate whose subject is the child and whose object is the parent)\n\n# In[14]:\n\n\nresults = graph.query(\"\"\"\\\nSELECT ?child ?childLabel ?parent ?parentLabel\nWHERE {\n?child rdfs:subClassOf ?parent .\n?child rdfs:label ?childLabel .\n?parent rdfs:label ?parentLabel .\n}\nLIMIT 5\n\"\"\")\n\nparents_df = pd.DataFrame(results, columns=[\"child\", \"child_label\", \"parent\", \"parent_label\"])```",
"description": "Querying the graph to find all parent-child relationships using `rdfs:subClassOf`. Results are shown in a DataFrame."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/DKG RDF Demo.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import rdflib\nimport pandas as pd\nfrom rdflib import Graph\ngraph = Graph()\n\n# Use SPARQL to use multiple predicates (both for child->parent and part->whole)\n\n# In[20]:\n\n\nresults = graph.query(\"\"\"\\\nPREFIX bfo: <https://bioregistry.io/bfo:>\n\nSELECT ?child ?childLabel ?parent ?parentLabel\nWHERE {\n?child rdfs:subClassOf|bfo:0000050 ?parent .\n?child rdfs:label ?childLabel .\n?parent rdfs:label ?parentLabel .\n}\nLIMIT 5\n\"\"\")\n\nparents_df = pd.DataFrame(results, columns=[\"child\", \"child_label\", \"parent\", \"parent_label\"])```",
"description": "SPARQL query to retrieve parent-child relations as well as part-whole relations using multiple predicates. Results are displayed in a DataFrame."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/TA1 Extraction Evaluation.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\nimport pandas as pd\nimport pandas as pd\n\nurl = \"https://docs.google.com/spreadsheets/d/e/2PACX-1vQ2G-ZFSotS2qo94mnTWCDvj9Y49ai-9O61DA7940sPYynEdBXq2cT2-Wl3nNldIb3gkpbPFaTFY2PJ/pub?output=xlsx\"\n\nxls = pd.ExcelFile(url)```",
"description": "This example demonstrates how to load an Excel file from a URL using pandas."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/TA1 Extraction Evaluation.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import pandas as pd\nurl = \"https://docs.google.com/spreadsheets/d/e/2PACX-1vQ2G-ZFSotS2qo94mnTWCDvj9Y49ai-9O61DA7940sPYynEdBXq2cT2-Wl3nNldIb3gkpbPFaTFY2PJ/pub?output=xlsx\"\nxls = pd.ExcelFile(url)\nsheets = {\nsheet_name: pd.read_excel(xls, sheet_name)\nfor sheet_name in xls.sheet_names\n}\nfor sheet in sheets.values():\nsheet['grounding'] = sheet['grounding'].map(eval)```",
"description": "This example shows how to read all sheets from the loaded Excel file into a dictionary of DataFrames and apply a transformation on a column."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/TA1 Extraction Evaluation.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import pandas as pd\nfrom collections import defaultdict\nfrom collections import defaultdict\nground_truth_df = pd.read_csv(\"/Users/cthoyt/Downloads/biomodels_groundings.tsv\", sep='\\t')\n\ndd = defaultdict(set)\nfor model_id, curie in ground_truth_df.values:\ndd[model_id].add(curie)\ndd = dict(dd)```",
"description": "This example illustrates how to create a defaultdict from CSV data. It reads a CSV file into a DataFrame, then iterates over its rows to add each item into a defaultdict(set). Finally, it converts the defaultdict to a regular dictionary."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/TA1 Extraction Evaluation.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import pandas as pd\nsheets = {your_dictionary_here}\ndd = {your_dictionary_here}\nfrom collections import defaultdict\nrows = []\nfor model_id, sheet in sheets.items():\nsheet_curies = {\ngrounding[\"id\"]\nfor groundings in sheet[\"grounding\"]\nfor grounding in groundings\n}\nground_truth_curies = dd[model_id]\n\nintersection_curies = sheet_curies & ground_truth_curies\nn_intersection = len(intersection_curies)\nn_ground_truth = len(ground_truth_curies)\nn_sheet = len(sheet_curies)\nrows.append((\nmodel_id,\nn_ground_truth,\nn_intersection,\nround(n_intersection / n_ground_truth, 2)\n))\n\nprint(\"The way to interpret the precision is the percent\")```",
"description": "This example demonstrates how to compute the intersection of CURIEs identifiers between sheets and a ground truth set. It iterates over the sheets and ground truth data, calculates intersections, and prints out a summary DataFrame."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/Entity Similarity Demo.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import requests\nimport pandas as pd\nimport requests\nimport pandas as pd\n\n\n# Documentation for the entity similarity endpoint can be found at http://34.230.33.149:8771/docs#/entities/entity_similarity_api_entity_similarity_post. It takes in compact URIs (CURIEs), which are the \"primary keys\" for terms in the DKG. It then performs an all-by-all comparison of sources and targets.\n\n# In[10]:\n\n\nURL = \"http://127.0.0.1:8771/api/entity_similarity\"\n\ndef get_similarities_df(sources, targets=None):\nif targets is None:\ntargets = sources\nres = requests.post(URL, json={\"sources\": sources, \"targets\": targets})\nres.raise_for_status()\ndf = pd.DataFrame(res.json())\n\ncuries = \",\".join(sorted(set(df.source).union(df.target)))\nres = requests.get(f\"http://127.0.0.1:8771/api/entities/{curies}\").json()\nnames = {record['id']: record['name'] for record in res}\n\nassert \"similarity\" in df.columns\ndf[\"source_name\"]=df['source'].map(names)\ndf[\"target_name\"]=df['target'].map(names)```",
"description": "This example demonstrates how to query an entity similarity API with a list of CURIEs (compact URIs), perform an all-by-all comparison of sources and targets, and process the returned similarity scores. It includes fetching entity names using CURIEs from another API endpoint and attaching these names to the similarity dataframe."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/Entity Similarity Demo.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import requests\nimport pandas as pd\n\nURL = \"http://127.0.0.1:8771/api/entity_similarity\"\n\ndef get_similarities_df(sources, targets=None):\n if targets is None:\n targets = sources\n res = requests.post(URL, json={\"sources\": sources, \"targets\": targets})\n res.raise_for_status()\n df = pd.DataFrame(res.json())\n\n curies = \",\".join(sorted(set(df.source).union(df.target)))\n res = requests.get(f\"http://127.0.0.1:8771/api/entities/{curies}\").json()\n names = {record['id']: record['name'] for record in res}\n\n assert \"similarity\" in df.columns\n df[\"source_name\"]=df['source'].map(names)\n df[\"target_name\"]=df['target'].map(names)\n return df[[\"source\", \"source_name\", \"target\", \"target_name\", \"similarity\"]]\nget_similarities_df(\n[\n\"ido:0000514\", # susceptible population\n\"ido:0000592\", # immune population\n\"vo:0004921\", # = human age\n\"ido:0000511\", # = infected population\n\"ido:0000512\", # = diseased population\n\"apollosv:00000233\", # = infected population\n]```",
"description": "A practical example making use of the 'get_similarities_df' function defined earlier to compare the similarity between various population types across different ontologies including susceptible, immune, human age, infected, and diseased populations."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/Rapid construction of new DKGs.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\n# After installing MIRA, the pre-defined DKGs can be constructed using the following shell script:\n#\n# ```shell\n# python -m mira.dkg.construct --use-case epi\n# ```\n#\n# This does the following:\n#\n# 1. Creates a nodes and edges file that can be loaded into a Neo4j graph database. These are orchestrated along with the MIRA web application in Docker (more information [here](https://github.com/indralab/mira/tree/main/docker)).\n# 2. Creates an RDF dump that can be loaded in any triple store and queried with SPARQL\n# 3. Uses graph machine learning to create dense node embeddings based on the topology of the knowledge graph\n# 4. Creates a \"metaregistry\" configuration file. Note that we actually combine all of the metaregistry configrations together into a single service running at http://34.230.33.149:8772/.\n#```",
"description": "Running a pre-defined DKG construction for epidemiology use-case using a shell script command."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/Rapid construction of new DKGs.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\n\nfrom mira.dkg.construct import construct, DKGConfig\n# In addition to the pre-configured DKGs, new DKGs can be rapidly constructed using the Python API to MIRA.\n\n# In[1]:\n\n\nfrom mira.dkg.construct import construct, DKGConfig\n\n\n# While the epidemiology use case had a close relationship between the DKG and the modeling framework, the new regnet framework being proposed in the early May 2023 hackathon can appear in several domains including:\n#\n# - gene transcription regulatory networks\n# - ecological networks (i.e., predator-prey networks *a la* Lotka-Volterra)\n# - cell signalling networks\n#\n# In the following example, we construct an *ad hoc* domain knowledge graph by specifying several resources useful for describing genes and phenomena that may appear in these networks including:\n#\n# - HGNC - an ontology of human genes that contains relationships to gene families families, proteins. Useful for annotating components of models.\n# - Gene Ontology (GO) - an ontology of molecular functional and biological processes used in annotating genes. Useful for both model-level annotation and annotating relationships between components of models (e.g., edges).\n# - WikiPathways - a resource categorizing genes in functional pathways. Useful for model-level annotation\n# - ProbOnto - an ontology of probability distributions\n\n# In[2]:\n\n\ngenereg_config = DKGConfig(\nuse_case=\"genereg\",\nprefixes=[\n\"hgnc\",\n\"go\",\n\"wikipathways\",\n\"probonto\",\n],\n)\n\nuse_case_paths = construct(\nconfig=genereg_config,\n# do_upload=True, # uncomment when you're ready to send to S3!```",
"description": "Constructing an ad hoc domain knowledge graph for the gene regulatory networks use-case using the Python API."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/Rapid construction of new DKGs.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\n# Alternatively, if you would rather use the command line, you can declare this configuration as the following JSON (let's say it's called `config.json`:\n#\n# ```json\n# {\n# \"use_case\": \"genereg\",\n# \"prefixes\": [\"hgnc\", \"go\", \"wikipathways\", \"probonto\"]\n# }\n# ```\n#\n# Then run the following code:\n#\n# ```shell\n# python -m mira.dkg.construct --use-case config.json\n# ```\n#```",
"description": "Demonstrating how to declare DKG configuration as JSON for the command line interface."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/Rapid construction of new DKGs.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\n\nimport pandas as pd\n\ngenereg_config = DKGConfig(\n use_case=\"genereg\",\n prefixes=[\n \"hgnc\",\n \"go\",\n \"wikipathways\",\n \"probonto\",\n ],\n)\n\nuse_case_paths = construct(\n config=genereg_config,\n # do_upload=True, # uncomment when you're ready to send to S3!\n)\n# ## Exploring the Content\n#\n# The job of this pipeline is not to fully automate building the docker image and deploying the service, so instead we directly explore the nodes and edges files created for the Neo4j graph database here. It can be seen that a combination of domain nodes and upper level ontology nodes appear, as well as a combination of instance-level relationships and higher level ontological relationships appear in the edges file.\n\n# In[3]:\n\n\nimport pandas as pd\n\n\n# In[6]:\n\n\nnodes_df = pd.read_csv(use_case_paths.NODES_PATH, sep='\\t', dtype=str)\nnodes_df\n\n\n# In[7]:\n\n\nedges_df = pd.read_csv(use_case_paths.EDGES_PATH, sep='\\t', dtype=str)```",
"description": "Exploring the nodes and edges files created for the Neo4j graph database of a DKG."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/Rapid construction of new DKGs.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\n# ## Next Steps\n#\n# We've built on two exsting softwares, `pyobo` and `bioontologies` for the discovery and parsing of ontologies, but we don't yet have abstract tooling for ingesting knowledge graphs.\n#\n# For example, in the ecological domain (where we might have predator and prey models like Lotka-Volterra), it would be useful to get and ingest the Global Biotic Interaction (GloBI) knowledge graph, which contains interactions between agents in the environment such as:\n#\n# - What do sea otters (Enhydra lutris) eat?\n# - What do honey bees (Apis) pollinate?\n#```",
"description": "Discussing potential extensions and applications of the DKG framework for ecological domain use-cases."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/Hackathon Scenario 2 - Find Models with Hospitalizations.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.sources.biomodels import query_biomodels, get_template_model\nfrom tqdm.auto import tqdm\nmodels_res = query_biomodels(\"submitter_keywords:COVID-19\", limit=30)\n\n\n# In[3]:\n\n\nrows = []\nfor model_data in tqdm(models_res):\ntry:\ntemplate_model = get_template_model(model_data[\"id\"])\nexcept Exception:\npass\nrows.append((\nmodel_data[\"id\"], model_data[\"name\"], template_model,\n))\n\n\n# In[4]:\n\n```",
"description": "Querying BioModels for COVID-19 related models"
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/Hackathon Scenario 2 - Find Models with Hospitalizations.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from tabulate import tabulate\nfrom textwrap import shorten\n\nmodels_res = query_biomodels(\"submitter_keywords:COVID-19\", limit=30)\nrows = []\nfor model_data in tqdm(models_res):\n try:\n template_model = get_template_model(model_data[\"id\"])\n except Exception:\n pass\n rows.append((\n model_data[\"id\"], model_data[\"name\"], template_model,\n ))\nseen = set()\nres_rows = []\nfor m_id, m_name, m in rows:\nif m_id.startswith('BIOMD'):\nfor template in m.templates:\nfor concept in template.get_concepts():\nif \"hosp\" in concept.name.lower():\nif m_id not in seen:\nseen.add(m_id)\nres_rows.append((\nm_id, shorten(m_name, 40), len(m.templates),\nconcept.get_curie_str(), shorten(concept.name, 30)\n))\n\nprint(tabulate(\nres_rows,\ntablefmt=\"github\",\nheaders=[\"model_id\", \"model_title\", \"model_size\", \"compartment_curie\", \"compartment_label\"],```",
"description": "Identifying and tabulating models with hospitalization compartments"
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/Hackathon Scenario 2 - Find Models with Hospitalizations.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.modeling.viz import GraphicalModel\n\nm1 = next(x for i, _, x in rows if i == \"BIOMD0000000960\")\nm2 = next(x for i, _, x in rows if i == \"BIOMD0000000971\")\nm3 = next(x for i, _, x in rows if i == \"BIOMD0000000958\")\nm1 = next(x for i, _, x in rows if i == \"BIOMD0000000960\")\nm2 = next(x for i, _, x in rows if i == \"BIOMD0000000971\")\nm3 = next(x for i, _, x in rows if i == \"BIOMD0000000958\")\n\n\n# In[19]:\n\n\nGraphicalModel.for_jupyter(m1, width=\"30%\")\n\n\n# In[20]:\n\n\nGraphicalModel.for_jupyter(m2, width=\"30%\")\n\n\n# In[21]:\n\n```",
"description": "Visualizing three selected BioModels"
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/Hackathon Scenario 2 - Find Models with Hospitalizations.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.examples.sir import svir\nfrom mira.examples.concepts import hospitalized, infected_symptomatic, infected_asymptomatic, recovered\n\nsvihr = svir.add_transition(infected_symptomatic, hospitalized)\nsvihr = svihr.add_transition(infected_asymptomatic, recovered)\nsvihr = svihr.add_transition(hospitalized, recovered)\n# Add the hospitalized node\n\nsvihr = svir.add_transition(infected_symptomatic, hospitalized)\nsvihr = svihr.add_transition(infected_asymptomatic, recovered)\nsvihr = svihr.add_transition(hospitalized, recovered)\n\n\n# In[26]:\n\n\nGraphicalModel.for_jupyter(svir, width=\"20%\")\n\n\n# In[27]:\n\n```",
"description": "Adding a hospitalization compartment to the SVIR model and visualizing the original and modified models"
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/mech_bayes.py",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import ControlledConversion\nfrom mira.examples.concepts import susceptible, exposed, infected\n# Exposure\nexposure = ControlledConversion(\nsubject=susceptible,\noutcome=exposed,\ncontroller=infected,```",
"description": "This section provides an example of modeling exposure as a controlled conversion process within a SEIRD model using the Mira library. It defines an 'exposure' process where a 'susceptible' entity becomes 'exposed' due to interaction with an 'infected' entity."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/mech_bayes.py",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import NaturalConversion\nfrom mira.examples.concepts import exposed, infected\n# Infection\ninfection = NaturalConversion(\nsubject=exposed,\noutcome=infected,```",
"description": "This example demonstrates the definition of an 'infection' process as a natural conversion in which an 'exposed' entity becomes 'infected'. It showcases the use of a natural conversion within the SEIRD modeling framework."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/mech_bayes.py",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import NaturalConversion\nfrom mira.examples.concepts import infected, recovered\n# recovery\nrecovery = NaturalConversion(\nsubject=infected,\noutcome=recovered,```",
"description": "This section illustrates the modeling of recovery from infection as a natural conversion process within the SEIRD framework, transforming an 'infected' entity into a 'recovered' one."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/mech_bayes.py",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import NaturalConversion, Concept\nfrom mira.examples.concepts import infected, dead\n# dying - in the paper they have the D1 and D2, where D1 is a patient that\n# will eventually die, and D2 is the actual death stage.\n# uberon:0000071 = \"death stage\"\ndying = Concept(\nname=\"death stage\",\nidentifiers={\"uberon\": \"0000071\"},\ncontext={\"description\": \"End of the life of an organism.\"}\n)\n# I -> D1\ndying_process = NaturalConversion(\nsubject=infected,\noutcome=dying,\n)\n# D1 -> D2\ndying_to_death = NaturalConversion(\nsubject=dying,\noutcome=dead,```",
"description": "This section details the development of a complex death process within the SEIRD model, capturing the transition from being 'infected' to a 'death stage' concept, and finally to being 'dead'. It introduces the concept of 'dying' as an intermediate state."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/mech_bayes.py",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import TemplateModel\nfrom mira.examples.concepts import susceptible, exposed, infected, recovered, dead\n\n# Ensure all the previous conversion and concept definitions (exposure, infection, recovery, dying, dying_process, dying_to_death) are included here to complete the example.\nseird = TemplateModel(\ntemplates=[\nexposure,\ninfection,\nrecovery,\ndying_process,\ndying_to_death,\n],```",
"description": "Illustrates how to assemble various model components defined earlier (exposure, infection, recovery, dying process, and dying to death processes) into a complete SEIRD template model named 'seird' by utilizing the TemplateModel."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/sir.py",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import ControlledConversion, NaturalConversion, TemplateModel\nfrom .concepts import susceptible, infected, recovered\n# SIR Model\ninfection = ControlledConversion(\nsubject=susceptible,\noutcome=infected,\ncontroller=infected,\n)\nrecovery = NaturalConversion(\nsubject=infected,\noutcome=recovered,\n)\nsir = TemplateModel(\ntemplates=[\ninfection,\nrecovery,\n],```",
"description": "Defines a basic SIR model without parameters, showcasing the setup of an infectious disease model where susceptible individuals can get infected and then either recover or progress to a different state."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/sir.py",
"origination_method": "extract_from_library_automatic",
"code": "```from copy import deepcopy as _d\nimport sympy\nfrom mira.metamodel import ControlledConversion, NaturalConversion, TemplateModel, Initial, Parameter, safe_parse_expr, Unit\nfrom .concepts import susceptible, infected, recovered\nsir_parameterized = TemplateModel(\ntemplates=[\nControlledConversion(\nsubject=_d(susceptible),\noutcome=_d(infected),\ncontroller=_d(infected),\nrate_law=safe_parse_expr(\n'beta * susceptible_population * infected_population',\nlocal_dict={'beta': sympy.Symbol('beta')}\n)\n),\nNaturalConversion(\nsubject=_d(infected),\noutcome=_d(recovered),\nrate_law=safe_parse_expr(\n'gamma * infected_population',\nlocal_dict={'gamma': sympy.Symbol('gamma')}\n)\n)\n],\nparameters={\n'beta': Parameter(name='beta', value=0.1),\n'gamma': Parameter(name='gamma', value=0.2)\n},\ninitials={\n'susceptible_population': Initial(concept=_d(susceptible), expression=sympy.Integer('1')),\n'infected_population': Initial(concept=_d(infected), expression=sympy.Integer('2')),\n'immune_population': Initial(concept=_d(recovered), expression=sympy.Integer('3')),\n}```",
"description": "Illustrates a parameterized SIR model, extending the basic SIR model to include transmission and recovery rates ('beta' and 'gamma'). Also demonstrates how to define initial conditions for the population."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/sir.py",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import NaturalConversion, TemplateModel\nfrom .concepts import susceptible, infected, recovered\n# SIR 2 City Model\ncities = [\n\"geonames:5128581\", # NYC\n\"geonames:4930956\", # boston\n]\nsusceptible_nyc, susceptible_boston = (susceptible.with_context(city=city) for city in cities)\ninfected_nyc, infected_boston = (infected.with_context(city=city) for city in cities)\nrecovered_nyc, recovered_boston = (recovered.with_context(city=city) for city in cities)\ninfection_nyc, infection_boston = (infection.with_context(city=city) for city in cities)\nrecovery_nyc, recovery_boston = (recovery.with_context(city=city) for city in cities)\nsusceptible_nyc_to_boston = NaturalConversion(subject=susceptible_nyc, outcome=susceptible_boston)\nsusceptible_boston_to_nyc = NaturalConversion(subject=susceptible_boston, outcome=susceptible_nyc)\ninfected_nyc_to_boston = NaturalConversion(subject=infected_nyc, outcome=infected_boston)\ninfected_boston_to_nyc = NaturalConversion(subject=infected_boston, outcome=infected_nyc)\nrecovered_nyc_to_boston = NaturalConversion(subject=recovered_nyc, outcome=recovered_boston)\nrecovered_boston_to_nyc = NaturalConversion(subject=recovered_boston, outcome=recovered_nyc)\nsir_2_city = TemplateModel(\ntemplates=[\ninfection_nyc,\ninfection_boston,\nrecovery_nyc,\nrecovery_boston,\nsusceptible_nyc_to_boston,\nsusceptible_boston_to_nyc,\ninfected_nyc_to_boston,\ninfected_boston_to_nyc,\nrecovered_nyc_to_boston,\nrecovered_boston_to_nyc,\n],```",
"description": "Describes an SIR model for two cities, incorporating movement between the cities. It assumes that individuals can change their city of residence, thereby affecting the local epidemic dynamics."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/sir.py",
"origination_method": "extract_from_library_automatic",
"code": "```\nsir_bilayer = \\\n{\"Wa\": [{\"influx\": 1, \"infusion\": 2},\n{\"influx\": 2, \"infusion\": 3}],\n\"Win\": [{\"arg\": 1, \"call\": 1},\n{\"arg\": 2, \"call\": 1},\n{\"arg\": 2, \"call\": 2}],\n\"Box\": [{\"parameter\": \"beta\"},\n{\"parameter\": \"gamma\"}],\n\"Qin\": [{\"variable\": \"S\"},\n{\"variable\": \"I\"},\n{\"variable\": \"R\"}],\n\"Qout\": [{\"tanvar\": \"S'\"},\n{\"tanvar\": \"I'\"},\n{\"tanvar\": \"R'\"}],\n\"Wn\": [{\"efflux\": 1, \"effusion\": 1},```",
"description": "Presents a bilayer network model structure for an SIR model, represented in a dictionary format that outlines various network properties and parameters, but not directly executable in mira without additional context."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/sir.py",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import GroupedControlledConversion, NaturalConversion, TemplateModel\nfrom .concepts import susceptible, infected_symptomatic, infected_asymptomatic, recovered\ninfection_symptomatic = GroupedControlledConversion(\nsubject=susceptible,\noutcome=infected_symptomatic,\ncontrollers=[infected_symptomatic, infected_asymptomatic],\n)\ninfection_asymptomatic = GroupedControlledConversion(\nsubject=susceptible,\noutcome=infected_asymptomatic,\ncontrollers=[infected_symptomatic, infected_asymptomatic],\n)\nrecovery = NaturalConversion(\nsubject=infected,\noutcome=recovered,\n)\nsvir = TemplateModel(\ntemplates=[\ninfection_symptomatic,\ninfection_asymptomatic,\n],```",
"description": "Defines a model for susceptible individuals becoming either symptomatically or asymptomatically infected, showcasing the use of GroupedControlledConversion to model multiple infection pathways."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/sir.py",
"origination_method": "extract_from_library_automatic",
"code": "```from copy import deepcopy as _d\nimport sympy\nfrom mira.metamodel import TemplateModel, Initial, Parameter, Unit, SympyExprStr\nfrom .concepts import susceptible, infected, recovered\nsir_parameterized = <Insert the sir_parameterized definition from lines 38-67 here>\n# SIR Parameterized Model with initial values and units, used as example in\n# docs and tests\nsir_parameterized_init = _d(sir_parameterized)\nsir_init_val_norm = 1e5\nfor template in sir_parameterized_init.templates:\nfor concept in template.get_concepts():\nconcept.units = Unit(expression=sympy.Symbol('person'))\nsir_parameterized_init.initials['susceptible_population'].expression = SympyExprStr(sympy.Float(sir_init_val_norm-1))\nsir_parameterized_init.initials['infected_population'].expression = SympyExprStr(sympy.Integer('1'))\nsir_parameterized_init.initials['immune_population'].expression = SympyExprStr(sympy.Integer('0'))\n\nsir_parameterized_init.parameters['beta'].units = \\\nUnit(expression=1 / (sympy.Symbol('person') * sympy.Symbol('day')))\nold_beta = sir_parameterized_init.parameters['beta'].value\n\nfor initial in sir_parameterized_init.initials.values():```",
"description": "Shows how to set up a parameterized SIR model with initial values and units. It further extends the parameterized example to normalize initial values and set units for model entities."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/ASKEM MIRA demo.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\n# ## Ingesting structured models with MIRA\n# The BioModels database contains 26 published COVID-19 models. Each of these models is available in a structured format: SBML. MIRA implements a client to BioModels and a processor to reverse-engineer SBML models into MIRA templates.\n\n# In[1]:\n\n\nget_ipython().run_cell_magic('html', '', '<iframe src=\"https://www.ebi.ac.uk/biomodels/search?query=submitter_keywords:COVID-19&domain=biomodels\" width=\"950\" height=\"600\"></iframe>\\n')\n\n\n# Input formats supported\n# - Models can be directly represented via template objects: https://miramodel.readthedocs.io/en/latest/metamodel.html\n# - Bilayer: https://miramodel.readthedocs.io/en/latest/sources.html#module-mira.sources.bilayer\n# - SBML: https://miramodel.readthedocs.io/en/latest/sources.html#module-mira.sources.sbml```",
"description": "Ingesting structured models with MIRA and viewing COVID-19 models from BioModels database."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/ASKEM MIRA demo.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\n\nfrom mira.sources.biomodels import get_template_model\nfrom mira.sources.sbml import template_model_from_sbml_file_path\n# ## Representing models using ontology-grounded meta-model templates\n# Let's get a specific model from BioModels as an example. This is a simple SIR model which is reverse-engineered into a ControlledConversion and NaturalConversion template.\n\n# In[2]:\n\n\nfrom mira.sources.biomodels import get_template_model\nfrom mira.sources.sbml import template_model_from_sbml_file_path\n\n# Uncomment this to allow local fallback\n# def local_get_template_model(model_id):\n# return template_model_from_sbml_file_path(\n# f'~/.data/mira/biomodels/{model_id}/{model_id}.xml').template_model\n# get_template_model = local_get_template_model\n\ntemplate_model = get_template_model('BIOMD0000000956')\n\n\n# Each template refers to a set of Concepts as arguments (the role of these Concepts is also well defined semantically) and. These Concepts also carry identifiers and context, grounded in namespaces and identifiers consistent with the MIRA DKG.\n\n# In[3]:\n\n\nfor template in template_model.templates:\nprint(template.type)\nfor key, value in template.get_concepts_by_role().items():\nprint(' %s - Concept(%s)' % (key, value))```",
"description": "Representing models using ontology-grounded meta-model templates and displaying model concepts."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/ASKEM MIRA demo.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\n\nfrom mira.sources.biomodels import get_template_model\nfrom mira.modeling import Model\nfrom mira.modeling.viz import GraphicalModel\nfrom IPython.display import Image, display, HTML\n# ## Representing rate laws and parameters\n\n# In[4]:\n\n\nfrom IPython.display import Image, display, HTML\nfrom mira.modeling import Model\nfrom mira.modeling.viz import GraphicalModel\n\ntemplate_model = get_template_model('BIOMD0000000955')\nGraphicalModel(Model(template_model)).write('model.png')\nImage('model.png', width='50%')\n\n\n# Let's now look at some rate laws from the model and list the corresponding parameters.\n\n# In[5]:\n\n\nfor template in template_model.templates:\nprint(template.rate_law)\n\n\n# In[6]:\n\n\nlist(template_model.parameters.items())[:15]```",
"description": "Representing rate laws and parameters after visualizing models as graphical entities."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/ASKEM MIRA demo.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\n\nfrom mira.sources.biomodels import get_template_model\nfrom mira.modeling import Model\nfrom mira.modeling.viz import GraphicalModel\nfrom IPython.display import HTML\n# ## Comparing models at the template level with ontology guidance\n# We get a set of BioModels models as examples for interesting comparisons.\n\n# In[7]:\n\n\nmodels = {\nmid: get_template_model(f'BIOMD0000000{mid}')\nfor mid in ['957', '963', '970', '984', '991']\n}\n\n\n# In[8]:\n\n\nviz = {'970', '991'}\nfor mid in viz:\ngm = GraphicalModel(Model(models[mid]))\ngm.write(f'{mid}.png', args=f'-Glabel=BIOMD0000000{mid}')\nHTML('<div class=\"row\">' + '\\n'.join([f'<img src={mid}.png style=\"width:40%;float:left\"> </img>'```",
"description": "Comparing models at the template level with ontology guidance and visualizing them."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/ASKEM MIRA demo.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\n\nfrom mira.sources.biomodels import get_template_model\nfrom mira.modeling import Model\nfrom mira.metamodel import TemplateModelDelta, get_dkg_refinement_closure\nfrom mira.dkg.web_client import is_ontological_child_web\nfrom IPython.display import Image\n# Let's now get our model comparison code ready and use MIRA's template model comparison algorithm to create a model comparison graph. We can also visualize this graph.\n#\n# The comparison algorithm uses the MIRA DKG's structure.\n\n# In[9]:\n\n\nfrom mira.metamodel import TemplateModelDelta, get_dkg_refinement_closure\nfrom mira.dkg.web_client import is_ontological_child_web\nrefinement_fun = get_dkg_refinement_closure().is_ontological_child\n\n\n# In[10]:\n\n\ntd = TemplateModelDelta(models['957'], models['963'], refinement_fun)\ntd.draw_graph('comparison3.png', args='-Grankdir=TB')\nImage('comparison3.png')\n\n\n# Next we compare two models where there are interesting node-level refinements.\n\n# In[11]:\n\n\ntd = TemplateModelDelta(models['970'], models['991'], refinement_fun)\ntd.draw_graph('comparison1.png', args='-Grankdir=TB')\nImage('comparison1.png')\n\n\n# In this example, we see that there are template-level relationships between two NaturalConversions in the two models.\n\n# In[12]:\n\n\ntd = TemplateModelDelta(models['984'], models['991'], refinement_fun)\ntd.draw_graph('comparison2.png', args='-Grankdir=TB')```",
"description": "Creating a model comparison graph with MIRA's template model comparison algorithm and visualizing the graph."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/ASKEM MIRA demo.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\n\nfrom mira.modeling.petri import PetriNetModel\nfrom mira.modeling import Model\nfrom mira.sources.biomodels import get_template_model\n# ## Generating model exchange formats from MIRA\n# Currently surpported\n# - Petri nets: https://miramodel.readthedocs.io/en/latest/modeling.html#module-mira.modeling.petri\n# - Bilayers: https://miramodel.readthedocs.io/en/latest/modeling.html#module-mira.modeling.bilayer\n# - ODEs: https://miramodel.readthedocs.io/en/latest/modeling.html#module-mira.modeling.ode\n\n# In[13]:\n\n\nfrom mira.modeling.petri import PetriNetModel\npm = PetriNetModel(Model(models['991']))```",
"description": "Generating model exchange formats from MIRA, specifically showing Petri net conversion."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/ASKEM MIRA demo.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\n# ## Deployment and integration\n# MIRA is available at: https://github.com/indralab/mira, and can be used as\n# - A Python library, documented at https://miramodel.readthedocs.io/\n# - A local, dockerized REST API: https://github.com/indralab/mira/tree/main/docker#readme\n# - A public REST API: http://34.230.33.149:8771/\n\n# In[14]:\n\n```",
"description": "Demonstrating deployment and integration options for MIRA, highlighting its availability as a Python library, and access via local and public REST APIs."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/jin2022.py",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import NaturalConversion, ControlledConversion, TemplateModel\nfrom .concepts import susceptible, infected, recovered, exposed\nexposure = ControlledConversion(\nsubject=susceptible,\noutcome=exposed,\ncontroller=infected,\n)\ninfection = NaturalConversion(\nsubject=exposed,\noutcome=infected,\n)\nrecovery = NaturalConversion(\nsubject=infected,\noutcome=recovered,\n)\n\nseir = TemplateModel(\ntemplates=[\nexposure,\ninfection,\nrecovery,\n],```",
"description": "This example demonstrates how to define a simple SEIR (Susceptible, Exposed, Infected, Recovered) model using the mira library. It showcases the creation of natural and controlled conversions between different states in a disease model, including transitions from susceptible to exposed, exposed to infected, and infected to recovered."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/jin2022.py",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import ControlledConversion, NaturalConversion, TemplateModel\nfrom .concepts import susceptible, infected, recovered, exposed, dead\n\nexposure = ControlledConversion(subject=susceptible, outcome=exposed, controller=infected)\ninfection = NaturalConversion(subject=exposed, outcome=infected)\nrecovery = NaturalConversion(subject=infected, outcome=recovered)\n# fix control structure so when you stratify a controller,\n# all of the resulting strata become multiple controllers\ntemplates = []\nfor template in (infection, recovery):\ntemplates.extend(\n(\ntemplate.with_context(vaccination_status=\"vaccinated\"),\ntemplate.with_context(vaccination_status=\"unvaccinated\"),\n)\n)\n\ntemplates.extend(\n(\nexposure.with_context(vaccination_status=\"vaccinated\").add_controller(\ninfected.with_context(vaccination_status=\"unvaccinated\")\n),\nexposure.with_context(vaccination_status=\"unvaccinated\").add_controller(\ninfected.with_context(vaccination_status=\"vaccinated\")\n),\n)```",
"description": "This section expands upon the SEIR model to stratify the template based on vaccination status. It demonstrates how to modify existing templates to include contextual information (such as vaccination status) and shows how to add multiple controllers for stratified versions of exposure by vaccination status."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/jin2022.py",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import NaturalConversion, TemplateModel\nfrom .concepts import infected, dead\n\nexposure = ControlledConversion(subject=susceptible, outcome=exposed, controller=infected)\ninfection = NaturalConversion(subject=exposed, outcome=infected)\nrecovery = NaturalConversion(subject=infected, outcome=recovered)\ntemplates = [exposure, infection, recovery]\ntemplates.extend(exposure.with_context(vaccination_status=\"vaccinated\").add_controller(infected.with_context(vaccination_status=\"unvaccinated\")), exposure.with_context(vaccination_status=\"unvaccinated\").add_controller(infected.with_context(vaccination_status=\"vaccinated\")))\nfor vaccination_status in [\"vaccinated\", \"unvaccinated\"]:\nsubject = infected.with_context(vaccination_status=vaccination_status)\ntemplates.append(NaturalConversion(subject=subject, outcome=dead))\n```",
"description": "This example further stratifies the SEIR model by adding a mortality outcome for both vaccinated and unvaccinated infected individuals, showcasing the flexibility of the mira library in incorporating additional complexities into disease models."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/jin2022.py",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.modeling.viz import GraphicalModel\nfrom pathlib import Path\nfrom mira.metamodel import TemplateModel\nfrom .concepts import susceptible, infected, recovered, exposed, dead\n\nseird_stratified = TemplateModel(templates=...)\n# Ensure all previous code forming `seird_stratified` is included here.\ndef _main():\nfrom mira.modeling.viz import GraphicalModel\nfrom pathlib import Path\n\ngm = GraphicalModel.from_template_model(seird_stratified)\ngm.write(Path.home().joinpath(\"Desktop\", \"seird_stratified.png\"))\n\n\nif __name__ == \"__main__\":```",
"description": "This final example section illustrates how to visualize the stratified SEIR model defined in previous sections. It demonstrates the use of the mira library for generating a graphical representation of the model and exporting it as a png file."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/biomodels.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.sources.biomodels import get_sbml_model\n# ## Downloading a model from BioModels\n\n# First, we import the BioModel source of MIRA and use a function that returns a BioModel model's SBML XML as a string based on the model's ID, from the web.\n\n# In[1]:\n\n\nfrom mira.sources.biomodels import get_sbml_model\n\nsbml = get_sbml_model('BIOMD0000000955')```",
"description": "Downloading an SBML model from BioModels using the mira library. This example demonstrates how to import the necessary module and retrieve an SBML model as a string."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/biomodels.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.sources.biomodels import get_sbml_model\nfrom mira.sources.sbml import template_model_from_sbml_string\nsbml = get_sbml_model('BIOMD0000000955')\n# We now import the SBML source module of MIRA which provides several functions to turn SBML models into MIRA TemplateModels.\n\n# ## Extracting MIRA Meta-model Templates from SBML\n\n# In[5]:\n\n\nfrom mira.sources.sbml import template_model_from_sbml_string\n\n\n# In[6]:\n\n\ntemplate_model = template_model_from_sbml_string(sbml)\n\n\n# Let's see what kinds of templates we got by processing this SBML model.\n\n# In[7]:\n\n\nfor idx, template in enumerate(template_model.templates):\nprint(template.__class__.__name__)```",
"description": "Extracting MIRA Meta-model Templates from an SBML model. This part illustrates importing the module for processing SBML strings and generating template models from the SBML, then iterating through the templates to display information about them."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/biomodels.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.sources.biomodels import get_sbml_model\nfrom mira.sources.sbml import template_model_from_sbml_string\nfrom mira.modeling import Model\nfrom mira.modeling.viz import GraphicalModel\nfrom IPython.display import Image\nsbml = get_sbml_model('BIOMD0000000955')\ntemplate_model = template_model_from_sbml_string(sbml)\ntransition_model = Model(template_model)\n# ## Visualizing the transition structure of the model\n# We now generate a transition model from the template model. This is the basis for visualizing the \"wiring diagram\" of the model and generating further model types like Petri nets and ODEs.\n\n# In[8]:\n\n\nfrom mira.modeling import Model\ntransition_model = Model(template_model)\n\n\n# In[9]:\n\n\nfrom mira.modeling.viz import GraphicalModel\ngraphical_model = GraphicalModel(transition_model)\ngraphical_model.write('simple.png')\nfrom IPython.display import Image```",
"description": "Visualizing the transition structure of a model by generating a transition model from template models, and creating a graphical representation that is saved as an image. This section also includes displaying the generated image."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/biomodels.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.sources.biomodels import get_sbml_model\nfrom mira.sources.sbml import template_model_from_sbml_string\nfrom mira.modeling import Model\nfrom mira.modeling.petri import PetriNetModel\nsbml = get_sbml_model('BIOMD0000000955')\ntemplate_model = template_model_from_sbml_string(sbml)\ntransition_model = Model(template_model)\n# ## Generating the model into a Petri net\n# We can now take the model and generate it into a Petri net model and serialize it into JSON.\n\n# In[10]:\n\n\nfrom mira.modeling.petri import PetriNetModel\npetri_model = PetriNetModel(transition_model)```",
"description": "Generating a Petri net model from the transition model and serializing the Petri net model into JSON. This demonstrates creating a Petri net from previously built models and converting it to a JSON representation."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/biomodels.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.sources.biomodels import get_sbml_model\nfrom mira.sources.sbml import template_model_from_sbml_string\nfrom mira.modeling import Model\nfrom mira.modeling.viz import GraphicalModel\nfrom mira.metamodel.ops import stratify\nfrom IPython.display import Image\nsbml = get_sbml_model('BIOMD0000000955')\ntemplate_model = template_model_from_sbml_string(sbml)\n# ## Modifying the model within MIRA\n# Let's not perform a modeling operation, for instance, by stratifying the populations into two cities between which individuals can travel. We use the `mira.modeling.ops.stratify` function to create a stratified `TemplateModel`, then assemble it into a transition Model, and visualize the model's wiring diagram.\n\n# In[11]:\n\n\nfrom mira.metamodel.ops import stratify\n\n\n# In[12]:\n\n\ntemplate_model2 = stratify(template_model, key='city',\nstrata=[\"geonames:5128581\", # NYC\n\"geonames:4930956\", # Boston\n]\n)\n\n\n# In[13]:\n\n\ntransition_model2 = Model(template_model2)\ngraphical_model2 = GraphicalModel(transition_model2)\ngraphical_model2.write('stratified.png')\nfrom IPython.display import Image```",
"description": "Modifying the model within MIRA by stratifying the populations and visualizing the modified model. This example showcases using the stratify function to segment the population based on specified strata and generating a graphical model to visualize the changes."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/Hackathon Scenario 3.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\n\nfrom IPython.display import Image\nfrom mira.examples.mech_bayes import seird\n# # The initial MechBayes SEIRD model\n#\n# *NOTE: Does not contain rate laws currently.*\n\n# In[7]:\n\n\nfrom IPython.display import Image\nfrom mira.examples.mech_bayes import seird\nlen(seird.templates)\n\n\n# In[8]:\n\n\nseird.draw_graph('mech_bayes_seird.png')```",
"description": "This example demonstrates the creation of a basic SEIRD model using the Mirabai library. It first imports necessary modules and the `seird` template from the MechBayes example, then prints the number of templates in the SEIRD model and finally draws a graph representation of it."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/Hackathon Scenario 3.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\n\nfrom mira.examples.mech_bayes import seird\nfrom IPython.display import Image\nfrom mira.examples.mech_bayes import dying\nfrom mira.metamodel import NaturalConversion, TemplateModel\nfrom mira.examples.concepts import infected, recovered\n# ## Add hospitalization\n\n# In[9]:\n\n\nfrom mira.examples.mech_bayes import dying\nfrom mira.metamodel import NaturalConversion, TemplateModel\nfrom mira.examples.concepts import infected, recovered\n\n# Add a NaturalConversion: infected -> hospitalized; NaturalConversion: hospitalized -> recovered; NaturalConversion: hospitalized -> dying;\n# ncit:C25179 = Hospitalization\nhospitalized = infected.with_context(status=\"ncit:C25179\")\nhospitalization = NaturalConversion(subject=infected, outcome=hospitalized)\nrecovery_from_hospitalization = NaturalConversion(subject=hospitalized, outcome=recovered)\ndying_from_hospitalization = NaturalConversion(subject=hospitalized, outcome=dying)\nhospitalization_mmt = TemplateModel(templates=[hospitalization, recovery_from_hospitalization, dying_from_hospitalization])\nseirhd = seird.extend(template_model=hospitalization_mmt)\n\nseirhd.draw_graph('seihrd.png')```",
"description": "This example showcases how to extend the basic SEIRD model to include hospitalization states, demonstrating additions of natural conversions for infected to hospitalized, hospitalized to recovered, and hospitalized to dying. A TemplateModel is built for hospitalization mechanisms and integrated into the SEIRD model to generate and visualize the SEIHRD model."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/Hackathon Scenario 3.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\n\nfrom IPython.display import Image\nfrom mira.metamodel import ControlledConversion, TemplateModel\nfrom mira.examples.mech_bayes import susceptible, infected, recovery, dying_to_death, dying_process\nfrom mira.examples.mech_bayes import seird\nfrom mira.examples.mech_bayes import dying\nfrom mira.metamodel import NaturalConversion\nfrom mira.examples.concepts import infected, recovered\nhospitalized = infected.with_context(status=\"ncit:C25179\")\nhospitalization = NaturalConversion(subject=infected, outcome=hospitalized)\nrecovery_from_hospitalization = NaturalConversion(subject=hospitalized, outcome=recovered)\ndying_from_hospitalization = NaturalConversion(subject=hospitalized, outcome=dying)\n# ## Remove the exposed\n# Just make a new template model since there is no delete method yet\n\n# In[11]:\n\n\nfrom mira.metamodel import ControlledConversion\nfrom mira.examples.mech_bayes import susceptible, infected, recovery, dying_to_death, dying_process\n\nsusceptible_to_infected = ControlledConversion(subject=susceptible, controller=infected, outcome=infected)\nsirhd = TemplateModel(\ntemplates=[\nsusceptible_to_infected, # S->I\nrecovery, # I->R\nhospitalization, # I->H\nrecovery_from_hospitalization, # H->R\ndying_from_hospitalization, # H->D1\ndying_process, # I->D1\ndying_to_death # D1->D2\n]\n)\nsirhd.draw_graph('sirhd.png')```",
"description": "This example illustrates adjusting the SEIHRD model by removing the exposed class to simplify it into an SIRHD model. It demonstrates defining controlled and natural conversions among susceptible, infected, hospitalized, and different dying states before creating a new template model and visualizing the simplified model."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/regnets.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.sources.amr.regnet import *\n# ### Load the example LV model from the shared representation into MIRA and display the TemplateModel\n#\n# We load the canonical Lotka-Volterra model from the Model-Representations repo into a MIRA Template Model.\n\n# In[1]:\n\n\nfrom mira.sources.amr.regnet import *\n\n\n# In[2]:\n\n\ntm = model_from_url('https://raw.githubusercontent.com/DARPA-ASKEM/Model-Representations/'\n'main/regnet/examples/lotka_volterra.json')\n\n\n# In[3]:\n\n```",
"description": "Loading the canonical Lotka-Volterra model into a MIRA Template Model and displaying it."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/regnets.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.sources.amr.regnet import *\nmodel_from_url('https://raw.githubusercontent.com/DARPA-ASKEM/Model-Representations/main/regnet/examples/lotka_volterra.json')\n# Here is an example rate law from the model:\n\n# In[4]:\n\n```",
"description": "Displaying an example rate law from the loaded Lotka-Volterra model."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/regnets.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.sources.amr.regnet import *\nfrom mira.modeling import Model\nfrom mira.modeling.amr.regnet import AMRRegNetModel\nmodel_from_url('https://raw.githubusercontent.com/DARPA-ASKEM/Model-Representations/main/regnet/examples/lotka_volterra.json')\n# ### Export the MIRA TemplateModel into the shared representation\n#\n# Here we show that we can export the model back into a valid regnet AMR.\n\n# In[5]:\n\n\nfrom mira.modeling import Model\nfrom mira.modeling.amr.regnet import AMRRegNetModel\n\n\n# In[6]:\n\n\nrm = AMRRegNetModel(Model(tm))\n\n\n# In[7]:\n\n```",
"description": "Exporting the MIRA TemplateModel back into a valid regnet AMR format."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/regnets.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.sources.amr.regnet import *\nfrom mira.modeling import Model\nfrom mira.modeling.amr.petrinet import AMRPetriNetModel\nmodel_from_url('https://raw.githubusercontent.com/DARPA-ASKEM/Model-Representations/main/regnet/examples/lotka_volterra.json')\n# ### Export the same underlying MIRA TemplateModel into a PetriNet representation\n#\n# This model is also compatible with a Petri net representation so we show that we can export it into a Petri net AMR.\n\n# In[8]:\n\n\nfrom mira.modeling.amr.petrinet import AMRPetriNetModel\n\n\n# In[9]:\n\n\npm = AMRPetriNetModel(Model(tm))```",
"description": "Exporting the MIRA TemplateModel into a PetriNet representation."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/regnets.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.sources.amr.regnet import *\nfrom mira.metamodel.ops import stratify\nfrom mira.modeling import Model\nfrom mira.modeling.amr.regnet import AMRRegNetModel\nmodel_from_url('https://raw.githubusercontent.com/DARPA-ASKEM/Model-Representations/main/regnet/examples/lotka_volterra.json')\n# ### Stratify the model into two subspecies of wolves\n#\n# We model a stratification where we split the population of wolves into two subspecies. There is no transition between the two subspecies (that wouldn't fit into the regnet framework), so e.g., we would be limited if we wanted to introduce multiple locations between which animals migrate.\n\n# In[10]:\n\n\nfrom mira.metamodel.ops import stratify\n\n\n# In[11]:\n\n\ntm2 = stratify(tm, key='subspecies', concepts_to_stratify=['Wolves'], strata=['brown', 'gray'], structure=[])\n\n\n# In[12]:\n\n\ntm2.draw_jupyter()\n\n\n# In[13]:\n\n```",
"description": "Stratifying the model to distinguish between two subspecies of wolves and representing the modified model."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/applications/Bevacizumab_pharmacokinetics.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\nimport matplotlib.pyplot as plt\nimport sympy\nimport numpy\nfrom mira.metamodel import *\n\nimport matplotlib.pyplot as plt\nimport sympy\nimport numpy\nfrom mira.metamodel import *\nfrom mira.modeling import Model\nfrom mira.modeling.amr.petrinet import AMRPetriNetModel\nfrom mira.modeling.ode import OdeModel, simulate_ode_model\n\n\n# In[18]:\n\n\nc = {\n'As_iv': Concept(name='As_iv'),\n'At_iv': Concept(name='At_iv'),\n'As_sc': Concept(name='As_sc'),\n'At_sc': Concept(name='At_sc'),\n'ALN_sc': Concept(name='ALN_sc'),\n'A_sc': Concept(name='A_sc')\n}\n\nAs_iv, At_iv, As_sc, At_sc, ALN_sc, A_sc = sympy.symbols('As_iv At_iv As_sc At_sc ALN_sc A_sc')```",
"description": "Defining concepts and symbols for a pharmacokinetic model. This example introduces the setup for a model including concepts like drug concentration in various compartments and pharmacokinetic parameters."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/applications/Bevacizumab_pharmacokinetics.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\nimport sympy\nfrom mira.metamodel import *\nfrom mira.modeling import Model\nc = {\n'As_iv': Concept(name='As_iv'),\n'At_iv': Concept(name='At_iv'),\n'As_sc': Concept(name='As_sc'),\n'At_sc': Concept(name='At_sc'),\n'ALN_sc': Concept(name='ALN_sc'),\n'A_sc': Concept(name='A_sc')\n}\nAs_iv, At_iv, As_sc, At_sc, ALN_sc, A_sc = sympy.symbols('As_iv At_iv As_sc At_sc ALN_sc A_sc')\n\nparameters = {\n'ka1': Parameter(name='ka1', value=None),\n'ka2': Parameter(name='ka2', value=None),\n'k10': Parameter(name='k10', value=None),\n'k12': Parameter(name='k12', value=None),\n'k21': Parameter(name='k21', value=None),\n'Frc': Parameter(name='Frc', value=None),\n'BIO': Parameter(name='BIO', value=None),\n}\n\n\ntemplates = [\n# IV dose to plasma/tissue\nNaturalConversion(subject=c['As_iv'], outcome=c['At_iv'], rate_law=As_iv*k12),\nNaturalConversion(subject=c['At_iv'], outcome=c['As_iv'], rate_law=At_iv*k21),\nNaturalDegradation(subject=c['As_iv'], rate_law=As_iv*k10),\n\n# SC dose to plasma/tissue\nNaturalConversion(subject=c['As_sc'], outcome=c['At_sc'], rate_law=As_sc*k12),\nNaturalConversion(subject=c['At_sc'], outcome=c['As_sc'], rate_law=At_sc*k21),\nNaturalDegradation(subject=c['As_sc'], rate_law=As_sc*k10),\n\n# SC dose to plasma/lymph nodes\nNaturalConversion(subject=c['ALN_sc'], outcome=c['As_sc'], rate_law=ALN_sc*ka2),\nNaturalConversion(subject=c['A_sc'], outcome=c['As_sc'], rate_law=BIO*(1-Frc)*ka1*A_sc),\nNaturalConversion(subject=c['A_sc'], outcome=c['ALN_sc'], rate_law=BIO*Frc*ka1*A_sc),```",
"description": "Setting up parameters and template reactions for the pharmacokinetic model. This includes defining parameters for the model like rate constants and bioavailability, as well as specifying transformations and degradations of the drug in the system."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/applications/Bevacizumab_pharmacokinetics.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\nimport sympy\nfrom mira.metamodel import *\nfrom mira.modeling import Model, TemplateModel\n\nobservables = {\n'A_t': Observable(name='At', expression=At_iv + At_sc),\n'A_s': Observable(name='As', expression=As_iv + As_sc),\n}\n\n\n# In[21]:\n\n\ntm = TemplateModel(\ntemplates=templates,\nparameters=parameters,\n)```",
"description": "Defining observables and creating a template model. This section goes over how to aggregate certain variables into observables that can be tracked over time, and how all the previously defined templates and parameters are used to create a template model."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/applications/Bevacizumab_pharmacokinetics.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\nimport numpy\nfrom mira.modeling import Model\nfrom mira.modeling.ode import OdeModel, simulate_ode_model\nmodel = Model(tm)\n\nmodel = Model(tm)\n\n\n# In[69]:\n\n\nom = OdeModel(model, initialized=False)\ninitial_test = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]\n\nparams_test = {'k12': 1.0, 'k21': 1.0, 'k10': 1.0, 'ka2': 1.0, 'BIO': 1.0, 'Frc': 1.0,\n'ka1': 1.0}\n```",
"description": "Initializing an ODE model with a test setup. This includes creating the ODE model from the template model, specifying initial values for the concentrations, and defining parameters for the simulation."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/applications/Bevacizumab_pharmacokinetics.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\nimport matplotlib.pyplot as plt\nimport numpy\nfrom mira.modeling.ode import simulate_ode_model\nom = OdeModel(model, initialized=False)\ninitial_test = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]\nparams_test = {'k12': 1.0, 'k21': 1.0, 'k10': 1.0, 'ka2': 1.0, 'BIO': 1.0, 'Frc': 1.0,\n'ka1': 1.0}\ntimes_test = numpy.linspace(0, 25, 100)\n\nres = simulate_ode_model(ode_model=om,\ninitials=initial_test,\nparameters=params_test,\ntimes=times_test)\n\n\n# In[82]:\n\n\nvariable_list = list(om.vmap.keys())\n\n\n# In[83]:\n\n\nplt.legend(handles = plt.plot(times_test,res), labels=variable_list,loc = 'upper left', bbox_to_anchor=(1,1))\nplt.xlabel('Time')\nplt.ylabel('Activation')```",
"description": "Simulating the ODE model and plotting the results. It showcases how to run a simulation using the earlier defined ODE model and parameters, then plot the resulting concentrations over time."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/chime.py",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import NaturalConversion, ControlledConversion, \\nTemplateModel\\nfrom .concepts import susceptible, infected, recovered\nfrom mira.metamodel import NaturalConversion, ControlledConversion, \\\nTemplateModel\nfrom .concepts import susceptible, infected, recovered\n\ninfection = ControlledConversion(\nsubject=susceptible,\noutcome=infected,\ncontroller=infected,```",
"description": "This example demonstrates how to create a controlled conversion in the CHIME SVIIvR epidemiological model. It specifically sets up an infection process where a susceptible individual becomes infected through interaction with an infected individual."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/chime.py",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import ControlledConversion\\nfrom .concepts import infected\\n\ninfection = ControlledConversion(\\n subject=susceptible,\\n outcome=infected,\\n controller=infected,\\n)\\n\ntemplates = []\ntemplates = []\ntemplates.append(\ninfection.with_context(vaccination_status=\"vaccinated\").add_controller(\ninfected.with_context(vaccination_status=\"unvaccinated\")\n)\n)\ntemplates.append(\ninfection.with_context(vaccination_status=\"unvaccinated\").add_controller(\ninfected.with_context(vaccination_status=\"vaccinated\")\n)```",
"description": "This example shows how to create templates for modeling the infection process with consideration of the vaccination status of individuals. It includes the creation of templates for vaccinated individuals becoming infected by unvaccinated ones and vice versa."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/chime.py",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import NaturalConversion\\nfrom .concepts import infected, recovered\\n\ntemplates = [] # Assuming 'templates' list is already initiated as shown in previous sections\nfor vaccination_status in [\"vaccinated\", \"unvaccinated\"]:\nsubject = infected.with_context(vaccination_status=vaccination_status)```",
"description": "This section illustrates how to append natural conversion processes - specifically the recovery process - for infected individuals with different vaccination statuses (vaccinated and unvaccinated) to the list of templates."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/chime.py",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import TemplateModel\\n\n# Assuming all previous templates are already added as shown in above examples\n```",
"description": "Here, an SVIIvR TemplateModel is created by compiling various templates defined earlier. This model represents the overall dynamics of the system being studied."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/chime.py",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.modeling.viz import GraphicalModel\\nfrom pathlib import Path\\nfrom mira.metamodel import TemplateModel\\n\n# Assuming SVIIvR TemplateModel (`sviivr`) is already created as shown in previous sections\ndef _main():\nfrom mira.modeling.viz import GraphicalModel\nfrom pathlib import Path\n\ngm = GraphicalModel.from_template_model(sviivr)```",
"description": "This example demonstrates how to visualize the SVIIvR epidemiological model using the GraphicalModel class from the mira library. It also shows how to write this graphical representation to a PNG file, saving it to the user's Desktop."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/chime.py",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.modeling.viz import GraphicalModel\\nfrom pathlib import Path\\nfrom mira.metamodel import TemplateModel\\n\n# Assuming SVIIvR TemplateModel (`sviivr`) is already created as shown in previous sections\\n# Place this code block within the `if __name__ == \"__main__\":` condition\ndef _main():\nfrom mira.modeling.viz import GraphicalModel\nfrom pathlib import Path\n\ngm = GraphicalModel.from_template_model(sviivr)\ngm.write(Path.home().joinpath(\"Desktop\", \"sviivr.png\"))\n\n\nif __name__ == \"__main__\":```",
"description": "The main function which wraps the visualization logic of the SVIIvR epidemiological model, intended for execution when the script is run directly."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/applications/Enzyme_substrate_kinetics.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\nfrom indra.sources import trips\nfrom indra.assemblers.pysb import PysbAssembler\nimport pysb\nfrom pysb import pathfinder\ntext = 'MEK1 phosphorylates ERK2 on threonine 185 and tyrosine 187.'\ntp = trips.process_text(text)\npysb.pathfinder.set_path\n# Assemble a PySB model\npa = PysbAssembler(tp.statements)\npa.make_model()```",
"description": "Assembling a PySB model from text using TRIPS and exporting it to SBML string format."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/applications/Enzyme_substrate_kinetics.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.sources.sbml import template_model_from_sbml_string\n```",
"description": "Creating a template model from an SBML string."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/applications/Enzyme_substrate_kinetics.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.modeling import Model\n```",
"description": "Initializing a MIRA Model using the template model created from the SBML string."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/applications/Enzyme_substrate_kinetics.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.modeling.ode import OdeModel\n```",
"description": "Creating an ODE model from the MIRA Model with uninitialized parameters."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/applications/Enzyme_substrate_kinetics.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```\nparameters = {}\nfor param,model_param_object in model.parameters.items():```",
"description": "Setting up model parameters for simulation."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/applications/Enzyme_substrate_kinetics.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import numpy\nfrom mira.modeling.ode import simulate_ode_model\ntimes_test = numpy.linspace(0, 250, 100)\ninitial_test = [10000, 10000, 0, 0, 0]\nres = simulate_ode_model(ode_model = om, times=times_test,```",
"description": "Simulating the ODE model over a given time period with specific initial conditions."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/applications/Enzyme_substrate_kinetics.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```\n```",
"description": "Creating a list of variables to track from the model's initials."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/applications/Enzyme_substrate_kinetics.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import matplotlib.pyplot as plt\nplt.legend(handles = plt.plot(times_test,res), labels=variable_list,loc = 'upper left', bbox_to_anchor=(1,1))\nplt.xlabel('Time')\nplt.ylabel('Activation')```",
"description": "Plotting the results of the model simulation."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/model_api.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import requests\nfrom mira.metamodel import Concept, ControlledConversion, NaturalConversion, TemplateModel\nrest_url = \"http://34.230.33.149:8771\"\n# Example TemplateModel\ninfected = Concept(name=\"infected population\", identifiers={\"ido\": \"0000511\"})\nsusceptible = Concept(name=\"susceptible population\", identifiers={\"ido\": \"0000514\"})\nimmune = Concept(name=\"immune population\", identifiers={\"ido\": \"0000592\"})\ncontrolled_conversion = ControlledConversion(\ncontroller=infected,\nsubject=susceptible,\noutcome=infected,\n)\nnatural_conversion = NaturalConversion(subject=infected, outcome=immune)\nsir_template_model = TemplateModel(templates=[controlled_conversion, natural_conversion])\nsir_template_model_dict = sir_template_model.dict()```",
"description": "Demonstrates creating a TemplateModel including concepts and their conversions, and printing its JSON representation."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/model_api.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import requests\nfrom mira.metamodel import TemplateModel\nrest_url = \"http://34.230.33.149:8771\"\nsir_template_model_dict = # Your TemplateModel dictionary here\n# The `/api/to_petrinet` endpoint returns a PetriNet model based on the `TemplateModel` provided:\n\n# In[2]:\n\n\nres = requests.post(rest_url + \"/api/to_petrinet\", json=sir_template_model_dict)```",
"description": "Shows how to convert a TemplateModel to a PetriNet model using the REST API."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/model_api.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import requests\nfrom mira.metamodel import TemplateModel\nrest_url = \"http://34.230.33.149:8771\"\nsir_template_model_dict = # Your TemplateModel dictionary here\n# The `/api/stratify` endpoint can stratify a model. In this example, the stratification is along two cities, effectively creating a two-city SIR model from the original SIR model:\n\n# In[3]:\n\n\nres = requests.post(rest_url + \"/api/stratify\", json={\"template_model\": sir_template_model_dict, \"key\": \"city\", \"strata\": [\"Boston\", \"New York City\"]})```",
"description": "Illustrates stratifying a model along two cities using the `/api/stratify` endpoint."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/model_api.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import requests\nrest_url = \"http://34.230.33.149:8771\"\n# ## Biomodels Model\n# The `/api/biomodels/<model id>` endpoint returns a `TemplateModel` json of the biomodels model.\n\n# In[4]:\n\n\nres = requests.get(rest_url + \"/api/biomodels/BIOMD0000000956\")```",
"description": "Retrieves a TemplateModel JSON of a specified biomodels model using the `/api/biomodels/<model id>` endpoint."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/model_api.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import requests\nfrom mira.metamodel import TemplateModel\nrest_url = \"http://34.230.33.149:8771\"\nsir_template_model_dict = # Your TemplateModel dictionary here\n# ## Bilayer Endpoints\n# The `/api/model_to_bilayer` and `/api/bilayer_to_model` endpoints can translate between a `TemplateModel` json and a `Bilayer`\n\n# In[5]:\n\n\n# Get a bilayer json representation from a TemplateModel json\nres = requests.post(rest_url + \"/api/model_to_bilayer\", json=sir_template_model_dict)```",
"description": "Example of getting a bilayer JSON representation from a TemplateModel JSON using `/api/model_to_bilayer`."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/model_api.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import requests\nrest_url = \"http://34.230.33.149:8771\"\nbilayer_json = # Your Bilayer JSON here\n# In[6]:\n\n\n# Reverse the process by providing the bilayer json and get back the SIR TemplateModel json\nbilayer_json = res.json()\nres = requests.post(rest_url + \"/api/bilayer_to_model\", json=bilayer_json)```",
"description": "Shows the reverse process of converting a bilayer JSON back to a SIR TemplateModel JSON using `/api/bilayer_to_model`."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/model_api.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import requests\nfrom mira.sources.biomodels import get_sbml_model\nrest_url = \"http://34.230.33.149:8771\"\nbiomd951_xml_str = get_sbml_model(\"BIOMD0000000956\")\n# ## SBML XML To Model\n# For the `/api/sbml_xml_to_model` endpoint, you can provide an SBML model in the form of a string of the XML and get back a model.\n#\n# First, get an XML string. Here, done by the `get_sbml_model` function from the `biomodels` submodule in MIRA:\n\n# In[7]:\n\n\nfrom mira.sources.biomodels import get_sbml_model\nbiomd951_xml_str = get_sbml_model(\"BIOMD0000000956\")\nprint(biomd951_xml_str[:250])\n\n\n# Next, submit this string to the endpoint and get the corresponding model back:\n\n# In[8]:\n\n\nres = requests.post(rest_url + \"/api/sbml_xml_to_model\", json={\"xml_string\": biomd951_xml_str})```",
"description": "Demonstrates converting an SBML XML model to a MIRA model using the `/api/sbml_xml_to_model` endpoint."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/model_api.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import requests\nfrom mira.metamodel import TemplateModel\nrest_url = \"http://34.230.33.149:8771\"\nsir_template_model_dict = # Your TemplateModel dictionary here\n# ## Graphviz dot File\n#\n# The `/api/viz/to_dot_file` endpoint takes a `TemplateModel` and returns a graphviz dotfile of the provided model:\n\n# In[9]:\n\n\nres = requests.post(rest_url + \"/api/viz/to_dot_file\", json=sir_template_model_dict)```",
"description": "Shows how to convert a TemplateModel to a graphviz dot file using the `/api/viz/to_dot_file` endpoint."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/model_api.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import requests\nfrom mira.metamodel import TemplateModel\nfrom IPython.display import Image\nrest_url = \"http://34.230.33.149:8771\"\nsir_template_model_dict = # Your TemplateModel dictionary here\n# ## Graph image\n#\n# The `/api/viz/to_image` endpoint returns an image of the model as a graph structure.\n\n# In[10]:\n\n\nres = requests.post(rest_url + \"/api/viz/to_image\", json=sir_template_model_dict)\nwith open(\"./graph.png\", \"wb\") as fio:\nfio.write(res.content)\n\nfrom IPython.display import Image```",
"description": "Illustrates converting a TemplateModel to an image of the model as a graph structure using the `/api/viz/to_image` endpoint and saving the image."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/model_api.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import requests\nfrom mira.metamodel import TemplateModel, NaturalConversion\nfrom IPython.display import Image\nrest_url = \"http://34.230.33.149:8771\"\nsir_template_model_dict = # Your TemplateModel dictionary here\n# Modified TemplateModel dictionary or JSON here\n# ## Comparing Two Models\n# The endpoints `/api/models_to_delta_graph` and `/api/models_to_delta_image` returns a graph and a png image of the delta, respectively, of the comparison between two models.\n# First, let's create a modified version of the SIR model that has location specified in the context of its templates:\n\n# In[11]:\n\n\n# Add a location to the templates that are not NaturalConversion (Note that this has no meaning outside as an illustration in this example)\ntemplates_w_context = [templ.with_context(location=\"geonames:5128581\") if not isinstance(templ, NaturalConversion) else templ for templ in sir_template_model.templates]\nsir_w_context = TemplateModel(templates=templates_w_context, parameters=sir_template_model.parameters, initials=sir_template_model.initials)\n\n\n# Submit the two models to `/api/models_to_delta_image` to get an image of the delta graph:\n\n# In[12]:\n\n\nres = requests.post(rest_url + \"/api/models_to_delta_image\", json={\"template_model1\": sir_template_model_dict, \"template_model2\": sir_w_context.dict()})\nwith open(\"./delta_graph.png\", \"wb\") as f:\nf.write(res.content)\nImage(filename=\"./delta_graph.png\")\n\n\n# From the image, it can be seen that the NaturalConversion of the two models are equals, while the ControlledConversion in one model is a refinement of the other, in this case because the context was added.\n#\n# The other endpoint provides a way to download the graph seen in the image as a node-link data json:\n\n# In[13]:\n\n\nres = requests.post(rest_url + \"/api/models_to_delta_graph\", json={\"template_model1\": sir_template_model_dict, \"template_model2\": sir_w_context.dict()})```",
"description": "Compares two models and returns a graph and a PNG image of the delta between them using `/api/models_to_delta_graph` and `/api/models_to_delta_image` endpoints."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/viz_strat_petri.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import ControlledConversion, NaturalConversion, Concept, Template, TemplateModel\n# We start with a simple SIR-like template model\n\n# In[1]:\n\n\nfrom mira.metamodel import ControlledConversion, NaturalConversion, Concept, Template, TemplateModel\n\ninfected = Concept(name='infected population', identifiers={'ido': '0000511'})\nsusceptible = Concept(name='susceptible population', identifiers={'ido': '0000514'})\nimmune = Concept(name='immune population', identifiers={'ido': '0000592'})\n\nt1 = ControlledConversion(\ncontroller=infected,\nsubject=susceptible,\noutcome=infected,\n)\nt2 = NaturalConversion(subject=infected, outcome=immune)```",
"description": "Definition of a simple SIR-like template model using mira's metamodel functionality. This includes defining concepts such as 'infected population', 'susceptible population', and 'immune population', and establishing transitions between these states."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/viz_strat_petri.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import ControlledConversion, NaturalConversion, Concept, Template, TemplateModel\nfrom mira.modeling import Model\nfrom mira.modeling.viz import GraphicalModel\nfrom IPython.display import Image\ntemplate_model = TemplateModel(templates=[ControlledConversion(controller=Concept(name='infected population'), subject=Concept(name='susceptible population'), outcome=Concept(name='infected population')), NaturalConversion(subject=Concept(name='infected population'), outcome=Concept(name='immune population'))])\ntransition_model = Model(template_model)\n# ### Model visualization\n# We next transform the template model into a transition model and then visualize it as a graph,\n\n# In[2]:\n\n\nfrom mira.modeling import Model\ntransition_model = Model(template_model)\n\n\n# Visualization is implemented through a `viz` module and a `GraphicalModel` class which takes a transition model as input and creates a Graphviz graph structure for visualization purposes.\n\n# In[3]:\n\n\nfrom mira.modeling.viz import GraphicalModel\ngraphical_model = GraphicalModel(transition_model)\ngraphical_model.write('simple.png')\nfrom IPython.display import Image```",
"description": "Transformation of the template model into a transition model and its visualization as a graph. This section utilizes mira's modeling capabilities and a 'viz' module to create and display a graphical representation of the model."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/viz_strat_petri.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import ControlledConversion, NaturalConversion, Concept, Template, TemplateModel\nfrom mira.metamodel.ops import stratify\nfrom mira.modeling import Model\nfrom mira.modeling.viz import GraphicalModel\nfrom IPython.display import Image\ntemplate_model = TemplateModel(templates=[ControlledConversion(controller=Concept(name='infected population'), subject=Concept(name='susceptible population'), outcome=Concept(name='infected population')), NaturalConversion(subject=Concept(name='infected population'), outcome=Concept(name='immune population'))])\n# ### Model stratification\n#\n# Here we demonstrate that model transformations can be performed at the level of templates to create new model variants. We stratify the initial model into two cities whose populations can be exchanged between each other. Since the strata can themselves be ontology-grounded e.g., GeoNames IDs, it is in principle possible to use external information about geography or flight networks to define fluxes between strata.\n\n# In[4]:\n\n\nfrom mira.metamodel.ops import stratify\n\nmodel_2_city = stratify(\ntemplate_model,\nkey=\"city\",\nstrata=[\n\"geonames:5128581\", # NYC\n\"geonames:4930956\", # Boston\n],\n)\n\n\n# In[5]:\n\n\ntransition_2_city = Model(model_2_city)\ngraphical_2_city = GraphicalModel(transition_2_city)\ngraphical_2_city.write('two_city.png')\nfrom IPython.display import Image```",
"description": "Stratification of the initial model into two cities (NYC and Boston), demonstrating how model transformations can be applied at the template level to create new variants. This involves stratifying the model based on 'city' and defining strata with GeoNames IDs."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/viz_strat_petri.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import ControlledConversion, NaturalConversion, Concept, Template, TemplateModel\nfrom mira.metamodel.ops import stratify\nfrom mira.modeling import Model\nfrom mira.modeling.petri import PetriNetModel\nfrom mira.modeling.viz import GraphicalModel\nfrom IPython.display import Image\ntemplate_model = TemplateModel(templates=[ControlledConversion(controller=Concept(name='infected population'), subject=Concept(name='susceptible population'), outcome=Concept(name='infected population')), NaturalConversion(subject=Concept(name='infected population'), outcome=Concept(name='immune population'))])\nmodel_2_city = stratify(template_model, key=\"city\", strata=[\"geonames:5128581\", \"geonames:4930956\"])\ntransition_model = Model(template_model)\ntransition_2_city = Model(model_2_city)\n# ### Model generation into Petri net form\n# Here we show that these transition models can be exported as JSON-serialized Petri nets consisting of a set of transitions, states, inputs and outputs.\n#\n# Below we show JSON representations of Petri nets for both the simple and the 2-city stratified models.\n\n# In[6]:\n\n\nfrom mira.modeling.petri import PetriNetModel\n\n\n# In[7]:\n\n\npm_simple = PetriNetModel(transition_model)\n\n\n# In[8]:\n\n\npm_simple.to_json()\n\n\n# In[10]:\n\n\npm_2_city = PetriNetModel(transition_2_city)```",
"description": "Exporting transition models as JSON-serialized Petri nets for both the simple and the 2-city stratified models. Details include JSON representations of Petri nets, showcasing the use of mira's Petri net functionality to transition models into a format useful for further analysis or integration with other tools."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/ensemble/ensemble.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import copy\nimport os\nimport re\nimport glob\nimport pandas as pd\nimport tqdm\nfrom collections import defaultdict\nimport pystow\nfrom mira.sources.sbml import template_model_from_sbml_file\n\n# ### Explore BioModels and find relevant models\n#\n# ### Step 1: process all BioModels for COVID-19\n\n# In[2]:\n\n\nbase_folder = pystow.join('mira', 'biomodels', 'models')\nfnames = sorted(glob.glob(os.path.join(base_folder.as_posix(),\n'BIOMD*/BIOMD*.xml')))\nmodels = {}\nfor fname in tqdm.tqdm(fnames):\nmodel_id = os.path.splitext(os.path.basename(fname))[0]\nmodels[model_id] = template_model_from_sbml_file(fname)\n\n\n# ### Step 2: Look for a set of domain concepts of interest\n#\n# These concepts are from the MIRA Epidemiology Domain Knowledge Graph.\n\n# In[3]:\n\n\ngroundings = {\n'hospitalization': 'ncit:C25179',\n'death': 'ncit:C28554',\n'detected': 'ncit:C15220',\n'infected': 'ido:0000511',\n}\n\n\n# MIRA's `mira.metamodel.search.find_models_with_grounding` function can be used to discover models with given domain concepts.\n#\n# We organize the results of the search into a table.\n\n# In[4]:\n\n\nmodels_for_grounding = defaultdict(set)\nfor grounding, curie in groundings.items():\ndb, id = curie.split(':')\nmodels_for_grounding[grounding] = set(find_models_with_grounding(models, db, id))\nmodels_for_grounding = dict(models_for_grounding)\n\n\n# In[5]:\n\n\n# Create a DataFrame with one row for each model file and one column for each term\ndf = pd.DataFrame(index=sorted(set(models)), columns=models_for_grounding.keys())\n\n# Fill the DataFrame with boolean values indicating whether each model file is associated with each term\nfor term, models_ in models_for_grounding.items():\nfor model in models_:\ndf.loc[model, term] = True\n\ndf.fillna(False, inplace=True) # Fill missing values with False\n\n# Reset the index to make the model file paths a regular column\ndf = df.reset_index().rename(columns={'index': 'model'})\n\n\n# In[6]:\n\n```",
"description": "This section processes all BioModels for COVID-19 and organizes models based on a set of domain concepts (hospitalization, death, detected, infected) from the MIRA Epidemiology Domain Knowledge Graph. It culminates in displaying a DataFrame summarizing the processed models."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/ensemble/ensemble.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from sympy import Symbol\nfrom mira.metamodel import Concept, NaturalConversion, Parameter, Observable, Distribution\nfrom mira.metamodel.ops import simplify_rate_laws\nfrom mira.modeling.viz import GraphicalModel\nfrom mira.modeling import Model\nimport copy\nmodels = {'BIOMD0000000983': copy.deepcopy(any_model_variable_here)}\n\n# ### Step 3: Prepare to add some extra information to models\n#\n# Here we define reused functions to:\n# 1. Define **parameter distributions** for each model. Note that these are just **placeholders** for now to demonstrate the use of distributions. The distributions are defined around the original parameter values.\n# 2. Define **observable domain concepts** corresponding to the challenge readouts. These will be integrated into models.\n\n# In[7]:\n\n\nfrom mira.modeling.viz import *\n\n\n# In[8]:\n\n\ndef add_distribution(p):\nif p.value == 0:\nreturn\nelse:\np.distribution = Distribution(\ntype='StandardUniform1',\nparameters={\n'minimum': p.value-0.2*abs(p.value),\n'maximum': p.value+0.2*abs(p.value),\n}\n)\n\n\n# We create domain concepts corresponding to the challenge varibles to predict:\n\n# In[9]:\n\n\ncases = Concept(name='Cases',\nidentifiers={'ido': '0000511'},\ncontext={'diagnosed': 'ncit:C113725'})\nhospitalizations = Concept(name='Hospitalizations',\nidentifiers={'ido': '0000511'},\ncontext={'hospitalization': 'ncit:C25179'})\ndeaths = Concept(name='Deaths',\nidentifiers={'ncit': 'C28554'})\n\n\n# ### Model 1: Zong et al. model\n\n# In[10]:\n\n\nmodel = copy.deepcopy(models['BIOMD0000000983'])\n\n\n# #### Rate law interpretation and manipulation -> structural simplification\n\n# In[11]:\n\n\nfor template in model.templates[2:4]:\nprint(template.type, template.rate_law.args[0])\n\n\n# In[12]:\n\n\nmodel = simplify_rate_laws(model)\n\n\n# In[13]:\n\n\nfor template in model.templates[2:6]:\nprint(template.type, template.rate_law.args[0])\n\n\n# In[14]:\n\n\nmodel.templates = model.templates[2:]\n\n\n# #### Stting up observables\n\n# \n\n# First we implement deaths in the model\n\n# In[15]:\n\n\ndeceased = Concept(name='Deceased', identifiers={'ncit': 'C28554'})\nt = NaturalConversion(\nsubject=model.get_concept('Infected_reported'),\noutcome=deceased,\nrate_law=(1-Symbol('q'))*Symbol('eta_r')*Symbol('Infected_reported'),\n)\n\n\n# In[16]:\n\n\nmodel = model.add_template(t)\n\n\n# In[17]:\n\n```",
"description": "Step 3 involves defining parameter distributions as placeholders for demonstrating the use of distributions in models and setting up observable domain concepts corresponding to the challenge readouts. It concludes with graphical representation of modifications made to the Zong et al. model, including simplification of rate laws, and setup of observables including deaths and hospitalization parameters."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/ensemble/ensemble.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import Observable, Unit, Time\nfrom mira.modeling.amr.petrinet import AMRPetriNetModel\nfrom mira.metamodel.ops import simplify_rate_laws\nfrom mira.modeling.viz import GraphicalModel\nimport sympy\nimport copy\nmodels = {'BIOMD0000000955': copy.deepcopy(any_model_variable_here)}\nadd_distribution = copy.deepcopy(any_function_def_here)\ncases = copy.deepcopy(any_cases_variable_here)\nhospitalizations = copy.deepcopy(any_hospitalizations_variable_here)\ndeaths = copy.deepcopy(any_deaths_variable_here)\n\n# ### Model 2: Giordano et al (SIDARTHE) model\n\n# In[24]:\n\n\nmodel = copy.deepcopy(models['BIOMD0000000955'])\nmodel = simplify_rate_laws(model)\n\n\n# In[25]:\n\n\nGraphicalModel.for_jupyter(model, width='50%')\n\n\n# In[26]:\n\n\nparam_reduce = ['Event_trigger_Fig3b', 'Event_trigger_Fig3d', 'Event_trigger_Fig4b', 'Event_trigger_Fig4d',\n'ModelValue_16', 'ModelValue_17', 'ModelValue_18', 'ModelValue_19', 'ModelValue_20', 'ModelValue_21',\n'Italy']\n\n\n# In[27]:\n\n\nfor p in param_reduce:\nmodel.substitute_parameter(p)\nfor v in model.parameters.values():\nadd_distribution(v)\n\n\n# In[32]:\n\n\nfrom mira.metamodel import Unit, Time\nimport sympy\n\n\n# In[34]:\n\n\nfor template in model.templates:\nfor concept in template.get_concepts():\nconcept.units = Unit(expression=sympy.parse_expr('1'))\nmodel.time = Time(name='t', units=Unit(expression=sympy.parse_expr('day')))\n\n\n# \n\n# In[35]:\n\n\nmodel.observables = {\n'Cases': Observable(**cases.dict(), expression=Symbol('Diagnosed')+Symbol('Recognized')+Symbol('Threatened')),\n'Hospitalizations': Observable(**hospitalizations.dict(), expression=Symbol('Recognized')+Symbol('Threatened')),\n'Deaths': Observable(**deaths.dict(), expression=Symbol('Extinct'))\n}\n\n\n# In[36]:\n\n\nmodel_to_json_file(model, 'BIOMD0000000955_template_model.json')\npm = AMRPetriNetModel(Model(model))```",
"description": "Example showcasing the Giordano et al (SIDARTHE) model. It involves simplifying rate laws of the model, reducing parameters, modifying unit expressions, and setting up observables for cases, hospitalizations, and deaths. The example concludes with saving the template model and corresponding Petri net model to JSON files."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/ensemble/ensemble.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import Observable\nfrom mira.modeling import Model\nfrom mira.modeling.amr.petrinet import PetriNetModel\nfrom mira.metamodel.ops import simplify_rate_laws\nimport re\nimport copy\nmodels = {'BIOMD0000000960': copy.deepcopy(any_model_variable_here)}\nadd_distribution = copy.deepcopy(any_function_def_here)\ncases = copy.deepcopy(any_cases_variable_here)\nhospitalizations = copy.deepcopy(any_hospitalizations_variable_here)\ndeaths = copy.deepcopy(any_deaths_variable_here)\n\n# ### Model 3: Paiva et al model\n\n# In[30]:\n\n\nmodel = copy.deepcopy(models['BIOMD0000000960'])\nmodel = simplify_rate_laws(model)\n\n\n# In[31]:\n\n\nGraphicalModel.for_jupyter(model, width='50%')\n\n\n# ### Parameter simplification\n# - Eliminate non-US parameters\n# - Eliminate duplicate parameters (initials defined for static parameters)\n# - Enable US-specific scenario parameter\n# - Eliminate all unused parameters\n\n# In[32]:\n\n\nparam_reduce = [p for p, v in model.parameters.items()\nif any(c in v.description for c in {'China', 'Italy', 'Spain', 'France', 'Germany'})]\nfor p in param_reduce:\nmodel.eliminate_parameter(p)\n\n\n# In[33]:\n\n\nredundant_params = []\nfor p in model.parameters.values():\nmatch = re.match(r'^Initial for (.*)$', p.description)\nif match:\nother_param = match.groups()[0]\nif other_param in model.parameters:\nredundant_params.append((p.name, other_param))\nelif '_' + other_param in model.parameters:\nredundant_params.append((p.name, '_' + other_param))\n\n\n# In[34]:\n\n\nfor redundant_param, preserved_param in redundant_params:\nmodel.eliminate_duplicate_parameter(redundant_param, preserved_param)\n\n\n# In[35]:\n\n\nmodel.substitute_parameter('_6_Trigger_USA', 1)\n\n\n# In[36]:\n\n\nmodel.eliminate_unused_parameters()\n\n\n# In[37]:\n\n\nfor v in model.parameters.values():\nadd_distribution(v)\n\n\n# #### Set up observables\n\n# In[38]:\n\n\nmodel.observables = {\n'Cases': Observable(**cases.dict(), expression=Symbol('Infectious')),\n'Hospitalizations': Observable(**hospitalizations.dict(), expression=Symbol('Hospitalized')),\n'Deaths': Observable(**deaths.dict(), expression=Symbol('Deceased'))\n}\n\n\n# #### Save model\n\n# In[39]:\n\n\nmodel_to_json_file(model, 'BIOMD0000000960_template_model.json')\npm = PetriNetModel(Model(model))```",
"description": "This section details the process of setting up the Paiva et al model, including simplifying rate laws, parameter reductions for geography-specific parameters and duplicates, and unused parameter elimination. It establishes observables for cases, hospitalizations, and deaths and saves the model and Petri net model to JSON."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/Hackathon Scenario 4.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\n# ### Scenario 4: model comparison\n\n# In[1]:\n\n\nfrom mira.sources.biomodels import get_template_model\nfrom mira.metamodel import TemplateModelComparison, get_dkg_refinement_closure\nrefinement_fun = get_dkg_refinement_closure().is_ontological_child```",
"description": "Setting up model comparison by importing necessary modules and defining a refinement function."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/Hackathon Scenario 4.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.sources.biomodels import get_template_model\nfrom mira.metamodel import TemplateModelComparison, get_dkg_refinement_closure\nrefinement_fun = get_dkg_refinement_closure().is_ontological_child\nmodel_ids = ['BIOMD0000000955', 'BIOMD0000000991',\n'BIOMD0000000983', 'BIOMD0000000963']```",
"description": "Defining a list of model IDs for comparison."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/Hackathon Scenario 4.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```model_ids = ['BIOMD0000000955', 'BIOMD0000000991', 'BIOMD0000000983', 'BIOMD0000000963']\nmodels = {model_id: get_template_model(model_id)\nfor model_id in model_ids}```",
"description": "Fetching models based on model IDs."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/Hackathon Scenario 4.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.sources.biomodels import get_template_model\nfrom mira.metamodel import TemplateModelComparison, get_dkg_refinement_closure\nrefinement_fun = get_dkg_refinement_closure().is_ontological_child\nmodel_ids = ['BIOMD0000000955', 'BIOMD0000000991', 'BIOMD0000000983', 'BIOMD0000000963']\nmodels = {model_id: get_template_model(model_id) for model_id in model_ids}\n```",
"description": "Creating a TemplateModelComparison object using the fetched models and the refinement function."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/Hackathon Scenario 4.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.sources.biomodels import get_template_model\nfrom mira.metamodel import TemplateModelComparison, get_dkg_refinement_closure\nrefinement_fun = get_dkg_refinement_closure().is_ontological_child\nmodel_ids = ['BIOMD0000000955', 'BIOMD0000000991', 'BIOMD0000000983', 'BIOMD0000000963']\nmodels = {model_id: get_template_model(model_id) for model_id in model_ids}\ntc = TemplateModelComparison(list(models.values()), refinement_fun)\nwith open('mira_comparison_scenario4.json', 'w') as fh:```",
"description": "Writing the model comparison results to a JSON file."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/Hackathon Scenario 4.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.sources.biomodels import get_template_model\nfrom mira.metamodel import TemplateModelComparison, get_dkg_refinement_closure\nrefinement_fun = get_dkg_refinement_closure().is_ontological_child\nmodel_ids = ['BIOMD0000000955', 'BIOMD0000000991', 'BIOMD0000000983', 'BIOMD0000000963']\nmodels = {model_id: get_template_model(model_id) for model_id in model_ids}\ntc = TemplateModelComparison(list(models.values()), refinement_fun)\nprint(model_ids)```",
"description": "Printing model IDs and invoking a method to get similarity scores from the model comparison."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/Hackathon Scenario 4.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.sources.biomodels import get_template_model\nfrom mira.metamodel import TemplateModelComparison, get_dkg_refinement_closure\nrefinement_fun = get_dkg_refinement_closure().is_ontological_child\nmodel_ids = ['BIOMD0000000955', 'BIOMD0000000991', 'BIOMD0000000983', 'BIOMD0000000963']\nmodels = {model_id: get_template_model(model_id) for model_id in model_ids}\ntc = TemplateModelComparison(list(models.values()), refinement_fun)\n```",
"description": "Storing similarity scores in a variable for further processing."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/Hackathon Scenario 4.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```simscores = tc.model_comparison.get_similarity_scores()\nnodes = []\nedges = []\nadded = set()\nfor entry in simscores:\nfor model_id in entry['models']:\nif model_id not in added:\nnodes.append((model_id, {'label': model_ids[model_id]}))\nadded.add(model_id)```",
"description": "Preparing data structures for a graph representation based on the similarity scores."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/Hackathon Scenario 4.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import networkx\nimport matplotlib.pyplot as plt\nsimscores = tc.model_comparison.get_similarity_scores()\nnodes = []\nedges = []\nadded = set()\nfor entry in simscores:\n for model_id in entry['models']:\n if model_id not in added:\n nodes.append((model_id, {'label': model_ids[model_id]}))\n added.add(model_id)\n edges.append((*entry['models'], {'weight': entry['score']}))\nimport networkx\n\n\n# In[33]:\n\n\nG = networkx.DiGraph()\nG.add_nodes_from(nodes)\n\n\n# In[34]:\n\n\nG.add_edges_from(edges)\n\n\n# In[35]:\n\n\npos = networkx.spring_layout(G)\nnetworkx.draw(G, pos, with_labels=True)\nedge_labels = {(u, v): '%.2f' % d['weight'] for u, v, d in G.edges(data=True)}\nnetworkx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)```",
"description": "Visualizing the network graph with similarity scores."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/decapodes/decapodes_examples.py",
"origination_method": "extract_from_library_automatic",
"code": "```import requests\nfrom mira.metamodel.decapodes import Decapode\nICE_DYNAMICS_EXAMPLE_JSON_URL = \"https://raw.githubusercontent.com/ciemss/Decapodes.jl/sa_climate_modeling/examples/climate/ice_dynamics.json\"\n\ndef get_ice_dynamics_example() -> Decapode:\n\"\"\"Return the ice dynamics decapode example\n\nReturns\n-------\n:\nThe ice dynamics example as a Decapode object\n\"\"\"\nres_json = requests.get(ICE_DYNAMICS_EXAMPLE_JSON_URL).json()```",
"description": "Fetching and processing the ice dynamics decapode example as a Decapode object."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/decapodes/decapodes_examples.py",
"origination_method": "extract_from_library_automatic",
"code": "```import requests\nICE_DYNAMICS_EXAMPLE_JSON_URL = \"https://raw.githubusercontent.com/ciemss/Decapodes.jl/sa_climate_modeling/examples/climate/ice_dynamics.json\"\n\ndef get_ice_decapode_json():\n\"\"\"Return the ice dynamics decapode example as json\n\nReturns\n-------\n: JSON\nThe ice dynamics example as a json object\n\"\"\"```",
"description": "Fetching the ice dynamics decapode example in JSON format."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/decapodes/decapodes_examples.py",
"origination_method": "extract_from_library_automatic",
"code": "```import requests\nfrom mira.metamodel.decapodes import Decapode\nBUDYKO_SELLERS_EXAMPLE_JSON_URL = \"https://raw.githubusercontent.com/AlgebraicJulia/Decapodes.jl/gh-pages/dev/budyko_sellers.json\"\n\ndef get_budyko_sellers_example() -> Decapode:\n\"\"\"Returns the budyko sellers decapode example\n\nReturns\n-------\n:\nThe budyko-sellers example as a Decapode object\n\"\"\"\nres_json = requests.get(BUDYKO_SELLERS_EXAMPLE_JSON_URL).json()```",
"description": "Fetching and processing the budyko sellers decapode example as a Decapode object."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/decapodes/decapodes_examples.py",
"origination_method": "extract_from_library_automatic",
"code": "```import requests\nBUDYKO_SELLERS_EXAMPLE_JSON_URL = \"https://raw.githubusercontent.com/AlgebraicJulia/Decapodes.jl/gh-pages/dev/budyko_sellers.json\"\n\ndef get_budyko_seller_decapode_json():\n\"\"\"Return the budyko sellers decapode example as json\n\nReturns\n-------\n: JSON\nThe budyko-sellers example as a json object\n\"\"\"```",
"description": "Fetching the budyko sellers decapode example in JSON format."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/decapodes/decapodes_examples.py",
"origination_method": "extract_from_library_automatic",
"code": "```import json\nfrom pathlib import Path\nfrom mira.metamodel.decapodes import Decapode\nEXAMPLES = Path(__file__).parent / \"decapodes_vs_decaexpr_composite\"\nDECAPODE_OSCILLATOR = EXAMPLES / \"d1_oscillator_decapode.json\"\n\ndef get_oscillator_decapode() -> Decapode:\n\"\"\"Return the oscillator decapode example\n\nExample from\n\nReturns\n-------\n:\nThe oscillator example as a Decapode object\n\"\"\"\nwith open(DECAPODE_OSCILLATOR) as f:\ndecapode_osc_json = json.load(f)```",
"description": "Loading and processing the oscillator decapode from a local JSON file as a Decapode object."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/decapodes/decapodes_examples.py",
"origination_method": "extract_from_library_automatic",
"code": "```import json\nfrom pathlib import Path\nEXAMPLES = Path(__file__).parent / \"decapodes_vs_decaexpr_composite\"\nDECAPODE_OSCILLATOR = EXAMPLES / \"d1_oscillator_decapode.json\"\n\ndef get_oscillator_decapode_json():\n\"\"\"Return the oscillator decapode example as json\n\nReturns\n-------\n: JSON\nThe oscillator example as a json object\n\"\"\"\nwith open(DECAPODE_OSCILLATOR) as f:```",
"description": "Loading the oscillator decapode example from a local JSON file."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/decapodes/decapodes_examples.py",
"origination_method": "extract_from_library_automatic",
"code": "```import json\nfrom pathlib import Path\nfrom mira.metamodel.decapodes import Decapode\nEXAMPLES = Path(__file__).parent / \"decapodes_vs_decaexpr_composite\"\nDECAPODE_FRICTION = EXAMPLES / \"d2_friction_decapode.json\"\n\ndef get_friction_decapode() -> Decapode:\n\"\"\"Return the friction decaexpr example\n\nReturns\n-------\n:\nThe friction example as a Decapode object\n\"\"\"\nwith open(DECAPODE_FRICTION) as f:\ndecapode_friction_json = json.load(f)```",
"description": "Loading and processing the friction decapode from a local JSON file as a Decapode object."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/decapodes/decapodes_examples.py",
"origination_method": "extract_from_library_automatic",
"code": "```import json\nfrom pathlib import Path\nEXAMPLES = Path(__file__).parent / \"decapodes_vs_decaexpr_composite\"\nDECAPODE_FRICTION = EXAMPLES / \"d2_friction_decapode.json\"\n\ndef get_friction_decapode_json():\n\"\"\"Return the friction decaexpr example as json\n\nReturns\n-------\n: JSON\nThe friction example as a json object\n\"\"\"\nwith open(DECAPODE_FRICTION) as f:```",
"description": "Loading the friction decapode example from a local JSON file."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/decapodes/decapodes_examples.py",
"origination_method": "extract_from_library_automatic",
"code": "```import json\nfrom pathlib import Path\nfrom mira.metamodel.decapodes import Decapode\nEXAMPLES = Path(__file__).parent / \"decapodes_vs_decaexpr_composite\"\nDECAEXPR_OSCILLATOR = EXAMPLES / \"oscillator_decaexpr.json\"\n\ndef get_oscillator_decaexpr() -> Decapode:\n\"\"\"Return the oscillator decaexpr example\n\nReturns\n-------\n:\nThe oscillator example as a Decapode object\n\"\"\"\nwith open(DECAEXPR_OSCILLATOR) as f:\ndecaexpr_osc_json = json.load(f)```",
"description": "Loading and processing the oscillator decaexpr from a local JSON file as a Decapode object."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/code/examples/decapodes/decapodes_examples.py",
"origination_method": "extract_from_library_automatic",
"code": "```import json\nfrom pathlib import Path\nfrom mira.metamodel.decapodes import Decapode\nEXAMPLES = Path(__file__).parent / \"decapodes_vs_decaexpr_composite\"\nDECAEXPR_FRICTION = EXAMPLES / \"friction_decaexpr.json\"\n\ndef get_friction_decaexpr() -> Decapode:\n\"\"\"Return the friction decaexpr example\n\nReturns\n-------\n:\nThe friction example as a Decapode object\n\"\"\"\nwith open(DECAEXPR_FRICTION) as f:\ndecaexpr_friction_json = json.load(f)```",
"description": "Loading and processing the friction decaexpr from a local JSON file as a Decapode object."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/hackathon_2023.10/stratification_autoname.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel.ops import stratify\nfrom mira.examples.sir import sir_parameterized\ncities = [\n\"geonames:5128581\", # NYC\n\"geonames:4930956\", # boston\n]\n\nfrom mira.metamodel.ops import stratify\nfrom mira.examples.sir import sir_parameterized\ncities = [\n\"geonames:5128581\", # NYC\n\"geonames:4930956\", # boston\n]\n\n\n# ## Default behavior (like before)\n# Name is generated from whatever you define as the strata.\n\n# In[2]:\n\n\nstratified_model = stratify(\nsir_parameterized,\nkey=\"city\",\nstrata=cities,\ncartesian_control=False,\ndirected=False\n)```",
"description": "Default behavior: Stratifying a model without automatic naming or custom names, resulting in default names generated from strata definitions."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/hackathon_2023.10/stratification_autoname.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel.ops import stratify\nfrom mira.examples.sir import sir_parameterized\ncities = [\n\"geonames:5128581\", # NYC\n\"geonames:4930956\", # boston\n]\n\nstratified_model_2 = stratify(\nsir_parameterized,\nkey=\"city\",\nstrata=cities,\nstrata_name_lookup=True,\ncartesian_control=False,\ndirected=False\n)```",
"description": "New option 1: Stratifying a model with automatic name lookup for renaming based on Digital Knowledge Graph (DKG)."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/hackathon_2023.10/stratification_autoname.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel.ops import stratify\nfrom mira.examples.sir import sir_parameterized\ncities = [\n\"geonames:5128581\", # NYC\n\"geonames:4930956\", # boston\n]\ncity_curie_map = {\"geonames:5128581\": \"yankees\", \"geonames:4930956\": \"red_sox\"}\n\ncity_curie_map = {\"geonames:5128581\": \"yankees\", \"geonames:4930956\": \"red_sox\"}\nstratified_model_3 = stratify(\nsir_parameterized,\nkey=\"city\",\nstrata=cities,\nstrata_curie_to_name=city_curie_map,\ncartesian_control=False,\ndirected=False\n)\nprint(stratified_model_3.templates[0].controller.name)```",
"description": "New option 2: Stratifying a model using a custom name mapping to provide more meaningful names."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/hackathon_2023.10/climate_grounding.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import requests\nfrom mira.sources.acsets.decapodes import process_decapode\nfrom mira.dkg.askemo import get_askem_climate_ontology_terms\nfrom mira.dkg.physical_constants import get_physical_constant_terms\n\nsynonym_mappings = {}\n# ### Extract synonym mappings for the Halfar model\n\n# In[16]:\n\n\nsynonym_mappings = {}\n\nfor wd, name, description, synonyms, xrefs, _value, _formula, symbols in get_physical_constant_terms():\ncurie = f\"wikidata:{wd}\"\nsynonym_dict[name] = curie\nfor synoynm in synonyms or []:\nsynonym_mappings[synoynm] = (curie, name)\nfor symbol in symbols or []:\nsynonym_mappings[symbol] = (curie, name)\n\nfor curie, term in get_askem_climate_ontology_terms().items():\nif \"askem.climate:0001002\" in term.part_ofs:\nprint(curie, term.name, term.synonyms)\nfor syn in term.synonyms:\nif syn.type == 'referenced_by_symbol':```",
"description": "Extracting synonym mappings for the Halfar model from both physical constants and askem climate ontology terms."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/hackathon_2023.10/climate_grounding.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import requests\nfrom mira.sources.acsets.decapodes import process_decapode\n# ### Create a Decapodes object from the Halfar model JSON\n\n# In[17]:\n\n\nmodel_url = 'https://raw.githubusercontent.com/ciemss/Decapodes.jl/sa_climate_modeling/examples/climate/ice_dynamics.json'\nmodel_json = requests.get(model_url).json()```",
"description": "Creating a Decapodes object from the Halfar model JSON."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/hackathon_2023.10/climate_grounding.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.sources.acsets.decapodes import process_decapode\n\nmodel_url = 'https://raw.githubusercontent.com/ciemss/Decapodes.jl/sa_climate_modeling/examples/climate/ice_dynamics.json'\nmodel_json = requests.get(model_url).json()\nmodel_decapode = process_decapode(model_json)\nsynonym_mappings = {} # Assume synonym_mappings has been defined earlier as per the first example\n# ### Look up groundings for model variables and show the ones that exist\n\n# In[18]:\n\n\nfor var in model_decapode.variables.values():\nif var.name in synonym_mappings:\ncurie, name = synonym_mappings[var.name]\nprefix, identifier = curie.split(':', 1)\nvar.identifiers = {prefix: identifier}```",
"description": "Looking up groundings for model variables and displaying the matched variables."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/hackathon_2023.10/climate_grounding.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.dkg.physical_constants import get_physical_constant_terms\n\nphysical_constants = {}\n# ### General physical constants in the DKG\n\n# In[42]:\n\n\nphysical_constants = {}\nfor wd, name, description, synonyms, xrefs, _value, _formula, symbols in get_physical_constant_terms():\ncurie = f\"wikidata:{wd}\"\nphysical_constants[name] = \\\n{\n'curie': curie,\n'description': description,\n'synonyms': ', '.join(synonyms),\n'xrefs': ', '.join(xrefs),\n'value': _value,\n'symbols': ', '.join(symbols)```",
"description": "Compiling a detailed dictionary of general physical constants from the DKG."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/hackathon_2023.10/climate_grounding.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import pandas\n\nphysical_constants = {} # Assume physical_constants has been defined earlier as per the fourth example\ndef get_df(constant_name):\n return pandas.DataFrame({k: [v] for k, v in physical_constants[constant_name].items()}).T\n\npandas.set_option('display.max_colwidth', None)\npandas.set_option('display.max_colwidth', None)\ndef get_df(constant_name):\nreturn pandas.DataFrame({k: [v] for k, v in physical_constants[constant_name].items()}).T\n\n\n# In[57]:\n\n\nget_df('Planck constant')\n\n\n# In[58]:\n\n```",
"description": "Using pandas to display physical constants data in a dataframe format."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/evaluation_2023.07/scenario1.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import sympy\nfrom copy import deepcopy as _d\nfrom mira.metamodel import *\nfrom mira.modeling import Model\nfrom mira.modeling.amr.petrinet import AMRPetriNetModel\nfrom mira.modeling.viz import GraphicalModel\nimport jsonschema\nimport sympy\nfrom copy import deepcopy as _d\nfrom mira.metamodel import *\nfrom mira.modeling import Model\nfrom mira.modeling.amr.petrinet import AMRPetriNetModel\nfrom mira.modeling.viz import GraphicalModel\nimport jsonschema\n\n\n# In[2]:\n\n\ndef sanity_check_tm(tm: TemplateModel):\nassert tm.templates\nall_concept_names = set(tm.get_concepts_name_map())\nall_parameter_names = set(tm.parameters)\nall_symbols = all_concept_names | all_parameter_names | ({tm.time.name} if tm.time else set())\nfor template in tm.templates:\nassert template.rate_law\nsymbols = template.rate_law.args[0].free_symbols\nfor symbol in symbols:\nassert symbol.name in all_symbols\nall_initial_names = {init.concept.name for init in tm.initials.values()}\nfor concept in all_concept_names:\nassert concept in all_initial_names\n\n\n# In[3]:\n\n\ndef sanity_check_amr(amr_json):\nimport requests\nassert 'schema' in amr_json\nschema_json = requests.get(amr_json['schema']).json()\njsonschema.validate(schema_json, amr_json)\n\n\n# In[4]:\n\n\nperson_units = lambda: Unit(expression=sympy.Symbol('person'))\nday_units = lambda: Unit(expression=sympy.Symbol('day'))\nper_day_units = lambda: Unit(expression=1/sympy.Symbol('day'))\ndimensionless_units = lambda: Unit(expression=sympy.Integer('1'))\nper_day_per_person_units = lambda: Unit(expression=1/(sympy.Symbol('day')*sympy.Symbol('person')))\n\nc = {\n'S': Concept(name='S', units=person_units(), identifiers={'ido': '0000514'}),\n'E': Concept(name='E', units=person_units(), identifiers={'apollosv': '0000154'}),\n'I': Concept(name='I', units=person_units(), identifiers={'ido': '0000511'}),\n'R': Concept(name='R', units=person_units(), identifiers={'ido': '0000592'}),\n'H': Concept(name='H', units=person_units(), identifiers={'ido': '0000511'},\ncontext={'property': 'ncit:C25179'}),\n'D': Concept(name='D', units=person_units(), identifiers={'ncit': 'C28554'}),\n}\n\n\nN_val = 19_340_000\nE_val = 1\nI_val = 4\n\nparameters = {\n'beta': Parameter(name='beta', value=0.4, units=per_day_per_person_units()),\n'r_E_to_I': Parameter(name='r_E_to_I', value=0.2, units=per_day_units()),\n'r_I_to_H': Parameter(name='r_I_to_H', value=0.1, units=per_day_units()),\n'p_I_to_H': Parameter(name='p_I_to_H', value=0.2, units=dimensionless_units()),\n'r_I_to_R': Parameter(name='r_I_to_R', value=0.07, units=per_day_units()),\n'p_I_to_R': Parameter(name='p_I_to_R', value=0.8, units=dimensionless_units()),\n'r_H_to_R': Parameter(name='r_H_to_R', value=0.1, units=per_day_units()),\n'p_H_to_R': Parameter(name='p_H_to_R', value=0.88, units=dimensionless_units()),\n'r_H_to_D': Parameter(name='r_H_to_D', value=0.1, units=per_day_units()),\n'p_H_to_D': Parameter(name='p_H_to_D', value=0.12, units=dimensionless_units()),\n'N': Parameter(name='N', value=N_val, units=person_units()),\n}\n\n\ninitials = {\n'S': Initial(concept=Concept(name='S'), value=N_val-(E_val+I_val)),\n'E': Initial(concept=Concept(name='E'), value=E_val),\n'I': Initial(concept=Concept(name='I'), value=I_val),\n'R': Initial(concept=Concept(name='R'), value=0),\n'H': Initial(concept=Concept(name='H'), value=0),\n'D': Initial(concept=Concept(name='D'), value=0),\n}\n\nobservables = {}\n\n\n# In[5]:\n\n\nS, E, I, R, D, H, N, beta, r_E_to_I, r_E_to_H, r_I_to_H, p_I_to_H, r_I_to_R, p_I_to_R, r_H_to_R, p_H_to_R, r_H_to_D, p_H_to_D = \\\nsympy.symbols('S E I R D H N beta r_E_to_I r_E_to_H r_I_to_H p_I_to_H r_I_to_R p_I_to_R r_H_to_R p_H_to_R r_H_to_D p_H_to_D')\n\n\n# In[6]:\n\n\nt1 = ControlledConversion(subject=c['S'],\noutcome=c['E'],\ncontroller=c['I'],\nrate_law=S*I*beta / N)\nt2 = NaturalConversion(subject=c['E'],\noutcome=c['I'],\nrate_law=r_E_to_I*E)\nt3 = NaturalConversion(subject=c['I'],\noutcome=c['R'],\nrate_law=r_I_to_R*p_I_to_R*I)\nt4 = NaturalConversion(subject=c['I'],\noutcome=c['H'],\nrate_law=r_I_to_H*p_I_to_H*I)\nt5 = NaturalConversion(subject=c['H'],\noutcome=c['R'],\nrate_law=r_H_to_R*p_H_to_R*H)\nt6 = NaturalConversion(subject=c['H'],\noutcome=c['D'],\nrate_law=r_H_to_D*p_H_to_D*H)\ntemplates = [t1, t2, t3, t4, t5, t6]\ntm = TemplateModel(\ntemplates=templates,\nparameters=parameters,\ninitials=initials,\ntime=Time(name='t', units=day_units()),\nobservables=observables,\nannotations=Annotations(name='Evaluation Scenario 1 Base model')\n)\nsanity_check_tm(tm)\nam = AMRPetriNetModel(Model(tm))\nsanity_check_amr(am.to_json())```",
"description": "Basic SEIRHD model representation and simulation using the MIRA library. Includes initializing the model with concepts, parameters, and initial conditions, followed by creating a set of templates representing the disease transmission dynamics. A template model is instantiated and sanity-checked before creating an antimicrobial resistance Petri net model, which is then serialized to a JSON file."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/evaluation_2023.07/scenario1.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.modeling.viz import GraphicalModel\n\n```",
"description": "Display of the basic SEIRHD model in a Jupyter notebook environment using the GraphicalModel class."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/evaluation_2023.07/scenario1.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import sympy\nfrom copy import deepcopy as _d\nfrom mira.metamodel import *\nfrom mira.modeling import Model\nfrom mira.modeling.amr.petrinet import AMRPetriNetModel\nfrom mira.modeling.viz import GraphicalModel\nimport jsonschema\n# ## Part 1/ii\n# 1) Masking Forecasts: For this question, assume that a masking policy will go into place on April 15th, 2020\n# a) Starting from April 3rd, 2020, forecast the next four weeks of the pandemic (for cases, hospitalizations, and deaths) assuming the following constant levels of masking compliance: 40%, 60%, and 80%. Assume that any person who complies with the masking policy is wearing a surgical mask. How does compliance affect forecasted cases, hospitalizations, and deaths?\n#\n# (1) Introduce a modification term to \u03b2 as described in Srivastav et. al. (DOI: 10.3934/mbe.2021010): (1 \u2212 \ud835\udf16\ud835\udc5a\ud835\udc50\ud835\udc5a), where \ud835\udc50\ud835\udc5a is the fraction of the population that wear face masks correctly and consistently (i.e. comply with masking policies), and \ud835\udf16\ud835\udc5a is the efficacy of the masks themselves.\n\n# In[8]:\n\n\neps_m = sympy.Symbol('eps_m')\nc_m = sympy.Symbol('c_m')\n\nt1_alt_1 = ControlledConversion(subject=c['S'],\noutcome=c['E'],\ncontroller=c['I'],\nrate_law=S*I*beta*(1-eps_m*c_m) / N)\n\nparameters_alt_1 = _d(parameters)\nparameters_alt_1['eps_m'] = Parameter(name='eps_m', value=0.5, units=dimensionless_units())\nparameters_alt_1['c_m'] = Parameter(name='c_m', value=0.5, units=dimensionless_units())\n\ntm_mask_1 = TemplateModel(\ntemplates=[t1_alt_1, t2, t3, t4, t5, t6],\nparameters=parameters_alt_1,\ninitials=initials,\ntime=Time(name='t', units=day_units()),\nobservables=observables,\nannotations=Annotations(name='Evaluation Scenario 1. Part 1 (ii) Masking type 1')\n)\n\nsanity_check_tm(tm_mask_1)\nam = AMRPetriNetModel(Model(tm_mask_1))\nsanity_check_amr(am.to_json())\nam.to_json_file('eval_scenario1_1_ii_1.json')\n\n```",
"description": "First masking scenario with modifications to the beta parameter to introduce mask efficacy and compliance. A variant of the SEIRHD model with an adjusted transmission rate considering mask usage. The modified model is sanity-checked and serialized."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/evaluation_2023.07/scenario1.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```import sympy\nfrom copy import deepcopy as _d\nfrom mira.metamodel import *\nfrom mira.modeling import Model\nfrom mira.modeling.amr.petrinet import AMRPetriNetModel\nfrom mira.modeling.viz import GraphicalModel\nimport jsonschema\n# (2) Adjust the transmission rate following an intervention period and create a time- varying \u03b2 function, as shown in https://doi.org/10.3390/ijerph18179027\n\n# In[9]:\n\n\nnew_params = {\n'beta_s': Parameter(name='beta_s', value=1, units=per_day_units()),\n'beta_c': Parameter(name='beta_c', value=0.4, units=per_day_units()),\n't_0': Parameter(name='t_0', value=89, unts=day_units, units=day_units()),\n'kappa': Parameter(name='kappa', value=5/11, units=per_day_units()),\n'k': Parameter(name='k', value=5.0, units=dimensionless_units()),\n}\nbeta_s, beta_c, t_0, kappa, k, t = sympy.symbols('beta_s beta_c t_0 kappa k t')\nm_1 = (beta_s - beta_c) / (1 + sympy.exp(-k*(t_0-t))) + beta_c\nbeta_time_varying = kappa*m_1\n\nt1_alt_2 = ControlledConversion(subject=c['S'],\noutcome=c['E'],\ncontroller=c['I'],\nrate_law=S*I*beta_time_varying / N)\n\nparams_alt_2 = _d(parameters)\nparams_alt_2.update(new_params)\n\ntm_mask_2 = TemplateModel(\ntemplates=[t1_alt_2, t2, t3, t4, t5, t6],\nparameters=params_alt_2,\ninitials=initials,\ntime=Time(name='t', units=day_units()),\nobservables=observables,\nannotations=Annotations(name='Evaluation Scenario 1. Part 1 (ii) Masking type 2')\n)\n\nsanity_check_tm(tm_mask_2)\nam = AMRPetriNetModel(Model(tm_mask_2))\nsanity_check_amr(am.to_json())\nam.to_json_file('eval_scenario1_1_ii_2.json')\n```",
"description": "Second masking scenario introducing time-varying beta reflecting the intervention's effect over time. Parameters for the new beta computation are defined, and the modified model is serialized after sanity checks."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/evaluation_2023.07/scenario1.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from mira.metamodel import *\nfrom mira.modeling import Model\nfrom mira.modeling.amr.petrinet import AMRPetriNetModel\nfrom mira.modeling.viz import GraphicalModel\nimport jsonschema\n# (3) Add compartments and transitions to represent mask wearing/non-mask\n# wearing populations. See examples for several similar options of representing this addition; you may implement the update in a way that represents one or a combination of these approaches, or has an otherwise analogous effect: https://doi.org/10.1098/rspa.2020.0376, https://doi.org/10.1016/j.idm.2020.04.001, https://doi.org/10.1016/j.chaos.2020.110599, https://doi.org/10.1177/0272989X211019029\n#\n#\n# The following table describes the strategies from the four papers referenced by the evaluation scenario 1 for stratifying models based on masking compliance:\n#\n# | Title | Compartments | Stratification |\n# |------|------------|------------|\n# | [A modelling framework to assess the likely effectiveness of facemasks in combination with 'lock-down' in managing the COVID-19 pandemic](https://doi.org/10.1098/rspa.2020.0376) | Includes susceptible, exposed, asymptomatic, symptomatic, and removed. | Stratification applied to all compartments. |\n# | [To mask or not to mask: Modeling the potential for face mask use by the general public to curtail the COVID-19 pandemic](https://doi.org/10.1016/j.idm.2020.04.001) | Includes susceptible, exposed, symptomatic infectious, hospitalized, asymptomatic infectious, and recovered. | Stratification was applied to all compartments |\n# | [Preventing epidemics by wearing masks: An application to COVID-19](https://doi.org/10.1016/j.chaos.2020.110599) | Includes susceptible, exposed, infected, and recovered. | Stratification was applied to all compartments. |\n# | [Effectiveness of Face Masks in Reducing the Spread of COVID-19: A Model-Based Analysis](https://doi.org/10.1177/0272989X211019029) | Includes susceptible, exposed, unconfirmed infected, confirmed infected, recovered confirmed infected, recovered unconfirmed infeced, and dead. | Masking transition exists between susceptible, exposed, and unconfirmed infected. Assumes confirmed infected have masks. All parts but confirmed infected, dead, and recovered confirmed infected have masks. |\n\n# In[10]:\n\n\ntm_mask_3 = stratify(tm_mask_1,\nkey='masking',\nstrata=['noncompliant', 'compliant'],\nstructure=[['noncompliant', 'compliant']],\ndirected=False,\nconcepts_to_stratify={'S', 'E', 'I'},\nparams_to_stratify={'eps_m', 'c_m'},\ncartesian_control=True)\ntm_mask_3.annotations.name = 'Evaluation Scenario 1. Part 1 (ii) Masking type 3'\n\n\n# In[11]:\n\n\nsanity_check_tm(tm_mask_3)\nam = AMRPetriNetModel(Model(tm_mask_3))\nsanity_check_amr(am.to_json())\nam.to_json_file('eval_scenario1_1_ii_3.json')\n\n\n# In[12]:\n\n```",
"description": "Third masking scenario demonstrating the stratification of the model by masking compliance. The simulation infrastructure supports the stratification of concepts and parameters, showing a diversification of the population in terms of mask usage."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/evaluation_2023.07/scenario1.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```from copy import deepcopy as _d\nfrom mira.metamodel import *\nfrom mira.modeling import Model\nfrom mira.modeling.amr.petrinet import AMRPetriNetModel\nfrom mira.modeling.viz import GraphicalModel\nimport pandas as pd\nimport jsonschema\n# ## Part 2/c\n# Social Distancing Forecasts. Instead of providing masks for all residents, the governor is interested in enforcing a social distancing policy to reduce contact between individuals. As before, begin with an SEIRHD model as described in the scenario description. For this\n# 4\n# question, assume that a social distancing policy will go into place on April 15th, 2020. Starting from April 3rd, 2020, forecast the next four weeks of the pandemic (for cases, hospitalizations, and deaths)\n#\n#\n# (2) (TA2 Model Stratification Workflow) As before, begin with an SEIRHD model as described in the scenario description. Stratify it by 18 age groups (0-4, 5-9, 10-14, 15-19, 20-24, ..., 80-84, 85+). For simplification purposes, before performing the stratification, you may remove the Exposed compartment. The final result for this question will be a stratified SIRHD model. Use the following data for population estimates / initial conditions: https://www.health.ny.gov/statistics/vital_statistics/2016/table01.htm\n# Update parameters and probabilities introduced from stratification, with reasonable assumptions, from (for example) the following resources: https://www.cdc.gov/coronavirus/2019-ncov/hcp/planning-scenarios.html\n# 5\n# https://docs.buckymodel.com/en/latest/input_output.html https://doi.org/10.3389/fpubh.2020.598547 https://doi.org/10.3201/eid2611.201074\n\n# In[13]:\n\n\nages = [f'{i*5}_{(i+1)*5-1}' for i in range(17)]\nages.append('85')\n\n\n# In[14]:\n\n\nt1 = ControlledConversion(subject=c['S'],\noutcome=c['I'],\ncontroller=c['I'],\nrate_law=S*I*beta / N)\nt2 = NaturalConversion(subject=c['I'],\noutcome=c['R'],\nrate_law=r_I_to_R*p_I_to_R*I)\nt3 = NaturalConversion(subject=c['I'],\noutcome=c['H'],\nrate_law=r_I_to_H*p_I_to_H*I)\nt4 = NaturalConversion(subject=c['H'],\noutcome=c['R'],\nrate_law=r_H_to_R*p_H_to_R*H)\nt5 = NaturalConversion(subject=c['H'],\noutcome=c['D'],\nrate_law=r_H_to_D*p_H_to_D*H)\n\n\nparams_sirhd = _d(parameters)\nparams_sirhd.pop('r_E_to_I')\ninitials_sirhd = _d(initials)\ninitials_sirhd.pop('E')\n\ntm_sirhd = TemplateModel(\ntemplates=[t1, t2, t3, t4, t5],\nparameters=parameters,\ninitials=initials,\ntime=Time(name='t', units=day_units()),\nobservables=observables,\nannotations=Annotations(name='Evaluation Scenario 1 SIRHD model')\n)\n\nsanity_check_tm(tm_sirhd)\nam = AMRPetriNetModel(Model(tm_sirhd))\nsanity_check_amr(am.to_json())\nam.to_json_file('eval_scenario1_2_sirhd.json')\n\n\ntm_age = stratify(tm_sirhd,\nkey='age',\nstrata=ages,\nstructure=[],\ndirected=False,\nparams_to_stratify={'beta'},\ncartesian_control=True)\ntm_age.annotations.name = 'Evaluation Scenario 1 SIRHD model age stratified'\n\n\nsanity_check_tm(tm_age)\nam = AMRPetriNetModel(Model(tm_age))\nsanity_check_amr(am.to_json())\nam.to_json_file('eval_scenario1_2_sirhd_age.json')\n```",
"description": "Social distancing scenario through age stratification of the SIRHD model. The model is simplified by removing the Exposed compartment before stratifying by age. Age-specific parameter modifications could be considered for realism. The stratified model is sanity-checked and visualized."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/hackathon_2023.07/scenario1-2-wastewater.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\nimport sympy\nimport itertools\nfrom mira.metamodel import *\nfrom mira.modeling import Model\nfrom mira.modeling.amr.petrinet import AMRPetriNetModel\nfrom mira.modeling.viz import GraphicalModel\n\n# In[1]:\n\n\nimport sympy\nimport itertools\nfrom mira.metamodel import *\nfrom mira.modeling import Model\nfrom mira.modeling.amr.petrinet import AMRPetriNetModel\nfrom mira.modeling.viz import GraphicalModel\n\n\n# In[2]:\n\n\n# Define units and symbols\nperson_units = lambda: Unit(expression=sympy.Symbol('person'))\nday_units = lambda: Unit(expression=sympy.Symbol('day'))\nperson_per_day_units = lambda: Unit(expression=sympy.Symbol('person')/sympy.Symbol('day'))\nper_day_units = lambda: Unit(expression=1/sympy.Symbol('day'))\ndimensionless_units = lambda: Unit(expression=sympy.Integer('1'))\nper_day_per_person_units = lambda: Unit(expression=1/(sympy.Symbol('day')*sympy.Symbol('person')))\nper_person_units = lambda: Unit(expression=1/sympy.Symbol('person'))\n\nS, E, I, R, V, Y, N, kappa, beta, beta_s, beta_c, k, t_0, t, alpha, delta, rho, gamma, rho_V, rho_Y, br, iota, mu_EI, mu_IR, tau, T_0, tau_star_0, V_0, Q_0 = \\\nsympy.symbols('S E I R V Y N kappa beta beta_s beta_c k t_0 t alpha delta rho gamma rho_V rho_Y br iota mu_EI mu_IR tau T_0 tau_star_0 V_0 Q_0')\n\n\n# In[3]:\n\n\n# Setup\n# FIXME: use the proper rate values and symbols from the paper\nconcepts_fazli = {\n'S': Concept(name='S', units=person_units(), identifiers={'ido': '0000514'}),\n'E': Concept(name='E', units=person_units(), identifiers={'apollosv': '0000154'}),\n'I': Concept(name='I', units=person_units(), identifiers={'ido': '0000511'}),\n'R': Concept(name='R', units=person_units(), identifiers={'ido': '0000592'}),\n# Maybe the count for V is RNA snippets?\n'V': Concept(name='V', units=dimensionless_units(), identifiers={\"chebi\": \"33697\"}), # RNA\n'Y': Concept(name='Y', units=dimensionless_units(), identifiers={\"cemo\": \"number_of_cases_by_testing\"}),\n}\n\nP = 50_000\nN_0_fazli = 0.05*P\n\nparameters_fazli = {\n# alpha is a mixing parameter in this model and used as an exponent\n'alpha': Parameter(name='alpha', value=1.07, units=dimensionless_units()),\n'N': Parameter(name='N', value=N_0_fazli, units=person_units()),\n# 't_0': Parameter(name='t_0', value=89, unts=day_units, units=day_units()),\n# 'kappa': Parameter(name='kappa', value=5/11, units=per_day_units()),\n# 'k': Parameter(name='k', value=5.0, units=dimensionless_units()),\n'iota': Parameter(name='iota', value=4.27, units=person_units()),\n'mu_EI': Parameter(name='mu_EI', value=1/6, units=per_day_units()),\n'mu_IR': Parameter(name='mu_IR', value=1/7.7, units=per_day_units()),\n'rho_V': Parameter(name='rho_V', value=3760, units=per_person_units()),\n'rho_Y': Parameter(name='rho_Y', value=0.14, units=per_person_units()),\n'br': Parameter(name='br', value=7.68, units=person_units())\n}\n\ninitials_fazli = {\n'S': Initial(concept=Concept(name='S'), value=0.95*N_0_fazli),\n'E': Initial(concept=Concept(name='E'), value=0.04*N_0_fazli),\n'I': Initial(concept=Concept(name='I'), value=0.01*N_0_fazli),\n'R': Initial(concept=Concept(name='R'), value=0),\n'V': Initial(concept=Concept(name='V'), value=0), # Verify with paper\n'Y': Initial(concept=Concept(name='Y'), value=0), # Verify with paper\n}\n\n# FIXME\n# Might want to spell out the reported cases, Y, as a function of I?\n# and wastewater, V, as a function of E and I?\nobservables_fazli = {\n'wastewater_rna': Observable(name='wastewater_rna', expression=SympyExprStr(V)),\n'reported_cases': Observable(name='reported_cases', expression=SympyExprStr(rho_V*I))\n}\n\n\n# In[4]:\n\n\n# model creation\n# FIXME: fix rates\n\n# Full equation also multiplies with a Gamma white noise here\n# Infection rate, see equation 15 in Fazli et al.\nmu_SE = beta*(I+iota)**alpha/N\n\n# Birthrate/people entering a susceptible state from\n# the outside population\nt0 = NaturalProduction(outcome=concepts_fazli['S'],\nrate_law=br)\n# Exposure\nt1 = ControlledConversion(subject=concepts_fazli['S'],\noutcome=concepts_fazli['E'],\ncontroller=concepts_fazli['I'],\nrate_law=mu_SE)\n# Infection\nt2 = NaturalConversion(subject=concepts_fazli['E'],\noutcome=concepts_fazli['I'],\nrate_law=mu_EI*E)\n# Removal/recovery\nt3 = NaturalConversion(subject=concepts_fazli['I'],\noutcome=concepts_fazli['R'],\nrate_law=mu_IR*I)\n# Shedding; both E and I shed\nt4 = GroupedControlledProduction(\ncontrollers=[concepts_fazli[\"E\"], concepts_fazli[\"I\"]],\noutcome=concepts_fazli[\"V\"],\nrate_law=rho_V*(E+I), # Verify with paper\n)\n# Testing/case - people from I are tested at a rate of rho_Y per day\n# t5 = ControlledProduction(\n# controller=concepts['I'],\n# outcome=concepts['Y'],\n# rate_law=rho_Y*I, # Verfiy with paper\n# )\ntemplates_fazli = [t0, t1, t2, t3, t4]#, t5]\ntm_fazli = TemplateModel(\ntemplates=templates_fazli,\ninitials=initials_fazli,\ntime=Time(name='t', units=day_units()),\nobservables=observables_fazli,\nannotations=Annotations(name='Scenario 1 q2 fazli')\n)\nAMRPetriNetModel(Model(tm_fazli)).to_json_file('scenario1_q2_fazli.json')```",
"description": "Setting up and modeling the Fazli et al. SEIR model with mira. This includes defining units, symbols, concepts, parameters, initials, observables, and the template model, followed by converting the model to JSON and visualizing it."
},
{
"origination_source_type": "code_file",
"origination_source": "src/beaker_bio_context/examples/hackathon_2023.07/scenario1-2-wastewater.ipynb",
"origination_method": "extract_from_library_automatic",
"code": "```#!/usr/bin/env python\n# coding: utf-8\nimport sympy\nfrom mira.metamodel import *\nfrom mira.modeling import Model\nfrom mira.modeling.amr.petrinet import AMRPetriNetModel\nfrom mira.modeling.viz import GraphicalModel\n\nperson_units = lambda: Unit(expression=sympy.Symbol('person'))\nday_units = lambda: Unit(expression=sympy.Symbol('day'))\nper_day_units = lambda: Unit(expression=1/sympy.Symbol('day'))\ndimensionless_units = lambda: Unit(expression=sympy.Integer('1'))\nper_person_units = lambda: Unit(expression=1/sympy.Symbol('person'))\n\n# In[6]:\n\n\n# Setup\n# FIXME: use the proper rate values and symbols from the paper\nconcepts_mcmahan = {\n'S': Concept(name='S', units=person_units(), identifiers={'ido': '0000514'}),\n'E': Concept(name='E', units=person_units(), identifiers={'apollosv': '0000154'}),\n'I': Concept(name='I', units=person_units(), identifiers={'ido': '0000511'}),\n'R': Concept(name='R', units=person_units(), identifiers={'ido': '0000592'}),\n'V': Concept(name='V', units=dimensionless_units(), identifiers={\"chebi\": \"33697\"}),\n'Y': Concept(name='Y', units=dimensionless_units(), identifiers={\"cemo\": \"number_of_cases_by_testing\"}),\n}\n\nN_0_mcmahan = 25_000\n\nparameters_mcmahan = {\n# fixme: get the final beta of the paper, they tried several\n'beta': Parameter(name='beta', value=1/5, units=per_day_units()),\n'gamma': Parameter(name='gamma', value=1/10, units=per_day_units()),\n'delta': Parameter(name='delta', value=1/5, units=per_day_units()),\n# 'alpha': Parameter(name='alpha', value=1/5, units=per_day_units()),\n# 'rho': Parameter(name='rho', value=1/9, units=per_day_units()),\n'N': Parameter(name='N', value=N_0_mcmahan, units=person_units()),\n't_0': Parameter(name='t_0', value=89, unts=day_units, units=day_units()),\n# D=11, gamma = 1/D, R_0 = 5 and\n# beta = R_0 * gamma * mask(t) so kappa = 5/11\n'kappa': Parameter(name='kappa', value=5/11, units=per_day_units()),\n'k': Parameter(name='k', value=5.0, units=dimensionless_units()),\n}\n\n# FIXME: use the proper rate values and symbols from the paper\ninitials_mcmahan = {\n'S': Initial(concept=Concept(name='S'), value=0.9999*N_0_mcmahan),\n'E': Initial(concept=Concept(name='E'), value=0.00005*N_0_mcmahan),\n'I': Initial(concept=Concept(name='I'), value=0.00005*N_0_mcmahan),\n'R': Initial(concept=Concept(name='R'), value=0),\n'V': Initial(concept=Concept(name='V'), value=0),\n}\n# Rely on symbols created earlier\n# FIXME\n# The function for V is very complicated\n\nT = 280 # Current wastewater temperature\ntau_star = tau_star_0*Q_0**((T-T_0)/10)\nV = V_0*0.5**(tau/tau_star)\n\n# Add to symbols: T_0, tau_star_0, V_0\nobservables_mcmahan = {\n'reported_cases': Observable(\nname='reported_cases',\nexpression=V)\n}\n\n\n# In[7]:\n\n\n# model creation\n# FIXME: fix rates\n\n# Exposure\nt1 = ControlledConversion(subject=concepts_mcmahan['S'],\noutcome=concepts_mcmahan['E'],\ncontroller=concepts_mcmahan['I'],\nrate_law=S*I*beta)\n# Infection/Illness\nt2 = NaturalConversion(subject=concepts_mcmahan['E'],\noutcome=concepts_mcmahan['I'],\nrate_law=alpha*E)\n# Removal/recovery\nt3 = NaturalConversion(subject=concepts_mcmahan['I'],\noutcome=concepts_mcmahan['R'],\nrate_law=gamma*I)\n\ntemplates_mcmahan = [t1, t2, t3]\ntm_mcmahan = TemplateModel(\ntemplates=templates_mcmahan,\nparameters=parameters_mcmahan,\ninitials=initials_mcmahan,\ntime=Time(name='t', units=day_units()),\nobservables=observables_mcmahan,\nannotations=Annotations(name='Scenario 1 q2 mcmahan')\n)\nAMRPetriNetModel(Model(tm_mcmahan)).to_json_file('scenario1_q2_mcmahan.json')\ntm_mcmahan.observables\n\n\n# In[8]:\n\n```",