import pandas as pd
import numpy as np
import pylab as pl
import gradio as gr
import plotly.express as px
import plotly.graph_objects as go
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
import seaborn as sns
from sklearn import linear_model
from plotly.subplots import make_subplots
import plotly.figure_factory as ff
from scipy import stats
import kaleido
import plotly.io as pio
pio.kaleido.scope.mathjax = None
def pdfs(pdfdf,coord,CC_check,NC_check): #### if works, just omit plotting_df from pdfs() inputs...
tempCC=df[(df[coord] != "--") & (df['class'] == 'CC')]
CCdata=pd.to_numeric(tempCC[coord], errors='coerce')
tempNC=df[(df[coord] != "--") & (df['class'] == 'NC')]
NCdata=pd.to_numeric(tempNC[coord], errors='coerce')
fac=1
if coord in ['ε145Nd','ε30Si','ε54Fe','ε60Ni','ε62Ni','ε66Zn','ε183W']:
fac=0.1
elif coord in ['ε96Zr','ε100Ru']:
fac=0.4
elif coord =='Δ17O':
fac=1.5
elif coord =='Δ95Mo':
fac=10
elif coord == 'δ15N':
fac=50
ccx_range=np.linspace(CCdata.min()-fac,CCdata.max()+fac,100)
ncx_range=np.linspace(NCdata.min()-fac,NCdata.max()+fac,100)
kde=stats.gaussian_kde(CCdata)
ccpdf=kde(ccx_range)
kde=stats.gaussian_kde(NCdata)
ncpdf=kde(ncx_range)
cctrace= go.Scatter(x=ccx_range, y=ccpdf, fill='tozeroy', mode='lines', line_shape='spline', line=dict(color='blue', width=1), name='CC',fillcolor='rgba(0,0,250, 0.5)', hoverinfo='none')
nctrace=go.Scatter(x=ncx_range, y=ncpdf, fill='tozeroy', mode='lines', line_shape='spline',line=dict(color='red', width=1),fillcolor='rgba(250,0,0, 0.5)', hoverinfo='none')
if CC_check==1 and NC_check==1:
PDF = go.Figure(data=[nctrace, cctrace])
elif CC_check==1 and NC_check==0:
PDF = go.Figure(data=[cctrace])
elif CC_check==0 and NC_check==1:
PDF = go.Figure(data=[nctrace])
else:
PDF = go.Figure(data=[])
return PDF
data = pd.read_excel("NIAD.xlsx")
df=pd.DataFrame(data)
df=df.fillna('--')
pd.set_option('display.max_rows', None, 'display.max_columns', None)
df3=df.filter(regex='ε|Δ|δ')
isotopes=list(df3.columns)
for coord in isotopes:
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]="--"
mask = ~df['group'].isin(['Carbonaceous meteorites', 'Chondrites', 'Iron meteorites', 'Achondrites','Achondrites','Non-carbonaceous meteorites','prim. Achondrites','diff. Achondrites','Miscellaneous materials'])
df=df[mask]
df = df[~df['group'].isin([' (H)', ' (L)', ' (LL)', ' (EH)', ' (EL)'])]
df2=[]
df2.append(df['class'])
df2.append(df['type'])
df2.append(df['group'])
df2.append(df['ε54Cr'])
df2.append(df['ε50Ti'])
df2.append(df['ε94Mo'])
x_vals='ε54Cr'
y_vals='ε50Ti'
z_vals='ε94Mo'
df2=pd.DataFrame(df2).transpose()
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]
temp_df=pd.concat([df['class'],df['type'],df['group'],df[x_vals],df[y_vals],df[z_vals],df[x_errors],df[y_errors],df[z_errors]],axis=1)
#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)
#3D plot:
markers={'Chon': 'circle', 'Iron': 'diamond', 'Acho': 'square', 'User':'circle', '--':'square'}
fig0= px.scatter_3d(data_frame=temp_xyz,x=x_vals,y=y_vals, z=z_vals , color='class', color_discrete_map={'CC':'blue','Planet.':'lightgreen','CAIs':'#F68F3A','Other':'#AB6AE0','Return':'#00B0F0','NC':'red','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={'orientation':'h'})
fig0.update_traces(marker=dict(size=5, line=dict(color='black', width=4)))
#x vs y:
scatter1=px.scatter(temp_xy,x=x_vals,y=y_vals, color='class',color_discrete_map={'CC':'blue','Planet.':'lightgreen','CAIs':'#F68F3A','Other':'#AB6AE0','Return':'#00B0F0','NC':'red','NA':'#FFEF00'},symbol='type', symbol_map=markers, hover_name='group',
hover_data={'class': False, 'type':False},error_x=x_errors, error_y=y_errors)
scatter1.update_traces(marker=dict(size=9, line=dict(color='black', width=1)), error_x_width=0,error_y_width=0,error_y=dict(thickness=1),error_x=dict(thickness=1))
#hist1
hist1=pdfs(df2,x_vals,True,True)
fig1=make_subplots(rows=2,cols=1,shared_xaxes=True,shared_yaxes=False,vertical_spacing=0,row_heights=[1,5])
for trace in hist1.data:
fig1.add_trace(trace, row=1, col=1)
for trace in scatter1.data:
fig1.add_trace(trace, row=2, col=1)
for trace in fig1.data[0:2]:
trace.update(showlegend=False)
fig1.update_yaxes(showticklabels=False, ticks="",row=1,col=1)
fig1.update_xaxes(mirror=True,row=1,col=1,ticks="inside")
fig1.update_xaxes(title_text=x_vals,row=2,col=1)
fig1.update_yaxes(mirror=True, title_text=y_vals)
fig1.update_yaxes(title_text="",row=1,col=1)
fig1.update_layout(template="simple_white", showlegend=True, legend=dict(title='', x=1.0, xanchor='left', y=0.3,yanchor='middle', bgcolor='rgba(0,0,0,0)'))
#y vs z:
scatter2=px.scatter(temp_yz,x=y_vals,y=z_vals, color='class',color_discrete_map={'CC':'blue','Planet.':'lightgreen','CAIs':'#F68F3A','Other':'#AB6AE0','Return':'#00B0F0','NC':'red','NA':'#FFEF00'},symbol='type', symbol_map=markers, hover_name='group',
hover_data={'class': False, 'type':False},error_x=y_errors, error_y=z_errors)
scatter2.update_traces(marker=dict(size=9, line=dict(color='black', width=1)), error_x_width=0,error_y_width=0,error_y=dict(thickness=1),error_x=dict(thickness=1))
#hist2
hist2=pdfs(df2,y_vals,True,True)
fig2=make_subplots(rows=2,cols=1,shared_xaxes=True,shared_yaxes=False,vertical_spacing=0,row_heights=[1,5])
for trace in hist2.data:
fig2.add_trace(trace, row=1, col=1)
for trace in scatter2.data:
fig2.add_trace(trace, row=2, col=1)
for trace in fig2.data[0:2]:
trace.update(showlegend=False)
fig2.update_yaxes(showticklabels=False, ticks="",row=1,col=1)
fig2.update_xaxes(mirror=True,row=1,col=1,ticks="inside")
fig2.update_xaxes(title_text=y_vals,row=2,col=1)
fig2.update_yaxes(mirror=True, title_text=z_vals)
fig2.update_yaxes(title_text="",row=1,col=1)
fig2.update_layout(template="simple_white", showlegend=True, legend=dict(title='', x=1.0, xanchor='left', y=0.3,yanchor='middle', bgcolor='rgba(0,0,0,0)'))
#z vs x:
scatter3=px.scatter(temp_zx,x=z_vals,y=x_vals, color='class',color_discrete_map={'CC':'blue','Planet.':'lightgreen','CAIs':'#F68F3A','Other':'#AB6AE0','Return':'#00B0F0','NC':'red','NA':'#FFEF00'},symbol='type', symbol_map=markers, hover_name='group',
hover_data={'class': False, 'type':False},error_x=z_errors, error_y=x_errors)
scatter3.update_traces(marker=dict(size=9, line=dict(color='black', width=1)), error_x_width=0,error_y_width=0,error_y=dict(thickness=1),error_x=dict(thickness=1))
#hist3
hist3=pdfs(df2,z_vals,True,True)
fig3=make_subplots(rows=2,cols=1,shared_xaxes=True,shared_yaxes=False,vertical_spacing=0,row_heights=[1,5])
for trace in hist3.data:
fig3.add_trace(trace, row=1, col=1)
for trace in scatter3.data:
fig3.add_trace(trace, row=2, col=1)
for trace in fig3.data[0:2]:
trace.update(showlegend=False)
fig3.update_yaxes(showticklabels=False, ticks="",row=1,col=1)
fig3.update_xaxes(mirror=True,row=1,col=1,ticks="inside")
fig3.update_xaxes(title_text=z_vals,row=2,col=1)
fig3.update_yaxes(mirror=True, title_text=x_vals)
fig3.update_yaxes(title_text="",row=1,col=1)
fig3.update_layout(template="simple_white", showlegend=True, legend=dict(title='', x=1.0, xanchor='left', y=0.3,yanchor='middle', bgcolor='rgba(0,0,0,0)'))
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) #parent df
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),gr.update(value=True),gr.update(value=True),gr.update(value=True)
def plot(plotting_df,x_vals, y_vals, z_vals,CC_check,NC_check):
#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)
#min and max for kde ranges: may omit
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': 'diamond', 'Acho': 'square', 'User':'circle', '--':'square'}
fig0= px.scatter_3d(data_frame=temp_xyz,x=x_vals,y=y_vals, z=z_vals , color='class', color_discrete_map={'CC':'blue','Planet.':'lightgreen','CAIs':'#F68F3A','Other':'#AB6AE0','Return':'#00B0F0','NC':'red','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=""))
fig0.update_traces(marker=dict(size=5, line=dict(color='black', width=4)))
fig0.update_traces(selector=dict(marker_color='#FFEF00'), marker=dict(line_color='black'))
#x vs y:
scatter1=px.scatter(temp_xy,x=x_vals,y=y_vals, color='class',color_discrete_map={'CC':'blue','Planet.':'lightgreen','CAIs':'#F68F3A','Other':'#AB6AE0','Return':'#00B0F0','NC':'red','NA':'#FFEF00'},symbol='type', symbol_map=markers, hover_name='group',
hover_data={'class': False, 'type':False},error_x=x_errors, error_y=y_errors)
scatter1.update_traces(marker=dict(size=9, line=dict(color='black', width=1)), error_x_width=0,error_y_width=0,error_y=dict(thickness=1),error_x=dict(thickness=1))
#hist1
hist1=pdfs(plotting_df,x_vals,CC_check,NC_check)
fig1=make_subplots(rows=2,cols=1,shared_xaxes=True,shared_yaxes=False,vertical_spacing=0,row_heights=[1,5])
for trace in hist1.data:
fig1.add_trace(trace, row=1, col=1)
for trace in scatter1.data:
fig1.add_trace(trace, row=2, col=1)
if not CC_check and not NC_check:
fig1.update_xaxes(mirror=True,ticks="inside")
elif not CC_check or not NC_check:
for trace in fig1.data[0:1]:
trace.update(showlegend=False)
elif CC_check and NC_check:
for trace in fig1.data[0:2]:
trace.update(showlegend=False)
fig1.update_layout(template="simple_white", legend=dict(title='', x=1.0, xanchor='left', y=0.3,yanchor='middle', bgcolor='rgba(0,0,0,0)'))
fig1.update_yaxes(showticklabels=False, ticks="",row=1,col=1)
fig1.update_xaxes(mirror=True,row=1,col=1,ticks="inside")
fig1.update_xaxes(title_text=x_vals,row=2,col=1)
fig1.update_yaxes(mirror=True, title_text=y_vals)
fig1.update_yaxes(title_text="",row=1,col=1)
#y vs z:
scatter2=px.scatter(temp_yz,x=y_vals,y=z_vals, color='class',color_discrete_map={'CC':'blue','Planet.':'lightgreen','CAIs':'#F68F3A','Other':'#AB6AE0','Return':'#00B0F0','NC':'red','NA':'#FFEF00'},symbol='type', symbol_map=markers, hover_name='group',
hover_data={'class': False, 'type':False},error_x=y_errors, error_y=z_errors)
scatter2.update_traces(marker=dict(size=9, line=dict(color='black', width=1)), error_x_width=0,error_y_width=0,error_y=dict(thickness=1),error_x=dict(thickness=1))
#hist2
hist2=pdfs(plotting_df,y_vals,CC_check,NC_check)
fig2=make_subplots(rows=2,cols=1,shared_xaxes=True,shared_yaxes=False,vertical_spacing=0,row_heights=[1,5])
for trace in hist2.data:
fig2.add_trace(trace, row=1, col=1)
for trace in scatter2.data:
fig2.add_trace(trace, row=2, col=1)
if not CC_check and not NC_check:
fig2.update_xaxes(mirror=True,ticks="inside")
elif not CC_check or not NC_check:
for trace in fig2.data[0:1]:
trace.update(showlegend=False)
elif CC_check and NC_check:
for trace in fig2.data[0:2]:
trace.update(showlegend=False)
fig2.update_layout(template="simple_white", legend=dict(title='', x=1.0, xanchor='left', y=0.3,yanchor='middle', bgcolor='rgba(0,0,0,0)'))
fig2.update_yaxes(showticklabels=False, ticks="",row=1,col=1)
fig2.update_xaxes(mirror=True,row=1,col=1,ticks="inside")
fig2.update_xaxes(title_text=y_vals,row=2,col=1)
fig2.update_yaxes(mirror=True, title_text=z_vals)
fig2.update_yaxes(title_text="",row=1,col=1)
#z vs x:
scatter3=px.scatter(temp_zx,x=z_vals,y=x_vals, color='class',color_discrete_map={'CC':'blue','Planet.':'lightgreen','CAIs':'#F68F3A','Other':'#AB6AE0','Return':'#00B0F0','NC':'red','NA':'#FFEF00'},symbol='type', symbol_map=markers, hover_name='group',
hover_data={'class': False, 'type':False},error_x=z_errors, error_y=x_errors)
scatter3.update_traces(marker=dict(size=9, line=dict(color='black', width=1)), error_x_width=0,error_y_width=0,error_y=dict(thickness=1),error_x=dict(thickness=1))
#hist3
hist3=pdfs(plotting_df,z_vals,CC_check,NC_check)
fig3=make_subplots(rows=2,cols=1,shared_xaxes=True,shared_yaxes=False,vertical_spacing=0,row_heights=[1,5])
for trace in hist3.data:
fig3.add_trace(trace, row=1, col=1)
for trace in scatter3.data:
fig3.add_trace(trace, row=2, col=1)
if not CC_check and not NC_check:
fig3.update_xaxes(mirror=True,ticks="inside")
elif not CC_check or not NC_check:
for trace in fig3.data[0:1]:
trace.update(showlegend=False)
elif CC_check and NC_check:
for trace in fig3.data[0:2]:
trace.update(showlegend=False)
fig3.update_layout(template="simple_white", legend=dict(title='', x=1.0, xanchor='left', y=0.3,yanchor='middle', bgcolor='rgba(0,0,0,0)'))
fig3.update_yaxes(showticklabels=False, ticks="",row=1,col=1)
fig3.update_xaxes(mirror=True,row=1,col=1,ticks="inside")
fig3.update_xaxes(title_text=z_vals,row=2,col=1)
fig3.update_yaxes(mirror=True, title_text=x_vals)
fig3.update_yaxes(title_text="",row=1,col=1)
#write .pdfs
pdf1=fig1.write_image(f"{y_vals} vs. {x_vals}.pdf", engine='kaleido')
pdf2=fig2.write_image(f"{z_vals} vs. {y_vals}.pdf", engine='kaleido')
pdf3=fig3.write_image(f"{x_vals} vs. {z_vals}.pdf", engine='kaleido')
return gr.update(value=fig0, visible=True),gr.update(value=fig1, visible=True),gr.update(value=fig2, visible=True),gr.update(value=fig3, visible=True),fig1,fig2,fig3,[f"{y_vals} vs. {x_vals}.pdf",f"{z_vals} vs. {y_vals}.pdf",f"{x_vals} vs. {z_vals}.pdf"]
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,CAI_check,Plan_check,SR_check,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'] == 'CAIs') | (plotting_df['class'] == 'Planet.') | (plotting_df['class'] == 'Return') | (plotting_df['class'] == 'Other'))]
if CAI_check:
plotting_df=pd.concat([plotting_df,temp_df[temp_df['class'] == 'CAIs']], axis=0)
if Plan_check:
plotting_df=pd.concat([plotting_df,temp_df[temp_df['class'] == 'Planet.']], axis=0)
if SR_check:
plotting_df=pd.concat([plotting_df,temp_df[temp_df['class'] == 'Return']], axis=0)
if Other_check:
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,CC_check,NC_check):
_,_,_,_,fig01,fig02,fig03,_=plot(plotting_df,x_vals,y_vals,z_vals,CC_check,NC_check)
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
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:
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())
cc_r1 = round(model.score(cc_xx, cc_temp_xy[y_vals].to_numpy()), 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
correl. coeff. (r2): {cc_r1}
slope: {CC_m1.round(4)}
y-axis intercept: {CC_b1.round(4)}')
model.fit(nc_xx,nc_temp_xy[y_vals].to_numpy())
nc_r1= round(model.score(nc_xx,nc_temp_xy[y_vals].to_numpy()),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
correl. coeff. (r2): {nc_r1}
slope: {NC_m1.round(4)}
y-axis intercept: {NC_b1.round(4)}')
model.fit(cc_yy,cc_temp_yz[z_vals].to_numpy())
cc_r2=round(model.score(cc_yy,cc_temp_yz[z_vals].to_numpy()),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
correl. coeff. (r2): {cc_r2}
slope: {CC_m2.round(4)}
y-axis intercept: {CC_b2.round(4)}')
model.fit(nc_yy,nc_temp_yz[z_vals].to_numpy())
nc_r2=round(model.score(nc_yy,nc_temp_yz[z_vals].to_numpy()),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
correl. coeff. (r2): {nc_r2}
slope: {NC_m2.round(4)}
y-axis intercept: {NC_b2.round(4)}')
model.fit(cc_zz,cc_temp_zx[x_vals].to_numpy())
cc_r3=round(model.score(cc_zz,cc_temp_zx[x_vals].to_numpy()),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
correl. coeff. (r2): {cc_r3}
slope: {CC_m3.round(4)}
y-axis intercept: {CC_b3.round(4)}')
model.fit(nc_zz,nc_temp_zx[x_vals].to_numpy())
nc_r3=round(model.score(nc_zz,nc_temp_zx[x_vals].to_numpy()),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
correl. coeff. (r2): {nc_r3}
slope: {NC_m3.round(4)}
y-axis intercept: {NC_b3.round(4)}')
##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.append_trace(trace1,row=2,col=1)
fig22.append_trace(trace2,row=2,col=1)
fig33.append_trace(trace3,row=2,col=1)
elif CC_reg==False and NC_reg==True: ##just NC regs
vp=1
fig11.append_trace(trace1a,row=2,col=1)
fig22.append_trace(trace2a,row=2,col=1)
fig33.append_trace(trace3a,row=2,col=1)
elif CC_reg==True and NC_reg==True: ##both
vp=1
fig11.append_trace(trace1,row=2,col=1)
fig11.append_trace(trace1a,row=2,col=1)
fig22.append_trace(trace2,row=2,col=1)
fig22.append_trace(trace2a,row=2,col=1)
fig33.append_trace(trace3,row=2,col=1)
fig33.append_trace(trace3a,row=2,col=1)
###############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)
#write .pdfs
pdf1=fig11.write_image(f"{y_vals} vs. {x_vals}.pdf", engine='kaleido')
pdf2=fig22.write_image(f"{z_vals} vs. {y_vals}.pdf", engine='kaleido')
pdf3=fig33.write_image(f"{x_vals} vs. {z_vals}.pdf", engine='kaleido')
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),fig11,fig22,fig33,[f"{y_vals} vs. {x_vals}.pdf",f"{z_vals} vs. {y_vals}.pdf",f"{x_vals} vs. {z_vals}.pdf"]
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),fig11,fig22,fig33,[f"{y_vals} vs. {x_vals}.pdf",f"{z_vals} vs. {y_vals}.pdf",f"{x_vals} vs. {z_vals}.pdf"]
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': 'diamond', 'Acho': 'square', 'User':'circle', '--':'square'}
fig0= px.scatter_3d(data_frame=temp_xyz,x=x_vals,y=y_vals, z=z_vals , color='class', color_discrete_map={'CC':'blue','Planet.':'lightgreen','CAIs':'#F68F3A','Other':'#AB6AE0','Return':'#00B0F0','NC':'red','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=""))
fig0.update_traces(marker=dict(size=5, line=dict(color='black', width=3)))
#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: ##neither
return gr.update(value=fig0), gr.update(value="Update 3D Regression", visible=False)
def new_users(hide):
if hide==0:
return gr.update(value=1), gr.update(value="Information for New Users"),gr.update(visible=False),gr.update(visible=False),gr.update(visible=False),gr.update(visible=False),gr.update(visible=False),gr.update(visible=False),gr.update(visible=False),gr.update(visible=False),gr.update(visible=False),gr.update(visible=False)
else:
return gr.update(value=0), gr.update(value="Hide Info"),gr.update(visible=True),gr.update(visible=True),gr.update(visible=True),gr.update(visible=True),gr.update(visible=True),gr.update(visible=True),gr.update(visible=True),gr.update(visible=True),gr.update(visible=True),gr.update(visible=True)
##########################
##Begin UI:
with gr.Blocks() as demo:
format= '{text}'
text_with_link=format.format
gr.Markdown(f"""
# CosmoPlot
Last updated October 3rd, 2024 :: {text_with_link(link='mailto:gerrit_budde@brown.edu,dan_razionale@brown.edu', text='Contact')} :: {text_with_link(link='https://sites.brown.edu/budde-lab/', text='Lab Webpage')} :: DOI:{text_with_link(link='https://doi.org/10.26300/zx3r-ev43', text='10.26300/zx3r-ev43')}
Citable Reference: Dan P. Razionale and Gerrit Budde (2024) CosmoPlot: A nucleosynthetic isotope anomaly database and plotting software. 55th Annual Lunar and Planetary Science Conference, {text_with_link(link='https://www.hou.usra.edu/meetings/lpsc2024/pdf/2282.pdf', text='2282.')}""")
with gr.Row():
with gr.Column(scale=23):
with gr.Row():
gr.Markdown(f"CosmoPlot is a combined nucleosynthetic isotope anomaly database and plotting software for bulk meteorites and planetary materials. Nucleosynthetic isotope anomalies are small, mass-independent deviations in the isotopic composition of extraterrestrial materials relative to that of Earth. They originate from the heterogeneous distribution of presolar matter in the solar accretion disk and, as such, are a powerful cosmochemical tool to investigate the early evolution of the Solar System (e.g. {text_with_link(link='https://www.elementsmagazine.org/planetary-genealogy/', text='Burkhardt, 2021')}). The underlying Nucleosynthetic Isotope Anomaly Database (NIAD) provides a comprehensive compilation of published data and literature sources, and is available for download (as an {text_with_link(link='https://huggingface.co/spaces/dpraz/CosmoPlot/blob/main/NIAD.xlsx', text='xlsx-file')}). It will be updated on a regular basis, and users are encouraged to provide comments and data suggestions. The online interface enables users to choose data from the NIAD for a multitude of elements and readily create interactive 2D and 3D diagrams, which also allow plotting user data (see 'Information for New Users').")
with gr.Row():
x_vals=gr.Dropdown(isotopes, value='ε54Cr',label="X-Coordinate",min_width=50)
gr.Button(visible=False)
y_vals=gr.Dropdown(isotopes, value='ε50Ti', label="Y-Coordinate",min_width=50)
gr.Button(visible=False)
z_vals=gr.Dropdown(isotopes, value='ε94Mo', label="Z-Coordinate",min_width=50)
with gr.Row():
with gr.Column():
CC_check=gr.Checkbox(value=True,label="Carbonaceous Meteorites", interactive=True, visible=True)
NC_check=gr.Checkbox(value=True,label="Non-carbonaceous Meteorites", interactive=True, visible=True)
gr.Button(visible=False)
CC_reg=gr.Checkbox(value=False,label="CC Regression Line", interactive=True, visible=True)
NC_reg=gr.Checkbox(value=False,label="NC Regression Line", interactive=True, visible=True)
with gr.Column():
CAI_check=gr.Checkbox(label='CAIs',value=True,interactive=True)
Plan_check=gr.Checkbox(label='Planetary Material',value=True,interactive=True)
SR_check=gr.Checkbox(label='Sample Return',value=True,interactive=True)
Other_check=gr.Checkbox(label='Other',value=True,interactive=True)
with gr.Row():
refresh_btn=gr.Button(value="Refresh Table")
with gr.Row():
threeD= gr.Plot(value=fig0,show_label=False, visible=True)
with gr.Row():
twoD_1=gr.Plot(value=fig1,show_label=False,visible=True, container=False)
with gr.Row():
twoD_2=gr.Plot(value=fig2,show_label=False, visible=True, container=False)
with gr.Row():
twoD_3=gr.Plot(value=fig3,show_label=False,visible=True, container=False)
with gr.Row():
fig_exports=gr.Files(value=["ε50Ti vs. ε54Cr.pdf","ε94Mo vs. ε50Ti.pdf","ε54Cr vs. ε94Mo.pdf"],visible=True, file_count="multiple", label="Download Figure .pdfs")
with gr.Column(scale=20, variant="compact"):
with gr.Row():
user_info_btn=gr.Button(value="Information for New Users",visible=True,size='sm')#
hide=gr.Number(value=1, visible=False)
with gr.Group():
a0=gr.Markdown(r"Dropdowns and Checkboxes:", visible=False)
a1=gr.Markdown(r"Select an isotope from the X-, Y- or Z- dropdown menus to view its reported nucleosynthetic data in the table and plots below. Avoid selecting the same isotope twice. The checkboxes will remove their respective data from the table and plots. The ‘Regression’ checkboxes fit a linear regression through the CC and NC meteorites.", visible=False)
a2=gr.Markdown(r"Data Tables:", visible=False)
a3=gr.Markdown(r"CosmoPlot Compilation: this table includes all selected data from the NIAD compilation sorted by class. Sort your selection alphabetically or sequentially by selecting the caret next to the headers. These data are amenable to simple copy + paste commands with Excel. Any changes, including those from checkboxes, sorting, or added data, can be reverted to default by pressing the ‘Refresh Table’ button.", visible=False)
a4=gr.Markdown(r"Plot your own data: this frame allows you to examine your own data alongside the CosmoPlot compilation. A column exists for every active isotope in the dropdowns. Add new columns by selecting new isotopes from the dropdowns or clicking the ‘Add Column’ button. Headers must exactly match an entry appearing in the dropdown lists. You may leave fields blank, but isotope columns only permit numerical entries. All data will remain in the table until you click the ‘Reset Datatable’ button. Click the ‘Append Data’ button to view your data on the plots.", visible=False)
a5=gr.Markdown(r"3D Regression Dataframe: this frame appears when one or both regression checkboxes are selected. It contains the bounds of the 3D regression (see below). You may edit the 3D regression by changing these bounds and clicking ‘Update 3D Regression’.", visible=False)
a6=gr.Markdown(r"Plots:", visible=False)
a7=gr.Markdown(r"All plots are interactive; several tools are available in the modebar, which appears on the plot when hovered by the cursor. Hover over their icons to display their function. Click on legend entries to temporarily remove them from the plot; double click to isolate them. Symbols provide textboxes with labels, values, and errors when hovered. All 2D plots are accompanied by marginal KDEs which show the relative distribution of x-axis values between CC and NC meteorites. Download these plots as .pdfs by clicking on them in the filegroup below the plots.", visible=False)
a8=gr.Markdown(r"Regressions:", visible=False)
a9=gr.Markdown(r"All 2D regressions are generated using the 'Thiel-Sen estimator', a robust multivariate regression model, in order to reduce the statistical weight placed on outlier data. Their correlation coefficient, as well as their slope and intercept, are visible by hovering the terminal points of the regression. The 3D regression is calculated by combing the two 2D regressions with the best correlation, as less data are usually available with all 3 coordinates filled.", visible=False)
user_info_btn.click(fn=new_users,inputs=[hide], outputs=[hide,user_info_btn,a0,a1,a2,a3,a4,a5,a6,a7,a8,a9])
with gr.Row():
add_data= gr.Dataframe(label="Plot your own data:",headers=["ID","ε54Cr","ε50Ti","ε94Mo"],col_count=4, type="pandas", interactive=True)
with gr.Row():
add_btn=gr.Button(value="Append Data",size='sm')#.style(size="sm")
reset_btn=gr.Button(value="Reset Datatable",size='sm')#.style(size="sm")
with gr.Row():
reg_df=gr.Dataframe(label="3D Regression Dataframe:",headers=["ID","ε54Cr","ε50Ti","ε94Mo"],col_count=(4,'fixed'),type="pandas", interactive=True,row_count=(4,'fixed'),visible=False)
with gr.Row():
update_reg_btn=gr.Button(value="Update 3D Regression",visible=False,size='sm')
with gr.Row():
plotting_df=gr.Dataframe(value=df2,headers=["class","type","group","ε54Cr","ε50Ti","ε94Mo"],label=" CosmoPlot Compilation:",type="pandas", visible=True, interactive=False)
fig01=gr.Plot(value=fig1,visible=False)
fig02=gr.Plot(value=fig2,visible=False)
fig03=gr.Plot(value=fig3,visible=False)
refresh_btn.click(refresh,inputs=[x_vals,y_vals,z_vals], outputs=[plotting_df,CC_check,NC_check,CAI_check,Plan_check,SR_check,Other_check]).success(plot,inputs=[plotting_df,x_vals,y_vals,z_vals,CC_check,NC_check],outputs=[threeD,twoD_1,twoD_2,twoD_3,fig01,fig02,fig03,fig_exports]).success(regs_False,inputs=[],outputs=[CC_reg, NC_reg,reg_df,update_reg_btn])
x_vals.input(fn=updateAdd_xchange,inputs=[x_vals,add_data],outputs=[add_data]).success(update_table,inputs=[x_vals,y_vals,z_vals,plotting_df], outputs=[plotting_df]).success(plot,inputs=[plotting_df,x_vals,y_vals,z_vals,CC_check,NC_check],outputs=[threeD,twoD_1,twoD_2,twoD_3,fig01,fig02,fig03,fig_exports]).success(regs_False,inputs=[],outputs=[CC_reg, NC_reg,reg_df,update_reg_btn])
y_vals.input(fn=updateAdd_ychange,inputs=[y_vals,add_data],outputs=[add_data]).success(update_table,inputs=[x_vals,y_vals,z_vals,plotting_df], outputs=[plotting_df]).success(plot,inputs=[plotting_df,x_vals,y_vals,z_vals,CC_check,NC_check],outputs=[threeD,twoD_1,twoD_2,twoD_3,fig01,fig02,fig03,fig_exports]).success(regs_False,inputs=[],outputs=[CC_reg, NC_reg,reg_df,update_reg_btn])
z_vals.input(fn=updateAdd_zchange,inputs=[z_vals,add_data],outputs=[add_data]).success(update_table,inputs=[x_vals,y_vals,z_vals,plotting_df], outputs=[plotting_df]).success(plot,inputs=[plotting_df,x_vals,y_vals,z_vals,CC_check,NC_check],outputs=[threeD,twoD_1,twoD_2,twoD_3,fig01,fig02,fig03,fig_exports]).success(regs_False,inputs=[],outputs=[CC_reg, NC_reg,reg_df,update_reg_btn])
reset_btn.click(fn=resetAdd,inputs=[x_vals,y_vals,z_vals],outputs=[add_data])
add_btn.click(fn=appendFn,inputs=[add_data,plotting_df],outputs=[plotting_df]).success(fn=twoD_regs,inputs=[CC_reg,NC_reg,x_vals,y_vals,z_vals,plotting_df,CC_check,NC_check], outputs=[twoD_1,twoD_2,twoD_3,reg_df,update_reg_btn,fig01,fig02,fig03,fig_exports]).success(fn=plot_3D_reg,inputs=[plotting_df,reg_df,x_vals, y_vals, z_vals,CC_reg,NC_reg],outputs=[threeD,update_reg_btn])
CC_check.input(fn=cc_checkbox_check,inputs=[plotting_df,CC_check, x_vals,y_vals,z_vals],outputs=[plotting_df]).success(regs_False,inputs=[],outputs=[CC_reg, NC_reg,reg_df,update_reg_btn]).success(plot,inputs=[plotting_df,x_vals,y_vals,z_vals,CC_check,NC_check],outputs=[threeD,twoD_1,twoD_2,twoD_3,fig01,fig02,fig03,fig_exports])
NC_check.input(fn=nc_checkbox_check,inputs=[plotting_df,NC_check, x_vals,y_vals,z_vals],outputs=[plotting_df]).success(regs_False,inputs=[],outputs=[CC_reg, NC_reg,reg_df,update_reg_btn]).success(plot,inputs=[plotting_df,x_vals,y_vals,z_vals,CC_check,NC_check],outputs=[threeD,twoD_1,twoD_2,twoD_3,fig01,fig02,fig03,fig_exports])
CAI_check.input(fn=other_checkbox_check,inputs=[plotting_df,CAI_check,Plan_check,SR_check,Other_check,x_vals,y_vals,z_vals],outputs=[plotting_df]).success(fn=twoD_regs,inputs=[CC_reg,NC_reg,x_vals,y_vals,z_vals,plotting_df,CC_check,NC_check], outputs=[twoD_1,twoD_2,twoD_3,reg_df,update_reg_btn,fig01,fig02,fig03,fig_exports]).success(fn=plot_3D_reg,inputs=[plotting_df,reg_df,x_vals, y_vals, z_vals,CC_reg,NC_reg],outputs=[threeD,update_reg_btn])#.success(plot,inputs=[plotting_df,x_vals,y_vals,z_vals,CC_check,NC_check],outputs=[threeD,twoD_1,twoD_2,twoD_3,fig01,fig02,fig03,fig_exports]) #.success(regs_False,inputs=[],outputs=[CC_reg, NC_reg,reg_df,update_reg_btn])
Plan_check.input(fn=other_checkbox_check,inputs=[plotting_df,CAI_check,Plan_check,SR_check,Other_check,x_vals,y_vals,z_vals],outputs=[plotting_df]).success(fn=twoD_regs,inputs=[CC_reg,NC_reg,x_vals,y_vals,z_vals,plotting_df,CC_check,NC_check], outputs=[twoD_1,twoD_2,twoD_3,reg_df,update_reg_btn,fig01,fig02,fig03,fig_exports]).success(fn=plot_3D_reg,inputs=[plotting_df,reg_df,x_vals, y_vals, z_vals,CC_reg,NC_reg],outputs=[threeD,update_reg_btn])
SR_check.input(fn=other_checkbox_check,inputs=[plotting_df,CAI_check,Plan_check,SR_check,Other_check,x_vals,y_vals,z_vals],outputs=[plotting_df]).success(fn=twoD_regs,inputs=[CC_reg,NC_reg,x_vals,y_vals,z_vals,plotting_df,CC_check,NC_check], outputs=[twoD_1,twoD_2,twoD_3,reg_df,update_reg_btn,fig01,fig02,fig03,fig_exports]).success(fn=plot_3D_reg,inputs=[plotting_df,reg_df,x_vals, y_vals, z_vals,CC_reg,NC_reg],outputs=[threeD,update_reg_btn])
Other_check.input(fn=other_checkbox_check,inputs=[plotting_df,CAI_check,Plan_check,SR_check,Other_check,x_vals,y_vals,z_vals],outputs=[plotting_df]).success(fn=twoD_regs,inputs=[CC_reg,NC_reg,x_vals,y_vals,z_vals,plotting_df,CC_check,NC_check], outputs=[twoD_1,twoD_2,twoD_3,reg_df,update_reg_btn,fig01,fig02,fig03,fig_exports]).success(fn=plot_3D_reg,inputs=[plotting_df,reg_df,x_vals, y_vals, z_vals,CC_reg,NC_reg],outputs=[threeD,update_reg_btn])
CC_reg.input(fn=twoD_regs,inputs=[CC_reg,NC_reg,x_vals,y_vals,z_vals,plotting_df,CC_check,NC_check], outputs=[twoD_1,twoD_2,twoD_3,reg_df,update_reg_btn,fig01,fig02,fig03,fig_exports]).success(fn=plot_3D_reg,inputs=[plotting_df,reg_df,x_vals, y_vals, z_vals,CC_reg,NC_reg],outputs=[threeD,update_reg_btn])
NC_reg.input(fn=twoD_regs,inputs=[CC_reg,NC_reg,x_vals,y_vals,z_vals,plotting_df,CC_check,NC_check], outputs=[twoD_1,twoD_2,twoD_3,reg_df,update_reg_btn,fig01,fig02,fig03,fig_exports]).success(fn=plot_3D_reg,inputs=[plotting_df,reg_df,x_vals, y_vals, z_vals,CC_reg,NC_reg],outputs=[threeD,update_reg_btn])
update_reg_btn.click(fn=plot_3D_reg,inputs=[plotting_df,reg_df,x_vals, y_vals, z_vals,CC_reg,NC_reg],outputs=[threeD,update_reg_btn])
demo.launch(debug=True)