volttron-lib-tree 2.0.0rc1__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,216 @@
1
+ Copyright 2022 Battelle Memorial Institute
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not
4
+ use this file except in compliance with the License. You may obtain a copy
5
+ of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11
+ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
+ License for the specific language governing permissions and limitations
13
+ under the License.
14
+
15
+
16
+ Apache License
17
+ Version 2.0, January 2004
18
+ http://www.apache.org/licenses/
19
+
20
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
21
+
22
+ 1. Definitions.
23
+
24
+ "License" shall mean the terms and conditions for use, reproduction,
25
+ and distribution as defined by Sections 1 through 9 of this document.
26
+
27
+ "Licensor" shall mean the copyright owner or entity authorized by
28
+ the copyright owner that is granting the License.
29
+
30
+ "Legal Entity" shall mean the union of the acting entity and all
31
+ other entities that control, are controlled by, or are under common
32
+ control with that entity. For the purposes of this definition,
33
+ "control" means (i) the power, direct or indirect, to cause the
34
+ direction or management of such entity, whether by contract or
35
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
36
+ outstanding shares, or (iii) beneficial ownership of such entity.
37
+
38
+ "You" (or "Your") shall mean an individual or Legal Entity
39
+ exercising permissions granted by this License.
40
+
41
+ "Source" form shall mean the preferred form for making modifications,
42
+ including but not limited to software source code, documentation
43
+ source, and configuration files.
44
+
45
+ "Object" form shall mean any form resulting from mechanical
46
+ transformation or translation of a Source form, including but
47
+ not limited to compiled object code, generated documentation,
48
+ and conversions to other media types.
49
+
50
+ "Work" shall mean the work of authorship, whether in Source or
51
+ Object form, made available under the License, as indicated by a
52
+ copyright notice that is included in or attached to the work
53
+ (an example is provided in the Appendix below).
54
+
55
+ "Derivative Works" shall mean any work, whether in Source or Object
56
+ form, that is based on (or derived from) the Work and for which the
57
+ editorial revisions, annotations, elaborations, or other modifications
58
+ represent, as a whole, an original work of authorship. For the purposes
59
+ of this License, Derivative Works shall not include works that remain
60
+ separable from, or merely link (or bind by name) to the interfaces of,
61
+ the Work and Derivative Works thereof.
62
+
63
+ "Contribution" shall mean any work of authorship, including
64
+ the original version of the Work and any modifications or additions
65
+ to that Work or Derivative Works thereof, that is intentionally
66
+ submitted to Licensor for inclusion in the Work by the copyright owner
67
+ or by an individual or Legal Entity authorized to submit on behalf of
68
+ the copyright owner. For the purposes of this definition, "submitted"
69
+ means any form of electronic, verbal, or written communication sent
70
+ to the Licensor or its representatives, including but not limited to
71
+ communication on electronic mailing lists, source code control systems,
72
+ and issue tracking systems that are managed by, or on behalf of, the
73
+ Licensor for the purpose of discussing and improving the Work, but
74
+ excluding communication that is conspicuously marked or otherwise
75
+ designated in writing by the copyright owner as "Not a Contribution."
76
+
77
+ "Contributor" shall mean Licensor and any individual or Legal Entity
78
+ on behalf of whom a Contribution has been received by Licensor and
79
+ subsequently incorporated within the Work.
80
+
81
+ 2. Grant of Copyright License. Subject to the terms and conditions of
82
+ this License, each Contributor hereby grants to You a perpetual,
83
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
84
+ copyright license to reproduce, prepare Derivative Works of,
85
+ publicly display, publicly perform, sublicense, and distribute the
86
+ Work and such Derivative Works in Source or Object form.
87
+
88
+ 3. Grant of Patent License. Subject to the terms and conditions of
89
+ this License, each Contributor hereby grants to You a perpetual,
90
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
91
+ (except as stated in this section) patent license to make, have made,
92
+ use, offer to sell, sell, import, and otherwise transfer the Work,
93
+ where such license applies only to those patent claims licensable
94
+ by such Contributor that are necessarily infringed by their
95
+ Contribution(s) alone or by combination of their Contribution(s)
96
+ with the Work to which such Contribution(s) was submitted. If You
97
+ institute patent litigation against any entity (including a
98
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
99
+ or a Contribution incorporated within the Work constitutes direct
100
+ or contributory patent infringement, then any patent licenses
101
+ granted to You under this License for that Work shall terminate
102
+ as of the date such litigation is filed.
103
+
104
+ 4. Redistribution. You may reproduce and distribute copies of the
105
+ Work or Derivative Works thereof in any medium, with or without
106
+ modifications, and in Source or Object form, provided that You
107
+ meet the following conditions:
108
+
109
+ (a) You must give any other recipients of the Work or
110
+ Derivative Works a copy of this License; and
111
+
112
+ (b) You must cause any modified files to carry prominent notices
113
+ stating that You changed the files; and
114
+
115
+ (c) You must retain, in the Source form of any Derivative Works
116
+ that You distribute, all copyright, patent, trademark, and
117
+ attribution notices from the Source form of the Work,
118
+ excluding those notices that do not pertain to any part of
119
+ the Derivative Works; and
120
+
121
+ (d) If the Work includes a "NOTICE" text file as part of its
122
+ distribution, then any Derivative Works that You distribute must
123
+ include a readable copy of the attribution notices contained
124
+ within such NOTICE file, excluding those notices that do not
125
+ pertain to any part of the Derivative Works, in at least one
126
+ of the following places: within a NOTICE text file distributed
127
+ as part of the Derivative Works; within the Source form or
128
+ documentation, if provided along with the Derivative Works; or,
129
+ within a display generated by the Derivative Works, if and
130
+ wherever such third-party notices normally appear. The contents
131
+ of the NOTICE file are for informational purposes only and
132
+ do not modify the License. You may add Your own attribution
133
+ notices within Derivative Works that You distribute, alongside
134
+ or as an addendum to the NOTICE text from the Work, provided
135
+ that such additional attribution notices cannot be construed
136
+ as modifying the License.
137
+
138
+ You may add Your own copyright statement to Your modifications and
139
+ may provide additional or different license terms and conditions
140
+ for use, reproduction, or distribution of Your modifications, or
141
+ for any such Derivative Works as a whole, provided Your use,
142
+ reproduction, and distribution of the Work otherwise complies with
143
+ the conditions stated in this License.
144
+
145
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
146
+ any Contribution intentionally submitted for inclusion in the Work
147
+ by You to the Licensor shall be under the terms and conditions of
148
+ this License, without any additional terms or conditions.
149
+ Notwithstanding the above, nothing herein shall supersede or modify
150
+ the terms of any separate license agreement you may have executed
151
+ with Licensor regarding such Contributions.
152
+
153
+ 6. Trademarks. This License does not grant permission to use the trade
154
+ names, trademarks, service marks, or product names of the Licensor,
155
+ except as required for reasonable and customary use in describing the
156
+ origin of the Work and reproducing the content of the NOTICE file.
157
+
158
+ 7. Disclaimer of Warranty. Unless required by applicable law or
159
+ agreed to in writing, Licensor provides the Work (and each
160
+ Contributor provides its Contributions) on an "AS IS" BASIS,
161
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
162
+ implied, including, without limitation, any warranties or conditions
163
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
164
+ PARTICULAR PURPOSE. You are solely responsible for determining the
165
+ appropriateness of using or redistributing the Work and assume any
166
+ risks associated with Your exercise of permissions under this License.
167
+
168
+ 8. Limitation of Liability. In no event and under no legal theory,
169
+ whether in tort (including negligence), contract, or otherwise,
170
+ unless required by applicable law (such as deliberate and grossly
171
+ negligent acts) or agreed to in writing, shall any Contributor be
172
+ liable to You for damages, including any direct, indirect, special,
173
+ incidental, or consequential damages of any character arising as a
174
+ result of this License or out of the use or inability to use the
175
+ Work (including but not limited to damages for loss of goodwill,
176
+ work stoppage, computer failure or malfunction, or any and all
177
+ other commercial damages or losses), even if such Contributor
178
+ has been advised of the possibility of such damages.
179
+
180
+ 9. Accepting Warranty or Additional Liability. While redistributing
181
+ the Work or Derivative Works thereof, You may choose to offer,
182
+ and charge a fee for, acceptance of support, warranty, indemnity,
183
+ or other liability obligations and/or rights consistent with this
184
+ License. However, in accepting such obligations, You may act only
185
+ on Your own behalf and on Your sole responsibility, not on behalf
186
+ of any other Contributor, and only if You agree to indemnify,
187
+ defend, and hold each Contributor harmless for any liability
188
+ incurred by, or claims asserted against, such Contributor by reason
189
+ of your accepting any such warranty or additional liability.
190
+
191
+ END OF TERMS AND CONDITIONS
192
+
193
+ APPENDIX: How to apply the Apache License to your work.
194
+
195
+ To apply the Apache License to your work, attach the following
196
+ boilerplate notice, with the fields enclosed by brackets "[]"
197
+ replaced with your own identifying information. (Don't include
198
+ the brackets!) The text should be enclosed in the appropriate
199
+ comment syntax for the file format. We also recommend that a
200
+ file or class name and description of purpose be included on the
201
+ same "printed page" as the copyright notice for easier
202
+ identification within third-party archives.
203
+
204
+ Copyright [yyyy] [name of copyright owner]
205
+
206
+ Licensed under the Apache License, Version 2.0 (the "License");
207
+ you may not use this file except in compliance with the License.
208
+ You may obtain a copy of the License at
209
+
210
+ http://www.apache.org/licenses/LICENSE-2.0
211
+
212
+ Unless required by applicable law or agreed to in writing, software
213
+ distributed under the License is distributed on an "AS IS" BASIS,
214
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
215
+ See the License for the specific language governing permissions and
216
+ limitations under the License.
@@ -0,0 +1,28 @@
1
+ Metadata-Version: 2.3
2
+ Name: volttron-lib-tree
3
+ Version: 2.0.0rc1
4
+ Summary: Tree data structures for handling topic-based resources in VOLTTRON.
5
+ License: Apache-2.0
6
+ Author: volttron
7
+ Author-email: volttron@pnnl.gov
8
+ Requires-Python: >=3.10,<4.0
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Intended Audience :: Education
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Requires-Dist: pydantic (>=2.0.0,<3.0.0)
21
+ Requires-Dist: treelib (>=1.6.1)
22
+ Requires-Dist: volttron-core (>=2.0.0rc30)
23
+ Project-URL: Documentation, https://volttron.readthedocs.org
24
+ Project-URL: Homepage, https://volttron.org
25
+ Project-URL: Repository, https://github.com/eclipse-volttron/volttron-lib-tree
26
+ Description-Content-Type: text/markdown
27
+
28
+ # volttron-lib-tree
@@ -0,0 +1 @@
1
+ # volttron-lib-tree
@@ -0,0 +1,34 @@
1
+ [tool.poetry]
2
+ name = "volttron-lib-tree"
3
+ version = "2.0.0rc1"
4
+ description = "Tree data structures for handling topic-based resources in VOLTTRON."
5
+ authors = ["volttron <volttron@pnnl.gov>"]
6
+ license = "Apache-2.0"
7
+ readme = "README.md"
8
+ homepage = "https://volttron.org"
9
+ repository = "https://github.com/eclipse-volttron/volttron-lib-tree"
10
+ documentation = "https://volttron.readthedocs.org"
11
+ classifiers = [
12
+ "Development Status :: 3 - Alpha",
13
+ "Intended Audience :: Education",
14
+ "Intended Audience :: Developers",
15
+ "Programming Language :: Python",
16
+ "Programming Language :: Python :: 3.10",
17
+ "Programming Language :: Python :: 3.11",
18
+ "Topic :: Software Development :: Libraries :: Python Modules"
19
+ ]
20
+
21
+ packages = [ { include = "volttron", from = "src" }]
22
+
23
+ [tool.poetry.dependencies]
24
+ python = "^3.10"
25
+ treelib = ">=1.6.1"
26
+ volttron-core = ">=2.0.0rc30"
27
+ pydantic = ">=2.0.0,<3.0.0"
28
+
29
+ [tool.poetry.group.dev.dependencies]
30
+ pytest = ">=7.0.0"
31
+
32
+ [build-system]
33
+ requires = ["poetry-core>=2.0.0"]
34
+ build-backend = "poetry.core.masonry.api"
@@ -0,0 +1,4 @@
1
+ from . device import DeviceNode, DeviceTree
2
+ from . topic import DuplicatedNodeIdError, NodeIDAbsentError, TopicNode, TopicTree
3
+
4
+ __all__ = DeviceNode, DeviceTree, DuplicatedNodeIdError, NodeIDAbsentError, TopicNode, TopicTree
@@ -0,0 +1,104 @@
1
+ # -*- coding: utf-8 -*- {{{
2
+ # ===----------------------------------------------------------------------===
3
+ #
4
+ # Installable Component of Eclipse VOLTTRON
5
+ #
6
+ # ===----------------------------------------------------------------------===
7
+ #
8
+ # Copyright 2022 Battelle Memorial Institute
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may not
11
+ # use this file except in compliance with the License. You may obtain a copy
12
+ # of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
18
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
19
+ # License for the specific language governing permissions and limitations
20
+ # under the License.
21
+ #
22
+ # ===----------------------------------------------------------------------===
23
+ # }}}
24
+
25
+ import logging
26
+ import re
27
+
28
+ from importlib.metadata import distribution, PackageNotFoundError
29
+
30
+ try:
31
+ distribution('volttron-core')
32
+ from volttron.client.known_identities import CONFIGURATION_STORE
33
+ except PackageNotFoundError:
34
+ from volttron.platform.agent.known_identities import CONFIGURATION_STORE
35
+
36
+ from .topic import TopicTree, TopicNode
37
+
38
+ _log = logging.getLogger(__name__)
39
+
40
+
41
+ class DeviceNode(TopicNode):
42
+ def __init__(self, tag=None, identifier=None, expanded=True, data=None, segment_type='TOPIC_SEGMENT', topic=''):
43
+ super(DeviceNode, self).__init__(tag, identifier, expanded, data, segment_type, topic)
44
+
45
+ def is_point(self):
46
+ return True if self.segment_type == 'POINT' else False
47
+
48
+ def is_device(self):
49
+ return True if self.segment_type == 'DEVICE' else False
50
+
51
+
52
+ class DeviceTree(TopicTree):
53
+ def __init__(self, topic_list=None, root_name='devices', assume_full_topics=False, *args, **kwargs):
54
+ super(DeviceTree, self).__init__(topic_list=topic_list, root_name=root_name, node_class=DeviceNode,
55
+ *args, **kwargs)
56
+ if assume_full_topics:
57
+ for n in self.leaves():
58
+ n.data['segment_type'] = 'POINT'
59
+ for n in [self.parent(l.identifier) for l in self.leaves()]:
60
+ n.data['segment_type'] = 'DEVICE'
61
+
62
+ def points(self, nid=None):
63
+ if nid is None:
64
+ points = [n for n in self._nodes.values() if n.is_point()]
65
+ else:
66
+ points = [self[n] for n in self.expand_tree(nid) if self[n].is_point()]
67
+ return points
68
+
69
+ def devices(self, nid=None):
70
+ if nid is None:
71
+ points = [n for n in self._nodes.values() if n.is_device()]
72
+ else:
73
+ points = [self[n] for n in self.expand_tree(nid) if self[n].is_device()]
74
+ return points
75
+
76
+ # TODO: Getting points requires getting device config, using it to find the registry config,
77
+ # and then parsing that. There is not a method in config.store, nor in the platform.driver for
78
+ # getting a completed configuration. The configuration is only fully assembled in the subsystem's
79
+ # _initial_update method called when the agent itself calls get_configs at startup. There does not
80
+ # seem to be an equivalent management method, and the code for this is in the agent subsystem
81
+ # rather than the service (though it is reached through the service, oddly...
82
+ @classmethod
83
+ def from_store(cls, platform, rpc_caller):
84
+ # TODO: Duplicate logic for external_platform check from VUIEndpoints to remove reference to it from here.
85
+ kwargs = {'external_platform': platform} if 'VUIEndpoints' in rpc_caller.__repr__() else {}
86
+ devices = rpc_caller(CONFIGURATION_STORE, 'manage_list_configs', 'platform.driver', **kwargs)
87
+ devices = devices if kwargs else devices.get(timeout=5)
88
+ devices = [d for d in devices if re.match('^devices/.*', d)]
89
+ device_tree = cls(devices)
90
+ for d in devices:
91
+ dev_config = rpc_caller(CONFIGURATION_STORE, 'manage_get', 'platform.driver', d, raw=False, **kwargs)
92
+ # TODO: If not AsyncResponse instead of if kwargs
93
+ dev_config = dev_config if kwargs else dev_config.get(timeout=5)
94
+ reg_cfg_name = dev_config.pop('registry_config')[len('config://'):]
95
+ data = {'config': dev_config, 'segment_type': 'DEVICE'}
96
+ device_tree.update_node(d, data=data)
97
+ registry_config = rpc_caller('config.store', 'manage_get', 'platform.driver',
98
+ f'{reg_cfg_name}', raw=False, **kwargs)
99
+ registry_config = registry_config if kwargs else registry_config.get(timeout=5)
100
+ for pnt in registry_config:
101
+ point_name = pnt.pop('Volttron Point Name')
102
+ n = device_tree.create_node(point_name, f"{d}/{point_name}", parent=d, data=pnt)
103
+ n.data['segment_type'] = 'POINT'
104
+ return device_tree
@@ -0,0 +1,198 @@
1
+ # -*- coding: utf-8 -*- {{{
2
+ # ===----------------------------------------------------------------------===
3
+ #
4
+ # Installable Component of Eclipse VOLTTRON
5
+ #
6
+ # ===----------------------------------------------------------------------===
7
+ #
8
+ # Copyright 2022 Battelle Memorial Institute
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may not
11
+ # use this file except in compliance with the License. You may obtain a copy
12
+ # of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
18
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
19
+ # License for the specific language governing permissions and limitations
20
+ # under the License.
21
+ #
22
+ # ===----------------------------------------------------------------------===
23
+ # }}}
24
+
25
+ import json
26
+ import logging
27
+ import re
28
+
29
+ from collections import defaultdict
30
+ from datetime import datetime, timedelta
31
+ from enum import Enum
32
+ from importlib.metadata import distribution, PackageNotFoundError
33
+ from os.path import normpath
34
+ from pydantic import BaseModel
35
+ from typing import Any, Union, Iterable
36
+ from treelib import Tree, Node
37
+ from treelib.exceptions import DuplicatedNodeIdError, NodeIDAbsentError
38
+
39
+ try:
40
+ distribution('volttron-core')
41
+ from volttron.client.known_identities import CONFIGURATION_STORE
42
+ except PackageNotFoundError:
43
+ from volttron.platform.agent.known_identities import CONFIGURATION_STORE
44
+
45
+ _log = logging.getLogger(__name__)
46
+
47
+
48
+ class TopicNode(Node):
49
+ def __init__(self, tag=None, identifier=None, expanded=True, data=None, segment_type='TOPIC_SEGMENT', topic=''):
50
+ super(TopicNode, self).__init__(tag, identifier, expanded, data)
51
+ self.data: dict[str, Any] = data if data else {}
52
+ self.data['segment_type'] = segment_type
53
+ self.data['topic'] = topic
54
+
55
+ @property
56
+ def segment_type(self):
57
+ return self.data['segment_type']
58
+
59
+ @property
60
+ def topic(self):
61
+ return self.data['topic']
62
+
63
+ def is_segment(self):
64
+ return True if self.segment_type == 'TOPIC_SEGMENT' else False
65
+
66
+
67
+ class TopicTree(Tree):
68
+ def __init__(self, topic_list=None, root_name='root', node_class=None, *args, **kwargs):
69
+ node_class = node_class if node_class else TopicNode
70
+ super(TopicTree, self).__init__(node_class=node_class, *args, **kwargs)
71
+ if topic_list:
72
+ self._from_topic_list(topic_list, root_name)
73
+ else:
74
+ self.create_node(root_name, root_name).data['segment_type'] = 'TOPIC_ROOT'
75
+
76
+ def _from_topic_list(self, topic_list, root_name):
77
+ tops = [t.split('/') for t in topic_list]
78
+ if all([top[0] == root_name for top in tops]):
79
+ [top.pop(0) for top in tops]
80
+ self.create_node(root_name, root_name).data['segment_type'] = 'TOPIC_ROOT'
81
+ for top in tops:
82
+ parent = root_name
83
+ for segment in top:
84
+ nid = '/'.join([parent, segment])
85
+ try:
86
+ self.create_node(segment, nid, parent=parent)
87
+ except DuplicatedNodeIdError:
88
+ pass
89
+ parent = nid
90
+
91
+ def add_node(self, node, parent=None):
92
+ super(TopicTree, self).add_node(node, parent)
93
+ node.data['topic'] = node.identifier[(len(self.root) + 1):]
94
+ return node
95
+
96
+ # TODO: Should this actually be get_child_topics() where topics or routes are returned with wildcards?
97
+ def get_children_dict(self, sub_root_node_id: Union[list, str], include_root: bool = True,
98
+ prefix: str = '', replace_topic: str = None) -> dict:
99
+ sub_root_node_id = sub_root_node_id if type(sub_root_node_id) is list else [sub_root_node_id]
100
+ level_dict = defaultdict(set)
101
+ for r_id in sub_root_node_id:
102
+ for d in self.children(r_id):
103
+ try:
104
+ if replace_topic:
105
+ if include_root:
106
+ level_dict[d.tag].add('/'.join([self.root, replace_topic, d.tag]))
107
+ else:
108
+ level_dict[d.tag].add('/'.join([replace_topic, d.tag]))
109
+ else:
110
+ if include_root:
111
+ level_dict[d.tag].add(d.identifier)
112
+ else:
113
+ level_dict[d.tag].add(d.identifier.split('/', 1)[1])
114
+ except NodeIDAbsentError:
115
+ return {}
116
+ ret_dict = {}
117
+ for k, s in level_dict.items():
118
+ if len(s) > 1:
119
+ ret_dict[k] = sorted([normpath('/'.join([prefix, v])) for v in s])
120
+ else:
121
+ ret_dict[k] = normpath('/'.join([prefix, s.pop()]))
122
+ return ret_dict
123
+
124
+ def resolve_query(self, topic_pattern: str = '', regex: str = None, exact_matches: Iterable = None,
125
+ return_leaves=False) -> Iterable:
126
+ def clipping(topic_parts, nids=None):
127
+ nids = nids if nids else []
128
+ if topic_parts:
129
+ part = topic_parts.pop(0)
130
+ if part:
131
+ if not nids:
132
+ return clipping(topic_parts, [part]) if self.get_node(part) else nids
133
+ else:
134
+ joined_nids = [self.get_node('/'.join([c.identifier, part])).identifier
135
+ for n in nids for c in self.children(n)]
136
+ return clipping(topic_parts, joined_nids)
137
+ else:
138
+ return nids
139
+ else:
140
+ return [l.identifier for n in nids for l in self.leaves(n)] if return_leaves else nids
141
+
142
+ if not topic_pattern:
143
+ # If None or empty string, default to "self.root"
144
+ topic_pattern = self.root
145
+ elif not topic_pattern.startswith(self.root):
146
+ topic_pattern = '/'.join([self.root, topic_pattern])
147
+
148
+ regex = re.compile(regex) if regex else None
149
+ topic_nids = clipping([part.strip('/') for part in topic_pattern.split('/-') if part != '']) if topic_pattern else []
150
+ if topic_nids and exact_matches:
151
+ nodes = (self.get_node(n) for n in topic_nids if n in exact_matches and (not regex or regex.search(n)))
152
+ elif topic_nids and not exact_matches:
153
+ nodes = (self.get_node(n) for n in topic_nids if not regex or regex.search(n))
154
+ elif not topic_nids and exact_matches:
155
+ nodes = (self.get_node(n) for n in exact_matches if (not regex or regex.search(n)) and self.contains(n))
156
+ else:
157
+ nodes = self.filter_nodes(lambda n: regex.search(n.identifier)) if regex else []
158
+ return nodes
159
+
160
+ def prune(self, topic_pattern: str = None, regex: str = None, exact_matches: Iterable = None, *args, **kwargs):
161
+ if topic_pattern:
162
+ pattern = re.compile(topic_pattern.replace('-', '[^/]+') + '(/|$)')
163
+ nids = [n.identifier for n in self.filter_nodes(lambda x: pattern.search(x.identifier))]
164
+ else:
165
+ nids = list(self.expand_tree())
166
+ if regex:
167
+ regex = re.compile(regex)
168
+ nids = [n for n in nids if regex.search(n)]
169
+ if exact_matches:
170
+ nids = [n for n in nids if n in exact_matches]
171
+ pruned = self.__class__(topic_list=nids, root_name=self.root, *args, **kwargs)
172
+ for nid in [n.identifier for n in pruned.all_nodes()]:
173
+ old = self.get_node(nid)
174
+ pruned.update_node(nid, data=old.data)
175
+ return pruned
176
+
177
+ def get_matches(self, topic, return_nodes=True):
178
+ pattern = topic.replace('-', '[^/]+') + '$'
179
+ nodes = self.filter_nodes(lambda x: re.match(pattern, x.identifier))
180
+ if return_nodes:
181
+ return list(nodes)
182
+ else:
183
+ return [n.identifier for n in nodes]
184
+
185
+ def to_json(self, with_data=False, sort=True, reverse=False):
186
+ """To format the tree in JSON format."""
187
+ def custom_encoder(obj):
188
+ if isinstance(obj, BaseModel):
189
+ return obj.model_dump()
190
+ if isinstance(obj, Enum):
191
+ return obj.value
192
+ if isinstance(obj, timedelta):
193
+ return obj.total_seconds()
194
+ if isinstance(obj, datetime):
195
+ return obj.isoformat()
196
+ return json.JSONEncoder().default(obj)
197
+
198
+ return json.dumps(self.to_dict(with_data=with_data, sort=sort, reverse=reverse), default=custom_encoder)