asciimath2unitsml 0.1.0 → 0.2.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 97081f507478d1952ab2010cd4810efe745980341b9d4d1a420dbd8132be88b0
4
- data.tar.gz: ef63bceb0dc7b7c8dc8c40a1b6fa3795b02a3d0f0d9454be41e121d3a5199054
3
+ metadata.gz: 939880ec148bae10c193dc7958d2866ff5788d7e98617158bfde25a736576b13
4
+ data.tar.gz: dc8d0afdfc6c134341735b55bfed5ae68b50da906ea5765e8404135d58adf011
5
5
  SHA512:
6
- metadata.gz: ead9d484a747edf442ff9ce220d46e53f32ccfeada2653ca44e2ecac9a3da4ade854fbfe0dbb6d0120b87358e5cfae0dee3135e7798eed331b7cff25b3558a9c
7
- data.tar.gz: ed1aaf1967055b8ca4e270bef69b02b24ccef20fb075cc9f46acee7f5447e7c92e9c2f9bfd36646ee043b4f335dd4fd15920d958d429bdf89d155c5ddc14d729
6
+ metadata.gz: f2f5e07977df15d3354ce4e509c585de929caf592ccd9ccd6974d5830b932b0982bd1c7c3cc0483c028e64846032925907316406f0f95cb9c6dda49ecb1ef2b6
7
+ data.tar.gz: e1f358839665b8b815772e32c30ecaea7581061962d7b87cb5e844aaddaed666ae1b95fb2885e7f8eff4bc0d656325660eeba5cf5a45414690614e987da7f31f
@@ -0,0 +1,53 @@
1
+ # Auto-generated by Cimas: Do not edit it manually!
2
+ # See https://github.com/metanorma/cimas
3
+ name: rake
4
+
5
+ on:
6
+ push:
7
+ branches: [ master, main ]
8
+ tags: [ v* ]
9
+ pull_request:
10
+
11
+ jobs:
12
+ rake:
13
+ name: Test on Ruby ${{ matrix.ruby }} ${{ matrix.os }}
14
+ runs-on: ${{ matrix.os }}
15
+ continue-on-error: ${{ matrix.experimental }}
16
+ strategy:
17
+ fail-fast: false
18
+ matrix:
19
+ ruby: [ '2.7', '2.6', '2.5', '2.4' ]
20
+ os: [ ubuntu-latest, windows-latest, macos-latest ]
21
+ experimental: [ false ]
22
+ include:
23
+ - ruby: '3.0'
24
+ os: 'ubuntu-latest'
25
+ experimental: true
26
+ - ruby: '3.0'
27
+ os: 'windows-latest'
28
+ experimental: true
29
+ - ruby: '3.0'
30
+ os: 'macos-latest'
31
+ experimental: true
32
+ steps:
33
+ - uses: actions/checkout@master
34
+ with:
35
+ submodules: true
36
+
37
+ - uses: ruby/setup-ruby@v1
38
+ with:
39
+ ruby-version: ${{ matrix.ruby }}
40
+ bundler-cache: true
41
+
42
+ - run: bundle exec rake
43
+
44
+ tests-passed:
45
+ needs: rake
46
+ runs-on: ubuntu-latest
47
+ steps:
48
+ - uses: peter-evans/repository-dispatch@v1
49
+ with:
50
+ token: ${{ secrets.METANORMA_CI_PAT_TOKEN || secrets.GITHUB_TOKEN }}
51
+ repository: ${{ github.repository }}
52
+ event-type: notify
53
+ client-payload: '{"ref": "${{ github.ref }}", "sha": "${{ github.sha }}"}'
data/.gitmodules ADDED
@@ -0,0 +1,4 @@
1
+ [submodule "lib/unitsdb"]
2
+ branch = master
3
+ path = lib/unitsdb
4
+ url = https://github.com/unitsml/unitsdb.git
data/README.adoc CHANGED
@@ -1,27 +1,76 @@
1
+ image:https://img.shields.io/gem/v/asciimath2unitsml.svg["Gem Version", link="https://rubygems.org/gems/asciimath2unitsml"]
2
+ image:https://github.com/plurimath/asciimath2unitsml/workflows/rake/badge.svg["Build Status", link="https://github.com/plurimath/asciimath2unitsml/actions?workflow=rake"]
3
+ // image:https://codeclimate.com/github/plurimath/asciimath2unitsml/badges/gpa.svg["Code Climate", link="https://codeclimate.com/github/plurimath/asciimath2unitsml"]
4
+ image:https://img.shields.io/github/issues-pr-raw/plurimath/asciimath2unitsml.svg["Pull Requests", link="https://github.com/plurimath/asciimath2unitsml/pulls"]
5
+ image:https://img.shields.io/github/commits-since/plurimath/asciimath2unitsml/latest.svg["Commits since latest",link="https://github.com/plurimath/asciimath2unitsml/releases"]
6
+
1
7
  = asciimath2unitsml
