<jupyter_start><jupyter_text>Global PLSR<jupyter_code>Total_X_data = pd.read_csv("X_data.csv")
Total_Y_data = pd.read_csv("PHN_aggregatd.csv")

Total_X_data.drop("Unnamed: 0", axis=1, inplace=True)
Total_Y_data.drop(["Unnamed: 0", "n_ap"], axis=1, inplace=True)
X_test = Total_X_data[:1068]
Y_test = Total_Y_data[:1068]
X_data = Total_X_data[1068:]
Y_data = Total_Y_data[1068:]
Total_Y_data<jupyter_output><empty_output><jupyter_text>Scaling and splitting the X_data and Y_data<jupyter_code>scaler_x = StandardScaler().fit(X_data)
scaler_y = StandardScaler().fit(Y_data)

X_data = scaler_x.transform(X_data)
Y_data = scaler_y.transform(Y_data)
X_data
X_train, X_val, y_train, y_val = train_test_split(X_data,Y_data,test_size=0.2,random_state=357, shuffle=True)<jupyter_output><empty_output><jupyter_text>Finding optimal number of PLS components for global Model<jupyter_code>def optimise_pls_cv(X, y, n_comp):
    # Define PLS object
    pls = PLSRegression(n_components=n_comp, max_iter=1000)

    # Cross-validation
    y_cv = cross_val_predict(pls, X, y, cv=10)

    # Calculate scores
    r2 = r2_score(y, y_cv)
    mse = mean_squared_error(y, y_cv)
   
    
    return (y_cv, r2, mse)
# test with 15 components
r2s = []
mses = []
rpds = []
xticks = np.arange(1, 15)
for n_comp in xticks:
    y_cv, r2, mse = optimise_pls_cv(X_data, Y_data, n_comp)
    r2s.append(r2)
    mses.append(mse)
   

# Plot the mses
def plot_metrics(vals, ylabel, objective):
    with plt.style.context('ggplot'):
        plt.plot(xticks, np.array(vals), '-v', color='blue', mfc='blue')
        if objective=='min':
            idx = np.argmin(vals)
        else:
            idx = np.argmax(vals)
        plt.plot(xticks[idx], np.array(vals)[idx], 'P', ms=10, mfc='red')

        plt.xlabel('Number of PLS components')
        plt.xticks = xticks
        plt.ylabel(ylabel)
        plt.title('PLS')

    plt.show()
plot_metrics(mses, 'MSE', 'min')
plot_metrics(r2s, 'R2', 'max')<jupyter_output><empty_output><jupyter_text>Predictions from global PLSR<jupyter_code>global_pls = PLSRegression(n_components=8)

# Fit
global_pls.fit(X_data, Y_data)

# Cross-validation
y_cv = cross_val_predict(global_pls, X_data, Y_data, cv=10)

# Calculate scores
score = r2_score(Y_data, y_cv)
mse = mean_squared_error(Y_data, y_cv)
score
mse
##predictions
X_test = Total_X_data[:1068]
Y_test = Total_Y_data[:1068]
Test_X_data = scaler_x.transform(X_test)
Test_Y_data = scaler_y.transform(Y_test)
ypred2 = global_pls.predict(Test_X_data)
print(r2_score(Test_Y_data,ypred2))
Total_Y_data.columns
names = ['first_ap_time', 'first_ap_amp', 'first_ap_width']
results_df = pd.DataFrame()
ypred = global_pls.predict(Test_X_data)

extra_results_df = pd.DataFrame([r2_score(Test_Y_data[:,i],ypred[:,i]) for i in range(len(names))],index=names,columns=['r2_score'])
results_df = pd.concat([results_df,extra_results_df],axis=1)
results_df<jupyter_output><empty_output><jupyter_text>Getting global X and Y scores<jupyter_code>X_scores = global_pls.x_scores_
Y_scores = global_pls.y_scores_
X_scores.shape
Y_scores.shape
#initial plot
plt.scatter(X_scores[:,0], X_scores[:,1])
#### yaha  bata suru<jupyter_output><empty_output><jupyter_text>Clustering with X_scores<jupyter_code>from sklearn.cluster import KMeans
distortions = []
for i in range(1, 15):
    km = KMeans(n_clusters=i, 
                init='k-means++', 
                n_init=10, 
                max_iter=300, 
                random_state=0)
    y_km = km.fit(X_scores)
    distortions.append(km.inertia_)
