cognite-neat 0.123.19__py3-none-any.whl → 0.123.21__py3-none-any.whl

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

Potentially problematic release.


This version of cognite-neat might be problematic. Click here for more details.

cognite/neat/_version.py CHANGED
@@ -1,2 +1,2 @@
1
- __version__ = "0.123.19"
1
+ __version__ = "0.123.21"
2
2
  __engine__ = "^2.0.4"
@@ -33,6 +33,7 @@ from ._mapping import MappingAPI
33
33
  from ._plugin import PluginAPI
34
34
  from ._prepare import PrepareAPI
35
35
  from ._read import ReadAPI
36
+ from ._session._data_model import DataModelAPI
36
37
  from ._set import SetAPI
37
38
  from ._show import ShowAPI
38
39
  from ._state import SessionState
@@ -115,6 +116,9 @@ class NeatSession:
115
116
  if load_engine != "skip" and (engine_version := load_neat_engine(client, load_engine)):
116
117
  print(f"Neat Engine {engine_version} loaded.")
117
118
 
119
+ # new API for data model operations
120
+ self.data_model = DataModelAPI(self._state)
121
+
118
122
  def _select_most_performant_store(self) -> Literal["memory", "oxigraph"]:
119
123
  """Select the most performant store based on the current environment."""
120
124
 
