| 1 |
""" |
| 2 |
pint.delegates.txt_defparser.context |
| 3 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 4 |
|
| 5 |
Definitions for parsing Context and their related objects |
| 6 |
|
| 7 |
Notices that some of the checks are done within the |
| 8 |
format agnostic parent definition class. |
| 9 |
|
| 10 |
See each one for a slighly longer description of the |
| 11 |
syntax. |
| 12 |
|
| 13 |
:copyright: 2022 by Pint Authors, see AUTHORS for more details. |
| 14 |
:license: BSD, see LICENSE for more details. |
| 15 |
""" |
| 16 |
|
| 17 |
from __future__ import annotations |
| 18 |
|
| 19 |
import numbers |
| 20 |
import re |
| 21 |
import typing as ty |
| 22 |
from dataclasses import dataclass |
| 23 |
from typing import Union |
| 24 |
|
| 25 |
import flexparser as fp |
| 26 |
|
| 27 |
from ...facets.context import definitions |
| 28 |
from ..base_defparser import ParserConfig, PintParsedStatement |
| 29 |
from . import block, common, plain |
| 30 |
|
| 31 |
# TODO check syntax |
| 32 |
T = ty.TypeVar("T", bound="Union[ForwardRelation, BidirectionalRelation]") |
| 33 |
|
| 34 |
|
| 35 |
def _from_string_and_context_sep( |
| 36 |
cls: type[T], s: str, config: ParserConfig, separator: str |
| 37 |
) -> T | None: |
| 38 |
if separator not in s: |
| 39 |
return None |
| 40 |
if ":" not in s: |
| 41 |
return None |
| 42 |
|
| 43 |
rel, eq = s.split(":") |
| 44 |
|
| 45 |
parts = rel.split(separator) |
| 46 |
|
| 47 |
src, dst = (config.to_dimension_container(s) for s in parts) |
| 48 |
|
| 49 |
return cls(src, dst, eq.strip()) |
| 50 |
|
| 51 |
|
| 52 |
@dataclass(frozen=True) |
| 53 |
class ForwardRelation(PintParsedStatement, definitions.ForwardRelation): |
| 54 |
"""A relation connecting a dimension to another via a transformation function. |
| 55 |
|
| 56 |
<source dimension> -> <target dimension>: <transformation function> |
| 57 |
""" |
| 58 |
|
| 59 |
@classmethod |
| 60 |
def from_string_and_config( |
| 61 |
cls, s: str, config: ParserConfig |
| 62 |
) -> fp.NullableParsedResult[ForwardRelation]: |
| 63 |
return _from_string_and_context_sep(cls, s, config, "->") |
| 64 |
|
| 65 |
|
| 66 |
@dataclass(frozen=True) |
| 67 |
class BidirectionalRelation(PintParsedStatement, definitions.BidirectionalRelation): |
| 68 |
"""A bidirectional relation connecting a dimension to another |
| 69 |
via a simple transformation function. |
| 70 |
|
| 71 |
<source dimension> <-> <target dimension>: <transformation function> |
| 72 |
|
| 73 |
""" |
| 74 |
|
| 75 |
@classmethod |
| 76 |
def from_string_and_config( |
| 77 |
cls, s: str, config: ParserConfig |
| 78 |
) -> fp.NullableParsedResult[BidirectionalRelation]: |
| 79 |
return _from_string_and_context_sep(cls, s, config, "<->") |
| 80 |
|
| 81 |
|
| 82 |
@dataclass(frozen=True) |
| 83 |
class BeginContext(PintParsedStatement): |
| 84 |
"""Being of a context directive. |
| 85 |
|
| 86 |
@context[(defaults)] <canonical name> [= <alias>] [= <alias>] |
| 87 |
""" |
| 88 |
|
| 89 |
_header_re = re.compile( |
| 90 |
r"@context\s*(?P<defaults>\(.*\))?\s+(?P<name>\w+)\s*(=(?P<aliases>.*))*" |
| 91 |
) |
| 92 |
|
| 93 |
name: str |
| 94 |
aliases: tuple[str, ...] |
| 95 |
defaults: dict[str, numbers.Number] |
| 96 |
|
| 97 |
@classmethod |
| 98 |
def from_string_and_config( |
| 99 |
cls, s: str, config: ParserConfig |
| 100 |
) -> fp.NullableParsedResult[BeginContext]: |
| 101 |
try: |
| 102 |
r = cls._header_re.search(s) |
| 103 |
if r is None: |
| 104 |
return None |
| 105 |
name = r.groupdict()["name"].strip() |
| 106 |
aliases = r.groupdict()["aliases"] |
| 107 |
if aliases: |
| 108 |
aliases = tuple(a.strip() for a in r.groupdict()["aliases"].split("=")) |
| 109 |
else: |
| 110 |
aliases = () |
| 111 |
defaults = r.groupdict()["defaults"] |
| 112 |
except Exception as exc: |
| 113 |
return common.DefinitionSyntaxError( |
| 114 |
f"Could not parse the Context header '{s}': {exc}" |
| 115 |
) |
| 116 |
|
| 117 |
if defaults: |
| 118 |
txt = defaults |
| 119 |
try: |
| 120 |
defaults = (part.split("=") for part in defaults.strip("()").split(",")) |
| 121 |
defaults = {str(k).strip(): config.to_number(v) for k, v in defaults} |
| 122 |
except (ValueError, TypeError) as exc: |
| 123 |
return common.DefinitionSyntaxError( |
| 124 |
f"Could not parse Context definition defaults '{txt}' {exc}" |
| 125 |
) |
| 126 |
else: |
| 127 |
defaults = {} |
| 128 |
|
| 129 |
return cls(name, tuple(aliases), defaults) |
| 130 |
|
| 131 |
|
| 132 |
@dataclass(frozen=True) |
| 133 |
class ContextDefinition( |
| 134 |
block.DirectiveBlock[ |
| 135 |
definitions.ContextDefinition, |
| 136 |
BeginContext, |
| 137 |
ty.Union[ |
| 138 |
plain.CommentDefinition, |
| 139 |
BidirectionalRelation, |
| 140 |
ForwardRelation, |
| 141 |
plain.UnitDefinition, |
| 142 |
], |
| 143 |
] |
| 144 |
): |
| 145 |
"""Definition of a Context |
| 146 |
|
| 147 |
@context[(defaults)] <canonical name> [= <alias>] [= <alias>] |
| 148 |
# units can be redefined within the context |
| 149 |
<redefined unit> = <relation to another unit> |
| 150 |
|
| 151 |
# can establish unidirectional relationships between dimensions |
| 152 |
<dimension 1> -> <dimension 2>: <transformation function> |
| 153 |
|
| 154 |
# can establish bidirectionl relationships between dimensions |
| 155 |
<dimension 3> <-> <dimension 4>: <transformation function> |
| 156 |
@end |
| 157 |
|
| 158 |
See BeginContext, Equality, ForwardRelation, BidirectionalRelation and |
| 159 |
Comment for more parsing related information. |
| 160 |
|
| 161 |
Example:: |
| 162 |
|
| 163 |
@context(n=1) spectroscopy = sp |
| 164 |
# n index of refraction of the medium. |
| 165 |
[length] <-> [frequency]: speed_of_light / n / value |
| 166 |
[frequency] -> [energy]: planck_constant * value |
| 167 |
[energy] -> [frequency]: value / planck_constant |
| 168 |
# allow wavenumber / kayser |
| 169 |
[wavenumber] <-> [length]: 1 / value |
| 170 |
@end |
| 171 |
""" |
| 172 |
|
| 173 |
def derive_definition(self) -> definitions.ContextDefinition: |
| 174 |
return definitions.ContextDefinition( |
| 175 |
self.name, self.aliases, self.defaults, self.relations, self.redefinitions |
| 176 |
) |
| 177 |
|
| 178 |
@property |
| 179 |
def name(self) -> str: |
| 180 |
assert isinstance(self.opening, BeginContext) |
| 181 |
return self.opening.name |
| 182 |
|
| 183 |
@property |
| 184 |
def aliases(self) -> tuple[str, ...]: |
| 185 |
assert isinstance(self.opening, BeginContext) |
| 186 |
return self.opening.aliases |
| 187 |
|
| 188 |
@property |
| 189 |
def defaults(self) -> dict[str, numbers.Number]: |
| 190 |
assert isinstance(self.opening, BeginContext) |
| 191 |
return self.opening.defaults |
| 192 |
|
| 193 |
@property |
| 194 |
def relations(self) -> tuple[BidirectionalRelation | ForwardRelation, ...]: |
| 195 |
return tuple( |
| 196 |
r |
| 197 |
for r in self.body |
| 198 |
if isinstance(r, (ForwardRelation, BidirectionalRelation)) |
| 199 |
) |
| 200 |
|
| 201 |
@property |
| 202 |
def redefinitions(self) -> tuple[plain.UnitDefinition, ...]: |
| 203 |
return tuple(r for r in self.body if isinstance(r, plain.UnitDefinition)) |