#!/bin/python3
"""============================================================================
sine basis linear regression script
Ramkumar
Sun Mar 23 05:11:57 PM IST 2025
============================================================================"""
# importing needed modules
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import qmc
from numpy.polynomial import chebyshev as C
from scipy.optimize import minimize
from scipy.interpolate import CubicSpline
#==============================================================================
# function definitions for sampling
def RandomSampling(n):
return np.random.sample(n)
def EquispacedSampling(n):
return np.linspace(0,1,n)
def LatinHypercubeSampling(n):
sampler = qmc.LatinHypercube(d=1)
return sampler.random(n).flatten()
def TrueFunction(x):
return (6*x-2)**2*np.sin(12*x-4)
# sampling data
N = 5
RS_5 = RandomSampling(N)
ES_5 = EquispacedSampling(N)
LHS_5 = LatinHypercubeSampling(N)
N = 10
RS_10 = RandomSampling(N)
ES_10 = EquispacedSampling(N)
LHS_10 = LatinHypercubeSampling(N)
N = 15
RS_15 = RandomSampling(N)
ES_15 = EquispacedSampling(N)
LHS_15 = LatinHypercubeSampling(N)
x = np.linspace(0,1,101)
cs_5_2 = CubicSpline(ES_5,TrueFunction(ES_5))
y_sample_5_2 = cs_5_2(ES_5)
y_pred_5_2 = cs_5_2(x)
cs_10_2 = CubicSpline(ES_10,TrueFunction(ES_10))
y_sample_10_2 = cs_10_2(ES_10)
y_pred_10_2 = cs_10_2(x)
cs_15_2 = CubicSpline(ES_15,TrueFunction(ES_15))
y_sample_15_2 = cs_15_2(ES_15)
y_pred_15_2 = cs_15_2(x)
# plotting graphs
plt.rcParams.update({"font.size":10})
fig,ax = plt.subplots(3,1,figsize=(12,6),sharex=True,sharey=True)
x = np.linspace(0,1,101)
ax = ax.flatten()
# degree 2
ax[0].plot(x,TrueFunction(x),'-k',label = "True function")
ax[0].plot(x,y_pred_5_2,'-r',label = "predicted")
ax[0].plot(ES_5,y_sample_5_2,'og',label="sample")
ax[0].grid()
# ax[0].set_xlabel("data points")
ax[0].set_ylabel("y")
ax[0].set_title(r"N = 5")
ax[1].plot(x,TrueFunction(x),'-k',label = "True function")
ax[1].plot(x,y_pred_10_2,'-r',label = "predicted")
ax[1].plot(ES_10,y_sample_10_2,'og',label="sample")
ax[1].grid()
ax[1].legend(loc=[1.01,0.5])
# ax[1].set_xlabel("data points")
ax[1].set_ylabel("y")
ax[1].set_title(r"N = 10")
ax[2].plot(x,TrueFunction(x),'-k',label = "True function")
ax[2].plot(x,y_pred_15_2,'-r',label = "predicted")
ax[2].plot(ES_15,y_sample_15_2,'og',label="sample")
ax[2].grid()
ax[2].set_xlabel("x")
ax[2].set_ylabel("y")
ax[2].set_title(r"N = 15")
# plt.savefig("spline.png",dpi=150,bbox_inches="tight")
fig.suptitle("Cubic Spline")
plt.show()
#==============================================================================