CosmoPlot / functions.py
dpraz's picture
Update functions.py
cb77a5a
raw
history blame
23.4 kB
import pandas as pd
import numpy as np
import pylab as pl
import plotly.express as px
import plotly.graph_objects as go
import gradio as gr
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
import seaborn as sns
from sklearn import linear_model
def update_table(coordx,coordy,coordz,plotting_df):
plotting_df = plotting_df[plotting_df['type'] != "User"]
xx=plotting_df.columns[3]
yy=plotting_df.columns[4]
zz=plotting_df.columns[5]
plotting_df=plotting_df.drop([xx,yy,zz], axis=1)
to_merge=pd.concat([df['group'],df[coordx],df[coordy],df[coordz]],axis=1) #assumes already rounded df. will needto be rounded here if not
plotting_df=plotting_df.merge(to_merge,how='left',on=['group'])
return gr.update(value=plotting_df)
def refresh(coordx,coordy,coordz):
for coord in [coordx,coordy,coordz]:
for jj in range(0,len(df[coord])):
try:
float(df[coord][jj])
df[coord][jj]=round(df[coord][jj],3)
except:
df[coord][jj]= ""
df[coord][jj]= " "
df[coord][jj]= "--"
plotting_df=pd.concat([df['class'],df['type'],df['group'],df[coordx],df[coordy],df[coordz]],axis=1)
return gr.update(value=plotting_df), gr.update(value=True),gr.update(value=True),gr.update(value=True)
def plot(plotting_df,x_vals, y_vals, z_vals):
#get error row IDs:
x_errors=df.columns[(df.columns.get_loc(f'{x_vals}'))+1]
y_errors=df.columns[(df.columns.get_loc(f'{y_vals}'))+1]
z_errors=df.columns[(df.columns.get_loc(f'{z_vals}'))+1]
to_merge=pd.concat([df['group'],df[x_errors],df[y_errors],df[z_errors]], axis=1) #if original df values must be used for plotting - would also add x,y,z_vals here, and drop them from temp_df - still merge on subgroup
temp_df=plotting_df.merge(to_merge,how='left',on=['group'])
#omits '-- from temporary plotting dfs
temp_xyz = pd.DataFrame(columns=temp_df.columns)
temp_xy = pd.DataFrame(columns=temp_df.columns)
temp_yz = pd.DataFrame(columns=temp_df.columns)
temp_zx = pd.DataFrame(columns=temp_df.columns)
for index, row in temp_df.iterrows():
x = row[x_vals]
y = row[y_vals]
z = row[z_vals]
if x != '--' and y != '--' and z != '--':
temp_xyz = pd.concat([temp_xyz, row.to_frame().T])
if x != '--' and y != '--':
temp_xy = pd.concat([temp_xy, row.to_frame().T])
if y != '--' and z != '--':
temp_yz = pd.concat([temp_yz, row.to_frame().T])
if z != '--' and x != '--':
temp_zx = pd.concat([temp_zx, row.to_frame().T])
temp_xyz.reset_index(drop=True, inplace=True)
temp_xy.reset_index(drop=True, inplace=True)
temp_yz.reset_index(drop=True, inplace=True)
temp_zx.reset_index(drop=True, inplace=True)
#get min and max for kde ranges:
cols=[x_vals,y_vals,z_vals]
temp_xyz.loc[:, cols] = temp_xyz.loc[:, cols].astype(float)
min_x = temp_xyz[x_vals].min()
max_x = temp_xyz[x_vals].max()
min_y = temp_xyz[y_vals].min()
max_y = temp_xyz[y_vals].max()
min_z = temp_xyz[z_vals].min()
max_z = temp_xyz[z_vals].max()
#3D plot:
markers={'Chon': 'circle', 'Iron': 'x', 'Acho': 'square', 'Plan': 'square', 'CAIs': 'diamond', 'User':'circle'}#, 'CI':'circle'
fig0= px.scatter_3d(data_frame=temp_xyz,x=x_vals,y=y_vals, z=z_vals , color='class', color_discrete_map={'CC':'blue','CI':'#a4dded','NC':'red','Other':'green','NA':'#FFEF00'},symbol='type', symbol_map=markers, hover_name='group',
hover_data={'class': False, 'type':False})
fig0.update_layout(template="none", showlegend=True, legend=dict(y=0.0, itemsizing="constant",title=""), modebar=dict(orientation='h'))#margin=dict(l=50, r=50, b=50, t=50),
fig0.update_traces(marker=dict(size=5, line=dict(color='white', width=4)))
fig0.update_traces(selector=dict(marker_color='#FFEF00'), marker=dict(line_color='black'))
#x vs y:
fig01=px.scatter(temp_xy,x=x_vals,y=y_vals, color='class',color_discrete_map={'CC':'blue','CI':'#a4dded','NC':'red','Other':'green','NA':'#FFEF00'},symbol='type', symbol_map=markers, hover_name='group',
hover_data={'class': False, 'type':False}, error_x=x_errors, error_y=y_errors)
fig01.update_layout(template="simple_white", showlegend=True, legend=dict(title='',y=1.0, xanchor="right",x=0.2, bgcolor='rgba(0,0,0,0)'), modebar=dict(orientation='h'))
fig01.update_traces(marker=dict(size=9, line=dict(color='white', width=1)), error_x_width=0,error_y_width=0)
fig01.update_traces(selector=dict(marker_color='#FFEF00'), marker=dict(line_color='black'))
fig01.update_xaxes(mirror=True)
fig01.update_yaxes(mirror=True)
#hist1:
palette = {'CC': '#0000FF', 'NC': '#FF0000', 'Other': '#00FF00'}
df_yclean = temp_df[temp_df[y_vals] != "--"]
#df_yclean[y_vals]=df_yclean[y_vals].astype(float)
df_ydich=df_yclean[df_yclean['class'].isin(['CC','NC'])]
hist1=plt.figure(figsize=(1.5,4.47),tight_layout=dict(pad=0.1))
sns.kdeplot(data=df_ydich, y=y_vals, hue='class', palette=palette, fill=True)
plt.ylim(min_y-abs(min_y*0.23),max_y+abs(max_y*0.19)) #may need to be a factor of average y val, not min and max...
plt.yticks([])
plt.ylabel('')
plt.gca().xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
legend = plt.gca().get_legend()
legend.set_title('')
#y vs z:
fig02=px.scatter(temp_yz,x=y_vals,y=z_vals, color='class',color_discrete_map={'CC':'blue','CI':'#a4dded','NC':'red','Other':'green','NA':'#FFEF00'},symbol='type',symbol_map=markers, hover_name='group',
hover_data={'class': False, 'type':False},
error_x=y_errors, error_y=z_errors)
fig02.update_layout(template="simple_white", showlegend=True, legend=dict(title='',y=1.0, xanchor="right",x=0.2, bgcolor='rgba(0,0,0,0)'), modebar=dict(orientation='h'))
fig02.update_traces(marker=dict(size=9, line=dict(color='white', width=1)), error_x_width=0,error_y_width=0)
fig02.update_traces(selector=dict(marker_color='#FFEF00'), marker=dict(line_color='black'))
fig02.update_xaxes(mirror=True)
fig02.update_yaxes(mirror=True)
#hist2:
df_zclean = temp_df[temp_df[z_vals] != "--"]
#df_zclean[z_vals]=df_zclean[z_vals].astype(float)
df_zdich=df_zclean[df_zclean['class'].isin(['CC','NC'])]
hist2=plt.figure(figsize=(1.5,4.47),tight_layout=dict(pad=0.1))
sns.kdeplot(data=df_zdich, y=z_vals, hue='class', palette=palette, fill=True)
plt.ylim(min_z-abs(min_z*0.23),max_z+abs(max_z*0.19))
plt.yticks([])
plt.ylabel('')
plt.gca().xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
legend = plt.gca().get_legend()
legend.set_title('')
#z vs x:
fig03=px.scatter(temp_zx,x=z_vals,y=x_vals, color='class',color_discrete_map={'CC':'blue','CI':'#a4dded','NC':'red','Other':'green','NA':'#FFEF00'},symbol='type', symbol_map=markers, hover_name='group',
hover_data={'class': False, 'type':False},
error_x=z_errors,error_y=x_errors)
fig03.update_layout(template="simple_white", showlegend=True, legend=dict(title='',y=1.0, xanchor="right",x=0.2, bgcolor='rgba(0,0,0,0)'), modebar=dict(orientation='h'))
fig03.update_traces(marker=dict(size=9, line=dict(color='white', width=1)), error_x_width=0,error_y_width=0)
fig03.update_traces(selector=dict(marker_color='#FFEF00'), marker=dict(line_color='black'))
fig03.update_xaxes(mirror=True)
fig03.update_yaxes(mirror=True)
#hist3:
df_xclean = temp_df[temp_df[x_vals] != "--"]
#df_xclean[x_vals]=df_xclean[x_vals].astype(float)
df_xdich=df_xclean[df_xclean['class'].isin(['CC','NC'])]
hist3=plt.figure(figsize=(1.5,4.47),tight_layout=dict(pad=0.1))
sns.kdeplot(data=df_xdich, y=x_vals, hue='class',palette=palette, fill=True)
plt.ylim(min_x-abs(min_x*0.23),max_x+abs(max_x*0.19))
plt.yticks([])
plt.ylabel('')
plt.gca().xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
legend = plt.gca().get_legend()
legend.set_title('')
return gr.update(value=fig0, visible=True),gr.update(value=fig01, visible=True),gr.update(value=fig02, visible=True),gr.update(value=fig03, visible=True), gr.update(value=hist1, visible=True),gr.update(value=hist2, visible=True),gr.update(value=hist3, visible=True), fig01,fig02,fig03
def cc_checkbox_check(plotting_df,CC_check, x_vals,y_vals,z_vals):
temp_columns=df[['class','type','group',x_vals,y_vals,z_vals]]
temp_df=pd.concat([temp_columns],axis=1)
plotting_df=plotting_df[plotting_df['class']!='CC']
if CC_check==False:
return plotting_df
else:
plotting_df=pd.concat([plotting_df,temp_df[temp_df['class']=='CC']], axis=0)
return plotting_df
def nc_checkbox_check(plotting_df,NC_check, x_vals,y_vals,z_vals):
temp_columns=df[['class','type','group',x_vals,y_vals,z_vals]]
temp_df=pd.concat([temp_columns],axis=1)
plotting_df=plotting_df[plotting_df['class']!='NC']
if NC_check==False:
return plotting_df
else:
plotting_df=pd.concat([plotting_df,temp_df[temp_df['class']=='NC']], axis=0)
return plotting_df
def other_checkbox_check(plotting_df,Other_check, x_vals,y_vals,z_vals):
temp_columns=df[['class','type','group',x_vals,y_vals,z_vals]]
temp_df=pd.concat([temp_columns],axis=1)
plotting_df=plotting_df[plotting_df['class']!='Other']
if Other_check==False:
return plotting_df
else:
plotting_df=pd.concat([plotting_df,temp_df[temp_df['class']=='Other']], axis=0)
return plotting_df
def updateAdd_xchange(x,add_data):
headers=add_data.columns
if x in headers:
return gr.update(value=add_data)
else:
new_col = pd.DataFrame(columns=[x], index=add_data.index)
add_data=pd.concat([add_data,new_col],axis=1)
return gr.update(value=add_data)
def updateAdd_ychange(y,add_data):
headers=add_data.columns
if y in headers:
return gr.update(value=add_data)
else:
new_col = pd.DataFrame(columns=[y], index=add_data.index)
add_data=pd.concat([add_data,new_col],axis=1)
return gr.update(value=add_data)
def updateAdd_zchange(z,add_data):
headers=add_data.columns
if z in headers:
return gr.update(value=add_data)
else:
new_col = pd.DataFrame(columns=[z], index=add_data.index)
add_data=pd.concat([add_data,new_col],axis=1)
return gr.update(value=add_data)
def resetAdd(x_vals,y_vals,z_vals):
new=pd.DataFrame(columns=['ID',x_vals,y_vals,z_vals])
return gr.update(value=new)
def appendFn(add_data,plotting_df):
adding=pd.DataFrame(columns=['class','type'], index=add_data.index)
adding['class']='NA'
adding['type']='User'
x=plotting_df.columns[3]
y=plotting_df.columns[4]
z=plotting_df.columns[5]
add_data = add_data.rename(columns={'ID': 'group'})
adding=pd.concat([adding,add_data['group'],add_data[x],add_data[y],add_data[z]], axis=1)
for row in [adding.columns[3],adding.columns[4],adding.columns[5]]:
for jj in range(0,adding.shape[0]):
if adding[row][jj]=='':
adding[row][jj]='--'
plotting_df=pd.concat([plotting_df,adding],axis=0)
return gr.update(value=plotting_df)
def twoD_regs(CC_reg,NC_reg,x_vals,y_vals,z_vals,plotting_df):
_,_,_,_,_,_,_,fig01,fig02,fig03=plot(plotting_df,x_vals,y_vals,z_vals)
fig11=fig01
fig22=fig02
fig33=fig03
model=linear_model.TheilSenRegressor(random_state=42)
reg_df = df[['class',x_vals,y_vals,z_vals]].copy() #pulls from parent df - currently rounded values
CCreg_df = reg_df[reg_df['class'] == 'CC']
NCreg_df = reg_df[reg_df['class'] == 'NC']
#temporary dfs
cc_temp_xy=CCreg_df[['class',x_vals,y_vals]].copy()
cc_temp_xy=cc_temp_xy[~(cc_temp_xy == '--').any(axis=1)]
cc_temp_yz=CCreg_df[['class',y_vals,z_vals]].copy()
cc_temp_yz=cc_temp_yz[~(cc_temp_yz == '--').any(axis=1)]
cc_temp_zx=CCreg_df[['class',z_vals,x_vals]].copy()
cc_temp_zx=cc_temp_zx[~(cc_temp_zx == '--').any(axis=1)]
nc_temp_xy=NCreg_df[['class',x_vals,y_vals]].copy()
nc_temp_xy=nc_temp_xy[~(nc_temp_xy == '--').any(axis=1)]
nc_temp_yz=NCreg_df[['class',y_vals,z_vals]].copy()
nc_temp_yz=nc_temp_yz[~(nc_temp_yz == '--').any(axis=1)]
nc_temp_zx=NCreg_df[['class',z_vals,x_vals]].copy()
nc_temp_zx=nc_temp_zx[~(nc_temp_zx == '--').any(axis=1)]
#min-max ranges: #equivalent to x_range in robust regression.pynb
cc_xx=cc_temp_xy[x_vals].to_numpy().reshape(-1,1)
cc_xy1 = np.array([min(cc_xx),max(cc_xx)])
cc_yy=cc_temp_yz[y_vals].to_numpy().reshape(-1,1)
cc_yz1 = np.array([min(cc_yy),max(cc_yy)])
cc_zz=cc_temp_zx[z_vals].to_numpy().reshape(-1,1)
cc_zx1 = np.array([min(cc_zz),max(cc_zz)])
#NC
nc_xx=nc_temp_xy[x_vals].to_numpy().reshape(-1,1)
nc_xy1 = np.array([min(nc_xx),max(nc_xx)])
nc_yy=nc_temp_yz[y_vals].to_numpy().reshape(-1,1)
nc_yz1 = np.array([min(nc_yy),max(nc_yy)])
nc_zz=nc_temp_zx[z_vals].to_numpy().reshape(-1,1)
nc_zx1 = np.array([min(nc_zz),max(nc_zz)])
#########model fitting, creation of regression traces
CC_m1,CC_m2,CC_m3,CC_b1,CC_b2,CC_b3,NC_m1,NC_m2,NC_m3,NC_b1,NC_b2,NC_b3 = 1,1,1,1,1,1,1,1,1,1,1,1
model.fit(cc_xx,cc_temp_xy[y_vals].to_numpy()) #if sizes are an issue, change this to just y_vals .to numpy
cc_r1=model.score(cc_xx,cc_temp_xy[y_vals].to_numpy()).round(5)
cc_xy2=model.predict(cc_xy1)
CC_m1=model.coef_
CC_b1=model.intercept_
trace1 = go.Scatter(x=np.ravel(cc_xy1),y=np.ravel(cc_xy2),mode='lines',line=dict(color='blue'),showlegend=False,hoverinfo='text',hovertext=f'CC Regression<br>Correlation Coef.:{cc_r1}')
model.fit(nc_xx,nc_temp_xy[y_vals].to_numpy())
nc_r1=model.score(nc_xx,nc_temp_xy[y_vals].to_numpy()).round(5)
nc_xy2=model.predict(nc_xy1)
NC_m1=model.coef_
NC_b1=model.intercept_
trace1a = go.Scatter(x=np.ravel(nc_xy1),y=np.ravel(nc_xy2),mode='lines',line=dict(color='red'),showlegend=False,hoverinfo='text',hovertext=f'NC Regression<br>Correlation Coef.:{nc_r1}')
model.fit(cc_yy,cc_temp_yz[z_vals].to_numpy())
cc_r2=model.score(cc_yy,cc_temp_yz[z_vals].to_numpy()).round(5)
cc_yz2=model.predict(cc_yz1)
CC_m2=model.coef_
CC_b2=model.intercept_
trace2 = go.Scatter(x=np.ravel(cc_yz1),y=np.ravel(cc_yz2),mode='lines',line=dict(color='blue'),showlegend=False,hoverinfo='text',hovertext=f'CC Regression<br>Correlation Coef.:{cc_r2}')
model.fit(nc_yy,nc_temp_yz[z_vals].to_numpy())
nc_r2=model.score(nc_yy,nc_temp_yz[z_vals].to_numpy()).round(5)
nc_yz2=model.predict(nc_yz1)
NC_m2=model.coef_
NC_b2=model.intercept_
trace2a = go.Scatter(x=np.ravel(nc_yz1),y=np.ravel(nc_yz2),mode='lines',line=dict(color='red'),showlegend=False,hoverinfo='text',hovertext=f'NC Regression<br>Correlation Coef.:{nc_r2}')
model.fit(cc_zz,cc_temp_zx[x_vals].to_numpy())
cc_r3=model.score(cc_zz,cc_temp_zx[x_vals].to_numpy()).round(5)
cc_zx2=model.predict(cc_zx1)
CC_m3=model.coef_
CC_b3=model.intercept_
trace3 = go.Scatter(x=np.ravel(cc_zx1),y=np.ravel(cc_zx2),mode='lines',line=dict(color='blue'),showlegend=False,hoverinfo='text',hovertext=f'CC Regression<br>Correlation Coef.:{cc_r3}')
model.fit(nc_zz,nc_temp_zx[x_vals].to_numpy())
nc_r3=model.score(nc_zz,nc_temp_zx[x_vals].to_numpy()).round(5)
nc_zx2=model.predict(nc_zx1)
NC_m3=model.coef_
NC_b3=model.intercept_
trace3a = go.Scatter(x=np.ravel(nc_zx1),y=np.ravel(nc_zx2),mode='lines',line=dict(color='red'),showlegend=False,hoverinfo='text',hovertext=f'NC Regression<br>Correlation Coef.:{nc_r3}')
##conditional statement which selectively appends regs based on boolean of regression buttons
vp=0 #visibility param
if CC_reg==True and NC_reg==False: ##just CC regs
vp=1
fig11 = fig01.to_dict()
fig11['data'].append(trace1)
#fig11['data'].append(trace1a)
fig11 = go.Figure(fig11)
fig22 = fig02.to_dict()
fig22['data'].append(trace2)
#fig22['data'].append(trace2a)
fig22 = go.Figure(fig22)
fig33 = fig03.to_dict()
fig33['data'].append(trace3)
#fig33['data'].append(trace3a)
fig33= go.Figure(fig33)
elif CC_reg==False and NC_reg==True: ##just NC regs
vp=1
fig11 = fig01.to_dict()
#fig11['data'].append(trace1)
fig11['data'].append(trace1a)
fig11 = go.Figure(fig11)
fig22 = fig02.to_dict()
#fig22['data'].append(trace2)
fig22['data'].append(trace2a)
fig22 = go.Figure(fig22)
fig33 = fig03.to_dict()
#fig33['data'].append(trace3)
fig33['data'].append(trace3a)
fig33= go.Figure(fig33)
elif CC_reg==True and NC_reg==True: ##both
vp=1
fig11 = fig01.to_dict()
fig11['data'].append(trace1)
fig11['data'].append(trace1a)
fig11 = go.Figure(fig11)
fig22 = fig02.to_dict()
fig22['data'].append(trace2)
fig22['data'].append(trace2a)
fig22 = go.Figure(fig22)
fig33 = fig03.to_dict()
fig33['data'].append(trace3)
fig33['data'].append(trace3a)
fig33= go.Figure(fig33)
#else:
###############begin 3D regression
df4=df.copy()
df4.replace('--', np.nan,inplace=True)
temp_x=df4[x_vals].dropna()
temp_y=df4[y_vals].dropna()
temp_z=df4[z_vals].dropna()
###CC 3D reg
if (cc_r1 and cc_r2)>cc_r3: ## y vs x ++++ z vs y :: y_vals is common var, m1/b1 flips, m2/b2 remains
val=1
model.fit(cc_temp_xy[y_vals].to_numpy().reshape(-1,1),cc_temp_xy[x_vals].to_numpy())
#CC_m1=model.coef_
#CC_b1=model.intercept_
passing_min=min(temp_y)
passing_max=max(temp_y)
CC_reg_min,CC_reg_max=threeD_regs_calcs(model.coef_,model.intercept_,CC_m2,CC_b2,passing_min,passing_max,val)
elif (cc_r1 and cc_r3)>cc_r2: ## y vs x ++++ x vs z :: x_vals is common var, m3/b3 flips ; m1/b1 remains
val=2
model.fit(cc_temp_zx[x_vals].to_numpy().reshape(-1,1),cc_temp_zx[z_vals].to_numpy())
#CC_m3=model.coef_
#CC_b3=model.intercept_
passing_min=min(temp_x)
passing_max=max(temp_x)
CC_reg_min,CC_reg_max=threeD_regs_calcs(CC_m1,CC_b1,model.coef_,model.intercept_,passing_min,passing_max,val)
elif (cc_r2 and cc_r3)>cc_r1: ## z vs y ++++ x vs z :: z_vals is common var, m2/b2 flips, m3/b3 remains
val=3
model.fit(cc_temp_yz[z_vals].to_numpy().reshape(-1,1),cc_temp_yz[y_vals].to_numpy())
#CC_m2=model.coef_
#CC_b2=model.intercept_
passing_min=min(temp_z)
passing_max=max(temp_z)
CC_reg_min,CC_reg_max=threeD_regs_calcs(model.coef_,model.intercept_,CC_m3,CC_b3,passing_min,passing_max,val)
###NC 3D reg
if (nc_r1 and nc_r2)>nc_r3: ## y vs x ++++ z vs y :: y_vals is common var, m1/b1 flips, m2/b2 remains
val=1
model.fit(nc_temp_xy[y_vals].to_numpy().reshape(-1,1),nc_temp_xy[x_vals].to_numpy())
#NC_m1=model.coef_
#NC_b1=model.intercept_
passing_min=min(temp_y)
passing_max=max(temp_y)
NC_reg_min,NC_reg_max=threeD_regs_calcs(model.coef_,model.intercept_,NC_m2,NC_b2,passing_min,passing_max,val)
elif (nc_r1 and nc_r3)>nc_r2: ## y vs x ++++ x vs z :: x_vals is common var, m3/b3 flips ; m1/b1 remains
val=2
model.fit(nc_temp_zx[x_vals].to_numpy().reshape(-1,1),nc_temp_zx[z_vals].to_numpy())
#NC_m3=model.coef_
#NC_b3=model.intercept_
passing_min=min(temp_x)
passing_max=max(temp_x)
NC_reg_min,NC_reg_max=threeD_regs_calcs(NC_m1,NC_b1,model.coef_,model.intercept_,passing_min,passing_max,val)
elif (nc_r2 and nc_r3)>nc_r1: ## z vs y ++++ x vs z :: z_vals is common var, m2/b2 flips, m3/b3 remains
val=3
model.fit(nc_temp_yz[z_vals].to_numpy().reshape(-1,1),nc_temp_yz[y_vals].to_numpy())
#NC_m2=model.coef_
#NC_b2=model.intercept_
passing_min=min(temp_z)
passing_max=max(temp_z)
NC_reg_min,NC_reg_max=threeD_regs_calcs(model.coef_,model.intercept_,NC_m3,NC_b3,passing_min,passing_max,val)
#creates df with 3Dregression data
id_df=pd.DataFrame(['CC_low','CC_high','NC_low','NC_high'], columns=['ID'])
temp_reg_df=pd.DataFrame([CC_reg_min,CC_reg_max,NC_reg_min,NC_reg_max], columns=[x_vals, y_vals, z_vals])
passing_df = pd.concat([id_df, temp_reg_df], axis=1)
if vp==0:
return gr.update(value=fig11),gr.update(value=fig22),gr.update(value=fig33),gr.update(value=passing_df,visible=False),gr.update(value="Update 3D Regression", visible=False)
else:
return gr.update(value=fig11),gr.update(value=fig22),gr.update(value=fig33),gr.update(value=passing_df,visible=True),gr.update(value="Update 3D Regression", visible=True)
def threeD_regs_calcs(m1,b1,m2,b2,passing_min,passing_max,val):
if val==1:
xmin=float((m1*passing_min)+b1)
xmax=float((m1*passing_max)+b1)
zmin=float((m2*passing_min)+b2)
zmax=float((m2*passing_max)+b2)
min_coord=np.round([xmin,passing_min,zmin],4)
max_coord=np.round([xmax,passing_max,zmax],4)
return min_coord,max_coord
elif val == 2:
ymin=float((m1*passing_min)+b1)
ymax=float((m1*passing_max)+b1)
zmin=float((m2*passing_min)+b2)
zmax=float((m2*passing_max)+b2)
min_coord=np.round([passing_min,ymin,zmin],4)
max_coord=np.round([passing_max,ymax,zmax],4)
return min_coord,max_coord
elif val == 3:
ymin=float((m1*passing_min)+b1)
ymax=float((m1*passing_max)+b1)
xmin=float((m2*passing_min)+b2)
xmax=float((m2*passing_max)+b2)
min_coord=np.round([xmin,ymin,passing_min],4)
max_coord=np.round([xmax,ymax,passing_max],4)
return min_coord,max_coord
def regs_False():
return gr.update(value=False), gr.update (value=False),gr.update(visible=False) , gr.update(value="Update 3D Regression", visible=False)
def plot_3D_reg(plotting_df,reg_df,x_vals, y_vals, z_vals,CC_reg,NC_reg):
#omits '-- from temporary plotting dfs
temp_xyz = pd.DataFrame(columns=plotting_df.columns)
for index, row in plotting_df.iterrows():
x = row[x_vals]
y = row[y_vals]
z = row[z_vals]
if x != '--' and y != '--' and z != '--':
temp_xyz = pd.concat([temp_xyz, row.to_frame().T])
temp_xyz.reset_index(drop=True, inplace=True)
#3D plot:
markers={'Chon': 'circle', 'Iron': 'x', 'Acho': 'square', 'Plan': 'square', 'CAIs': 'diamond', 'User':'circle'}#, 'CI':'circle'
fig0= px.scatter_3d(data_frame=temp_xyz,x=x_vals,y=y_vals, z=z_vals , color='class', color_discrete_map={'CC':'blue','CI':'#a4dded','NC':'red','Other':'green','NA':'#FFEF00'},symbol='type', symbol_map=markers, hover_name='group',
hover_data={'class': False, 'type':False})
fig0.update_layout(template="none", showlegend=True, legend=dict(y=0.0, itemsizing="constant",title=""), modebar=dict(orientation='h'))
fig0.update_traces(marker=dict(size=5, line=dict(color='white', width=4)))
fig0.update_traces(selector=dict(marker_color='#FFEF00'), marker=dict(line_color='black'))
#creates traces
cc_reg_df = reg_df.iloc[:2, :]
nc_reg_df = reg_df.iloc[2:, :]
CCtrace=go.Scatter3d(x=cc_reg_df[x_vals],y=cc_reg_df[y_vals],z=cc_reg_df[z_vals], mode='lines',showlegend=False,line=dict(color='blue'),hoverinfo='skip')
NCtrace=go.Scatter3d(x=nc_reg_df[x_vals],y=nc_reg_df[y_vals],z=nc_reg_df[z_vals], mode='lines',showlegend=False,line=dict(color='red'),hoverinfo='skip')
#conditional statement that adds or removes regressions depending - ends function
if CC_reg==True and NC_reg==False: ##just CC regs
fig0.add_traces(CCtrace)
return gr.update(value=fig0), gr.update(value="Update 3D Regression", visible=True)
elif CC_reg==False and NC_reg==True: ##just NC regs
fig0.add_traces(NCtrace)
return gr.update(value=fig0), gr.update(value="Update 3D Regression", visible=True)
elif CC_reg==True and NC_reg==True: ##both
fig0.add_traces([CCtrace, NCtrace])
return gr.update(value=fig0), gr.update(value="Update 3D Regression", visible=True)
else: # CC_reg==False and NC_reg==False: ##neither
return gr.update(value=fig0), gr.update(value="Update 3D Regression", visible=False)