plt.plot(range(1, 15), distortions, marker='o')
plt.xlabel('Number of clusters')
plt.ylabel('Distortion')
plt.tight_layout()

from yellowbrick.cluster import KElbowVisualizer
model = KMeans()
visualizer = KElbowVisualizer(model, k=(2,12))

visualizer.fit(X_scores)        # Fit the data to the visualizer
visualizer.show()
from sklearn.metrics import silhouette_samples
from matplotlib import cm

km = KMeans(n_clusters=6, 
            init='k-means++', 
            n_init=10, 
            max_iter=500,
            tol=1e-04,
            random_state=377)
y_km = km.fit_predict(X_scores)

cluster_labels = np.unique(y_km)
n_clusters = cluster_labels.shape[0]
silhouette_vals = silhouette_samples(X_scores, y_km, metric='euclidean')
y_ax_lower, y_ax_upper = 0, 0
yticks = []
for i, c in enumerate(cluster_labels):
    c_silhouette_vals = silhouette_vals[y_km == c]
    c_silhouette_vals.sort()
    y_ax_upper += len(c_silhouette_vals)
    color = cm.jet(float(i) / n_clusters)
    plt.barh(range(y_ax_lower, y_ax_upper), c_silhouette_vals, height=1.0, 
             edgecolor='none', color=color)

    yticks.append((y_ax_lower + y_ax_upper) / 2.)
    y_ax_lower += len(c_silhouette_vals)
    
silhouette_avg = np.mean(silhouette_vals)
plt.axvline(silhouette_avg, color="red", linestyle="--") 

plt.yticks(yticks, cluster_labels + 1)
plt.ylabel('Cluster')
plt.xlabel('Silhouette coefficient')

plt.tight_layout()

km = KMeans(n_clusters=6, 
            init='k-means++', 
            n_init=10, 
            max_iter=300,
            tol=1e-04,
            random_state=0)

y_km = km.fit_predict(Y_scores)


plt.scatter(X_scores[y_km == 0, 0],
            X_scores[y_km == 0, 1],
            s=50, c='lightgreen',
            marker='s', edgecolor='black',
            label='Cluster 1')
plt.scatter(X_scores[y_km == 1, 0],
           X_scores[y_km == 1, 1],
            s=50, c='orange',
            marker='o', edgecolor='black',
            label='Cluster 2')
plt.scatter(X_scores[y_km == 2, 1],
           X_scores[y_km == 2, 2],
            s=50, c='lightblue',
            marker='o', edgecolor='black',
            label='Cluster 3')
plt.scatter(X_scores[y_km == 3, 2],
           X_scores[y_km == 3, 3],
            s=50, c='yellow',
            marker='o', edgecolor='black',
            label='Cluster 4')
plt.scatter(X_scores[y_km == 4, 3],
           X_scores[y_km == 4, 4],
            s=50, c='maroon',
            marker='o', edgecolor='black',
            label='Cluster 4')
plt.scatter(km.cluster_centers_[:, 0],
            km.cluster_centers_[:, 1],
            s=250, marker='*',
            c='red', edgecolor='black',
            label='Centroids')
