Skip to content
Snippets Groups Projects
Commit a8b55cdd authored by freba's avatar freba :call_me:
Browse files

Refactoring: Nomenclature streamlining.

parent 704c190e
No related branches found
No related tags found
No related merge requests found
......@@ -6,17 +6,17 @@ This code documentation will be updated throughout the coming weeks (July 2020).
** TODO Improve project structure :noexport:crypt:
-----BEGIN PGP MESSAGE-----
jA0EBwMCbJNQxW1U+m/q0sA6AbkdydQ3++VaS9WKvLpLT4t1SdDwBTIBVCU8hlnH
xgvvdAF+cVx5zaw5mlpRHRIxIxfHwd4HeM0P6Eh1jJ40ilbxmt42OMVRhq5FFoBM
pqx3IbJzasyW3keBR9m7SatptEl+WDgUIft6VMJ/txqJySztsBdEfTlSj42rC7Wf
iNdgncwKbmhiFO4opvMIWK8zmMdpxOpmm8cnerpf6FuWDP9TFvM4hOEhaMe/FS8S
nY7nxaerOqeooGnXwk7pyQEpC/MG72U9QYXdcykiBtKFVy/KnDPKzNpIH/Cyc28i
ql6hUVQ6IgQ/aaTN7yoJy91pQwQaL4amVEpHhA==
=XxqX
jA0EBwMCbCtBH7j5fVrq0sA9AfaIicpdxk+RhVV+BsUPT+YyDpLOjtHLO2xNIVik
8uBlWOdn0fUHoi5YLLqeio/GL7juq5oXdIm/BTpoTLKLYgOT1Jsqi6LxPIwoU4It
f64fpXwUNbvFjUnt18rZ+pno0yZ/+uoj4TgxoZiIozs2q7WdlEUYwpmvPiDsACD9
/tiDcmV7bDLSFeuhTGLqrJSpp90PL0HgqijQFSufMvR8yISsxKZTTPKNRC4l6G0I
FvWESaH8bVZTXJjrS8E+34QvtltfG5aOa2yiGLm9LPP+uMmia5BRFs6NGUdkluCr
QmRzhUVsFPgYWmFHgCoCMyKP3h2fy3Z9LNAWC/SQ5w==
=ujxO
-----END PGP MESSAGE-----
* TODO SINDYc
* TODO SINDYc (Polynomial Prediction Model)
#+NAME: simo_IDCL_sindy_header
#+NAME: sindyc_header
#+begin_src python :exports none :results none :noweb yes
"""Simulation definitions for the SIMO results.
"""
......@@ -46,27 +46,27 @@ simspec = dict(system='SIMO', Ts=1, ID=IDspec, CL=CLspec,
<<paper_simulation>>
<<paper_plotting_header>>
def unpack(msindy):
msindy_ = {}
def unpack(msindyc):
msindyc_ = {}
for imodel in range(simulator.mp.nx):
msindy_[imodel] = []
msindyc_[imodel] = []
for isample in range(simulator.simspec["samples"]):
try:
m = msindy[isample][imodel]
m = msindyc[isample][imodel]
if isinstance(m, pd.DataFrame):
msindy_[imodel].append(m.iloc[:, 0])
msindyc_[imodel].append(m.iloc[:, 0])
except KeyError:
pass
df = pd.concat(msindy_[imodel], axis=0)
msindy_[f"df_{imodel}"] = df
return msindy_
df = pd.concat(msindyc_[imodel], axis=0)
msindyc_[f"df_{imodel}"] = df
return msindyc_
def plot_clusterModels(
msindy_,
msindyc_,
cluster=0,
true_coefficients=None,
filename="simo_IDCL_sindy.pdf",
filename="sindyc.pdf",
rotate_xlabels=True,
xlabels=None,
kind="bar",
......@@ -86,10 +86,10 @@ def plot_clusterModels(
breakpoint()
return df
def _unpack(msindy_, xlabels):
df_0 = msindy_["df_0"]
def _unpack(msindyc_, xlabels):
df_0 = msindyc_["df_0"]
df_0 = adjust_df(df_0, name="Model 0", xlabels=xlabels)
df_1 = msindy_["df_1"]
df_1 = msindyc_["df_1"]
df_1 = adjust_df(df_1, name="Model 1", xlabels=xlabels)
return df_0, df_1
......@@ -101,8 +101,8 @@ def plot_clusterModels(
dfs_0 = []
dfs_1 = []
idx = 0
for key, _msindy_ in msindy_.items():
df_0, df_1 = _unpack(_msindy_, xlabels)
for key, _msindyc_ in msindyc_.items():
df_0, df_1 = _unpack(_msindyc_, xlabels)
df_0 = unstack(df_0, criterion=key)
df_1 = unstack(df_1, criterion=key)
......@@ -175,18 +175,18 @@ def plot_clusterModels(
return filepath
def select_Xi_parsimony_sweep(msindy):
"""Loop over the SINDYc models in `msindy` and identify the ones
def select_Xi_parsimony_sweep(msindyc):
"""Loop over the SINDYc models in `msindyc` and identify the ones
with the simplest structure. Select the coefficients as average
over the list of candidate models `cmodels`.
Args:
msindy (dict): Dictionary of SINDYc models (samples: models)
msindyc (dict): Dictionary of SINDYc models (samples: models)
"""
dfs = []
cmodels_ = [] # Candidate model
ncoeff = 100 # Number of coefficients observed so far
for isample, model in msindy.items():
for isample, model in msindyc.items():
m = model[0].iloc[:, 0]
ncoeff_ = m[m != 0].shape[0]
if ncoeff_ <= ncoeff:
......@@ -240,34 +240,34 @@ def select_Xi_parsimony_sweep(msindy):
#+end_src
#+NAME: simo_IDCL_c0
#+begin_src python :noweb strip-export :exports both :tangle ./Scripts/simo_IDCL_c0.py :results file :return filepath
#+NAME: c0
#+begin_src python :noweb strip-export :exports both :tangle ./Scripts/c0.py :results file :return filepath
cluster=0
<<simo_IDCL_sindy_header>>
msindy = simulator.identify()
<<sindyc_header>>
msindyc = simulator.identify()
results = simulator.cosimulate_ID()
df, dfm = simulator.combine_sample_dataframes(dfs=results, aggregation_axis=1)
data = dict(msindy=msindy, df=df, dfm=dfm, raw_results=results)
save_to_disc(data, filename="data_simo_IDCL_c0.pkl")
data = dict(msindyc=msindyc, df=df, dfm=dfm, raw_results=results)
save_to_disc(data, filename="data_c0.pkl")
filepath = plot_clusterModels(
unpack(msindy),
unpack(msindyc),
cluster=cluster,
# true_coefficients=simulator.mp.true_coefficients,
xlabels=simulator.formatted_model_coefficients,
rotate_xlabels=False,
kind="violin",
filename="simo_IDCL_sindy_c0.pdf",
filename="sindyc_c0.pdf",
)
#+end_src
#+NAME: simo_IDCL_c1
#+begin_src python :noweb strip-export :exports both :tangle ./Scripts/simo_IDCL_c1.py :results file :return filepath
#+NAME: c1
#+begin_src python :noweb strip-export :exports both :tangle ./Scripts/c1.py :results file :return filepath
cluster=1
<<simo_IDCL_sindy_header>>
<<sindyc_header>>
simspec = dict(system='SIMO',
Ts=1,
ID=IDspec,
......@@ -275,31 +275,31 @@ simspec = dict(system='SIMO',
cluster=cluster,
samples=5)
data = read_from_disc('data_simo_IDCL_c0.pkl')
data = read_from_disc('data_c0.pkl')
u = data['raw_results']['system'][0].filter(regex='u').values.T
d = data['raw_results']['system'][0].filter(regex='d').values.T
UD = dict(U=u, D =d)
msindy = simulator.identify(UD=UD)
msindyc = simulator.identify(UD=UD)
results = simulator.cosimulate_ID()
df, dfm = simulator.combine_sample_dataframes(dfs=results, aggregation_axis=1)
data = dict(msindy=msindy, df=df, dfm=dfm, raw_results=results)
save_to_disc(data, filename="data_simo_IDCL_c1.pkl")
data = dict(msindyc=msindyc, df=df, dfm=dfm, raw_results=results)
save_to_disc(data, filename="data_c1.pkl")
filepath = plot_clusterModels(
unpack(msindy),
unpack(msindyc),
cluster=cluster,
# true_coefficients=simulator.mp.true_coefficients,
xlabels=simulator.formatted_model_coefficients,
rotate_xlabels=False,
kind="violin",
filename="simo_IDCL_sindy_c1.pdf",
filename="sindyc_c1.pdf",
)
#+end_src
#+NAME: simo_IDCL_cosimulate_ID_c0
#+begin_src python :results file :exports both :return filename :tangle ./Scripts/simo_IDCL_cosimulate_ID_c0.py :noweb yes
#+NAME: cosimulate_ID_c0
#+begin_src python :results file :exports both :return filename :tangle ./Scripts/cosimulate_ID_c0.py :noweb yes
import copy
import numpy as np
......@@ -329,7 +329,7 @@ df, df_oos = df[0], df_oos[0]
dfm, dfm_oos = dfm[0], dfm_oos[0]
save_to_disc(
{"df": df, "df_oos": df_oos, "dfs_oos": dfs_oos, "dfm": dfm, "dfm_oos": dfm_oos},
"simo_IDCL_cosimulate_ID_c0.pkl",
"cosimulate_ID_c0.pkl",
)
......@@ -354,7 +354,7 @@ filename = plot_sns(
dfs=dict(
ts_id=dict(system=df, model=dfm), ts_oos=dict(system=df_oos, model=dfm_oos)
),
filename="simo_IDCL_cosimulate_ID_oos_c0.pdf",
filename="cosimulate_ID_oos_c0.pdf",
show=False,
save=True,
)
......@@ -404,9 +404,9 @@ def plot_one_step_prediction_map(mp, xs, us, cluster=0, **kwargs):
c_u0 * x + c_u1 * p + c_u0sq * x ** 2 + c_u0u1 * x * p + c_u1sq * p ** 2
)
else:
data = read_from_disc("data_simo_IDCL_c0.pkl")
msindy = data["msindy"]
coeff = msindy[3][0]
data = read_from_disc("data_c0.pkl")
msindyc = data["msindyc"]
coeff = msindyc[3][0]
c_u0 = coeff.loc["u0"][0]
c_u1 = coeff.loc["u1"][0]
c_u0sq = coeff.loc["u0^{2}"][0]
......@@ -478,17 +478,17 @@ filepath = plot_one_step_prediction_map(mp, xs, us, cluster=[0])
* TODO Markov Chain Monte Carlo
#+NAME: simo_IDCL_c0_stan
#+begin_src python :noweb strip-export :exports none :results file :tangle ./Scripts/simo_IDCL_c0_stan.py :return filepath
#+NAME: c0_stan
#+begin_src python :noweb strip-export :exports none :results file :tangle ./Scripts/c0_stan.py :return filepath
cluster=0
<<simo_IDCL_sindy_header>>
<<sindyc_header>>
<<code_stan_fitModel>>
<<paper_simulation_header>>
data = read_from_disc('data_simo_IDCL_c0.pkl')
msindy = data['msindy']
data = read_from_disc('data_c0.pkl')
msindyc = data['msindyc']
Xistar = select_Xi_parsimony_sweep(msindy)
Xistar = select_Xi_parsimony_sweep(msindyc)
print(Xistar)
df = data["df"][0]
......@@ -505,7 +505,7 @@ for n in range(nXi):
subscript = f"{n+2}" # Only valid for this scenario
var_names["plot_labels"].append(r"$\xi_" + subscript + r"$")
var_names["labels"].append(f"Xi[{n+1}]")
filename = "simo_IDCL_c0_stan.pdf"
filename = "c0_stan.pdf"
filepath = os.path.join(PLOTPATH, filename)
filepath = Plotter.plot_density(
stan_results,
......@@ -530,9 +530,9 @@ filepath = Plotter.plot_density(
#+end_src
#+NAME: simo_IDCL_c0_stan_ppc
#+NAME: c0_stan_ppc
#+CAPTION: Posterior-Predictive check.
#+begin_src python :exports none :results file :tangle ./Scripts/simo_IDCL_c0_stan_ppc.py :noweb yes :return filepath
#+begin_src python :exports none :results file :tangle ./Scripts/c0_stan_ppc.py :noweb yes :return filepath
import numpy as np
<<paper_plotting_header>>
import arviz as az
......@@ -571,7 +571,7 @@ print(stan_data)
filepath = Plotter.plot_ppc(
stan_data,
filename="simo_IDCL_c0_stan_ppc.pdf",
filename="c0_stan_ppc.pdf",
data_pairs={"y": "y_hat"},
num_pp_samples=200,
xlim={0: (-0.5, 2.0)},
......@@ -582,9 +582,9 @@ filepath = Plotter.plot_ppc(
#+end_src
#+NAME: simo_IDCL_c1_stan_ppc
#+NAME: c1_stan_ppc
#+CAPTION: Posterior-Predictive check.
#+begin_src python :exports none :results file :tangle ./Scripts/simo_IDCL_c1_stan_ppc.py :noweb yes :return filepath
#+begin_src python :exports none :results file :tangle ./Scripts/c1_stan_ppc.py :noweb yes :return filepath
import numpy as np
<<paper_plotting_header>>
import arviz as az
......@@ -622,7 +622,7 @@ print(stan_data)
filepath = Plotter.plot_ppc(
stan_data,
filename="simo_IDCL_c1_stan_ppc.pdf",
filename="c1_stan_ppc.pdf",
data_pairs={"y": "y_hat"},
num_pp_samples=200,
xlim={0: (-0.5, 2.0)},
......@@ -633,8 +633,8 @@ filepath = Plotter.plot_ppc(
#+end_src
#+NAME: simo_IDCL_stan_cosimulate_ID_c0
#+begin_src python :results file :exports results :return filename :tangle ./Scripts/simo_IDCL_stan_cosimulate_ID_c0.py :noweb yes
#+NAME: stan_cosimulate_ID_c0
#+begin_src python :results file :exports results :return filename :tangle ./Scripts/stan_cosimulate_ID_c0.py :noweb yes
from collections import OrderedDict
import numpy as np
......@@ -650,7 +650,7 @@ simspec = dict(system='SIMO', Ts=1, ID=IDspec, CL=CLspec, cluster=0, samples=5)
<<paper_simulation>>
# Reuse data from initial simulation experiment for continuity
data = read_from_disc("data_simo_IDCL_c0.pkl")
data = read_from_disc("data_c0.pkl")
u = data["raw_results"]["system"][0].filter(regex="u").values.T
d = data["raw_results"]["system"][0].filter(regex="d").values.T
UD = dict(U=u, D=d)
......@@ -660,7 +660,7 @@ simulator.D = UD["D"]
results = simulator.cosimulate_IDStan(path_predicate="./", name="c0_23")
dfss_oos_ = results["stan"]
df_oos = results["system"]
dfm_oos = results["sindy"]
dfm_oos = results["sindyc"]
a_dfss_oos = []
for sample, df in dfss_oos_.items():
......@@ -688,8 +688,8 @@ filename = Plotter.plot_sectors(
* TODO Stan submodels
#+NAME: simo_IDCL_sindy_stan_code_12
#+begin_src stan :exports none :results none :tangle ./Scripts/simo_IDCL_sindy_stan_code_12.stan
#+NAME: sindyc_stan_code_12
#+begin_src stan :exports none :results none :tangle ./Scripts/sindyc_stan_code_12.stan
functions {
real[] dy_dt(real t, real[] y, real[] xi, real[] params, int[] ncupoly) {
vector[ncupoly[1]] poly;
......@@ -717,7 +717,7 @@ data {
real<lower=0> ts[N-1]; // Sampling instances
int<lower=0> nu; // number of system inputs
int<lower=0> ny; // number of system outputs
int<lower=0> nXi; // number of SINDy model coefficients
int<lower=0> nXi; // number of Sindyc model coefficients
real z_init[1, ny]; // initial model state = `y_init`
real y[N, ny]; // state observations
real u[N-1, nu]; // control inputs
......@@ -782,8 +782,8 @@ generated quantities {
#+end_src
#+NAME: simo_IDCL_sindy_stan_code_23
#+begin_src stan :exports none :results none :tangle ./Scripts/simo_IDCL_sindy_stan_code_23.stan
#+NAME: sindyc_stan_code_23
#+begin_src stan :exports none :results none :tangle ./Scripts/sindyc_stan_code_23.stan
functions {
real[] dy_dt(real t, real[] y, real[] xi, real[] params, int[] ncupoly) {
vector[ncupoly[1]] poly;
......@@ -811,7 +811,7 @@ data {
real<lower=0> ts[N-1]; // Sampling instances
int<lower=0> nu; // number of system inputs
int<lower=0> ny; // number of system outputs
int<lower=0> nXi; // number of SINDy model coefficients
int<lower=0> nXi; // number of Sindyc model coefficients
real z_init[1, ny]; // initial model state = `y_init`
real y[N, ny]; // state observations
real u[N-1, nu]; // control inputs
......@@ -876,8 +876,8 @@ generated quantities {
#+end_src
#+NAME: simo_IDCL_sindy_stan_code_34
#+begin_src stan :exports none :results none :tangle ./Scripts/simo_IDCL_sindy_stan_code_34.stan
#+NAME: sindyc_stan_code_34
#+begin_src stan :exports none :results none :tangle ./Scripts/sindyc_stan_code_34.stan
functions {
real[] dy_dt(real t, real[] y, real[] xi, real[] params, int[] ncupoly) {
vector[ncupoly[1]] poly;
......@@ -905,7 +905,7 @@ data {
real<lower=0> ts[N-1]; // Sampling instances
int<lower=0> nu; // number of system inputs
int<lower=0> ny; // number of system outputs
int<lower=0> nXi; // number of SINDy model coefficients
int<lower=0> nXi; // number of Sindyc model coefficients
real z_init[1, ny]; // initial model state = `y_init`
real y[N, ny]; // state observations
real u[N-1, nu]; // control inputs
......@@ -970,8 +970,8 @@ generated quantities {
#+end_src
#+NAME: simo_IDCL_sindy_stan_code_345
#+begin_src stan :exports none :results none :tangle ./Scripts/simo_IDCL_sindy_stan_code_345.stan
#+NAME: sindyc_stan_code_345
#+begin_src stan :exports none :results none :tangle ./Scripts/sindyc_stan_code_345.stan
functions {
real[] dy_dt(real t, real[] y, real[] xi, real[] params, int[] ncupoly) {
vector[ncupoly[1]] poly;
......@@ -999,7 +999,7 @@ data {
real<lower=0> ts[N-1]; // Sampling instances
int<lower=0> nu; // number of system inputs
int<lower=0> ny; // number of system outputs
int<lower=0> nXi; // number of SINDy model coefficients
int<lower=0> nXi; // number of Sindyc model coefficients
real z_init[1, ny]; // initial model state = `y_init`
real y[N, ny]; // state observations
real u[N-1, nu]; // control inputs
......@@ -1068,8 +1068,8 @@ generated quantities {
#+end_src
#+NAME: simo_IDCL_sindy_stan_code_124
#+begin_src stan :exports none :results none :tangle ./Scripts/simo_IDCL_sindy_stan_code_124.stan
#+NAME: sindyc_stan_code_124
#+begin_src stan :exports none :results none :tangle ./Scripts/sindyc_stan_code_124.stan
functions {
real[] dy_dt(real t, real[] y, real[] xi, real[] params, int[] ncupoly) {
vector[ncupoly[1]] poly;
......@@ -1097,7 +1097,7 @@ data {
real<lower=0> ts[N-1]; // Sampling instances
int<lower=0> nu; // number of system inputs
int<lower=0> ny; // number of system outputs
int<lower=0> nXi; // number of SINDy model coefficients
int<lower=0> nXi; // number of Sindyc model coefficients
real z_init[1, ny]; // initial model state = `y_init`
real y[N, ny]; // state observations
real u[N-1, nu]; // control inputs
......@@ -1166,8 +1166,8 @@ generated quantities {
#+end_src
#+NAME: simo_IDCL_sindy_stan_code_1234
#+begin_src stan :exports none :results none :tangle ./Scripts/simo_IDCL_sindy_stan_code_1234.stan
#+NAME: sindyc_stan_code_1234
#+begin_src stan :exports none :results none :tangle ./Scripts/sindyc_stan_code_1234.stan
functions {
real[] dy_dt(real t, real[] y, real[] xi, real[] params, int[] ncupoly) {
vector[ncupoly[1]] poly;
......@@ -1195,7 +1195,7 @@ data {
real<lower=0> ts[N-1]; // Sampling instances
int<lower=0> nu; // number of system inputs
int<lower=0> ny; // number of system outputs
int<lower=0> nXi; // number of SINDy model coefficients
int<lower=0> nXi; // number of Sindyc model coefficients
real z_init[1, ny]; // initial model state = `y_init`
real y[N, ny]; // state observations
real u[N-1, nu]; // control inputs
......@@ -1454,12 +1454,12 @@ class Identification:
"""
"""
def test_sparsity(ny, msindy, sparsity_threshold):
def test_sparsity(ny, msindyc, sparsity_threshold):
"""
"""
y_msindy = msindy[:, :ny]
nz = np.count_nonzero(y_msindy)
nval = y_msindy.shape[0] * y_msindy.shape[1]
y_msindyc = msindyc[:, :ny]
nz = np.count_nonzero(y_msindyc)
nval = y_msindyc.shape[0] * y_msindyc.shape[1]
if (nz / nval) < sparsity_threshold:
return True
else:
......@@ -1609,7 +1609,7 @@ import arviz as az
class StanInference:
"""Derive a Stan model based on a SINDy model. The latter is used as
"""Derive a Stan model based on a Sindyc model. The latter is used as
grounds to inform the priors.
"""
......@@ -1629,11 +1629,11 @@ class StanInference:
def __init__(
self,
m_SINDy,
m_Sindyc,
data,
cy,
cu,
name="SINDyStan",
name="SindycStan",
iter=1000,
chains=4,
warmup=500,
......@@ -1646,7 +1646,7 @@ class StanInference:
):
"""
"""
self.m = m_SINDy
self.m = m_Sindyc
self.data = data
# self.m_Stan = m_Stan
self.cy, self.cu = cy, cu
......@@ -2477,7 +2477,7 @@ class Simulator(SystemSimulator):
"""
"""
name = "SINDyStan"
name = "SindycStan"
map_model = {
"Xi[0]": "u0",
"Xi[1]": "u1",
......@@ -2548,7 +2548,7 @@ class Simulator(SystemSimulator):
dfm[imodel] = pd.concat(aggregates, axis=1)
return dfm
def combine_sindy(df, aggregation_axis):
def combine_sindyc(df, aggregation_axis):
"""
"""
# Model specific dataframes
......@@ -2594,7 +2594,7 @@ class Simulator(SystemSimulator):
aggregation_axis = 1
df = combine_system(dfs["system"], aggregation_axis)
dfm = combine_sindy(dfs["sindy"], aggregation_axis)
dfm = combine_sindyc(dfs["sindyc"], aggregation_axis)
try:
dfms = combine_stan(dfs["stan"], aggregation_axis)
return df, dfm, dfms
......@@ -2668,7 +2668,7 @@ class Simulator(SystemSimulator):
Args:
dfs (dict): Dictionary with the fields
`sindy: {isample: {imodel}}`.
`sindyc: {isample: {imodel}}`.
x0 (array): Initial state (stacked state and input)
U (array): System excitation (both controlled and uncontrolled)
T (arrray): Timestamps for the simulation horizon
......@@ -2691,15 +2691,15 @@ class Simulator(SystemSimulator):
df_m.loc[:, "y"] = df_m.loc[:, "x_0"]
except KeyError:
breakpoint()
dfs["sindy"][isample][imodel] = df_m
dfs["sindyc"][isample][imodel] = df_m
return dfs
def _prepare_simulation_containers(self):
"""Prepare simulation containers: `dfs` contains fields for the
system response data `system` and the model responses `sindy`.
system response data `system` and the model responses `sindyc`.
"""
dfs = {
"sindy": {
"sindyc": {
isample: {imodel: None for imodel in range(self.mp.nx)}
for isample in range(self.mp.ns)
},
......@@ -2720,7 +2720,7 @@ class Simulator(SystemSimulator):
def cosimulate_ID(self):
"""Perform a cosimulation experiment in-sample or out-of-sample
given the ID data and the identified SINDy models.
given the ID data and the identified Sindyc models.
"""
dfs = self._prepare_simulation_containers()
dfs = self.loop_and_simulate_model(
......@@ -2730,7 +2730,7 @@ class Simulator(SystemSimulator):
def simulate_out_of_sample(self, Tsim=200, UD=None, **kwargs):
"""Perform a cosimulation experiment in-sample or out-of-sample
given the ID data and the identified SINDy models.
given the ID data and the identified Sindyc models.
"""
if UD is None: # No excitation sequence provided
siggen = SignalGenerator(filter=dict(tau=2.5, Ts=self.simspec["Ts"]))
......@@ -3039,7 +3039,7 @@ class Simulator(SystemSimulator):
dfss_oos = dict()
for key, value in dfss_oos_.items():
dfss_oos[key] = value["trajectory"]
results = {"stan": dfss_oos, "system": df_oos, "sindy": dfm_oos}
results = {"stan": dfss_oos, "system": df_oos, "sindyc": dfm_oos}
return results
def _ID(self):
......@@ -3142,7 +3142,7 @@ class Simulator(SystemSimulator):
"""
raise NotImplementedError
def _identify_SINDy(self, data):
def _identify_SINDyc(self, data):
"""Adjust the `data` such that we only identify a model given
meaningful data (such as, only use the single excitation sequence
in the SIMO case).
......@@ -3152,8 +3152,8 @@ class Simulator(SystemSimulator):
data["X"] = X
return data
def identify_SINDy(self, data):
"""Identify a SINDy model given `data`. `data` contains response data
def identify_SINDyc(self, data):
"""Identify a Sindyc model given `data`. `data` contains response data
recorded over several samples `self.mp.ns`.
"""
# Identify one SINDyc model per sample `self.mp.ns`
......@@ -3173,7 +3173,7 @@ class Simulator(SystemSimulator):
break
else:
combineddata = np.vstack([data_["Y"], data_["P"]])
ny = 1 # Number of effective SINDyc outputs
ny = 1 # Number of effective Sindycc outputs
self.identifier.fit(
ny,
combineddata,
......@@ -3196,7 +3196,7 @@ class Simulator(SystemSimulator):
"""
m = msindyc[0][0]
dfs = self.step_response(gain=gain)
df = dfs["sindy"][0] # NOTE Unclear indexing
df = dfs["sindyc"][0] # NOTE Unclear indexing
msindyc_ = msindyc[0] # NOTE Unclear indexing
for imodel in df.keys():
ysteady = df[imodel]["y"].iloc[-steps:].mean()
......@@ -3210,7 +3210,7 @@ class Simulator(SystemSimulator):
@classmethod
def identify_stan(self, df, Xistar, sigma_y_init, name, fitnewmodel=True):
"""Fit a Stan model given the single trajectory dataframe `df`
and the identified SINDy model `Xistar` (such that it provides
and the identified SINDyc model `Xistar` (such that it provides
the coefficients for a linear model `ax + b`, where `b` is
the first coefficient in `Xistar`).
"""
......@@ -3291,7 +3291,7 @@ class Simulator(SystemSimulator):
identifier = ""
for m in mask:
identifier += str(m + 1)
model_file = "./simo_IDCL_sindy_stan_code_{}.stan".format(identifier)
model_file = "./sindyc_stan_code_{}.stan".format(identifier)
print("Using the following model file:")
print(model_file)
......@@ -3352,11 +3352,11 @@ class Simulator(SystemSimulator):
from scipy import stats
dfs = []
for isample, sindy in msindyc.items():
for isample, sindyc in msindyc.items():
try:
dfs.append(sindy[model].iloc[:, cluster])
dfs.append(sindyc[model].iloc[:, cluster])
except np.linalg.LinAlgError:
dfs.append(sindy[model][cluster])
dfs.append(sindyc[model][cluster])
try:
dfs = pd.concat(dfs, axis=1)
......@@ -3381,7 +3381,7 @@ class Simulator(SystemSimulator):
def identify(self, UD=None):
"""Identify a SINDyc model using the class-methods `ID` and
`identify_SINDy`, using inputs provided by respective private methods.
`identify_SINDyc`, using inputs provided by respective private methods.
"""
ID_params = self._ID()
if UD is not None:
......@@ -3392,8 +3392,8 @@ class Simulator(SystemSimulator):
self.uid = U
self.did = D
data = self.ID(**ID_params)
sindy = self.identify_SINDy(self._identify_SINDy(data))
return sindy
sindyc = self.identify_SINDyc(self._identify_SINDyc(data))
return sindyc
@classmethod
def save_inferred_stan_densities(self, data, name):
......@@ -3431,7 +3431,7 @@ class Simulator(SystemSimulator):
df_m = self.simulate_model(
model,
# NOTE Dirty implementation, due to that
# `simulate_model` asks for SINDy-related
# `simulate_model` asks for SINDyc-related
# initial model state, consisting of a
# stacking of state and control input,
# we here use `x0` only partly right!
......@@ -3440,7 +3440,7 @@ class Simulator(SystemSimulator):
T=T,
)
df_m = df_m.rename({"x_0": "y"}, axis=1)
dfs["sindy"][isample][imodel] = df_m
dfs["sindyc"][isample][imodel] = df_m
return dfs
def step_response(self, gain=1.0):
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment