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 Feb 4, 2022
1 parent 2d772ab commit c60347f
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
26 changes: 24 additions & 2 deletions 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_list_from_yaml(self):
yaml = '''
- name: H2O
composition: {H: 2, O: 1}
Expand All @@ -1186,14 +1186,36 @@ def test_listFomYaml(self):
self.assertEqual(species[1].composition, {'H': 1, 'O': 2})
self.assertNear(species[0].thermo.h(300), 100)

def test_listFromYaml_section(self):
def test_list_from_yaml_section(self):
species = ct.Species.list_from_yaml(
(self.test_data_path / "ideal-gas.yaml").read_text(),
'species')

self.assertEqual(species[0].name, 'O2')
self.assertEqual(species[1].composition, {'N': 1, 'O': 1})

def test_from_yaml(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_from_dict(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)

@utilities.allow_deprecated
def test_listFromXml(self):
S = ct.Species.listFromXml((self.cantera_data_path / "h2o2.xml").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 c60347f

Please sign in to comment.