Skip to content

Commit

Permalink
[Python] Add Species.from_dict
Browse files Browse the repository at this point in the history
  • Loading branch information
ischoegl committed Jan 19, 2022
1 parent 442298c commit 3000123
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
24 changes: 23 additions & 1 deletion interfaces/cython/cantera/test/test_thermo.py
Original file line number Diff line number Diff line change
Expand Up @@ -1172,7 +1172,7 @@ def test_listFromCti(self):
S = ct.Species.listFromCti((self.cantera_data_path / "h2o2.cti").read_text())
self.assertEqual(S[3].name, self.gas.species_name(3))

def test_listFomYaml(self):
def test_listFromYaml(self):
yaml = '''
- name: H2O
composition: {H: 2, O: 1}
Expand All @@ -1186,6 +1186,28 @@ def test_listFomYaml(self):
self.assertEqual(species[1].composition, {'H': 1, 'O': 2})
self.assertNear(species[0].thermo.h(300), 100)

def test_fromYaml(self):
yaml = """
name: H2O
composition: {H: 2, O: 1}
thermo: {model: constant-cp, h0: 100}
"""
species = ct.Species.from_yaml(yaml)
self.assertEqual(species.name, 'H2O')
self.assertEqual(species.composition, {'H': 2, 'O': 1})
self.assertNear(species.thermo.h(300), 100)

def test_fromDict(self):
data = {
"name": "H2O",
"composition": "{H: 2, O: 1}",
"thermo": "{model: constant-cp, h0: 100}",
}
species = ct.Species.from_dict(data)
self.assertEqual(species.name, 'H2O')
self.assertEqual(species.composition, {'H': 2, 'O': 1})
self.assertNear(species.thermo.h(300), 100)

def test_listFromYaml_section(self):
species = ct.Species.list_from_yaml(
(self.test_data_path / "ideal-gas.yaml").read_text(),
Expand Down
17 changes: 16 additions & 1 deletion interfaces/cython/cantera/thermo.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -123,13 +123,28 @@ cdef class Species:
@staticmethod
def from_yaml(text):
"""
Create a Species object from its YAML string representation.
Create a `Species` object from its YAML string representation.
"""
cxx_species = CxxNewSpecies(AnyMapFromYamlString(stringify(text)))
species = Species(init=False)
species._assign(cxx_species)
return species

@staticmethod
def from_dict(data):
"""
Create a `Species` object from a dictionary corresponding to its YAML
representation.
:param data:
A dictionary corresponding to the YAML representation.
"""
cdef CxxAnyMap any_map = dict_to_anymap(data)
cxx_species = CxxNewSpecies(any_map)
species = Species(init=False)
species._assign(cxx_species)
return species

@staticmethod
def listFromFile(filename, section='species'):
"""
Expand Down

0 comments on commit 3000123

Please sign in to comment.