Class: Molecules::Calc

Inherits:
Tap::Task
  • Object
show all
Defined in:
lib/molecules/calc.rb

Overview

:startdoc::task a mass calculator

Calculates the mass of a molecule or formula. The options can be used to alter the output (precision, mass calculation method etc.)

% tap run -- molecules/calc H2O --: dump
18.0106 Da

% tap run -- molecules/calc "NH3 + H2O" --precision 2 --: dump
35.04 Da

Units can carry prefixes (ex ‘mm’, ‘kg’). See Ruby Units for more information.

% tap run -- molecules/calc H2O --units yg --precision 2 --: dump
29.91 yg

Note that Calc returns instances of Unit, which by default prints itself with a precison of 4. To view the full-precision value, inspect the scalar value of the result.

% tap run -- molecules/calc H2O --: inspect -m scalar
18.0105646863

Instance Method Summary collapse

Instance Method Details

#parse(formula) ⇒ Object

Parses the formula string into an EmpiricalFormula. Can be used as a hook for more complicated formulae in subclases.



48
49
50
# File 'lib/molecules/calc.rb', line 48

def parse(formula)
  EmpiricalFormula.parse(formula)
end

#process(formula) ⇒ Object

Returns an array of the calculated masses, in the correct unit.



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/molecules/calc.rb', line 53

def process(formula)
  mass = parse(formula).mass do |element|
    case type
    when :monoisotopic then element.mass
    when :average then element.std_atomic_weight.value
    else raise "unknown mass type: #{type}"
    end
  end

  mass = Unit.new(mass, "Da").convert_to(units)
  unless precision == nil
    mass = Unit.new( Utils.round(mass.scalar, precision), units) 
  end

  mass
end