unitsml 0.6.11 → 0.6.13

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 (46) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/rake.yml +5 -0
  3. data/Gemfile +0 -1
  4. data/docs/README.adoc +234 -1
  5. data/lib/unitsml/compose/builder.rb +347 -0
  6. data/lib/unitsml/compose/composable.rb +118 -0
  7. data/lib/unitsml/compose/composite.rb +145 -0
  8. data/lib/unitsml/compose/term_tree.rb +48 -0
  9. data/lib/unitsml/compose.rb +151 -0
  10. data/lib/unitsml/conversion/definition.rb +117 -0
  11. data/lib/unitsml/conversion.rb +332 -0
  12. data/lib/unitsml/dimension.rb +30 -3
  13. data/lib/unitsml/errors/base_error.rb +11 -0
  14. data/lib/unitsml/errors/empty_composition_error.rb +14 -0
  15. data/lib/unitsml/errors/invalid_power_error.rb +37 -0
  16. data/lib/unitsml/errors/invalid_unit_entry_error.rb +44 -0
  17. data/lib/unitsml/errors/misplaced_extender_error.rb +18 -0
  18. data/lib/unitsml/errors/mixed_terms_error.rb +15 -0
  19. data/lib/unitsml/errors/parse_error.rb +18 -0
  20. data/lib/unitsml/errors/quantity_errors.rb +1 -0
  21. data/lib/unitsml/errors/unknown_dimension_error.rb +18 -0
  22. data/lib/unitsml/errors/unknown_prefix_error.rb +15 -0
  23. data/lib/unitsml/errors/unknown_unit_error.rb +16 -0
  24. data/lib/unitsml/errors.rb +11 -0
  25. data/lib/unitsml/formula.rb +65 -4
  26. data/lib/unitsml/model/unit.rb +2 -0
  27. data/lib/unitsml/model/units/conversion_note.rb +19 -0
  28. data/lib/unitsml/model/units/conversions.rb +25 -0
  29. data/lib/unitsml/model/units/float64_conversion_from.rb +62 -0
  30. data/lib/unitsml/model/units/special_conversion_from.rb +27 -0
  31. data/lib/unitsml/model/units/wsdl_conversion_from.rb +26 -0
  32. data/lib/unitsml/model/units.rb +5 -0
  33. data/lib/unitsml/number.rb +5 -1
  34. data/lib/unitsml/opal/database_payload.rb +1 -1
  35. data/lib/unitsml/opal.rb +23 -0
  36. data/lib/unitsml/parg/tree_mapper.rb +31 -1
  37. data/lib/unitsml/parser.rb +12 -1
  38. data/lib/unitsml/power_numerator.rb +61 -0
  39. data/lib/unitsml/quantity.rb +122 -22
  40. data/lib/unitsml/unit.rb +60 -4
  41. data/lib/unitsml/unitsdb/quantities.rb +21 -0
  42. data/lib/unitsml/unitsdb/units.rb +6 -0
  43. data/lib/unitsml/utility.rb +61 -10
  44. data/lib/unitsml/version.rb +1 -1
  45. data/lib/unitsml.rb +11 -0
  46. metadata +24 -2
data/lib/unitsml/opal.rb CHANGED
@@ -33,11 +33,20 @@ require "unitsml"
33
33
  require "unitsml/version"
34
34
  require "unitsml/errors"
35
35
  require "unitsml/errors/base_error"
36
+ require "unitsml/errors/empty_composition_error"
36
37
  require "unitsml/errors/invalid_model_error"
38
+ require "unitsml/errors/invalid_power_error"
39
+ require "unitsml/errors/invalid_unit_entry_error"
40
+ require "unitsml/errors/misplaced_extender_error"
41
+ require "unitsml/errors/mixed_terms_error"
37
42
  require "unitsml/errors/opal_payload_not_bundled_error"
38
43
  require "unitsml/errors/plurimath_load_error"
39
44
  require "unitsml/errors/parg_load_error"
45
+ require "unitsml/errors/parse_error"
40
46
  require "unitsml/errors/quantity_errors"
47
+ require "unitsml/errors/unknown_dimension_error"
48
+ require "unitsml/errors/unknown_prefix_error"
49
+ require "unitsml/errors/unknown_unit_error"
41
50
  require "unitsml/errors/unsupported_payload_type_error"
