Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
S
SINDyc And MCMC Framework
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Wiki
Requirements
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Locked files
Build
Pipelines
Jobs
Pipeline schedules
Test cases
Artifacts
Deploy
Releases
Package registry
Container registry
Model registry
Operate
Environments
Terraform modules
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Code review analytics
Issue analytics
Insights
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
GitLab community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
freba
SINDyc And MCMC Framework
Commits
a8b55cdd
Commit
a8b55cdd
authored
Sep 3, 2020
by
freba
Browse files
Options
Downloads
Patches
Plain Diff
Refactoring: Nomenclature streamlining.
parent
704c190e
No related branches found
No related tags found
No related merge requests found
Changes
1
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
Documentation.org
+120
-120
120 additions, 120 deletions
Documentation.org
with
120 additions
and
120 deletions
Documentation.org
+
120
−
120
View file @
a8b55cdd
...
...
@@ -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-----
jA0EBwMCb
JNQxW1U+m/q0sA6AbkdydQ3++VaS9WKvLpLT4t1SdDwBTIBVCU8hlnH
xgvvdAF+cVx5zaw5mlpRHRIxIxfHwd4HeM0P6Eh1jJ40ilbxmt42OMVRhq5FFoBM
pqx3IbJzasyW3keBR9m7SatptEl+WDgUIft6VMJ/txqJySztsBdEfTlSj42rC7Wf
iNdgncwKbmhiFO4opvMIWK8zmMdpxOpmm8cnerpf6FuWDP9TFvM4hOEhaMe/FS8S
nY7nxaerOqeooGnXwk7pyQEpC/MG72U9QYXdcykiBtKFVy/KnDPKzNpIH/Cyc28i
ql6hUVQ6IgQ/aaTN7yoJy91pQwQaL4amVEpHhA
==
=
XxqX
jA0EBwMCb
CtBH7j5fVrq0sA9AfaIicpdxk+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: sindy
c
_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(msindy
c
):
msindy
c
_ = {}
for imodel in range(simulator.mp.nx):
msindy_[imodel] = []
msindy
c
_[imodel] = []
for isample in range(simulator.simspec["samples"]):
try:
m = msindy[isample][imodel]
m = msindy
c
[isample][imodel]
if isinstance(m, pd.DataFrame):
msindy_[imodel].append(m.iloc[:, 0])
msindy
c
_[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(msindy
c
_[imodel], axis=0)
msindy
c
_[f"df_{imodel}"] = df
return msindy
c
_
def plot_clusterModels(
msindy_,
msindy
c
_,
cluster=0,
true_coefficients=None,
filename="
simo_IDCL_
sindy.pdf",
filename="sindy
c
.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(msindy
c
_, xlabels):
df_0 = msindy
c
_["df_0"]
df_0 = adjust_df(df_0, name="Model 0", xlabels=xlabels)
df_1 = msindy_["df_1"]
df_1 = msindy
c
_["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, _msindy
c
_ in msindy
c
_.items():
df_0, df_1 = _unpack(_msindy
c
_, 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(msindy
c
):
"""Loop over the SINDYc models in `msindy
c
` 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)
msindy
c
(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 msindy
c
.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()
<<sindy
c
_header>>
msindy
c
= 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(msindy
c
=msindy
c
, df=df, dfm=dfm, raw_results=results)
save_to_disc(data, filename="data_c0.pkl")
filepath = plot_clusterModels(
unpack(msindy),
unpack(msindy
c
),
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="sindy
c
_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>>
<<sindy
c
_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)
msindy
c
= 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(msindy
c
=msindy
c
, df=df, dfm=dfm, raw_results=results)
save_to_disc(data, filename="data_c1.pkl")
filepath = plot_clusterModels(
unpack(msindy),
unpack(msindy
c
),
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="sindy
c
_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")
msindy
c
= data["msindy
c
"]
coeff = msindy
c
[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>>
<<sindy
c
_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')
msindy
c
= data['msindy
c
']
Xistar = select_Xi_parsimony_sweep(msindy)
Xistar = select_Xi_parsimony_sweep(msindy
c
)
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["sindy
c
"]
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: sindy
c
_stan_code_12
#+begin_src stan :exports none :results none :tangle ./Scripts/sindy
c
_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 S
INDy
model coefficients
int<lower=0> nXi; // number of S
indyc
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: sindy
c
_stan_code_23
#+begin_src stan :exports none :results none :tangle ./Scripts/sindy
c
_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 S
INDy
model coefficients
int<lower=0> nXi; // number of S
indyc
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: sindy
c
_stan_code_34
#+begin_src stan :exports none :results none :tangle ./Scripts/sindy
c
_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 S
INDy
model coefficients
int<lower=0> nXi; // number of S
indyc
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: sindy
c
_stan_code_345
#+begin_src stan :exports none :results none :tangle ./Scripts/sindy
c
_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 S
INDy
model coefficients
int<lower=0> nXi; // number of S
indyc
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: sindy
c
_stan_code_124
#+begin_src stan :exports none :results none :tangle ./Scripts/sindy
c
_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 S
INDy
model coefficients
int<lower=0> nXi; // number of S
indyc
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: sindy
c
_stan_code_1234
#+begin_src stan :exports none :results none :tangle ./Scripts/sindy
c
_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 S
INDy
model coefficients
int<lower=0> nXi; // number of S
indyc
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, msindy
c
, sparsity_threshold):
"""
"""
y_msindy = msindy[:, :ny]
nz = np.count_nonzero(y_msindy)
nval = y_msindy.shape[0] * y_msindy.shape[1]
y_msindy
c
= msindy
c
[:, :ny]
nz = np.count_nonzero(y_msindy
c
)
nval = y_msindy
c
.shape[0] * y_msindy
c
.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 S
INDy
model. The latter is used as
"""Derive a Stan model based on a S
indyc
model. The latter is used as
grounds to inform the priors.
"""
...
...
@@ -1629,11 +1629,11 @@ class StanInference:
def __init__(
self,
m_S
INDy
,
m_S
indyc
,
data,
cy,
cu,
name="S
INDy
Stan",
name="S
indyc
Stan",
iter=1000,
chains=4,
warmup=500,
...
...
@@ -1646,7 +1646,7 @@ class StanInference:
):
"""
"""
self.m = m_S
INDy
self.m = m_S
indyc
self.data = data
# self.m_Stan = m_Stan
self.cy, self.cu = cy, cu
...
...
@@ -2477,7 +2477,7 @@ class Simulator(SystemSimulator):
"""
"""
name = "S
INDy
Stan"
name = "S
indyc
Stan"
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_sindy
c
(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_sindy
c
(dfs["sindy
c
"], 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}}`.
`sindy
c
: {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["sindy
c
"][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 `sindy
c
`.
"""
dfs = {
"sindy": {
"sindy
c
": {
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 S
INDy
models.
given the ID data and the identified S
indyc
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 S
INDy
models.
given the ID data and the identified S
indyc
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, "sindy
c
": dfm_oos}
return results
def _ID(self):
...
...
@@ -3142,7 +3142,7 @@ class Simulator(SystemSimulator):
"""
raise NotImplementedError
def _identify_SINDy(self, data):
def _identify_SINDy
c
(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 S
INDy
model given `data`. `data` contains response data
def identify_SINDy
c
(self, data):
"""Identify a S
indyc
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 S
INDy
c outputs
ny = 1 # Number of effective S
indyc
c 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["sindy
c
"][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 SINDy
c
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 = "./sindy
c
_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, sindy
c
in msindyc.items():
try:
dfs.append(sindy[model].iloc[:, cluster])
dfs.append(sindy
c
[model].iloc[:, cluster])
except np.linalg.LinAlgError:
dfs.append(sindy[model][cluster])
dfs.append(sindy
c
[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_SINDy
c
`, 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
sindy
c
= self.identify_SINDy
c
(self._identify_SINDy
c
(data))
return sindy
c
@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 SINDy
c
-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["sindy
c
"][isample][imodel] = df_m
return dfs
def step_response(self, gain=1.0):
...
...
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment