phyelds 1.1.0__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.
- LICENSE +201 -0
- phyelds/__init__.py +18 -0
- phyelds/abstractions/__init__.py +92 -0
- phyelds/calculus/__init__.py +117 -0
- phyelds/calculus/align.py +27 -0
- phyelds/data/__init__.py +196 -0
- phyelds/internal/__init__.py +129 -0
- phyelds/libraries/__init__.py +0 -0
- phyelds/libraries/collect.py +76 -0
- phyelds/libraries/leader_election.py +81 -0
- phyelds/libraries/spreading.py +59 -0
- phyelds/libraries/time.py +14 -0
- phyelds/libraries/utils.py +19 -0
- phyelds/simulator/__init__.py +165 -0
- phyelds/simulator/actions.py +17 -0
- phyelds/simulator/deployments.py +77 -0
- phyelds/simulator/neighborhood.py +63 -0
- phyelds/simulator/render.py +81 -0
- phyelds/simulator/runner.py +30 -0
- phyelds-1.1.0.dist-info/LICENSE +201 -0
- phyelds-1.1.0.dist-info/METADATA +24 -0
- phyelds-1.1.0.dist-info/RECORD +23 -0
- phyelds-1.1.0.dist-info/WHEEL +4 -0
LICENSE
ADDED
|
@@ -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 2025 Aguzzi Gianluca, Domini Davide
|
|
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.
|
phyelds/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""
|
|
2
|
+
phyelds: A Python library for aggregate computing system with a pythonic interface.
|
|
3
|
+
|
|
4
|
+
This library provides a set of tools for building and running aggregate computing systems.
|
|
5
|
+
|
|
6
|
+
A global engine is used to manage the state and message passing between different contexts.
|
|
7
|
+
In order to use it, you should:
|
|
8
|
+
1. Call `engine.setup(messages, id, state)` to initialize the engine with the current context.
|
|
9
|
+
2. Call an aggregate script
|
|
10
|
+
3. Call `engine.cooldown()` to reset the engine state and get the messages to send.
|
|
11
|
+
4. Store the state for the next iteration.
|
|
12
|
+
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from phyelds.internal import MutableEngine
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
engine = MutableEngine()
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Engine interface: how to implement an aggregate computing engine.
|
|
3
|
+
"""
|
|
4
|
+
from abc import ABC
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Engine(ABC):
|
|
8
|
+
"""
|
|
9
|
+
Abstract base class for the engine. This class should be implemented by the user.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
def __init__(self):
|
|
13
|
+
self.node_id = None
|
|
14
|
+
|
|
15
|
+
def setup(
|
|
16
|
+
self, node_id: int, messages: dict[int, dict[str, any]], state=None
|
|
17
|
+
) -> None:
|
|
18
|
+
"""
|
|
19
|
+
Setup the engine with the current context.
|
|
20
|
+
:param node_id:
|
|
21
|
+
:param messages: The messages to send.
|
|
22
|
+
:param state: The state of the engine.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def enter(self, name: str) -> None:
|
|
26
|
+
"""
|
|
27
|
+
Enter a new context.
|
|
28
|
+
:param name: The name of the context.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
def exit(self) -> None:
|
|
32
|
+
"""
|
|
33
|
+
Exit the current context.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
def current_path(self) -> list[str]:
|
|
37
|
+
"""
|
|
38
|
+
Get the current path of the engine.
|
|
39
|
+
:return: The current path.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
def write_state(self, value: any, stack: list[str]) -> None:
|
|
43
|
+
"""
|
|
44
|
+
Write the state of the engine.
|
|
45
|
+
:param value: The value to write.
|
|
46
|
+
:param stack: The stack of the engine.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
def read_state(self, stack: list[str]) -> any:
|
|
50
|
+
"""
|
|
51
|
+
Read the state of the engine.
|
|
52
|
+
:param stack: The stack of the engine.
|
|
53
|
+
:return: The value of the state.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
def state_trace(self) -> dict[str, any]:
|
|
57
|
+
"""
|
|
58
|
+
Get the state trace of the engine.
|
|
59
|
+
:return: The state trace.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
def forget(self, _self_path):
|
|
63
|
+
"""
|
|
64
|
+
Forget the value store in the engine.
|
|
65
|
+
:param _self_path:
|
|
66
|
+
:return:
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
def send(self, data: any) -> None:
|
|
70
|
+
"""
|
|
71
|
+
Send data to the engine.
|
|
72
|
+
:param data: The data to send.
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
def aligned(self) -> list[int]:
|
|
76
|
+
"""
|
|
77
|
+
Get the aligned ids.
|
|
78
|
+
:return: The aligned ids.
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
def aligned_values(self, path: list[str]) -> dict[int, any]:
|
|
82
|
+
"""
|
|
83
|
+
Get the aligned values.
|
|
84
|
+
:param path: The path of the values.
|
|
85
|
+
:return: The aligned values.
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
def cooldown(self) -> None:
|
|
89
|
+
"""
|
|
90
|
+
Cooldown the engine.
|
|
91
|
+
:return:
|
|
92
|
+
"""
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Core syntax for phyelds.
|
|
3
|
+
It exposes a set of functions that are used to create and manipulate fields,
|
|
4
|
+
as well as to manage the state of the system.
|
|
5
|
+
@aggregate is a decorator that marks a function as an aggregate function,
|
|
6
|
+
Example:
|
|
7
|
+
@aggregate
|
|
8
|
+
def my_function():
|
|
9
|
+
# do something
|
|
10
|
+
return result
|
|
11
|
+
|
|
12
|
+
Then, there is the core syntax of phyelds:
|
|
13
|
+
- remember: used to remember a value across iterations.
|
|
14
|
+
- neighbors: used to get the neighbors of a node.
|
|
15
|
+
- neighbors_distances: used to get the distances to the neighbors.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from phyelds import engine
|
|
19
|
+
from phyelds.calculus.align import AlignContext
|
|
20
|
+
from phyelds.data import State, Field
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def aggregate(func):
|
|
24
|
+
"""
|
|
25
|
+
A decorator for aggregate functions,
|
|
26
|
+
namely each function that is called in the context of a field.
|
|
27
|
+
You can use it in the following way:
|
|
28
|
+
@aggregate
|
|
29
|
+
def my_function():
|
|
30
|
+
# do something
|
|
31
|
+
return result
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def wrapper(*args, **kwargs):
|
|
35
|
+
engine.enter(func.__name__)
|
|
36
|
+
result = func(*args, **kwargs)
|
|
37
|
+
engine.exit()
|
|
38
|
+
return result
|
|
39
|
+
|
|
40
|
+
return wrapper
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@aggregate
|
|
44
|
+
def remember(init):
|
|
45
|
+
"""
|
|
46
|
+
One of the main operator of phyelds TODO
|
|
47
|
+
:param init:
|
|
48
|
+
:return:
|
|
49
|
+
"""
|
|
50
|
+
return State(init, engine.current_path(), engine)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@aggregate
|
|
54
|
+
def neighbors(value):
|
|
55
|
+
"""
|
|
56
|
+
Get the `value` of the neighbors from the current node.
|
|
57
|
+
Example:
|
|
58
|
+
neighbors(context.data["temperature"]) // returns the temperature of the neighbors
|
|
59
|
+
:param value: used to query the neighbors.
|
|
60
|
+
:return: the field representing this value
|
|
61
|
+
"""
|
|
62
|
+
if isinstance(value, Field):
|
|
63
|
+
raise TypeError("Field is not supported as a value")
|
|
64
|
+
engine.send(value)
|
|
65
|
+
values = engine.aligned_values(engine.current_path())
|
|
66
|
+
values[engine.node_id] = value
|
|
67
|
+
return Field(values, engine.node_id)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@aggregate
|
|
71
|
+
def neighbors_distances(position):
|
|
72
|
+
"""
|
|
73
|
+
Get the distances to the neighbors from the current node.
|
|
74
|
+
:param position: the current node position
|
|
75
|
+
:return: the field representing the distances to the neighbors
|
|
76
|
+
"""
|
|
77
|
+
positions = neighbors(position)
|
|
78
|
+
x, y = position
|
|
79
|
+
distances = {}
|
|
80
|
+
for node_id, pos in positions.data.items():
|
|
81
|
+
# pos are x, y tuples
|
|
82
|
+
n_x, n_y = pos
|
|
83
|
+
distances[node_id] = ((x - n_x) ** 2 + (y - n_y) ** 2) ** 0.5
|
|
84
|
+
return Field(distances, engine.node_id)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def align(name: str):
|
|
88
|
+
"""
|
|
89
|
+
Used to align a part of the code with the current context,
|
|
90
|
+
creating different non communicating zones
|
|
91
|
+
:param name: what you would like to align on
|
|
92
|
+
:return: the context
|
|
93
|
+
"""
|
|
94
|
+
return AlignContext(name)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def align_right():
|
|
98
|
+
"""
|
|
99
|
+
Typically used in if statements to align the code
|
|
100
|
+
Example:
|
|
101
|
+
if condition:
|
|
102
|
+
with align_left():
|
|
103
|
+
# do something
|
|
104
|
+
else:
|
|
105
|
+
with align_right():
|
|
106
|
+
# do something else
|
|
107
|
+
:return:
|
|
108
|
+
"""
|
|
109
|
+
return align("left")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def align_left():
|
|
113
|
+
"""
|
|
114
|
+
Typically used in if statements to align the code
|
|
115
|
+
See align_right
|
|
116
|
+
"""
|
|
117
|
+
return align("right")
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Alignment context manager for phyelds.
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from phyelds import engine
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class AlignContext:
|
|
10
|
+
"""
|
|
11
|
+
Context manager for alignment in phyelds.
|
|
12
|
+
This context manager is used to align the state of the engine with the
|
|
13
|
+
current context. It should be used in the following way:
|
|
14
|
+
with AlignContext("context_name"):
|
|
15
|
+
# do something
|
|
16
|
+
pass
|
|
17
|
+
|
|
18
|
+
"""
|
|
19
|
+
def __init__(self, name: str):
|
|
20
|
+
self.name = name
|
|
21
|
+
|
|
22
|
+
def __enter__(self):
|
|
23
|
+
engine.enter(self.name)
|
|
24
|
+
return self
|
|
25
|
+
|
|
26
|
+
def __exit__(self, exception_type, exception_value, traceback):
|
|
27
|
+
engine.exit()
|
phyelds/data/__init__.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Internal state class used to manage the state of the system (namely `rep` of field calculus).
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import Any, Dict, Optional, List
|
|
6
|
+
import wrapt
|
|
7
|
+
from phyelds.abstractions import Engine
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Field:
|
|
11
|
+
"""
|
|
12
|
+
Field class used to manage the interactions of between nodes (namely `nbr` of field calculus).
|
|
13
|
+
It provides methods to perform operations on the field, such as addition,
|
|
14
|
+
subtraction, multiplication, and division.
|
|
15
|
+
You should never use it directly, but rather use the `neighbors` function
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
def __init__(self, data: Dict[int, Any], node_id: int) -> None:
|
|
19
|
+
self.data = dict(sorted(data.items()))
|
|
20
|
+
self._iter_index: Optional[int] = None
|
|
21
|
+
self._iter_keys: Optional[List[int]] = None
|
|
22
|
+
self.node_id = node_id
|
|
23
|
+
|
|
24
|
+
def __iter__(self) -> "Field":
|
|
25
|
+
self._iter_index = 0
|
|
26
|
+
self._iter_keys = sorted(self.data.keys())
|
|
27
|
+
return self
|
|
28
|
+
|
|
29
|
+
def __next__(self) -> Any:
|
|
30
|
+
if self._iter_keys is None or self._iter_index is None:
|
|
31
|
+
raise StopIteration
|
|
32
|
+
|
|
33
|
+
if self._iter_index >= len(self._iter_keys):
|
|
34
|
+
self._iter_index = None
|
|
35
|
+
self._iter_keys = None
|
|
36
|
+
raise StopIteration
|
|
37
|
+
|
|
38
|
+
key = self._iter_keys[self._iter_index]
|
|
39
|
+
value = self.data[key]
|
|
40
|
+
self._iter_index += 1
|
|
41
|
+
return value
|
|
42
|
+
|
|
43
|
+
def exclude_self(self) -> dict[int, Any]:
|
|
44
|
+
"""
|
|
45
|
+
Exclude the current node from the field.
|
|
46
|
+
:return: A new Field object with the current node excluded.
|
|
47
|
+
"""
|
|
48
|
+
to_return = self.data.copy()
|
|
49
|
+
to_return.pop(self.node_id, None)
|
|
50
|
+
return to_return
|
|
51
|
+
|
|
52
|
+
def local(self):
|
|
53
|
+
"""
|
|
54
|
+
Get the local value of the current node.
|
|
55
|
+
:return:
|
|
56
|
+
"""
|
|
57
|
+
return self.data.get(self.node_id, None)
|
|
58
|
+
|
|
59
|
+
def select(self, field) -> list:
|
|
60
|
+
"""
|
|
61
|
+
Select the values from the field that are present in the current field.
|
|
62
|
+
:param field: The field to select from.
|
|
63
|
+
:return: A list of values from the current field that are present in the given field.
|
|
64
|
+
"""
|
|
65
|
+
return [
|
|
66
|
+
self.data[k] for k in self.data.keys() & field.data.keys() if field.data[k]
|
|
67
|
+
]
|
|
68
|
+
|
|
69
|
+
# Helper method to apply binary operations
|
|
70
|
+
def _apply_binary_op(self, other, op):
|
|
71
|
+
if isinstance(other, Field):
|
|
72
|
+
return Field(
|
|
73
|
+
{
|
|
74
|
+
k: op(self.data[k], other.data[k])
|
|
75
|
+
for k in self.data.keys() & other.data.keys()
|
|
76
|
+
},
|
|
77
|
+
self.node_id,
|
|
78
|
+
)
|
|
79
|
+
return Field({k: op(v, other) for k, v in self.data.items()}, self.node_id)
|
|
80
|
+
|
|
81
|
+
def __add__(self, other):
|
|
82
|
+
return self._apply_binary_op(other, lambda a, b: a + b)
|
|
83
|
+
|
|
84
|
+
def __sub__(self, other):
|
|
85
|
+
return self._apply_binary_op(other, lambda a, b: a - b)
|
|
86
|
+
|
|
87
|
+
def __mul__(self, other):
|
|
88
|
+
return self._apply_binary_op(other, lambda a, b: a * b)
|
|
89
|
+
|
|
90
|
+
def __truediv__(self, other):
|
|
91
|
+
return self._apply_binary_op(other, lambda a, b: a / b)
|
|
92
|
+
|
|
93
|
+
def __mod__(self, other):
|
|
94
|
+
return self._apply_binary_op(other, lambda a, b: a % b)
|
|
95
|
+
|
|
96
|
+
def __pow__(self, other):
|
|
97
|
+
return self._apply_binary_op(other, lambda a, b: a**b)
|
|
98
|
+
|
|
99
|
+
def __floordiv__(self, other):
|
|
100
|
+
return self._apply_binary_op(other, lambda a, b: a // b)
|
|
101
|
+
|
|
102
|
+
def __and__(self, other):
|
|
103
|
+
return self._apply_binary_op(other, lambda a, b: a & b)
|
|
104
|
+
|
|
105
|
+
def __or__(self, other):
|
|
106
|
+
return self._apply_binary_op(other, lambda a, b: a | b)
|
|
107
|
+
|
|
108
|
+
def __xor__(self, other):
|
|
109
|
+
return self._apply_binary_op(other, lambda a, b: a ^ b)
|
|
110
|
+
|
|
111
|
+
def __invert__(self):
|
|
112
|
+
return Field({k: ~v for k, v in self.data.items()}, self.node_id)
|
|
113
|
+
|
|
114
|
+
def __lt__(self, other):
|
|
115
|
+
return self._apply_binary_op(other, lambda a, b: a < b)
|
|
116
|
+
|
|
117
|
+
def __le__(self, other):
|
|
118
|
+
return self._apply_binary_op(other, lambda a, b: a <= b)
|
|
119
|
+
|
|
120
|
+
def __gt__(self, other):
|
|
121
|
+
return self._apply_binary_op(other, lambda a, b: a > b)
|
|
122
|
+
|
|
123
|
+
def __str__(self):
|
|
124
|
+
"""String representation of the field."""
|
|
125
|
+
return self.__repr__()
|
|
126
|
+
|
|
127
|
+
def __repr__(self):
|
|
128
|
+
"""String representation of the field."""
|
|
129
|
+
return f"Field (id: {self.node_id}) -- data: {self.data} -- local: {self.local()}"
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class State(wrapt.ObjectProxy):
|
|
133
|
+
"""
|
|
134
|
+
A wrapper class that delegates operations to the underlying value
|
|
135
|
+
while maintaining state management functionality.
|
|
136
|
+
"""
|
|
137
|
+
|
|
138
|
+
def __init__(self, default: Any, path: List, engine: Engine):
|
|
139
|
+
self.__wrapped__ = default # then it will be updated
|
|
140
|
+
state = engine.read_state(path)
|
|
141
|
+
if state is None:
|
|
142
|
+
value = default
|
|
143
|
+
engine.write_state(default, path)
|
|
144
|
+
else:
|
|
145
|
+
value = state
|
|
146
|
+
super().__init__(value)
|
|
147
|
+
self._self_path = list(path)
|
|
148
|
+
self._self_engine = engine
|
|
149
|
+
|
|
150
|
+
@property
|
|
151
|
+
def value(self) -> Any:
|
|
152
|
+
"""Get the current value."""
|
|
153
|
+
return self.__wrapped__
|
|
154
|
+
|
|
155
|
+
def update(self, new_value: Any) -> Any:
|
|
156
|
+
"""Update the stored value."""
|
|
157
|
+
if isinstance(new_value, State):
|
|
158
|
+
new_value = new_value.value
|
|
159
|
+
self._self_engine.write_state(new_value, self._self_path)
|
|
160
|
+
self.__wrapped__ = new_value
|
|
161
|
+
return self
|
|
162
|
+
|
|
163
|
+
def update_fn(self, fn: callable) -> Any:
|
|
164
|
+
"""Update the stored value using a function."""
|
|
165
|
+
self.__wrapped__ = fn(self.__wrapped__)
|
|
166
|
+
self._self_engine.write_state(self.__wrapped__, self._self_path)
|
|
167
|
+
return self
|
|
168
|
+
|
|
169
|
+
def forget(self):
|
|
170
|
+
"""Forget the stored value."""
|
|
171
|
+
self._self_engine.forget(self._self_path)
|
|
172
|
+
self.__wrapped__ = None
|
|
173
|
+
|
|
174
|
+
def __str__(self):
|
|
175
|
+
"""String representation of the state."""
|
|
176
|
+
return str(self.__wrapped__)
|
|
177
|
+
|
|
178
|
+
def __repr__(self):
|
|
179
|
+
"""String representation of the state."""
|
|
180
|
+
return f"State: {repr(self.__wrapped__)}"
|
|
181
|
+
|
|
182
|
+
def __copy__(self):
|
|
183
|
+
"""Create a shallow copy of the state."""
|
|
184
|
+
return State(self.__wrapped__, self._self_path, self._self_engine)
|
|
185
|
+
|
|
186
|
+
def __deepcopy__(self, memo):
|
|
187
|
+
"""Create a deep copy of the state."""
|
|
188
|
+
return self.__copy__()
|
|
189
|
+
|
|
190
|
+
def __reduce__(self):
|
|
191
|
+
"""Reduce the state for pickling."""
|
|
192
|
+
return self.__wrapped__
|
|
193
|
+
|
|
194
|
+
def __reduce_ex__(self, protocol):
|
|
195
|
+
"""Reduce the state for pickling."""
|
|
196
|
+
return self.__reduce__()
|