matcore 0.1.0__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.
Files changed (58) hide show
  1. matcore/README.md +41 -0
  2. matcore/__init__.py +7 -0
  3. matcore/__main__.py +4 -0
  4. matcore/checks.py +199 -0
  5. matcore/cli.py +44 -0
  6. matcore/formula.py +235 -0
  7. matcore/gnu_units.py +50 -0
  8. matcore/identifiers.py +44 -0
  9. matcore/releases/0.10.0/matcore.schema.json +9614 -0
  10. matcore/releases/0.10.0/schema/derived.yaml +183 -0
  11. matcore/releases/0.10.0/schema/dft.yaml +1135 -0
  12. matcore/releases/0.10.0/schema/gc.yaml +101 -0
  13. matcore/releases/0.10.0/schema/identifier-schemes.yaml +65 -0
  14. matcore/releases/0.10.0/schema/mbpt.yaml +407 -0
  15. matcore/releases/0.10.0/schema/meta-schema.yaml +85 -0
  16. matcore/releases/0.10.0/schema/minimal.yaml +3326 -0
  17. matcore/releases/0.10.0/schema/ml.yaml +708 -0
  18. matcore/releases/0.10.0/schema/pf.yaml +890 -0
  19. matcore/releases/0.10.0/schema/pim.yaml +689 -0
  20. matcore/releases/0.10.0/schema/ps.yaml +436 -0
  21. matcore/releases/0.10.0/schema/releases.yaml +127 -0
  22. matcore/releases/0.10.0/schema/units.yaml +115 -0
  23. matcore/releases/0.8.0/matcore.schema.json +6144 -0
  24. matcore/releases/0.8.0/schema/derived.yaml +183 -0
  25. matcore/releases/0.8.0/schema/dft.yaml +1071 -0
  26. matcore/releases/0.8.0/schema/identifier-schemes.yaml +65 -0
  27. matcore/releases/0.8.0/schema/mbpt.yaml +407 -0
  28. matcore/releases/0.8.0/schema/meta-schema.yaml +85 -0
  29. matcore/releases/0.8.0/schema/minimal.yaml +2741 -0
  30. matcore/releases/0.8.0/schema/ml.yaml +687 -0
  31. matcore/releases/0.8.0/schema/pf.yaml +890 -0
  32. matcore/releases/0.8.0/schema/pim.yaml +245 -0
  33. matcore/releases/0.8.0/schema/ps.yaml +433 -0
  34. matcore/releases/0.8.0/schema/releases.yaml +99 -0
  35. matcore/releases/0.8.0/schema/units.yaml +95 -0
  36. matcore/releases/0.9.0/matcore.schema.json +7672 -0
  37. matcore/releases/0.9.0/schema/derived.yaml +183 -0
  38. matcore/releases/0.9.0/schema/dft.yaml +1135 -0
  39. matcore/releases/0.9.0/schema/gc.yaml +101 -0
  40. matcore/releases/0.9.0/schema/identifier-schemes.yaml +65 -0
  41. matcore/releases/0.9.0/schema/mbpt.yaml +407 -0
  42. matcore/releases/0.9.0/schema/meta-schema.yaml +85 -0
  43. matcore/releases/0.9.0/schema/minimal.yaml +3123 -0
  44. matcore/releases/0.9.0/schema/ml.yaml +708 -0
  45. matcore/releases/0.9.0/schema/pf.yaml +890 -0
  46. matcore/releases/0.9.0/schema/pim.yaml +676 -0
  47. matcore/releases/0.9.0/schema/ps.yaml +436 -0
  48. matcore/releases/0.9.0/schema/releases.yaml +113 -0
  49. matcore/releases/0.9.0/schema/units.yaml +115 -0
  50. matcore/releases/__init__.py +53 -0
  51. matcore/validate.py +65 -0
  52. matcore-0.1.0.dist-info/METADATA +55 -0
  53. matcore-0.1.0.dist-info/RECORD +58 -0
  54. matcore-0.1.0.dist-info/WHEEL +4 -0
  55. matcore-0.1.0.dist-info/entry_points.txt +3 -0
  56. matcore-0.1.0.dist-info/licenses/LICENSE +201 -0
  57. matcore-0.1.0.dist-info/licenses/LICENSE-CC-BY-4.0 +395 -0
  58. matcore-0.1.0.dist-info/licenses/NOTICE +16 -0