plt.legend(scatterpoints=1)
plt.grid()
plt.tight_layout()
#plt.savefig('images/11_02.png', dpi=300)
plt.show()
y_km
X_score_df = pd.DataFrame(X_scores)
X_score_df
X_score_df['Cluster'] = y_km
X_cluster_df = X_score_df
X_cluster_df<jupyter_output><empty_output><jupyter_text>Creating four dataframes having different cluster labels<jupyter_code>X_cluster_1 = X_cluster_df.loc[X_cluster_df['Cluster'] == 1]
X_cluster_0 = X_cluster_df.loc[X_cluster_df['Cluster'] == 0]
X_cluster_2 = X_cluster_df.loc[X_cluster_df['Cluster'] == 2]
X_cluster_3 = X_cluster_df.loc[X_cluster_df['Cluster'] == 3]
X_cluster_4 = X_cluster_df.loc[X_cluster_df['Cluster'] == 4]
X_cluster_5 = X_cluster_df.loc[X_cluster_df['Cluster'] == 5]
X_cluster_5.shape
X_cluster_1.head()<jupyter_output><empty_output><jupyter_text>Creating new X and Y dataset for local PLSR  PLSR 0<jupyter_code>X_cluster_0 = pd.DataFrame(X_cluster_0)
Y_data= pd.DataFrame(Y_data)
X_data = pd.DataFrame(X_data)
Y_data_0= Y_data[Y_data.index.isin(X_cluster_0.index)]
X_data_0= X_data[X_data.index.isin(X_cluster_0.index)]
X_data_0
Y_data_0<jupyter_output><empty_output><jupyter_text>Following similar procedure for creating X and Y dataset for PLSR 1<jupyter_code>X_cluster_1 = pd.DataFrame(X_cluster_1)
Y_data_1= Y_data[Y_data.index.isin(X_cluster_1.index)]
X_data_1= X_data[X_data.index.isin(X_cluster_1.index)]<jupyter_output><empty_output><jupyter_text>Following similar procedure for creating X and Y dataset for PLSR 2 ,3 and 4<jupyter_code>X_cluster_2 = pd.DataFrame(X_cluster_2)
Y_data_2= Y_data[Y_data.index.isin(X_cluster_2.index)]
X_data_2= X_data[X_data.index.isin(X_cluster_2.index)]
X_cluster_3 = pd.DataFrame(X_cluster_3)
Y_data_3= Y_data[Y_data.index.isin(X_cluster_3.index)]
X_data_3= X_data[X_data.index.isin(X_cluster_3.index)]
X_cluster_4 = pd.DataFrame(X_cluster_4)
Y_data_4= Y_data[Y_data.index.isin(X_cluster_4.index)]
X_data_4= X_data[X_data.index.isin(X_cluster_4.index)]
X_cluster_5 = pd.DataFrame(X_cluster_5)
Y_data_5= Y_data[Y_data.index.isin(X_cluster_5.index)]
X_data_5= X_data[X_data.index.isin(X_cluster_5.index)]<jupyter_output><empty_output><jupyter_text>Training PLSR 0,1,2,3 ,4 and 5<jupyter_code>## Training the whole
local_pls_0 = PLSRegression(n_components=8)

# Fit
local_pls_0.fit(X_data_0, Y_data_0)

# Cross-validation
y_cv = cross_val_predict(local_pls_0, X_data_0, Y_data_0, cv=10)

# Calculate scores
score = r2_score(Y_data_0, y_cv)
mse = mean_squared_error(Y_data_0, y_cv)
score
mse<jupyter_output><empty_output><jupyter_text>Training PLSR 1<jupyter_code>## Training whole
local_pls_1 = PLSRegression(n_components=8)

# Fit
local_pls_1.fit(X_data_1, Y_data_1)

# Cross-validation
y_cv = cross_val_predict(local_pls_1, X_data_1, Y_data_1, cv=10)

# Calculate scores
score = r2_score(Y_data_1, y_cv)
mse = mean_squared_error(Y_data_1, y_cv)
score
mse<jupyter_output><empty_output><jupyter_text>Training PLSR 2<jupyter_code>local_pls_2 = PLSRegression(n_components=8)

# Fit
local_pls_2.fit(X_data_2, Y_data_2)

# Cross-validation
y_cv = cross_val_predict(local_pls_2, X_data_2, Y_data_2, cv=10)

# Calculate scores
score = r2_score(Y_data_2, y_cv)
mse = mean_squared_error(Y_data_2, y_cv)
score
mse<jupyter_output><empty_output><jupyter_text>Training PLSR 3<jupyter_code>local_pls_3 = PLSRegression(n_components=8)

# Fit
local_pls_3.fit(X_data_3, Y_data_3)

# Cross-validation
y_cv = cross_val_predict(local_pls_3, X_data_3, Y_data_3, cv=10)