42
51
 
43
52
  require "unitsml/opal/database_payload"
@@ -78,12 +87,25 @@ require "unitsml/model/quantities/name"
78
87
  require "unitsml/model/quantity"
79
88
  require "unitsml/model/unit"
80
89
  require "unitsml/model/units"
90
+ require "unitsml/model/units/conversion_note"
91
+ require "unitsml/model/units/conversions"
81
92
  require "unitsml/model/units/enumerated_root_unit"
93
+ require "unitsml/model/units/float64_conversion_from"
82
94
  require "unitsml/model/units/name"
83
95
  require "unitsml/model/units/root_units"
96
+ require "unitsml/model/units/special_conversion_from"
84
97
  require "unitsml/model/units/symbol"
85
98
  require "unitsml/model/units/system"
99
+ require "unitsml/model/units/wsdl_conversion_from"
86
100
 
101
+ require "unitsml/compose"
102
+ require "unitsml/compose/term_tree"
103
+ require "unitsml/compose/builder"
104
+ require "unitsml/compose/composable"
105
+ require "unitsml/compose/composite"
106
+ # PowerNumerator must be defined before Unit/Dimension include it (no lazy
107
+ # autoload under Opal).
108
+ require "unitsml/power_numerator"
87
109
  require "unitsml/dimension"
88
110
  require "unitsml/extender"
89
111
  require "unitsml/fenced"
@@ -94,6 +116,7 @@ require "unitsml/number"
94
116
  require "unitsml/parg"
95
117
  require "unitsml/parser"
96
118
  require "unitsml/quantity"
119
+ require "unitsml/conversion"
97
120
  require "unitsml/prefix"
98
121
  require "unitsml/prefix_adapter"
99
122
  require "unitsml/sqrt"
@@ -8,6 +8,16 @@ module Unitsml
8
8
  # (sorted), bottom-up, mirroring rule-for-rule the Transform rules in
9
9
  # unitsml/transform.rb.
10
10
  class TreeMapper
11
+ # Edition-2 artifacts (parsanol capture edition 2) name every
12
+ # uncaptured rule reference; these four are the names this grammar
13
+ # gains — the fence punctuation, the sign-suffix hyphen and the
14
+ # zero-width guard — none of which the v1 trees ever surfaced and
15
+ # none of which are authored capture names. Stripping them in the
16
+ # normalize pass keeps the dispatch table reading the same shapes
17
+ # for both editions, so this mapper works against artifacts baked
18
+ # before and after the asciiunits edition-2 flip.
19
+ STRUCTURAL_NAMES = %w[lparen rparen hyphen end_guard].freeze
20
+
11
21
  def apply(tree)
12
22
  map(normalize(tree))
13
23
  end
@@ -18,7 +28,9 @@ module Unitsml
18
28
  # Slice leaves; the mapper works on string keys and stringified leaves.
19
29
  def normalize(node)
20
30
  case node
21
- when Hash then node.to_h { |key, value| [key.to_s, normalize(value)] }
31
+ when Hash
32
+ node.to_h { |key, value| [key.to_s, normalize(value)] }
33
+ .except(*STRUCTURAL_NAMES)
22
34
  when Array then node.map { |value| normalize(value) }
23
35
  else node
24
36
  end
@@ -122,6 +134,24 @@ module Unitsml
122
134
  when %w[power_numerator prefix unit]
123
135
  Unit.new(text(node["unit"]), node["power_numerator"],
124
136
  prefix: Prefix.new(text(node["prefix"])))
137
+ when %w[prefix sequence unit]
138
+ Formula.new(
139
+ [Unit.new(text(node["unit"]),
140
+ prefix: Prefix.new(text(node["prefix"]))),
141
+ node["sequence"]],
142
+ )
143
+ when %w[sequence sqrt]
144
+ Formula.new(
145
+ [Sqrt.new(node["sqrt"]), node["sequence"]],
146
+ )
147
+ when %w[sequence unit]
148
+ Formula.new(
149
+ [Unit.new(text(node["unit"])), node["sequence"]],
150
+ )
151
+ when %w[implicit_extended sequence]
152
+ Formula.new(
153
+ [node["implicit_extended"], node["sequence"]],
154
+ )
125
155
  when %w[prefix] then Prefix.new(text(node["prefix"]))
126
156
  when %w[prefix unit]