File without changes
@@ -0,0 +1,3 @@
1
+ from ._routes import DataModelAPI
2
+
3
+ __all__ = ["DataModelAPI"]
@@ -0,0 +1,154 @@
1
+ from typing import Any, Literal
2
+ from zipfile import Path
3
+
4
+ from cognite.neat.core._data_model import importers
5
+ from cognite.neat.core._data_model.importers._base import BaseImporter
6
+ from cognite.neat.core._issues._base import IssueList
7
+ from cognite.neat.core._issues.errors._general import NeatValueError
8
+ from cognite.neat.core._issues.warnings._general import MissingCogniteClientWarning
9
+ from cognite.neat.core._utils.reader._base import NeatReader
10
+ from cognite.neat.plugins._manager import get_plugin_manager
11
+ from cognite.neat.plugins.data_model.importers._base import DataModelImporterPlugin
12
+ from cognite.neat.session._state import SessionState
13
+ from cognite.neat.session.exceptions import NeatSessionError, session_class_wrapper
14
+
15
+ InternalReaderName = Literal["excel", "ontology", "yaml"]
16
+
17
+
18
+ @session_class_wrapper
19
+ class ReadAPI:
20
+ def __init__(self, state: SessionState) -> None:
21
+ self._state = state
22
+
23
+ def __call__(self, name: str, io: str | Path, **kwargs: Any) -> IssueList:
24
+ """Provides access to the external plugins for data model importing.
25
+
26
+ Args:
27
+ name (str): The name of format (e.g. Excel) plugin is handling.
28
+ io (str | Path | None): The input/output interface for the plugin.
29
+ **kwargs (Any): Additional keyword arguments for the plugin.
30
+
31
+ !!! note "kwargs"
32
+ Users must consult the documentation of the plugin to understand
33
+ what keyword arguments are supported.
34
+ """
35
+
36
+ # Clean the input name once before matching.
37
+ clean_name: InternalReaderName | str = name.strip().lower()
38
+
39
+ # The match statement cleanly handles each case.
40
+ match clean_name:
41
+ case "excel":
42
+ return self.excel(io, **kwargs)
43
+
44
+ case "ontology":
45
+ return self.ontology(io)
46
+
47
+ case "yaml":
48
+ return self.yaml(io, **kwargs)
49
+
50
+ case _: # The wildcard '_' acts as the default 'else' case.
51
+ return self._plugin(name, io, **kwargs)
52
+
53
+ def _plugin(self, name: str, io: str | Path, **kwargs: Any) -> IssueList:
54
+ """Provides access to the external plugins for data model importing.
55
+
56
+ Args:
57
+ name (str): The name of format (e.g. Excel) plugin is handling.
58
+ io (str | Path | None): The input/output interface for the plugin.
59
+ **kwargs (Any): Additional keyword arguments for the plugin.
60
+
61
+ !!! note "kwargs"
62
+ Users must consult the documentation of the plugin to understand
63
+ what keyword arguments are supported.
64
+ """
65
+
66
+ # Some plugins may not support the io argument
67
+ reader = NeatReader.create(io)
68
+ path = reader.materialize_path()
69
+
70
+ self._state._raise_exception_if_condition_not_met(
71
+ "Data Model Read",
72
+ empty_data_model_store_required=True,
73
+ )
74
+
75
+ plugin_manager = get_plugin_manager()
76
+ plugin = plugin_manager.get(name, DataModelImporterPlugin)
77
+
78
+ print(
79
+ f"You are using an external plugin {plugin.__name__}, which is not developed by the NEAT team."
80
+ "\nUse it at your own risk."
81
+ )
82
+
83
+ return self._state.data_model_import(plugin().configure(io=path, **kwargs))
84
+
85
+ def excel(self, io: str | Path, *, enable_manual_edit: bool = False) -> IssueList:
86
+ """Reads a Neat Excel Data Model to the data model store.
87
+ The data model spreadsheets may contain conceptual or physical data model definitions.
88
+
89
+ Args:
90
+ io: file path to the Excel sheet
91
+ enable_manual_edit: If True, the user will be able to re-import data model
92
+ which where edit outside of NeatSession
93
+ """
94
+ reader = NeatReader.create(io)
95
+ path = reader.materialize_path()
96
+
97
+ self._state._raise_exception_if_condition_not_met(
98
+ "Read Excel Data Model",
99
+ empty_data_model_store_required=not enable_manual_edit,
100
+ )
101
+
102
+ return self._state.data_model_import(importers.ExcelImporter(path), enable_manual_edit)
103
+
104
+ def ontology(self, io: str | Path) -> IssueList:
105
+ """Reads an OWL ontology source into NeatSession.
106
+
107
+ Args:
108
+ io: file path or url to the OWL file
109
+ """
110
+
111
+ self._state._raise_exception_if_condition_not_met(
112
+ "Read Ontology",
113
+ empty_data_model_store_required=True,
114
+ )
115
+
116
+ reader = NeatReader.create(io)
117
+ importer = importers.OWLImporter.from_file(reader.materialize_path(), source_name=f"file {reader!s}")
118
+ return self._state.data_model_import(importer)
119
+
120
+ def yaml(self, io: str | Path, *, format: Literal["neat", "toolkit"] = "neat") -> IssueList:
121
+ """Reads a yaml with either neat data mode, or several toolkit yaml files to
122
+ import Data Model(s) into NeatSession.
123
+
124
+ Args:
125
+ io: File path to the Yaml file in the case of "neat" yaml, or path to a zip folder or directory with several
126
+ Yaml files in the case of "toolkit".
127
+ format: The format of the yaml file(s). Can be either "neat" or "toolkit".
128
+
129
+ Example:
130
+ ```python
131
+ neat.read.yaml("path_to_toolkit_yamls")
132
+ ```
133
+ """
134
+ self._state._raise_exception_if_condition_not_met(
135
+ "Read YAML data model",
136
+ empty_data_model_store_required=True,
137
+ )
138
+ reader = NeatReader.create(io)
139
+ path = reader.materialize_path()
140
+ importer: BaseImporter
141
+ if format == "neat":
142
+ importer = importers.DictImporter.from_yaml_file(path, source_name=f"{reader!s}")
143
+ elif format == "toolkit":
144
+ dms_importer = importers.DMSImporter.from_path(path, self._state.client)
145
+ if dms_importer.issue_list.has_warning_type(MissingCogniteClientWarning):
146
+ raise NeatSessionError(
147
+ "No client provided. You are referencing Cognite containers in your data model, "
148
+ "NEAT needs a client to lookup the container definitions. "
149
+ "Please set the client in the session, NeatSession(client=client)."
150
+ )
151
+ importer = dms_importer
152
+ else:
153
+ raise NeatValueError(f"Unsupported YAML format: {format}")
154
+ return self._state.data_model_import(importer)
@@ -0,0 +1,43 @@
1
+ from cognite.neat.core._data_model.models.conceptual._verified import ConceptualDataModel
2
+ from cognite.neat.core._data_model.models.physical._verified import PhysicalDataModel
3
+ from cognite.neat.session._session._data_model._read import ReadAPI
4
+ from cognite.neat.session._session._data_model._show import ShowAPI
5
+ from cognite.neat.session._state import SessionState
6
+ from cognite.neat.session.exceptions import session_class_wrapper
7
+
8
+
9
+ @session_class_wrapper
10
+ class DataModelAPI:
11
+ """API for managing data models in NEAT session."""
12
+
13
+ def __init__(self, state: SessionState) -> None:
14
+ self._state = state
15
+ self.read = ReadAPI(state)
16
+ self.show = ShowAPI(state)
17
+
18
+ @property
19
+ def physical(self) -> PhysicalDataModel | None:
20
+ """Access to the physical data model level."""
21
+ return self._state.data_model_store.try_get_last_physical_data_model
22
+
23
+ @property
24
+ def conceptual(self) -> ConceptualDataModel | None:
25
+ """Access to the conceptual data model level."""
26
+ return self._state.data_model_store.try_get_last_conceptual_data_model
27
+
28
+ def _repr_html_(self) -> str:
29
+ if self._state.data_model_store.empty:
30
+ return (
31
+ "<strong>No data model</strong>. Get started by reading data model with the <em>.read</em> attribute."
32
+ )
33
+
34
+ output = []
35
+
36
+ if self._state.data_model_store.provenance:
37
+ if self.physical:
38
+ html = self.physical._repr_html_()
39
+ if self.conceptual:
40
+ html = self.conceptual._repr_html_()
41
+ output.append(f"<H2>Data Model</H2><br />{html}")
42
+
43
+ return "<br />".join(output)
@@ -0,0 +1,147 @@
1
+ from typing import Any
2
+
3
+ import networkx as nx
4
+ from IPython.display import HTML, display
5
+ from pyvis.network import Network as PyVisNetwork # type: ignore
6
+
7
+ from cognite.neat.core._constants import IN_NOTEBOOK, IN_PYODIDE
8
+ from cognite.neat.core._data_model.analysis._base import DataModelAnalysis
9
+ from cognite.neat.core._utils.io_ import to_directory_compatible
10
+ from cognite.neat.core._utils.rdf_ import uri_display_name
11
+ from cognite.neat.session._show import _generate_hex_color_per_type
12
+ from cognite.neat.session._state import SessionState
13
+ from cognite.neat.session.exceptions import NeatSessionError, session_class_wrapper
14
+
15
+
16
+ @session_class_wrapper
17
+ class ShowAPI:
18
+ def __init__(self, state: SessionState) -> None:
19
+ self._state = state
20
+
21
+ def __call__(self) -> Any:
22
+ """Generates a visualization of the data model without implements."""
23
+ if self._state.data_model_store.empty:
24
+ raise NeatSessionError("No data model available. Try using [bold].read[/bold] to read a data model.")
25
+
26
+ last_target = self._state.data_model_store.provenance[-1].target_entity
27
+ data_model = last_target.physical or last_target.conceptual
28
+ analysis = DataModelAnalysis(physical=last_target.physical, conceptual=last_target.conceptual)
29
+
30
+ if last_target.physical is not None:
31
+ di_graph = analysis._physical_di_graph(format="data-model")
32
+ else:
33
+ di_graph = analysis._conceptual_di_graph(format="data-model")
34
+
35
+ identifier = to_directory_compatible(str(data_model.metadata.identifier))
36
+ name = f"{identifier}.html"
37
+ return self._generate_visualization(di_graph, name)
38
+
39
+ def implements(self) -> Any:
40
+ """Generates a visualization of implements of the data model concepts, showing
41
+ the inheritance between the concepts in the data model."""
42
+ if self._state.data_model_store.empty:
43
+ raise NeatSessionError("No data model available. Try using [bold].read[/bold] to read a data model.")
44
+
45
+ last_target = self._state.data_model_store.provenance[-1].target_entity
46
+ data_model = last_target.physical or last_target.conceptual
47
+ analysis = DataModelAnalysis(physical=last_target.physical, conceptual=last_target.conceptual)
48
+
49
+ if last_target.physical is not None:
50
+ di_graph = analysis._physical_di_graph(format="implements")
51
+ else:
52
+ di_graph = analysis._conceptual_di_graph(format="implements")
53
+ identifier = to_directory_compatible(str(data_model.metadata.identifier))
54
+ name = f"{identifier}_implements.html"
55
+ return self._generate_visualization(di_graph, name)
56
+
57
+ def provenance(self) -> Any:
58
+ if not self._state.data_model_store.provenance:
59
+ raise NeatSessionError("No data model available. Try using [bold].read[/bold] to load data model.")
60
+
61
+ di_graph = self._generate_provenance_di_graph()
62
+ unique_hash = self._state.data_model_store.calculate_provenance_hash(shorten=True)
63
+ return self._generate_visualization(di_graph, name=f"data_model_provenance_{unique_hash}.html")
64
+
65
+ def _generate_visualization(self, di_graph: nx.DiGraph, name: str) -> Any:
66
+ if not IN_NOTEBOOK:
67
+ raise NeatSessionError("Visualization is only available in Jupyter notebooks!")
68
+
69
+ net = PyVisNetwork(
70
+ notebook=IN_NOTEBOOK,
71
+ cdn_resources="remote",
72
+ directed=True,
73
+ height="750px",
74
+ width="100%",
75
+ select_menu=IN_NOTEBOOK,
76
+ )
77
+
78
+ # Change the plotting layout
79
+ net.repulsion(
80
+ node_distance=100,
81
+ central_gravity=0.3,
82
+ spring_length=200,
83
+ spring_strength=0.05,
84
+ damping=0.09,
85
+ )
86
+
87
+ net.from_nx(di_graph)
88
+ if IN_PYODIDE:
89
+ net.write_html(name)
90
+ return display(HTML(name))
91
+
92
+ else:
93
+ return net.show(name)
94
+
95
+ def _generate_provenance_di_graph(self) -> nx.DiGraph:
96
+ di_graph = nx.DiGraph()
97
+ hex_colored_types = _generate_hex_color_per_type(["Agent", "Entity", "Activity", "Export", "Pruned"])
98
+
99
+ for change in self._state.data_model_store.provenance:
100
+ source = uri_display_name(change.source_entity.id_)
101
+ target = uri_display_name(change.target_entity.id_)
102
+ agent = uri_display_name(change.agent.id_)
103
+
104
+ di_graph.add_node(
105
+ source,
106
+ label=source,
107
+ type="Entity",
108
+ title="Entity",
109
+ color=hex_colored_types["Entity"],
110
+ )
111
+
112
+ di_graph.add_node(
113
+ target,
114
+ label=target,
115
+ type="Entity",
116
+ title="Entity",
117
+ color=hex_colored_types["Entity"],
118
+ )
119
+
120
+ di_graph.add_node(
121
+ agent,
122
+ label=agent,
123
+ type="Agent",
124
+ title="Agent",
125
+ color=hex_colored_types["Agent"],
126
+ )
127
+
128
+ di_graph.add_edge(source, agent, label="used", color="grey")
129
+ di_graph.add_edge(agent, target, label="generated", color="grey")
130
+
131
+ for (
132
+ source_id,
133
+ exports,
134
+ ) in self._state.data_model_store.exports_by_source_entity_id.items():
135
+ source_shorten = uri_display_name(source_id)
136
+ for export in exports:
137
+ export_id = uri_display_name(export.target_entity.id_)
138
+ di_graph.add_node(
139
+ export_id,
140
+ label=export_id,
141
+ type="Export",
142
+ title="Export",
143
+ color=hex_colored_types["Export"],
144
+ )
145
+ di_graph.add_edge(source_shorten, export_id, label="exported", color="grey")
146
+
147
+ return di_graph
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cognite-neat
3
- Version: 0.123.19
3
+ Version: 0.123.21
4
4
  Summary: Knowledge graph transformation