# Calculate scores
score = r2_score(Y_data_3, y_cv)
mse = mean_squared_error(Y_data_3, y_cv)
score
mse<jupyter_output><empty_output><jupyter_text>Training PLSR 4<jupyter_code>local_pls_4 = PLSRegression(n_components=8)

# Fit
local_pls_4.fit(X_data_4, Y_data_4)

# Cross-validation
y_cv = cross_val_predict(local_pls_4, X_data_4, Y_data_4, cv=10)

# Calculate scores
score = r2_score(Y_data_4, y_cv)
mse = mean_squared_error(Y_data_4, y_cv)
score
mse<jupyter_output><empty_output><jupyter_text>Training PLSR 5<jupyter_code>X_data_5.shape
local_pls_5 = PLSRegression(n_components=8)

# Fit
local_pls_5.fit(X_data_5, Y_data_5)

# Cross-validation
y_cv = cross_val_predict(local_pls_5, X_data_5, Y_data_5, cv=10)

# Calculate scores
score = r2_score(Y_data_5, y_cv)
mse = mean_squared_error(Y_data_5, y_cv)
score
mse<jupyter_output><empty_output><jupyter_text>HCPLSR Predictions<jupyter_code>## scaling the test data from global scaler
X_test = Total_X_data[:1068]
Y_test = Total_Y_data[:1068]
Test_X_data = scaler_x.transform(X_test)
## predicted y_data
ypred_global = global_pls.predict(Test_X_data)<jupyter_output><empty_output><jupyter_text>Classification Algorithm with X<jupyter_code>target = X_cluster_df.Cluster
X_cluster_df
data =X_cluster_df.drop(["Cluster"], axis=1)
data
train_data, test_data, train_labels, test_labels = train_test_split(data, target, random_state=0, shuffle=True, test_size=0.3)
from sklearn.pipeline import Pipeline
from sklearn.externals import joblib
from sklearn.linear_model import LogisticRegression
from sklearn.decomposition import PCA
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn import svm
from sklearn import tree


# Construct some pipelines
pipe_lr = Pipeline([('scl', StandardScaler()),

			('clf', LogisticRegression(random_state=42))])

pipe_svm = Pipeline([('scl', StandardScaler()),
                    

			('clf', svm.SVC(random_state=42))])

pipe_dt = Pipeline([

			('clf', tree.DecisionTreeClassifier(random_state=42))])

pipe_KNN = Pipeline([('scl', StandardScaler()),

			('clf', KNeighborsClassifier(n_neighbors=3))])

pipe_RF = Pipeline([

			('clf', RandomForestClassifier(random_state=42))])


# List of pipelines for ease of iteration
pipelines = [pipe_lr, pipe_svm, pipe_dt, pipe_KNN, pipe_RF]
			
# Dictionary of pipelines and classifier types for ease of reference
pipe_dict = {0: 'Logistic Regression', 1: 'Support Vector Machine', 2: 'Decision Tree', 3:'KNN', 4:'Random Forest'}

# Fit the pipelines
for pipe in pipelines:
	pipe.fit(train_data, train_labels)

# Compare accuracies
for idx, val in enumerate(pipelines):
	print('%s pipeline test accuracy: %.3f' % (pipe_dict[idx], val.score(test_data, test_labels)))

# Identify the most accurate model on test data
best_acc = 0.0
best_clf = 0
best_pipe = ''
for idx, val in enumerate(pipelines):
	if val.score(test_data, test_labels) > best_acc:
		best_acc = val.score(test_data, test_labels)
		best_pipe = val
		best_clf = idx
print('Classifier with best accuracy: %s' % pipe_dict[best_clf])<jupyter_output>C:\Users\Ashesh\Anaconda3\lib\site-packages\sklearn\externals\joblib\__init__.py:15: FutureWarning: sklearn.externals.joblib is deprecated in 0.21 and will be removed in 0.23. Please import this functionality directly from joblib, which can be installed with: pip install joblib. If this warning is raised when loading pickled models, you may need to re-serialize those models with scikit-learn 0.21+.
  warnings.warn(msg, category=FutureWarning)<jupyter_text>Feature Selection and Hyperparameter Tuning RandomForest<jupyter_code>from mlxtend.feature_selection import SequentialFeatureSelector as SFS
