Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Python] Add CanteraError class for execptions #370

Merged
merged 1 commit into from
Oct 19, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion SConstruct
Original file line number Diff line number Diff line change
Expand Up @@ -990,7 +990,7 @@ if env['VERBOSE']:
env['python_cmd_esc'] = quoted(env['python_cmd'])

# Python 2 Package Settings
cython_min_version = LooseVersion('0.19')
cython_min_version = LooseVersion('0.23')
env['install_python2_action'] = ''
if env['python_package'] == 'new':
env['python_package'] = 'full' # Allow 'new' as a synonym for 'full'
Expand Down
2 changes: 1 addition & 1 deletion doc/sphinx/compiling.rst
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ Linux
* Checking out the source code from version control requires Git (install
``git``).

* The minimum compatible Cython version is 0.19. If your distribution does not
* The minimum compatible Cython version is 0.23. If your distribution does not
contain a suitable version, you may be able to install a more recent version
using `pip`.

Expand Down
7 changes: 7 additions & 0 deletions include/cantera/cython/funcWrapper.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
#include "cantera/base/ctexceptions.h"
#include <stdexcept>

#define CANTERA_USE_INTERNAL
#include "cantera/clib/clib_defs.h"
#include "Python.h"

typedef double(*callback_wrapper)(double, void*, void**);
Expand Down Expand Up @@ -88,6 +90,9 @@ class Func1Py : public Cantera::Func1
void* m_pyobj;
};

extern "C" {
CANTERA_CAPI PyObject* pyCanteraError;
}