5
5
  Project-URL: Documentation, https://cognite-neat.readthedocs-hosted.com/
6
6
  Project-URL: Homepage, https://cognite-neat.readthedocs-hosted.com/
@@ -1,5 +1,5 @@
1
1
  cognite/neat/__init__.py,sha256=12StS1dzH9_MElqxGvLWrNsxCJl9Hv8A2a9D0E5OD_U,193
2
- cognite/neat/_version.py,sha256=tq3UEbgPuNWhnXVDhfdajZdA7tHZ1G3c1u-0dOKje_A,47
2
+ cognite/neat/_version.py,sha256=9-mMs5I23aZ63EJvthXAffhYSuElr0qE664JQ-Vdr_I,47
3
3
  cognite/neat/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
4
  cognite/neat/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
5
  cognite/neat/core/_config.py,sha256=WT1BS8uADcFvGoUYOOfwFOVq_VBl472TisdoA3wLick,280
@@ -165,7 +165,7 @@ cognite/neat/plugins/data_model/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm
165
165
  cognite/neat/plugins/data_model/importers/__init__.py,sha256=d4UJNCFR1DXPY7lv5LdCW2hiStEhvXiu2g_bRSIp1y0,89
166
166
  cognite/neat/plugins/data_model/importers/_base.py,sha256=M9zXp7tEu1SfJZRAJAtLmqpssdFcoi2X-5e25q_n_h8,1034
