# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# +
import control
import numpy as np
import matplotlib.pyplot as plt
import kontrol.regulator

s = control.tf("s")
k = np.random.random()
q = np.random.randint(1, 100)
wn = np.random.random()
plant = k*wn**2 / (s**2 + wn/q*s + wn**2)
kd = kontrol.regulator.feedback.critical_damping(plant)
regulator = kontrol.regulator.predefined.pid(kd=kd)
ki = kontrol.regulator.feedback.add_integral_control( plant, regulator)
_, _, _, _, ugf_kd, _ = control.stability_margins( regulator*plant, returnall=True)
_, _, _, _, ugf_ki, _ = control.stability_margins( ki/s*plant, returnall=True)

oltf_kd = kd*s*plant
oltf_ki = ki/s*plant
f = np.logspace(-3, 1, 1000)
plt.loglog(f, abs(oltf_kd(1j*2*np.pi*f)))
plt.loglog(f, abs(oltf_ki(1j*2*np.pi*f)))
plt.loglog(f, abs((ki/s*plant.dcgain())(1j*2*np.pi*f)))
plt.vlines(ugf_ki/2/np.pi, min(f), max(f))
# -

ugf_kd/2/np.pi

ugf_ki/2/np.pi

# +
import numpy as np
import scipy.special

import kontrol.sensact

"""Tests for kontrol.sensact.calibration.calibrate"""
# Test method="linear"
xdata = np.linspace(-1, 1, 1000)
m = np.random.random()
c = np.random.random()
ydata = m*xdata + c

## Tests exception
try:
    kontrol.sensact.calibrate(xdata=xdata, ydata=ydata, method="abc")
    raise
except ValueError:
    pass

slope, intercept, linear_range, model = kontrol.sensact.calibrate(
    xdata=xdata, ydata=ydata, method="linear", return_linear_range=True,
    return_model=True)

assert np.allclose([m, c], [slope, intercept])
assert np.allclose(ydata, model(xdata))

# Test methor="erf"
xdata = np.linspace(-3, 3, 1000)
a = 1
b = 1
c = 0
d = 0
ydata = a*scipy.special.erf(b*(xdata-c)) + d
slope, intercept, linear_range, model = kontrol.sensact.calibrate(
    xdata=xdata, ydata=ydata, method="erf", return_linear_range=True,
    return_model=True)

assert np.allclose(
    [model.amplitude, model.slope, model.x_offset, model.y_offset],
    [a, b, c, d], rtol=1e-3, atol=1e-3)
assert np.allclose(model(xdata), ydata, rtol=1e-3, atol=1e-3)
# -

import numpy as np
np.random.random()

print([model.amplitude, model.slope, model.x_offset, model.y_offset],
    [a, b, c, d])

abs(ydata-model(xdata))

# ?np.allclose

model(xdata)

StarcoderdataJupyterScriptsDedupFiltered