2
8
  Convert Units expressions via MathML to UnitsML
3
9
 
4
10
  This gem converts
5
11
  MathML incorporating UnitsML expressions (based on the Ascii representation provided by NIST)
6
12
  into MathML complying with https://www.w3.org/TR/mathml-units/[], with
7
- UnitsML markup embedded in it, and with unique identifiers for each distinct unit and dimension.
13
+ UnitsML markup embedded in it, and with unique identifiers for each distinct unit, prefix, and dimension.
14
+ Dimensions are automatically inserted corresponding to each unit.
8
15
  Units expressions are identified in MathML as `<mtext>unitsml(...)</mtext>`, which in turn
9
16
  can be identified in AsciiMath as `"unitsml(...)"`.
17
+
10
18
  The consuming document is meant to deduplicate the instances of UnitsML markup
11
19
  with the same identifier, and potentially remove them to elsewhere in the document
12
20
  or another document.
13
21
 
22
+ == Notation
23
+
24
+ The `unitsml()` expression consists of a unit string.
25
+ The units used in `unitsml()` are taken from the UnitsDB database as updated by Ribose:
26
+ https://github.com/unitsml/unitsdb[]. Units are given as an ASCII based code, consisting of
27
+ multiplication or division of single units, each of which is defined as a Prefix
28
+ (taken from https://github.com/unitsml/unitsdb/blob/master/prefixes.yaml[]),
29
+ unit (taken from https://github.com/unitsml/unitsdb/blob/master/units.yaml[]),
30
+ and exponent; e.g. `mm*s^-2`.
31
+
14
32
  The conventions used for writing units are:
15
33
 
16
34
  * `^` for exponents, e.g. `m^-2`
17
- * `*` to combine two units by multiplication; e.g. `m*s^-2`. Division is not supported, use negative exponents instead
35
+ * `*` to combine two units by multiplication; e.g. `m*s^-2`.
36
+ * `/` to combine two units by division;
18
37
  * `u` for μ (micro-)
19
38
 
39
+ For more on units notation, see <<units_notation,Units Notation>>.
40
+
41
+ The `unitsml()` can take additional optional parameters, giving further information for the UnitsML
42
+ to be generated:
43
+
44
+ * `unitsml(unit-string, quantity: ID)` provides the UnitsDB identifier for the quantity being measured
45
+ (taken from https://github.com/unitsml/unitsdb/blob/master/quantities.yaml[]). For example,
46
+ `unitsml(s, quantity: NISTq109)` indicates that the second is used to measure period duration.
47
+ If a single quantity is associated with the unit in UnitsDB (as given in
48
+ https://github.com/unitsml/unitsdb/blob/master/units.yaml[]), that quantity is added automatically;
49
+ otherwise, no quantity is added unless explicitly nominated in this way.
50
+ * `unitsml(unit-string, name: NAME)` provides a name for the unit, if one is not already available
51
+ from UnitsDB. For example, `unitsml(cal_th/cm^2, name: langley)`.
52
+ * `unitsml(unit-string, symbol: SYMBOL)` provides an alternate symbol for the unit, in AsciiMath.
53
+ The unit-string gives the canonical representation of the unit, but SYMBOL is what will be rendered.
54
+ For example, `unitsml(cal_th/cm^2, name: langley, symbol: La)`, or `unitsml(mm*s^-2, symbol: mm cdot s^-2)`.
55
+ (All variables in SYMBOL are rendered upright, as is the default for units.)
56
+
57
+ Standalone prefixes can be recognised by replacing the unit with hyphen; so `unitsml(p-)` corresponds
58
+ to the standalone prefix "pico" (and is rendered as "p").
59
+
60
+ == Rendering
61
+
62
+ The output of the gem is MathML, with MathML unit expressions (expressed as `<mi>`,
63
+ complying with https://www.w3.org/TR/mathml-units/[MathML Units]) cross-referenced to UnitsML
64
+ definitions embedded in the MathML.
65
+
20
66
  The gem follows the MathML Units convention of inserting a spacing invisible times operator
21
67
  (`<mo rspace='thickmathspace'>&#x2062;</mo>`) between any numbers (`<mn>`) and unit expressions
22
68
  in MathML, and representing units in MathML as non-italic variables (`<mi mathvariant='normal'>`).
23
69
 
24
- So:
70
+ Space is not inserted between a number and a unit expression, when that unit expression wholly consists
71
+ of punctuation: _1 m_, _1 °C_, but _9° 7′ 22″_.
72
+
73
+ == Example
25
74
 
26
75
  [source]
27
76
  ----
@@ -83,13 +132,18 @@ is converted into:
83
132
  </math>
84
133
  ----
85
134
 
135
+ == Usage
136
+
86
137
  The converter is run as:
87
138
 
88
139
  [source,ruby]
89
140
  ----
90
141
  c = Asciimath2UnitsML::Conv.new()
91
- c.Asciimath2UnitsML({Asciimath string containing "unitsml()"})
92
- c.MathML2UnitsML({Nokogiri parse of MathML document containing <mtext>unitsml()</mtext>})
142
+ c.Asciimath2UnitsML(1 "unitsml(mm*s^-2)") # AsciiMath string containing UnitsML
143
+ c.MathML2UnitsML("<math xmlns='http://www.w3.org/1998/Math/MathML'><mn>7</mn>"\
144
+ "<mtext>unitsml(kg^-2)</mtext></math>") # AsciiMath string containing <mtext>unitsml()</mtext>
145
+ c.MathML2UnitsML(Nokogiri::XML("<math xmlns='http://www.w3.org/1998/Math/MathML'><mn>7</mn>"\
146
+ "<mtext>unitsml(kg^-2)</mtext></math>")) # Nokogiri parse of MathML document containing <mtext>unitsml()</mtext>
93
147
  ----
94
148
 
95
149
  The converter class may be initialised with options:
@@ -100,3 +154,107 @@ supplied instead; it will be encoded as XML entities. The value `:space` is rend
100
154
  as a spacing invisible times in MathML (`<mo rspace='thickmathspace'>&#x2062;</mo>`),
101
155
  and as a non-breaking space in HTML. The value `:nospace` is rendered as a non-spacing
102
156
  invisible times in MathML (`<mo>&#x2062;</mo>`), and is not rendered in HTML.
157
+
158
+ [[units_notation]]
159
+ == Units Notation
160
+
161
+ The units used in `unitsml()` are taken from the UnitsDB database as updated by Ribose:
162
+ https://github.com/unitsml/unitsdb[]. Units are given as an ASCII based code, consisting of
163
+ multiplication or division of single units, each of which is defined as a Prefix
164
+ (taken from https://github.com/unitsml/unitsdb/blob/master/prefixes.yaml[]),
165
+ unit (taken from https://github.com/unitsml/unitsdb/blob/master/units.yaml[]),
166
+ and exponent; e.g. `mm*s^-2`.
167
+
168
+ In case of ambiguity, the interpretation with no prefix is prioritised over the interpretation
169
+ as a unit; so `ct` is interpreted as _hundredweight_, rather than _centi-ton_. Exceptionally,
170
+ `kg` is decomposed into kilo-gram rather than treated as a basic unit, for consistency with
171
+ other prefixes of grams. (Prefixed units appear in UnitsDB, and are indicated as `prefixed: true`.)
172
+
173
+ A unit may have multiple symbols; these are registered separately in
174
+ https://github.com/unitsml/unitsdb/units.yaml[units.yaml], as entries under `unit_symbols`.
175
+ These different symbols will be recognised as the same Unit in the UnitsML markup, but
176
+ the original symbol will be retained in the MathML expression. So an expression like `1 unitsml(mL)`
177
+ will be recognised as referring to microlitres; the expression will be given under its canonical
178
+ rendering `ml` in UnitsML markup, but the MathML rendering referencing that UnitsML expression
179
+ will keep the notation `mL`.
180
+
181
+ The symbols used for units can be highly ambiguous; in order to guarantee accurate parsing,
182
+ the symbols used to data enter units are unambiguous in https://github.com/unitsml/unitsdb/units.yaml[units.yaml].
183
+ They may be found as the entries for `unit_symbols/id` under each unit. For example, `B` is ambiguous between
184
+ _bel_ (as in decibel) and _byte_; they are kept unambiguous by using `bel_B` and `byte_B` to refer to them,
185
+ although they will still both be rendered as `B`.
186
+
187
+ The following table is the current list of ambiguous symbols, which are disambiguated in the symbol ids used.
188
+ This table can be generated (in Asciidoc format) through `Asciimath2UnitsML::Conv.new().ambig_units`:
189
+
190
+ [cols="7*"]
191
+ |===
192
+ |Symbol | Unit + ID | | | | |
193
+
194
+
195
+ | &#8242; | minute (minute of arc): `'` | foot: `'_ft` | minute: `'_min` | minute (minute of arc): `prime` | foot: `prime_ft` | minute: `prime_min`
196
+ | &#8243; | second (second of arc): `"` | second: `"_s` | inch: `"_in` | second (second of arc): `dprime` | second: `dprime_s` | inch: `dprime_in`
197
+ | &#8243;Hg | conventional inch of mercury: `"Hg` | conventional inch of mercury: `dprime_Hg` | inch of mercury (32 degF): `"Hg_32degF` | inch of mercury (60 degF): `"Hg_60degF` | inch of mercury (32 degF): `dprime_Hg_32degF` | inch of mercury (60 degF): `dprime_Hg_60degF`
198
+ | hp | horsepower: `hp` | horsepower (UK): `hp_UK` | horsepower, water: `hp_water` | horsepower, metric: `hp_metric` | horsepower, boiler: `hp_boiler` | horsepower, electric: `hp_electric`
199
+ | Btu | British thermal unit_IT: `Btu` | British thermal unit (mean): `Btu_mean` | British thermal unit (39 degF): `Btu_39degF` | British thermal unit (59 degF): `Btu_59degF` | British thermal unit (60 degF): `Btu_60degF` |
200
+ | a | are: `a` | year (365 days): `a_year` | year, tropical: `a_tropical_year` | year, sidereal: `a_sidereal_year` | |
201
+ | d | day: `d` | darcy: `darcy` | day, sidereal: `d_sidereal` | | |
202
+ | inHg | conventional inch of mercury: `inHg` | inch of mercury (32 degF): `inHg_32degF` | inch of mercury (60 degF): `inHg_60degF` | | |
203
+ | inH~2~O | conventional inch of water: `inH_2O` | inch of water (39.2 degF): `inH_2O_39degF` | inch of water (60 degF): `inH_2O_60degF` | | |
204
+ | min | minute: `min` | minim: `minim` | minute, sidereal: `min_sidereal` | | |
205
+ | pc | parsec: `pc` | pica (printer's): `pica_printer` | pica (computer): `pica_computer` | | |
206
+ | t | metric ton: `t` | long ton: `ton_long` | short ton: `ton_short` | | |
207
+ | B | bel: `bel_B` | byte: `byte_B` | | | |
208
+ | cmHg | conventional centimeter of mercury: `cmHg` | centimeter of mercury (0 degC): `cmHg_0degC` | | | |
209
+ | cmH~2~O | conventional centimeter of water: `cmH_2O` | centimeter of water (4 degC): `cmH_2O_4degC` | | | |
210
+ | cup | cup (US): `cup` | cup (FDA): `cup_label` | | | |
211
+ | D | debye: `D` | darcy: `Darcy` | | | |
212
+ | ft | foot: `ft` | foot (based on US survey foot): `ft_US_survey` | | | |
213
+ | ftH~2~O | conventional foot of water: `ftH_2O` | foot of water (39.2 degF): `ftH_2O_39degF` | | | |
214
+ | gi | gill (US): `gi` | gill [Canadian and UK (Imperial)]: `gi_imperial` | | | |
215
+ | h | hour: `h` | hour, sidereal: `h_sidereal` | | | |
216
+ | &#8242;Hg | conventional foot of mercury: `'Hg` | conventional foot of mercury: `prime_Hg` | | | |
217
+ | __&#295;__ | natural unit of action: `h-bar` | atomic unit of action: `h-bar_atomic` | | | |
218
+ | __m__~e~ | natural unit of mass: `m_e` | atomic unit of mass: `m_e_atomic` | | | |
219
+ | in | inch: `in` | inch (based on US survey foot): `in_US_survey` | | | |
220
+ | K | kelvin: `K` | kayser: `kayser` | | | |
221
+ | L | liter: `L` | lambert: `Lambert` | | | |
222
+ | lb | pound (avoirdupois): `lb` | pound (troy or apothecary): `lb_troy` | | | |
223
+ | mi | mile: `mi` | mile (based on US survey foot): `mi_US_survey` | | | |
224
+ | mil | mil (length): `mil` | angular mil (NATO): `mil_nato` | | | |
225
+ | oz | ounce (avoirdupois): `oz` | ounce (troy or apothecary): `oz_troy` | | | |
226
+ | pt | point (printer's): `pt_printer` | point (computer): `pt_computer` | | | |
227
+ | rad | radian: `rad` | rad (absorbed dose): `rad_radiation` | | | |
228
+ | s | second: `s` | second, sidereal: `s_sidereal` | | | |
229
+ | tbsp | tablespoon: `tbsp` | tablespoon (FDA): `tbsp_label` | | | |
230
+ | ton | ton of TNT (energy equivalent): `ton_TNT` | ton of refrigeration (12 000 Btu_IT/h): `ton_refrigeration` | | | |
231
+ | tsp | teaspoon: `tsp` | teaspoon (FDA): `tsp_label` | | | |
232
+ | yd | yard: `yd` | yard (based on US survey foot): `yd_US_survey` | | | |
233
+ | &#186; | degree (degree of arc): `deg` | | | | |
234
+ | &#947; | gamma: `gamma` | | | | |
235
+ | &#956; | micron: `micron` | | | | |
236
+ | &#8486; | ohm: `Ohm` | | | | |
237
+ | &#197; | angstrom: `Aring` | | | | |
238
+ | &#295; | natural unit of action in eV s: `h-bar_eV_s` | | | | |
239
+ | ab&#937; | abohm: `abohm` | | | | |
240
+ | (ab&#937;)^-1^ | abmho: `abS` | | | | |
241
+ | aW | abwatt: `aW (Cardelli)` | | | | |
242
+ | b | barn: `barn` | | | | |
243
+ | Btu~th~ | British thermal unit_th: `Btu_th` | | | | |
244
+ | &#176;C | degree Celsius: `degC` | | | | |
245
+ | cal~IT~ | I.T. calorie: `cal_IT` | | | | |
246
+ | cal~th~ | thermochemical calorie: `cal_th` | | | | |
247
+ | &#176;F | degree Fahrenheit: `degF` | | | | |
248
+ | __a__~0~ | atomic unit of length: `a_0` | | | | |
249
+ | __c__ | natural unit of velocity: `c` | | | | |
250
+ | __c__~0~ | natural unit of velocity: `c_0` | | | | |
251
+ | __e__ | atomic unit of charge: `e` | | | | |
252
+ | __E__~h~ | atomic unit of energy: `e_h` | | | | |
253
+ | &#956;in | microinch: `uin` | | | | |
254
+ | &#176;K | kelvin: `degK` | | | | |
255
+ | kcal~IT~ | kilocalorie_IT: `kcal_IT` | | | | |
256
+ | kcal~th~ | kilocalorie_th: `kcal_th` | | | | |
257
+ | mmH~2~O | conventional millimeter of water: `mmH_2O` | | | | |
258
+ | &#176;R | degree Rankine: `degR` | | | | |
259
+ | &#x19b;~C~ | natural unit of length: `lambda-bar_C` | | | | |
260
+ |===
@@ -1,5 +1,5 @@
1
1
  # coding: utf-8
2
-
2
+
3
3
  lib = File.expand_path("../lib", __FILE__)
4
4
  $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5
5
  require "asciimath2unitsml/version"
@@ -12,7 +12,7 @@ Gem::Specification.new do |spec|
12
12
 
13
13
  spec.summary = "Convert Asciimath via MathML to UnitsML"
14
14
  spec.description = <<~DESCRIPTION
15
- Convert Asciimath via MathML to UnitsML
15
+ Convert Asciimath via MathML to UnitsML
16
16
  DESCRIPTION
17
17
 
18
18
  spec.homepage = "https://github.com/plurimath/asciimath2unitsml"
@@ -24,6 +24,27 @@ Gem::Specification.new do |spec|
24
24
  spec.test_files = `git ls-files -- {spec}/*`.split("\n")
25
25
  spec.required_ruby_version = Gem::Requirement.new(">= 2.4.0")
26
26
 
27
+ # get an array of submodule dirs relatively to root repo
28
+ `git config --file .gitmodules --get-regexp '\\.path$'`
29
+ .split("\n")
30
+ .map { |kv_str| kv_str.split(" ") }
31
+ .each do |(_, submodule_path)|
32
+
33
+ # for each submodule, change working directory to that submodule
34
+ Dir.chdir(submodule_path) do
35
+
36
+ # issue git ls-files in submodule's directory
37
+ submodule_files = `git ls-files | grep -i '.yaml$'`.split($\)
38
+
39
+ submodule_files_paths = submodule_files.map do |filename|
40
+ File.join submodule_path, filename
41
+ end
42
+
43
+ # add relative paths to gem.files
44
+ spec.files += submodule_files_paths
45
+ end
46
+ end
47
+
27
48
  spec.add_dependency "asciimath"
28
49
  spec.add_dependency "htmlentities"
29
50
  spec.add_dependency "nokogiri", "~> 1.10.4"
@@ -39,5 +60,6 @@ Gem::Specification.new do |spec|
39
60
  spec.add_development_dependency "rubocop", "= 0.54.0"
40
61
  spec.add_development_dependency "simplecov", "~> 0.15"
41
62
  spec.add_development_dependency "timecop", "~> 0.9"
63
+ spec.add_development_dependency "rexml"
42
64
  end
43
65
 
@@ -1,3 +1,4 @@
1
1
  require_relative "asciimath2unitsml/version"
2
2
  require_relative "asciimath2unitsml/conv"
3
+ require_relative "unitsdb_ruby/unitsdb"
3
4
 
@@ -5,6 +5,8 @@ require "yaml"
5
5
  require "rsec"
6
6
  require_relative "string"
7
7
  require_relative "parse"
8
+ require_relative "render"
9
+ require_relative "unit"
8
10
 
9
11
  module Asciimath2UnitsML
10
12
  MATHML_NS = "http://www.w3.org/1998/Math/MathML".freeze
@@ -12,124 +14,47 @@ module Asciimath2UnitsML
12
14
 
13
15
  class Conv
14
16
  def initialize(options = {})
15
- @prefixes_id = read_yaml("../unitsdb/prefixes.yaml")
16
- @prefixes = flip_name_and_id(@prefixes_id)
17
- @quantities = read_yaml("../unitsdb/quantities.yaml")
18
- @units_id = read_yaml("../unitsdb/units.yaml")
19
- @units = flip_name_and_id(@units_id)
20
- @parser = parser
21
- @multiplier = multiplier(options[:multiplier] || "\u00b7")
22
- end
23
-
24
- def multiplier(x)
25
- case x
26
- when :space
27
- { html: "&nbsp;", mathml: "<mo rspace='thickmathspace'>&#x2062;</mo>" }
28
- when :nospace
29
- { html: "", mathml: "<mo>&#x2062;</mo>" }
30
- else
31
- { html: HTMLEntities.new.encode(x), mathml: "<mo>#{HTMLEntities.new.encode(x)}</mo>" }
17
+ @dimensions_id = read_yaml("../unitsdb/dimensions.yaml").each_with_object({}) do |(k, v), m|
18
+ m[k.to_s] = UnitsDB::Dimension.new(k, v)
32
19
  end
33
- end
34
-
35
- def unit_id(text)
36
- "U_" +
37
- (@units[text.to_sym] ? @units[text.to_sym][:id] : text.gsub(/\*/, ".").gsub(/\^/, ""))
38
- end
39
-
40
- def unit(units, text, dims)
41
- dimid = dim_id(dims)
42
- <<~END
43
- <Unit xmlns='#{UNITSML_NS}' xml:id='#{unit_id(text)}'#{dimid ? " dimensionURL='##{dimid}'" : ""}>
44
- #{unitsystem(units)}
45
- #{unitname(units, text)}
46
- #{unitsymbol(units)}
47
- #{rootunits(units)}
48
- </Unit>
49
- END
50
- end
51
-
52
- def unitsystem(units)
53
- ret = []
54
- units.any? { |x| @units[x[:unit].to_sym][:si] != true } and
55
- ret << "<UnitSystem name='not_SI' type='not_SI' xml:lang='en-US'/>"
56
- if units.any? { |x| @units[x[:unit].to_sym][:si] == true }
57
- base = units.size == 1 && @units[units[0][:unit].to_sym][:type].include?("si-base")
58
- ret << "<UnitSystem name='SI' type='#{base ? "SI_base" : "SI_derived"}' xml:lang='en-US'/>"
20
+ @prefixes_id = read_yaml("../unitsdb/prefixes.yaml").each_with_object({}) do |(k, v), m|
21
+ m[k] = UnitsDB::Prefix.new(k, v)
59
22
  end
60
- ret.join("\n")
61
- end
62
-
63
- def unitname(units, text)
64
- name = @units[text.to_sym] ? @units[text.to_sym][:name] : compose_name(units, text)
65
- "<UnitName xml:lang='en'>#{name}</UnitName>"
66
- end
67
-
68
- # TODO: compose name from the component units
69
- def compose_name(units, text)
70
- text
71
- end
72
-
73
- def unitsymbol(units)
74
- <<~END
75
- <UnitSymbol type="HTML">#{htmlsymbol(units)}</UnitSymbol>
76
- <UnitSymbol type="MathML">#{mathmlsymbolwrap(units)}</UnitSymbol>
77
- END
78
- end
79
-
80
- def htmlsymbol(units)
81
- units.map do |u|
82
- u[:exponent] and exp = "<sup>#{u[:exponent].sub(/-/, "&#x2212;")}</sup>"
83
- "#{u[:prefix]}#{u[:unit]}#{exp}"
84
- end.join(@multiplier[:html])
85
- end
86
-
87
- def mathmlsymbol(units)
88
- exp = units.map do |u|
89
- base = "<mi mathvariant='normal'>#{u[:prefix]}#{u[:unit]}</mi>"
90
- if u[:exponent]
91
- exp = "<mn>#{u[:exponent]}</mn>".sub(/<mn>-/, "<mo>&#x2212;</mo><mn>")
92
- "<msup><mrow>#{base}</mrow><mrow>#{exp}</mrow></msup>"
93
- else
94
- base
95
- end
96
- end.join(@multiplier[:mathml])
97
- end
98
-
99
- def mathmlsymbolwrap(units)
100
- <<~END
101
- <math xmlns='#{MATHML_NS}'>
102
- <mrow>#{mathmlsymbol(units)}</mrow>
103
- </math>
104
- END
23
+ @prefixes = flip_name_and_symbol(@prefixes_id)
24
+ @quantities = read_yaml("../unitsdb/quantities.yaml").each_with_object({}) do |(k, v), m|
25
+ m[k.to_s] = UnitsDB::Quantity.new(k, v)
26
+ end
27
+ @units_id = read_yaml("../unitsdb/units.yaml").each_with_object({}) do |(k, v), m|
28
+ m[k.to_s] = UnitsDB::Unit.new(k.to_s, v)
29
+ end
30
+ @units = flip_name_and_symbols(@units_id)
31
+ @symbols = @units.each_with_object({}) do |(k, v), m|
32
+ v.symbolids.each { |x| m[x] = v.symbols_hash[x] }
33
+ end
34
+ @parser = parser
35
+ @multiplier = multiplier(options[:multiplier] || "\u00b7")
105
36
  end
106
37
 
107
- def rootunits(units)
108
- return if units.size == 1
109
- exp = units.map do |u|
110
- prefix = " prefix='#{u[:prefix]}'" if u[:prefix]
111
- exponent = " powerNumerator='#{u[:exponent]}'" if u[:exponent]
112
- "<EnumeratedRootUnit unit='#{@units[u[:unit].to_sym][:name]}'#{prefix}#{exponent}/>"
113
- end.join("\n")
114
- <<~END
115
- <RootUnits>#{exp}</RootUnits>
116
- END
38
+ def float_to_display(f)
39
+ ret = f.to_f.round(1).to_s.sub(/\.0$/, "")
117
40
  end
118
41
 
119
42
  def prefix(units)
120
- units.map { |u| u[:prefix] }.reject { |u| u.nil? }.uniq.map do |p1|
121
- p = p1.to_sym
43
+ units.map { |u| u[:prefix] }.reject { |u| u.nil? }.uniq.map do |p|
122
44
  <<~END
123
- <Prefix xmlns='#{UNITSML_NS}' prefixBase='#{@prefixes[p][:base]}'
124
- prefixPower='#{@prefixes[p][:power]}' xml:id='#{@prefixes[p][:id]}'>
125
- <PrefixName xml:lang="en">#{@prefixes[p][:name]}</PrefixName>
126
- <PrefixSymbol type="ASCII">#{@prefixes[p][:symbol]}</PrefixSymbol>
45
+ <Prefix xmlns='#{UNITSML_NS}' prefixBase='#{@prefixes[p].base}'
46
+ prefixPower='#{@prefixes[p].power}' xml:id='#{@prefixes[p].id}'>
47
+ <PrefixName xml:lang="en">#{@prefixes[p].name}</PrefixName>
48
+ <PrefixSymbol type="ASCII">#{@prefixes[p].ascii}</PrefixSymbol>
49
+ <PrefixSymbol type="unicode">#{@prefixes[p].unicode}</PrefixSymbol>
50
+ <PrefixSymbol type="LaTeX">#{@prefixes[p].latex}</PrefixSymbol>
51
+ <PrefixSymbol type="HTML">#{HTMLEntities.new.encode(@prefixes[p].html, :basic)}</PrefixSymbol>
127
52
  </Prefix>
128
53
  END
129
54
  end.join("\n")
130
55
  end
131
56
 
132
- def dimension(dims)
57
+ def dimension_components(dims)
133
58
  return if dims.nil? || dims.empty?
134
59
  <<~END
135
60
  <Dimension xmlns='#{UNITSML_NS}' xml:id="#{dim_id(dims)}">
@@ -139,8 +64,8 @@ module Asciimath2UnitsML
139
64
  end
140
65
 
141
66
  def units2dimensions(units)
142
- norm = normalise_units(units)
143
- return if norm.any? { |u| u[:unit] == "unknown" || u[:prefix] == "unknown" }
67
+ norm = decompose_units(units)
68
+ return if norm.any? { |u| u[:unit] == "unknown" || u[:prefix] == "unknown" || u[:unit].nil? }
144
69
  norm.map do |u|
145
70
  { dimension: U2D[u[:unit]][:dimension],
146
71
  unit: u[:unit],
@@ -150,16 +75,23 @@ module Asciimath2UnitsML
150
75
  end
151
76
 
152
77
  def dimension1(u)
153
- %(<#{u[:dimension]} symbol="#{u[:symbol]}" powerNumerator="#{u[:exponent]}"/>)
78
+ %(<#{u[:dimension]} symbol="#{u[:symbol]}" powerNumerator="#{float_to_display(u[:exponent])}"/>)
154
79
  end
155
80
 
156
81
  def dim_id(dims)
157
82
  return nil if dims.nil? || dims.empty?
158
- "D_" + dims.map { |d| U2D[d[:unit]][:symbol] + (d[:exponent] == 1 ? "" : d[:exponent].to_s) }.join("")
83
+ dimhash = dims.each_with_object({}) { |h, m| m[h[:dimension]] = h }
84
+ dimsvector = %w(Length Mass Time ElectricCurrent ThermodynamicTemperature
85
+ AmountOfSubstance LuminousIntensity PlaneAngle)
86
+ .map { |h| dimhash.dig(h, :exponent) }.join(":")
87
+ id = @dimensions_id&.values&.select { |d| d.vector == dimsvector }&.first&.id and return id.to_s
88
+ "D_" + dims.map do |d|
89
+ U2D[d[:unit]][:symbol] + (d[:exponent] == 1 ? "" : float_to_display(d[:exponent]))
90
+ end.join("")
159
91
  end
160
92
 
161
- def normalise_units(units)
162
- gather_units(units.map { |u| normalise_unit(u) }.flatten)
93
+ def decompose_units(units)
94
+ gather_units(units_only(units).map { |u| decompose_unit(u) }.flatten)
163
95
  end
164
96
 
165
97
  def gather_units(units)
@@ -168,41 +100,85 @@ module Asciimath2UnitsML
168
100
  else
169
101
  m[-1] = { prefix: combine_prefixes(@prefixes[m[-1][:prefix]], @prefixes[k[:prefix]]),
170
102
  unit: m[-1][:unit],
171
- exponent: (k[:exponent]&.to_i || 1) + (m[-1][:exponent]&.to_i || 1) }
103
+ exponent: (k[:exponent]&.to_f || 1) + (m[-1][:exponent]&.to_f || 1) }
172
104
  end
173
105
  end
174
106
  end
175
107
 
176
- def normalise_unit(u)
177
- if @units[u[:unit].to_sym][:type]&.include?("si-base") then u
178
- elsif !@units[u[:unit].to_sym][:bases] then { prefix: u[:prefix], unit: "unknown", exponent: u[:exponent] }
108
+ # treat g not kg as base unit: we have stripped the prefix k in parsing
109
+ # reduce units down to basic units
110
+ def decompose_unit(u)
111
+ if u[:unit].nil? then u
112
+ elsif u[:unit] == "g" then u
113
+ elsif @units[u[:unit]].system_type == "SI_base" then u
114
+ elsif !@units[u[:unit]].si_derived_bases
115
+ { prefix: u[:prefix], unit: "unknown", exponent: u[:exponent] }
179
116
  else
180
- @units[u[:unit].to_sym][:bases].each_with_object([]) do |k, m|
181
- m << { prefix: k["prefix"] ?
182
- combine_prefixes(@prefixes_id[k["prefix"]], @prefixes[u[:prefix]]) : u[:prefix],
183
- unit: @units_id[k["id"].to_sym][:symbol],
184
- exponent: (k["power"]&.to_i || 1) * (u[:exponent]&.to_i || 1) }
117
+ @units[u[:unit]].si_derived_bases.each_with_object([]) do |k, m|
118
+ m << { prefix: !k[:prefix].nil? && !k[:prefix].empty? ?
119
+ combine_prefixes(@prefixes_id[k[:prefix]], @prefixes[u[:prefix]]) : u[:prefix],
120
+ unit: @units_id[k[:id]].symbolid,
121
+ exponent: (k[:power]&.to_i || 1) * (u[:exponent]&.to_f || 1) }
185
122
  end
186
123
  end
187
124
  end
188
125
 
189
126
  def combine_prefixes(p1, p2)
190
127
  return nil if p1.nil? && p2.nil?
191
- return p1[:symbol] if p2.nil?
192
- return p2[:symbol] if p1.nil?
193
- return "unknown" if p1[:base] != p2[:base]
194
- @prefixes.each do |p|
195
- return p[:symbol] if p[:base] == p1[:base] && p[:power] == p1[:power] + p2[:power]
128
+ return p1.symbolid if p2.nil?
129
+ return p2.symbolid if p1.nil?
130
+ return "unknown" if p1.base != p2.base
131
+ @prefixes.each do |_, p|
132
+ return p.symbolid if p.base == p1.base && p.power == p1.power + p2.power
196
133
  end
197
134
  "unknown"
198
135
  end
199
136
 
200
- def unitsml(units, text)
137
+ def quantityname(id)
138
+ ret = ""
139
+ @quantities[id].names.each do |q|
140
+ ret += %(<QuantityName xml:lang="en-US">#{q}</QuantityName>)
141
+ end
142
+ ret
143
+ end
144
+
145
+ def quantity(normtext, quantity)
146
+ return unless @units[normtext] && @units[normtext].quantities.size == 1 || @quantities[quantity]
147
+ id = quantity || @units[normtext].quantities.first
148
+ dim = %( dimensionURL="##{@units[normtext].dimension}") if @units[normtext]&.dimension
149
+ <<~END
150
+ <Quantity xmlns='#{UNITSML_NS}' xml:id="#{id}"#{dim} quantityType="base">
151
+ #{quantityname(id)}
152
+ </Quantity>
153
+ END
154
+ end
155
+
156
+ def dimid2dimensions(normtext)
157
+ @dimensions_id[normtext].keys.map do |k|
158
+ { dimension: k,
159
+ symbol: U2D.values.select { |v| v[:dimension] == k }.first[:symbol],
160
+ exponent: @dimensions_id[normtext].exponent(k) }
161
+ end
162
+ end
163
+
164
+ def dimension(normtext)
165
+ return unless @units[normtext]&.dimension
166
+ dims = dimid2dimensions(@units[normtext]&.dimension)
167
+ <<~END
168
+ <Dimension xmlns='#{UNITSML_NS}' xml:id="#{@units[normtext]&.dimension}">
169
+ #{dims.map { |u| dimension1(u) }.join("\n") }
170
+ </Dimension>
171
+ END
172
+ end
173
+
174
+ def unitsml(units, origtext, normtext, quantity, name)
201
175
  dims = units2dimensions(units)
202
176
  <<~END
203
- #{unit(units, text, dims)}
177
+ #{unit(units, origtext, normtext, dims, name)}
204
178
  #{prefix(units)}
205
- #{dimension(dims)}
179
+ #{dimension(normtext)}
180
+ #{dimension_components(dims)}
181
+ #{quantity(normtext, quantity)}
206
182
  END
207
183
  end
208
184
  end