from mlxtend.plotting import plot_sequential_feature_selection as plot_sfs
rf = RandomForestClassifier()
from sklearn.model_selection import GridSearchCV
# Create the parameter grid based on the results of random search 
param_grid = {
    'bootstrap': [True],
    'max_depth': [80, 90, 100, 110],
    'max_features': [2, 3],
    'min_samples_leaf': [3, 4, 5],
    'min_samples_split': [8, 10, 12],
    'n_estimators': [100, 200, 300, 1000]
}
# Create a based model
rf = RandomForestClassifier()
# Instantiate the grid search model
grid_search = GridSearchCV(estimator = rf, param_grid = param_grid, 
                          cv = 5, n_jobs = -1, verbose = 2)
grid_search.fit(train_data, train_labels)
grid_search.best_params_
## fitting RF model with following features
rf_bp = RandomForestClassifier(bootstrap ='True',
 max_depth= 90,
 max_features= 3,
 min_samples_leaf = 3,
 min_samples_split = 10,
 n_estimators = 300)
rf_bp.fit(train_data, train_labels)
forest_pred = rf_bp.predict(test_data)
from sklearn.metrics import accuracy_score
from sklearn.metrics import accuracy_score
accuracy_score(forest_pred, test_labels)<jupyter_output><empty_output><jupyter_text>Training whole data<jupyter_code>rf_whole = RandomForestClassifier(bootstrap ='True',
 max_depth= 110,
 max_features= 2,
 min_samples_leaf = 3,
 min_samples_split = 8,
 n_estimators = 200)
rf_whole.fit(data, target)<jupyter_output><empty_output><jupyter_text>predicting class labels<jupyter_code>global_x_weights = global_pls.x_weights_
Test_X_data
X_scores_proj = np.dot(Test_X_data,global_x_weights)
X_scores_proj
pred_rf = rf_whole.predict(X_scores_proj)
pred_rf.shape
## Appending this to the projected_X_scores
projected_X_scores = pd.DataFrame(X_scores_proj)
projected_X_scores['Cluster'] = pred_rf
projected_X_scores<jupyter_output><empty_output><jupyter_text>Extracting class label 0,1,2,3,4 and 5<jupyter_code>X_scores_0 = projected_X_scores.loc[projected_X_scores['Cluster'] == 0].drop(["Cluster"],axis=1)
X_scores_1 = projected_X_scores.loc[projected_X_scores['Cluster'] == 1].drop(["Cluster"],axis=1)
X_scores_2 = projected_X_scores.loc[projected_X_scores['Cluster'] == 2].drop(["Cluster"],axis=1)
X_scores_3 = projected_X_scores.loc[projected_X_scores['Cluster'] == 3].drop(["Cluster"],axis=1)
X_scores_4 = projected_X_scores.loc[projected_X_scores['Cluster'] == 4].drop(["Cluster"],axis=1)
X_scores_5 = projected_X_scores.loc[projected_X_scores['Cluster'] == 5].drop(["Cluster"],axis=1)
Test_X_data = pd.DataFrame(Test_X_data)
Test_Y_data = pd.DataFrame(Test_Y_data)

Test_Y_data
Test_X_data_0= Test_X_data[Test_X_data.index.isin(X_scores_0.index)]
Test_X_data_1= Test_X_data[Test_X_data.index.isin(X_scores_1.index)]
Test_X_data_2= Test_X_data[Test_X_data.index.isin(X_scores_2.index)]
Test_X_data_3= Test_X_data[Test_X_data.index.isin(X_scores_3.index)]
Test_X_data_4= Test_X_data[Test_X_data.index.isin(X_scores_4.index)]
Test_X_data_5= Test_X_data[Test_X_data.index.isin(X_scores_5.index)]
Test_Y_data_0 = Test_Y_data[Test_Y_data.index.isin(X_scores_0.index)]
Test_Y_data_1 = Test_Y_data[Test_Y_data.index.isin(X_scores_1.index)]
Test_Y_data_2 = Test_Y_data[Test_Y_data.index.isin(X_scores_2.index)]
Test_Y_data_3 = Test_Y_data[Test_Y_data.index.isin(X_scores_3.index)]
Test_Y_data_4 = Test_Y_data[Test_Y_data.index.isin(X_scores_4.index)]
Test_Y_data_5 = Test_Y_data[Test_Y_data.index.isin(X_scores_5.index)]
## Predictions
pred_0 = local_pls_0.predict(Test_X_data_0)
pred_1 = local_pls_1.predict(Test_X_data_1)
pred_2 = local_pls_2.predict(Test_X_data_2)
pred_3 = local_pls_3.predict(Test_X_data_3)
pred_4 = local_pls_4.predict(Test_X_data_4)
pred_5 = local_pls_5.predict(Test_X_data_5)
all_pred = np.concatenate([pred_0, pred_1, pred_2, pred_3,pred_4, pred_5])
all_pred.shape