matcore/README.md ADDED
@@ -0,0 +1,41 @@
1
+ # matcore
2
+
3
+ Tools for MatCore metadata records. MatCore (Material Core Metadata) is a reporting standard for the metadata of
4
+ computational materials science datasets.
5
+
6
+ This first release validates a record. It checks the record against the version of the standard the record names,
7
+ from 0.8.0 on:
8
+
9
+ - the record's JSON Schema: structure, types, shapes, values and units;
10
+ - the checks a JSON Schema cannot make:
11
+ - labels that name no structure or computation of the record;
12
+ - chemical formulas;
13
+ - identifier check digits;
14
+ - terms outside a vocabulary, as user-specified values or possible typos;
15
+ - a chemical potential's qualifiers;
16
+ - each `Unknown` value;
17
+ - `x-gnu:` units, when GNU Units is installed.
18
+
19
+ ```bash
20
+ pip install matcore
21
+ matcore validate record.json
22
+ matcore validate --json record.json
23
+ ```
24
+
25
+ Each finding gives its JSON pointer, a severity (error, warning or info), the rule it applies and a message. The
26
+ command exits with status 1 when any finding is an error.
27
+
28
+ In Python:
29
+
30
+ ```python
31
+ import json
32
+ from matcore import validate
33
+
34
+ for finding in validate(json.load(open('record.json'))):
35
+ print(finding.pointer, finding.severity, finding.message)
36
+ ```
37
+
38
+ ## Licences
39
+
40
+ All code in this package is licensed under Apache-2.0. The bundled releases of the standard (matcore/releases/) are
41
+ data licensed under CC BY 4.0. See https://matcore.org for the standard.
matcore/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """Tools for MatCore metadata records: validate a record against the standard version it names (decision 0089)."""
2
+ from importlib.metadata import version
3
+
4
+ from .validate import Finding, validate
5
+
6
+ __version__ = version('matcore')
7
+ __all__ = ['Finding', 'validate', '__version__']
matcore/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ """Run the matcore command line as `python -m matcore`."""
2
+ from .cli import main
3
+
4
+ raise SystemExit(main())
matcore/checks.py ADDED
@@ -0,0 +1,199 @@
1
+ """The checks a JSON Schema cannot make (decision 0089 item 3, amended 2026-11-29).
2
+
3
+ Each check reads the property definitions of the release a record names and pairs them with the record's values:
4
+ labels refer to structures and computations of the record and are unique; formulas follow their grammar; identifiers
5
+ pass their scheme's check digit (Annex I); a value outside an open vocabulary is user-specified, or a possible typo
6
+ when it is close to a listed term (0013); a chemical potential's qualified entries combine per species (0087 item 2);
7
+ each Unknown is counted (§1.3); an x-gnu: unit is read by GNU Units where it is installed.
8
+ """
9
+ import difflib
10
+ from collections import Counter, defaultdict
11
+
12
+ from . import gnu_units
13
+ from .formula import component_errors
14
+ from .identifiers import identifier_errors
15
+ from .releases import load, sections
16
+
17
+
18
+ def nodes(props, obj, path):
19
+ """Yield each value of a record that a property defines: (property, value, path, container).
20
+
21
+ props (list[dict]): the property definitions; obj: the record's object holding them; path (tuple): its path.
22
+ A repeatable property yields each entry with its index; a value of the wrong JSON type is skipped, the JSON Schema
23
+ having reported it.
24
+ """
25
+ if not isinstance(obj, dict):
26
+ return
27
+ for p in props:
28
+ if p['name'] not in obj:
29
+ continue
30
+ value, at = obj[p['name']], (*path, p['name'])
31
+ entries = enumerate(value) if p['repeatable'] and isinstance(value, list) else [(None, value)]
32
+ for i, entry in entries:
33
+ here = at if i is None else (*at, i)
34
+ yield p, entry, here, obj
35
+ if p.get('subproperties'):
36
+ yield from nodes(p['subproperties'], entry, here)
37
+
38
+
39
+ def scalars(value, path):
40
+ """Yield each string of a leaf's value with its path, descending into arrays (an Extent of [:] or more).
41
+
42
+ value: the leaf's value; path (tuple): its path.
43
+ """
44
+ if isinstance(value, list):
45
+ for i, v in enumerate(value):
46
+ yield from scalars(v, (*path, i))
47
+ elif isinstance(value, str):
48
+ yield value, path
49
+
50
+
51
+ def label_findings(found):
52
+ """Return (path, severity, rule, message) for duplicate labels and labels that name nothing.
53
+
54
+ found (list[tuple]): the nodes of the record.
55
+ """
56
+ defined = {'structure': [], 'computation': []}
57
+ for p, v, at, _ in found:
58
+ if p['name'] == 'label' and len(at) == 4 and at[:2] in (('minimal', 'structure'), ('minimal', 'computation')):
59
+ if isinstance(v, str):
60
+ defined[at[1]].append((v, at))
61
+ rule = 'labels (computation › label; 0046, 0062)'
62
+ count = Counter(v for pairs in defined.values() for v, _ in pairs)
63
+ out = [(at, 'error', rule, f'The label {v!r} names more than one structure or computation.')
64
+ for pairs in defined.values() for v, at in pairs if count[v] > 1]
65
+ names = {kind: {v for v, _ in pairs} for kind, pairs in defined.items()}
66
+ for p, v, at, container in found:
67
+ kind = {'structure-label': 'structure', 'computation-label': 'computation'}.get(p['name'])
68
+ if kind and not (kind == 'computation' and 'dataset' in container):
69
+ out += [(where, 'error', rule, f'No {kind} of the record has the label {s!r}.')
70
+ for s, where in scalars(v, at) if s not in names[kind]]
71
+ return out
72
+
73
+
74
+ def formula_findings(found):
75
+ """Return findings for material components whose formula breaks its grammar or its variables (0034).
76
+
77
+ found (list[tuple]): the nodes of the record.
78
+ """
79
+ out = []
80
+ for p, v, at, _ in found:
81
+ if p['name'] == 'material-component' and isinstance(v, dict) and isinstance(v.get('formula'), str):
82
+ variables = [(x.get('name'), x.get('value'), x.get('qualifier')) for x in v.get('variable', [])
83
+ if isinstance(x, dict) and isinstance(x.get('name'), str)
84
+ and isinstance(x.get('value'), (int, float))]
85
+ topologies = [t.get('substance') for t in v.get('topology', []) if isinstance(t, dict)]
86
+ out += [((*at, 'formula'), 'error', 'formula (minimal › structure › material-component › formula; 0034)', e)
87
+ for e in component_errors(v['formula'], variables, topologies)]
88
+ return out
89
+
90
+
91
+ def identifier_findings(found, schemes):
92
+ """Return findings for identifiers that fail their scheme's form or check digit.
93
+
94
+ found (list[tuple]): the nodes of the record; schemes (dict): the release's Annex I table.
95
+ """
96
+ return [((*at, 'value'), 'error', 'identifier (Annex I)', e)
97
+ for p, v, at, _ in found if p['name'] == 'identifier' and isinstance(v, dict)
98
+ and isinstance(v.get('value'), str) and isinstance(v.get('scheme'), str)
99
+ for e in identifier_errors(v['scheme'], v['value'], schemes)]
100
+
101
+
102
+ def terms_of(p, container):
103
+ """Return the open terms that apply to a leaf, or None when it has none: its own, or its sibling's case (0013).
104
+
105
+ p (dict): the property; container (dict): the object holding its value.
106
+ """
107
+ values = p.get('values') or {}
108
+ if 'depends-on' in values:
109
+ case = values['cases'].get(container.get(values['depends-on']))
110
+ return case.get('terms') if isinstance(case, dict) else None
111
+ return values.get('terms')
112
+
113
+
114
+ def term_findings(found):
115
+ """Return findings for values outside an open vocabulary: a warning when close to a term, else info (0013).
116
+
117
+ found (list[tuple]): the nodes of the record.
118
+ """
119
+ out = []
120
+ rule = 'open terms (0013)'
121
+ for p, v, at, container in found:
122
+ terms = None if p.get('subproperties') else terms_of(p, container)
123
+ for s, where in scalars(v, at) if terms else []:
124
+ if s in terms or s == 'Unknown':
125
+ continue
126
+ near = [t for t in terms if t.lower() == s.lower()] or difflib.get_close_matches(s, terms, 1, 0.8)
127
+ if near:
128
+ out.append((where, 'warning', rule, f'{s!r} is not a listed term; perhaps {near[0]!r}.'))
129
+ else:
130
+ out.append((where, 'info', rule, f'{s!r} is not a listed term; it is read as user-specified.'))
131
+ return out
132
+
133
+
134
+ def qualifier_findings(found):
135
+ """Return findings for a chemical potential's entries that do not combine, species by species: an entry without
136
+ a qualifier stands alone, and each listed qualifier occurs at most once (0087 item 2).
137
+
138
+ found (list[tuple]): the nodes of the record.
139
+ """
140
+ out = []
141
+ for p, v, at, _ in found:
142
+ cp = next((s for s in p.get('subproperties') or [] if s['name'] == 'chemical-potential'), None)
143
+ if p['name'] != 'conditions' or cp is None or not isinstance(v, dict):
144
+ continue
145
+ listed = next(s for s in cp['subproperties'] if s['name'] == 'qualifier')['values']['terms']
146
+ seen = defaultdict(list)
147
+ for i, entry in enumerate(v.get('chemical-potential') or []):
148
+ if not isinstance(entry, dict):
149
+ continue
150
+ q, before = entry.get('qualifier'), seen[entry.get('species')]
151
+ if (q is None and before) or (q is not None and (None in before or (q in listed and q in before))):
152
+ out.append(((*at, 'chemical-potential', i), 'error', 'chemical-potential qualifiers (0087 item 2)',
153
+ f'For species {entry.get("species")!r}, an entry without a qualifier stands alone, and '
154
+ f'each listed qualifier occurs at most once.'))
155
+ before.append(q)
156
+ return out
157
+
158
+
159
+ def unknown_findings(found):
160
+ """Return an info finding for each Unknown, so a validator counts what a record leaves unknown (§1.3).
161
+
162
+ found (list[tuple]): the nodes of the record.
163
+ """
164
+ return [(where, 'info', 'Unknown (§1.3)', "The information was not available to the record's author.")
165
+ for p, v, at, _ in found if not p.get('subproperties')
166
+ for s, where in scalars(v, at) if s == 'Unknown']
167
+
168
+
169
+ def gnu_findings(found):
170
+ """Return findings for x-gnu: units: checked by an installed GNU Units, else noted as unchecked.
171
+
172
+ found (list[tuple]): the nodes of the record.
173
+ """
174
+ rule = 'x-gnu: units (GNU Units; Annex U Rule 4)'
175
+ out = []
176
+ for p, v, at, _ in found:
177
+ if p['name'] != 'unit' or not isinstance(v, str) or not v.startswith('x-gnu:'):
178
+ continue
179
+ program = gnu_units.find()
180
+ if program is None:
181
+ out.append((at, 'info', rule, 'Not checked: GNU Units is not installed.'))
182
+ continue
183
+ out += [(at, 'error', rule, e) for e in gnu_units.errors(v.removeprefix('x-gnu:'))]
184
+ if program[1] != gnu_units.PINNED:
185
+ out.append((at, 'info', rule, f'Checked with GNU Units {program[1]}; Annex U Rule 4 pins '
186
+ f'{gnu_units.PINNED}.'))
187
+ return out
188
+
189
+
190
+ def check(record, version):
191
+ """Return the findings of the checks a JSON Schema cannot make, as (path, severity, rule, message).
192
+
193
+ record (dict): the record; version (str): the bundled release it names.
194
+ """
195
+ found = [n for key, props in sections(version).items() if isinstance(record.get(key), dict)
196
+ for n in nodes(props, record[key], (key,))]
197
+ schemes = load(version, 'identifier-schemes')['schemes']
198
+ return (label_findings(found) + formula_findings(found) + identifier_findings(found, schemes)
199
+ + term_findings(found) + qualifier_findings(found) + unknown_findings(found) + gnu_findings(found))
matcore/cli.py ADDED
@@ -0,0 +1,44 @@
1
+ """The matcore command line (decision 0089 item 2).
2
+
3
+ matcore validate [--json] FILE... prints the findings of each record; exits 1 when any finding is an error.
4
+ """
5
+ import argparse
6
+ import json
7
+ import sys
8
+
9
+ from .validate import Finding, validate
10
+
11
+
12
+ def findings_of(path):
13
+ """Return the findings of a record file, a file that is not JSON being one error.
14
+
15
+ path (str): the file's path.
16
+ """
17
+ try:
18
+ with open(path, encoding='utf-8') as f:
19
+ record = json.load(f)
20
+ except json.JSONDecodeError as e:
21
+ return [Finding('', 'error', 'JSON (RFC 8259)', f'Not valid JSON: {e.msg} at line {e.lineno}, column {e.colno}.')]
22
+ return validate(record)
23
+
24
+
25
+ def main(argv=None):
26
+ """Run the command line and return its exit status.
27
+
28
+ argv (list[str] | None): the arguments, sys.argv[1:] when None.
29
+ """
30
+ parser = argparse.ArgumentParser(prog='matcore', description='Tools for MatCore metadata records.')
31
+ commands = parser.add_subparsers(dest='command', required=True)
32
+ check = commands.add_parser('validate', help='check records against the standard version each one names')
33
+ check.add_argument('--json', action='store_true', help='print the findings as JSON')
34
+ check.add_argument('files', nargs='+', metavar='FILE')
35
+ args = parser.parse_args(argv)
36
+ results = {path: findings_of(path) for path in args.files}
37
+ if args.json:
38
+ json.dump({p: [f.to_dict() for f in fs] for p, fs in results.items()}, sys.stdout, indent=1, ensure_ascii=False)
39
+ print()
40
+ else:
41
+ for path, fs in results.items():
42
+ print(f'{path}: no findings' if not fs else '\n'.join(
43
+ f'{path}: {f.severity} {f.pointer or "/"} {f.message} ({f.rule})' for f in fs))
44
+ return int(any(f.severity == 'error' for fs in results.values() for f in fs))
matcore/formula.py ADDED
@@ -0,0 +1,235 @@
1
+ """Parse and check a material component's chemical formula (decision 0034).
2
+
3
+ formula_errors() checks one formula against the grammar of the `formula` note; component_errors() also checks it
4
+ against the component's `variable` and `topology` entries. The reserved value Unknown (§1.3) is a whole formula with
5
+ no terms (decision 0087 item 6).
6
+
7
+ A count is held as a linear expression: a dict from variable name to coefficient, '' for the constant.
8
+ """
9
+ import itertools
10
+ import re
11
+ from collections import Counter
12
+
13
+ # The 118 symbols of the IUPAC Periodic Table, atomic numbers 1 to 118, as listed in the Standard Atomic
14
+ # Weights table of the IUPAC Commission on Isotopic Abundances and Atomic Weights (https://www.ciaaw.org/atomic-weights.htm).
15
+ ELEMENTS = (
16
+ 'H He Li Be B C N O F Ne Na Mg Al Si P S Cl Ar K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr Rb Sr Y '
17
+ 'Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe Cs Ba La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu Hf Ta W Re '
18
+ 'Os Ir Pt Au Hg Tl Pb Bi Po At Rn Fr Ra Ac Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr Rf Db Sg Bh Hs Mt Ds '
19
+ 'Rg Cn Nh Fl Mc Lv Ts Og').split()
20
+ NUMBER = re.compile(r'[0-9]+(\.[0-9]+)?')
21
+ USER = re.compile(r'J[a-z]+')
22
+ SYMBOL = re.compile(r'[A-Z][a-z]?')
23
+ TOLERANCE = 1e-9
24
+
25
+
26
+ class FormulaError(ValueError):
27
+ """A formula that does not follow the grammar; the message says where."""
28
+
29
+
30
+ class Parser:
31
+ """Recursive-descent parser for the grammar of decision 0034 item 3.
32
+
33
+ text (str): the formula. After parse(), `groups` holds the text inside every pair of group parentheses.
34
+ """
35
+
36
+ def __init__(self, text):
37
+ self.s, self.i, self.groups = text, 0, []
38
+
39
+ def peek(self):
40
+ """Return the next character, or '' at the end."""
41
+ return self.s[self.i:self.i + 1]
42
+
43
+ def fail(self, message):
44
+ """Raise a FormulaError at the current position.
45
+
46
+ message (str): what is wrong.
47
+ """
48
+ raise FormulaError(f'{self.s!r}, position {self.i}: {message}')
49
+
50
+ def expect(self, char, what):
51
+ """Consume char, or fail: 'unclosed' at the end, 'unexpected' before another character.
52
+
53
+ char (str): the closing character; what (str): the bracket's name, for the message.
54
+ """
55
+ if self.peek() == char:
56
+ self.i += 1
57
+ elif self.peek():
58
+ self.fail(f'unexpected character {self.peek()!r}')
59
+ else:
60
+ self.fail(f'unclosed {what}')
61
+
62
+ def parse(self):
63
+ """Return the formula's terms, a list of (item, count); an item is a symbol (str) or a list of terms.
64
+
65
+ The reserved value Unknown (§1.3) is a whole formula with no terms (decision 0087 item 6).
66
+ """
67
+ if self.s == 'Unknown':
68
+ return []
69
+ if not self.s:
70
+ raise FormulaError('empty formula')
71
+ terms = self.formula()
72
+ if self.peek():
73
+ self.fail(f'unexpected character {self.peek()!r}')
74
+ return terms
75
+
76
+ def formula(self):
77
+ """Return the terms up to the end or a closing parenthesis."""
78
+ terms = []
79
+ while self.peek() and self.peek() != ')':
80
+ terms.append(self.term())
81
+ if not terms:
82
+ self.fail('empty group')
83
+ return terms
84
+
85
+ def term(self):
86
+ """Return one (item, count): an element, a user-defined species or a group, then its count."""
87
+ c, start = self.peek(), self.i
88
+ if c == '(':
89
+ self.i += 1
90
+ item = self.formula()
91
+ self.expect(')', 'parenthesis')
92
+ self.groups.append(self.s[start + 1:self.i - 1])
93
+ elif c == 'J':
94
+ m = USER.match(self.s, self.i)
95
+ if not m:
96
+ self.fail('a user-defined species is J followed by lowercase letters')
97
+ item, self.i = m.group(), m.end()
98
+ elif c.isupper():
99
+ m = SYMBOL.match(self.s, self.i)
100
+ item = m.group() if m.group() in ELEMENTS else c
101
+ if item not in ELEMENTS:
102
+ self.fail(f'unknown element symbol {m.group()!r}')
103
+ self.i += len(item)
104
+ else:
105
+ self.fail(f'unexpected character {c!r}')
106
+ return item, self.count()
107
+
108
+ def count(self):
109
+ """Return the count after a term: a number, an expression in braces, or 1 when none is written."""
110
+ if self.peek() == '{':
111
+ self.i += 1
112
+ e = self.expr()
113
+ self.expect('}', 'brace')
114
+ if set(e) <= {''}:
115
+ self.fail('braces hold an expression with a variable; write a fixed count as a number')
116
+ return e
117
+ m = NUMBER.match(self.s, self.i)
118
+ if not m:
119
+ return {'': 1.0}
120
+ value = float(m.group())
121
+ if value == 0:
122
+ self.fail('a count must be positive')
123
+ if value == 1:
124
+ self.fail('a count of 1 is omitted')
125
+ self.i = m.end()
126
+ return {'': value}
127
+
128
+ def expr(self):
129
+ """Return a sum of products, each optionally signed, as a linear expression."""
130
+ out = {}
131
+ while True:
132
+ sign = 1
133
+ if self.peek() in ('+', '-'):
134
+ sign = -1 if self.peek() == '-' else 1
135
+ self.i += 1
136
+ for k, v in self.product().items():
137
+ out[k] = out.get(k, 0) + sign * v
138
+ if not (self.peek() and self.peek() in '+-'):
139
+ return out
140
+
141
+ def product(self):
142
+ """Return a product of factors written side by side (implied multiplication), which must stay linear."""
143
+ out = None
144
+ while self.peek() and (self.peek().isdigit() or self.peek().islower() or self.peek() == '('):
145
+ f = self.factor()
146
+ if out is None:
147
+ out = f
148
+ elif set(out) - {''} and set(f) - {''}:
149
+ self.fail('an expression must be linear in its variables')
150
+ else:
151
+ c, e = (out, f) if set(out) <= {''} else (f, out)
152
+ out = {k: c[''] * v for k, v in e.items()}
153
+ if out is None:
154
+ self.fail(f'unexpected character {self.peek()!r}' if self.peek() else 'unclosed brace')
155
+ return out
156
+
157
+ def factor(self):
158
+ """Return a number, a one-letter variable, or a parenthesized expression."""
159
+ if self.peek() == '(':
160
+ self.i += 1
161
+ e = self.expr()
162
+ self.expect(')', 'parenthesis')
163
+ return e
164
+ m = NUMBER.match(self.s, self.i)
165
+ if m:
166
+ self.i = m.end()
167
+ return {'': float(m.group())}
168
+ self.i += 1
169
+ return {self.s[self.i - 1]: 1.0}
170
+
171
+
172
+ def formula_errors(formula):
173
+ """Return the grammar errors of a formula, as messages (at most one: parsing stops at the first).
174
+
175
+ formula (str): the formula.
176
+ """
177
+ try:
178
+ Parser(formula).parse()
179
+ except FormulaError as e:
180
+ return [str(e)]
181
+ return []
182
+
183
+
184
+ def counts(terms):
185
+ """Yield every count in the terms, at every depth.
186
+
187
+ terms (list): parsed terms, as Parser.parse() returns them.
188
+ """
189
+ for item, count in terms:
190
+ yield count
191
+ if isinstance(item, list):
192
+ yield from counts(item)
193
+
194
+
195
+ def component_errors(formula, variables, topologies):
196
+ """Return the errors of a material component's composition, as messages.
197
+
198
+ formula (str): its `formula`; variables (list[tuple]): its `variable` entries as (name, value,
199
+ qualifier), qualifier None when absent; topologies (list[str]): the `substance` of each of its
200
+ `topology` entries.
201
+ """
202
+ parser = Parser(formula)
203
+ try:
204
+ terms = parser.parse()
205
+ except FormulaError as e:
206
+ return [str(e)]
207
+ out = [f'variable name {n!r} is not one lowercase letter' for n in {n for n, _, _ in variables}
208
+ if not re.fullmatch('[a-z]', n)]
209
+ used = {k for c in counts(terms) for k in c if k}
210
+ given = {}
211
+ for name, value, qualifier in variables:
212
+ given.setdefault(name, []).append((value, qualifier))
213
+ out += [f'{n!r} has no variable entry' for n in sorted(used - set(given))]
214
+ out += [f'variable {n!r} is not in the formula' for n in sorted(set(given) - used)]
215
+ for name, entries in given.items():
216
+ types = Counter(t for _, t in entries)
217
+ out += [f'variable {name!r} has more than one {t}' for t, k in types.items() if t and k > 1]
218
+ if not out:
219
+ ranges = [[(n, min(v for v, _ in given[n])), (n, max(v for v, _ in given[n]))] for n in sorted(used)]
220
+ for corner in itertools.product(*ranges):
221
+ at = dict(corner)
222
+ for c in counts(terms):
223
+ if sum(v * at.get(k, 1) if k else v for k, v in c.items()) < -TOLERANCE:
224
+ where = ', '.join(f'{k}={v}' for k, v in at.items())
225
+ out.append(f'a count in {formula!r} falls below 0 at {where}')
226
+ break
227
+ if len(terms) > 1 and all(isinstance(item, list) for item, _ in terms):
228
+ total = Counter()
229
+ for _, c in terms:
230
+ total.update(c)
231
+ if abs(total[''] - 1) > TOLERANCE or any(abs(v) > TOLERANCE for k, v in total.items() if k):
232
+ out.append(f'the counts of the groups of {formula!r}, a mixture, must sum to 1')
233
+ out += [f'topology {m!r} is not a group of {formula!r} or the whole formula' for m in topologies
234
+ if m != formula and m not in parser.groups]
235
+ return out
matcore/gnu_units.py ADDED
@@ -0,0 +1,50 @@
1
+ """Check an x-gnu: unit expression with an installed GNU Units (decision 0089, amended 2026-11-29).
2
+
3
+ Nothing from GNU Units is bundled: its database is licensed GPL-3.0-or-later. The program is looked for as `gunits`,
4
+ then `units`, and used only if its --version output names GNU Units (macOS ships a different `units`). An expression
5
+ is accepted when GNU Units converts it to itself with factor 1; the manual states no exit status for an unknown unit,
6
+ so the answer, not the status, decides.
7
+ """
8
+ import re
9
+ import shutil
10
+ import subprocess
11
+ from functools import cache
12
+
13
+ PINNED = '2.23' # the version Annex U Rule 4 pins
14
+ TIMEOUT = 10
15
+
16
+
17
+ @cache
18
+ def find():
19
+ """Return (path, version) of an installed GNU Units, or None when there is none."""
20
+ for name in ('gunits', 'units'):
21
+ path = shutil.which(name)
22
+ if not path:
23
+ continue
24
+ try:
25
+ out = subprocess.run([path, '--version'], capture_output=True, text=True, timeout=TIMEOUT).stdout
26
+ except (OSError, subprocess.SubprocessError):
27
+ continue
28
+ if 'gnu units' in out.lower():
29
+ version = re.search(r'\d+\.\d+(\.\d+)?', out)
30
+ return path, version.group() if version else ''
31
+ return None
32
+
33
+
34
+ def errors(expression):
35
+ """Return GNU Units' complaint about an expression, as a list of at most one message; empty when it reads it.
36
+
37
+ expression (str): the expression after `x-gnu:`. find() must have found GNU Units.
38
+ """
39
+ path, _ = find()
40
+ try:
41
+ r = subprocess.run([path, '--terse', expression, expression], capture_output=True, text=True,
42
+ timeout=TIMEOUT)
43
+ except (OSError, subprocess.SubprocessError) as e:
44
+ return [f'GNU Units could not be run: {e}']
45
+ try:
46
+ if abs(float(r.stdout.strip()) - 1) < 1e-9:
47
+ return []
48
+ except ValueError:
49
+ pass
50
+ return [' '.join((r.stdout + r.stderr).split()) or 'GNU Units could not read the expression']
matcore/identifiers.py ADDED
@@ -0,0 +1,44 @@
1
+ """Check an identifier against its scheme in Annex I: pattern and check digit (decision 0014).
2
+
3
+ The scheme table is a release's schema/identifier-schemes.yaml; identifier_errors() takes it as an argument, so a
4
+ record is checked against the table of the version it names.
5
+ """
6
+ import re
7
+
8
+ CROCKFORD = '0123456789abcdefghjkmnpqrstvwxyz'
9
+
10
+
11
+ def mod11_2(chars):
12
+ """Return True if the last of chars (str) is the ISO/IEC 7064 MOD 11-2 check character of the rest."""
13
+ total = 0
14
+ for c in chars[:-1]:
15
+ total = (total + int(c)) * 2
16
+ r = (12 - total % 11) % 11
17
+ return chars[-1] == ('X' if r == 10 else str(r))
18
+
19
+
20
+ def mod97_10_ror(chars):
21
+ """Return True if the last two of chars (str, e.g. '02mhbdp94') are ROR's checksum of the six before them."""
22
+ n = 0
23
+ for c in chars[1:7]:
24
+ n = n * 32 + CROCKFORD.index(c)
25
+ return chars[7:] == str(98 - (n * 100) % 97).zfill(2)
26
+
27
+
28
+ CHECKSUMS = {'iso7064-mod11-2': mod11_2, 'iso7064-mod97-10-ror': mod97_10_ror, None: None}
29
+
30
+
31
+ def identifier_errors(scheme, value, schemes):
32
+ """Return the errors of an identifier value, as messages; none for a scheme outside the table.
33
+
34
+ scheme (str): the identifier's scheme; value (str): its value; schemes (dict): the scheme table.
35
+ """
36
+ s = schemes.get(scheme)
37
+ if s is None:
38
+ return []
39
+ if not re.fullmatch(s['pattern'], value):
40
+ return [f'{value!r} is not in the form of {scheme}: {s["form"]}']
41
+ check = CHECKSUMS[s['checksum']]
42
+ if check and not check(value.rsplit('/', 1)[-1].replace('-', '')):
43
+ return [f'{value!r} fails the {scheme} check digit']
44
+ return []