Class: NumericWithUnit::Unit

Inherits:
Object
  • Object
show all
Defined in:
lib/numeric_with_unit/unit.rb,
lib/numeric_with_unit/unit.rb,
lib/numeric_with_unit/unit.rb,
lib/numeric_with_unit/unit.rb

Defined Under Namespace

Classes: Config, NoUnitError

Constant Summary collapse

@@list =
[]
@@prefix =
{
  'Y' => 10**24, 
  'Z' => 10**21, 
  'E' => 10**18, 
  'P' => 10**15, 
  'T' => 10**12, 
  'G' => 10**9, 
  'M' => 10**6, 
  'k' => 10**3, 
  'h' => 10**2, 
  'da' => 10**1, 
  'd' => 10**-1, 
  'c' => 10**-2, 
  'm' => 10**-3, 
  'μ' => 10**-6, 
  'u' => 10**-6, 
  'n' => 10**-9, 
  'p' => 10**-12, 
  'f' => 10**-15, 
  'a' => 10**-18, 
  'z' => 10**-21, 
  'y' => 10**-24,
  'Ki' => 2**10,
  'Mi' => 2**20,
  'Gi' => 2**30,
  'Ti' => 2**40,
  'Pi' => 2**50,
  'Ei' => 2**60,
  'Zi' => 2**70,
  'Yi' => 2**80
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(derivation = nil) {|config| ... } ⇒ Unit

Returns a new instance of Unit.

Yields:

  • (config)


330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# File 'lib/numeric_with_unit/unit.rb', line 330

def initialize(derivation=nil)
  # TODO: Unit::Configとinitializeの役割が分離できていないので見なおせ
  config = Config.new
  yield(config) if block_given?
  config.compile
  
  @symbol = config.symbol
  @dimension = config.dimension
  @from_si = config.from_si
  @to_si = config.to_si
  
  unless derivation
    derivation = Hash.new(0)
    derivation[self] += 1
  end
  @derivation = derivation
end

Instance Attribute Details

#derivationObject (readonly)

Returns the value of attribute derivation.



328
329
330
# File 'lib/numeric_with_unit/unit.rb', line 328

def derivation
  @derivation
end

#dimensionObject (readonly)

Returns the value of attribute dimension.



328
329
330
# File 'lib/numeric_with_unit/unit.rb', line 328

def dimension
  @dimension
end

#symbolObject (readonly)

Instance Methods



327
328
329
# File 'lib/numeric_with_unit/unit.rb', line 327

def symbol
  @symbol
end

Class Method Details

.<<(arg) ⇒ Object

add unit to base unit list.



192
193
194
195
196
197
198
# File 'lib/numeric_with_unit/unit.rb', line 192

def self.<<(arg)
  if arg.is_a?(self)
    @@list << arg
  else
    @@list << Unit[arg]
  end
end

.[](arg) ⇒ Object

apply to_s to arg and return parsed unit.



170
171
172
# File 'lib/numeric_with_unit/unit.rb', line 170

def self.[](arg)
  self.parse(arg.to_s)
end

.[]=(key, arg) ⇒ Object

cast unit and add unit to base unit list at the same time.



175
176
177
178
179
180
181
182
183
184
# File 'lib/numeric_with_unit/unit.rb', line 175

def self.[]=(key, arg)
  if arg.is_a?(Array) and arg.size == 2
    a = [key, arg.first]
    u = arg.last
  else
    a = [key]
    u = arg
  end
  @@list << (u.is_a?(self) ? u : self[u]).cast(*a)
end

.assignObject

create new unit and add unit to base unit list at the same time.



206
207
208
# File 'lib/numeric_with_unit/unit.rb', line 206

def self.assign
  @@list << self.new{|config| yield(config)}
end

.delete(unit_symbol) ⇒ Object

remove unit from base unit list.



201
202
203
# File 'lib/numeric_with_unit/unit.rb', line 201

def self.delete(unit_symbol)
  @@list.delete_if{|unit| unit.symbol == unit_symbol}
end

.derive {|derivation| ... } ⇒ Object

create new unit from derivation _(for internal use)_ .

Yields:



109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/numeric_with_unit/unit.rb', line 109

def self.derive #(block)
  derivation = Hash.new(0)
  yield(derivation)
  derivation.delete_if{|k,v| k.symbol.nil?}
  
  return Unit.new if derivation.empty?
  
  
  # constructing symbol
  h = derivation.reject{|k,v| k.symbol.empty?}.sort_by{|u,v| u.symbol}.sort_by{|u,v| v}
  syms_pos = h.select{|u,v| v > 0}.map{|u,v| u.symbol + (v.abs>1 ? v.abs.to_s : '')}
  syms_neg = h.select{|u,v| v < 0}.map{|u,v| u.symbol + (v.abs>1 ? v.abs.to_s : '')}
  symbol = syms_pos.join('.')
  symbol += '/' + (syms_neg.size>1 ? "(#{syms_neg.join('.')})" : "#{syms_neg.first}") unless syms_neg.empty?
  
  # constructing dimension
  dimension = Hash.new(0)
  derivation.each do |u,v|
    u.dimension.each do |d,i|
      dimension[d] += i*v
    end
  end
  
  # constructing from_si proc
  from_si = derivation.map{|u,v|
    prc = if v > 0
      ->(x){u.from_si(x)}
    else
      ->(x){x.quo(u.from_si(1)-u.from_si(0))} #FIXME: ℃とKの変換のような場合に、変換式の切片を消すため。変換式が線形じゃないケースは想定していない
    end
    [prc, v.abs]
  }.map{|prc,v|
    ->(x){ v.times{x = prc[x]}; x }
  }.reduce{|memo, prc|
    ->(x){memo[prc[x]]}
  }
  
  # constructing to_si proc
  to_si = derivation.map{|u,v|
    prc = if v > 0
      ->(x){u.to_si(x)}
    else
      ->(x){x.quo(u.to_si(1)-u.to_si(0))} #FIXME: ℃とKの変換のような場合に、変換式の切片を消すため。変換式が線形じゃないケースは想定していない
    end
    [prc, v.abs]
  }.map{|prc,v|
    ->(x){ v.times{x = prc[x]}; x }
  }.reduce{|memo, prc|
    ->(x){memo[prc[x]]}
  }
  
  # deriving new unit
  self.new(derivation){|config|
    config.symbol = symbol
    config.dimension = dimension
    config.from_si = from_si
    config.to_si = to_si
  }
end

.listObject

return base unit list.



187
188
189
# File 'lib/numeric_with_unit/unit.rb', line 187

def self.list
  @@list
end

.parse(unit_str) ⇒ Object

parsing unit_str (ex. “kg”, km/hr“, ”cm2“) to (derived) unit.



212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/numeric_with_unit/unit.rb', line 212

def self.parse(unit_str)
  rec = ->(arg){__send__(__method__, arg)}

  dervation_str = parse_3rd(parse_2nd(parse_1st(unit_str)))
  derive{|derivation|
    dervation_str.each do |unit_str, order|
      if i = @@list.rindex{|unit| unit.symbol == unit_str}
        derivation[@@list[i]] += order
      elsif m = unit_str.match(/^(?<prefix>#{@@prefix.keys.join('|')})(?<unit>#{list.join('|')})$/) and m[:unit].empty?.!
        u = rec[m[:unit]].cast(unit_str, @@prefix[m[:prefix]])
        derivation[u] += order
      else
        raise NoUnitError, "[#{unit_str}] is not defined!"
      end
    end
  }
end

Instance Method Details

#*(other_unit) ⇒ Object



395
396
397
398
399
400
# File 'lib/numeric_with_unit/unit.rb', line 395

def *(other_unit)
  self.class.derive do |derivation|
    @derivation.each{|k, v| derivation[k] += v}
    other_unit.derivation.each{|k, v| derivation[k] += v}
  end
end

#**(num) ⇒ Object



409
410
411
412
413
414
415
416
417
418
419
420
# File 'lib/numeric_with_unit/unit.rb', line 409

def **(num)
  if num.zero?
    self.class.new
  else
    self.class.derive do |derivation|
      # NOTE:
      # ここto_iでOKか?v*numが整数じゃなければraiseすべき?→すべき→NumericWithUnitでやるべき?
      # Unitでは整数じゃない次数の単位は許容すべきか否か→していい気がする
      @derivation.each{|k, v| derivation[k] = (v*num).to_i}
    end
  end
end

#/(other_unit) ⇒ Object



402
403
404
405
406
407
# File 'lib/numeric_with_unit/unit.rb', line 402

def /(other_unit)
  self.class.derive do |derivation|
    @derivation.each{|k, v| derivation[k] += v}
    other_unit.derivation.each{|k, v| derivation[k] -= v}
  end
end

#==(other) ⇒ Object



387
388
389
390
391
392
393
# File 'lib/numeric_with_unit/unit.rb', line 387

def ==(other)
  if other.is_a?(self.class)
    symbol == other.symbol and dimension == other.dimension
  else
    super
  end
end

#cast(new_symbol, factor = 1) ⇒ Object

create new unit with new symbol and factor from self. use for converting [in] = 25.4 .



350
351
352
353
354
355
356
357
# File 'lib/numeric_with_unit/unit.rb', line 350

def cast(new_symbol, factor = 1)
  self.class.new do |config|
    config.symbol = new_symbol
    config.dimension = @dimension
    config.from_si = ->(x){from_si(x.quo(factor))}
    config.to_si = ->(x){to_si(x * factor)}
  end
end

#dimension_equal?(other_unit) ⇒ Boolean

return true if self and other_unit have the same dimension.

Returns:

  • (Boolean)


381
382
383
384
385
# File 'lib/numeric_with_unit/unit.rb', line 381

def dimension_equal?(other_unit)
  (@dimension.keys | other_unit.dimension.keys).all?{|k|
    @dimension[k] == other_unit.dimension[k]
  }
end

#dimensionless?Boolean

Returns:

  • (Boolean)


376
377
378
# File 'lib/numeric_with_unit/unit.rb', line 376

def dimensionless?
  @dimension.all?{|k,v| v.zero?}
end

#from_si(value) ⇒ Object



371
372
373
# File 'lib/numeric_with_unit/unit.rb', line 371

def from_si(value)
  @from_si.call(value)
end

#inspectObject



363
364
365
# File 'lib/numeric_with_unit/unit.rb', line 363

def inspect
  "#<#{self.class}:[#{@symbol}] #{@dimension}>"
end

#simplifyObject



423
424
425
426
427
428
429
430
431
# File 'lib/numeric_with_unit/unit.rb', line 423

def simplify
  self.class.derive{|derivation|
    @dimension.each do|d,o|
      u = self.class.list.find{|u| u.dimension == {d => 1}} #TODO: find? ok?
      raise NoUnitError, "No unit with #{{d=>1}} dimension is assined." unless u
      derivation[u] = o
    end
  }
end

#to_sObject



359
360
361
# File 'lib/numeric_with_unit/unit.rb', line 359

def to_s
  @symbol
end

#to_si(value) ⇒ Object



367
368
369
# File 'lib/numeric_with_unit/unit.rb', line 367

def to_si(value)
  @to_si.call(value)
end