def plot_3D_dirichlet(alpha_values): def dirichlet_pdf(thetas,alphas): norm = gamma(np.sum(alphas))/np.prod([gamma(a) for a in alphas]) if(np.isclose(np.sum(alphas),len(alphas))): return np.ones(thetas.shape[0])*norm else: log_prob = np.log(norm)+np.sum((alphas-1)*np.log(thetas),axis=1) return np.exp(log_prob) s = 30 t1 = [] t2 = [] for i in range(s): t1=list(np.arange(i).astype(float))+t1 t2=list(np.arange(i).astype(float)[::-1])+t2 t1 = np.array(t1) t2 = np.array(t2) t3 = s-t1-t2-2 t1 = t1/(s-2) t2 = t2/(s-2) t3 = t3/(s-2) t1[t1==0]+=0.0001 t2[t2==0]+=0.0001 t3[t3==0]+=0.0001 pdf = dirichlet_pdf(np.concatenate([t1.reshape(-1,1),t2.reshape(-1,1),t3.reshape(-1,1)],axis=1),alpha_values) fig = ff.create_ternary_contour(np.array([t1,t2,t3]), np.array(pdf), pole_labels=['theta1', 'theta2', 'theta3'], interp_mode='cartesian', ncontours=20, colorscale='Viridis') fig = set_basic_layout(fig) fig.update_layout(margin=dict(t=75,l=75,b=75,r=75)) return fig
def make_ternary_plot(flammability_data, dropdown_value): """ Make ternary graph from flammability data. """ data = [] if flammability_data and dropdown_value: flammability_data = json.loads(flammability_data) xf = flammability_data['Xf'] xa = flammability_data['Xa'] xi = flammability_data['Xi'] z = np.array(flammability_data[dropdown_value]) colorscale = 'Hot' ncontours = None showscale = True if dropdown_value == 'phi': # Cap phi values at 2 for i, value in enumerate(z): if value > 2: z[i] = 2 ncontours = 8 colorscale = 'Rainbow' if dropdown_value == 'Flammable': ncontours = 2 showscale = False figure = create_ternary_contour(np.array([xf, xa, xi]), z, pole_labels=['Fuel', 'Air', 'Inert'], interp_mode='cartesian', colorscale=colorscale, showscale=showscale, ncontours=ncontours) data = figure.to_plotly_json()['data'] # Clean up for item in data: item.pop('showlegend', None) layout = copy.deepcopy(plot_layout) layout['title'] = 'Ternary Contour Plot' layout['showlegend'] = False layout['ternary'] = dict( sum=1, aaxis=dict(title='Fuel'), baxis=dict(title='Air'), caxis=dict(title='Inert'), showlegend=False, width=700, ) figure = dict(data=data, layout=layout) return figure
def plot(arg=None,X=None,Y=None,Z=None,E=None,I=None): npzfile = np.load(arg) x = np.array(X) y = np.array(Y) z = np.array(Z) e = np.array(E) alloy_name = str(npzfile['e'][0] + npzfile['e'][1] + npzfile['e'][2]) fig = ff.create_ternary_contour(np.array([x,y,z]), e, pole_labels=[npzfile['e'][0], npzfile['e'][1], npzfile['e'][2]], interp_mode='cartesian', ncontours=5, colorscale='Viridis', showscale=True, showmarkers=True, title=str(alloy_name)) htmlfile = str(alloy_name) +'.html' filename = htmlfile plotly.offline.plot(fig, filename , auto_open=False) return htmlfile
def MakePlots(dff, name): Xf = np.array(dff.Xf.tolist()) Xa = np.array(dff.Xa.tolist()) Xi = np.array(dff.Xi.tolist()) Tad = np.array(dff.Tad.tolist()) phi = np.array(dff.phi.tolist()) phi[phi > 2] = 2 flm = np.array(dff.Flammable.tolist()) pio.orca.ensure_server() time.sleep(10) fgg = ff.create_ternary_contour(np.array([Xf, Xa, Xi]), Tad, pole_labels=['Fuel', 'Air', 'Inert'], interp_mode='cartesian', colorscale='Hot', showscale=True, title=name + 'Tad', showmarkers=True) fgg.write_image(name + "_Tad.png") time.sleep(1) fgg2 = ff.create_ternary_contour(np.array([Xf, Xa, Xi]), flm, pole_labels=['Fuel', 'Air', 'Inert'], interp_mode='cartesian', colorscale='Hot', title=name + 'Flammability', ncontours=2) fgg2.write_image(name + "_flm.png") time.sleep(1) fgg3 = ff.create_ternary_contour(np.array([Xf, Xa, Xi]), phi, pole_labels=['Fuel', 'Air', 'Inert'], interp_mode='cartesian', colorscale='Rainbow', ncontours=8, showscale=True, title=name + 'Equivalence Ratio') fgg3.write_image(name + "_phi.png") return fgg, fgg2, fgg3
def plot(self,title): self.predict_data_mean() fig = ff.create_ternary_contour( np.array([self.tri_grid[:,i] for i in range(3)])/self.resolution, self.y_score_sum, pole_labels=self.axis, interp_mode='cartesian', ncontours=20, colorscale='Rainbow', showmarkers=True, showscale=True, title=title ) fig.show()
def plot_goal_ternary(df: pd.DataFrame, kpis: Dict[str, callable], goals: Dict[str, callable], control_params: set) -> None: """ Arguments --- df: Observation dataframe kpis: Dictionary of funtions that scores a given combination of control params goals: Dictionary of how the goals are metrified. One of the keys must be 'combined' control_params: Set of the columns to be used as features. """ if len(goals.keys()) != 4: raise ValueError('The `goals` dictionary must have four elements') # Group by the control params and apply kpi to each combination output = [] for kpi, kpi_function in kpis.items(): s = df.groupby(list(control_params)).apply(kpi_function) s.name = kpi output.append(s) # Generate a aggregated dataframe for training a regressor agg_df = pd.DataFrame(output).T.reset_index() # Get data y = agg_df.loc[:, kpis.keys()] X = agg_df.loc[:, control_params] # Perform a random forest regression on X->y rf = RandomForestRegressor() rf.fit(X, y) # Use the regression to predict values for each simulation coords = rf.predict(X) # MinMax normalizer def norm(x): return (x - x.min()) / (x.max() - x.min()) # Encapsulate RF regression results in a dict metrics = dict(zip(kpis.keys(), coords.T)) metrics = {k: norm(v) for (k, v) in metrics.items()} labels = [k for k in goals.keys() if k != 'combined'] x = goals[labels[0]](metrics) y = goals[labels[1]](metrics) z = goals[labels[2]](metrics) # Combined Goals definition kpi = norm(goals['combined']([x, y, z])) # Create a matrix for the sides of the triangle (shape: 3xN) xyz = np.stack([x, y, z]).T scaler = MinMaxScaler() # Normalize each side by MinMax xyz = scaler.fit_transform(xyz).T # Normalize each data point so that it sums to 1.0 v = np.round(normalize(xyz, axis=0, norm='l2')**2, decimals=10) # Generate ternary plot fig = ff.create_ternary_contour( v, kpi, pole_labels=[labels[0], labels[1], labels[2]], interp_mode='cartesian', ncontours=15, colorscale='Viridis', showmarkers=True, showscale=True) fig.show()