bigraph-schema 0.0.71__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of bigraph-schema might be problematic. Click here for more details.

@@ -0,0 +1,243 @@
1
+ """
2
+ Utility functions for working with bigraph schemas
3
+ """
4
+
5
+ import collections
6
+ import numpy as np
7
+
8
+
9
+ NONE_SYMBOL = '!nil'
10
+
11
+ DTYPE_MAP = {
12
+ 'float': 'float64',
13
+ 'integer': 'int64',
14
+ 'string': 'str'}
15
+
16
+ overridable_schema_keys = {'_type', '_default', '_check', '_apply', '_serialize', '_deserialize', '_fold', '_divide',
17
+ '_slice', '_bind', '_merge', '_type_parameters', '_value', '_description', '_inherit'}
18
+
19
+ # nonoverridable_schema_keys = type_schema_keys - overridable_schema_keys
20
+
21
+ merge_schema_keys = (
22
+ '_ports',
23
+ '_type_parameters',
24
+ )
25
+
26
+
27
+ def type_merge(dct, merge_dct, path=tuple(), merge_supers=False):
28
+ """
29
+ Recursively merge type definitions, never overwrite.
30
+
31
+ Args:
32
+ - dct: The dictionary to merge into. This dictionary is mutated and ends up being the merged dictionary. If you
33
+ want to keep dct you could call it like ``deep_merge_check(copy.deepcopy(dct), merge_dct)``.
34
+ - merge_dct: The dictionary to merge into ``dct``.
35
+ - path: If the ``dct`` is nested within a larger dictionary, the path to ``dct``. This is normally an empty tuple
36
+ (the default) for the end user but is used for recursive calls.
37
+ Returns:
38
+ - dct
39
+ """
40
+ for k in merge_dct:
41
+ if not k in dct or k in overridable_schema_keys:
42
+ dct[k] = merge_dct[k]
43
+ elif k in merge_schema_keys or isinstance(
44
+ dct[k], dict
45
+ ) and isinstance(
46
+ merge_dct[k], collections.abc.Mapping
47
+ ):
48
+ type_merge(
49
+ dct[k],
50
+ merge_dct[k],
51
+ path + (k,),
52
+ merge_supers)
53
+
54
+ else:
55
+ raise ValueError(
56
+ f'cannot merge types at path {path + (k,)}:\n'
57
+ f'{dct}\noverwrites \'{k}\' from\n{merge_dct}')
58
+
59
+ return dct
60
+
61
+
62
+ def visit_method(schema, state, method, values, core):
63
+ """
64
+ Visit a method for a schema and state and apply it, returning the result
65
+ """
66
+ schema = core.access(schema)
67
+ method_key = f'_{method}'
68
+
69
+ # TODO: we should probably cache all this
70
+ if isinstance(state, dict) and method_key in state:
71
+ visit = core.find_method(
72
+ {method_key: state[method_key]},
73
+ method_key)
74
+ elif method_key in schema:
75
+ visit = core.find_method(
76
+ schema,
77
+ method_key)
78
+ else:
79
+ visit = core.find_method(
80
+ 'any',
81
+ method_key)
82
+
83
+ result = visit(
84
+ schema,
85
+ state,
86
+ values,
87
+ core)
88
+
89
+ return result
90
+
91
+
92
+ def is_empty(value):
93
+ if isinstance(value, np.ndarray):
94
+ return False
95
+ elif value is None or value == {}:
96
+ return True
97
+ else:
98
+ return False
99
+
100
+
101
+ def union_keys(schema, state):
102
+ keys = {}
103
+ for key in schema:
104
+ keys[key] = True
105
+ for key in state:
106
+ keys[key] = True
107
+
108
+ return keys
109
+ # return set(schema.keys()).union(state.keys())
110
+
111
+
112
+ def tuple_from_type(tuple_type):
113
+ if isinstance(tuple_type, tuple):
114
+ return tuple_type
115
+
116
+ elif isinstance(tuple_type, list):
117
+ return tuple(tuple_type)
118
+
119
+ elif isinstance(tuple_type, dict):
120
+ tuple_list = [
121
+ tuple_type[f'_{parameter}']
122
+ for parameter in tuple_type['_type_parameters']]
123
+
124
+ return tuple(tuple_list)
125
+ else:
126
+ raise Exception(f'do not recognize this type as a tuple: {tuple_type}')
127
+
128
+
129
+ def array_shape(core, schema):
130
+ if '_type_parameters' not in schema:
131
+ schema = core.access(schema)
132
+ parameters = schema.get('_type_parameters', [])
133
+
134
+ return tuple([
135
+ int(schema[f'_{parameter}'])
136
+ for parameter in schema['_type_parameters']])
137
+
138
+
139
+ def lookup_dtype(data_name):
140
+ data_name = data_name or 'string'
141
+ dtype_name = DTYPE_MAP.get(data_name)
142
+ if dtype_name is None:
143
+ raise Exception(f'unknown data type for array: {data_name}')
144
+
145
+ return np.dtype(dtype_name)
146
+
147
+
148
+ def read_datatype(data_schema):
149
+ return lookup_dtype(
150
+ data_schema['_type'])
151
+
152
+
153
+ def read_shape(shape):
154
+ return tuple([
155
+ int(x)
156
+ for x in tuple_from_type(
157
+ shape)])
158
+
159
+
160
+ def compare_dicts(a, b):
161
+ if isinstance(a, dict) and isinstance(b, dict):
162
+ result = {}
163
+ for key in union_keys(a, b):
164
+ if key in a:
165
+ if key in b:
166
+ inner = compare_dicts(a[key], b[key])
167
+ if inner:
168
+ result[key] = inner
169
+ else:
170
+ result[key] = f'A: {a[key]}\nB: (missing)'
171
+ else:
172
+ result[key] = f'A: (missing)\nB: {b[key]}'
173
+ if result:
174
+ return result
175
+ else:
176
+ if a != b:
177
+ return f'A: {a}\nB: {b}'
178
+
179
+
180
+ def get_path(tree, path):
181
+ """
182
+ Given a tree and a path, find the subtree at that path
183
+
184
+ Args:
185
+ - tree: the tree we are looking in (a nested dict)
186
+ - path: a list/tuple of keys we follow down the tree to find the subtree we are looking for
187
+
188
+ Returns:
189
+ - subtree: the subtree found by following the list of keys down the tree
190
+ """
191
+
192
+ if len(path) == 0:
193
+ return tree
194
+ else:
195
+ head = path[0]
196
+ if not tree or head not in tree:
197
+ return None
198
+ else:
199
+ return get_path(tree[head], path[1:])
200
+
201
+
202
+ def remove_path(tree, path):
203
+ """
204
+ Removes whatever subtree lives at the given path
205
+ """
206
+
207
+ if path is None or len(path) == 0:
208
+ return None
209
+
210
+ upon = get_path(tree, path[:-1])
211
+ if upon is not None:
212
+ del upon[path[-1]]
213
+ return tree
214
+
215
+
216
+ def type_parameters_for(schema):
217
+ parameters = []
218
+ for key in schema['_type_parameters']:
219
+ subschema = schema.get(f'_{key}', 'any')
220
+ parameters.append(subschema)
221
+
222
+ return parameters
223
+
224
+
225
+ def state_instance(dataclass, state):
226
+ if hasattr(dataclass, '__dataclass_fields__'):
227
+ fields = dataclass.__dataclass_fields__
228
+ state = state or {}
229
+
230
+ init = {}
231
+ for key, field in fields.items():
232
+ substate = state_instance(
233
+ field.type,
234
+ state.get(key))
235
+ init[key] = substate
236
+ instance = dataclass(**init)
237
+ # elif get_origin(dataclass) in [typing.Union, typing.Mapping]:
238
+ # instance = state
239
+ else:
240
+ instance = state
241
+ # instance = dataclass(state)
242
+
243
+ return instance
@@ -0,0 +1,52 @@
1
+ Metadata-Version: 2.4
2
+ Name: bigraph-schema
3
+ Version: 0.0.71
4
+ Summary: A serializable type schema for compositional systems biology
5
+ Author: Eran Agmon, Ryan Spangler
6
+ Requires-Python: >=3.7
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ License-File: AUTHORS.md
10
+ Requires-Dist: fire
11
+ Requires-Dist: numpy
12
+ Requires-Dist: orjson
13
+ Requires-Dist: parsimonious
14
+ Requires-Dist: pint
15
+ Requires-Dist: plum-dispatch
16
+ Requires-Dist: pytest
17
+ Requires-Dist: requests>=2.31.0
18
+ Requires-Dist: setuptools
19
+ Requires-Dist: twine>=4.0.2
20
+ Dynamic: license-file
21
+
22
+ # Bigraph-schema
23
+
24
+ [![PyPI version](https://img.shields.io/pypi/v/bigraph-schema.svg)](https://pypi.org/project/bigraph-schema/)
25
+ [![Tutorial](https://img.shields.io/badge/GitHub%20Pages-Tutorial-brightgreen)](https://vivarium-collective.github.io/bigraph-schema/notebooks/demo.html)
26
+
27
+ Welcome to `bigraph-schema` – a library providing a serializable type schema for composite systems simulations.
28
+ This library provides the core of the broader Vivarium 2.0 project.
29
+
30
+ The goal of `bigraph-schema` is to support interoperability and extensibility across composite simulation formats,
31
+ facilitating integration with existing and future modeling platforms. This is achieved by establishing a
32
+ standardized and serializable schema for the complex, hierarchical, and multiscale nature of biological systems.
33
+
34
+ ## Installation
35
+
36
+ To install `bigraph-schema`, you can use pip:
37
+
38
+ ```console
39
+ pip install bigraph-schema
40
+ ```
41
+
42
+ ## Getting Started
43
+
44
+ To get started with bigraph-schema, check out our resources:
45
+
46
+ * [Type System Overview](https://vivarium-collective.github.io/bigraph-schema/notebooks/core.html): A tutorial demonstrating the functionality of bigraph-schema's type system, "core".
47
+ * [Bigraph Schema Basics Tutorial](https://vivarium-collective.github.io/bigraph-viz/notebooks/basics.html): A tutorial covering the essential aspects of the bigraph-schema library.
48
+ This resource will guide you through the core concepts and methods, helping you to master the basic operations.
49
+
50
+ ## License
51
+
52
+ Bigraph-schema is open-source software released under the [Apache 2 License](https://github.com/vivarium-collective/bigraph-schema/blob/main/LICENSE).
@@ -0,0 +1,17 @@
1
+ bigraph_schema/__init__.py,sha256=nm1cg8sphh7Ll2mJ8BPIR7J9KPdt6matrvMIkME0QF0,528
2
+ bigraph_schema/edge.py,sha256=GZfjs7Jn6df9KcdOHuiM7--GXEXiO-ZYA_fqZ2B5Cpk,3241
3
+ bigraph_schema/parse.py,sha256=uJBfkXRr-Z5pcPIWMSup_iFPdHBGmFOxVKyXSN6jNSM,5628
4
+ bigraph_schema/protocols.py,sha256=-IUabYHsw61k0iV10wp5hxjNZanCW72wmfSNJM6C7CE,783
5
+ bigraph_schema/registry.py,sha256=n1Rsv_U_lL1R-seBHbGGqo1wlD3BYlrYT3BBlsL4ggk,9252
6
+ bigraph_schema/tests.py,sha256=_jNrbPl-Ofk8l4z9B4CC851W0xCsWjaYcY7-bvzNU90,67785
7
+ bigraph_schema/type_functions.py,sha256=8Q9fEcDr0fh2Ueb8KuQqVq6hMzgUApYA96ciX0C6MY0,90078
8
+ bigraph_schema/type_system.py,sha256=Pn5FUsiNvRgXdiI4O0bNPULDkItxBlBm3BKPR_7HtPA,53756
9
+ bigraph_schema/type_system_adjunct.py,sha256=aQPGcwES7gdfuRDunGrFHpqhA6BW7OvMsIQCKPGDY0M,16320
10
+ bigraph_schema/units.py,sha256=PaeqYpCot3eFfZdOUoGqhZjobONpgjc8zxFNNSKg0e4,3020
11
+ bigraph_schema/utilities.py,sha256=2DwDjwdy7r6EvbRyuh-qmdJerTBtn_kfXtzObsn2i6s,6313
12
+ bigraph_schema-0.0.71.dist-info/licenses/AUTHORS.md,sha256=1ndh21uie4wWDB9qYiNofzTjITFC_ZSrP_HqFImvcdo,142
13
+ bigraph_schema-0.0.71.dist-info/licenses/LICENSE,sha256=sF9SV-O54AFkJTMLiJaQw0Ngd4QC7nAkzLV3QBIYnC0,11358
14
+ bigraph_schema-0.0.71.dist-info/METADATA,sha256=Zo1efB2aeZnwoHsXPUHSlYOxBqVtGJCH70s0d_Q50-I,2180
15
+ bigraph_schema-0.0.71.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
16
+ bigraph_schema-0.0.71.dist-info/top_level.txt,sha256=zce6hZ5UdrtyAiwHWgN62ErKNHqbuEEL6eadbSvLu6g,15
17
+ bigraph_schema-0.0.71.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,6 @@
1
+ # Authors of Bigraph Schema
2
+
3
+ The maintainers of the Bigraph-Schema project are:
4
+
5
+ * Ryan Spangler (@prismofeverything)
6
+ * Eran Agmon (@eagmon)
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2023 Ryan Spangler and Eran Agmon
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ bigraph_schema