示例#1
0
def make_model(data, calculate_derivatives=True):
    """
    constructs SINDy model
    ...

    Parameters
    ----------
    data: Data object
        training data object constructed using Data class
    calculate_derivatives: bool
        if False, precalculated derivative values will be used.
        Otherwise, they will be calculated during training (differentiation method can be specified)

    Returns
    -------
    model: SINDy model object
        trained SINDy model
    """

    optimizer = ps.SR3(threshold=0.01,
                       thresholder='l1',
                       normalize=True,
                       max_iter=1000)  # ?
    feature_lib = ps.PolynomialLibrary(degree=2)  # ?

    model = ps.SINDy(optimizer,
                     feature_library=feature_lib,
                     feature_names=FEATURES + COMMANDS)

    if calculate_derivatives:
        model.fit(x=data.x,
                  u=data.u,
                  t=data.t,
                  multiple_trajectories=data.multiple_trajectories)
    else:
        model.fit(x=data.x,
                  x_dot=data.x_dot,
                  u=data.u,
                  t=data.t,
                  multiple_trajectories=data.multiple_trajectories)

    return model
示例#2
0
import time


# %%
# System auswählen
system = 1 # 1 = volterra, 2 = lorenz, 3 = roessler, 4 = wp
# NN auswerten?
NN = False

poly_order = 2
t_end = 3
th = 0.2 # coef threshold
if (system == 1):
    sys_name = "Volterra"
    p_nom = np.array([[0, 1.3, 0, 0, -0.9, 0], [0, 0, -1.8, 0, 0.8, 0]]).T
    feature_library = ps.PolynomialLibrary(degree=2)
    feature_names=["x", "y"]
    n = 2
elif (system == 2):
    sys_name = "Lorenz"
    p_nom = np.array(   [[0, -10, 10, 0, 0, 0, 0, 0, 0, 0], 
                        [0, 28, -1, 0, 0, 0, -1, 0, 0, 0],
                        [0, 0, 0, -8/3, 0, 1, 0, 0, 0, 0]]).T
    feature_library = ps.PolynomialLibrary(degree=2)
    feature_names=["x", "y", "z"]
    n = 3
elif (system == 3):
    sys_name = "Roessler"
    p_nom = np.array(   [[0.0, 0.0, -1.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                        [ 0.0, 1.0, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
                        [ 0.1, 0.0, 0.0, -5.3, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]]).T
示例#3
0
def fit_model_cb(sender, data):
    df = get_data(cfg.CSV)

    # Get x data
    x_names = get_data(cfg.X_NAMES)
    X = df[x_names].to_numpy()
    add_data(cfg.X, X)

    # Get der data

    # Get input data
    u_names = get_data(cfg.U_NAMES)
    if len(u_names) > 0:
        U = df[u_names].to_numpy()
    else:
        U = None

    add_data(cfg.U, U)

    # Get time data
    if get_value("Method##time") == "Constant Step":
        dt = get_value("Step size##time")
        time = np.arange(0, X.shape[0]) * dt
    else:
        time_channel = get_value("Channel##combo##time")
        if time_channel == None or time_channel == "":
            log_error("Time channel must be selected", logger="logger##main")
            return
        time = df[time_channel].to_numpy()
    add_data(cfg.TIME, time)

    # Get Optimizer
    if get_value("Methods##Optimizers") == "STLSQ":
        threshold = get_value("threshold##optimizers")
        alpha = get_value("alpha##optimizers")
        max_iter = get_value("max_iter##optimizers")
        optimizer = ps.STLSQ(threshold=threshold,
                             alpha=alpha,
                             max_iter=max_iter)
    elif get_value("Methods##Optimizers") == "Lasso":
        alpha = get_value("alpha##optimizers")
        max_iter = get_value("max_iter##optimizers")
        optimizer = Lasso(alpha=alpha, max_iter=max_iter, fit_intercept=False)
    else:
        optimizer = None

    ##############################
    # Feature libraries
    ##############################
    libs = []
    if get_value("Enable##polynomial##libraries") == True:
        degree = get_value("Degree##polynomial##libraries")
        include_interaction = not (get_value("Type##polynomial##libraries")
                                   == "Only states")
        interaction_only = get_value(
            "Type##polynomial##libraries") == "Only interaction"
        include_bias = get_value("Include bias terms##polynomial##libraries")
        log_debug(
            f'degree: {degree}, include_interaction: {include_interaction}, interaction_only: {interaction_only}, include_bias: {include_bias}'
        )
        libs.append(
            ps.PolynomialLibrary(degree=degree,
                                 include_interaction=include_interaction,
                                 interaction_only=interaction_only,
                                 include_bias=include_bias))

    if get_value("Enable##fourier##libraries") == True:
        n_frequencies = get_value("n_frequencies##fourier##libraries")
        include_sin = get_value("Include sin##fourier##libraries")
        include_cos = get_value("Include cos##fourier##libraries")
        try:
            fourierlib = ps.FourierLibrary(n_frequencies=n_frequencies,
                                           include_sin=include_sin,
                                           include_cos=include_cos)
            libs.append(fourierlib)
        except ValueError as err:
            log_error(err, "logger##main")
            return

    if get_value("Enable##identity##libraries") == True:
        libs.append(ps.IdentityLibrary())

    # Handle the case if nothing's selected
    if not libs:
        libs.append(ps.PolynomialLibrary())

    log_debug(libs, logger="logger##main")

    # Get "feature_library" by reducing the "libs" list
    feature_library = functools.reduce(lambda a, b: a + b, libs)
    try:
        model = ps.SINDy(optimizer=optimizer, feature_library=feature_library)
        model.fit(X, t=time, u=U)
        log_info(f"Model fitted.", logger="logger##main")
    except ValueError as err:
        log_error(err, logger="logger##main")
        return

    model_eqs = []
    for i, eq in enumerate(model.equations()):
        model_eqs.append(f"der(x{i}) = {eq}")
    model_text = "\n".join(model_eqs)

    set_value("Score##fitting", model.score(X, time, u=U))
    set_value("Equations##fitting", model_text)
    add_data(cfg.MODEL, model)

    # clear X_fit listbox
    configure_item("X_fit##fitting", items=[])
示例#4
0
    #     lambda x, y: (np.abs(STEERING_MAX*y-x) > np.deg2rad(1)) * np.sign(STEERING_MAX*y-x),
    # ]

    # library_function_names = [
    #     lambda x, y: '(|{}*y-x| > radians(1)) * sign({} * '.format(STEERING_MAX, STEERING_MAX) + y + ' - ' + x + ')',
    # ]

    # custom_library = ps.CustomLibrary(
    #     library_functions=library_functions,
    #     function_names=library_function_names,
    # )

    model_steering = SINDy(
        features=FEATURES,
        commands=COMMANDS,
        feature_library=ps.PolynomialLibrary(degree=1),  # custom_library
        optimizer=ps.STLSQ(threshold=2))

    train_data = Data(train_dir)
    model_steering.fit(train_data)
    model_steering.print()

    # FIT BODY ANGLE MODEL
    FEATURES = ['body_angle_rad']
    COMMANDS = ['speed_m_per_sec', 'steering_angle_rad']
    PRECALCULATED_DERIVATIVES = []

    library_functions = [lambda x, y: x * np.tan(y)]

    library_function_names = [lambda x, y: x + '*' + 'tan(' + y + ')']
示例#5
0
import json
import numpy as np
import sys
import scipy.signal as sig
import matplotlib.pyplot as plt

#%%
sys.path.append(
    "/home/virati/Dropbox/projects/Research/MDD-DBS/Ephys/DBSpace/src/")
import DBSpace as dbo
from DBSpace import nestdict
import DBSpace.control.dyn_osc as DO

optimizer = ps.STLSQ(threshold=0.1, fit_intercept=True)
fourier_library = ps.FourierLibrary()
polynomial_library = ps.PolynomialLibrary()
# linear_library

functions = [lambda x: np.exp(x), lambda x, y: np.sin(x + y)]
lib_custom = ps.CustomLibrary(library_functions=functions)
lib_generalized = GeneralizedLibrary([fourier_library, polynomial_library])


#%%
def load_scc_lfp(pt, condit, downsample=5):
    with open("../../assets/experiments/metadata/Targeting_Conditions.json",
              "r") as file:
        Ephys = json.load(file)

    timeseries = dbo.load_BR_dict(Ephys[pt][condit]["Filename"], sec_offset=0)
    time_lims = Ephys[pt][condit]["Configurations"]["Bilateral"]["Stim"]