cyberiadaml-py 0.1.0__tar.gz

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.
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
@@ -0,0 +1,28 @@
1
+ Metadata-Version: 2.1
2
+ Name: cyberiadaml-py
3
+ Version: 0.1.0
4
+ Summary: The Python 3 library for processing the CyberiadaML state machine graphs
5
+ Author: L140-beep
6
+ Author-email: kartoshka0302@mail.ru
7
+ Requires-Python: >=3.10,<3.11
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.10
10
+ Requires-Dist: pydantic (>=2.6.1,<3.0.0)
11
+ Requires-Dist: xmltodict (>=0.13.0,<0.14.0)
12
+ Description-Content-Type: text/markdown
13
+
14
+ # The Cyberiada State Machine Python 3 Library
15
+
16
+ The native Python 3 library for processing CyberiadaML - the version of GraphML for storing state machine graphs
17
+ used by the Cyberiada Project.
18
+
19
+ The code is distributed under the Lesser GNU Public License (version 3), the documentation -- under
20
+ the GNU Free Documentation License (version 1.3).
21
+
22
+ ## Requirements
23
+
24
+ * `poetry` (which installs latter libraries)
25
+ * `xmltodict`
26
+ * `pydantic`
27
+ * `types-xmltodict`
28
+
@@ -0,0 +1,14 @@
1
+ # The Cyberiada State Machine Python 3 Library
2
+
3
+ The native Python 3 library for processing CyberiadaML - the version of GraphML for storing state machine graphs
4
+ used by the Cyberiada Project.
5
+
6
+ The code is distributed under the Lesser GNU Public License (version 3), the documentation -- under
7
+ the GNU Free Documentation License (version 1.3).
8
+
9
+ ## Requirements
10
+
11
+ * `poetry` (which installs latter libraries)
12
+ * `xmltodict`
13
+ * `pydantic`
14
+ * `types-xmltodict`
@@ -0,0 +1 @@
1
+ """Library for parsing and building CyberiadaMl schemes."""
@@ -0,0 +1,261 @@
1
+ """Module implements building CyberiadaML schemes."""
2
+ from typing import Dict, Iterable, List
3
+
4
+ from xmltodict import unparse
5
+ from pydantic import RootModel
6
+
7
+ try:
8
+ from cyberiadaml_py.types.cgml_scheme import (
9
+ CGML,
10
+ CGMLDataNode,
11
+ CGMLEdge,
12
+ CGMLGraph,
13
+ CGMLGraphml,
14
+ CGMLKeyNode,
15
+ CGMLNode
16
+ )
17
+ from cyberiadaml_py.types.common import Point, Rectangle
18
+ from cyberiadaml_py.types.elements import (
19
+ AwailableKeys,
20
+ CGMLComponent,
21
+ CGMLElements,
22
+ CGMLInitialState,
23
+ CGMLNote,
24
+ CGMLState,
25
+ CGMLTransition
26
+ )
27
+ except ImportError:
28
+ from .types.cgml_scheme import (
29
+ CGML,
30
+ CGMLDataNode,
31
+ CGMLEdge,
32
+ CGMLGraph,
33
+ CGMLGraphml,
34
+ CGMLKeyNode,
35
+ CGMLNode
36
+ )
37
+ from .types.common import Point, Rectangle
38
+ from .types.elements import (
39
+ AwailableKeys,
40
+ CGMLComponent,
41
+ CGMLElements,
42
+ CGMLInitialState,
43
+ CGMLNote,
44
+ CGMLState,
45
+ CGMLTransition
46
+ )
47
+
48
+
49
+ class CGMLBuilderException(Exception):
50
+ """Logical errors during building CGML scheme."""
51
+
52
+ ...
53
+
54
+
55
+ class CGMLBuilder:
56
+ """Contains functions to build CGML scheme."""
57
+
58
+ def __init__(self) -> None:
59
+ self.scheme: CGML = CGMLBuilder.createEmptyscheme()
60
+
61
+ @staticmethod
62
+ def createEmptyscheme() -> CGML:
63
+ """Create empty CyberiadaML scheme."""
64
+ return CGML(graphml=CGMLGraphml(
65
+ [],
66
+ 'http://graphml.graphdrawing.org/xmlns',
67
+ ))
68
+
69
+ def build(self, elements: CGMLElements) -> str:
70
+ """Build CGML scheme from elements."""
71
+ self.scheme.graphml.key = self._getKeys(elements.keys)
72
+ self.scheme.graphml.data = self._getFormatNode(elements.format)
73
+ self.scheme.graphml.graph = CGMLGraph(
74
+ 'directed',
75
+ 'G',
76
+ )
77
+ nodes: List[CGMLNode] = [*self._getStateNodes(elements.states),
78
+ *self._getNoteNodes(
79
+ list(elements.notes.values())),
80
+ self._getMetaNode(
81
+ elements.meta, elements.platform),
82
+ *self._getComponentsNodes(elements.components)
83
+ ]
84
+ edges: List[CGMLEdge] = [
85
+ *self._getEdges(elements.transitions),
86
+ *self._getComponentsEdges(elements.components)
87
+ ]
88
+ if elements.initial_state is not None:
89
+ nodes.append(
90
+ self._getInitialNode(elements.initial_state))
91
+ edges.append(self._getInitialEdge(
92
+ elements.initial_state.transitionId,
93
+ elements.initial_state.id,
94
+ elements.initial_state.target))
95
+ self.scheme.graphml.graph.node = nodes
96
+ self.scheme.graphml.graph.edge = edges
97
+ scheme: CGML = RootModel[CGML](self.scheme).model_dump(
98
+ by_alias=True, exclude_defaults=True)
99
+ # У model_dump неправильный возвращаемый тип (CGML),
100
+ # поэтому приходится явно показывать линтеру, что это dict
101
+ if isinstance(scheme, dict):
102
+ return unparse(scheme, pretty=True)
103
+ else:
104
+ raise CGMLBuilderException('Internal error: scheme is not dict')
105
+
106
+ def _getComponentsEdges(self,
107
+ components: List[CGMLComponent]) -> List[CGMLEdge]:
108
+ edges: List[CGMLEdge] = []
109
+ for component in components:
110
+ edges.append(CGMLEdge(f'edge_{component.id}', '', component.id))
111
+ return edges
112
+
113
+ def _getComponentsNodes(self,
114
+ components: List[CGMLComponent]) -> List[CGMLNode]:
115
+ nodes: List[CGMLNode] = []
116
+ for component in components:
117
+ node: CGMLNode = CGMLNode(component.id)
118
+ data: List[CGMLDataNode] = []
119
+ data.append(self._nameToData(component.id))
120
+ data.append(self._actionsToData(component.parameters))
121
+ node.data = data
122
+ nodes.append(node)
123
+ return nodes
124
+
125
+ def _getInitialEdge(self, transitionId: str,
126
+ initId: str, target: str) -> CGMLEdge:
127
+ return CGMLEdge(
128
+ transitionId,
129
+ initId,
130
+ target
131
+ )
132
+
133
+ def _getEdges(self,
134
+ transitions: Dict[str, CGMLTransition]) -> List[CGMLEdge]:
135
+ edges: List[CGMLEdge] = []
136
+ for transition in list(transitions.values()):
137
+ edge: CGMLEdge = CGMLEdge(
138
+ transition.id, transition.source, transition.target)
139
+ data: List[CGMLDataNode] = []
140
+ data.append(self._actionsToData(transition.actions))
141
+ if transition.color is not None:
142
+ data.append(self._colorToData(transition.color))
143
+ if transition.position is not None:
144
+ data.append(self._pointToData(transition.position))
145
+ data.extend(transition.unknownDatanodes)
146
+ edge.data = data
147
+ edges.append(edge)
148
+ return edges
149
+
150
+ def _getInitialNode(self, initialState: CGMLInitialState) -> CGMLNode:
151
+ initialNode: CGMLNode = CGMLNode(initialState.id)
152
+ data: List[CGMLDataNode] = []
153
+ if initialState.position is not None:
154
+ data.append(self._pointToData(initialState.position))
155
+ data.append(self._getInitialDataNode())
156
+ initialNode.data = data
157
+ return initialNode
158
+
159
+ def _getInitialDataNode(self) -> CGMLDataNode:
160
+ return CGMLDataNode(
161
+ 'dInitial'
162
+ )
163
+
164
+ def _getMetaNode(self, meta: str, platform: str) -> CGMLNode:
165
+ metaNode: CGMLNode = CGMLNode('')
166
+ data: List[CGMLDataNode] = []
167
+ data.append(self._nameToData(platform))
168
+ data.append(self._actionsToData(meta))
169
+ metaNode.data = data
170
+ return metaNode
171
+
172
+ def _getNoteNodes(self, notes: List[CGMLNote]) -> List[CGMLNode]:
173
+ nodes: List[CGMLNode] = []
174
+ for note in notes:
175
+ data: List[CGMLDataNode] = []
176
+ data.append(self._noteToData(note.text))
177
+ data.append(self._pointToData(note.position))
178
+ data.extend(note.unknownDatanodes)
179
+ nodes.append(CGMLNode(
180
+ note.id,
181
+ data=data
182
+ ))
183
+ return nodes
184
+
185
+ def _pointToData(self, point: Point) -> CGMLDataNode:
186
+ return CGMLDataNode(
187
+ 'dGeometry', None, str(point.x), str(point.y)
188
+ )
189
+
190
+ def _noteToData(self, note_information: str) -> CGMLDataNode:
191
+ return CGMLDataNode('dNote', note_information)
192
+
193
+ def _getStateNodes(self, states: Dict[str, CGMLState]) -> List[CGMLNode]:
194
+ def _getCGMLNode(nodes: Dict[str, CGMLNode],
195
+ state: CGMLState, stateId: str) -> CGMLNode:
196
+ if nodes.get(stateId) is not None:
197
+ return nodes[stateId]
198
+ else:
199
+ node = CGMLNode(stateId)
200
+ data: List[CGMLDataNode] = []
201
+ if state.bounds is not None:
202
+ data.append(self._boundsToData(state.bounds))
203
+ if state.color is not None:
204
+ data.append(self._colorToData(state.color))
205
+ data.append(self._actionsToData(state.actions))
206
+ data.append(self._nameToData(state.name))
207
+ data.extend(state.unknownDatanodes)
208
+ node.data = data
209
+ return node
210
+
211
+ nodes: Dict[str, CGMLNode] = {}
212
+ for stateId in list(states.keys()):
213
+ state: CGMLState = states[stateId]
214
+ node: CGMLNode = _getCGMLNode(nodes, state, stateId)
215
+ if state.parent is not None:
216
+ parentState: CGMLState = states[state.parent]
217
+ parent: CGMLNode = _getCGMLNode(
218
+ nodes, parentState, state.parent)
219
+ if parent.graph is None:
220
+ parent.graph = CGMLGraph(
221
+ node=[node]
222
+ )
223
+ elif isinstance(parent.graph, CGMLGraph):
224
+ if (parent.graph.node is not None and
225
+ isinstance(parent.graph.node, Iterable)):
226
+ parent.graph.node.append(node)
227
+ else:
228
+ parent.graph.node = [node]
229
+ nodes[state.parent] = parent
230
+ else:
231
+ nodes[stateId] = node
232
+ return list(nodes.values())
233
+
234
+ def _nameToData(self, name: str) -> CGMLDataNode:
235
+ return CGMLDataNode('dName', name)
236
+
237
+ def _colorToData(self, color: str) -> CGMLDataNode:
238
+ return CGMLDataNode('dColor', color)
239
+
240
+ def _actionsToData(self, actions: str) -> CGMLDataNode:
241
+ return CGMLDataNode(
242
+ 'dData', actions
243
+ )
244
+
245
+ def _boundsToData(self, bounds: Rectangle) -> CGMLDataNode:
246
+ return CGMLDataNode('dGeometry',
247
+ None,
248
+ str(bounds.x),
249
+ str(bounds.y),
250
+ str(bounds.width),
251
+ str(bounds.height))
252
+
253
+ def _getFormatNode(self, format: str) -> CGMLDataNode:
254
+ return CGMLDataNode('gFormat', format)
255
+
256
+ def _getKeys(self, awaialaibleKeys: AwailableKeys) -> List[CGMLKeyNode]:
257
+ keyNodes: List[CGMLKeyNode] = []
258
+ for key in list(awaialaibleKeys.keys()):
259
+ keyNodes.extend(awaialaibleKeys[key])
260
+
261
+ return keyNodes
@@ -0,0 +1,373 @@
1
+ """The module implements parsing CyberiadaML schemes."""
2
+ from collections import defaultdict
3
+ from collections.abc import Iterable
4
+ from typing import Any, Dict, List, Optional
5
+
6
+ from xmltodict import parse
7
+
8
+ try:
9
+ from .types.common import Point, Rectangle
10
+ from .types.cgml_scheme import (
11
+ CGML,
12
+ CGMLDataNode,
13
+ CGMLEdge,
14
+ CGMLGraph,
15
+ CGMLNode
16
+ )
17
+ from .types.elements import (
18
+ CGMLComponent,
19
+ CGMLElements,
20
+ AwailableKeys,
21
+ CGMLInitialState,
22
+ CGMLNote,
23
+ CGMLState,
24
+ CGMLTransition
25
+ )
26
+ except ImportError:
27
+ from cyberiadaml_py.types.cgml_scheme import (
28
+ CGML,
29
+ CGMLDataNode,
30
+ CGMLEdge,
31
+ CGMLGraph,
32
+ CGMLNode
33
+ )
34
+ from cyberiadaml_py.types.common import Point, Rectangle
35
+ from cyberiadaml_py.types.elements import (
36
+ CGMLComponent,
37
+ CGMLElements,
38
+ AwailableKeys,
39
+ CGMLInitialState,
40
+ CGMLNote,
41
+ CGMLState,
42
+ CGMLTransition
43
+ )
44
+
45
+
46
+ class CGMLParserException(Exception):
47
+ """Logical errors during parsing CGML scheme."""
48
+
49
+ ...
50
+
51
+
52
+ class CGMLParser:
53
+ """Class that contains functions for parsing CyberiadaML."""
54
+
55
+ def __init__(self) -> None:
56
+ self.elements: CGMLElements = CGMLParser.createEmptyElements()
57
+
58
+ @staticmethod
59
+ def createEmptyElements() -> CGMLElements:
60
+ """Create CGMLElements with empty fields."""
61
+ return CGMLElements(
62
+ states={},
63
+ transitions={},
64
+ components=[],
65
+ platform='',
66
+ format='',
67
+ meta='',
68
+ keys=defaultdict(),
69
+ notes={}
70
+ )
71
+
72
+ def parseCGML(self, graphml: str) -> CGMLElements:
73
+ """
74
+ Parse CyberiadaGraphml scheme.
75
+
76
+ Args:
77
+ graphml (str): CyberiadaML scheme.
78
+
79
+ Returns:
80
+ CGMLElements: notes, states, transitions,\
81
+ initial state and components
82
+ Raises:
83
+ CGMLParserException('Data node with key "gFormat" is empty'):\
84
+ content of <data key='gFormat'> is None
85
+ CGMLParserException('Data node with key "gFormat" is missing'):\
86
+ <data key='gFormat'> doesn't exist in graphml->data.s
87
+ CGMLParserException('No position for note!):\
88
+ <node>, that contains <data key='dNote'>, graphml
89
+ doesn't contains <data key='dGeometry' x='...' y='...'>
90
+ CGMLParserException('Unknown key "key" for "node-type",\
91
+ did you forgot ...'):\
92
+ using an undeclarated key
93
+ CGMLParserException('<node-type> with key\
94
+ dGeometry doesnt have x, y properties'): \
95
+ <data key='dGeometry'> must contain at least x and y\
96
+ properties (width and height are additional)
97
+ ValidationError(...): pydatinc's validation error, occurs when\
98
+ the scheme doesn't match the format.
99
+ """
100
+ self.elements = CGMLParser.createEmptyElements()
101
+ cgml = CGML(**parse(graphml))
102
+ self.elements.format = self._getFormat(cgml)
103
+ if self.elements.format != 'Cyberiada-GraphML':
104
+ raise CGMLParserException(
105
+ ('Format must be '
106
+ f'Cyberiada-GraphML, but got {self.elements.format}'))
107
+ self.elements.keys = self._getAwaialbleKeys(cgml)
108
+ graphs: List[CGMLGraph] = self._toList(cgml.graphml.graph)
109
+ states: Dict[str, CGMLState] = {}
110
+ transitions: Dict[str, CGMLTransition] = {}
111
+ notes: Dict[str, CGMLNote] = {}
112
+ for graph in graphs:
113
+ states = states | self._parseGraphNodes(graph)
114
+ transitions = transitions | self._parseGraphEdges(graph)
115
+ try:
116
+ self.elements.platform, self.elements.meta = self._getMeta(
117
+ states[''])
118
+ del states['']
119
+ except KeyError:
120
+ raise CGMLParserException('Meta node is missing')
121
+ for stateId in list(states.keys()):
122
+ state, isInit = self._processStateData(states[stateId], stateId)
123
+ if isinstance(state, CGMLNote):
124
+ notes[state.id] = state
125
+ del states[stateId]
126
+ elif isinstance(state, CGMLState):
127
+ if isInit:
128
+ if self.elements.initial_state is not None:
129
+ raise CGMLParserException('Double init states')
130
+ position: Point | None = None
131
+ if state.bounds is not None:
132
+ position = Point(state.bounds.x, state.bounds.y)
133
+ self.elements.initial_state = CGMLInitialState(
134
+ transitionId='', id=stateId,
135
+ target='', position=position)
136
+ del states[stateId]
137
+ else:
138
+ states[stateId] = state
139
+ else:
140
+ raise CGMLParserException(
141
+ 'Internal error: Unknown type of node')
142
+ # TODO Вынести в отдельные функции
143
+ componentIds: List[str] = []
144
+ for transition in list(transitions.values()):
145
+ processedTransition: CGMLTransition = self._processEdgeData(
146
+ transition)
147
+ if (self.elements.initial_state is not None and
148
+ (processedTransition.source ==
149
+ self.elements.initial_state.id)):
150
+ self.elements.initial_state.target = processedTransition.target
151
+ self.elements.initial_state\
152
+ .transitionId = processedTransition.id
153
+ elif transition.source == '':
154
+ componentIds.append(transition.target)
155
+ else:
156
+ self.elements.transitions[transition.id] = processedTransition
157
+ for componentId in componentIds:
158
+ componentState: CGMLState | None = states.get(componentId)
159
+ if componentState is None:
160
+ raise CGMLParserException('Unknown component node')
161
+ self.elements.components.append(CGMLComponent(
162
+ id=componentId,
163
+ parameters=componentState.actions
164
+ )) # TODO: raise exception if smth else
165
+ del states[componentId]
166
+ self.elements.states = states
167
+ self.elements.notes = notes
168
+ return self.elements
169
+
170
+ def _getDataContent(self, dataNode: CGMLDataNode) -> str:
171
+ return dataNode.content if dataNode.content is not None else ''
172
+
173
+ def _processEdgeData(self, transition: CGMLTransition) -> CGMLTransition:
174
+ newTransition = CGMLTransition(
175
+ id=transition.id,
176
+ source=transition.source,
177
+ target=transition.target,
178
+ actions=transition.actions,
179
+ unknownDatanodes=[]
180
+ )
181
+ for dataNode in transition.unknownDatanodes:
182
+ for keyNode in self.elements.keys['edge']:
183
+ if dataNode.key == keyNode.id:
184
+ break
185
+ else:
186
+ raise CGMLParserException(
187
+ (f'Unknown key {dataNode.key} for edge, did you forgot: '
188
+ f'"<key id="{dataNode.key}" for="edge"/>"?'))
189
+ match dataNode.key:
190
+ case 'dData':
191
+ newTransition.actions = self._getDataContent(dataNode)
192
+ case 'dGeometry':
193
+ if dataNode.x is None or dataNode.y is None:
194
+ raise CGMLParserException(
195
+ 'Edge with key dGeometry\
196
+ doesnt have x, y properties')
197
+ newTransition.position = Point(
198
+ float(dataNode.x), float(dataNode.y))
199
+ case 'dColor':
200
+ newTransition.color = self._getDataContent(dataNode)
201
+ case _:
202
+ newTransition.unknownDatanodes.append(dataNode)
203
+ return newTransition
204
+
205
+ def _processStateData(self,
206
+ state: CGMLState,
207
+ stateId: str) -> tuple[CGMLState | CGMLNote, bool]:
208
+ """Return tuple[CGMLState | CGMLNote, isInit]."""
209
+ # no mutations? B^)
210
+ newState = CGMLState(
211
+ name=state.name,
212
+ actions=state.actions,
213
+ unknownDatanodes=[],
214
+ bounds=state.bounds,
215
+ parent=state.parent
216
+ )
217
+ isNote: bool = False
218
+ isInit: bool = False
219
+ for dataNode in state.unknownDatanodes:
220
+ match dataNode.key:
221
+ case 'dName':
222
+ newState.name = self._getDataContent(dataNode)
223
+ case 'dGeometry':
224
+ if dataNode.x is None or dataNode.y is None:
225
+ raise CGMLParserException(
226
+ 'Node with key dGeometry\
227
+ doesnt have x, y properties')
228
+ x: float = float(dataNode.x)
229
+ y: float = float(dataNode.y)
230
+
231
+ if (dataNode.width is not None and
232
+ dataNode.height is not None):
233
+ newState.bounds = Rectangle(
234
+ x=x,
235
+ y=y,
236
+ width=float(dataNode.width),
237
+ height=float(dataNode.height)
238
+ )
239
+ else:
240
+ newState.bounds = Rectangle(
241
+ x=x,
242
+ y=y
243
+ )
244
+ case 'dData':
245
+ newState.actions = self._getDataContent(dataNode)
246
+ case 'dNote':
247
+ isNote = True
248
+ newState.actions = self._getDataContent(dataNode)
249
+ case 'dInitial':
250
+ isInit = True
251
+ if isNote:
252
+ raise CGMLParserException('dInit in dNote')
253
+ case 'dColor':
254
+ newState.color = self._getDataContent(dataNode)
255
+ case _:
256
+ newState.unknownDatanodes.append(dataNode)
257
+ if isNote:
258
+ bounds: Rectangle | None = newState.bounds
259
+ if bounds is None:
260
+ raise CGMLParserException('No position for note!')
261
+ else:
262
+ return (CGMLNote(
263
+ id=stateId,
264
+ position=Point(
265
+ x=bounds.x,
266
+ y=bounds.y,
267
+ ),
268
+ text=newState.actions,
269
+ unknownDatanodes=newState.unknownDatanodes
270
+ ), False)
271
+ return (newState, isInit)
272
+
273
+ def _getMeta(self, metaNode: CGMLState) -> tuple[str, str]:
274
+ """Return tuple[platfrom, meta]."""
275
+ dataNodes: List[CGMLDataNode] = self._toList(metaNode.unknownDatanodes)
276
+ platform: str = ''
277
+ meta: str = ''
278
+ for dataNode in dataNodes:
279
+ match dataNode.key:
280
+ case 'dName':
281
+ platform = self._getDataContent(dataNode)
282
+ case 'dData':
283
+ meta = self._getDataContent(dataNode)
284
+ return platform, meta
285
+
286
+ def _toList(self, nodes: List | None | Any) -> List:
287
+ if nodes is None:
288
+ return []
289
+ if isinstance(nodes, list):
290
+ return nodes
291
+ else:
292
+ return [nodes]
293
+
294
+ def _parseGraphEdges(self, root: CGMLGraph) -> Dict[str, CGMLTransition]:
295
+ def _parseEdge(edge: CGMLEdge,
296
+ cgmlTransitions: Dict[str, CGMLTransition]) -> None:
297
+ cgmlTransitions[edge.id] = CGMLTransition(
298
+ id=edge.id,
299
+ source=edge.source,
300
+ target=edge.target,
301
+ actions='',
302
+ unknownDatanodes=self._toList(
303
+ edge.data),
304
+ )
305
+
306
+ cgmlTransitions: Dict[str, CGMLTransition] = {}
307
+ if root.edge is not None:
308
+ if isinstance(root.edge, Iterable):
309
+ for edge in root.edge:
310
+ _parseEdge(edge, cgmlTransitions)
311
+ else:
312
+ _parseEdge(root.edge, cgmlTransitions)
313
+ return cgmlTransitions
314
+
315
+ def _parseGraphNodes(self,
316
+ root: CGMLGraph,
317
+ parent: Optional[str] = None) -> Dict[str, CGMLState]:
318
+ def parseNode(node: CGMLNode) -> Dict[str, CGMLState]:
319
+ cgmlStates: Dict[str, CGMLState] = {}
320
+ cgmlStates[node.id] = CGMLState(
321
+ name='',
322
+ actions='',
323
+ unknownDatanodes=self._toList(node.data),
324
+ )
325
+ if parent is not None:
326
+ cgmlStates[node.id].parent = parent
327
+ graphs: List[CGMLGraph] = self._toList(node.graph)
328
+ for graph in graphs:
329
+ cgmlStates = cgmlStates | self._parseGraphNodes(
330
+ graph, node.id)
331
+
332
+ return cgmlStates
333
+
334
+ cgmlStates: Dict[str, CGMLState] = {}
335
+ if root.node is not None:
336
+ if isinstance(root.node, Iterable):
337
+ for node in root.node:
338
+ cgmlStates = cgmlStates | parseNode(node)
339
+ else:
340
+ cgmlStates = cgmlStates | parseNode(root.node)
341
+ return cgmlStates
342
+
343
+ def _checkDataNodeKey(self, node_name: str, key: str,
344
+ awaialableKeys: AwailableKeys) -> bool:
345
+ return key in awaialableKeys[node_name]
346
+
347
+ # key nodes to comfortable dict
348
+ def _getAwaialbleKeys(self, cgml: CGML) -> AwailableKeys:
349
+ keyNodeDict: AwailableKeys = defaultdict(lambda: [])
350
+ if cgml.graphml.key is not None:
351
+ if isinstance(cgml.graphml.key, Iterable):
352
+ for keyNode in cgml.graphml.key:
353
+ keyNodeDict[keyNode.for_].append(keyNode)
354
+ else:
355
+ keyNodeDict[cgml.graphml.key.for_].append(cgml.graphml.key)
356
+ return keyNodeDict
357
+
358
+ def _getFormat(self, cgml: CGML) -> str:
359
+ # TODO: DRY
360
+ if isinstance(cgml.graphml.data, Iterable):
361
+ for dataNode in cgml.graphml.data:
362
+ if dataNode.key == 'gFormat':
363
+ if dataNode.content is not None:
364
+ return dataNode.content
365
+ raise CGMLParserException(
366
+ 'Data node with key "gFormat" is empty')
367
+ else:
368
+ if cgml.graphml.data.key == 'gFormat':
369
+ if cgml.graphml.data.content is not None:
370
+ return cgml.graphml.data.content
371
+ raise CGMLParserException(
372
+ 'Data node with key "gFormat" is empty')
373
+ raise CGMLParserException('Data node with key "gFormat" is missing')
@@ -0,0 +1,74 @@
1
+ """Module contains types, that representing unprocessed CyberiadaML scheme."""
2
+
3
+ from typing import List, Optional
4
+
5
+ from pydantic.dataclasses import dataclass
6
+ from pydantic import Field, ConfigDict
7
+
8
+
9
+ @dataclass(config=ConfigDict(extra='forbid'))
10
+ class CGMLDataNode:
11
+ """Type representing <data> node."""
12
+
13
+ key: str = Field(alias='@key')
14
+ content: Optional[str] = Field(default=None, alias='#text')
15
+ x: Optional[str] = Field(default=None, alias='@x')
16
+ y: Optional[str] = Field(default=None, alias='@y')
17
+ width: Optional[str] = Field(default=None, alias='@width')
18
+ height: Optional[str] = Field(default=None, alias='@height')
19
+
20
+
21
+ @dataclass(config=ConfigDict(extra='allow'))
22
+ class CGMLKeyNode:
23
+ """Type representing <key> node."""
24
+
25
+ id: str = Field(alias='@id')
26
+ for_: str = Field(alias='@for')
27
+ attr_name: Optional[str] = Field(default=None, alias='@attr.name')
28
+ attr_type: Optional[str] = Field(default=None, alias='@attr.type')
29
+
30
+
31
+ @dataclass(config=ConfigDict(extra='forbid'))
32
+ class CGMLEdge:
33
+ """Type representing <edge> node."""
34
+
35
+ id: str = Field(alias='@id')
36
+ source: str = Field(alias='@source')
37
+ target: str = Field(alias='@target')
38
+ data: Optional[List[CGMLDataNode] | CGMLDataNode] = None
39
+
40
+
41
+ @dataclass(config=ConfigDict(extra='forbid'))
42
+ class CGMLGraph:
43
+ """Type representing <graph> node."""
44
+
45
+ edgedefault: Optional[str] = Field(alias='@edgedefault', default=None)
46
+ id: Optional[str] = Field(alias='@id', default=None)
47
+ node: Optional[List['CGMLNode'] | 'CGMLNode'] = None
48
+ edge: Optional[List[CGMLEdge] | CGMLEdge] = None
49
+
50
+
51
+ @dataclass(config=ConfigDict(extra='forbid'))
52
+ class CGMLNode:
53
+ """Type representing <node> node."""
54
+
55
+ id: str = Field(alias='@id')
56
+ graph: Optional[CGMLGraph | List[CGMLGraph]] = None
57
+ data: List[CGMLDataNode] | CGMLDataNode | None = None
58
+
59
+
60
+ @dataclass(config=ConfigDict(extra='forbid'))
61
+ class CGMLGraphml:
62
+ """Type representing <graphml> node."""
63
+
64
+ data: CGMLDataNode | List[CGMLDataNode]
65
+ xmlns: str = Field(alias='@xmlns')
66
+ key: Optional[List[CGMLKeyNode] | CGMLKeyNode] = None
67
+ graph: Optional[List[CGMLGraph] | CGMLGraph] = None
68
+
69
+
70
+ @dataclass(config=ConfigDict(extra='forbid'))
71
+ class CGML:
72
+ """Root type of CyberiadaML scheme."""
73
+
74
+ graphml: CGMLGraphml
@@ -0,0 +1,24 @@
1
+ """Module contains common geometry classes."""
2
+ from dataclasses import dataclass
3
+ from typing import Optional, TypeAlias
4
+
5
+
6
+ @dataclass
7
+ class Point:
8
+ """Point data class."""
9
+
10
+ x: float
11
+ y: float
12
+
13
+
14
+ @dataclass
15
+ class Rectangle:
16
+ """Rectangle data class."""
17
+
18
+ x: float
19
+ y: float
20
+ width: Optional[float] = None
21
+ height: Optional[float] = None
22
+
23
+
24
+ Key: TypeAlias = str
@@ -0,0 +1,152 @@
1
+ """Module contains the types of parsed scheme's elements."""
2
+ from typing import (
3
+ List,
4
+ Dict,
5
+ DefaultDict,
6
+ Optional,
7
+ TypeAlias
8
+ )
9
+
10
+ from pydantic.dataclasses import dataclass
11
+ from pydantic import Field
12
+
13
+ try:
14
+ from .cgml_scheme import CGMLDataNode, CGMLKeyNode
15
+ from .common import Point, Rectangle
16
+ except ImportError:
17
+ from cyberiadaml_py.types.cgml_scheme import CGMLDataNode, CGMLKeyNode
18
+ from cyberiadaml_py.types.common import Point, Rectangle
19
+ # { node: ['dGeometry', ...], edge: ['dData', ...]}
20
+ AwailableKeys: TypeAlias = DefaultDict[str, List[CGMLKeyNode]]
21
+
22
+
23
+ @dataclass
24
+ class CGMLState:
25
+ """
26
+ Data class with information about state.
27
+
28
+ State is <node>, that not connected with meta node,\
29
+ doesn't have data node with key 'dNote' or 'dInitial'
30
+
31
+ Parameters:
32
+ name: content of data node with key 'dName'.
33
+ actions: content of data node with key 'dData'.
34
+ bounds: x, y, width, height properties of data node with key 'dGeometry'.
35
+ parent: parent state id.
36
+ color: content of data node with key 'dColor'.
37
+ unknownDatanodes: all datanodes, whose information\
38
+ is not included in the type.
39
+ """
40
+
41
+ name: str
42
+ actions: str
43
+ unknownDatanodes: List[CGMLDataNode]
44
+ parent: Optional[str] = None
45
+ bounds: Optional[Rectangle] = None
46
+ color: Optional[str] = None
47
+
48
+
49
+ @dataclass
50
+ class CGMLComponent:
51
+ """
52
+ Data class with information about component.
53
+
54
+ Component is node, that connected with meta node (<node id=''>).
55
+ parameters: content of data node with key 'dData'.
56
+ """
57
+
58
+ id: str
59
+ parameters: str
60
+
61
+
62
+ @dataclass
63
+ class CGMLInitialState:
64
+ """
65
+ Data class with information about initial state (pseudo node).
66
+
67
+ Intiial state is <node>, that contains data node with key 'dInitial'.
68
+
69
+ Parameters:
70
+ id: state's id.
71
+ target: state's id, thats connetcted with initial state\
72
+ (<edge source="initial state id" target="target state's id">)
73
+ position: x, y properties of data node with 'dGeometry' key.
74
+ """
75
+
76
+ transitionId: str
77
+ id: str
78
+ target: str
79
+ position: Optional[Point] = None
80
+
81
+
82
+ @dataclass
83
+ class CGMLTransition:
84
+ """
85
+ Data class with information about transition(<edge>).
86
+
87
+ Parameters:
88
+ source: <edge> source property's content.
89
+ target: <edge> target property's content.
90
+ actions: content of data node with 'dData' key.
91
+ color: content of data node with 'dColor' key.
92
+ position: x, y properties of data node with 'dGeometry' key.
93
+ unknownDatanodes: all datanodes, whose information\
94
+ is not included in the type.
95
+ """
96
+
97
+ id: str
98
+ source: str
99
+ target: str
100
+ actions: str
101
+ unknownDatanodes: List[CGMLDataNode]
102
+ color: Optional[str] = None
103
+ position: Optional[Point] = None
104
+
105
+
106
+ @dataclass
107
+ class CGMLNote:
108
+ """
109
+ Dataclass with infromation about note.
110
+
111
+ Note is <node> containing data node with key 'dNote'
112
+ unknownDatanodes: all datanodes, whose information\
113
+ is not included in the type.
114
+ """
115
+
116
+ position: Point
117
+ text: str
118
+ unknownDatanodes: List[CGMLDataNode]
119
+ id: str = Field(serialization_alias='@id')
120
+
121
+
122
+ @dataclass
123
+ class CGMLElements:
124
+ """
125
+ Dataclass with elements of parsed scheme.
126
+
127
+ Contains dict of CGMLStates, where the key is state's id.
128
+ Also contains trainstions, components, awaialable keys, notes.
129
+
130
+ States doesn't contains components nodes and initial state.
131
+ Transitions doesn't contains edges from meta-node(<node id=''>)\
132
+ to components nodes.
133
+
134
+ Parameters:
135
+ meta: content of data node\
136
+ with key 'dData' inside <node id="">
137
+ format: content of data node with key 'gFormat'.
138
+ platform: content of data node with key 'dName'\
139
+ inside <node id="">
140
+ keys: dict of KeyNodes, where the key is 'for' attribute.\
141
+ Example: { "node": [KeyNode, ...], "edge": [...] }
142
+ """
143
+
144
+ states: Dict[str, CGMLState]
145
+ transitions: Dict[str, CGMLTransition]
146
+ components: List[CGMLComponent]
147
+ platform: str
148
+ meta: str
149
+ format: str
150
+ keys: AwailableKeys
151
+ notes: Dict[str, CGMLNote]
152
+ initial_state: Optional[CGMLInitialState] = None
@@ -0,0 +1,31 @@
1
+ [tool.poetry]
2
+ name = "cyberiadaml-py"
3
+ version = "0.1.0"
4
+ description = "The Python 3 library for processing the CyberiadaML state machine graphs"
5
+ authors = ["L140-beep <kartoshka0302@mail.ru>"]
6
+ readme = "README.md"
7
+
8
+ [tool.poetry.dependencies]
9
+ python = "~3.10"
10
+ xmltodict = "^0.13.0"
11
+ pydantic = "^2.6.1"
12
+
13
+
14
+ [tool.poetry.group.dev.dependencies]
15
+ types-xmltodict = "^0.13.0.3"
16
+ pytest = "^8.0.1"
17
+ mypy = "^1.8.0"
18
+ flake8 = "^7.0.0"
19
+ flake8-docstrings = "^1.7.0"
20
+ flake8-import-order = "^0.18.2"
21
+ flake8-quotes = "^3.4.0"
22
+ flake8-pyproject = "^1.2.3"
23
+
24
+ [build-system]
25
+ requires = ["poetry-core"]
26
+ build-backend = "poetry.core.masonry.api"
27
+
28
+ [tool.flake8]
29
+ import-order-style="pep8"
30
+ inline-quotes = "single"
31
+ ignore=["D107", "W504"]