Skip to content

Commit dcae577

Browse files
Merge pull request #57 from linkml/ruff_lint_autofixes
Automatic python code fixes suggested by ruff
2 parents 10ae9a9 + 52248e7 commit dcae577

16 files changed

+214
-165
lines changed

src/linkml_map/compiler/compiler.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -81,9 +81,9 @@ def _compile_header(self, specification: TransformationSpecification) -> str:
8181
def _compile_iterator(self, specification: TransformationSpecification) -> Iterator[str]:
8282
raise NotImplementedError
8383

84-
def derived_target_schemaview(self, specification: TransformationSpecification):
84+
def derived_target_schemaview(self, specification: TransformationSpecification) -> SchemaView:
8585
"""
86-
Returns a view over the target schema, including any derived classes.
86+
Return a view over the target schema, including any derived classes.
8787
"""
8888
mapper = SchemaMapper(source_schemaview=self.source_schemaview)
8989
return SchemaView(yaml_dumper.dumps(mapper.derive_schema(specification)))

src/linkml_map/compiler/graphviz_compiler.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,10 @@ class Record(BaseModel):
2020
fields: list[tuple[str, str]] = []
2121

2222
@property
23-
def id(self):
23+
def id(self) -> str:
2424
return f"{self.source}{self.name}"
2525