127
157
  Unit.new(text(node["unit"]), prefix: Prefix.new(text(node["prefix"])))
@@ -15,7 +15,7 @@ module Unitsml
15
15
  end
16
16
 
17
17
  def parse
18
- tree = self.class.artifact.parse("expression", text)
18
+ tree = parse_tree
19
19
  mapped = Parg::TreeMapper.new.apply(tree)
20
20
  formula = build_formula(mapped)
21
21
  update_units_exponents(formula.value, false)
@@ -51,6 +51,17 @@ module Unitsml
51
51
  end
52
52
  end
53
53
 
54
+ # The artifact is loaded first, so Parsanol is defined by the time the
55
+ # rescue clause names it.
56
+ def parse_tree
57
+ artifact = self.class.artifact
58
+ begin
59
+ artifact.parse("expression", text)
60
+ rescue ::Parsanol::ParseFailed
61
+ raise Errors::ParseError.new(text)
62
+ end
63
+ end
64
+
54
65
  def update_units_exponents(array, inverse, sqrt = false)
55
66
  array.each do |object|
56
67
  if object.is_a?(Sqrt)
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Unitsml
4
+ # Storage for the power_numerator exponent shared by Unit and Dimension.
5
+ # Values assigned through #power_numerator= are always a Unitsml::Number (or a
6
+ # Fenced exponent for the parser's m^((1/2)) form, or nil for none) -- never a
7
+ # bare Numeric: public Numeric inputs like Unit.new("m", 2) are coerced into a
8
+ # Number so render/compare paths can rely on raw_value/to_latex/to_i/to_f.
9
+ # Internal dimension-vector throwaway units may bypass this setter and keep a
10
+ # raw Numeric in @power_numerator; those objects are never rendered.
11
+ # Anything else (a String, a Hash, a BasicObject) raises instead of being
12
+ # stored and crashing later at render.
13
+ module PowerNumerator
14
+ attr_reader :power_numerator
15
+
16
+ def power_numerator=(power)
17
+ @power_numerator = coerce_power_type(power)
18
+ end
19
+
20
+ private
21
+
22
+ # The exponent lexemes the library itself stores: an integer, an n/m or
23
+ # n//m fraction (parser), or a decimal ("0.5" for sqrt, "2.0" from unit
24
+ # decomposition). Anything else ("abc") has no numeric meaning and would
25
+ # render and serialize as garbage.
26
+ NUMBER_LEXEME = %r{\A-?\d+(\.\d+)?(//?-?\d+)?\z}
27
+ private_constant :NUMBER_LEXEME
28
+
29
+ def coerce_power_type(power)
30
+ return power if Compose.type?(NilClass, power)
31
+ return validate_number_power(power) if Compose.type?(Number, power)
32
+ return validate_fenced_power(power) if Compose.type?(Fenced, power)
33
+ # Only the numeric types the parser can express (Integer, Rational, whole
34
+ # Float) coerce; other Numerics (BigDecimal, Complex, ...) are rejected
35
+ # rather than stringified into a non-parser exponent.
36
+ if Compose.type_any?([Integer, Rational, Float], power)
37
+ return Number.new(Compose.numeric_exponent_string(power))
38
+ end
39
+
40
+ raise Errors::InvalidPowerError.new(value: power,
41
+ reason: :unsupported_storage)
42
+ end
43
+
44
+ def validate_number_power(power)
45
+ lexeme = Compose.safe_string(power.raw_value)
46
+ return power if lexeme&.match?(NUMBER_LEXEME)
47
+
48
+ raise Errors::InvalidPowerError.new(value: power,
49
+ reason: :invalid_number)
50
+ end
51
+
52
+ # A Fenced exponent is checked at its innermost Number; other parser
53
+ # payloads inside the fence are kept as-is.
54
+ def validate_fenced_power(power)
55
+ inner = power.value
56
+ inner = inner.value while Compose.type?(Fenced, inner)
57
+ validate_number_power(inner) if Compose.type?(Number, inner)
58
+ power
59
+ end
60
+ end
61
+ end
@@ -11,10 +11,25 @@ module Unitsml
11
11
  class Quantity
12
12
  attr_reader :value, :formula, :scale
13
13
 
14
- def initialize(value:, unit_expression: nil, scale: :ratio)
14
+ # Distinguishes an omitted unit keyword from an explicit nil.
15
+ ABSENT = Object.new.freeze
16
+ private_constant :ABSENT
17
+
18
+ # unit: accepts a String (parsed, like unit_expression:), a Unit, a
19
+ # Formula (kept as-is, never reparsed) or nil (a pure number).
20
+ # unit_expression: remains the String-only spelling; give only one.
21
+ def initialize(value:, unit: ABSENT, unit_expression: ABSENT,
22
+ scale: nil)
23
+ unless unit.equal?(ABSENT) || unit_expression.equal?(ABSENT)
24
+ raise ArgumentError, "give only one of unit: or unit_expression:"
25
+ end
26
+
15
27
  @value = value
16
- @formula = unit_expression && Unitsml.parse(unit_expression)
17
- @scale = scale.to_sym
28
+ @formula = build_formula(unit.equal?(ABSENT) ? unit_expression : unit)
29
+ # The scale derives from the unitsdb scale_reference of the units in
30
+ # the expression (degC is continuous_interval); an explicit argument
31
+ # (the :difference typing of subtraction) overrides it.
32
+ @scale = (scale || derived_scale).to_sym
18
33
  end
19
34
 
20
35
  # Canonical dimension identity; "1" (dimensionless) for pure numbers.
@@ -25,10 +40,14 @@ module Unitsml
25
40
  end
26
41
  end
27
42
 
43
+ # rubocop:disable Metrics/AbcSize, Layout/LineLength
28
44
  # Base-dimension exponents summed across the composed expression —
29
45
  # V (L²MT⁻³I⁻¹) times A (I¹) merges to the watt vector L²MT⁻³.
30
46
  def dimension_vector
31
- vector = raw_dimension_list.each_with_object(Hash.new(0)) do |entry, acc|
47
+ list = raw_dimension_list
48
+ return nil if list.nil?
49
+
50
+ vector = list.each_with_object(Hash.new(0)) do |entry, acc|
32
51
  exponent = entry[:exponent]
33
52
  exponent = exponent.raw_value if exponent.respond_to?(:raw_value)
34
53
  acc[entry[:dimension]] += exponent.to_i
@@ -42,25 +61,28 @@ module Unitsml
42
61
  formula&.norm_text || value.to_s
43
62
  end
44
63
 
64
+ # Units compose structurally through Compose::Builder (the same engine
65
+ # as Unit#* and Unit#/); nothing is reparsed from text. A Numeric is a
66
+ # scalar; a bare Unit, Dimension or Formula operand is a magnitude-1
67
+ # Quantity (Compose.quantity_operand).
45
68
  def *(other)
46
- if other.is_a?(Numeric)
47
- gate_scaling!
48
- return Quantity.new(value: value * other, unit_expression: norm_text)
49
- end
69
+ return scalar_product(other) if Compose.type?(Numeric, other)
50
70
 
71
+ other = Compose.quantity_operand(other)
51
72
  scale_ratio_gate!(other, "multiplication")
52
73
  Quantity.new(value: value * other.value,
53
- unit_expression: compose(self, other, "*"))
74
+ unit: compose(formula, other.formula, "*"))
54
75
  end
55
76
 
56
- # rubocop:disable Metrics/AbcSize
77
+ # rubocop:disable-next Metrics/AbcSize
57
78
  def /(other)
58
- if other.is_a?(Numeric)
79
+ if Compose.type?(Numeric, other)
59
80
  gate_zero!(other)
60
81
  gate_scaling!
61
- return Quantity.new(value: value / other, unit_expression: norm_text)
82
+ return Quantity.new(value: value / other, unit: copied_formula)
62
83
  end
63
84
 
85
+ other = Compose.quantity_operand(other)
64
86
  scale_ratio_gate!(other, "division")
65
87
  if other.value.zero?
66
88
  raise Errors::IndeterminateResultError,
@@ -68,31 +90,81 @@ module Unitsml
68
90
  end
69
91
 
70
92
  Quantity.new(value: value / other.value,
71
- unit_expression: compose(self, other, "/"))
93
+ unit: compose(formula, other.formula, "/"))
72
94
  end
