module Mspire::MolecularFormula::Reader

Public Instance Methods

[](arg, charge=nil)
Alias for: from_any
formula_and_charge(string) click to toggle source

returns the formula portion and the charge portion (signed Int) of a string returns nil for charge if no charge specified. e.g. C2H4+3 => ['C2H4', 3] e.g. C2H4+++ => ['C2H4', 3] e.g. C2H4- => ['C2H4', -1]

# File lib/mspire/molecular_formula/reader.rb, line 11
def formula_and_charge(string)
  md = string.match(/([^+-]*)([\+-]+)(\d*)\Z/)
  if md
    charges_string = md[2]
    chrg = 
      if md[3] != ''
        md[2] == '-' ? -md[3].to_i : md[3].to_i
      else
        sign = charges_string[0]
        cnt = charges_string.count(sign)
        sign == '-' ? -cnt : cnt
      end
    [md[1], chrg]
  else
    [string, nil]
  end
end
from_aaseq(aaseq, charge=0, aa_formula_hash=Mspire::MolecularFormula::AA::FORMULAS_STRING) click to toggle source

a linear peptide (so includes all the residue masses plus water)

# File lib/mspire/molecular_formula/aa.rb, line 68
def from_aaseq(aaseq, charge=0, aa_formula_hash=Mspire::MolecularFormula::AA::FORMULAS_STRING)
  hash = aaseq.each_char.inject({}) do |hash,aa| 
    hash.merge(aa_formula_hash[aa]) {|hash,old,new| (old ? old : 0) + new }
  end
  hash[:H] += 2
  hash[:O] += 1
  self.new(hash, charge)
end
from_any(arg, charge=nil) click to toggle source

arg may be a String, Hash, or MolecularFormula object.

# File lib/mspire/molecular_formula/reader.rb, line 43
def from_any(arg, charge=nil)
  if arg.is_a?(String)
    from_string(arg, charge)
  else
    self.new(arg, arg.respond_to?(:charge) ? arg.charge : 0)
  end
end
Also aliased as: []
from_string(arg, charge=nil) click to toggle source

takes a string, with properly capitalized elements making up the formula. The elements may be in any order. A charge (e.g., +2, +, -, -3 may be affixed to the end )

# File lib/mspire/molecular_formula/reader.rb, line 33
def from_string(arg, charge=nil)
  (mol_form_str, chrg_from_str) = formula_and_charge(arg)
  mf = self.new({}, charge || chrg_from_str || 0)
  mol_form_str.scan(/([A-Z][a-z]?)(\d*)/).each do |k,v| 
    mf[k.to_sym] = (v == '' ? 1 : v.to_i)
  end
  mf
end