unitsml 0.6.10 → 0.6.12

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 35805b77f3e1587e414519d8d7526fe96db3708fdb8fe95e8113b64f9ca26f49
4
- data.tar.gz: e012fbeba397f8b3b85b57cc7a56d77839f0dba449a5d75d98d73163f5a9a932
3
+ metadata.gz: efbbf3687355c803f0d27613089435d0b7773d7b9a0da6b1e84205d3ffb2d3e6
4
+ data.tar.gz: 74ac8457146883ac81a3b2596bbb4f16193676509c588d838c97199843ce520e
5
5
  SHA512:
6
- metadata.gz: 3fd505b4a288aa157e8aa34a8d123f872dd13a32fbe8d2c41caa85cf5ee03ddf4ab96e5aeea27420932266f74609d065e5285d6fbaad66ea3c107a1ebb8bb85c
7
- data.tar.gz: 770c47c3a78f61cabad7975e39e314f5c959f0983df0e6cebaf23b55840ad550c911c9d08483d8378fd1100fb8176170b4bf60f3d2f0afc93557bf2fdea766b2
6
+ metadata.gz: cb598545c494c983148c0cc7b604d6871b10e93b426c533bcfa3a1429e559f1a6ccda07444186a4a502699a30c9f3ea2d81995ba6ed4176de0a6e95f3aeb99fa
7
+ data.tar.gz: ed77d97452ecbbccd900027206625d31057046c9c69de0c2b62771fe087e375b33aa03d13b664598dda68c5d26a68d94e0e833b14de9b43bab907a0a7f9e3857
@@ -14,6 +14,8 @@ jobs:
14
14
  mkdir -p .bundle
15
15
  touch .bundle/config
16
16
  cat .bundle/config
17
+ git clone --depth 1 https://github.com/unitsml/unitsml-testsuite.git unitsml-testsuite
18
+ echo "CORPUS_DIR=$PWD/unitsml-testsuite/corpora/renders" >> "$GITHUB_ENV"
17
19
  echo "---" >> .bundle/config
18
20
  echo 'BUNDLE_BUILD__RUBY___LL: "--with-cflags=-std=gnu17"' >> .bundle/config
19
21
  cat .bundle/config
data/docs/README.adoc CHANGED
@@ -283,6 +283,19 @@ unit.to_asciimath(explicit_parenthesis: false) # "m/s^-1*m/s^-1"
283
283
  ====
284
284
 
285
285
 