73
- # rubocop:enable Metrics/AbcSize
74
95
 
75
96
  # R-A4: differences are legal on both ratio and interval scales;
76
97
  # only the dimension identity must match.
77
98
  def +(other)
78
99
  quantity_kind!(other)
79
100
  gate_dimension!(other)
80
- Quantity.new(value: value + other.value, unit_expression: norm_text)
101
+ Quantity.new(value: value + other.value, unit: copied_formula)
81
102
  end
82
103
 
83
104
  def -(other)
84
105
  quantity_kind!(other)
85
106
  gate_dimension!(other)
86
- Quantity.new(value: value - other.value, unit_expression: norm_text)
107
+ # A difference of two quantities is difference-typed: its conversion
108
+ # skips the affine addends (20 degC - 15 degC converts to 5 K, not
109
+ # 278.15 K).
110
+ Quantity.new(value: value - other.value, unit: copied_formula,
111
+ scale: :difference)
112
+ end
113
+
114
+ # R-A3: convert this quantity to another (dimension-compatible) unit
115
+ # using unitsdb canonical_conversion data, or conversion definitions
116
+ # supplied by the caller (definitions: a hash of unit ids/symbols to
117
+ # Conversion::Definition or Float64ConversionFrom instances) where
118
+ # given. Exact rational arithmetic throughout; the returned value is
119
+ # a Rational when a conversion was applied.
120
+ def convert_to(target_expression, definitions: nil)
121
+ target_formula = if target_expression.is_a?(Formula)
122
+ target_expression
123
+ else
124
+ Unitsml.parse(target_expression)
125
+ end
126
+ gate_target = Quantity.new(value: 0,
127
+ unit_expression: target_formula.norm_text)
128
+ gate_dimension!(gate_target)
129
+
130
+ src = Conversion.to_canonical(formula, definitions: definitions)
131
+ dst = Conversion.to_canonical(target_formula, definitions: definitions)
132
+ converted = if scale == :difference
133
+ # differences carry no affine addends
134
+ (Rational(value) * src.factor) / dst.factor
135
+ else
136
+ ((Rational(value) * src.factor) + src.offset - dst.offset) / dst.factor
137
+ end
138
+
139
+ Quantity.new(value: converted, unit_expression: target_formula.norm_text)
87
140
  end