## Appending Truth values Y_test 
Y_test_sequential = pd.concat([Test_Y_data_0, Test_Y_data_1, Test_Y_data_2, Test_Y_data_3, Test_Y_data_4, Test_Y_data_5])
Test_X_data_0
Y_test_sequential
print(r2_score(Y_test_sequential,all_pred))
Y_test_sequential = Y_test_sequential.to_numpy()
extra_results_df = pd.DataFrame([r2_score(Y_test_sequential[:,i],all_pred[:,i]) for i in range(len(names))],index=names,columns=['r2_score'])
results_df = pd.concat([results_df,extra_results_df],axis=1)
results_df<jupyter_output><empty_output><jupyter_text>Plots<jupyter_code>global_reg = pd.DataFrame(global_pls.coef_)
local_0_reg = pd.DataFrame(local_pls_0.coef_)
local_1_reg = pd.DataFrame(local_pls_1.coef_)
local_2_reg = pd.DataFrame(local_pls_2.coef_)
local_3_reg = pd.DataFrame(local_pls_3.coef_)
local_4_reg = pd.DataFrame(local_pls_4.coef_)
local_5_reg = pd.DataFrame(local_pls_5.coef_)
g = global_pls.coef_
p0= local_pls_0.coef_
p1= local_pls_1.coef_
p2=local_pls_2.coef_
p3=local_pls_3.coef_
p4=local_pls_4.coef_
p5=local_pls_5.coef_
global_reg
coeffs= np.array([p0,p1,p2,p3,p4,p5])
coeffs.shape
headers = ['V_myo(um3)', 'V_SR(um3)', 'V_myo_uL(uL)', 'V_SR_uL(uL)',
       'i_NaK_max(uA)', 'K_m_K(mM)', 'K_m_Na(mM)', 'K_o(millimolar)',
        'Na_o(millimolar)',
           'Ca_TRPN_Max(mM)', 'g_Na(microS)', 'g_t(microS)',
       'a_endo', 'b_endo', 'g_ss(microS)', 'g_K1(microS)', 'g_f(microS)',
       'f_Na', 'g_B_Na(microS)', 'g_B_Ca(microS)', 'g_B_K(microS)',
       'E_Ca(millivolt)', 'Ca_o(millimolar)', 'g_D(um3_per_ms)',
       'J_R(um3_per_ms)', 'J_L(um3_per_ms)', 'N', 'K_mNa(mM)', 'K_mCa(mM)',
       'eta', 'k_sat', 'g_NCX(mM_per_ms)', 'g_SERCA(mM_per_ms)', 'K_SERCA(mM)',
       'g_pCa(mM_per_ms)', 'K_mpCa(mM)', 'g_CaB(mM_per_mV_ms)',
       'g_SRl(per_ms)', 'k_CMDN(mM)', 'B_CMDN(mM)', 'k_on(per_mM_per_ms)',
       'k_Ref_off(per_ms)', 'gamma_trpn', 'alpha_0(per_ms)',
       'alpha_r1(per_ms)', 'alpha_r2(per_ms)', 'n_Rel', 'K_z', 'n_Hill',
       'Ca_50ref(mM)', 'z_p', 'beta_1', 'beta_0', 'T_ref(N_per_mm2)',
       'a in component Cross_Bridges', 'A_1', 'A_2', 'A_3', 'alpha_1(per_ms)',
       'alpha_2(per_ms)', 'alpha_3(per_ms)', 'V_L(mV)', 'del_VL(mV)', 'phi_L',
       't_L(ms)', 'tau_L(ms)', 'tau_R(ms)', 'phi_R', 'theta_R', 'K_RyR(mM)',
       'K_L(mM)', 'a', 'b', 'c', 'd', 'tau_s_ss']