// Translate C++ Exceptions generated by Cantera to appropriate Python
// exceptions. Used with Cython function declarations, e.g:
Expand All @@ -105,6 +110,8 @@ inline int translate_exception()
PyErr_SetObject(exn.m_type, exn.m_value);
} catch (const std::out_of_range& exn) {
PyErr_SetString(PyExc_IndexError, exn.what());
} catch (const Cantera::CanteraError& exn) {
PyErr_SetString(pyCanteraError, exn.what());
} catch (const std::exception& exn) {
PyErr_SetString(PyExc_RuntimeError, exn.what());
} catch (...) {
Expand Down
530 changes: 265 additions & 265 deletions interfaces/cython/cantera/_cantera.pxd

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion interfaces/cython/cantera/composite.py
Original file line number Diff line number Diff line change
Expand Up @@ -615,7 +615,7 @@ def collect_data(self, cols=('extra','T','density','Y'), threshold=0,
single_species = True
collabels = ['{}_{}'.format(species, c)]
else:
raise Exception('property "{}" not supported'.format(c))
raise CanteraError('property "{}" not supported'.format(c))

# Get the data for the current group of columns
if single_species:
Expand Down
8 changes: 4 additions & 4 deletions interfaces/cython/cantera/onedim.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -850,7 +850,7 @@ cdef class Sim1D:
self.energy_enabled = True
self.sim.solve(loglevel, <cbool>False)
solved = True
except Exception as e:
except CanteraError as e:
log(str(e))
solved = False

Expand All @@ -866,7 +866,7 @@ cdef class Sim1D:
self.energy_enabled = True
self.sim.solve(loglevel, <cbool>False)
solved = True
except Exception as e:
except CanteraError as e:
log(str(e))

if solved and not self.extinct():
Expand All @@ -875,7 +875,7 @@ cdef class Sim1D:
try:
self.sim.solve(loglevel, <cbool>True)
solved = True
except Exception as e:
except CanteraError as e:
log(str(e))
solved = False

Expand All @@ -887,7 +887,7 @@ cdef class Sim1D:
log('Flame is extinct on {} point grid', N)

if not solved:
raise Exception('Could not find a solution for the 1D problem')
raise CanteraError('Could not find a solution for the 1D problem')

if solve_multi:
log('Solving with multicomponent transport')
Expand Down
22 changes: 11 additions & 11 deletions interfaces/cython/cantera/reactor.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ cdef class Reactor(ReactorBase):
name from the index.
"""
if not self.n_vars:
raise Exception('Reactor empty or network not initialized.')
raise CanteraError('Reactor empty or network not initialized.')
cdef np.ndarray[np.double_t, ndim=1] y = np.zeros(self.n_vars)
self.reactor.getState(&y[0])
return y
Expand Down Expand Up @@ -402,12 +402,12 @@ cdef class WallSurface:
"""
def __get__(self):
if self._kinetics is None:
raise Exception('No kinetics manager present')
raise CanteraError('No kinetics manager present')
self.cxxwall.syncCoverages(self.side)
return self._kinetics.coverages
def __set__(self, coverages):
if self._kinetics is None:
raise Exception("Can't set coverages before assigning kinetics manager.")
raise CanteraError("Can't set coverages before assigning kinetics manager.")

if isinstance(coverages, (dict, str, unicode, bytes)):
self.cxxwall.setCoverages(self.side, comp_map(coverages))
Expand Down Expand Up @@ -474,12 +474,12 @@ cdef class ReactorSurface:
"""
def __get__(self):
if self._kinetics is None:
raise Exception('No kinetics manager present')
raise CanteraError('No kinetics manager present')
self.surface.syncCoverages()
return self._kinetics.coverages
def __set__(self, coverages):
if self._kinetics is None:
raise Exception("Can't set coverages before assigning kinetics manager.")
raise CanteraError("Can't set coverages before assigning kinetics manager.")

if isinstance(coverages, (dict, str, unicode, bytes)):
self.surface.setCoverages(comp_map(coverages))
Expand Down Expand Up @@ -1116,7 +1116,7 @@ cdef class ReactorNet:
all entities contained.
"""
if not self.n_vars:
raise Exception('ReactorNet empty or not initialized.')
raise CanteraError('ReactorNet empty or not initialized.')
cdef np.ndarray[np.double_t, ndim=1] y = np.zeros(self.n_vars)
self.net.getState(&y[0])
return y
Expand Down Expand Up @@ -1153,9 +1153,9 @@ cdef class ReactorNet:
if not residual_threshold:
residual_threshold = 10. * self.rtol
if residual_threshold <= self.rtol:
raise Exception('Residual threshold (' + str(residual_threshold) +
') should be below solver rtol (' +
str(self.rtol) + ')')
raise CanteraError('Residual threshold (' + str(residual_threshold) +
') should be below solver rtol (' +
str(self.rtol) + ')')
if return_residuals:
residuals = np.empty(max_steps)
# check if system is initialized
Expand All @@ -1177,8 +1177,8 @@ cdef class ReactorNet:
if residual < residual_threshold:
break
if step == max_steps - 1:
raise Exception('Maximum number of steps reached before convergence'
' below maximum residual')
raise CanteraError('Maximum number of steps reached before'
' convergence below maximum residual')
if return_residuals:
return residuals[:step + 1]

Expand Down
2 changes: 1 addition & 1 deletion interfaces/cython/cantera/test/test_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -424,7 +424,7 @@ def test_pdep(self):
def test_invalid(self):
try:
gas = ct.Solution('../data/invalid.cti')
except RuntimeError as e:
except ct.CanteraError as e:
err = e

self.assertIn('already contains', err.args[0])
Expand Down
6 changes: 3 additions & 3 deletions interfaces/cython/cantera/test/test_onedim.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,10 @@ def test_grid_check(self):
gas = ct.Solution('h2o2.xml')
flame = ct.FreeFlow(gas)

with self.assertRaises(RuntimeError):
with self.assertRaises(ct.CanteraError):
flame.grid = [0, 0.1, 0.1, 0.2]

with self.assertRaises(RuntimeError):
with self.assertRaises(ct.CanteraError):
flame.grid = [0, 0.1, 0.2, 0.05]

def test_unpicklable(self):
Expand Down Expand Up @@ -279,7 +279,7 @@ def test_multicomponent(self):
def test_soret_flag(self):
self.create_sim(101325, 300, 'H2:1.0, O2:1.0')
self.assertFalse(self.sim.soret_enabled)
with self.assertRaises(RuntimeError):
with self.assertRaises(ct.CanteraError):
self.sim.soret_enabled = True
self.sim.transport_model = 'Multi'
self.sim.soret_enabled = True
Expand Down
10 changes: 5 additions & 5 deletions interfaces/cython/cantera/test/test_reactor.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,12 +458,12 @@ def test_valve_errors(self):
self.make_reactors()
res = ct.Reservoir()

with self.assertRaises(RuntimeError):
with self.assertRaises(ct.CanteraError):
# Must assign contents of both reactors before creating Valve
v = ct.Valve(self.r1, res)

v = ct.Valve(self.r1, self.r2)
with self.assertRaises(RuntimeError):
with self.assertRaises(ct.CanteraError):
# inlet and outlet cannot be reassigned
v._install(self.r2, self.r1)

Expand Down Expand Up @@ -497,15 +497,15 @@ def test_pressure_controller_errors(self):

p = ct.PressureController(self.r1, self.r2, master=mfc, K=0.5)

with self.assertRaises(RuntimeError):
with self.assertRaises(ct.CanteraError):
p = ct.PressureController(self.r1, self.r2, K=0.5)
p.mdot(0.0)

with self.assertRaises(RuntimeError):
with self.assertRaises(ct.CanteraError):
p = ct.PressureController(self.r1, self.r2, master=mfc)
p.mdot(0.0)

with self.assertRaises(RuntimeError):
with self.assertRaises(ct.CanteraError):
p = ct.PressureController(self.r1, self.r2)
p.mdot(0.0)

Expand Down
14 changes: 7 additions & 7 deletions interfaces/cython/cantera/test/test_thermo.py
Original file line number Diff line number Diff line change
Expand Up @@ -601,29 +601,29 @@ def test_add_species_disabled(self):
ref = ct.Solution('gri30.xml')

reactor = ct.IdealGasReactor(self.phase)
with self.assertRaises(RuntimeError):
with self.assertRaises(ct.CanteraError):
self.phase.add_species(ref.species('CH4'))
del reactor
gc.collect()
self.phase.add_species(ref.species('CH4'))

flame = ct.FreeFlame(self.phase, width=0.1)
with self.assertRaises(RuntimeError):
with self.assertRaises(ct.CanteraError):
self.phase.add_species(ref.species('CO'))
del flame
gc.collect()
self.phase.add_species(ref.species('CO'))

mix = ct.Mixture([(self.phase, 2.0)])
with self.assertRaises(RuntimeError):
with self.assertRaises(ct.CanteraError):
self.phase.add_species(ref.species('CH2O'))
del mix
gc.collect()
self.phase.add_species(ref.species('CH2O'))

def test_add_species_duplicate(self):
species = self.phase.species('H2O2')
with self.assertRaises(RuntimeError):
with self.assertRaises(ct.CanteraError):
self.phase.add_species(species)


Expand Down Expand Up @@ -1160,16 +1160,16 @@ def test_element_atomic_number(self):
self.assertEqual(self.ar_num.atomic_number, 18)

def test_element_name_not_present(self):
with self.assertRaises(RuntimeError):
with self.assertRaises(ct.CanteraError):
ct.Element('I am not an element')

def test_element_atomic_number_small(self):
with self.assertRaises(RuntimeError):
with self.assertRaises(ct.CanteraError):
ct.Element(0)

def test_element_atomic_number_big(self):
num_elements = ct.Element.num_elements_defined
with self.assertRaises(RuntimeError):
with self.assertRaises(ct.CanteraError):
ct.Element(num_elements + 1)

def test_element_bad_input(self):
Expand Down
2 changes: 1 addition & 1 deletion interfaces/cython/cantera/test/test_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def test_bad_geometry(self):
{'H':'atom', 'H2':'nonlinear', 'H2O':'nonlinear'},
{'H':'atom', 'H2':'linear', 'H2O':'atom'}]
for geoms in bad:
with self.assertRaises(RuntimeError):
with self.assertRaises(ct.CanteraError):
ct.Solution(source=self.phase_data.format(**geoms))


Expand Down
2 changes: 1 addition & 1 deletion interfaces/cython/cantera/thermo.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,7 @@ cdef class ThermoPhase(_SolutionBase):
automatically.
"""
if self._references:
raise RuntimeError('Cannot add species to ThermoPhase object if it'
raise CanteraError('Cannot add species to ThermoPhase object if it'
' is linked to a Reactor, Domain1D (flame), or Mixture object.')
self.thermo.addUndefinedElements()
self.thermo.addSpecies(species._species)
Expand Down
7 changes: 7 additions & 0 deletions interfaces/cython/cantera/utils.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
# at http://www.cantera.org/license.txt for license and copyright information.

import sys
from cpython.ref cimport PyObject

cdef int _pythonMajorVersion = sys.version_info[0]

cdef CxxPythonLogger* _logger = new CxxPythonLogger()
Expand Down Expand Up @@ -52,3 +54,8 @@ cdef Composition comp_map(X) except *:

cdef comp_map_to_dict(Composition m):
return {pystr(species):value for species,value in m.items()}

class CanteraError(RuntimeError):
pass

cdef public PyObject* pyCanteraError = <PyObject*>CanteraError