88
141
 
89
142
  def ==(other)
90
143
  other.is_a?(Quantity) && value == other.value &&
91
144
  dimension_vector == other.dimension_vector
92
145
  end
146
+ # rubocop:enable Metrics/AbcSize, Layout/LineLength
93
147
 
94
148
  private
95
149
 
150
+ # The scale of a quantity is the scale of the units it composes: any
151
+ # interval-scaled unit (degC per unitsdb scale_reference) makes the
152
+ # quantity interval-scaled.
153
+ def derived_scale
154
+ interval_units? ? :interval : :ratio
155
+ end
156
+
157
+ def interval_units?
158
+ return false unless formula
159
+
160
+ extract_units(formula.value).any? { |unit| unit_interval?(unit) }
161
+ end
162
+
163
+ def unit_interval?(unit)
164
+ record = unit.unit_instance
165
+ record&.scale_reference&.id.to_s.include?("interval")
166
+ end
167
+
96
168
  # Base dimensions in canonical DIMS_VECTOR order; nil when all
97
169
  # exponents cancel (dimensionless).
98
170
  def dimension_list
@@ -108,12 +180,13 @@ module Unitsml
108
180
  def raw_dimension_list
109
181
  return [] unless formula
110
182
 
111
- Utility.units2dimensions(extract_units(formula.value))
183
+ Utility.units2dimensions(extract_units(formula.value)) ||
184
+ Conversion.dimension_entries(formula)
112
185
  end
113
186
 
114
187
  # Formula#units renders XML; the dimension identity needs the raw
115
188
  # decomposition, so extract it the same way Formula does internally.
116
- # rubocop:disable Metrics/MethodLength, Metrics/AbcSize, Metrics/CyclomaticComplexity
189
+ # rubocop:disable-next Metrics/MethodLength, Metrics/AbcSize, Metrics/CyclomaticComplexity
117
190
  def extract_units(formula)
118
191
  formula.each_with_object([]) do |term, units_arr|
119
192
  case term
@@ -132,21 +205,26 @@ module Unitsml
132
205
  end
133
206
  end
134
207
  end
135
- # rubocop:enable Metrics/MethodLength, Metrics/AbcSize, Metrics/CyclomaticComplexity
136
208
 