26-
def __str__(self):
26+
def __str__(self) -> str:
2727
return (
2828
f"""<
2929
<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0">
@@ -47,6 +47,7 @@ class GraphvizObject(CompiledSpecification):
4747
def render(self, file_path: str, format="png", view=False) -> None:
4848
"""
4949
Render a graphviz graph to a file.
50+
5051
:param file_path:
5152
:return:
5253
"""

src/linkml_map/compiler/j2_based_compiler.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,13 @@ def compile(self, specification: TransformationSpecification) -> CompiledSpecifi
2424
if not template_dir:
2525
template_dir = TEMPLATE_DIR
2626
if not template_dir:
27-
raise ValueError("template_dir must be set")
27+
msg = "template_dir must be set"
28+
raise ValueError(msg)
2829
loader = FileSystemLoader(template_dir)
2930
env = Environment(loader=loader, autoescape=True)
3031
if not self.template_name:
31-
raise ValueError("template_name must be set")
32+
msg = "template_name must be set"
33+
raise ValueError(msg)
3234
template = env.get_template(self.template_name)
3335
rendered = template.render(
3436
spec=specification,

src/linkml_map/compiler/python_compiler.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -95,10 +95,7 @@ def _compile_iterator(self, specification: TransformationSpecification) -> Itera
9595

9696
def _compiled_class_derivations_iter(self, cd: ClassDerivation) -> Iterator[str]:
9797
sv = self.source_schemaview
98-
if cd.populated_from:
99-
populated_from = cd.populated_from
100-
else:
101-
populated_from = cd.name
98+
populated_from = cd.populated_from if cd.populated_from else cd.name
10299
if populated_from not in sv.all_classes():
103100
return
104101
induced_slots = {s.name: s for s in sv.class_induced_slots(populated_from)}

src/linkml_map/functions/unit_conversion.py

+31-24
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
from enum import Enum
1111
from functools import lru_cache
12-
from typing import Any, Optional
12+
from typing import Any, Optional, Union
1313

1414
import lark
1515
import pint
@@ -55,7 +55,7 @@ class DimensionalityError(Exception):
5555

5656
def convert_units(
5757
magnitude: float, from_unit: str, to_unit: str, system: Optional[UnitSystem] = None
58-
):
58+
) -> Any:
5959
"""
6060
Convert a quantity between units.
6161
@@ -79,28 +79,32 @@ def convert_units(
7979
:param to_unit:
8080
:return: converted magnitude
8181
"""
82-
import pint
83-
8482
ureg: pint.UnitRegistry = get_unit_registry(system)
8583
from_unit = normalize_unit(from_unit, system)
8684
to_unit = normalize_unit(to_unit, system)
8785
try:
8886
from_unit_q = ureg.parse_units(from_unit)
89-
except lark.exceptions.UnexpectedCharacters:
90-
raise UndefinedUnitError(f"Cannot parse unit: {from_unit}")
91-
except pint.errors.UndefinedUnitError:
92-
raise UndefinedUnitError(f"Unknown source unit: {from_unit}")
87+
except lark.exceptions.UnexpectedCharacters as err:
88+
msg = f"Cannot parse unit: {from_unit}"
89+
raise UndefinedUnitError(msg) from err
90+
except pint.errors.UndefinedUnitError as err:
91+
msg = f"Unknown source unit: {from_unit}"
92+
raise UndefinedUnitError(msg) from err
9393
quantity = magnitude * from_unit_q
9494
try:
9595
return quantity.to(to_unit).magnitude
96-
except pint.errors.UndefinedUnitError:
97-
raise UndefinedUnitError(f"Unknown target unit: {from_unit}")
98-
except pint.errors.DimensionalityError:
99-
raise DimensionalityError(f"Cannot convert from {from_unit} to {to_unit}")
96+
except pint.errors.UndefinedUnitError as err:
97+
msg = f"Unknown target unit: {from_unit}"
98+
raise UndefinedUnitError(msg) from err
99+
except pint.errors.DimensionalityError as err:
100+
msg = f"Cannot convert from {from_unit} to {to_unit}"
101+
raise DimensionalityError(msg) from err
100102

101103

102104
@lru_cache
103-
def get_unit_registry(system: Optional[UnitSystem] = None) -> Any:
105+
def get_unit_registry(
106+
system: Optional[UnitSystem] = None,
107+
) -> Union[pint.UnitRegistry, PintUcumRegistry]:
104108
"""
105109
Get a unit registry.
106110
@@ -140,18 +144,21 @@ def get_unit_registry(system: Optional[UnitSystem] = None) -> Any:
140144
if system.value in dir(ureg.sys):
141145
ureg.default_system = system.value
142146
return ureg
143-
raise NotImplementedError(f"Unknown unit system: {system}")
147+
msg = f"Unknown unit system: {system}"
148+
raise NotImplementedError(msg)
144149

145150

146151
def normalize_unit(unit: str, system: Optional[UnitSystem] = None) -> str:
147-
if system is None:
148-
return unit
149-
if system == UnitSystem.UCUM:
150-
try:
151-
return str(get_unit_registry(system).from_ucum(unit))
152-
except pint.errors.UndefinedUnitError:
153-
raise UndefinedUnitError(f"Unknown unit: {unit}")
154-
except lark.exceptions.UnexpectedCharacters:
155-
raise UndefinedUnitError(f"Cannot parse unit: {unit}")
156-
else:
152+
"""Normalize the unit to UnitSystem.UCUM, if possible."""
153+
if system is None or system != UnitSystem.UCUM:
157154
return unit
155+
156+
# this is UnitSystem.UCUM
157+
try:
158+
return str(get_unit_registry(system).from_ucum(unit))
159+
except pint.errors.UndefinedUnitError as err:
160+
msg = f"Unknown unit: {unit}"
161+
raise UndefinedUnitError(msg) from err
162+
except lark.exceptions.UnexpectedCharacters as err:
163+
msg = f"Cannot parse unit: {unit}"
164+
raise UndefinedUnitError(msg) from err

src/linkml_map/importer/importer.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ class Importer(ABC):
2727
@abstractmethod
2828
def import_specification(self, input: Any) -> TransformationSpecification:
2929
"""
30-
Import into a specification
30+
Import into a specification.
3131
3232
:param specification:
3333
:return:

src/linkml_map/inference/inference.py

+13-12
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
1+
"""Infer missing values in a specification."""
2+
13
from linkml_runtime import SchemaView
24

35
from linkml_map.datamodel.transformer_model import TransformationSpecification
46

57

68
def induce_missing_values(
79
specification: TransformationSpecification, source_schemaview: SchemaView
8-
):
10+
) -> None:
911
"""
1012
Infer missing values in a specification.
1113
@@ -24,15 +26,14 @@ def induce_missing_values(
2426
# TODO: decide if this is the desired behavior
2527
if sd.populated_from is None and sd.expr is None:
2628
sd.populated_from = sd.name
27-
if not sd.range:
29+
if not sd.range and sd.populated_from:
2830
# auto-populate range field
29-
if sd.populated_from:
30-
if cd.populated_from not in source_schemaview.all_classes():
31-
continue
32-
source_induced_slot = source_schemaview.induced_slot(
33-
sd.populated_from, cd.populated_from
34-
)
35-
source_induced_slot_range = source_induced_slot.range
36-
for range_cd in specification.class_derivations.values():
37-
if range_cd.populated_from == source_induced_slot_range:
38-
sd.range = range_cd.name
31+
if cd.populated_from not in source_schemaview.all_classes():
32+
continue
33+
source_induced_slot = source_schemaview.induced_slot(
34+
sd.populated_from, cd.populated_from
35+
)
36+
source_induced_slot_range = source_induced_slot.range
37+
for range_cd in specification.class_derivations.values():
38+
if range_cd.populated_from == source_induced_slot_range:
39+
sd.range = range_cd.name

src/linkml_map/inference/inverter.py

+25-23
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
"""Invert a transformation specification."""
2+
13
import logging
24
import re
35
from copy import copy
@@ -19,8 +21,8 @@
1921
logger = logging.getLogger(__name__)
2022

2123

22-
class NonInvertibleSpecification(ValueError):
23-
pass
24+
class NonInvertibleSpecificationError(ValueError):
25+
"""Error thrown when a specification is not invertible."""
2426

2527

2628
@dataclass
@@ -40,7 +42,7 @@ class TransformationSpecificationInverter:
4042

4143
strict: bool = field(default=True)
4244

43-
def invert(self, spec: TransformationSpecification):
45+
def invert(self, spec: TransformationSpecification) -> TransformationSpecification:
4446
"""
4547
Invert a transformation specification.
4648
@@ -57,7 +59,9 @@ def invert(self, spec: TransformationSpecification):
5759
inverted_spec.enum_derivations[inverted_ed.name] = inverted_ed
5860
return inverted_spec
5961

60-
def invert_class_derivation(self, cd: ClassDerivation, spec: TransformationSpecification):
62+
def invert_class_derivation(
63+
self, cd: ClassDerivation, spec: TransformationSpecification
64+
) -> ClassDerivation:
6165
"""
6266
Invert a class derivation.
6367
@@ -73,10 +77,13 @@ def invert_class_derivation(self, cd: ClassDerivation, spec: TransformationSpeci
7377
if inverted_sd:
7478
inverted_cd.slot_derivations[inverted_sd.name] = inverted_sd
7579
elif self.strict:
76-
raise NonInvertibleSpecification(f"Cannot invert slot derivation: {sd.name}")
80+
msg = f"Cannot invert slot derivation: {sd.name}"
81+
raise NonInvertibleSpecificationError(msg)
7782
return inverted_cd
7883

79-
def invert_enum_derivation(self, ed: EnumDerivation, spec: TransformationSpecification):
84+
def invert_enum_derivation(
85+
self, ed: EnumDerivation, spec: TransformationSpecification
86+
) -> EnumDerivation:
8087
"""
8188
Invert an enum derivation.
8289
@@ -88,7 +95,8 @@ def invert_enum_derivation(self, ed: EnumDerivation, spec: TransformationSpecifi
8895
name=ed.populated_from if ed.populated_from else ed.name, populated_from=ed.name
8996
)
9097
if inverted_ed.expr:
91-
raise NonInvertibleSpecification("TODO: invert enum derivation with expression")
98+
msg = "TODO: invert enum derivation with expression"
99+
raise NonInvertibleSpecificationError(msg)
92100
for pv_deriv in ed.permissible_value_derivations.values():
93101
inverted_pv_deriv = PermissibleValueDerivation(
94102
name=pv_deriv.populated_from if pv_deriv.populated_from else pv_deriv.name,
@@ -116,15 +124,13 @@ def invert_slot_derivation(
116124
if not self.strict:
117125
return None
118126
# TODO: add logic for reversible expressions
119-
raise NonInvertibleSpecification(
120-
f"Cannot invert expression {sd.expr} in slot derivation: {sd.name}"
121-
)
127+
msg = f"Cannot invert expression {sd.expr} in slot derivation: {sd.name}"
128+
raise NonInvertibleSpecificationError(msg)
129+
122130
if not populated_from:
123131
# use defaults. TODO: decide on semantics of defaults
124132
populated_from = sd.name
125-
# raise NonInvertibleSpecification(f"No populate_from or expr in slot derivation: {sd.name}")
126133
inverted_sd = SlotDerivation(name=populated_from, populated_from=sd.name)
127-
# source_cls_name = spec.class_derivations[cd.populated_from].name
128134
source_cls_name = cd.populated_from
129135
if (
130136
source_cls_name is None or source_cls_name in self.source_schemaview.all_classes()
@@ -133,7 +139,6 @@ def invert_slot_derivation(
133139
else:
134140
source_slot = None
135141
if sd.range:
136-
# source_slot = self.source_schemaview.induced_slot(sd.populated_from, source_cls_name)
137142
inverted_sd.range = source_slot.range
138143
if source_slot.range in self.source_schemaview.all_classes():
139144
id_slot = self.source_schemaview.get_identifier_slot(
@@ -144,14 +149,13 @@ def invert_slot_derivation(
144149
if source_slot and source_slot.multivalued:
145150
if source_slot.inlined_as_list:
146151
inverted_sd.cast_collection_as = CollectionType.MultiValuedList
147-
elif source_slot.inlined:
148-
if source_slot.range in self.source_schemaview.all_classes():
149-
id_slot = self.source_schemaview.get_identifier_slot(
150-
source_slot.range, use_key=True
151-
)
152-
if id_slot:
153-
inverted_sd.cast_collection_as = CollectionType.MultiValuedDict
154-
inverted_sd.dictionary_key = id_slot.name
152+
elif source_slot.inlined and source_slot.range in self.source_schemaview.all_classes():
153+
id_slot = self.source_schemaview.get_identifier_slot(
154+
source_slot.range, use_key=True
155+
)
156+
if id_slot:
157+
inverted_sd.cast_collection_as = CollectionType.MultiValuedDict
158+
inverted_sd.dictionary_key = id_slot.name
155159
if sd.unit_conversion:
156160
source_slot = self.source_schemaview.induced_slot(sd.populated_from, source_cls_name)
157161
target_unit = None
@@ -165,8 +169,6 @@ def invert_slot_derivation(
165169
inverted_uc = UnitConversionConfiguration(
166170
target_unit=target_unit, target_unit_scheme=target_unit_scheme
167171
)
168-
# if sd.unit_conversion.target_unit:
169-
# inverted_uc.source_unit = sd.unit_conversion.target_unit
170172
if sd.unit_conversion.source_unit_slot:
171173
inverted_uc.target_unit_slot = sd.unit_conversion.source_unit_slot
172174
if sd.unit_conversion.source_magnitude_slot:

0 commit comments

Comments
 (0)