ag_names = ['Time to AP','Amplitude of AP','Width of AP']

plt.figure(figsize=(20,10))
for n,agt in enumerate(ag_names):
  plt.subplot(3,1,n+1)
  plt.title(ag_names[n],fontweight='bold',fontsize=14)
  width=0.1

  x = np.array([i for i in range(0,15)])

  plt.bar(x-0.2,coeffs[0,:15,n].T,width=width,label='cluster: 1')
  plt.bar(x-0.1,coeffs[1,:15,n].T,width=width,label='cluster: 2')
  plt.bar(x    ,coeffs[2,:15,n].T,width=width,label='cluster: 3')
  plt.bar(x+0.1,coeffs[3,:15,n].T,width=width,label='cluster: 4')
  plt.bar(x+0.2,coeffs[4,:15,n].T,width=width,label='cluster: 5')
  plt.bar(x+0.3,coeffs[5,:15,n].T,width=width,label='cluster: 6')
  
  
  if n == 0:
    plt.ylim(-1.5,1.5)
    plt.ylabel('Regression coefficients',fontweight='bold',fontsize=14)
    plt.tick_params(axis='x',labelbottom=False)
    plt.legend(bbox_to_anchor=(1, 1),prop={'size': 20})
    
  elif n == 1:
    plt.ylim(-1.5,1.5)
    plt.ylabel('Regression coefficients',fontweight='bold',fontsize=14)
    plt.tick_params(axis='x',labelbottom=False)
    
    
  else:
    plt.ylim(-1.5,1.5)
    plt.ylabel('Regression coefficients',fontweight='bold',fontsize=14)
    #plt.xticks(x,headers[:8],fontweight='bold',fontsize=16)
    ax=plt.gca()
    ax.set_xticks(x)
    
    #ax.set_xtickslabels(headers[:14])
    ax.tick_params(labelsize=15)
    ax.set_xticklabels(headers, weight='bold', rotation=45)
    plt.xlabel('Parameter',fontweight='bold',fontsize=16)
    
    plt.tight_layout()<jupyter_output><empty_output><jupyter_text>selecting important ones<jupyter_code>headers = ['V_myo(um3)', 'V_SR(um3)', 'V_myo_uL(uL)', 'V_SR_uL(uL)',
       'i_NaK_max(uA)', 'K_m_K(mM)', 'K_m_Na(mM)', 'K_o(millimolar)',
        'Na_o(millimolar)',
           'Ca_TRPN_Max(mM)', 'g_Na(microS)', 'g_t(microS)',
       'a_endo', 'b_endo', 'g_ss(microS)', 'g_K1(microS)', 'g_f(microS)',
       'f_Na', 'g_B_Na(microS)', 'g_B_Ca(microS)', 'g_B_K(microS)',
       'E_Ca(millivolt)', 'Ca_o(millimolar)', 'g_D(um3_per_ms)',
       'J_R(um3_per_ms)', 'J_L(um3_per_ms)', 'N', 'K_mNa(mM)', 'K_mCa(mM)',
       'eta', 'k_sat', 'g_NCX(mM_per_ms)', 'g_SERCA(mM_per_ms)', 'K_SERCA(mM)',
       'g_pCa(mM_per_ms)', 'K_mpCa(mM)', 'g_CaB(mM_per_mV_ms)',
       'g_SRl(per_ms)', 'k_CMDN(mM)', 'B_CMDN(mM)', 'k_on(per_mM_per_ms)',
       'k_Ref_off(per_ms)', 'gamma_trpn', 'alpha_0(per_ms)',
       'alpha_r1(per_ms)', 'alpha_r2(per_ms)', 'n_Rel', 'K_z', 'n_Hill',
       'Ca_50ref(mM)', 'z_p', 'beta_1', 'beta_0', 'T_ref(N_per_mm2)',
       'a in component Cross_Bridges', 'A_1', 'A_2', 'A_3', 'alpha_1(per_ms)',
       'alpha_2(per_ms)', 'alpha_3(per_ms)', 'V_L(mV)', 'del_VL(mV)', 'phi_L',
       't_L(ms)', 'tau_L(ms)', 'tau_R(ms)', 'phi_R', 'theta_R', 'K_RyR(mM)',
       'K_L(mM)', 'a', 'b', 'c', 'd', 'tau_s_ss']