137
209
  # R-A4: ratio-scale operations are specified errors on non-ratio
138
210
  # quantities. Differences and comparisons remain legal on both.
139
211
  # Scalar multiplication/division scales the magnitude: legal on
140
212
  # ratio scales, a specified error on non-ratio ones.
141
213
  def gate_scaling!
142
- return if scale == :ratio
214
+ # A difference of interval-scaled values is ratio-scaled: scaling a
215
+ # difference is meaningful (2 x 5 K = 10 K of difference); scaling an
216
+ # absolute interval value is not.
217
+ return if %i[ratio difference].include?(scale)
143
218
 
144
219
  raise Errors::ScaleOperationError,
145
220
  "scaling is not legal on a #{scale} scale quantity"
146
221
  end
147
222
 
148
223
  def scale_ratio_gate!(other, operation)
149
- return if scale == :ratio && other.scale == :ratio
224
+ # Only absolute interval-scaled values are barred from * and /: a
225
+ # difference is ratio-scaled (scaling or dividing it is meaningful),
226
+ # so difference/ratio combinations compose freely.
227
+ return if scale != :interval && other.scale != :interval
150
228
 
151
229
  raise Errors::ScaleOperationError,
152
230
  "#{operation} is not legal between #{scale} and " \
@@ -160,6 +238,9 @@ module Unitsml
160
238
  end
161
239
 
162
240
  def gate_dimension!(other)
241
+ # Unknown dimensions (units without a decomposition path) defer the
242
+ # legality decision to the conversion layer.
243
+ return if dimension_vector.nil? || other.dimension_vector.nil?
163
244
  return if dimension_vector == other.dimension_vector
164
245
 
165
246
  raise Errors::DimensionMismatchError,
@@ -167,6 +248,11 @@ module Unitsml
167
248
  "vs #{other.dimension_vector.inspect}"
168
249
  end
169
250
 
251
+ def scalar_product(number)
252
+ gate_scaling!
253
+ Quantity.new(value: value * number, unit: copied_formula)
254
+ end
255
+
170
256
  def gate_zero!(other)
171
257
  return unless other.zero?
172
258
 
@@ -174,8 +260,22 @@ module Unitsml
174
260
  "division by a zero quantity is indeterminate"
175
261
  end
176
262
 
263
+ def build_formula(source)
264
+ case source
265
+ when ABSENT, nil then nil
266
+ when String then Unitsml.parse(source)
267
+ when Unit then Compose::Builder.from_terms([source])
268
+ when Formula then source
269
+ else raise Errors::InvalidUnitEntryError.new(value: source, field: :unit)
270
+ end
271
+ end
272
+
273
+ def copied_formula
274
+ Compose::Builder.copy_formula(formula)
275
+ end
276
+
177
277
  def compose(left, right, operator)
178
- "#{left.norm_text}#{operator}#{right.norm_text}"
278
+ Compose::Builder.quantity_product(left, right, operator)
179
279
  end
180
280
  end
181
281
  end
data/lib/unitsml/unit.rb CHANGED
@@ -3,8 +3,10 @@
3
3
  module Unitsml
4
4
  class Unit
5
5
  include MathmlHelper
6
+ include Compose::Composable
7
+ include PowerNumerator
6
8
 
7
- attr_accessor :unit_name, :power_numerator, :prefix
9
+ attr_accessor :unit_name, :prefix
8
10
 
9
11
  SI_UNIT_SYSTEM = %w[si_base si_derived_special
10
12
  si_derived_non_special].freeze
@@ -12,9 +14,9 @@ module Unitsml
12
14
  def initialize(unit_name,
13
15
  power_numerator = nil,
14
16
  prefix: nil)
15
- @prefix = prefix
16
- @unit_name = unit_name
17
- @power_numerator = power_numerator
17
+ @prefix = coerce_prefix(prefix)
18
+ @unit_name = resolve_ref(unit_name)
19
+ self.power_numerator = power_numerator
18
20
  end
19
21
 
20
22
  def ==(other)
@@ -122,6 +124,60 @@ module Unitsml
122
124
 
123
125
  private
124
126
 