286
+ == JavaScript / TypeScript
287
+
288
+ The native JavaScript implementation of UnitsML is the `unitsml` package
289
+ on npm (https://github.com/unitsml/unitsml-ts[unitsml/unitsml-ts]) — a
290
+ TypeScript implementation on the shared checksummed
291
+ https://github.com/unitsml/asciiunits[PARG] grammar artifact, with
292
+ `asciiunits` and `unitsdb` as its npm dependencies. Ruby and TypeScript
293
+ share conformance corpora (parse and render oracles) to guarantee
294
+ identical behavior.
295
+
296
+ The former Opal-compiled `@unitsml/unitsml` package is deprecated; its
297
+ repository (unitsml/unitsml-js) is archived.
298
+
286
299
  == Installation
287
300
 
288
301
  Add this line to your application's Gemfile:
@@ -0,0 +1,276 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Unitsml
4
+ # Canonical unit conversion (R-A3): reduces a parsed unit expression to
5
+ # its SI-referenced canonical composition using the unitsdb
6
+ # canonical_conversion data (unitsdb schema 2.1.0), prefix factors and
7
+ # si_derived_bases/root_units chains.
8
+ #
9
+ # Semantics: value_target = value * factor + offset. The additive offset
10
+ # exists only for affine scales (temperature) and is permitted only when
11
+ # the whole expression is that single unit with power 1 — an affine unit
12
+ # inside a composite raises.
13
+ module Conversion
14
+ Result = Struct.new(:factor, :offset, keyword_init: true)
15
+
16
+ module_function
17
+
18
+ # The dispatch walkers mirror the grammar's case structure; the
19
+ # branchiness is inherent and gated by the conformance suite.
20
+ # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Metrics/MethodLength, Layout/LineLength, Lint/DuplicateBranch, Lint/ElseLayout
21
+
22
+ # Returns a Result for the parsed expression.
23
+ def to_canonical(formula)
24
+ walk(formula, 1)
25
+ end
26
+
27
+ def walk(node, sign)
28
+ case node
29
+ when Formula
30
+ # The parser already normalizes "/" and "//" by inverting the
31
+ # following exponents (update_units_exponents), so the tree walks
32
+ # multiplicatively with no sign tracking.
33
+ node.value.reduce(Result.new(factor: Rational(1), offset: 0)) do |acc, part|
34
+ next acc if part.is_a?(Extender)
35
+
36
+ merge(acc, walk_with_sign(part, sign))
37
+ end
38
+ when Fenced
39
+ walk(node.value, sign)
40
+ when Sqrt
41
+ sub = walk(node.value, sign)
42
+ Result.new(factor: sqrt_rational(sub.factor), offset: sub.offset)
43
+ when Extender
44
+ Result.new(factor: Rational(1), offset: 0)
45
+ when Unit
46
+ unit_result(node, sign)
47
+ when Dimension, Number_, Prefix
48
+ Result.new(factor: Rational(1), offset: 0)
49
+ else
50
+ raise Errors::ConversionError, "cannot convert #{node.class} node"
51
+ end
52
+ end
53
+
54
+ def walk_inner(node, sign)
55
+ case node
56
+ when Formula
57
+ # The parser already normalizes "/" and "//" by inverting the
58
+ # following exponents (update_units_exponents), so the tree walks
59
+ # multiplicatively with no sign tracking.
60
+ node.value.reduce(Result.new(factor: Rational(1),
61
+ offset: 0)) do |acc, part|
62
+ next acc if part.is_a?(Extender)
63
+
64
+ merge(acc, walk_with_sign(part, sign))
65
+ end
66
+ when Fenced
67
+ walk(node.value, sign)
68
+ when Sqrt
69
+ sub = walk(node.value, sign)
70
+ Result.new(factor: sqrt_rational(sub.factor), offset: sub.offset)
71
+ when Extender
72
+ Result.new(factor: Rational(1), offset: 0)
73
+ when Unit
74
+ unit_result(node, sign)
75
+ when Dimension, Number_, Prefix
76
+ Result.new(factor: Rational(1), offset: 0)
77
+ else
78
+ raise Errors::ConversionError, "cannot convert #{node.class} node"
79
+ end
80
+ end
81
+
82
+ def walk_with_sign(part, sign)
83
+ result = walk(part, sign)
84
+ sign.negative? ? Result.new(factor: 1 / result.factor, offset: 0) : result
85
+ end
86
+
87
+ def merge(left, right)
88
+ if (left.offset != 0 && right.factor != 1) || (right.offset != 0 && left.factor != 1)
89
+ raise Errors::ConversionError,
90
+ "affine unit inside a composite expression"
91
+ end
92
+
93
+ Result.new(
94
+ factor: left.factor * right.factor,
95
+ offset: left.offset + right.offset,
96
+ )
97
+ end
98
+
99
+ def unit_result(unit, _sign)
100
+ prefix_factor = if unit.prefix
101
+ Rational(unit.prefix.base)**unit.prefix.power
102
+ else
103
+ Rational(1)
104
+ end
105
+ power = node_power(unit.power_numerator)
106
+ record = unit.unit_instance
107
+ unless record
108
+ raise Errors::ConversionError,
109
+ "unknown unit #{unit.unit_name.inspect}"
110
+ end
111
+
112
+ factor, offset = record_factor(record, power, [record_identity(record)])
113
+ factor *= prefix_factor
114
+ Result.new(factor: factor, offset: offset)
115
+ end
116
+
117
+ # [multiplicative factor, additive offset] for one unit record at the
118
+ # given power. Cyclic derivations (e.g. a unit defined in terms of
119
+ # itself) have no linear canonical conversion and raise.
120
+ def record_identity(record)
121
+ record.identifiers&.map { |i| "#{i.type}:#{i.id}" }&.sort&.join("|")
122
+ end
123
+
124
+ def record_factor(record, power, _visited = [])
125
+ cc = record.canonical_conversion
126
+ return conversion_factor(cc, power) if cc
127
+
128
+ bases = record.si_derived_bases
129
+ bases = record.root_units if bases.nil? || bases.empty?
130
+ if bases.nil? || bases.empty?
131
+ system = record.unit_system_reference&.first&.id.to_s
132
+ if Lutaml::Model::Utils.snake_case(system) == "si_base"
133
+ return [Rational(1),
134
+ Rational(0)]
135
+ end
136
+
137
+ raise Errors::ConversionError,
138
+ "no canonical conversion path for #{record.symbols&.first&.id.inspect}"
139
+ end
140
+
141
+ factor = Rational(1)
142
+ bases.each do |base|
143
+ base_power = (base.power || 1) * power
144
+ prefix_factor = prefix_factor_from_reference(base.prefix_reference)
145
+ sub_factor, sub_offset = base_factor(base.unit_reference, base_power)
146
+ if sub_offset != 0
147
+ raise Errors::ConversionError,
148
+ "affine unit inside a derived composition"
149
+ end
150
+
151
+ factor *= (prefix_factor**power) * (sub_factor**base_power)
152
+ end
153
+ [factor, Rational(0)]
154
+ end
155
+
156
+ def conversion_factor(cc, power)
157
+ if cc.offset && cc.offset != "0" && power != 1
158
+ raise Errors::ConversionError, "affine unit raised to power #{power}"
159
+ end
160
+
161
+ factor = Rational(cc.factor)**power
162
+ offset = Rational(cc.offset || 0)
163
+ [factor, offset]
164
+ end
165
+
166
+ def base_factor(unit_reference, power)
167
+ record = Unitsml::Unitsdb.units.find_by_id(unit_reference.id)
168
+ raise Errors::ConversionError, "unknown conversion target" unless record
169
+
170
+ record_factor(record, power)
171
+ end
172
+
173
+ def prefix_factor_from_reference(reference)
174
+ return Rational(1) if reference.nil?
175
+
176
+ record = Unitsml::Unitsdb.prefixes.find_by_id(reference.id)
177
+ return Rational(1) unless record
178
+
179
+ Rational(record.base)**record.power
180
+ end
181
+
182
+ def node_power(numerator)
183
+ return 1 if numerator.nil?
184
+
185
+ numerator.raw_value.to_s.to_r
186
+ end
187
+
188
+ def sqrt_rational(rational)
189
+ root = Integer.sqrt(rational.numerator)
190
+ den = Integer.sqrt(rational.denominator)
191
+ if root * root == rational.numerator && den * den == rational.denominator
192
+ Rational(root, den)
193
+ else
194
+ raise Errors::ConversionError,
195
+ "square root of #{rational} is not rational"
196
+ end
197
+ end
198
+
199
+ # Dimension-only decomposition (no factors): the same entry shape
200
+ # Utility.units2dimensions returns, for units that canonical data can
201
+ # reduce but the legacy decomposition cannot. nil when any unit has
202
+ # no path.
203
+ def dimension_entries(formula)
204
+ entries = []
205
+ collect_units(formula.value).each do |unit|
206
+ dims = unit_dimensions(
207
+ unit.unit_instance,
208
+ node_power(unit.power_numerator),
209
+ [],
210
+ )
211
+ return nil if dims.nil?
212
+
213
+ entries.concat(dims)
214
+ end
215
+ summed = Hash.new(0)
216
+ symbols = {}
217
+ entries.each do |entry|
218
+ summed[entry[:dimension]] += entry[:exponent]
219
+ symbols[entry[:dimension]] ||= entry[:symbol]
220
+ end
221
+ summed.map do |dimension, exponent|
222
+ { dimension: dimension, symbol: symbols[dimension], exponent: exponent }
223
+ end
224
+ end
225
+
226
+ def collect_units(value)
227
+ value.flat_map do |node|
228
+ case node
229
+ when Unit then [node]
230
+ when Formula then collect_units(node.value)
231
+ when Fenced then collect_units([node.value])
232
+ when Sqrt then node.value.is_a?(Unit) ? [node.value] : []
233
+ else []
234
+ end
235
+ end
236
+ end
237
+
238
+ def unit_dimensions(record, power, visited)
239
+ return nil if record.nil? || visited.include?(record.object_id)
240
+
241
+ visited = visited + [record.object_id]
242
+ sym = record.symbols&.first&.id
243
+ if (u2d = Unitsml::Utility::U2D[sym])
244
+ return [{ dimension: u2d[:dimension], symbol: u2d[:symbol],
245
+ exponent: power }]
246
+ end
247
+
248
+ if (cc = record.canonical_conversion)
249
+ dims = []
250
+ cc.root_units.each do |root|
251
+ target = Unitsml::Unitsdb.units.find_by_id(root.unit_reference.id)
252
+ sub = unit_dimensions(target, (root.power || 1) * power, visited)
253
+ return nil if sub.nil?
254
+
255
+ dims.concat(sub)
256
+ end
257
+ return dims
258
+ end
259
+
260
+ chains = record.si_derived_bases
261
+ chains = record.root_units if chains.nil? || chains.empty?
262
+ return nil if chains.nil? || chains.empty?
263
+
264
+ dims = []
265
+ chains.each do |base|
266
+ target = Unitsml::Unitsdb.units.find_by_id(base.unit_reference.id)
267
+ sub = unit_dimensions(target, (base.power || 1) * power, visited)
268
+ return nil if sub.nil?
269
+
270
+ dims.concat(sub)
271
+ end
272
+ dims
273
+ end
274
+ # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Metrics/MethodLength, Layout/LineLength, Lint/DuplicateBranch, Lint/ElseLayout
275
+ end
276
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Unitsml
4
+ module Errors
5
+ class QuantityOperationError < BaseError; end
6
+ class DimensionMismatchError < QuantityOperationError; end
7
+ class ScaleOperationError < QuantityOperationError; end
8
+ class IndeterminateResultError < QuantityOperationError; end
9
+ class ConversionError < QuantityOperationError; end
10
+ end
11
+ end
@@ -8,6 +8,10 @@ module Unitsml
8
8
  "unitsml/errors/opal_payload_not_bundled_error"
9
9
  autoload :PlurimathLoadError, "unitsml/errors/plurimath_load_error"
10
10
  autoload :PargLoadError, "unitsml/errors/parg_load_error"
11
+ autoload :QuantityOperationError, "unitsml/errors/quantity_errors"
12
+ autoload :DimensionMismatchError, "unitsml/errors/quantity_errors"
13
+ autoload :ScaleOperationError, "unitsml/errors/quantity_errors"
14
+ autoload :IndeterminateResultError, "unitsml/errors/quantity_errors"
11
15
  autoload :UnsupportedPayloadTypeError,
12
16
  "unitsml/errors/unsupported_payload_type_error"
13
17
  end
@@ -7,7 +7,7 @@ module Unitsml
7
7
  class Formula
8
8
  include MathmlHelper
9
9
 
10
- attr_accessor :value, :explicit_value, :root
10
+ attr_accessor :value, :explicit_value, :root, :norm_text
11
11
 
12
12
  def initialize(value = [],
13
13
  explicit_value: nil,