Class: AsciiChem::ModelAdapter::ToCanonical

Inherits:
Object
  • Object
show all
Defined in:
lib/asciichem/model_adapter/to_canonical.rb

Overview

AsciiChem::Model -> Chemicalml::Model. Walks the AsciiChem tree and builds a canonical document. Pure transformation; no I/O.

Mapping rules:

  • Formula -> Chemicalml::Cml::Document.
  • Molecule -> Chemicalml::Cml::Molecule. Inner atoms collect IDs; bonds reference consecutive IDs. Groups flatten with their multiplicity applied to each contained atom's count.
  • Atom -> Chemicalml::Cml::Atom (element, isotope, charge, count, lone pairs, radical electrons).
  • Bond -> Chemicalml::Cml::Bond (kind, refs).
  • Reaction -> Chemicalml::Cml::Reaction.
  • ReactionCascade -> Chemicalml::Cml::ReactionList.
  • ElectronConfiguration, EmbeddedMath, Text -> skipped (no canonical representation yet; a future extension can carry them as namespaced metadata).

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(formula) ⇒ ToCanonical

Returns a new instance of ToCanonical.



29
30
31
32
33
34
35
36
37
38
39
# File 'lib/asciichem/model_adapter/to_canonical.rb', line 29

def initialize(formula)
  @formula = formula
  @ids = IdRegistry.new
  @atom_mapping = {}
  # Map of canonical molecule ID -> array of GroupRecord.
  # Keyed by molecule ID because aci:group elements live inside
  # their parent <molecule>, and multiple molecules can exist
  # (top-level + reactants + products).
  @groups = Hash.new { |hash, key| hash[key] = [] }
  @molecule_id_stack = []
end

Instance Attribute Details

#atom_mappingObject (readonly)

Returns the value of attribute atom_mapping.



27
28
29
# File 'lib/asciichem/model_adapter/to_canonical.rb', line 27

def atom_mapping
  @atom_mapping
end

#groupsObject (readonly)

Returns the value of attribute groups.



27
28
29
# File 'lib/asciichem/model_adapter/to_canonical.rb', line 27

def groups
  @groups
end

Instance Method Details

#buildObject



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/asciichem/model_adapter/to_canonical.rb', line 41

def build
  molecules = []
  reactions = []
  reaction_lists = []
  @formula.nodes.each do |node|
    case node
    when AsciiChem::Model::Molecule
      molecules << molecule_to_canonical(node)
    when AsciiChem::Model::Reaction
      reactions << reaction_to_canonical(node)
    when AsciiChem::Model::ReactionCascade
      reaction_lists << reaction_cascade_to_canonical(node)
    end
  end
  Chemicalml::Cml::Document.new(
    molecules: molecules,
    reactions: reactions,
    reaction_lists: reaction_lists
  )
end