From d79199fd267d35a4325abd41502cdbfa43e9dde2 Mon Sep 17 00:00:00 2001 From: PeterMeisrimelModelon <92585725+PeterMeisrimelModelon@users.noreply.github.com> Date: Fri, 26 Jan 2024 14:40:48 +0100 Subject: [PATCH] Unifying numpy, scipy, pylab imports --- src/common/algorithm_drivers.py | 18 +- src/common/core.py | 52 +-- src/common/io.py | 83 +++-- src/common/plotting/plot_gui.py | 2 +- src/pyfmi/__init__.py | 6 +- src/pyfmi/debug.py | 128 +++---- .../examples/fmi20_bouncing_ball_native.py | 26 +- src/pyfmi/examples/fmi_bouncing_ball.py | 30 +- src/pyfmi/examples/fmi_bouncing_ball_cs.py | 30 +- .../examples/fmi_bouncing_ball_native.py | 26 +- src/pyfmi/examples/fmu_with_input.py | 28 +- src/pyfmi/examples/fmu_with_input_function.py | 24 +- src/pyfmi/fmi.pxd | 20 +- src/pyfmi/fmi.pyx | 346 +++++++++--------- src/pyfmi/fmi_algorithm_drivers.py | 26 +- src/pyfmi/fmi_coupled.pyx | 13 +- src/pyfmi/fmi_extended.pyx | 24 +- src/pyfmi/master.pyx | 43 ++- src/pyfmi/simulation/assimulo_interface.pxd | 12 +- src/pyfmi/simulation/assimulo_interface.pyx | 93 +++-- tests/test_fmi_master.py | 8 +- 21 files changed, 520 insertions(+), 518 deletions(-) diff --git a/src/common/algorithm_drivers.py b/src/common/algorithm_drivers.py index fc69c50e..209abc86 100644 --- a/src/common/algorithm_drivers.py +++ b/src/common/algorithm_drivers.py @@ -18,11 +18,11 @@ Module containing optimization, simulation and initialization algorithms. """ -import numpy as N +import numpy as np default_int = int -int = N.int32 -N.int = N.int32 +int = np.int32 +np.int = np.int32 class AlgorithmBase(object): """ @@ -33,16 +33,20 @@ class AlgorithmBase(object): # __metaclass__=ABCMeta # @abstractmethod - def __init__(self, model, alg_args): pass + def __init__(self, model, alg_args): + pass # @abstractmethod - def solve(self): pass + def solve(self): + pass # @abstractmethod - def get_result(self): pass + def get_result(self): + pass @classmethod - def get_default_options(self): pass + def get_default_options(self): + pass class ResultBase(object): """ diff --git a/src/common/core.py b/src/common/core.py index 8bd8baaf..0cfb3f52 100644 --- a/src/common/core.py +++ b/src/common/core.py @@ -25,7 +25,7 @@ import sys import shutil -import numpy as N +import numpy as np # location for temporary JModelica files def get_temp_location(): @@ -490,20 +490,20 @@ def __init__(self, abscissa, ordinate, tol=1e-8): """ self._abscissa = abscissa.astype('float') self._ordinate = ordinate - self._n = N.size(abscissa) - self._n_ordinate = N.size(self.ordinate,1) + self._n = np.size(abscissa) + self._n_ordinate = np.size(self.ordinate,1) self._x0 = abscissa[0] self._xf = abscissa[-1] - if not N.all(N.diff(self.abscissa) >= 0): + if not np.all(np.diff(self.abscissa) >= 0): raise Exception("The abscissae must be increasing.") - [double_point_indices] = N.nonzero(N.abs(N.diff(self.abscissa)) <= tol) + [double_point_indices] = np.nonzero(np.abs(np.diff(self.abscissa)) <= tol) while (len(double_point_indices) > 0): for i in double_point_indices: self.abscissa[i+1] = self.abscissa[i+1] + tol - [double_point_indices] = N.nonzero( - N.abs(N.diff(self.abscissa)) <= tol) + [double_point_indices] = np.nonzero( + np.abs(np.diff(self.abscissa)) <= tol) def eval(self,x): """ @@ -561,9 +561,9 @@ def eval(self,x): Two dimensional n x m matrix containing the ordinate values corresponding to the argument x. """ - y = N.zeros([N.size(x),self._n_ordinate]) + y = np.zeros([np.size(x),self._n_ordinate]) for i in range(self._n_ordinate): - y[:,i] = N.interp(x,self.abscissa,self.ordinate[:,i]) + y[:,i] = np.interp(x,self.abscissa,self.ordinate[:,i]) return y class TrajectoryLinearInterpolationExtrapolation(Trajectory): @@ -590,11 +590,11 @@ def eval(self, x): See http://stackoverflow.com/questions/2745329/how-to-make-scipy-interpolate-give-a-an-extrapolated-result-beyond-the-input-ran """ - y = N.zeros([N.size(x),N.size(self.ordinate,1)]) - for i in range(N.size(y,1)): - y[:,i] = N.interp(x,self.abscissa,self.ordinate[:,i]) - y[:,i] = N.where(x < self.abscissa[0], self.ordinate[0,i]+(x-self.abscissa[0])*(self.ordinate[0,i]-self.ordinate[1,i])/(self.abscissa[0]-self.abscissa[1]), y[:,i]) - y[:,i] = N.where(x > self.abscissa[-1], self.ordinate[-1,i]+(x-self.abscissa[-1])*(self.ordinate[-1,i]-self.ordinate[-2,i])/(self.abscissa[-1]-self.abscissa[-2]), y[:,i]) + y = np.zeros([np.size(x),np.size(self.ordinate,1)]) + for i in range(np.size(y,1)): + y[:,i] = np.interp(x,self.abscissa,self.ordinate[:,i]) + y[:,i] = np.where(x < self.abscissa[0], self.ordinate[0,i]+(x-self.abscissa[0])*(self.ordinate[0,i]-self.ordinate[1,i])/(self.abscissa[0]-self.abscissa[1]), y[:,i]) + y[:,i] = np.where(x > self.abscissa[-1], self.ordinate[-1,i]+(x-self.abscissa[-1])*(self.ordinate[-1,i]-self.ordinate[-2,i])/(self.abscissa[-1]-self.abscissa[-2]), y[:,i]) return y class TrajectoryConstantInterpolationExtrapolation(Trajectory): @@ -634,27 +634,27 @@ def eval(self, x): See http://stackoverflow.com/questions/2745329/how-to-make-scipy-interpolate-give-a-an-extrapolated-result-beyond-the-input-ran """ - y = N.zeros([N.size(x),N.size(self.ordinate,1)]) - x = N.array([x]).flatten() + y = np.zeros([np.size(x),np.size(self.ordinate,1)]) + x = np.array([x]).flatten() if self._mode == 1: - for i in range(N.size(y,1)): - for j in range(N.size(x)): + for i in range(np.size(y,1)): + for j in range(np.size(x)): try: y[j,i] = self.ordinate[self.abscissa<=x[j],i][-1] except IndexError: pass - y[:,i] = N.where(x < self.abscissa[0], self.ordinate[0,i], y[:,i]) - y[:,i] = N.where(x > self.abscissa[-1], self.ordinate[-1,i], y[:,i]) + y[:,i] = np.where(x < self.abscissa[0], self.ordinate[0,i], y[:,i]) + y[:,i] = np.where(x > self.abscissa[-1], self.ordinate[-1,i], y[:,i]) else: - for i in range(N.size(y,1)): - for j in range(N.size(x)): + for i in range(np.size(y,1)): + for j in range(np.size(x)): try: y[j,i] = self.ordinate[self.abscissa>=x[j],i][0] except IndexError: pass - y[:,i] = N.where(x < self.abscissa[0], self.ordinate[0,i], y[:,i]) - y[:,i] = N.where(x > self.abscissa[-1], self.ordinate[-1,i], y[:,i]) + y[:,i] = np.where(x < self.abscissa[0], self.ordinate[0,i], y[:,i]) + y[:,i] = np.where(x > self.abscissa[-1], self.ordinate[-1,i], y[:,i]) return y class TrajectoryUserFunction(Trajectory): @@ -686,9 +686,9 @@ def eval(self, x): corresponding to the argument x. """ try: - y = N.array(N.matrix(self.traj(float(x)))) + y = np.array(np.matrix(self.traj(float(x)))) except TypeError: - y = N.array(N.matrix(self.traj(x)).transpose()) + y = np.array(np.matrix(self.traj(x)).transpose()) #In order to guarantee that the #return values are on the correct #form. May need to be evaluated diff --git a/src/common/io.py b/src/common/io.py index c0e391da..2f3b4c8a 100644 --- a/src/common/io.py +++ b/src/common/io.py @@ -24,7 +24,6 @@ import os from functools import reduce -import numpy as N import numpy as np import scipy scipy_minmaj = tuple(map(int, scipy.__version__.split('.')[:2])) @@ -200,7 +199,7 @@ def _exhaustive_search_for_derivatives(self, name): state = self._find_underlying_state(name) index = self.get_variable_index(state) - alias_index = N.where(self.dataInfo[:,1]==self.dataInfo[index,1])[0] + alias_index = np.where(self.dataInfo[:,1]==self.dataInfo[index,1])[0] #Loop through all alias for ind in alias_index: @@ -326,7 +325,7 @@ def __init__(self, filename, delimiter=";"): data.append([float(d) for d in row]) - self.data = N.array(data) + self.data = np.array(data) def get_variable_data(self,name): """ @@ -604,9 +603,9 @@ def write_header(self, file_name='', parameters=None): f.write('int dataInfo(%d,%d)\n' % (num_vars+len(names_sens) + 1, 4)) f.write('0 1 0 -1 # time\n') - list_of_continuous_states = N.append(self.model._save_real_variables_val, + list_of_continuous_states = np.append(self.model._save_real_variables_val, self.model._save_int_variables_val) - list_of_continuous_states = N.append(list_of_continuous_states, + list_of_continuous_states = np.append(list_of_continuous_states, self.model._save_bool_variables_val).tolist() list_of_continuous_states = dict(zip(list_of_continuous_states, range(len(list_of_continuous_states)))) @@ -712,7 +711,7 @@ def write_point(self, data=None, parameter_data=[]): if data is None: #Retrieves the time-point [r,i,b] = self.model.save_time_point() - data = N.append(N.append(N.append(self.model.time,r),i),b) + data = np.append(np.append(np.append(self.model.time,r),i),b) #Write the point str_text = (" %.14E" % data[0]) @@ -806,7 +805,7 @@ def get_variable_data(self,name): factor = -1 if var.alias == fmi.FMI_NEGATED_ALIAS else 1 if var.variability == fmi.FMI_CONSTANT or var.variability == fmi.FMI_PARAMETER: - return Trajectory([self.time[0],self.time[-1]],N.array([self.model.get(name),self.model.get(name)]).ravel()) + return Trajectory([self.time[0],self.time[-1]],np.array([self.model.get(name),self.model.get(name)]).ravel()) else: return Trajectory(self.time,factor*self.data[var.value_reference]) @@ -928,7 +927,7 @@ def __init__(self,fname): nLines = int(nLines[0]) nCols = int(nCols[0]) - self.dataInfo = N.array([list(map(int,fid.readline().split()[0:nCols])) for i in range(nLines)]) + self.dataInfo = np.array([list(map(int,fid.readline().split()[0:nCols])) for i in range(nLines)]) # Find out how many data matrices there are if len(self._name) == 1: #Only time @@ -963,7 +962,7 @@ def __init__(self,fname): if len(info) == 0 and i < nLines-1: raise JIOError("Inconsistent number of lines in the result data.") del(info) - self.data.append(N.array(data)) + self.data.append(np.array(data)) if len(self.data) == 0: raise JIOError('Could not find any variable data in the result file.') @@ -1109,7 +1108,7 @@ def shift_time(self,time_shift): The time shift offset. """ for i in range(len(self.data)): - for j in range(N.shape(self.data[i])[0]): + for j in range(np.shape(self.data[i])[0]): self.data[i][j,0] = self.data[i][j,0] + time_shift def append(self, res): @@ -1122,9 +1121,9 @@ def append(self, res): res -- A simulation result object of type DymolaResultTextual. """ - n_points = N.size(res.data[1],0) + n_points = np.size(res.data[1],0) time_shift = self.data[1][-1,0] - self.data[1] = N.vstack((self.data[1],res.data[1])) + self.data[1] = np.vstack((self.data[1],res.data[1])) self.data[1][n_points:,0] = self.data[1][n_points:,0] + time_shift #Overriding SCIPYs default reader for MATLAB v4 format @@ -1449,7 +1448,7 @@ def get_variable_data(self, name): elif '{}.'.format(DiagnosticsBase.calculated_diagnostics['nbr_state_limits_step']['name']) in name: return Trajectory(self._get_diagnostics_trajectory(0), self._calculate_nbr_state_limits_step(name)) elif name == f'{DIAGNOSTICS_PREFIX}cpu_time': - return Trajectory(self._get_diagnostics_trajectory(0), N.cumsum(self.get_variable_data(f'{DIAGNOSTICS_PREFIX}cpu_time_per_step').x)) + return Trajectory(self._get_diagnostics_trajectory(0), np.cumsum(self.get_variable_data(f'{DIAGNOSTICS_PREFIX}cpu_time_per_step').x)) else: varInd = self.get_variable_index(name) @@ -1488,12 +1487,12 @@ def _calculate_events_and_steps(self, name): event_type_data = self.get_variable_data(f'{DIAGNOSTICS_PREFIX}event_data.event_info.event_type') except Exception: if name == steps_name: - self._data_3[steps_name] = N.array(range(len(self._get_diagnostics_trajectory(0)))) + self._data_3[steps_name] = np.array(range(len(self._get_diagnostics_trajectory(0)))) return self._data_3[name] - self._data_3[all_events_name] = N.zeros(len(event_type_data.x)) - self._data_3[time_events_name] = N.zeros(len(event_type_data.x)) - self._data_3[state_events_name] = N.zeros(len(event_type_data.x)) - self._data_3[steps_name] = N.zeros(len(event_type_data.x)) + self._data_3[all_events_name] = np.zeros(len(event_type_data.x)) + self._data_3[time_events_name] = np.zeros(len(event_type_data.x)) + self._data_3[state_events_name] = np.zeros(len(event_type_data.x)) + self._data_3[steps_name] = np.zeros(len(event_type_data.x)) nof_events = 0 nof_time_events = 0 nof_state_events = 0 @@ -1520,7 +1519,7 @@ def _calculate_nbr_state_limits_step(self, name): state_name = name.replace(step_limitation_name, '') state_error_data = self.get_variable_data(f'{DIAGNOSTICS_PREFIX}state_errors.'+state_name) event_type_data = self.get_variable_data(f'{DIAGNOSTICS_PREFIX}event_data.event_info.event_type') - self._data_3[name] = N.zeros(len(event_type_data.x)) + self._data_3[name] = np.zeros(len(event_type_data.x)) nof_times_state_limits_step = 0 for ind, state_error in enumerate(state_error_data.x): if event_type_data.x[ind] == -1 and state_error >= 1.0: @@ -1670,7 +1669,7 @@ def integration_point(self, solver = None): #Sets the parameters, if any if solver and self.options["sensitivities"]: - self.param_sol += [N.array(solver.interpolate_sensitivity(model.time, 0)).flatten()] + self.param_sol += [np.array(solver.interpolate_sensitivity(model.time, 0)).flatten()] def simulation_end(self): """ @@ -1685,16 +1684,16 @@ def get_result(self): result of an instance of ResultBase or of an instance of a subclass of ResultBase. """ - t = N.array(self.time_sol) - r = N.array(self.real_sol) - data = N.c_[t,r] + t = np.array(self.time_sol) + r = np.array(self.real_sol) + data = np.c_[t,r] if len(self.int_sol) > 0 and len(self.int_sol[0]) > 0: - i = N.array(self.int_sol) - data = N.c_[data,i] + i = np.array(self.int_sol) + data = np.c_[data,i] if len(self.bool_sol) > 0 and len(self.bool_sol[0]) > 0: - b = N.array(self.bool_sol) - data = N.c_[data,b] + b = np.array(self.bool_sol) + data = np.c_[data,b] return ResultStorageMemory(self.model, data, [self.real_var_ref,self.int_var_ref,self.bool_var_ref], self.vars) @@ -1822,18 +1821,18 @@ def simulation_start(self): for i,val in enumerate(const_val_bool): const_str += "%.14E"%(const_alias_bool[i]*val)+delimiter - #for val in N.append(const_val_real,N.append(const_val_int,const_val_boolean)): + #for val in np.append(const_val_real,np.append(const_val_int,const_val_boolean)): # const_str += "%.14E"%val+delimiter self.const_str = const_str self._file = f self.cont_valref_real = cont_valref_real - self.cont_alias_real = N.array(cont_alias_real) + self.cont_alias_real = np.array(cont_alias_real) self.cont_valref_int = cont_valref_int - self.cont_alias_int = N.array(cont_alias_int) + self.cont_alias_int = np.array(cont_alias_int) self.cont_valref_bool = cont_valref_bool - self.cont_alias_bool = N.array(cont_alias_bool) + self.cont_alias_bool = np.array(cont_alias_bool) def integration_point(self, solver = None): """ @@ -1859,7 +1858,7 @@ def integration_point(self, solver = None): i = model.get_integer(self.cont_valref_int)*self.cont_alias_int b = model.get_boolean(self.cont_valref_bool)*self.cont_alias_bool - data = N.append(N.append(r,i),b) + data = np.append(np.append(r,i),b) cont_str = "" for val in data: @@ -2259,10 +2258,10 @@ def simulation_start(self): #f.write('%s,%d)\n' % (' '*14, self._nvariables)) self._file = f - self._data_order = N.array(valueref_of_continuous_states) - self.real_var_ref = N.array(self.real_var_ref) - self.int_var_ref = N.array(self.int_var_ref) - self.bool_var_ref = N.array(self.bool_var_ref) + self._data_order = np.array(valueref_of_continuous_states) + self.real_var_ref = np.array(self.real_var_ref) + self.int_var_ref = np.array(self.int_var_ref) + self.bool_var_ref = np.array(self.bool_var_ref) def integration_point(self, solver = None):#parameter_data=[]): """ @@ -2287,14 +2286,14 @@ def integration_point(self, solver = None):#parameter_data=[]): i = model.get_integer(self.int_var_ref) b = model.get_boolean(self.bool_var_ref) - data = N.append(N.append(r,i),b) + data = np.append(np.append(r,i),b) #Write the point str_text = (" %.14E" % self.model.time) + ''.join([" %.14E" % (data[data_order[j]]) for j in range(self._nvariables-1)]) #Sets the parameters, if any if solver and self.options["sensitivities"]: - parameter_data = N.array(solver.interpolate_sensitivity(model.time, 0)).flatten() + parameter_data = np.array(solver.interpolate_sensitivity(model.time, 0)).flatten() for j in range(len(parameter_data)): str_text = str_text + (" %.14E" % (parameter_data[j])) @@ -2397,11 +2396,11 @@ def robust_float(value): return float(value) except ValueError: if value.startswith("1.#INF"): - return float(N.inf) + return float(np.inf) elif value.startswith("-1.#INF"): - return float(-N.inf) + return float(-np.inf) elif value.startswith("1.#QNAN") or value.startswith("-1.#IND"): - return float(N.nan) + return float(np.nan) else: raise ValueError @@ -2609,7 +2608,7 @@ def simulation_start(self, diagnostics_params={}, diagnostics_vars={}): self.dump_data_internal = fmi_util.DumpData(self.model, self._file, self.real_var_ref, self.int_var_ref, self.bool_var_ref, self._with_diagnostics) if self._with_diagnostics: - diag_data = N.array([val[0] for val in diagnostics_vars.values()], dtype=float) + diag_data = np.array([val[0] for val in diagnostics_vars.values()], dtype=float) self.diagnostics_point(diag_data) def integration_point(self, solver = None): diff --git a/src/common/plotting/plot_gui.py b/src/common/plotting/plot_gui.py index 380f929f..7c3cf89e 100644 --- a/src/common/plotting/plot_gui.py +++ b/src/common/plotting/plot_gui.py @@ -25,7 +25,7 @@ from matplotlib import rcParams import fnmatch import re -import oss +import os #GUI modules try: diff --git a/src/pyfmi/__init__.py b/src/pyfmi/__init__.py index 05b87784..49d628c6 100644 --- a/src/pyfmi/__init__.py +++ b/src/pyfmi/__init__.py @@ -26,13 +26,13 @@ from pyfmi.fmi_coupled import CoupledFMUModelME2 from pyfmi.master import Master from pyfmi.fmi_extended import FMUModelME1Extended -import numpy as N +import numpy as np import os.path import sys import time -int = N.int32 -N.int = N.int32 +int = np.int32 +np.int = np.int32 def testattr(**kwargs): """Add attributes to a test function/method/class. diff --git a/src/pyfmi/debug.py b/src/pyfmi/debug.py index a66e6e41..3e1b8837 100644 --- a/src/pyfmi/debug.py +++ b/src/pyfmi/debug.py @@ -19,8 +19,8 @@ This file contains methods for helping with debugging a simulation. """ -import numpy as N -import pylab as P +import numpy as np +import pylab as pl class DebugInformation: @@ -49,7 +49,7 @@ def _load_data(self): if len(row_data) > 2: event_indicators = row_data[2].strip().replace("\n","") event_indicators = event_indicators.split(" ") - self.event_indicators.append(N.array([abs(float(i)) for i in event_indicators])) + self.event_indicators.append(np.array([abs(float(i)) for i in event_indicators])) row_data = file.readline() elif row_data.startswith("Solver"): self.solver = row_data.split(" ")[-1] @@ -63,69 +63,69 @@ def _load_data(self): def plot_time_distribution(self, normalized=False): if normalized: - total_time = N.sum(self.real_time) - P.plot(self.simulated_time,self.real_time/total_time) - P.ylabel("Real Time (normalized)") + total_time = np.sum(self.real_time) + pl.plot(self.simulated_time,self.real_time/total_time) + pl.ylabel("Real Time (normalized)") else: - P.plot(self.simulated_time,self.real_time) - P.ylabel("Real Time [s]") - P.xlabel("Time [s]") + pl.plot(self.simulated_time,self.real_time) + pl.ylabel("Real Time [s]") + pl.xlabel("Time [s]") self._plot_events() - P.legend(("Time","Events")) + pl.legend(("Time","Events")) - P.grid() - P.show() + pl.grid() + pl.show() def plot_cumulative_time_elapsed(self, log_scale=False): - cumulative_sum = N.cumsum(self.real_time) + cumulative_sum = np.cumsum(self.real_time) if log_scale: - P.semilogy(self.simulated_time, cumulative_sum) + pl.semilogy(self.simulated_time, cumulative_sum) else: - P.plot(self.simulated_time, cumulative_sum) - P.xlabel("Time [s]") - P.ylabel("Real Time [s]") + pl.plot(self.simulated_time, cumulative_sum) + pl.xlabel("Time [s]") + pl.ylabel("Real Time [s]") self._plot_events() - P.legend(("Time","Events")) + pl.legend(("Time","Events")) - P.grid() - P.show() + pl.grid() + pl.show() def plot_step_size(self): - P.semilogy(self.simulated_time,N.diff([0.0]+self.simulated_time),drawstyle="steps-pre") - P.ylabel("Step-size") - P.xlabel("Time [s]") - P.title("Step-size history") - P.grid() - P.show() + pl.semilogy(self.simulated_time,np.diff([0.0]+self.simulated_time),drawstyle="steps-pre") + pl.ylabel("Step-size") + pl.xlabel("Time [s]") + pl.title("Step-size history") + pl.grid() + pl.show() def _plot_events(self): for ev in self.events: - P.axvline(x=ev,color='r') + pl.axvline(x=ev,color='r') def plot_event_indicators(self, mask=None, region=None): - ev_ind = N.array(self.event_indicators) - time = N.array(self.simulated_time) - ev_ind_name = N.array(["event_ind_%d"%i for i in range(len(ev_ind[0,:]))]) + ev_ind = np.array(self.event_indicators) + time = np.array(self.simulated_time) + ev_ind_name = np.array(["event_ind_%d"%i for i in range(len(ev_ind[0,:]))]) if region: lw = time > region[0] up = time < region[1] - time = time[N.logical_and(lw,up)] - ev_ind = ev_ind[N.logical_and(lw,up), :] + time = time[np.logical_and(lw,up)] + ev_ind = ev_ind[np.logical_and(lw,up), :] if mask: - P.plot(time, ev_ind[:,mask]) - P.legend(ev_ind_name[mask]) + pl.plot(time, ev_ind[:,mask]) + pl.legend(ev_ind_name[mask]) else: - P.plot(time, ev_ind) - P.legend(ev_ind_name) - P.grid() - P.xlabel("Time [s]") - P.title("Event Indicators") - P.show() + pl.plot(time, ev_ind) + pl.legend(ev_ind_name) + pl.grid() + pl.xlabel("Time [s]") + pl.title("Event Indicators") + pl.show() class ImplicitEulerDebugInformation(DebugInformation): pass @@ -157,11 +157,11 @@ def _load_data(self): self.order.append(int(row_data[2].strip())) error_data = row_data[3].strip().replace("\n","") error_data = error_data.split(" ") - self.weighted_error.append(N.array([abs(float(i)) for i in error_data])) + self.weighted_error.append(np.array([abs(float(i)) for i in error_data])) if len(row_data) > 4: event_indicators = row_data[4].strip().replace("\n","") event_indicators = event_indicators.split(" ") - self.event_indicators.append(N.array([abs(float(i)) for i in event_indicators])) + self.event_indicators.append(np.array([abs(float(i)) for i in event_indicators])) row_data = file.readline() elif row_data.startswith("Solver"): self.solver = row_data.split(" ")[-1] @@ -174,44 +174,44 @@ def _load_data(self): def plot_order(self): - P.plot(self.simulated_time, self.order,drawstyle="steps-pre") - P.grid() - P.xlabel("Time [s]") - P.ylabel("Order") - P.title("Order evolution") + pl.plot(self.simulated_time, self.order,drawstyle="steps-pre") + pl.grid() + pl.xlabel("Time [s]") + pl.ylabel("Order") + pl.title("Order evolution") self._plot_events() - P.legend(("Order","Events")) + pl.legend(("Order","Events")) - P.show() + pl.show() def plot_error(self, threshold=None, region=None, legend=True): - err = N.array(self.weighted_error) - time = N.array(self.simulated_time) + err = np.array(self.weighted_error) + time = np.array(self.simulated_time) if region: lw = time > region[0] up = time < region[1] - time = time[N.logical_and(lw,up)] - err = err[N.logical_and(lw,up), :] + time = time[np.logical_and(lw,up)] + err = err[np.logical_and(lw,up), :] if threshold: time_points, nbr_vars = err.shape - mask = N.ones(nbr_vars,dtype=bool) + mask = np.ones(nbr_vars,dtype=bool) for i in range(nbr_vars): - if N.max(err[:,i]) < threshold: + if np.max(err[:,i]) < threshold: mask[i] = False - P.semilogy(time, err[:,mask]) + pl.semilogy(time, err[:,mask]) if legend: - P.legend(N.array(self.state_variables)[mask],loc="lower right") + pl.legend(np.array(self.state_variables)[mask],loc="lower right") else: - P.semilogy(time, err) + pl.semilogy(time, err) if legend: - P.legend(self.state_variables, loc="lower right") - P.xlabel("Time [s]") - P.ylabel("Error") - P.title("Error evolution") - P.grid() - P.show() + pl.legend(self.state_variables, loc="lower right") + pl.xlabel("Time [s]") + pl.ylabel("Error") + pl.title("Error evolution") + pl.grid() + pl.show() class Radau5ODEDebugInformation(CVodeDebugInformation): pass diff --git a/src/pyfmi/examples/fmi20_bouncing_ball_native.py b/src/pyfmi/examples/fmi20_bouncing_ball_native.py index 9911313f..22fc59fc 100644 --- a/src/pyfmi/examples/fmi20_bouncing_ball_native.py +++ b/src/pyfmi/examples/fmi20_bouncing_ball_native.py @@ -16,8 +16,8 @@ # along with this program. If not, see . import os -import pylab as P -import numpy as N +import pylab as pl +import numpy as np from pyfmi import load_fmu @@ -155,18 +155,18 @@ def run_demo(with_plots=True): #Plot the solution if with_plots: #Plot the height - P.figure(1) - P.plot(t_sol,N.array(sol)[:,0]) - P.title(bouncing_fmu.get_name()) - P.ylabel('Height (m)') - P.xlabel('Time (s)') + pl.figure(1) + pl.plot(t_sol,np.array(sol)[:,0]) + pl.title(bouncing_fmu.get_name()) + pl.ylabel('Height (m)') + pl.xlabel('Time (s)') #Plot the velocity - P.figure(2) - P.plot(t_sol,N.array(sol)[:,1]) - P.title(bouncing_fmu.get_name()) - P.ylabel('Velocity (m/s)') - P.xlabel('Time (s)') - P.show() + pl.figure(2) + pl.plot(t_sol,np.array(sol)[:,1]) + pl.title(bouncing_fmu.get_name()) + pl.ylabel('Velocity (m/s)') + pl.xlabel('Time (s)') + pl.show() if __name__ == "__main__": run_demo() diff --git a/src/pyfmi/examples/fmi_bouncing_ball.py b/src/pyfmi/examples/fmi_bouncing_ball.py index f15b080c..d7b4b658 100644 --- a/src/pyfmi/examples/fmi_bouncing_ball.py +++ b/src/pyfmi/examples/fmi_bouncing_ball.py @@ -16,8 +16,8 @@ # along with this program. If not, see . import os -import pylab as P -import numpy as N +import pylab as pl +import numpy as np from pyfmi import load_fmu @@ -44,24 +44,24 @@ def run_demo(with_plots=True, version="2.0"): v_res = res['v'] t = res['time'] - assert N.abs(res.final('h') - (0.0424044)) < 1e-4 + assert np.abs(res.final('h') - (0.0424044)) < 1e-4 # Plot the solution if with_plots: # Plot the height - P.figure() - P.clf() - P.subplot(2,1,1) - P.plot(t, h_res) - P.ylabel('Height (m)') - P.xlabel('Time (s)') + pl.figure() + pl.clf() + pl.subplot(2,1,1) + pl.plot(t, h_res) + pl.ylabel('Height (m)') + pl.xlabel('Time (s)') # Plot the velocity - P.subplot(2,1,2) - P.plot(t, v_res) - P.ylabel('Velocity (m/s)') - P.xlabel('Time (s)') - P.suptitle('FMI Bouncing Ball') - P.show() + pl.subplot(2,1,2) + pl.plot(t, v_res) + pl.ylabel('Velocity (m/s)') + pl.xlabel('Time (s)') + pl.suptitle('FMI Bouncing Ball') + pl.show() if __name__ == "__main__": diff --git a/src/pyfmi/examples/fmi_bouncing_ball_cs.py b/src/pyfmi/examples/fmi_bouncing_ball_cs.py index c3e8785c..5008adbc 100644 --- a/src/pyfmi/examples/fmi_bouncing_ball_cs.py +++ b/src/pyfmi/examples/fmi_bouncing_ball_cs.py @@ -16,8 +16,8 @@ # along with this program. If not, see . import os -import pylab as P -import numpy as N +import pylab as pl +import numpy as np from pyfmi import load_fmu @@ -44,24 +44,24 @@ def run_demo(with_plots=True, version='2.0'): v_res = res['v'] t = res['time'] - assert N.abs(res.final('h') - (0.0424044)) < 1e-2 + assert np.abs(res.final('h') - (0.0424044)) < 1e-2 # Plot the solution if with_plots: # Plot the height - P.figure() - P.clf() - P.subplot(2,1,1) - P.plot(t, h_res) - P.ylabel('Height (m)') - P.xlabel('Time (s)') + pl.figure() + pl.clf() + pl.subplot(2,1,1) + pl.plot(t, h_res) + pl.ylabel('Height (m)') + pl.xlabel('Time (s)') # Plot the velocity - P.subplot(2,1,2) - P.plot(t, v_res) - P.ylabel('Velocity (m/s)') - P.xlabel('Time (s)') - P.suptitle('FMI Bouncing Ball') - P.show() + pl.subplot(2,1,2) + pl.plot(t, v_res) + pl.ylabel('Velocity (m/s)') + pl.xlabel('Time (s)') + pl.suptitle('FMI Bouncing Ball') + pl.show() if __name__ == "__main__": diff --git a/src/pyfmi/examples/fmi_bouncing_ball_native.py b/src/pyfmi/examples/fmi_bouncing_ball_native.py index bf747260..b1dd78ef 100644 --- a/src/pyfmi/examples/fmi_bouncing_ball_native.py +++ b/src/pyfmi/examples/fmi_bouncing_ball_native.py @@ -16,8 +16,8 @@ # along with this program. If not, see . import os -import pylab as P -import numpy as N +import pylab as pl +import numpy as np from pyfmi import load_fmu @@ -144,18 +144,18 @@ def run_demo(with_plots=True): #Plot the solution if with_plots: #Plot the height - P.figure(1) - P.plot(t_sol,N.array(sol)[:,0]) - P.title(bouncing_fmu.get_name()) - P.ylabel('Height (m)') - P.xlabel('Time (s)') + pl.figure(1) + pl.plot(t_sol,np.array(sol)[:,0]) + pl.title(bouncing_fmu.get_name()) + pl.ylabel('Height (m)') + pl.xlabel('Time (s)') #Plot the velocity - P.figure(2) - P.plot(t_sol,N.array(sol)[:,1]) - P.title(bouncing_fmu.get_name()) - P.ylabel('Velocity (m/s)') - P.xlabel('Time (s)') - P.show() + pl.figure(2) + pl.plot(t_sol,np.array(sol)[:,1]) + pl.title(bouncing_fmu.get_name()) + pl.ylabel('Velocity (m/s)') + pl.xlabel('Time (s)') + pl.show() if __name__ == "__main__": run_demo() diff --git a/src/pyfmi/examples/fmu_with_input.py b/src/pyfmi/examples/fmu_with_input.py index 177b60d0..985233f5 100644 --- a/src/pyfmi/examples/fmu_with_input.py +++ b/src/pyfmi/examples/fmu_with_input.py @@ -16,8 +16,8 @@ # along with this program. If not, see . import os -import numpy as N -import pylab as p +import numpy as np +import pylab as pl from pyfmi import load_fmu @@ -35,9 +35,9 @@ def run_demo(with_plots=True): fmu_name = os.path.join(path_to_fmus_me1,'SecondOrder.fmu') # Generate input - t = N.linspace(0.,10.,100) - u = N.cos(t) - u_traj = N.transpose(N.vstack((t,u))) + t = np.linspace(0.,10.,100) + u = np.cos(t) + u_traj = np.transpose(np.vstack((t,u))) # Create input object input_object = ('u', u_traj) @@ -56,17 +56,17 @@ def run_demo(with_plots=True): u_sim = res['u'] time_sim = res['time'] - assert N.abs(res.final('x1')*1.e1 - (-8.3999640)) < 1e-3 - assert N.abs(res.final('x2')*1.e1 - (-5.0691179)) < 1e-3 - assert N.abs(res.final('u')*1.e1 - (-8.3907153)) < 1e-3 + assert np.abs(res.final('x1')*1.e1 - (-8.3999640)) < 1e-3 + assert np.abs(res.final('x2')*1.e1 - (-5.0691179)) < 1e-3 + assert np.abs(res.final('u')*1.e1 - (-8.3907153)) < 1e-3 if with_plots: - p.figure() - p.subplot(2,1,1) - p.plot(time_sim, x1_sim, time_sim, x2_sim) - p.subplot(2,1,2) - p.plot(time_sim, u_sim,'x-',t, u[:],'x-') - p.show() + pl.figure() + pl.subplot(2,1,1) + pl.plot(time_sim, x1_sim, time_sim, x2_sim) + pl.subplot(2,1,2) + pl.plot(time_sim, u_sim,'x-',t, u[:],'x-') + pl.show() if __name__=="__main__": run_demo() diff --git a/src/pyfmi/examples/fmu_with_input_function.py b/src/pyfmi/examples/fmu_with_input_function.py index e0abaaa9..2e4c42f5 100644 --- a/src/pyfmi/examples/fmu_with_input_function.py +++ b/src/pyfmi/examples/fmu_with_input_function.py @@ -16,8 +16,8 @@ # along with this program. If not, see . import os -import numpy as N -import pylab as p +import numpy as np +import pylab as pl from pyfmi import load_fmu @@ -35,7 +35,7 @@ def run_demo(with_plots=True): fmu_name = os.path.join(path_to_fmus_me1,'SecondOrder.fmu') # Create input object - input_object = ('u', N.cos) + input_object = ('u', np.cos) # Load the dynamic library and XML data model = load_fmu(fmu_name) @@ -48,17 +48,17 @@ def run_demo(with_plots=True): u_sim = res['u'] time_sim = res['time'] - assert N.abs(res.final('x1') - (-1.646485144)) < 1e-3 - assert N.abs(res.final('x2')*1.e1 - (-7.30591626709)) < 1e-3 - assert N.abs(res.final('u')*1.e1 - (1.54251449888)) < 1e-3 + assert np.abs(res.final('x1') - (-1.646485144)) < 1e-3 + assert np.abs(res.final('x2')*1.e1 - (-7.30591626709)) < 1e-3 + assert np.abs(res.final('u')*1.e1 - (1.54251449888)) < 1e-3 if with_plots: - p.figure() - p.subplot(2,1,1) - p.plot(time_sim, x1_sim, time_sim, x2_sim) - p.subplot(2,1,2) - p.plot(time_sim, u_sim) - p.show() + pl.figure() + pl.subplot(2,1,1) + pl.plot(time_sim, x1_sim, time_sim, x2_sim) + pl.subplot(2,1,2) + pl.plot(time_sim, u_sim) + pl.show() if __name__=="__main__": run_demo() diff --git a/src/pyfmi/fmi.pxd b/src/pyfmi/fmi.pxd index ad27c383..b110a24c 100644 --- a/src/pyfmi/fmi.pxd +++ b/src/pyfmi/fmi.pxd @@ -17,8 +17,8 @@ """ Module containing the FMI interface Python wrappers. """ -import numpy as N -cimport numpy as N +import numpy as np +cimport numpy as np cimport pyfmi.fmil_import as FMIL @@ -219,9 +219,9 @@ cdef class FMUModelBase2(ModelBase): cpdef serialized_fmu_state_size(self, state) cdef _add_scalar_variables(self, FMIL.fmi2_import_variable_list_t* variable_list) cdef _add_scalar_variable(self, FMIL.fmi2_import_variable_t* variable) - cdef int _get_directional_derivative(self, N.ndarray v_ref, N.ndarray z_ref, N.ndarray dv, N.ndarray dz) except -1 + cdef int _get_directional_derivative(self, np.ndarray v_ref, np.ndarray z_ref, np.ndarray dv, np.ndarray dz) except -1 cpdef set_real(self, valueref, values) - cpdef N.ndarray get_real(self, valueref) + cpdef np.ndarray get_real(self, valueref) cdef int _set_real(self, FMIL.fmi2_value_reference_t* vrefs, FMIL.fmi2_real_t* values, size_t _size) cdef int _get_real_by_ptr(self, FMIL.fmi2_value_reference_t* vrefs, size_t _size, FMIL.fmi2_real_t* values) cdef int _get_real_by_list(self, FMIL.fmi2_value_reference_t[:] valueref, size_t _size, FMIL.fmi2_real_t[:] values) @@ -233,8 +233,8 @@ cdef class FMUModelCS2(FMUModelBase2): cpdef _get_time(self) cpdef _set_time(self, FMIL.fmi2_real_t t) cpdef int do_step(self, FMIL.fmi2_real_t current_t, FMIL.fmi2_real_t step_size, new_step=*) - cdef int _set_input_derivatives(self, N.ndarray value_refs, N.ndarray values, N.ndarray orders) - cdef int _get_output_derivatives(self, N.ndarray value_refs, N.ndarray values, N.ndarray orders) + cdef int _set_input_derivatives(self, np.ndarray value_refs, np.ndarray values, np.ndarray orders) + cdef int _get_output_derivatives(self, np.ndarray value_refs, np.ndarray values, np.ndarray orders) cdef class FMUModelME2(FMUModelBase2): @@ -253,11 +253,11 @@ cdef class FMUModelME2(FMUModelBase2): cdef class WorkerClass2: cdef int _dim - cdef N.ndarray _tmp1_val, _tmp2_val, _tmp3_val, _tmp4_val - cdef N.ndarray _tmp1_ref, _tmp2_ref, _tmp3_ref, _tmp4_ref + cdef np.ndarray _tmp1_val, _tmp2_val, _tmp3_val, _tmp4_val + cdef np.ndarray _tmp1_ref, _tmp2_ref, _tmp3_ref, _tmp4_ref cdef FMIL.fmi2_real_t* get_real_vector(self, int index) cdef FMIL.fmi2_value_reference_t* get_value_reference_vector(self, int index) - cdef N.ndarray get_value_reference_numpy_vector(self, int index) - cdef N.ndarray get_real_numpy_vector(self, int index) + cdef np.ndarray get_value_reference_numpy_vector(self, int index) + cdef np.ndarray get_real_numpy_vector(self, int index) cpdef verify_dimensions(self, int dim) diff --git a/src/pyfmi/fmi.pyx b/src/pyfmi/fmi.pyx index bc29d43e..13263331 100644 --- a/src/pyfmi/fmi.pyx +++ b/src/pyfmi/fmi.pyx @@ -34,9 +34,9 @@ from collections import OrderedDict cimport cython from io import UnsupportedOperation -import scipy.sparse as sp -import numpy as N -cimport numpy as N +import scipy.sparse as sps +import numpy as np +cimport numpy as np from numpy cimport PyArray_DATA cimport pyfmi.fmil_import as FMIL @@ -46,8 +46,8 @@ from pyfmi.common.core import create_temp_dir from pyfmi.fmi_util import cpr_seed, enable_caching from pyfmi.fmi_util cimport encode, decode -int = N.int32 -N.int = N.int32 +int = np.int32 +np.int = np.int32 """Basic flags related to FMI""" @@ -141,8 +141,8 @@ FMI2_INITIAL_UNKNOWN = 3 DEF FORWARD_DIFFERENCE = 1 DEF CENTRAL_DIFFERENCE = 2 -FORWARD_DIFFERENCE_EPS = (N.finfo(float).eps)**0.5 -CENTRAL_DIFFERENCE_EPS = (N.finfo(float).eps)**(1/3.0) +FORWARD_DIFFERENCE_EPS = (np.finfo(float).eps)**0.5 +CENTRAL_DIFFERENCE_EPS = (np.finfo(float).eps)**(1/3.0) """Flags for evaluation of FMI Jacobians""" """Evaluate Jacobian w.r.t. states.""" @@ -1156,7 +1156,7 @@ cdef class IntegerType2(DeclaredType2): """ Class defining data structure based on the XML element Enumeration. """ - def __init__(self, name, description = "", quantity = "", min = -N.inf, max = N.inf): + def __init__(self, name, description = "", quantity = "", min = -np.inf, max = np.inf): DeclaredType2.__init__(self, name, description, quantity) self._min = min @@ -1188,7 +1188,7 @@ cdef class RealType2(DeclaredType2): """ Class defining data structure based on the XML element Enumeration. """ - def __init__(self, name, description = "", quantity = "", min = -N.inf, max = N.inf, nominal = 1.0, unbounded = False, + def __init__(self, name, description = "", quantity = "", min = -np.inf, max = np.inf, nominal = 1.0, unbounded = False, relative_quantity = False, display_unit = "", unit = ""): DeclaredType2.__init__(self, name, description, quantity) @@ -1542,9 +1542,9 @@ cdef class FMUModelBase(ModelBase): Calls the low-level FMI function: fmiGetReal """ cdef int status - cdef N.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] val_ref = N.array(valueref, copy=False, dtype=N.uint32).ravel() - cdef FMIL.size_t nref = N.size(val_ref) - cdef N.ndarray[FMIL.fmi1_real_t, ndim=1,mode='c'] val = N.array([0.0]*nref, dtype=float, ndmin=1) + cdef np.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] val_ref = np.array(valueref, copy=False, dtype=np.uint32).ravel() + cdef FMIL.size_t nref = np.size(val_ref) + cdef np.ndarray[FMIL.fmi1_real_t, ndim=1,mode='c'] val = np.array([0.0]*nref, dtype=float, ndmin=1) if nref == 0: ## get_real([]) return val @@ -1575,11 +1575,11 @@ cdef class FMUModelBase(ModelBase): Calls the low-level FMI function: fmiSetReal """ cdef int status - cdef N.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] val_ref = N.array(valueref, copy=False, dtype=N.uint32).ravel() - cdef N.ndarray[FMIL.fmi1_real_t, ndim=1,mode='c'] val = N.array(values, copy=False, dtype=float).ravel() - cdef FMIL.size_t nref = N.size(val_ref) + cdef np.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] val_ref = np.array(valueref, copy=False, dtype=np.uint32).ravel() + cdef np.ndarray[FMIL.fmi1_real_t, ndim=1,mode='c'] val = np.array(values, copy=False, dtype=float).ravel() + cdef FMIL.size_t nref = np.size(val_ref) - if nref != N.size(val): + if nref != np.size(val): raise FMUException( 'The length of valueref and values are inconsistent.') @@ -1609,9 +1609,9 @@ cdef class FMUModelBase(ModelBase): Calls the low-level FMI function: fmiGetInteger """ cdef int status - cdef N.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] val_ref = N.array(valueref, dtype=N.uint32,ndmin=1).ravel() - cdef FMIL.size_t nref = N.size(val_ref) - cdef N.ndarray[FMIL.fmi1_integer_t, ndim=1,mode='c'] val = N.array([0]*nref, dtype=int,ndmin=1) + cdef np.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] val_ref = np.array(valueref, dtype=np.uint32,ndmin=1).ravel() + cdef FMIL.size_t nref = np.size(val_ref) + cdef np.ndarray[FMIL.fmi1_integer_t, ndim=1,mode='c'] val = np.array([0]*nref, dtype=int,ndmin=1) if nref == 0: ## get_integer([]) return val @@ -1642,11 +1642,11 @@ cdef class FMUModelBase(ModelBase): Calls the low-level FMI function: fmiSetInteger """ cdef int status - cdef N.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] val_ref = N.array(valueref, dtype=N.uint32,ndmin=1).ravel() - cdef N.ndarray[FMIL.fmi1_integer_t, ndim=1,mode='c'] val = N.array(values, dtype=int,ndmin=1).ravel() - cdef FMIL.size_t nref = N.size(val_ref) + cdef np.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] val_ref = np.array(valueref, dtype=np.uint32,ndmin=1).ravel() + cdef np.ndarray[FMIL.fmi1_integer_t, ndim=1,mode='c'] val = np.array(values, dtype=int,ndmin=1).ravel() + cdef FMIL.size_t nref = np.size(val_ref) - if nref != N.size(val): + if nref != np.size(val): raise FMUException( 'The length of valueref and values are inconsistent.') @@ -1677,11 +1677,11 @@ cdef class FMUModelBase(ModelBase): Calls the low-level FMI function: fmiGetBoolean """ cdef int status - cdef N.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] val_ref = N.array(valueref, dtype=N.uint32,ndmin=1).ravel() - cdef FMIL.size_t nref = N.size(val_ref) + cdef np.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] val_ref = np.array(valueref, dtype=np.uint32,ndmin=1).ravel() + cdef FMIL.size_t nref = np.size(val_ref) if nref == 0: ## get_boolean([]) - return N.array([]) + return np.array([]) cdef void *val = FMIL.malloc(sizeof(FMIL.fmi1_boolean_t)*nref) @@ -1697,7 +1697,7 @@ cdef class FMUModelBase(ModelBase): if status != 0: raise FMUException('Failed to get the Boolean values.') - return N.array(return_values) + return np.array(return_values) def set_boolean(self, valueref, values): """ @@ -1718,19 +1718,19 @@ cdef class FMUModelBase(ModelBase): Calls the low-level FMI function: fmiSetBoolean """ cdef int status - cdef N.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] val_ref = N.array(valueref, dtype=N.uint32,ndmin=1).ravel() - cdef FMIL.size_t nref = N.size(val_ref) + cdef np.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] val_ref = np.array(valueref, dtype=np.uint32,ndmin=1).ravel() + cdef FMIL.size_t nref = np.size(val_ref) cdef void *val = FMIL.malloc(sizeof(FMIL.fmi1_boolean_t)*nref) - values = N.array(values,ndmin=1).ravel() + values = np.array(values,ndmin=1).ravel() for i in range(nref): if values[i]: (val)[i] = 1 else: (val)[i] = 0 - if nref != N.size(values): + if nref != np.size(values): raise FMUException( 'The length of valueref and values are inconsistent.') @@ -1762,8 +1762,8 @@ cdef class FMUModelBase(ModelBase): Calls the low-level FMI function: fmiGetString """ cdef int status - cdef N.ndarray[FMIL.fmi1_value_reference_t, ndim=1, mode='c'] input_valueref = N.array(valueref, dtype=N.uint32, ndmin=1).ravel() - cdef FMIL.size_t nref = N.size(input_valueref) + cdef np.ndarray[FMIL.fmi1_value_reference_t, ndim=1, mode='c'] input_valueref = np.array(valueref, dtype=np.uint32, ndmin=1).ravel() + cdef FMIL.size_t nref = np.size(input_valueref) if nref == 0: ## get_string([]) return [] @@ -1801,21 +1801,21 @@ cdef class FMUModelBase(ModelBase): Calls the low-level FMI function: fmiSetString """ cdef int status - cdef N.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] val_ref = N.array(valueref, dtype=N.uint32,ndmin=1).ravel() - cdef FMIL.fmi1_string_t* val = FMIL.malloc(sizeof(FMIL.fmi1_string_t)*N.size(val_ref)) + cdef np.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] val_ref = np.array(valueref, dtype=np.uint32,ndmin=1).ravel() + cdef FMIL.fmi1_string_t* val = FMIL.malloc(sizeof(FMIL.fmi1_string_t)*np.size(val_ref)) if not isinstance(values, list): raise FMUException( 'The values needs to be a list of values.') - if len(values) != N.size(val_ref): + if len(values) != np.size(val_ref): raise FMUException( 'The length of valueref and values are inconsistent.') values = [encode(item) for item in values] - for i in range(N.size(val_ref)): + for i in range(np.size(val_ref)): val[i] = values[i] - status = FMIL.fmi1_import_set_string(self._fmu, val_ref.data, N.size(val_ref), val) + status = FMIL.fmi1_import_set_string(self._fmu, val_ref.data, np.size(val_ref), val) FMIL.free(val) @@ -2886,9 +2886,9 @@ cdef class FMUModelCS1(FMUModelBase): cdef int status cdef unsigned int max_output_derivative cdef FMIL.size_t nref - cdef N.ndarray[FMIL.fmi1_real_t, ndim=1,mode='c'] values - cdef N.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] value_refs - cdef N.ndarray[FMIL.fmi1_integer_t, ndim=1,mode='c'] orders + cdef np.ndarray[FMIL.fmi1_real_t, ndim=1,mode='c'] values + cdef np.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] value_refs + cdef np.ndarray[FMIL.fmi1_integer_t, ndim=1,mode='c'] orders cdef FMIL.fmi1_import_capabilities_t *fmu_capabilities fmu_capabilities = FMIL.fmi1_import_get_capabilities(self._fmu) @@ -2899,20 +2899,20 @@ cdef class FMUModelCS1(FMUModelBase): if isinstance(variables,str): nref = 1 - value_refs = N.array([0], dtype=N.uint32,ndmin=1).ravel() - orders = N.array(order, dtype=N.int32) + value_refs = np.array([0], dtype=np.uint32,ndmin=1).ravel() + orders = np.array(order, dtype=np.int32) value_refs[0] = self.get_variable_valueref(variables) elif isinstance(variables,list) and isinstance(variables[-1],str): nref = len(variables) - value_refs = N.array([0]*nref, dtype=N.uint32,ndmin=1).ravel() - orders = N.array([0]*nref, dtype=N.int32) + value_refs = np.array([0]*nref, dtype=np.uint32,ndmin=1).ravel() + orders = np.array([0]*nref, dtype=np.int32) for i in range(nref): value_refs[i] = self.get_variable_valueref(variables[i]) orders[i] = order else: raise FMUException("The variables must either be a string or a list of strings") - values = N.array([0.0]*nref,dtype=float, ndmin=1) + values = np.array([0.0]*nref,dtype=float, ndmin=1) status = FMIL.fmi1_import_get_real_output_derivatives(self._fmu, value_refs.data, nref, orders.data, values.data) @@ -2974,30 +2974,30 @@ cdef class FMUModelCS1(FMUModelBase): cdef int status cdef int can_interpolate_inputs cdef FMIL.fmi1_import_capabilities_t *fmu_capabilities - cdef N.ndarray[FMIL.fmi1_integer_t, ndim=1,mode='c'] np_orders = N.array(orders, dtype=N.int32, ndmin=1).ravel() - cdef N.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] value_refs - cdef N.ndarray[FMIL.fmi1_real_t, ndim=1,mode='c'] val = N.array(values, dtype=float, ndmin=1).ravel() - cdef FMIL.size_t nref = N.size(val) - orders = N.array([0]*nref, dtype=N.int32) + cdef np.ndarray[FMIL.fmi1_integer_t, ndim=1,mode='c'] np_orders = np.array(orders, dtype=np.int32, ndmin=1).ravel() + cdef np.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] value_refs + cdef np.ndarray[FMIL.fmi1_real_t, ndim=1,mode='c'] val = np.array(values, dtype=float, ndmin=1).ravel() + cdef FMIL.size_t nref = np.size(val) + orders = np.array([0]*nref, dtype=np.int32) - if nref != N.size(np_orders): + if nref != np.size(np_orders): raise FMUException("The number of variables must be the same as the number of orders.") fmu_capabilities = FMIL.fmi1_import_get_capabilities(self._fmu) can_interpolate_inputs = FMIL.fmi1_import_get_canInterpolateInputs(fmu_capabilities) #NOTE IS THIS THE HIGHEST ORDER OF INTERPOLATION OR SIMPLY IF IT CAN OR NOT? - for i in range(N.size(np_orders)): + for i in range(np.size(np_orders)): if np_orders[i] < 1: raise FMUException("The order must be greater than zero.") if not can_interpolate_inputs: raise FMUException("The FMU does not support input derivatives.") if isinstance(variables,str): - value_refs = N.array([0], dtype=N.uint32,ndmin=1).ravel() + value_refs = np.array([0], dtype=np.uint32,ndmin=1).ravel() value_refs[0] = self.get_variable_valueref(variables) elif isinstance(variables,list) and isinstance(variables[-1],str): - value_refs = N.array([0]*nref, dtype=N.uint32,ndmin=1).ravel() + value_refs = np.array([0]*nref, dtype=np.uint32,ndmin=1).ravel() for i in range(nref): value_refs[i] = self.get_variable_valueref(variables[i]) else: @@ -3402,7 +3402,7 @@ cdef class FMUModelME1(FMUModelBase): def _get_continuous_states(self): cdef int status - cdef N.ndarray[double, ndim=1,mode='c'] ndx = N.zeros(self._nContinuousStates, dtype=N.double) + cdef np.ndarray[double, ndim=1,mode='c'] ndx = np.zeros(self._nContinuousStates, dtype=np.double) status = FMIL.fmi1_import_get_continuous_states(self._fmu, ndx.data ,self._nContinuousStates) if status != 0: @@ -3410,11 +3410,11 @@ cdef class FMUModelME1(FMUModelBase): return ndx - def _set_continuous_states(self, N.ndarray[FMIL.fmi1_real_t] values): + def _set_continuous_states(self, np.ndarray[FMIL.fmi1_real_t] values): cdef int status - cdef N.ndarray[FMIL.fmi1_real_t, ndim=1,mode='c'] ndx = values + cdef np.ndarray[FMIL.fmi1_real_t, ndim=1,mode='c'] ndx = values - if N.size(ndx) != self._nContinuousStates: + if np.size(ndx) != self._nContinuousStates: raise FMUException( 'Failed to set the new continuous states. ' \ 'The number of values are not consistent with the number of '\ @@ -3444,7 +3444,7 @@ cdef class FMUModelME1(FMUModelBase): The nominal values. """ cdef int status - cdef N.ndarray[FMIL.fmi1_real_t, ndim=1, mode='c'] xn = N.zeros(self._nContinuousStates, dtype=N.double) + cdef np.ndarray[FMIL.fmi1_real_t, ndim=1, mode='c'] xn = np.zeros(self._nContinuousStates, dtype=np.double) status = self._get_nominal_continuous_states_fmil( xn.data, self._nContinuousStates) if status != 0: @@ -3494,7 +3494,7 @@ cdef class FMUModelME1(FMUModelBase): Calls the low-level FMI function: fmiGetDerivatives """ cdef int status - cdef N.ndarray[FMIL.fmi1_real_t, ndim=1,mode='c'] values = N.empty(self._nContinuousStates,dtype=N.double) + cdef np.ndarray[FMIL.fmi1_real_t, ndim=1,mode='c'] values = np.empty(self._nContinuousStates,dtype=np.double) if self._nContinuousStates > 0: status = FMIL.fmi1_import_get_derivatives(self._fmu, values.data, self._nContinuousStates) @@ -3522,7 +3522,7 @@ cdef class FMUModelME1(FMUModelBase): Calls the low-level FMI function: fmiGetEventIndicators """ cdef int status - cdef N.ndarray[FMIL.fmi1_real_t, ndim=1,mode='c'] values = N.empty(self._nEventIndicators,dtype=N.double) + cdef np.ndarray[FMIL.fmi1_real_t, ndim=1,mode='c'] values = np.empty(self._nEventIndicators,dtype=np.double) status = FMIL.fmi1_import_get_event_indicators(self._fmu, values.data, self._nEventIndicators) @@ -3679,7 +3679,7 @@ cdef class FMUModelME1(FMUModelBase): Calls the low-level FMI function: fmiGetStateValueReferences """ cdef int status - cdef N.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] values = N.zeros(self._nContinuousStates,dtype=N.uint32) + cdef np.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] values = np.zeros(self._nContinuousStates,dtype=np.uint32) status = FMIL.fmi1_import_get_state_value_references( self._fmu, values.data, self._nContinuousStates) @@ -4166,7 +4166,7 @@ cdef class FMUModelBase2(ModelBase): self._log = [] - cpdef N.ndarray get_real(self, valueref): + cpdef np.ndarray get_real(self, valueref): """ Returns the real-values from the valuereference(s). @@ -4187,9 +4187,9 @@ cdef class FMUModelBase2(ModelBase): Calls the low-level FMI function: fmi2GetReal """ cdef int status - cdef N.ndarray[FMIL.fmi2_value_reference_t, ndim=1,mode='c'] input_valueref = N.array(valueref, copy=False, dtype=N.uint32).ravel() - cdef FMIL.size_t nref = N.size(input_valueref) - cdef N.ndarray[FMIL.fmi2_real_t, ndim=1,mode='c'] output_value = N.zeros(nref) + cdef np.ndarray[FMIL.fmi2_value_reference_t, ndim=1,mode='c'] input_valueref = np.array(valueref, copy=False, dtype=np.uint32).ravel() + cdef FMIL.size_t nref = np.size(input_valueref) + cdef np.ndarray[FMIL.fmi2_real_t, ndim=1,mode='c'] output_value = np.zeros(nref) if nref == 0: ## get_real([]) return output_value @@ -4221,13 +4221,13 @@ cdef class FMUModelBase2(ModelBase): """ cdef int status - cdef N.ndarray[FMIL.fmi2_value_reference_t, ndim=1,mode='c'] input_valueref = N.array(valueref, copy=False, dtype=N.uint32).ravel() - cdef N.ndarray[FMIL.fmi2_real_t, ndim=1,mode='c'] set_value = N.array(values, copy=False, dtype=float).ravel() + cdef np.ndarray[FMIL.fmi2_value_reference_t, ndim=1,mode='c'] input_valueref = np.array(valueref, copy=False, dtype=np.uint32).ravel() + cdef np.ndarray[FMIL.fmi2_real_t, ndim=1,mode='c'] set_value = np.array(values, copy=False, dtype=float).ravel() - if N.size(input_valueref) != N.size(set_value): + if np.size(input_valueref) != np.size(set_value): raise FMUException('The length of valueref and values are inconsistent.') - status = FMIL.fmi2_import_set_real(self._fmu, input_valueref.data, N.size(input_valueref), set_value.data) + status = FMIL.fmi2_import_set_real(self._fmu, input_valueref.data, np.size(input_valueref), set_value.data) if status != 0: raise FMUException('Failed to set the Real values. See the log for possibly more information.') @@ -4265,9 +4265,9 @@ cdef class FMUModelBase2(ModelBase): Calls the low-level FMI function: fmi2GetInteger """ cdef int status - cdef N.ndarray[FMIL.fmi2_value_reference_t, ndim=1,mode='c'] input_valueref = N.array(valueref, dtype=N.uint32,ndmin=1).ravel() - cdef FMIL.size_t nref = N.size(input_valueref) - cdef N.ndarray[FMIL.fmi2_integer_t, ndim=1,mode='c'] output_value = N.zeros(nref, dtype=int) + cdef np.ndarray[FMIL.fmi2_value_reference_t, ndim=1,mode='c'] input_valueref = np.array(valueref, dtype=np.uint32,ndmin=1).ravel() + cdef FMIL.size_t nref = np.size(input_valueref) + cdef np.ndarray[FMIL.fmi2_integer_t, ndim=1,mode='c'] output_value = np.zeros(nref, dtype=int) if nref == 0: ## get_integer([]) return output_value @@ -4298,11 +4298,11 @@ cdef class FMUModelBase2(ModelBase): Calls the low-level FMI function: fmi2SetInteger """ cdef int status - cdef N.ndarray[FMIL.fmi2_value_reference_t, ndim=1,mode='c'] input_valueref = N.array(valueref, dtype=N.uint32,ndmin=1).ravel() - cdef N.ndarray[FMIL.fmi2_integer_t, ndim=1,mode='c'] set_value = N.array(values, dtype=int,ndmin=1).ravel() - cdef FMIL.size_t nref = N.size(input_valueref) + cdef np.ndarray[FMIL.fmi2_value_reference_t, ndim=1,mode='c'] input_valueref = np.array(valueref, dtype=np.uint32,ndmin=1).ravel() + cdef np.ndarray[FMIL.fmi2_integer_t, ndim=1,mode='c'] set_value = np.array(values, dtype=int,ndmin=1).ravel() + cdef FMIL.size_t nref = np.size(input_valueref) - if nref != N.size(set_value): + if nref != np.size(set_value): raise FMUException('The length of valueref and values are inconsistent.') status = FMIL.fmi2_import_set_integer(self._fmu, input_valueref.data, nref, set_value.data) @@ -4344,11 +4344,11 @@ cdef class FMUModelBase2(ModelBase): Calls the low-level FMI function: fmi2GetBoolean """ cdef int status - cdef N.ndarray[FMIL.fmi2_value_reference_t, ndim=1,mode='c'] input_valueref = N.array(valueref, dtype=N.uint32, ndmin=1).ravel() - cdef FMIL.size_t nref = N.size(input_valueref) + cdef np.ndarray[FMIL.fmi2_value_reference_t, ndim=1,mode='c'] input_valueref = np.array(valueref, dtype=np.uint32, ndmin=1).ravel() + cdef FMIL.size_t nref = np.size(input_valueref) if nref == 0: ## get_boolean([]) - return N.array([]) + return np.array([]) cdef void* output_value = FMIL.malloc(sizeof(FMIL.fmi2_boolean_t)*nref) @@ -4364,7 +4364,7 @@ cdef class FMUModelBase2(ModelBase): if status != 0: raise FMUException('Failed to get the Boolean values.') - return N.array(return_values) + return np.array(return_values) def set_boolean(self, valueref, values): """ @@ -4386,12 +4386,12 @@ cdef class FMUModelBase2(ModelBase): """ cdef int status - cdef N.ndarray[FMIL.fmi2_value_reference_t, ndim=1,mode='c'] input_valueref = N.array(valueref, dtype=N.uint32,ndmin=1).flatten() - cdef FMIL.size_t nref = N.size(input_valueref) + cdef np.ndarray[FMIL.fmi2_value_reference_t, ndim=1,mode='c'] input_valueref = np.array(valueref, dtype=np.uint32,ndmin=1).flatten() + cdef FMIL.size_t nref = np.size(input_valueref) cdef void* set_value = FMIL.malloc(sizeof(FMIL.fmi2_boolean_t)*nref) - values = N.array(values,ndmin=1).ravel() + values = np.array(values,ndmin=1).ravel() for i in range(nref): if values[i]: ( set_value)[i] = 1 @@ -4429,8 +4429,8 @@ cdef class FMUModelBase2(ModelBase): Calls the low-level FMI function: fmi2GetString """ cdef int status - cdef N.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode='c'] input_valueref = N.array(valueref, dtype=N.uint32, ndmin=1).ravel() - cdef FMIL.size_t nref = N.size(input_valueref) + cdef np.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode='c'] input_valueref = np.array(valueref, dtype=np.uint32, ndmin=1).ravel() + cdef FMIL.size_t nref = np.size(input_valueref) if nref == 0: ## get_string([]) return [] @@ -4469,21 +4469,21 @@ cdef class FMUModelBase2(ModelBase): Calls the low-level FMI function: fmi2SetString """ cdef int status - cdef N.ndarray[FMIL.fmi2_value_reference_t, ndim=1,mode='c'] val_ref = N.array(valueref, dtype=N.uint32,ndmin=1).ravel() - cdef FMIL.fmi2_string_t* val = FMIL.malloc(sizeof(FMIL.fmi2_string_t)*N.size(val_ref)) + cdef np.ndarray[FMIL.fmi2_value_reference_t, ndim=1,mode='c'] val_ref = np.array(valueref, dtype=np.uint32,ndmin=1).ravel() + cdef FMIL.fmi2_string_t* val = FMIL.malloc(sizeof(FMIL.fmi2_string_t)*np.size(val_ref)) if not isinstance(values, list): raise FMUException( 'The values needs to be a list of values.') - if len(values) != N.size(val_ref): + if len(values) != np.size(val_ref): raise FMUException( 'The length of valueref and values are inconsistent.') values = [encode(item) for item in values] - for i in range(N.size(val_ref)): + for i in range(np.size(val_ref)): val[i] = values[i] - status = FMIL.fmi2_import_set_string(self._fmu, val_ref.data, N.size(val_ref), val) + status = FMIL.fmi2_import_set_string(self._fmu, val_ref.data, np.size(val_ref), val) FMIL.free(val) @@ -6096,7 +6096,7 @@ cdef class FMUModelBase2(ModelBase): cdef FMUState2 internal_state = state cdef FMIL.size_t n_bytes - cdef N.ndarray[FMIL.fmi2_byte_t, ndim=1, mode='c'] serialized_fmu + cdef np.ndarray[FMIL.fmi2_byte_t, ndim=1, mode='c'] serialized_fmu cap1 = FMIL.fmi2_import_get_capability(self._fmu, FMIL.fmi2_me_canSerializeFMUstate) cap2 = FMIL.fmi2_import_get_capability(self._fmu, FMIL.fmi2_cs_canSerializeFMUstate) @@ -6104,7 +6104,7 @@ cdef class FMUModelBase2(ModelBase): raise FMUException('This FMU dos not support serialisation of FMU-state') n_bytes = self.serialized_fmu_state_size(state) - serialized_fmu = N.empty(n_bytes, dtype=N.byte) + serialized_fmu = np.empty(n_bytes, dtype=np.byte) status = FMIL.fmi2_import_serialize_fmu_state(self._fmu, internal_state.fmu_state, serialized_fmu.data, n_bytes) @@ -6136,7 +6136,7 @@ cdef class FMUModelBase2(ModelBase): """ cdef int status - cdef N.ndarray[FMIL.fmi2_byte_t, ndim=1, mode='c'] ser_fmu = serialized_fmu[0] + cdef np.ndarray[FMIL.fmi2_byte_t, ndim=1, mode='c'] ser_fmu = serialized_fmu[0] cdef FMUState2 state = FMUState2() cdef FMIL.size_t n_byte = len(ser_fmu) @@ -6485,8 +6485,8 @@ cdef class FMUModelBase2(ModelBase): cdef list data = [], row = [], col = [] cdef list local_group cdef int nbr_var_ref = len(var_ref), nbr_func_ref = len(func_ref) - cdef N.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] v = N.zeros(nbr_var_ref, dtype = N.double) - cdef N.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] data_local + cdef np.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] v = np.zeros(nbr_var_ref, dtype = np.double) + cdef np.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] data_local cdef int ind_local = 5 if add_diag else 4 if not self._has_entered_init_mode: @@ -6495,7 +6495,7 @@ cdef class FMUModelBase2(ModelBase): if group is not None: if output_matrix is not None: - if not isinstance(output_matrix, sp.csc_matrix): + if not isinstance(output_matrix, sps.csc_matrix): output_matrix = None else: data_local = output_matrix.data @@ -6526,16 +6526,16 @@ cdef class FMUModelBase2(ModelBase): A = output_matrix else: if len(data) == 0: - A = sp.csc_matrix((nbr_func_ref,nbr_var_ref)) + A = sps.csc_matrix((nbr_func_ref,nbr_var_ref)) else: - A = sp.csc_matrix((data, (row, col)), (nbr_func_ref,nbr_var_ref)) + A = sps.csc_matrix((data, (row, col)), (nbr_func_ref,nbr_var_ref)) return A else: if output_matrix is None or \ - (not isinstance(output_matrix, N.ndarray)) or \ - (isinstance(output_matrix, N.ndarray) and (output_matrix.shape[0] != nbr_func_ref or output_matrix.shape[1] != nbr_var_ref)): - A = N.zeros((nbr_func_ref,nbr_var_ref)) + (not isinstance(output_matrix, np.ndarray)) or \ + (isinstance(output_matrix, np.ndarray) and (output_matrix.shape[0] != nbr_func_ref or output_matrix.shape[1] != nbr_var_ref)): + A = np.zeros((nbr_func_ref,nbr_var_ref)) else: A = output_matrix @@ -6794,11 +6794,11 @@ cdef class FMUModelBase2(ModelBase): cdef FMIL.size_t nv, nz #input arrays - cdef N.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode='c'] v_ref = N.zeros(len(var_ref), dtype = N.uint32) - cdef N.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode='c'] z_ref = N.zeros(len(func_ref), dtype = N.uint32) - cdef N.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] dv = N.zeros(len(v), dtype = N.double) + cdef np.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode='c'] v_ref = np.zeros(len(var_ref), dtype = np.uint32) + cdef np.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode='c'] z_ref = np.zeros(len(func_ref), dtype = np.uint32) + cdef np.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] dv = np.zeros(len(v), dtype = np.double) #output array - cdef N.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] dz = N.zeros(len(func_ref), dtype = N.double) + cdef np.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] dz = np.zeros(len(func_ref), dtype = np.double) if not self._provides_directional_derivatives(): raise FMUException('This FMU does not provide directional derivatives') @@ -6823,20 +6823,20 @@ cdef class FMUModelBase2(ModelBase): return dz - cdef int _get_directional_derivative(self, N.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode="c"] v_ref, - N.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode="c"] z_ref, - N.ndarray[FMIL.fmi2_real_t, ndim=1, mode="c"] dv, - N.ndarray[FMIL.fmi2_real_t, ndim=1, mode="c"] dz) except -1: + cdef int _get_directional_derivative(self, np.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode="c"] v_ref, + np.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode="c"] z_ref, + np.ndarray[FMIL.fmi2_real_t, ndim=1, mode="c"] dv, + np.ndarray[FMIL.fmi2_real_t, ndim=1, mode="c"] dz) except -1: cdef int status - assert N.size(dv) >= N.size(v_ref) and N.size(dz) >= N.size(z_ref) + assert np.size(dv) >= np.size(v_ref) and np.size(dz) >= np.size(z_ref) if not self._provides_directional_derivatives(): raise FMUException('This FMU does not provide directional derivatives') status = FMIL.fmi2_import_get_directional_derivative(self._fmu, - v_ref.data, N.size(v_ref), - z_ref.data, N.size(z_ref), + v_ref.data, np.size(v_ref), + z_ref.data, np.size(z_ref), dv.data, dz.data) @@ -7147,11 +7147,11 @@ cdef class FMUModelCS2(FMUModelBase2): """ cdef int status cdef unsigned int can_interpolate_inputs - cdef N.ndarray[FMIL.fmi2_integer_t, ndim=1, mode='c'] orders - cdef N.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode='c'] value_refs - cdef N.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] val = N.array(values, dtype=float, ndmin=1).ravel() - cdef FMIL.size_t nref = N.size(val) - orders = N.array([0]*nref, dtype=N.int32) + cdef np.ndarray[FMIL.fmi2_integer_t, ndim=1, mode='c'] orders + cdef np.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode='c'] value_refs + cdef np.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] val = np.array(values, dtype=float, ndmin=1).ravel() + cdef FMIL.size_t nref = np.size(val) + orders = np.array([0]*nref, dtype=np.int32) can_interpolate_inputs = FMIL.fmi2_import_get_capability(self._fmu, FMIL.fmi2_cs_canInterpolateInputs) #NOTE IS THIS THE HIGHEST ORDER OF INTERPOLATION OR SIMPLY IF IT CAN OR NOT? @@ -7162,10 +7162,10 @@ cdef class FMUModelCS2(FMUModelBase2): raise FMUException("The FMU does not support input derivatives.") if isinstance(variables,str): - value_refs = N.array([0], dtype=N.uint32, ndmin=1).ravel() + value_refs = np.array([0], dtype=np.uint32, ndmin=1).ravel() value_refs[0] = self.get_variable_valueref(variables) - elif isinstance(variables,list) and N.prod([int(isinstance(v,str)) for v in variables]): #prod equals 0 or 1 - value_refs = N.array([0]*nref, dtype=N.uint32,ndmin=1).ravel() + elif isinstance(variables,list) and np.prod([int(isinstance(v,str)) for v in variables]): #prod equals 0 or 1 + value_refs = np.array([0]*nref, dtype=np.uint32,ndmin=1).ravel() for i in range(nref): value_refs[i] = self.get_variable_valueref(variables[i]) orders[i] = order @@ -7179,16 +7179,16 @@ cdef class FMUModelCS2(FMUModelBase2): if status != 0: raise FMUException('Failed to set the Real input derivatives.') - cdef int _set_input_derivatives(self, N.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode="c"] value_refs, - N.ndarray[FMIL.fmi2_real_t, ndim=1, mode="c"] values, - N.ndarray[FMIL.fmi2_integer_t, ndim=1, mode="c"] orders): + cdef int _set_input_derivatives(self, np.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode="c"] value_refs, + np.ndarray[FMIL.fmi2_real_t, ndim=1, mode="c"] values, + np.ndarray[FMIL.fmi2_integer_t, ndim=1, mode="c"] orders): cdef int status - assert N.size(values) >= N.size(value_refs) and N.size(orders) >= N.size(value_refs) + assert np.size(values) >= np.size(value_refs) and np.size(orders) >= np.size(value_refs) status = FMIL.fmi2_import_set_real_input_derivatives(self._fmu, value_refs.data, - N.size(value_refs), orders.data, + np.size(value_refs), orders.data, values.data) return status @@ -7214,9 +7214,9 @@ cdef class FMUModelCS2(FMUModelBase2): cdef int status cdef unsigned int max_output_derivative cdef FMIL.size_t nref - cdef N.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] values - cdef N.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode='c'] value_refs - cdef N.ndarray[FMIL.fmi2_integer_t, ndim=1, mode='c'] orders + cdef np.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] values + cdef np.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode='c'] value_refs + cdef np.ndarray[FMIL.fmi2_integer_t, ndim=1, mode='c'] orders max_output_derivative = FMIL.fmi2_import_get_capability(self._fmu, FMIL.fmi2_cs_maxOutputDerivativeOrder) @@ -7225,20 +7225,20 @@ cdef class FMUModelCS2(FMUModelBase2): if isinstance(variables,str): nref = 1 - value_refs = N.array([0], dtype=N.uint32, ndmin=1).ravel() - orders = N.array([order], dtype=N.int32) + value_refs = np.array([0], dtype=np.uint32, ndmin=1).ravel() + orders = np.array([order], dtype=np.int32) value_refs[0] = self.get_variable_valueref(variables) - elif isinstance(variables,list) and N.prod([int(isinstance(v,str)) for v in variables]): #prod equals 0 or 1 + elif isinstance(variables,list) and np.prod([int(isinstance(v,str)) for v in variables]): #prod equals 0 or 1 nref = len(variables) - value_refs = N.array([0]*nref, dtype=N.uint32, ndmin=1).ravel() - orders = N.array([0]*nref, dtype=N.int32) + value_refs = np.array([0]*nref, dtype=np.uint32, ndmin=1).ravel() + orders = np.array([0]*nref, dtype=np.int32) for i in range(nref): value_refs[i] = self.get_variable_valueref(variables[i]) orders[i] = order else: raise FMUException("The variables must either be a string or a list of strings") - values = N.array([0.0]*nref, dtype=float, ndmin=1) + values = np.array([0.0]*nref, dtype=float, ndmin=1) #status = FMIL.fmi2_import_get_real_output_derivatives(self._fmu, value_refs.data, nref, # orders.data, values.data) @@ -7249,15 +7249,15 @@ cdef class FMUModelCS2(FMUModelBase2): return values - cdef int _get_output_derivatives(self, N.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode="c"] value_refs, - N.ndarray[FMIL.fmi2_real_t, ndim=1, mode="c"] values, - N.ndarray[FMIL.fmi2_integer_t, ndim=1, mode="c"] orders): + cdef int _get_output_derivatives(self, np.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode="c"] value_refs, + np.ndarray[FMIL.fmi2_real_t, ndim=1, mode="c"] values, + np.ndarray[FMIL.fmi2_integer_t, ndim=1, mode="c"] orders): cdef int status - assert N.size(values) >= N.size(value_refs) and N.size(orders) >= N.size(value_refs) + assert np.size(values) >= np.size(value_refs) and np.size(orders) >= np.size(value_refs) status = FMIL.fmi2_import_get_real_output_derivatives(self._fmu, - value_refs.data, N.size(value_refs), + value_refs.data, np.size(value_refs), orders.data, values.data) return status @@ -7766,7 +7766,7 @@ cdef class FMUModelME2(FMUModelBase2): cdef int _get_event_indicators(self, FMIL.fmi2_real_t[:] values): #if not values.flags['C_CONTIGUOUS']: - # values = N.ascontiguousarray(values) + # values = np.ascontiguousarray(values) if self._nEventIndicators > 0: return FMIL.fmi2_import_get_event_indicators(self._fmu, &values[0], self._nEventIndicators) else: @@ -7788,7 +7788,7 @@ cdef class FMUModelME2(FMUModelBase2): Calls the low-level FMI function: fmiGetEventIndicators """ cdef int status - cdef N.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] values = N.empty(self._nEventIndicators, dtype=N.double) + cdef np.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] values = np.empty(self._nEventIndicators, dtype=np.double) status = self._get_event_indicators(values) @@ -7962,7 +7962,7 @@ cdef class FMUModelME2(FMUModelBase2): The continuous states. """ cdef int status - cdef N.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] ndx = N.zeros(self._nContinuousStates, dtype=N.double) + cdef np.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] ndx = np.zeros(self._nContinuousStates, dtype=np.double) status = self._get_continuous_states_fmil(ndx) if status != 0: @@ -7976,7 +7976,7 @@ cdef class FMUModelME2(FMUModelBase2): else: return FMIL.fmi2_status_ok - def _set_continuous_states(self, N.ndarray[FMIL.fmi2_real_t, ndim=1, mode="c"] values): + def _set_continuous_states(self, np.ndarray[FMIL.fmi2_real_t, ndim=1, mode="c"] values): """ Set the values of the continuous states. @@ -7986,9 +7986,9 @@ cdef class FMUModelME2(FMUModelBase2): The new values of the continuous states. """ cdef int status - cdef N.ndarray[FMIL.fmi2_real_t, ndim=1,mode='c'] ndx = values + cdef np.ndarray[FMIL.fmi2_real_t, ndim=1,mode='c'] ndx = values - if N.size(ndx) != self._nContinuousStates: + if np.size(ndx) != self._nContinuousStates: raise FMUException( 'Failed to set the new continuous states. ' \ 'The number of values are not consistent with the number of '\ @@ -8017,7 +8017,7 @@ cdef class FMUModelME2(FMUModelBase2): The nominal values. """ cdef int status - cdef N.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] xn = N.zeros(self._nContinuousStates, dtype=N.double) + cdef np.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] xn = np.zeros(self._nContinuousStates, dtype=np.double) status = self._get_nominal_continuous_states_fmil( xn.data, self._nContinuousStates) if status != 0: @@ -8071,7 +8071,7 @@ cdef class FMUModelME2(FMUModelBase2): Calls the low-level FMI function: fmi2GetDerivatives """ cdef int status - cdef N.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] values = N.empty(self._nContinuousStates, dtype = N.double) + cdef np.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] values = np.empty(self._nContinuousStates, dtype = np.double) status = self._get_derivatives(values) @@ -8236,9 +8236,9 @@ cdef class FMUModelME2(FMUModelBase2): cdef double tmp_nominal, fac, tmp cdef int method = FORWARD_DIFFERENCE if self.force_finite_differences is True or self.force_finite_differences == 0 else CENTRAL_DIFFERENCE cdef double RUROUND = FORWARD_DIFFERENCE_EPS if method == FORWARD_DIFFERENCE else CENTRAL_DIFFERENCE_EPS - cdef N.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] dfpert, df, eps, nominals - cdef N.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode='c'] v_ref = N.array(var_ref, copy=False, dtype = N.uint32) - cdef N.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode='c'] z_ref = N.array(func_ref, copy=False, dtype = N.uint32) + cdef np.ndarray[FMIL.fmi2_real_t, ndim=1, mode='c'] dfpert, df, eps, nominals + cdef np.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode='c'] v_ref = np.array(var_ref, copy=False, dtype = np.uint32) + cdef np.ndarray[FMIL.fmi2_value_reference_t, ndim=1, mode='c'] z_ref = np.array(func_ref, copy=False, dtype = np.uint32) cdef int ind_local = 5 if add_diag else 4 cdef list local_group @@ -8283,11 +8283,11 @@ cdef class FMUModelME2(FMUModelBase2): else: # First time extraction of nominals #If we are using the states, then the nominals should instead be picked up from the C callback function for nominals if self._states_references and len_v == len(self._states_references) and (self._states_references[i] == var_ref[i] for i in range(len_v)): - group["nominals"] = N.array(self.nominal_continuous_states, dtype=float) + group["nominals"] = np.array(self.nominal_continuous_states, dtype=float) nominals = group["nominals"] nominals_pt = PyArray_DATA(nominals) else: - group["nominals"] = N.empty(len_v, dtype=float) + group["nominals"] = np.empty(len_v, dtype=float) nominals = group["nominals"] nominals_pt = PyArray_DATA(nominals) for i in range(len_v): @@ -8302,7 +8302,7 @@ cdef class FMUModelME2(FMUModelBase2): if group is not None: if output_matrix is not None: - if not isinstance(output_matrix, sp.csc_matrix): + if not isinstance(output_matrix, sps.csc_matrix): output_matrix = None else: output_matrix_data_pt = PyArray_DATA(output_matrix.data) @@ -8395,23 +8395,23 @@ cdef class FMUModelME2(FMUModelBase2): A = output_matrix else: if len(data) == 0: - A = sp.csc_matrix((len_f,len_v)) + A = sps.csc_matrix((len_f,len_v)) else: - A = sp.csc_matrix((data, (row, col)), (len_f,len_v)) + A = sps.csc_matrix((data, (row, col)), (len_f,len_v)) return A else: if output_matrix is None or \ - (not isinstance(output_matrix, N.ndarray)) or \ - (isinstance(output_matrix, N.ndarray) and (output_matrix.shape[0] != len_f or output_matrix.shape[1] != len_v)): - A = N.zeros((len_f,len_v)) + (not isinstance(output_matrix, np.ndarray)) or \ + (isinstance(output_matrix, np.ndarray) and (output_matrix.shape[0] != len_f or output_matrix.shape[1] != len_v)): + A = np.zeros((len_f,len_v)) else: A = output_matrix if len_v == 0 or len_f == 0: return A - dfpert = N.zeros(len_f, dtype = N.double) + dfpert = np.zeros(len_f, dtype = np.double) df = df[:len_f] #Should be removed in the future for i in range(len_v): tmp = v_pt[i] @@ -8735,22 +8735,22 @@ cdef class WorkerClass2: self._dim = 0 def _update_work_vectors(self, dim): - self._tmp1_val = N.zeros(dim, dtype = N.double) - self._tmp2_val = N.zeros(dim, dtype = N.double) - self._tmp3_val = N.zeros(dim, dtype = N.double) - self._tmp4_val = N.zeros(dim, dtype = N.double) + self._tmp1_val = np.zeros(dim, dtype = np.double) + self._tmp2_val = np.zeros(dim, dtype = np.double) + self._tmp3_val = np.zeros(dim, dtype = np.double) + self._tmp4_val = np.zeros(dim, dtype = np.double) - self._tmp1_ref = N.zeros(dim, dtype = N.uint32) - self._tmp2_ref = N.zeros(dim, dtype = N.uint32) - self._tmp3_ref = N.zeros(dim, dtype = N.uint32) - self._tmp4_ref = N.zeros(dim, dtype = N.uint32) + self._tmp1_ref = np.zeros(dim, dtype = np.uint32) + self._tmp2_ref = np.zeros(dim, dtype = np.uint32) + self._tmp3_ref = np.zeros(dim, dtype = np.uint32) + self._tmp4_ref = np.zeros(dim, dtype = np.uint32) cpdef verify_dimensions(self, int dim): if dim > self._dim: self._update_work_vectors(dim) - cdef N.ndarray get_real_numpy_vector(self, int index): - cdef N.ndarray ret = None + cdef np.ndarray get_real_numpy_vector(self, int index): + cdef np.ndarray ret = None if index == 0: ret = self._tmp1_val @@ -8776,8 +8776,8 @@ cdef class WorkerClass2: return ret - cdef N.ndarray get_value_reference_numpy_vector(self, int index): - cdef N.ndarray ret = None + cdef np.ndarray get_value_reference_numpy_vector(self, int index): + cdef np.ndarray ret = None if index == 0: ret = self._tmp1_ref diff --git a/src/pyfmi/fmi_algorithm_drivers.py b/src/pyfmi/fmi_algorithm_drivers.py index 70618d33..1f0f4869 100644 --- a/src/pyfmi/fmi_algorithm_drivers.py +++ b/src/pyfmi/fmi_algorithm_drivers.py @@ -21,7 +21,8 @@ import logging as logging_module import time -import numpy as N +import numpy as np +import scipy.optimize as spopt import pyfmi.fmi as fmi import pyfmi.fmi_coupled as fmi_coupled @@ -35,8 +36,8 @@ from timeit import default_timer as timer default_int = int -int = N.int32 -N.int = N.int32 +int = np.int32 +np.int = np.int32 PYFMI_JACOBIAN_LIMIT = 10 PYFMI_JACOBIAN_SPARSE_SIZE_LIMIT = 100 @@ -583,10 +584,10 @@ def _set_options(self): self.solver_options['rtol'] = rtol #rtol was provided as a vector - if isinstance(self.solver_options["rtol"], N.ndarray) or isinstance(self.solver_options["rtol"], list): + if isinstance(self.solver_options["rtol"], np.ndarray) or isinstance(self.solver_options["rtol"], list): #rtol all are all equal -> set it as scalar and use that - if N.all(N.isclose(self.solver_options["rtol"], self.solver_options["rtol"][0])): + if np.all(np.isclose(self.solver_options["rtol"], self.solver_options["rtol"][0])): self.solver_options["rtol"] = self.solver_options["rtol"][0] self.rtol = self.solver_options["rtol"] @@ -639,7 +640,7 @@ def _set_options(self): except KeyError: #Need to calculate the nnz. [derv_state_dep, derv_input_dep] = self.model.get_derivatives_dependencies() - nnz = N.sum([len(derv_state_dep[key]) for key in derv_state_dep.keys()])+fnbr + nnz = np.sum([len(derv_state_dep[key]) for key in derv_state_dep.keys()])+fnbr if nnz/float(fnbr*fnbr) <= PYFMI_JACOBIAN_SPARSE_NNZ_LIMIT: self.solver_options["linear_solver"] = "SPARSE" else: @@ -665,7 +666,7 @@ def _set_absolute_tolerance_options(self): self.solver_options["atol"] = 0.01*self.rtol else: self.solver_options["atol"] = 0.01*self.rtol*self.model.nominal_continuous_states - elif isinstance(preinit_nominals, N.ndarray) and (N.size(preinit_nominals) > 0): + elif isinstance(preinit_nominals, np.ndarray) and (np.size(preinit_nominals) > 0): # Heuristic: # Try to find if atol was specified as "atol = factor * model.nominal_continuous_states", # and if that's the case, recompute atol with nominals from after initialization. @@ -712,7 +713,7 @@ def _set_solver_options(self): solver_options["maxh"] = float(self.final_time - self.start_time) / float(self.options["ncp"]) if "rtol" in solver_options: - rtol_is_vector = (isinstance(self.solver_options["rtol"], N.ndarray) or isinstance(self.solver_options["rtol"], list)) + rtol_is_vector = (isinstance(self.solver_options["rtol"], np.ndarray) or isinstance(self.solver_options["rtol"], list)) rtol_vector_support = self.simulator.supports.get("rtol_as_vector", False) if rtol_is_vector and not rtol_vector_support and self._rtol_as_scalar_fallback: @@ -1094,7 +1095,7 @@ def solve(self): """ result_handler = self.result_handler h = (self.final_time-self.start_time)/self.ncp - grid = N.linspace(self.start_time,self.final_time,self.ncp+1)[:-1] + grid = np.linspace(self.start_time,self.final_time,self.ncp+1)[:-1] status = 0 final_time = self.start_time @@ -1276,7 +1277,7 @@ def _set_options(self): scale = [] for parameter in self.parameters: scale.append(self.model.get_variable_nominal(parameter)) - self.options["scaling"] = N.array(scale) + self.options["scaling"] = np.array(scale) if self.options["simulate_options"] == "Default": self.options["simulate_options"] = self.model.simulate_options() @@ -1301,7 +1302,6 @@ def solve(self): """ Runs the estimation. """ - import scipy.optimize as sciopt from pyfmi.fmi_util import parameter_estimation_f #Define callback @@ -1321,13 +1321,13 @@ def parameter_estimation_callback(y): p0 = [] for i,parameter in enumerate(self.parameters): p0.append(self.model.get(parameter)/self.options["scaling"][i]) - p0 = N.array(p0).flatten() + p0 = np.array(p0).flatten() print('\nRunning solver: ' + self.options["method"]) print(' Initial parameters (scaled): ' + str(p0)) print(' ') - res = sciopt.minimize(parameter_estimation_f, p0, + res = spopt.minimize(parameter_estimation_f, p0, args=(self.parameters, self.measurements, self.model, self.input, self.options), method=self.options["method"], bounds=None, diff --git a/src/pyfmi/fmi_coupled.pyx b/src/pyfmi/fmi_coupled.pyx index 7885c9e6..c821917b 100644 --- a/src/pyfmi/fmi_coupled.pyx +++ b/src/pyfmi/fmi_coupled.pyx @@ -17,6 +17,10 @@ # distutils: define_macros=NPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION +import time +import numpy as np +cimport numpy as np + import pyfmi.fmi as fmi from pyfmi.fmi cimport FMUModelME2 cimport fmil_import as FMIL @@ -24,10 +28,7 @@ cimport fmil_import as FMIL from pyfmi.fmi_util import enable_caching, Graph from collections import OrderedDict -import time -import numpy as np -cimport numpy as np -import scipy.optimize as sopt +import scipy.optimize as spopt def init_f_block(u, coupled, block): @@ -1978,7 +1979,7 @@ cdef class CoupledFMUModelME2(CoupledFMUModelBase): u = np.array(u).ravel() success = False - res = sopt.root(init_f_block, u, args=(self,block)) + res = spopt.root(init_f_block, u, args=(self,block)) success = res["success"] if not success: @@ -1988,7 +1989,7 @@ cdef class CoupledFMUModelME2(CoupledFMUModelBase): for model in block["outputs"].keys(): self.get_specific_connection_outputs(model, block["outputs_mask"][model], y) - res = sopt.root(init_f_block, y[block["global_outputs_mask"]], args=(self,block)) + res = spopt.root(init_f_block, y[block["global_outputs_mask"]], args=(self,block)) if not res["success"]: print res raise Exception("Failed to converge the initialization system.") diff --git a/src/pyfmi/fmi_extended.pyx b/src/pyfmi/fmi_extended.pyx index 07d37ce9..894e5693 100644 --- a/src/pyfmi/fmi_extended.pyx +++ b/src/pyfmi/fmi_extended.pyx @@ -22,8 +22,8 @@ Module containing the FMI interface Python wrappers. """ import logging -import numpy as N -cimport numpy as N +import numpy as np +cimport numpy as np cimport fmil_import as FMIL from pyfmi.fmi cimport FMUModelME1 @@ -38,7 +38,7 @@ cdef class FMUModelME1Extended(FMUModelME1): cdef public list _input_value_refs, _input_alias_type, _input_factorials cdef public int _input_active, _input_order cdef public dict _input_derivatives, _options - cdef public N.ndarray _input_tmp + cdef public np.ndarray _input_tmp def __init__(self, fmu, log_file_name="", log_level=FMI_DEFAULT_LOG_LEVEL, _connect_dll=True): #Instantiate the FMU @@ -52,7 +52,7 @@ cdef class FMUModelME1Extended(FMUModelME1): for name in vars.keys(): input_value_refs.append(self.get_variable_valueref(name)) input_alias_type.append(-1.0 if self.get_variable_alias(name)[name] == -1 else 1.0) - assert not N.any(input_alias_type == -1) + assert not np.any(input_alias_type == -1) self._input_derivatives = {} for val_ref in input_value_refs: @@ -97,7 +97,7 @@ cdef class FMUModelME1Extended(FMUModelME1): cdef void _eval_input(self, double time): cdef int i,j - cdef N.ndarray input_tmp = self._input_tmp.copy() + cdef np.ndarray input_tmp = self._input_tmp.copy() for i,ref in enumerate(self._input_value_refs): for j in range(self._input_order): @@ -126,7 +126,7 @@ cdef class FMUModelME1Extended(FMUModelME1): Calls the low-level FMI function: fmiGetDerivatives """ cdef int status - cdef N.ndarray[FMIL.fmi1_real_t, ndim=1,mode='c'] values = N.empty(self._nContinuousStates,dtype=N.double) + cdef np.ndarray[FMIL.fmi1_real_t, ndim=1,mode='c'] values = np.empty(self._nContinuousStates,dtype=np.double) if self._input_active: self._eval_input(self.time) @@ -281,12 +281,12 @@ cdef class FMUModelME1Extended(FMUModelME1): """ cdef int status cdef FMIL.size_t nref - cdef N.ndarray[FMIL.fmi1_integer_t, ndim=1,mode='c'] np_orders = N.array(orders, dtype=N.int32, ndmin=1).flatten() - cdef N.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] value_refs - cdef N.ndarray[FMIL.fmi1_real_t, ndim=1,mode='c'] val = N.array(values, dtype=float, ndmin=1).flatten() + cdef np.ndarray[FMIL.fmi1_integer_t, ndim=1,mode='c'] np_orders = np.array(orders, dtype=np.int32, ndmin=1).flatten() + cdef np.ndarray[FMIL.fmi1_value_reference_t, ndim=1,mode='c'] value_refs + cdef np.ndarray[FMIL.fmi1_real_t, ndim=1,mode='c'] val = np.array(values, dtype=float, ndmin=1).flatten() nref = len(val) - orders = N.array([0]*nref, dtype=N.int32) + orders = np.array([0]*nref, dtype=np.int32) if nref != len(np_orders): raise FMUException("The number of variables must be the same as the number of orders.") @@ -298,10 +298,10 @@ cdef class FMUModelME1Extended(FMUModelME1): self._input_order = np_orders[i] if isinstance(variables,str): - value_refs = N.array([0], dtype=N.uint32,ndmin=1).flatten() + value_refs = np.array([0], dtype=np.uint32,ndmin=1).flatten() value_refs[0] = self.get_variable_valueref(variables) elif isinstance(variables,list) and isinstance(variables[-1],str): - value_refs = N.array([0]*nref, dtype=N.uint32,ndmin=1).flatten() + value_refs = np.array([0]*nref, dtype=np.uint32,ndmin=1).flatten() for i in range(nref): value_refs[i] = self.get_variable_valueref(variables[i]) else: diff --git a/src/pyfmi/master.pyx b/src/pyfmi/master.pyx index a9942b25..b7fe956a 100644 --- a/src/pyfmi/master.pyx +++ b/src/pyfmi/master.pyx @@ -32,9 +32,8 @@ import time import numpy as np import warnings cimport numpy as np -import scipy.sparse as sp -import scipy.sparse.linalg as splin -import scipy.optimize as sopt +import scipy.sparse as sps +import scipy.optimize as spopt from pyfmi.fmi cimport FMUModelCS2 from cpython cimport bool @@ -460,7 +459,7 @@ cdef class Master: self.y_prev = None self.input_traj = None - self._ident_matrix = sp.eye(self._len_inputs, self._len_outputs, format="csr") #y = Cx + Du , u = Ly -> DLy DL[inputsXoutputs] + self._ident_matrix = sps.eye(self._len_inputs, self._len_outputs, format="csr") #y = Cx + Du , u = Ly -> DLy DL[inputsXoutputs] self._error_data = {"time":[], "error":[], "step-size":[], "rejected":[]} @@ -559,8 +558,8 @@ cdef class Master: col_discrete.append(self.models_dict[src]["global_index_outputs_discrete"]+self.models_dict[src]["local_output_discrete"].index(src_var)) len_connections_discrete = len_connections_discrete + 1 - self.L = sp.csr_matrix((data, (row, col)), (len_connections,len_connections), dtype=np.float64) - self.L_discrete = sp.csr_matrix((data_discrete, (row_discrete, col_discrete)), (len_connections_discrete,len_connections_discrete), dtype=np.float64) + self.L = sps.csr_matrix((data, (row, col)), (len_connections,len_connections), dtype=np.float64) + self.L_discrete = sps.csr_matrix((data_discrete, (row_discrete, col_discrete)), (len_connections_discrete,len_connections_discrete), dtype=np.float64) cpdef compute_global_D(self): cdef list data = [] @@ -601,7 +600,7 @@ cdef class Master: col = self._storedDcol if self._D is None: - self._D = sp.csr_matrix((data, (row, col)))#, (len(col),len(row))) + self._D = sps.csr_matrix((data, (row, col)))#, (len(col),len(row))) else: self._D.data = np.array(data, dtype=np.float64) @@ -622,7 +621,7 @@ cdef class Master: data.extend(local_C) col.extend([self.models_dict[model]["global_index_states"]+i]*len(local_C)) row.extend(np.array([self.models_dict[model]["global_index_outputs"]]*len(self.models_dict[model]["local_output_vref"]))+np.array(range(len(self.models_dict[model]["local_output_vref"])))) - return sp.csr_matrix((data, (row, col))) + return sps.csr_matrix((data, (row, col))) def compute_global_A(self): cdef list data = [] @@ -638,7 +637,7 @@ cdef class Master: data.extend(local_A) col.extend([self.models_dict[model]["global_index_states"]+i]*len(local_A)) row.extend(np.array([self.models_dict[model]["global_index_derivatives"]]*len(self.models_dict[model]["local_derivative_vref"]))+np.array(range(len(self.models_dict[model]["local_derivative_vref"])))) - return sp.csr_matrix((data, (row, col))) + return sps.csr_matrix((data, (row, col))) def compute_global_B(self): cdef list data = [] @@ -654,7 +653,7 @@ cdef class Master: data.extend(local_B) col.extend([self.models_dict[model]["global_index_inputs"]+i]*len(local_B)) row.extend(np.array([self.models_dict[model]["global_index_derivatives"]]*len(self.models_dict[model]["local_derivative_vref"]))+np.array(range(len(self.models_dict[model]["local_derivative_vref"])))) - return sp.csr_matrix((data, (row, col))) + return sps.csr_matrix((data, (row, col))) def connection_setup(self, connections): for connection in connections: @@ -845,7 +844,7 @@ cdef class Master: else: return C.dot(xd)+D.dot(ud) else: #First step - return splin.spsolve((self._ident_matrix-D.dot(self.L)),C.dot(xd)).reshape((-1,1)) + return sps.linalg.spsolve((self._ident_matrix-D.dot(self.L)),C.dot(xd)).reshape((-1,1)) y_last = self.get_last_y() if y_last is not None: @@ -890,7 +889,7 @@ cdef class Master: if ud is not None and udd is not None: return C.dot(A.dot(xd))+C.dot(B.dot(ud+self.get_current_step_size()*udd))+D.dot(udd) else: #First step - return splin.spsolve((self._ident_matrix-D.dot(self.L)),C.dot(A.dot(xd)+B.dot(self.L.dot(yd_cur)))).reshape((-1,1)) + return sps.linalg.spsolve((self._ident_matrix-D.dot(self.L)),C.dot(A.dot(xd)+B.dot(self.L.dot(yd_cur)))).reshape((-1,1)) yd_last = self.get_last_yd() if yd_last is not None: @@ -957,7 +956,7 @@ cdef class Master: z = yd - D.dot(uhat) - yd = splin.spsolve((self._ident_matrix-DL),z).reshape((-1,1)) + yd = sps.linalg.spsolve((self._ident_matrix-DL),z).reshape((-1,1)) """ return ydd @@ -972,7 +971,7 @@ cdef class Master: z = yd - D.dot(uhat) - yd = splin.spsolve((self._ident_matrix-DL),z).reshape((-1,1)) + yd = sps.linalg.spsolve((self._ident_matrix-DL),z).reshape((-1,1)) return yd @@ -984,7 +983,7 @@ cdef class Master: JM_FMUS = False break if JM_FMUS: - res = sopt.root(init_f, y, args=(self)) + res = spopt.root(init_f, y, args=(self)) if not res["success"]: print(res) raise fmi.FMUException("Failed to converge the output system.") @@ -1005,8 +1004,8 @@ cdef class Master: z = y - DL.dot(y_prev) #z = y - matvec(DL, y_prev.ravel()) - y = splin.spsolve((self._ident_matrix-DL),z).reshape((-1,1)) - #y = splin.lsqr((sp.eye(*DL.shape)-DL),z)[0].reshape((-1,1)) + y = sps.linalg.spsolve((self._ident_matrix-DL),z).reshape((-1,1)) + #y = sps.linalg.lsqr((sps.eye(*DL.shape)-DL),z)[0].reshape((-1,1)) elif self.algebraic_loops and self.support_directional_derivatives: pass @@ -1113,7 +1112,7 @@ cdef class Master: for model in block["outputs"].keys(): self.get_specific_connection_outputs(model, block["outputs_mask"][model], y) - res = sopt.root(init_f_block, y[block["global_outputs_mask"]], args=(self,block)) + res = spopt.root(init_f_block, y[block["global_outputs_mask"]], args=(self,block)) if not res["success"]: print(res) raise fmi.FMUException("Failed to converge the initialization system.") @@ -1135,9 +1134,9 @@ cdef class Master: if self.algebraic_loops: #If there is an algebraic loop, solve the resulting system if self.support_directional_derivatives: - res = sopt.root(init_f, self.get_connection_outputs(), args=(self), jac=init_jac) + res = spopt.root(init_f, self.get_connection_outputs(), args=(self), jac=init_jac) else: - res = sopt.root(init_f, self.get_connection_outputs(), args=(self)) + res = spopt.root(init_f, self.get_connection_outputs(), args=(self)) if not res["success"]: print(res) raise fmi.FMUException("Failed to converge the initialization system.") @@ -1314,7 +1313,7 @@ cdef class Master: D = self.compute_global_D() DL = D.dot(self.L) import numpy.linalg - import scipy.linalg as slin + from scipy.linalg import expm print("At time: %E , rho(DL)=%s"%(tcur + step_size, str(numpy.linalg.eig(DL.todense())[0]))) C = self.compute_global_C() if C is not None: @@ -1326,7 +1325,7 @@ cdef class Master: B = self.compute_global_B() if C is not None and A is not None and B is not None: A = A.todense(); B = B.todense() - eAH = slin.expm(A*step_size) + eAH = expm(A*step_size) K1 = np.linalg.solve(_ident_matrix-DL,C) K2 = np.linalg.solve(A,(eAH-np.eye(*eAH.shape)).dot(B.dot(self.L.todense()))) R1 = np.hstack((eAH, K1)) diff --git a/src/pyfmi/simulation/assimulo_interface.pxd b/src/pyfmi/simulation/assimulo_interface.pxd index 91f7c0d6..531615e7 100644 --- a/src/pyfmi/simulation/assimulo_interface.pxd +++ b/src/pyfmi/simulation/assimulo_interface.pxd @@ -16,8 +16,8 @@ # along with this program. If not, see . -import numpy as N -cimport numpy as N +import numpy as np +cimport numpy as np import logging from pyfmi.fmi cimport FMUModelME2 @@ -49,16 +49,16 @@ cdef class FMIODE2(cExplicit_Problem): cdef public object _model, problem_name, result_file_name, __input, _A, debug_file_name, debug_file_object cdef public object export, _sparse_representation, _with_jacobian, _logging, _write_header, _start_time cdef public dict timings - cdef public N.ndarray y0, input_real_mask, input_other_mask + cdef public np.ndarray y0, input_real_mask, input_other_mask cdef public list input_names, input_real_value_refs, input_other, _logg_step_event cdef public double t0, _synchronize_factor cdef public jac_use, state_events_use, time_events_use cdef public FMUModelME2 model_me2 cdef public int model_me2_instance - cdef public N.ndarray _state_temp_1, _event_temp_1 + cdef public np.ndarray _state_temp_1, _event_temp_1 cdef int _logging_as_dynamic_diagnostics cdef int _number_of_diagnostics_variables cpdef _set_input_values(self, double t) - cdef _update_model(self, double t, N.ndarray[double, ndim=1, mode="c"] y) - cdef int _compare(self, double t, N.ndarray[double, ndim=1, mode="c"] y) + cdef _update_model(self, double t, np.ndarray[double, ndim=1, mode="c"] y) + cdef int _compare(self, double t, np.ndarray[double, ndim=1, mode="c"] y) diff --git a/src/pyfmi/simulation/assimulo_interface.pyx b/src/pyfmi/simulation/assimulo_interface.pyx index 288c41c3..db7debea 100644 --- a/src/pyfmi/simulation/assimulo_interface.pyx +++ b/src/pyfmi/simulation/assimulo_interface.pyx @@ -24,10 +24,9 @@ required by Assimulo. import logging as logging_module from operator import index -import numpy as N - -cimport numpy as N -import scipy.sparse as sp +import numpy as np +cimport numpy as np +import scipy.sparse as sps import time from pyfmi.common.io import ResultWriterDymola @@ -73,17 +72,17 @@ def write_data(simulator,write_scaled_result=False, result_file_name=''): model = simulator.problem._model - t = N.array(simulator.problem._sol_time) - r = N.array(simulator.problem._sol_real) - data = N.c_[t,r] + t = np.array(simulator.problem._sol_time) + r = np.array(simulator.problem._sol_real) + data = np.c_[t,r] if len(simulator.problem._sol_int) > 0 and len(simulator.problem._sol_int[0]) > 0: - i = N.array(simulator.problem._sol_int) - data = N.c_[data,i] + i = np.array(simulator.problem._sol_int) + data = np.c_[data,i] if len(simulator.problem._sol_bool) > 0 and len(simulator.problem._sol_bool[0]) > 0: - #b = N.array(simulator.problem._sol_bool).reshape( + #b = np.array(simulator.problem._sol_bool).reshape( # -1,len(model._save_bool_variables_val)) - b = N.array(simulator.problem._sol_bool) - data = N.c_[data,b] + b = np.array(simulator.problem._sol_bool) + data = np.c_[data,b] export = ResultWriterDymola(model) export.write_header(file_name=result_file_name) @@ -145,7 +144,7 @@ class FMIODE(Explicit_Problem): #If there is no state in the model, add a dummy #state der(y)=0 if f_nbr == 0: - self.y0 = N.array([0.0]) + self.y0 = np.array([0.0]) #Determine the result file name if result_file_name == '': @@ -195,7 +194,7 @@ class FMIODE(Explicit_Problem): input_value_refs.append(self._model.get_variable_valueref(name)) input_alias_type.append(-1.0 if self._model.get_variable_alias(name)[name] == -1 else 1.0) self.input_value_refs = input_value_refs - self.input_alias_type = input_alias_type if N.any(input_alias_type==-1) else 1.0 + self.input_alias_type = input_alias_type if np.any(input_alias_type==-1) else 1.0 self.input = input def rhs(self, t, y, sw=None): @@ -220,7 +219,7 @@ class FMIODE(Explicit_Problem): #If there is no state, use the dummy if self._f_nbr == 0: - rhs = N.array([0.0]) + rhs = np.array([0.0]) return rhs @@ -294,7 +293,7 @@ class FMIODE(Explicit_Problem): #Sets the inputs, if any if self.input is not None: - self._model.set_real(self.input_value_refs, self.input[1].eval(N.array([solver.t]))[0,:]*self.input_alias_type) + self._model.set_real(self.input_value_refs, self.input[1].eval(np.array([solver.t]))[0,:]*self.input_alias_type) #Evaluating the rhs (Have to evaluate the values in the model) rhs = self._model.get_derivatives() @@ -385,8 +384,8 @@ class FMIODE(Explicit_Problem): #Sets the inputs, if any if self.input is not None: - self._model.set_real(self.input_value_refs, self.input[1].eval(N.array([solver.t]))[0,:]*self.input_alias_type) - #self._model.set(self.input[0],self.input[1].eval(N.array([solver.t]))[0,:]) + self._model.set_real(self.input_value_refs, self.input[1].eval(np.array([solver.t]))[0,:]*self.input_alias_type) + #self._model.set(self.input[0],self.input[1].eval(np.array([solver.t]))[0,:]) #Evaluating the rhs (Have to evaluate the values in the model) rhs = self._model.get_derivatives() @@ -520,8 +519,8 @@ class FMIODESENS(FMIODE): if parameters is not None: if not isinstance(parameters,list): raise FMIModel_Exception("Parameters must be a list of names.") - self.p0 = N.array(model.get(parameters)).flatten() - self.pbar = N.array([N.abs(x) if N.abs(x) > 0 else 1.0 for x in self.p0]) + self.p0 = np.array(model.get(parameters)).flatten() + self.pbar = np.array([np.abs(x) if np.abs(x) > 0 else 1.0 for x in self.p0]) self.parameters = parameters @@ -564,7 +563,7 @@ class FMIODESENS(FMIODE): #Sets the parameters, if any if self.parameters is not None: - p_data = N.array(solver.interpolate_sensitivity(t, 0)).flatten() + p_data = np.array(solver.interpolate_sensitivity(t, 0)).flatten() self.export.integration_point(solver)#parameter_data=p_data) @@ -614,7 +613,7 @@ cdef class FMIODE2(cExplicit_Problem): #If there is no state in the model, add a dummy state der(y)=0 if f_nbr == 0: - self.y0 = N.array([0.0]) + self.y0 = np.array([0.0]) #Determine the result file name if result_file_name == '': @@ -644,12 +643,12 @@ cdef class FMIODE2(cExplicit_Problem): #Need to calculate the nnz. [derv_state_dep, derv_input_dep] = model.get_derivatives_dependencies() - self.jac_nnz = N.sum([len(derv_state_dep[key]) for key in derv_state_dep.keys()])+f_nbr + self.jac_nnz = np.sum([len(derv_state_dep[key]) for key in derv_state_dep.keys()])+f_nbr if extra_equations: self._extra_f_nbr = extra_equations.get_size() self._extra_y0 = extra_equations.y0 - self.y0 = N.append(self.y0, self._extra_y0) + self.y0 = np.append(self.y0, self._extra_y0) self._extra_equations = extra_equations if hasattr(self._extra_equations, "jac"): @@ -673,8 +672,8 @@ cdef class FMIODE2(cExplicit_Problem): else: self._synchronize_factor = 0.0 - self._state_temp_1 = N.empty(f_nbr, dtype = N.double) - self._event_temp_1 = N.empty(g_nbr, dtype = N.double) + self._state_temp_1 = np.empty(f_nbr, dtype = np.double) + self._event_temp_1 = np.empty(g_nbr, dtype = np.double) def _adapt_input(self, input): if input is not None: @@ -699,8 +698,8 @@ cdef class FMIODE2(cExplicit_Problem): self.input_other.append(name) input_other_mask.append(i) - self.input_real_mask = N.array(input_real_mask) - self.input_other_mask = N.array(input_other_mask) + self.input_real_mask = np.array(input_real_mask) + self.input_other_mask = np.array(input_other_mask) self._input_activated = 1 else: @@ -717,7 +716,7 @@ cdef class FMIODE2(cExplicit_Problem): if self.input_other: self._model.set(self.input_other, values[self.input_other_mask]) - cdef _update_model(self, double t, N.ndarray[double, ndim=1, mode="c"] y): + cdef _update_model(self, double t, np.ndarray[double, ndim=1, mode="c"] y): if self.model_me2_instance: #Moving data to the model self.model_me2._set_time(t) @@ -734,7 +733,7 @@ cdef class FMIODE2(cExplicit_Problem): #Sets the inputs, if any self._set_input_values(t) - cdef int _compare(self, double t, N.ndarray[double, ndim=1, mode="c"] y): + cdef int _compare(self, double t, np.ndarray[double, ndim=1, mode="c"] y): cdef int res if self.model_me2_instance: @@ -754,7 +753,7 @@ cdef class FMIODE2(cExplicit_Problem): else: return t != self._model.time or (not self._f_nbr == 0 and not (self._model.continuous_states == y).all()) - def rhs(self, double t, N.ndarray[double, ndim=1, mode="c"] y, sw=None): + def rhs(self, double t, np.ndarray[double, ndim=1, mode="c"] y, sw=None): """ The rhs (right-hand-side) for an ODE problem. """ @@ -784,14 +783,14 @@ cdef class FMIODE2(cExplicit_Problem): #If there is no state, use the dummy if self._f_nbr == 0: - der = N.array([0.0]) + der = np.array([0.0]) if self._extra_f_nbr > 0: - der = N.append(der, self._extra_equations.rhs(y_extra)) + der = np.append(der, self._extra_equations.rhs(y_extra)) return der - def jac(self, double t, N.ndarray[double, ndim=1, mode="c"] y, sw=None): + def jac(self, double t, np.ndarray[double, ndim=1, mode="c"] y, sw=None): """ The jacobian function for an ODE problem. """ @@ -816,7 +815,7 @@ cdef class FMIODE2(cExplicit_Problem): msg = preface + ''%(solver_info_tag) self._model.append_log_message("Model", 6, msg) - return N.array([[0.0]]) + return np.array([[0.0]]) A = self._model._get_A(add_diag=True, output_matrix=self._A) if self._A is None: @@ -829,16 +828,16 @@ cdef class FMIODE2(cExplicit_Problem): Jac = A.tocoo() #Convert to COOrdinate A2 = self._extra_equations.jac(y_extra).tocoo() - data = N.append(Jac.data, A2.data) - row = N.append(Jac.row, A2.row+self._f_nbr) - col = N.append(Jac.col, A2.col+self._f_nbr) + data = np.append(Jac.data, A2.data) + row = np.append(Jac.row, A2.row+self._f_nbr) + col = np.append(Jac.col, A2.col+self._f_nbr) #Convert to compresssed sparse column - Jac = sp.coo_matrix((data, (row, col))) + Jac = sps.coo_matrix((data, (row, col))) Jac = Jac.tocsc() else: - Jac = N.zeros((self._f_nbr+self._extra_f_nbr,self._f_nbr+self._extra_f_nbr)) - Jac[:self._f_nbr,:self._f_nbr] = A if isinstance(A, N.ndarray) else A.toarray() + Jac = np.zeros((self._f_nbr+self._extra_f_nbr,self._f_nbr+self._extra_f_nbr)) + Jac[:self._f_nbr,:self._f_nbr] = A if isinstance(A, np.ndarray) else A.toarray() Jac[self._f_nbr:,self._f_nbr:] = self._extra_equations.jac(y_extra) else: raise fmi.FMUException("No Jacobian provided for the extra equations") @@ -851,7 +850,7 @@ cdef class FMIODE2(cExplicit_Problem): return Jac - def state_events(self, double t, N.ndarray[double, ndim=1, mode="c"] y, sw=None): + def state_events(self, double t, np.ndarray[double, ndim=1, mode="c"] y, sw=None): """ The event indicator function for a ODE problem. """ @@ -874,7 +873,7 @@ cdef class FMIODE2(cExplicit_Problem): else: return self._model.get_event_indicators() - def time_events(self, double t, N.ndarray[double, ndim=1, mode="c"] y, sw=None): + def time_events(self, double t, np.ndarray[double, ndim=1, mode="c"] y, sw=None): """ Time event function. """ @@ -975,7 +974,7 @@ cdef class FMIODE2(cExplicit_Problem): msg = preface + ''%(event_info_tag) self._model.append_log_message("Model", 6, msg) else: - diag_data = N.ndarray(self._number_of_diagnostics_variables, dtype=float) + diag_data = np.ndarray(self._number_of_diagnostics_variables, dtype=float) index = 0 diag_data[index] = solver.t index +=1 @@ -1150,7 +1149,7 @@ cdef class FMIODE2(cExplicit_Problem): msg = preface + ''%(solver_info_tag) self._model.append_log_message("Model", 6, msg) else: - diag_data = N.ndarray(self._number_of_diagnostics_variables, dtype=float) + diag_data = np.ndarray(self._number_of_diagnostics_variables, dtype=float) index = 0 diag_data[index] = solver.t index +=1 @@ -1330,8 +1329,8 @@ class FMIODESENS2(FMIODE2): if parameters is not None: if not isinstance(parameters,list): raise FMIModel_Exception("Parameters must be a list of names.") - self.p0 = N.array(model.get(parameters)).flatten() - self.pbar = N.array([N.abs(x) if N.abs(x) > 0 else 1.0 for x in self.p0]) + self.p0 = np.array(model.get(parameters)).flatten() + self.pbar = np.array([np.abs(x) if np.abs(x) > 0 else 1.0 for x in self.p0]) self.param_valref = [model.get_variable_valueref(x) for x in parameters] for param in parameters: diff --git a/tests/test_fmi_master.py b/tests/test_fmi_master.py index 13e58749..42af2971 100644 --- a/tests/test_fmi_master.py +++ b/tests/test_fmi_master.py @@ -424,10 +424,10 @@ def test_unstable_simulation_extrapolation(self): assert abs(res[model_sub1].final("x1")) > 100 assert abs(res[model_sub2].final("x2")) > 100 - #import pylab as plt - #plt.plot(res[model_sub1]["time"], res[model_sub1]["x1"]) - #plt.plot(res_full["time"], res_full["p1.x1"]) - #plt.show() + #import pylab as pl + #pl.plot(res[model_sub1]["time"], res[model_sub1]["x1"]) + #pl.plot(res_full["time"], res_full["p1.x1"]) + #pl.show() @testattr(stddist = True) def test_initialize(self):