167
167
  cognite/neat/session/__init__.py,sha256=fxQ5URVlUnmEGYyB8Baw7IDq-uYacqkigbc4b-Pr9Fw,58
168
- cognite/neat/session/_base.py,sha256=6P63Kq4JJSi3S1CpcVLiG-dfKsN9Ml3o5GqZXjcLVvo,12937
168
+ cognite/neat/session/_base.py,sha256=yxAItY6663wcmlrwxmzWkJorrrrm9oahpYOP-5RGwvQ,13081
169
169
  cognite/neat/session/_collector.py,sha256=-icWXOT9YBjAOVZfpPtBx-D39kpRP2RaQKdPtcr7Xm8,4233
170
170
  cognite/neat/session/_drop.py,sha256=ipD8RS_ZebPNpeIkhC7yqSSeo7e57TXMRxrh5_6IRik,4239
171
171
  cognite/neat/session/_experimental.py,sha256=0peZPZ9JpmzQE05wHbng2tWmPPLLTAVfWZEEUhdnI6o,1274
@@ -184,12 +184,17 @@ cognite/neat/session/_template.py,sha256=NCgrrwLT98DpLYoo3Wybr_OUXrEXpsJZjrJ83Kq
184
184
  cognite/neat/session/_to.py,sha256=_R-UB3iEIQoa12kTD7tuSrRDdbySQXQg_mzbn5t-7bg,19399