127
+ # Resolve a unit reference to a canonical symbol id, exactly like the parser
128
+ # (symbol ids only — no short-name resolution). The empty string and the
129
+ # UNKNOWN sentinel are passed through untouched (internal callers rely on
130
+ # them); nil is not a sentinel and fails fast rather than silently building
131
+ # a broken unit. Raises for anything unresolvable.
132
+ def resolve_ref(ref)
133
+ raise Errors::UnknownUnitError.new(value: ref) if Compose.type?(NilClass, ref)
134
+
135
+ string = Compose.safe_string(ref)
136
+ raise Errors::UnknownUnitError.new(value: ref) if string.nil?
137
+ return string if string.empty? || string == Utility::UNKNOWN
138
+ return string if Unitsdb.units.find_by_symbol_id(string)
139
+
140
+ raise Errors::UnknownUnitError.new(value: ref)
141
+ end
142
+
143
+ # A pre-built Prefix (the parse path) is passed through untouched, so the
144
+ # parser keeps its lazy resolution. A string/symbol prefix (the builder) is
145
+ # validated eagerly and wrapped.
146
+ def coerce_prefix(prefix)
147
+ return prefix if Compose.type?(NilClass, prefix)
148
+ return validate_prefix_object(prefix) if Compose.type?(Prefix, prefix)
149
+
150
+ coerce_prefix_string(prefix)
151
+ end
152
+
153
+ def coerce_prefix_string(prefix)
154
+ name = Compose.safe_string(prefix)
155
+ raise Errors::UnknownPrefixError.new(value: prefix) if name.nil?
156
+
157
+ # A blank prefix means "no prefix", and the UNKNOWN sentinel from internal
158
+ # decomposition (combine_prefixes for da-/h-prefixed derived units, whose
159
+ # unit is dropped before rendering) both resolve to nil rather than an
160
+ # unvalidated bare string that would crash at render time.
161
+ return if name.strip.empty? || name == Utility::UNKNOWN
162
+ unless Unitsdb.prefixes.find_by_symbol_name(name)
163
+ raise Errors::UnknownPrefixError.new(value: prefix)
164
+ end
165
+
166
+ Prefix.new(name)
167
+ end
168
+
169
+ # A pre-built Prefix (the parse path) is kept as-is so the parser retains
170
+ # its lazy resolution; a directly-constructed one carrying an unresolvable
171
+ # name is rejected here rather than crashing at render.
172
+ def validate_prefix_object(prefix)
173
+ name = Compose.safe_string(prefix.prefix_name)
174
+ raise Errors::UnknownPrefixError.new(value: prefix) if name.nil?
175
+ return prefix if name.strip.empty? || name == Utility::UNKNOWN
176
+ return prefix if Unitsdb.prefixes.find_by_symbol_name(name)
177
+
178
+ raise Errors::UnknownPrefixError.new(value: prefix)
179
+ end
180
+
125
181
  def display_exp
126
182
  return unless power_numerator
127
183
 
@@ -8,6 +8,27 @@ module Unitsml
8
8
  quantity.identifiers.find { |id| id.id == q_id }
9
9
  end
10
10
  end
11
+
12
+ # Resolve a quantity by its human name: English names + short slug,
13
+ # case-insensitive. Non-English synonyms are skipped (some contain
14
+ # commas the parser's comma-metadata handling would truncate).
15
+ def find_by_name(name)
16
+ string = Compose.safe_string(name)
17
+ return if string.nil? || string.strip.empty?
18
+
19
+ key = string.downcase
20
+ quantities.find { |quantity| name_matches?(quantity, key) }
21
+ end
22
+
23
+ private
24
+
25
+ def name_matches?(quantity, key)
26
+ return true if quantity.short.to_s.downcase == key
27
+
28
+ quantity.names.any? do |name|
29
+ name.lang == "en" && name.value.to_s.downcase == key
30
+ end
31
+ end
11
32
  end
12
33
 
13
34
  Configuration.register_model(Quantities, id: :quantities)
@@ -9,6 +9,12 @@ module Unitsml
9
9
  find_first_through(units, via: :identifiers, field: :id, value: u_id)
10
10
  end
11
11
 
12
+ def find_by_reference_uri(uri)
13
+ units.find do |unit|
14
+ unit.references&.any? { |ref| ref.uri == uri }
15
+ end
16
+ end
17
+
12
18
  def find_by_name(u_name)
13
19
  find_first_through(units, via: :symbols, field: :id, value: u_name)
14
20
  end