Repository: pybamm-team/PyBaMM

Issue:
Fix events with non-casadi solvers with non-casadi formats
Calling flatten on line 716 of `base_solver.py` raises error

Discussion:

Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e35bf59a6..3d68502a4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,9 @@
 
 ## Features
 
+-   Added NCA parameter set ([#824](https://github.com/pybamm-team/PyBaMM/pull/824))
+-   Added options to export a solution to matlab or csv ([#811](https://github.com/pybamm-team/PyBaMM/pull/811))
+-   Allow porosity to vary in space ([#809](https://github.com/pybamm-team/PyBaMM/pull/809))
 -   Added functionality to solve DAE models with non-smooth current inputs ([#808](https://github.com/pybamm-team/PyBaMM/pull/808))
 -   Added functionality to simulate experiments and testing protocols ([#807](https://github.com/pybamm-team/PyBaMM/pull/807))
 -   Added fuzzy string matching for parameters and variables ([#796](https://github.com/pybamm-team/PyBaMM/pull/796))
@@ -49,6 +52,7 @@
 
 ## Bug fixes
 
+-   Made `graphviz` an optional dependency ([#810](https://github.com/pybamm-team/PyBaMM/pull/810))
 -   Fixed examples to run with basic pip installation ([#800](https://github.com/pybamm-team/PyBaMM/pull/800))
 -   Added events for CasADi solver when stepping ([#800](https://github.com/pybamm-team/PyBaMM/pull/800))
 -   Improved implementation of broadcasts ([#776](https://github.com/pybamm-team/PyBaMM/pull/776))
diff --git a/examples/scripts/SPMe.py b/examples/scripts/SPMe.py
index ee87649a9..709958fd4 100644
--- a/examples/scripts/SPMe.py
+++ b/examples/scripts/SPMe.py
@@ -9,6 +9,7 @@ pybamm.set_logging_level("INFO")
 
 # load model
 model = pybamm.lithium_ion.SPMe()
+model.convert_to_format = "python"
 
 # create geometry
 geometry = model.default_geometry
diff --git a/pybamm/expression_tree/operations/simplify.py b/pybamm/expression_tree/operations/simplify.py
index 6e090db82..df033cea4 100644
--- a/pybamm/expression_tree/operations/simplify.py
+++ b/pybamm/expression_tree/operations/simplify.py
@@ -22,8 +22,10 @@ def simplify_if_constant(symbol, keep_domains=False):
     if symbol.is_constant():
         result = symbol.evaluate_ignoring_errors()
         if result is not None:
-            if isinstance(result, numbers.Number) or (
-                isinstance(result, np.ndarray) and result.ndim == 0
+            if (
+                isinstance(result, numbers.Number)
+                or (isinstance(result, np.ndarray) and result.ndim == 0)
+                or isinstance(result, np.bool_)
             ):
                 return pybamm.Scalar(result)
             elif isinstance(result, np.ndarray) or issparse(result):
diff --git a/pybamm/expression_tree/scalar.py b/pybamm/expression_tree/scalar.py
index 975c77087..b96d618c7 100644
--- a/pybamm/expression_tree/scalar.py
+++ b/pybamm/expression_tree/scalar.py
@@ -2,6 +2,7 @@
 # Scalar class
 #
 import pybamm
+import numpy as np
 
 
 class Scalar(pybamm.Symbol):
@@ -40,7 +41,7 @@ class Scalar(pybamm.Symbol):
 
     @value.setter
     def value(self, value):
-        self._value = float(value)
+        self._value = np.float64(value)
 
     def set_id(self):
         """ See :meth:`pybamm.Symbol.set_id()`. """
diff --git a/pybamm/parameters/parameter_values.py b/pybamm/parameters/parameter_values.py
index 358c50a5f..dbe21647b 100644
--- a/pybamm/parameters/parameter_values.py
+++ b/pybamm/parameters/parameter_values.py
@@ -385,8 +385,9 @@ class ParameterValues:
             model.variables[variable] = self.process_symbol(equation)
 
         for event in model.events:
-            pybamm.logger.debug("Processing parameters for event'{}''"
-                                .format(event.name))
+            pybamm.logger.debug(
+                "Processing parameters for event'{}''".format(event.name)
+            )
             event.expression = self.process_symbol(event.expression)
 
         pybamm.logger.info("Finish setting parameters for {}".format(model.name))
diff --git a/pybamm/solvers/base_solver.py b/pybamm/solvers/base_solver.py
index 450735eee..7b11c219e 100644
--- a/pybamm/solvers/base_solver.py
+++ b/pybamm/solvers/base_solver.py
@@ -217,16 +217,20 @@ class BaseSolver(object):
         # Check for heaviside functions in rhs and algebraic and add discontinuity
         # events if these exist.
         # Note: only checks for the case of t < X, t <= X, X < t, or X <= t
-        for symbol in itertools.chain(model.concatenated_rhs.pre_order(),
-                                      model.concatenated_algebraic.pre_order()):
+        for symbol in itertools.chain(
+            model.concatenated_rhs.pre_order(), model.concatenated_algebraic.pre_order()
+        ):
             if isinstance(symbol, pybamm.Heaviside):
                 if symbol.right.id == pybamm.t.id:
                     expr = symbol.left
                 elif symbol.left.id == pybamm.t.id:
                     expr = symbol.right
 
-                model.events.append(pybamm.Event(str(symbol), expr.new_copy(),
-                                                 pybamm.EventType.DISCONTINUITY))
+                model.events.append(
+                    pybamm.Event(
+                        str(symbol), expr.new_copy(), pybamm.EventType.DISCONTINUITY
+                    )
+                )
 
         # Process rhs, algebraic and event expressions
         rhs, rhs_eval, jac_rhs = process(model.concatenated_rhs, "RHS")
@@ -242,7 +246,8 @@ class BaseSolver(object):
         # discontinuity events are evaluated before the solver is called, so don't need
         # to process them
         discontinuity_events_eval = [
-            event for event in model.events
+            event
+            for event in model.events
             if event.event_type == pybamm.EventType.DISCONTINUITY
         ]
 
@@ -452,12 +457,17 @@ class BaseSolver(object):
 
         # make sure they are increasing in time
         discontinuities = sorted(discontinuities)
-        pybamm.logger.info(
-            'Discontinuity events found at t = {}'.format(discontinuities)
-        )
+        if len(discontinuities) > 0:
+            pybamm.logger.info(
+                "Discontinuity events found at t = {}".format(discontinuities)
+            )
+        else:
+            pybamm.logger.info("No discontinuity events found")
+
         # remove any identical discontinuities
         discontinuities = [
-            v for i, v in enumerate(discontinuities)
+            v
+            for i, v in enumerate(discontinuities)
             if i == len(discontinuities) - 1
             or discontinuities[i] < discontinuities[i + 1]
         ]
@@ -467,16 +477,18 @@ class BaseSolver(object):
         start_indices = [0]
         end_indices = []
         for dtime in discontinuities:
-            dindex = np.searchsorted(t_eval, dtime, side='left')
+            dindex = np.searchsorted(t_eval, dtime, side="left")
             end_indices.append(dindex + 1)
             start_indices.append(dindex + 1)
             if t_eval[dindex] == dtime:
                 t_eval[dindex] += sys.float_info.epsilon
                 t_eval = np.insert(t_eval, dindex, dtime - sys.float_info.epsilon)
             else:
-                t_eval = np.insert(t_eval, dindex,
-                                   [dtime - sys.float_info.epsilon,
-                                    dtime + sys.float_info.epsilon])
+                t_eval = np.insert(
+                    t_eval,
+                    dindex,
+                    [dtime - sys.float_info.epsilon, dtime + sys.float_info.epsilon],
+                )
         end_indices.append(len(t_eval))
 
         # integrate separatly over each time segment and accumulate into the solution
@@ -485,16 +497,21 @@ class BaseSolver(object):
         old_y0 = model.y0
         solution = None
         for start_index, end_index in zip(start_indices, end_indices):
-            pybamm.logger.info("Calling solver for {} < t < {}"
-                               .format(t_eval[start_index], t_eval[end_index - 1]))
+            pybamm.logger.info(
+                "Calling solver for {} < t < {}".format(
+                    t_eval[start_index], t_eval[end_index - 1]
+                )
+            )
             timer.reset()
             if solution is None:
                 solution = self._integrate(
-                    model, t_eval[start_index:end_index], ext_and_inputs)
+                    model, t_eval[start_index:end_index], ext_and_inputs
+                )
                 solution.solve_time = timer.time()
             else:
                 new_solution = self._integrate(
-                    model, t_eval[start_index:end_index], ext_and_inputs)
+                    model, t_eval[start_index:end_index], ext_and_inputs
+                )
                 new_solution.solve_time = timer.time()
                 solution.append(new_solution, start_index=0)
 
@@ -506,14 +523,16 @@ class BaseSolver(object):
                 y0_guess = solution.y[:, -1]
                 if model.algebraic:
                     model.y0 = self.calculate_consistent_state(
-                        model, t_eval[end_index], y0_guess)
+                        model, t_eval[end_index], y0_guess
+                    )
                 else:
                     model.y0 = y0_guess
 
                 last_state = solution.y[:, -1]
                 if len(model.algebraic) > 0:
                     model.y0 = self.calculate_consistent_state(
-                        model, t_eval[end_index], last_state)
+                        model, t_eval[end_index], last_state
+                    )
                 else:
                     model.y0 = last_state
 


Test patch:
diff --git a/tests/integration/test_models/test_full_battery_models/test_lithium_ion/test_spme.py b/tests/integration/test_models/test_full_battery_models/test_lithium_ion/test_spme.py
index 0dc59f881..bf4866984 100644
--- a/tests/integration/test_models/test_full_battery_models/test_lithium_ion/test_spme.py
+++ b/tests/integration/test_models/test_full_battery_models/test_lithium_ion/test_spme.py
@@ -15,6 +15,13 @@ class TestSPMe(unittest.TestCase):
         modeltest = tests.StandardModelTest(model)
         modeltest.test_all()
 
+    def test_basic_processing_python(self):
+        options = {"thermal": "isothermal"}
+        model = pybamm.lithium_ion.SPMe(options)
+        model.convert_to_format = "python"
+        modeltest = tests.StandardModelTest(model, solver=pybamm.ScipySolver())
+        modeltest.test_all()
+
     def test_basic_processing_1plus1D(self):
         options = {"current collector": "potential pair", "dimensionality": 1}
         model = pybamm.lithium_ion.SPMe(options)