sign_indexes = []
sign_headers = []
for agt in range(3):
  sign_ind = []
  sign_head = []
  for i in range(1,coeffs.shape[1]):

    if np.any(abs(np.squeeze(coeffs[:,i,agt])) > np.max(abs(coeffs[:,:76,agt]))*0.5):  # Significant if 5% of maximum value
      sign_ind.append(i)
      sign_head.append(headers[i])
  sign_indexes.append(sign_ind)
  sign_headers.append(sign_head)
  
sign_indexes = np.array(sign_indexes)
sign_indexes[2]
sign_headers[2]
new_sign_indexes = np.array(sign_indexes[2])
new_sign_headers = np.array(sign_headers[2])
plt.figure(figsize=(20,10))
for n,agt in enumerate(ag_names):
  plt.subplot(3,1,n+1)
  plt.title(ag_names[n],fontweight='bold',fontsize=14)
  width=0.1


  x = np.array([i for i in range(0,14)])
  plt.bar(x-0.2,coeffs[0,new_sign_indexes,n].T,width=width,label='cluster: 1');
  plt.bar(x-0.1,coeffs[1,new_sign_indexes,n].T,width=width,label='cluster: 2');
  plt.bar(x    ,coeffs[2,new_sign_indexes,n].T,width=width,label='cluster: 3');
  plt.bar(x+0.1,coeffs[3,new_sign_indexes,n].T,width=width,label='cluster: 4');
  plt.bar(x+0.2,coeffs[4,new_sign_indexes,n].T,width=width,label='cluster: 5');
  plt.bar(x+0.3,coeffs[5,new_sign_indexes,n].T,width=width,label='cluster: 6');

  if n == 0:
    plt.ylim(-1.5,1.5)
    plt.ylabel('Regression coeffisients',fontweight='bold',fontsize=12)
    plt.tick_params(axis='x',labelbottom=False)
    plt.legend(bbox_to_anchor=(1, 1),prop={'size': 20})
    
  elif n == 1:
    plt.ylim(-1.5,1.5)
    plt.ylabel('Regression coeffisients',fontweight='bold',fontsize=12)
    plt.tick_params(axis='x',labelbottom=False)
    
    
  else:
    plt.ylim(-1.5,1.5)
    plt.ylabel('Regression coeffisients',fontweight='bold',fontsize=12)
    #plt.xticks(x,new_sign_headers,fontweight='bold',fontsize=16,rotation=90);
    ax=plt.gca()
    ax.set_xticks(x)
    
    ax.tick_params(labelsize=15)
    ax.set_xticklabels(new_sign_headers, weight='bold', rotation=45)
    plt.xlabel('Parameter',fontweight='bold',fontsize=100)

    plt.xlabel('Parameter',fontweight='bold',fontsize=25)
    
    
    


plt.tight_layout()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14689405173834238, 'fraction_numerical': 0.029782501235788433, 'mean_word_length': 5.75111234705228, 'pattern_counts': {'":': 0, '<': 96, '<?xml version=': 0, '>': 98, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '24', 'dir': 'jupyter-structured-clean-dedup', 'id': '557452', 'license': 'MIT', 'n_tokens_mistral': 10714, 'n_tokens_neox': 10098, 'n_words': 1489, 'path': 'Data Cleaning and Modelling/Modelling State Variables/HCPLSR_ Classical Metamodelling of Aggregated Phenotypes.ipynb', 'repo_name': 'ashez2051/Metamodelling-of-Pandit-Hinch-Niederer-Model', 'size': '24276'}