<jupyter_start><jupyter_text>Mass-Spring-System<jupyter_code># Use ODEINT to solve the differential equations defined by the vector field
from scipy.integrate import odeint

def vectorfield(w, t, p):
    """
    Defines the differential equations for the coupled spring-mass system.

    Arguments:
        w :  vector of the state variables:
                  w = [x1,y1,x2,y2]
        t :  time
        p :  vector of the parameters:
                  p = [m1,m2,k1,k2,L1,L2,b1,b2]
    """
    x1, v1, x2, v2, x3, v3 = w
    m, k, kp, d, u1, u2, dist = p

    # Create f = (x1',y1',x2',y2'):
    f = [v1,
         (k * ((-2 * x1) + x2) + kp * (-x1 ** 3 + (x2 - x1) ** 3) + d * (v2-2*v1)) / m + u1,
         v2,
         (k * (x1 - (2 * x2) + x3) + kp * ((x3 - x2) ** 3 - (x2 - x1) ** 3) + d * (v1-2*v2+v3)) / m + u2,
         v3,
         (k * (x2 - x3) + kp * ((x2 - x3) ** 3) + d* (v2-v3)) / m + dist]
    return f
num_rollouts= 1
# Masses:
m = 0.5 
# Spring constants
kp = 63.5
k = 217.0
#damping constant
d= 0.15
# ODE solver parameters
abserr = 1.0e-8
relerr = 1.0e-6

num_data= 100003
interval= 0.001
stoptime = interval*(num_data)
np.random.seed(98)
hist= np.zeros((1,15))

for roll in range(1):
    act1= 2000*(np.random.rand(num_data)-0.5)
    act2= 2000*(np.random.rand(num_data)-0.5)
    dist = 1000*(np.random.rand(num_data)-0.5)
    #Initial states
    w0= np.zeros((1,6))
    #w0 = np.random.randn(1,6) 
    w0= w0.flatten()
    prev = [[w0[0],w0[2],w0[4]]]
    # Pack up the parameters and initial conditions:
    p = [m, k, kp, d, act1[0], act2[0], dist[0]]
    # Call the ODE solver.
    t1= np.array([0,interval])
    wsol1 = odeint(vectorfield, w0, t1, args=(p,),
            atol=abserr, rtol=relerr)
    wsol1 = wsol1.flatten()
    wcurr = np.array([wsol1[6:]])
    w0=wsol1[6:]
    prevv= prev
    prev = [[w0[0],w0[2],w0[4]]]
    # Pack up the parameters and initial conditions:
    p = [m, k, kp, d, act1[1], dist[1], act2[1]]
    # Call the ODE solver.
    t2= np.array([0+interval,interval+interval])
    wsol1 = odeint(vectorfield, w0, t2, args=(p,),
            atol=abserr, rtol=relerr)
    wsol1 = wsol1.flatten()
    wcurr = np.array([wsol1[6:]])
    w0=wsol1[6:]
    curr = np.hstack((prevv, prev, np.array([[act1[1]]]),np.array([[dist[1]]]),np.array([[act2[1]]]),wcurr))
    hist= np.vstack((hist, curr))
   
    lag=2
    for ts in range(num_data-lag):
        prevv = prev
        t = np.array([stoptime * float(ts+lag) / (num_data), stoptime * float(ts + lag + 1) / (num_data)])
        p = [m, k, kp, d, act1[ts+lag],  dist[ts+lag], act2[ts+lag]]
        # Call the ODE solver.
        wsol1 = odeint(vectorfield, w0, t, args=(p,),
            atol=abserr, rtol=relerr)
        wsol1 = wsol1.flatten()
        w0 = wsol1[6:]
        prev = np.array([[wsol1[0],wsol1[2],wsol1[4]]])
        action= [act1[ts+lag],act2[ts+lag]]
        new = np.hstack((prevv,prev,np.array([[act1[ts+lag]]]),np.array([[dist[ts+lag]]]),np.array([[act2[ts+lag]]]),np.array([w0])))
        hist = np.vstack((hist, new))