185
185
  cognite/neat/session/_wizard.py,sha256=hARNNzD5Zfkk_V147rIjOLVvrFaqzXGXWhZuH1NJG3M,1486
186
186
  cognite/neat/session/exceptions.py,sha256=z5jxwfVTXDCCFZKTTYVIaksNKqb9CMa2tyIZgyNL3Us,3475
187
+ cognite/neat/session/_session/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
188
+ cognite/neat/session/_session/_data_model/__init__.py,sha256=417QF6wm3r-bLTmhYGXL_5XnEFShCklLCoGg3YBOIqY,62
189
+ cognite/neat/session/_session/_data_model/_read.py,sha256=boGdDCBQgBWsCf--HagOyOmUc4F49oPWLge7cVh7_6M,6355
190
+ cognite/neat/session/_session/_data_model/_routes.py,sha256=wF83vLtmgyGCM2zxnHq0m3-sPQXQamObc58u2kSN7nQ,1666
191
+ cognite/neat/session/_session/_data_model/_show.py,sha256=yX4BTIeBzcCcllfJvGm8g4qy13heFmcJtpXPixI8T2o,5835
187
192
  cognite/neat/session/_state/README.md,sha256=o6N7EL98lgyWffw8IoEUf2KG5uSKveD5__TW45YzVjA,902
188
193
  cognite/neat/session/engine/__init__.py,sha256=D3MxUorEs6-NtgoICqtZ8PISQrjrr4dvca6n48bu_bI,120
189
194
  cognite/neat/session/engine/_import.py,sha256=1QxA2_EK613lXYAHKQbZyw2yjo5P9XuiX4Z6_6-WMNQ,169
190
195
  cognite/neat/session/engine/_interface.py,sha256=3W-cYr493c_mW3P5O6MKN1xEQg3cA7NHR_ev3zdF9Vk,533
191
196
  cognite/neat/session/engine/_load.py,sha256=g52uYakQM03VqHt_RDHtpHso1-mFFifH5M4T2ScuH8A,5198
192
- cognite_neat-0.123.19.dist-info/METADATA,sha256=gQ3qarTxcFxur3j6ztkaifwEuzaVvXdwKXV0jiycG38,9172
193
- cognite_neat-0.123.19.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
194
- cognite_neat-0.123.19.dist-info/licenses/LICENSE,sha256=W8VmvFia4WHa3Gqxq1Ygrq85McUNqIGDVgtdvzT-XqA,11351
195
- cognite_neat-0.123.19.dist-info/RECORD,,
197
+ cognite_neat-0.123.21.dist-info/METADATA,sha256=MKG9VkaPiSGq4Ygn0MnUdqyX5TYKqtGmJfNVt-DvOdg,9172
198
+ cognite_neat-0.123.21.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
199
+ cognite_neat-0.123.21.dist-info/licenses/LICENSE,sha256=W8VmvFia4WHa3Gqxq1Ygrq85McUNqIGDVgtdvzT-XqA,11351
200
+ cognite_neat-0.123.21.dist-info/RECORD,,