commonlib-reader 1.3.0__tar.gz → 1.4.1__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.
@@ -1,12 +1,11 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: commonlib-reader
3
- Version: 1.3.0
3
+ Version: 1.4.1
4
4
  Summary: Reader for Equinor commonlib api.
5
5
  Author: Åsmund Våge Fannemel
6
6
  Author-email: Åsmund Våge Fannemel <asmf@equinor.com>
7
7
  License: MIT
8
- Requires-Dist: pandas>=2.1.4
9
- Requires-Dist: eq-api-connector>=1.1.0,<2.0.0
8
+ Requires-Dist: eq-api-connector>=1.2.0,<2.0.0
10
9
  Requires-Python: >=3.10, <4.0.0
11
10
  Project-URL: Repository, https://github.com/equinor/commonlib-reader.git
12
11
  Description-Content-Type: text/markdown
@@ -14,9 +13,12 @@ Description-Content-Type: text/markdown
14
13
  # commonlib-reader
15
14
  Connector package for Equinor [Commonlib](https://commonlib.equinor.com/) [api](https://commonlibapi.equinor.com/swagger/index.html).
16
15
 
16
+ See the [changelog](CHANGELOG.md) for release history.
17
+
17
18
  Current features:
18
19
  - Reading any code table with the `Code` class
19
20
  - Reading library definitions and attribute definitions with the `Library` and `AttributeDefinition` classes
21
+ - Reading projects with the `Project` class
20
22
  - Getting facility data using the [Facility](commonlib_reader/facility.py) class
21
23
  - [IMS source ](commonlib_reader/ims.py) lookup tables for facilities
22
24
  - Getting Tag category, Tag type, Tag format, and Tag format element data. See [tag.py](commonlib_reader/tag.py)
@@ -71,6 +73,18 @@ Each entry provides `name`, `description`, `identity`, `is_valid`, `attributes`,
71
73
  other CommonLib metadata. Use `Code.get_names()` or `Code.get_name_and_desc()` when
72
74
  only dropdown-friendly names or name/description data is required.
73
75
 
76
+ ### Projects
77
+
78
+ Use `Project.get_all()` to retrieve projects and optionally filter by name or
79
+ abbreviation.
80
+
81
+ ```python
82
+ from commonlib_reader import Project
83
+
84
+ projects = Project.get_all(name="M.IGLED.6I.X.0010")
85
+ matching_projects = Project.get_all(abbreviation="IGLED")
86
+ ```
87
+
74
88
  ## Installing
75
89
 
76
90
  Install package from pypi using `pip install commonlib_reader`
@@ -1,9 +1,12 @@
1
1
  # commonlib-reader
2
2
  Connector package for Equinor [Commonlib](https://commonlib.equinor.com/) [api](https://commonlibapi.equinor.com/swagger/index.html).
3
3
 
4
+ See the [changelog](CHANGELOG.md) for release history.
5
+
4
6
  Current features:
5
7
  - Reading any code table with the `Code` class
6
8
  - Reading library definitions and attribute definitions with the `Library` and `AttributeDefinition` classes
9
+ - Reading projects with the `Project` class
7
10
  - Getting facility data using the [Facility](commonlib_reader/facility.py) class
8
11
  - [IMS source ](commonlib_reader/ims.py) lookup tables for facilities
9
12
  - Getting Tag category, Tag type, Tag format, and Tag format element data. See [tag.py](commonlib_reader/tag.py)
@@ -58,6 +61,18 @@ Each entry provides `name`, `description`, `identity`, `is_valid`, `attributes`,
58
61
  other CommonLib metadata. Use `Code.get_names()` or `Code.get_name_and_desc()` when
59
62
  only dropdown-friendly names or name/description data is required.
60
63
 
64
+ ### Projects
65
+
66
+ Use `Project.get_all()` to retrieve projects and optionally filter by name or
67
+ abbreviation.
68
+
69
+ ```python
70
+ from commonlib_reader import Project
71
+
72
+ projects = Project.get_all(name="M.IGLED.6I.X.0010")
73
+ matching_projects = Project.get_all(abbreviation="IGLED")
74
+ ```
75
+
61
76
  ## Installing
62
77
 
63
78
  Install package from pypi using `pip install commonlib_reader`
@@ -1,13 +1,10 @@
1
1
  [project]
2
2
  name = "commonlib-reader"
3
- version = "1.3.0"
3
+ version = "1.4.1"
4
4
  description = "Reader for Equinor commonlib api."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10,<4.0.0"
7
- dependencies = [
8
- "pandas>=2.1.4",
9
- "eq-api-connector (>=1.1.0,<2.0.0)",
10
- ]
7
+ dependencies = ["eq-api-connector (>=1.2.0,<2.0.0)"]
11
8
 
12
9
  [[project.authors]]
13
10
  name = "Åsmund Våge Fannemel"
@@ -21,11 +18,11 @@ Repository = "https://github.com/equinor/commonlib-reader.git"
21
18
 
22
19
  [dependency-groups]
23
20
  dev = [
24
- "pytest>=7.4.4,<10.0.0",
21
+ "pytest>=9.2.0,<10.0.0",
25
22
  "pytest-cov>=7.0.0,<8.0.0",
26
- "black>=24.1.1,<27.0.0",
23
+ "black>=26.10.0,<27.0.0",
27
24
  ]
28
25
 
29
26
  [build-system]
30
- requires = ["uv_build>=0.11.16,<0.13"]
27
+ requires = ["uv_build>=0.11.16,<0.14"]
31
28
  build-backend = "uv_build"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "commonlib-reader"
3
- version = "1.3.0"
3
+ version = "1.4.1"
4
4
  description = "Reader for Equinor commonlib api."
5
5
  authors = [
6
6
  { name = "Åsmund Våge Fannemel", email = "asmf@equinor.com" }
@@ -10,17 +10,16 @@ license = { text = "MIT" }
10
10
  urls = {"Repository" = "https://github.com/equinor/commonlib-reader.git"}
11
11
  requires-python = ">=3.10,<4.0.0"
12
12
  dependencies = [
13
- "pandas>=2.1.4",
14
- "eq-api-connector (>=1.1.0,<2.0.0)"
13
+ "eq-api-connector (>=1.2.0,<2.0.0)"
15
14
  ]
16
15
 
17
16
  [dependency-groups]
18
17
  dev = [
19
- "pytest>=7.4.4,<10.0.0",
18
+ "pytest>=9.2.0,<10.0.0",
20
19
  "pytest-cov>=7.0.0,<8.0.0",
21
- "black>=24.1.1,<27.0.0"
20
+ "black>=26.10.0,<27.0.0"
22
21
  ]
23
22
 
24
23
  [build-system]
25
- requires = ["uv_build>=0.11.16,<0.13"]
24
+ requires = ["uv_build>=0.11.16,<0.14"]
26
25
  build-backend = "uv_build"
@@ -8,9 +8,8 @@ class Code:
8
8
  """A generic representation of one entry in a CommonLib library.
9
9
 
10
10
  A Library defines the code table and its attribute schema; a Code stores one
11
- value from that table. Use this class to read entries from libraries without
12
- a dedicated domain class implemented in this package, such as Facility,
13
- Discipline, Unit, TagType, TagCategory, or TagFormat.
11
+ value from that table. Use this class directly for generic libraries, or as
12
+ a base class for dedicated readers that add library-specific behavior.
14
13
 
15
14
  Attributes:
16
15
  library (str): Name of the library the code belongs to.
@@ -3,38 +3,15 @@ from typing import List
3
3
  from commonlib_reader.code import Code
4
4
 
5
5
 
6
- class Discipline:
6
+ class Discipline(Code):
7
7
  def __init__(self, data: dict):
8
8
  if not isinstance(data, dict):
9
9
  raise ValueError("Input data shall be dictionary.")
10
-
11
- self._data = data
12
-
13
- def __eq__(self, other):
14
- if isinstance(other, Discipline):
15
- return self._data == other._data
16
-
17
- return False
10
+ super().__init__(data, library="Discipline")
18
11
 
19
12
  def __str__(self):
20
13
  return f"Discipline: {self.name}-{self.description}"
21
14
 
22
- @property
23
- def name(self) -> str:
24
- return self._data.get("name", "")
25
-
26
- @property
27
- def description(self) -> str:
28
- return self._data.get("description", "")
29
-
30
- @property
31
- def identity(self) -> str:
32
- return self._data.get("identity", "")
33
-
34
- @property
35
- def is_valid(self) -> bool:
36
- return self._data.get("isValid", False)
37
-
38
15
  @classmethod
39
16
  def get_all(cls, scope: str, only_valid: bool = True) -> List["Discipline"]:
40
17
  """Get all disciplines for
@@ -57,7 +34,7 @@ class Discipline:
57
34
  f"No discipline data found for scope {scope}. Verify that scope is correct."
58
35
  )
59
36
 
60
- dis = [Discipline(x) for x in dis_data] # type: ignore
37
+ dis = [cls(x) for x in dis_data]
61
38
  if only_valid:
62
39
  dis = [x for x in dis if x.is_valid]
63
40
 
@@ -0,0 +1,316 @@
1
+ from collections.abc import Mapping
2
+ from types import MappingProxyType
3
+ from typing import List, Union
4
+
5
+ from commonlib_reader.code import Code
6
+
7
+
8
+ class Unit(Code):
9
+ """A class representing a unit of measurement.
10
+
11
+ Properties:
12
+ name (str): The name of the unit.
13
+ description (str): A description of the unit.
14
+ identity (str): The unique identifier for the unit.
15
+ quantity (str): The quantity this unit measures.
16
+ """
17
+
18
+ # In memory cache for units and conversion codes
19
+ _units = None
20
+ _conversion_codes = None
21
+
22
+ def __init__(self, data: Union[dict, str]):
23
+ if isinstance(data, str):
24
+ matches = [unit for unit in self.get_units() if unit.name == data]
25
+ if not matches:
26
+ raise ValueError(f"No unit named {data} found.")
27
+ data = matches[0]._data
28
+
29
+ super().__init__(data, library="UnitOfMeasure")
30
+ self.__dict__.update(self.attributes)
31
+
32
+ @property
33
+ def name(self) -> str:
34
+ """Get or set the unit symbol."""
35
+ return self._data.get("name", "")
36
+
37
+ @name.setter
38
+ def name(self, value: str):
39
+ self._data["name"] = value
40
+
41
+ @property
42
+ def description(self) -> str:
43
+ """Get or set the unit description."""
44
+ return self._data.get("description", "")
45
+
46
+ @description.setter
47
+ def description(self, value: str):
48
+ self._data["description"] = value
49
+
50
+ @property
51
+ def identity(self) -> str:
52
+ """Get or set the unit identity."""
53
+ return self._data.get("identity", "")
54
+
55
+ @identity.setter
56
+ def identity(self, value: str):
57
+ self._data["identity"] = value
58
+
59
+ @staticmethod
60
+ def _as_bool(value) -> bool:
61
+ if isinstance(value, bool):
62
+ return value
63
+ return str(value).strip().lower() == "true"
64
+
65
+ @property
66
+ def quantity(self) -> str:
67
+ """Get the quantity measured by this unit."""
68
+ return self.attributes.get("Quantity", "")
69
+
70
+ @property
71
+ def conversion(self) -> str:
72
+ """Get the unit's conversion reference."""
73
+ return self.attributes.get("Conversion", "")
74
+
75
+ @property
76
+ def measure_system(self) -> str:
77
+ """Get the measurement system this unit belongs to."""
78
+ return self.attributes.get("MeasureSystem", "")
79
+
80
+ @property
81
+ def alias_of_uom(self) -> str:
82
+ """Get the unit symbol this unit aliases, if any."""
83
+ return self.attributes.get("AliasOfUoM", "")
84
+
85
+ @property
86
+ def alternate_symbols(self) -> str:
87
+ """Get alternate symbols for this unit."""
88
+ return self.attributes.get("AlternateSymbols", "")
89
+
90
+ @property
91
+ def is_in_base_units(self) -> bool:
92
+ """Whether the unit is expressed using the seven base units."""
93
+ return self._as_bool(self.attributes.get("IsInBaseUnits", False))
94
+
95
+ @property
96
+ def is_to_be_translated_to_alias(self) -> bool:
97
+ """Whether incoming values should be translated to the alias symbol."""
98
+ return self._as_bool(
99
+ self.attributes.get("IsToBeTranslatedToAlias", False)
100
+ )
101
+
102
+ @property
103
+ def is_default_for_transport(self) -> bool:
104
+ """Whether this is the default unit for transport."""
105
+ return self._as_bool(self.attributes.get("IsDefaultForTransport", False))
106
+
107
+ @property
108
+ def is_default_for_print(self) -> bool:
109
+ """Whether this is the default unit for print."""
110
+ return self._as_bool(self.attributes.get("IsDefaultForPrint", False))
111
+
112
+ @property
113
+ def definition(self) -> str:
114
+ """Get the unit definition, if provided."""
115
+ return self.attributes.get("Definition", "")
116
+
117
+ @property
118
+ def remark(self) -> str:
119
+ """Get general notes about the unit."""
120
+ return self.attributes.get("Remark", "")
121
+
122
+ @property
123
+ def iec61360_code(self) -> str:
124
+ """Get the IEC 61360 identifier, if provided."""
125
+ return self.attributes.get("IEC61360Code", "")
126
+
127
+ @property
128
+ def dexpi_name(self) -> str:
129
+ """Get the DEXPI unit name, if provided."""
130
+ return self.attributes.get("DEXPIName", "")
131
+
132
+ @property
133
+ def iso15926_name(self) -> str:
134
+ """Get the ISO 15926 unit name, if provided."""
135
+ return self.attributes.get("ISO15926Name", "")
136
+
137
+ @property
138
+ def iso15926_url(self) -> str:
139
+ """Get the ISO 15926 reference URL, if provided."""
140
+ return self.attributes.get("ISO15926URL", "")
141
+
142
+ @property
143
+ def is_cfihos(self) -> bool:
144
+ """Whether this unit is used by CFIHOS."""
145
+ return self._as_bool(self.attributes.get("IsCFIHOS", False))
146
+
147
+ @property
148
+ def internal_comments(self) -> str:
149
+ """Get internal maintenance comments, if provided."""
150
+ return self.attributes.get("InternalComments", "")
151
+
152
+ @classmethod
153
+ def _freeze_cache_value(cls, value):
154
+ if isinstance(value, dict):
155
+ return MappingProxyType(
156
+ {
157
+ key: cls._freeze_cache_value(item)
158
+ for key, item in value.items()
159
+ }
160
+ )
161
+ if isinstance(value, (list, tuple)):
162
+ return tuple(cls._freeze_cache_value(item) for item in value)
163
+ return value
164
+
165
+ @classmethod
166
+ def _thaw_cache_value(cls, value):
167
+ if isinstance(value, Mapping):
168
+ return {
169
+ key: cls._thaw_cache_value(item) for key, item in value.items()
170
+ }
171
+ if isinstance(value, tuple):
172
+ return [cls._thaw_cache_value(item) for item in value]
173
+ return value
174
+
175
+ @classmethod
176
+ def _get_conversion_codes(cls):
177
+ if cls._conversion_codes is None:
178
+ codes = Code.get_codes("UnitOfMeasureConversion")
179
+ cls._conversion_codes = MappingProxyType(
180
+ {
181
+ code.identity: cls._freeze_cache_value(code.attributes)
182
+ for code in codes
183
+ }
184
+ )
185
+ return cls._conversion_codes
186
+
187
+ def _get_conversion_factors(self):
188
+ """Return the API's ``(FactorA, FactorB)`` conversion coefficients.
189
+
190
+ ``FactorA`` is the scale factor and ``FactorB`` is the offset. The API
191
+ converts a value to its base unit as ``(value - FactorB) / FactorA``;
192
+ the inverse is ``base_value * FactorA + FactorB``.
193
+ """
194
+ reference = self.conversion
195
+ conversion_attributes = self._get_conversion_codes().get(reference)
196
+ if conversion_attributes is None:
197
+ raise ValueError(
198
+ f"No conversion factors found for unit {self.name} ({reference})."
199
+ )
200
+
201
+ try:
202
+ factor_a = float(conversion_attributes["FactorA"])
203
+ factor_b = float(conversion_attributes["FactorB"])
204
+ except (KeyError, TypeError, ValueError):
205
+ raise ValueError(
206
+ f"Invalid conversion factors for unit {self.name} ({reference})."
207
+ ) from None
208
+ return factor_a, factor_b
209
+
210
+ @property
211
+ def factor_a(self) -> float:
212
+ """Get the unit's multiplicative conversion factor."""
213
+ return self._get_conversion_factors()[0]
214
+
215
+ @property
216
+ def factor_b(self) -> float:
217
+ """Get the unit's additive conversion factor."""
218
+ return self._get_conversion_factors()[1]
219
+
220
+ def convert(self, value: float, to_unit: Union[str, "Unit"]) -> float:
221
+ """Convert a value from this unit to another unit of the same quantity.
222
+
223
+ A string target may be either a unit identity (for example,
224
+ ``"Pa|pressure"``) or an unambiguous symbol for this quantity.
225
+ """
226
+ if isinstance(to_unit, str):
227
+ matches = [unit for unit in self.get_units() if unit.identity == to_unit]
228
+ if not matches:
229
+ symbol_matches = [
230
+ unit for unit in self.get_units() if unit.name == to_unit
231
+ ]
232
+ quantity_matches = [
233
+ unit
234
+ for unit in symbol_matches
235
+ if unit.quantity == self.quantity
236
+ ]
237
+ matches = quantity_matches or symbol_matches
238
+ if not matches:
239
+ raise ValueError(f"No target unit {to_unit} found for {self.name}.")
240
+ if len(matches) > 1:
241
+ raise ValueError(f"Target unit {to_unit} is ambiguous.")
242
+ to_unit = matches[0]
243
+ elif not isinstance(to_unit, Unit):
244
+ raise ValueError("Target unit must be a unit symbol, identity, or Unit.")
245
+
246
+ if self.quantity != to_unit.quantity:
247
+ raise ValueError(
248
+ f"Cannot convert between {self.quantity} and {to_unit.quantity}."
249
+ )
250
+
251
+ source_a, source_b = self._get_conversion_factors()
252
+ target_a, target_b = to_unit._get_conversion_factors()
253
+ if source_a == 0:
254
+ raise ValueError(f"Conversion factor A is zero for unit {self.name}.")
255
+
256
+ base_value = (float(value) - source_b) / source_a
257
+ return base_value * target_a + target_b
258
+
259
+ @classmethod
260
+ def get_convertible_units(cls, unit: Union[str, "Unit"]) -> List["Unit"]:
261
+ """List units with usable conversion factors for the same quantity.
262
+
263
+ Args:
264
+ unit: A Unit instance, unit identity, or unambiguous unit symbol.
265
+
266
+ Returns:
267
+ List[Unit]: Compatible units, including the input unit when valid.
268
+
269
+ Raises:
270
+ ValueError: If the input cannot be resolved or has no usable factors.
271
+ """
272
+ if isinstance(unit, str):
273
+ matches = [candidate for candidate in cls.get_units() if candidate.identity == unit]
274
+ if not matches:
275
+ matches = [candidate for candidate in cls.get_units() if candidate.name == unit]
276
+ if not matches:
277
+ raise ValueError(f"No unit named or identified by {unit} found.")
278
+ if len(matches) > 1:
279
+ raise ValueError(f"Unit symbol {unit} is ambiguous; use its identity.")
280
+ unit = matches[0]
281
+ elif not isinstance(unit, cls):
282
+ raise ValueError("Input must be a Unit instance, unit symbol, or identity.")
283
+
284
+ source_a, _ = unit._get_conversion_factors()
285
+ if source_a == 0:
286
+ raise ValueError(f"Conversion factor A is zero for unit {unit.name}.")
287
+
288
+ convertible_units = []
289
+ for candidate in cls.get_units():
290
+ if candidate.quantity != unit.quantity:
291
+ continue
292
+ try:
293
+ factor_a, _ = candidate._get_conversion_factors()
294
+ except ValueError:
295
+ continue
296
+ if factor_a != 0:
297
+ convertible_units.append(candidate)
298
+
299
+ return convertible_units
300
+
301
+ def convertible_units(self) -> List["Unit"]:
302
+ """List units convertible with this unit's quantity."""
303
+ return type(self).get_convertible_units(self)
304
+
305
+ @classmethod
306
+ def get_units(cls) -> List["Unit"]:
307
+ """Get list of Unit objects of entries in code library. Caches locally in memory.
308
+
309
+ Returns:
310
+ List[Unit]: List of Unit objects from entries in code library.
311
+ """
312
+ if cls._units is None:
313
+ units = Code._get_code_data("UnitOfMeasure")
314
+ cls._units = tuple(cls._freeze_cache_value(unit) for unit in units)
315
+
316
+ return [cls(cls._thaw_cache_value(unit)) for unit in cls._units]
@@ -1,82 +0,0 @@
1
- from typing import List, Union
2
-
3
- from commonlib_reader.code import Code
4
-
5
-
6
- class Unit:
7
- """A class representing a unit of measurement.
8
-
9
- Properties:
10
- name (str): The name of the unit.
11
- description (str): A description of the unit.
12
- identity (str): The unique identifier for the unit.
13
- quantity (str): The quantity this unit measures.
14
- """
15
-
16
- _units = None
17
-
18
- def __init__(self, data: Union[dict, str]):
19
- if isinstance(data, str):
20
- s = [x for x in Unit.get_units() if x.name == data]
21
- if len(s) > 0:
22
- data = s[0]._data
23
- else:
24
- raise ValueError(f"No unit named {data} found.")
25
-
26
- if isinstance(data, dict):
27
- self._data = data
28
- for key in data.keys():
29
- if key == "attributes":
30
- for attr in data["attributes"]:
31
- self.__setattr__(attr["definitionName"], attr["displayValue"])
32
- else:
33
- self.__setattr__(key, data[key])
34
- else:
35
- raise ValueError("Input data must be a dict from codetable")
36
-
37
- @property
38
- def name(self) -> str:
39
- """Get the unit name."""
40
- return getattr(self, "_name", "")
41
-
42
- @name.setter
43
- def name(self, value: str):
44
- """Set the unit name."""
45
- self._name = value
46
-
47
- @property
48
- def description(self) -> str:
49
- """Get the unit description."""
50
- return getattr(self, "_description", "")
51
-
52
- @description.setter
53
- def description(self, value: str):
54
- """Set the unit description."""
55
- self._description = value
56
-
57
- @property
58
- def identity(self) -> str:
59
- """Get the unit identity."""
60
- return getattr(self, "_identity", "")
61
-
62
- @identity.setter
63
- def identity(self, value: str):
64
- """Set the unit identity."""
65
- self._identity = value
66
-
67
- @property
68
- def quantity(self) -> str:
69
- """Get the quantity measured by this unit."""
70
- return getattr(self, "Quantity", "")
71
-
72
- @classmethod
73
- def get_units(cls) -> List["Unit"]:
74
- """Get list of Unit objects of entries in code library. Caches locally in memory.
75
-
76
- Returns:
77
- List[Unit]: List of Unit objects from entries in code library.
78
- """
79
- if cls._units is None:
80
- cls._units = Code._get_code_data("UnitOfMeasure")
81
-
82
- return [Unit(x) for x in cls._units]