hist=pd.DataFrame(data=hist,columns =["prev11", "prev22","prev33","prev1","prev2","prev3","u1","dist.","u2","x1", "v1", "x2", "v2", "x3", "v3"])
df=hist[1:][{"u1","dist.","u2","prev11","prev22","prev33","prev1","prev2","prev3","x1", "v1", "x2", "v2", "x3", "v3"}]
df = df[['u1','dist.','u2',"prev11","prev22","prev33","prev1","prev2","prev3",'x1','v1','x2','v2','x3','v3']]
df
plot_cols = ['v1', 'v3']
plot_features = hist[plot_cols][:]
_ = plot_features.plot(subplots=True)
NN_in= df[{"u1","u2","dist."}]
NN_in= NN_in[['u1','dist.','u2']].shift(-1)
NN_label= df[{"x1", "x3"}]
NN_label= NN_label[ ["x1", "x3"] ]
NN_previous= df[{"prev11","prev33","prev1","prev3"}]
NN_previous= NN_previous[ ["prev11","prev33"] ]
diff1= df["x1"] - df["prev1"]
diff3= df["x3"] - df["prev3"]
diff21= df["x1"] - df["prev11"]
diff23= df["x3"] - df["prev33"]
df.insert(7, "diff21", diff21)
df.insert(8, "diff23", diff23)
df.insert(9, "diff1", diff1)
df.insert(10, "diff3", diff3)
bothdiff= df[["diff1","diff3"]].shift(0)
bothdiff2= df[["diff21","diff23"]].shift(0)
frames = [NN_in,bothdiff2, NN_label, NN_previous, bothdiff]
df = pd.concat(frames, axis=1)
#x1_ = df[{'x1'}]
#x3_ = df[{'x3'}]
#prev111 = x1_.shift(3)
#prev333 = x3_.shift(3)
#prev1111 = x1_.shift(4)
#prev3333 = x3_.shift(4)
#df.insert(3,"prev1111",prev1111)
#df.insert(4,"prev3333",prev3333)
#df.insert(3,"prev111",prev111)
#df.insert(4,"prev333",prev333)
#diff31= df["x1"] - df["prev111"]
#diff33= df["x3"] - df["prev333"]
#df=df.drop(columns=["prev111","prev333"])
#df.insert(3, "diff31", diff31)
#df.insert(4, "diff33", diff33)
af=df.dropna()
df= af[ ["u1","dist.","u2", "x1", "x3","diff21","diff23","diff1","diff3"] ]
df
ww= df[0:5000]
ww.to_csv('u1000damptestdata5k_0.001ssim.csv',index=False)

ww
#max(df[{'diff1'}].values)
plot_cols = ['u1','dist.','u2']
plot_features = df[plot_cols][1:500]
_ = plot_features.plot(subplots=True)
plot_states = ['x1', 'v1', 'x2', 'v2', 'x3', 'v3']
plot_states = ['x1', 'x3']
plot_features = df[plot_states][:]
_ = plot_features.plot(subplots=True)
plot_out= ['x1','x3']
plot_features = df[plot_out][1:5000]
_ = plot_features.plot(subplots=True)
aaa= pd.read_csv('nodistreinf_startsim40000_train500-250_batch16sim300-1000-1000-pen10xcost.csv')
aaa
plt.figure(figsize=(8,3))
fig, axs = plt.subplots(2, sharex=True,figsize=(14,5))
x= range(20001)
params = {'mathtext.default': 'regular' }          
plt.rcParams.update(params)
y=aaa.iloc[:20001,3].values
z=aaa.iloc[:20001,4].values
fig.suptitle('Damped System Trajectory with a Maximum $\Delta$u of 500 N')
axs[0].plot(x, y )
axs[1].plot(x, z)
axs[0].set_ylabel("x1 (m)") 
axs[1].set_ylabel("x3 (m)") 
axs[1].set_xlabel("Time (ms)") 
#axs[0].set_title("Position (m)") 
#axs[0].plot(range(5000), aaa.iloc[:,3].values, 'B')
plt.savefig('reinfdampuctr.png', dpi=300)
#max(df[{'diff1'}].values)
plot_cols = ['u1','dist.','u2']
plot_features = aaa[plot_cols][1:500]
_ = plot_features.plot(subplots=True)
plot_states = ['x1', 'v1', 'x2', 'v2', 'x3', 'v3']
plot_states = ['x1', 'x3']
plot_features = aaa[plot_states][:]
_ = plot_features.plot(subplots=True)
plot_out= ['x1','x3']
plot_features =aaa[plot_out][1:5000]
_ = plot_features.plot(subplots=True)
max(aaa.iloc[:,2])
df.mean()
df.std()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.23285054910074804, 'fraction_numerical': 0.08562788476842273, 'mean_word_length': 4.2106135986733, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '336896', 'license': 'Apache-2.0', 'n_tokens_mistral': 3021, 'n_tokens_neox': 2816, 'n_words': 498, 'path': 'data_generation/testdatageneration.ipynb', 'repo_name': 'stephenadhi/nn-mpc', 'size': '6283'}