def complete_tri_set_interpolation(_location_list, _value_list, _scale): """ Because the color function in ternary package only accept coloring based on certain hexagonal points, color on those points need to be determined by interpolation based on density matrix in Cartesian space. Therefore, hexagonal points are first converted to Cartesian space, and their value are interpolated based on density matrix to generate value for plotting. :param _location_list: List of locations of density matrix in Cartesian space. :param _value_list: List of density value of density matrix in Cartesian space. :param _scale: Scale of ternary plot, which determined number of hexagonal points in triangle space. :return: Dict that map location in triangle space to its value (also color) in final ternary plot. """ result_tri_array = np.array(list(simplex_iterator(_scale))) / _scale result_car_array = tri_to_car(result_tri_array) # The set of locations of hexagonal points result_car_array is generated. Its density value is determined by # interpolation with location and value of density matrix. result_value_array = scipy.interpolate.griddata( np.array(_location_list), np.array(_value_list), result_car_array, method='cubic') # Generate Dict to store the location-value mapping of hexagonal points target_dict = {} for (i, j, k), result_value in zip(simplex_iterator(bin_num), result_value_array): target_dict[(i, j)] = result_value return target_dict
def complete_tri_set_interpolation(_location_list, _value_list, _scale): result_tri_array = np.array(list(simplex_iterator(_scale))) / _scale result_car_array = tri_to_car(result_tri_array) result_value_array = scipy.interpolate.griddata( np.array(_location_list), np.array(_value_list), result_car_array, method='cubic') target_dict = {} for (i, j, k), result_value in zip(simplex_iterator(bin_num), result_value_array): target_dict[(i, j)] = result_value return target_dict
def generate_heatmap_data(scale=5): from ternary.helpers import simplex_iterator d = dict() for (i, j, k) in simplex_iterator(scale): d[(i, j, k)] = (i**beta * j**(1-beta)) print i,j,k,d[(i, j, k)] return d
def run(data, version1=True): with gzip.open(model_path, 'rb') as fp: model = pkl.load(fp) with gzip.open(featurizer_path, 'rb') as fp: featurizer = pkl.load(fp) with open(label_path, 'rb') as fp: label_enc = pkl.load(fp) ############## Version 1 ################ if version1: scale = 16 boundary = True prediction = [] for i, j, k in simplex_iterator(scale=scale, boundary=boundary): prediction.append({ 'x': i, 'y': j, 'pred': get_coords(data, normalize([i, j, k]), featurizer, model) }) df = pd.DataFrame(prediction) df_dict = df.to_dict() return df_dict ############## Version 2 ################ else: X = featurizer.featurize(Composition(data)) return model.predict_proba([X])
def generate_random_heatmap_data(scale=5): from ternary.helpers import simplex_iterator d = dict() for (i, j, k) in simplex_iterator(scale): d[(i, j)] = random.random() return d
def featurize_simplex(scale, featurizer, feature_cols=None, scaler=None, tern_axes=['Ca', 'Al', 'Ba']): """ Generate feature matrix for simplex (intended for making heatmaps) Args: scale: simplex scale. Determines point density featurizer: matminer-like featurizer instance feature_cols: subset of column names to use for features. If None, use all columns scaler: fitted scaler instance. If None, feature matrix will not be scaled tern_axes: ternary axes. Default ['Ca','Al','Ba'] Returns: coords: list of simplex coordinates X: feature matrix """ coords = [tup for tup in simplex_iterator(scale)] comps = [get_comp_from_coords(c, tern_axes=tern_axes) for c in coords] df = pd.DataFrame([[comp] for comp in comps], columns=['composition']) featurizer.featurize_dataframe(df, col_id='composition', inplace=True) if feature_cols is None: X = df else: X = df.loc[:, feature_cols] if scaler is not None: X = pd.DataFrame(scaler.transform(X), columns=X.columns) return coords, X
def heatmap_inputs(cat_ox_lims, tuple_scale, pkl_dict, slice_axis, slice_vals, tern_axes, conditions, Ba=0.9): inputs = {} red_feat = {} for slice_val in slice_vals: for tup in simplex_iterator(scale=tuple_scale): formula = sliceformula_from_tuple(tup=tup, slice_val=slice_val, slice_axis=slice_axis, tern_axes=tern_axes, Ba=Ba) try: rf = pkl_dict.dict[formula] except KeyError: rf = formula_redfeat(formula, cat_ox_lims=cat_ox_lims) pkl_dict.dict[formula] = rf red_feat[formula] = rf inp_dict = formula_input(formula, cat_ox_lims, conditions, red_feat=rf) inputs[formula] = inp_dict return inputs
def generate_weights_data_new(scale=20): d = dict() from ternary.helpers import simplex_iterator temp = [] for (i, j, k) in simplex_iterator(scale): temp.append([float(i), float(j), float(k)]) return temp
def predict_simplex(estimator, scale, featurizer=None, feature_cols=None, scaler=None, use_X=None, tern_axes=['Ca', 'Al', 'Ba'], metric='median'): """ Generate predictions for simplex (intended for making heatmaps) Args: estimator: fitted estimator scale: simplex scale. Determines point density featurizer: matminer-like featurizer instance feature_cols: subset of column names to use for features. If None, use all columns scaler: fitted scaler instance. If None, feature matrix will not be scaled use_X: optional arg to provide feature matrix if already calculated. If provided, featurizer, feature_cols, and scaler will be ignored tern_axes: ternary axes. Default ['Ca','Al','Ba'] metric: if 'median', return point estimate. If 'iqr', return IQR of prediction Returns: coords: list of simplex coordinates y: estimator predictions """ if use_X is None: coords, X = featurize_simplex(scale, featurizer, feature_cols, scaler, tern_axes) else: coords = [tup for tup in simplex_iterator(scale)] X = use_X if type(X) == pd.core.frame.DataFrame: X = X.values # handle nans and infs # find rows with any nan or inf values bad_val_idx = np.max(np.array( [np.max(np.isinf(X), axis=1), np.max(np.isnan(X), axis=1)]), axis=0) if np.sum(bad_val_idx) > 0: print( 'Warning: feature matrix contains nans or infs. Number of bad rows: {}' .format(np.sum(bad_val_idx))) # set all features in bad rows to zero so that they don't break estimator.predict() X[bad_val_idx] = 0 if metric == 'median': y = estimator.predict(X) elif metric == 'iqr': lb, ub = predict_interval(estimator, X, 0.682) y = ub - lb # set predictions for bad feature values to nan y[bad_val_idx] = np.nan return coords, y
def generate_heatmap_data_new(scale=20): d = dict() acc = M #read mAP values for all simplex_iterator values generated in tune_weights file from ternary.helpers import simplex_iterator a=0 for (i, j, k) in simplex_iterator(scale): d[(i, j, k)] = color_point_new(float(acc[a])) a+=1 return d
def generate_heatmap_data(scale=5): from ternary.helpers import simplex_iterator d = dict() for (i, j, k) in simplex_iterator(scale): p1 = 0 if (i+j) is not 0: p1 = float(i)/float(i+j) d[(i, j, k)] = (i+j) * np.exp( -(p1 - beta)**2/(2*sigma**2) ) print i,j,k,d[(i, j, k)] return d
def test_simplex_iterator(self): scale = 0 expected = [(0, 0, 0)] points = list(simplex_iterator(scale=scale)) self.assertEqual(points, expected) scale = 1 expected = [(0, 0, 1), (0, 1, 0), (1, 0, 0)] points = list(simplex_iterator(scale=scale)) self.assertEqual(points, expected) scale = 2 expected = [(0, 0, 2), (0, 1, 1), (0, 2, 0), (1, 0, 1), (1, 1, 0), (2, 0, 0)] points = list(simplex_iterator(scale=scale)) self.assertEqual(points, expected) scale = 3 expected = [(0, 0, 3), (0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0), (3, 0, 0)] points = list(simplex_iterator(scale=scale)) self.assertEqual(points, expected)
def test_simplex_iterator_without_boundary(self): scale = 0 expected = [] points = list(simplex_iterator(scale=scale, boundary=False)) self.assertEqual(points, expected) scale = 1 expected = [] points = list(simplex_iterator(scale=scale, boundary=False)) self.assertEqual(points, expected) scale = 2 expected = [] points = list(simplex_iterator(scale=scale, boundary=False)) self.assertEqual(points, expected) scale = 3 expected = [(1, 1, 1)] points = list(simplex_iterator(scale=scale, boundary=False)) self.assertEqual(points, expected)
def heatmap_density(X, Y, Z, scale, boundary=True): """ A function to calculate the how many point located in bin (x, y, z) It is very sutiable for hexgonal bin """ X = np.around(X).astype(int) Y = np.around(Y).astype(int) Z = np.around(Z).astype(int) data = dict() for i, j, k in simplex_iterator(scale=scale, boundary=boundary): xb = (X == i) yb = (Y == j) zb = (Z == k) data[(i, j)] = (xb & yb & zb).sum() return data
def _generate_heatmap_data(f, scale): """Generate RGBA data for a ``simplex to 3D'' heatmap plot. Parameters ---------- f : callable The function to plot. Input: coordinates `right`, `top`, `left` in the simplex, i.e. that sum to 1. Output: a list of 3 numbers between 0 and 1. scale The scale of the ternary plot. Returns ------- d_scaled_point_color : dict Key: a point of the integer simplex defined by `scale`. Value: the RGBA code of the color representing the output of `f`. d_point_values : dict Key: a point of the simplex, with coordinates in (0, 1). Value: the values of function f(right, top, left). Examples -------- >>> def f(right, top, left): ... return [right, 0, 0] >>> d_scaled_point_color, d_point_values = _generate_heatmap_data(f, scale=2) >>> d_scaled_point_color {(0, 0, 2): (0.5, 0.5, 0.5, 1.0), (0, 1, 1): (0.5, 0.5, 0.5, 1.0), (0, 2, 0): (0.5, 0.5, 0.5, 1.0), \ (1, 0, 1): (0.75, 0.5, 0.5, 1.0), (1, 1, 0): (0.75, 0.5, 0.5, 1.0), (2, 0, 0): (1.0, 0.5, 0.5, 1.0)} >>> d_point_values # doctest: +ELLIPSIS {Point(right=Fraction(0, 1), top=Fraction(0, 1), left=Fraction(1, 1)): [Fraction(0, 1), 0, 0], ... """ d_point_values = dict() d_scaled_point_color = dict() for (right, top, left) in simplex_iterator(scale): scaled_point = (right, top, left) point = Point(Fraction(right, scale), Fraction(top, scale), Fraction(left, scale)) values = f(*point) d_point_values[point] = values color = abc_to_rgb(values) d_scaled_point_color[scaled_point] = (float(color[0]), float(color[1]), float(color[2]), 1.) return d_scaled_point_color, d_point_values
def gen_heatmap(comp1, comp2, comp3, scale): def computeValue(comp1, comp2, comp3, quant1, quant2, quant3): glass = { comp1: quant1, comp2: quant2, comp3: quant3, } _, _, m, _, _, _ = model.get_params_from_dict(glass) return m d = dict() for (i, j, k) in simplex_iterator(scale): d[(i, j, k)] = computeValue( comp1, comp2, comp3, i, j, k, ) return d
def ternaryplot(comp1, comp2, comp3, compounds, train_val_viscosity_df, model, model_name, max_distance=0.5): scale = 100 neighbor = 1 distance_to_plot = max_distance metric = 'canberra' parameters_dict = { 'Tg': { 'index': 1, 'label': '$T_{g}$ [K]', 'round': 50, 'bad_val': 400, 'format': lambda x, pos: x if x != 400 else 'OoD', }, 'm': { 'index': 2, 'label': 'Fragility index', 'round': 2, 'bad_val': 10, 'format': lambda x, pos: x if x != 10 else 'OoD', }, } chemtrans = { 'SiO2': r'$\mathrm{SiO_2}$', 'Na2O': r'$\mathrm{Na_2O}$', 'Li2O': r'$\mathrm{Li_2O}$', 'CaO': r'$\mathrm{CaO}$', 'Al2O3': r'$\mathrm{Al_2O_3}$', } base_ternary = [(i, j, k) for i, j, k in simplex_iterator(scale)] df_ternary = pd.DataFrame(base_ternary, columns=[comp1, comp2, comp3]) df_ternary = df_ternary.reindex(compounds, axis=1).fillna(0) data_ternary = df_ternary.div(df_ternary.sum(axis=1), axis=0).values df_train_val = train_val_viscosity_df.drop_duplicates(subset=['ID']) data_train_val = df_train_val.reindex(compounds, axis=1).values min_dist = distance_between_data_and_train( data_ternary, data_train_val, metric=metric, neighbor=neighbor, ) with torch.no_grad(): params_pred = model.viscosity_params_from_composition(df_ternary) for param_name, param_info in parameters_dict.items(): param_values = params_pred[param_name] round_base = param_info['round'] label = param_info['label'] bad_val = param_info['bad_val'] heatmap = \ {k: round_base * round(float(v)/round_base) if d <= max_distance \ else bad_val \ for k, v, d in zip(base_ternary, param_values, min_dist)} fig, tax = ternary.figure(scale=scale) fig.set_size_inches(8 / 1.5, 10 / 1.5) cb_kwargs = { "shrink": 0.9, "pad": 0.10, "aspect": 30, "orientation": "horizontal", 'format': param_info['format'], } tax.heatmap( heatmap, style="hexagonal", use_rgba=False, colorbar=True, cbarlabel=label, cmap='pink_r', cb_kwargs=cb_kwargs, ) tax.clear_matplotlib_ticks() tax.get_axes().axis('off') tax.boundary() tax.left_axis_label( chemtrans.get(comp3, comp3) + ' mol%', fontsize=10, offset=0.14, ) tax.right_axis_label( chemtrans.get(comp2, comp2) + ' mol%', fontsize=10, offset=0.14, ) tax.bottom_axis_label( chemtrans.get(comp1, comp1) + ' mol%', fontsize=10, offset=0.14, ) tax.ticks(axis='lbr', linewidth=1, multiple=scale / 10, offset=0.03) fig.savefig( rf'plots/{model_name}/ternary_{comp1}_{comp2}_{comp3}' f'_{param_name}.png', dpi=300, bbox_inches='tight', pad_inches=2e-2, ) plt.close(fig)
def feature_ternary_heatmap(scale, feature_name, featurizer=None, use_X=None, style='triangular', labelsize=11, add_labeloffset=0, cmap=None, ax=None, figsize=None, vlim=None, multiple=0.1, tick_kwargs={ 'tick_formats': '%.1f', 'offset': 0.02 }, tern_axes=['Ca', 'Al', 'Ba'], tern_labels=['CaO', 'Al$_2$O$_3$', 'BaO']): """ """ if use_X is None: coords, X = featurize_simplex(scale, featurizer, feature_cols=featurizer.feature_labels(), tern_axes=tern_axes) X = pd.DataFrame(X, columns=featurizer.feature_labels()) else: coords = [tup for tup in simplex_iterator(scale)] X = use_X y = X.loc[:, feature_name] if vlim is None: vmin = min(y) vmax = max(y) else: vmin, vmax = vlim points = dict(zip([c[0:2] for c in coords], y)) if ax == None: fig, ax = plt.subplots(figsize=figsize) tfig, tax = ternary.figure(scale=scale, ax=ax) else: tax = ternary.TernaryAxesSubplot(scale=scale, ax=ax) tax.heatmap(points, style=style, colorbar=False, cmap=cmap, vmin=vmin, vmax=vmax) #rescale_ticks(tax,new_scale=axis_scale,multiple = multiple, **tick_kwargs) tax.boundary() tax.ax.axis('off') tax.right_corner_label(tern_labels[0], fontsize=labelsize, va='center', offset=0.08 + add_labeloffset) tax.top_corner_label(tern_labels[1], fontsize=labelsize, va='center', offset=0.05 + add_labeloffset) tax.left_corner_label(tern_labels[2], fontsize=labelsize, va='center', offset=0.08 + add_labeloffset) tax._redraw_labels() return tax
def generate_ternary_heatmap(PL, scale=1.0): from ternary.helpers import simplex_iterator d = dict() for (i,j,k) in simplex_iterator(scale): d[(i,j)] = PL[i-1,j-1] return d
### Machine Learning Fit # Make a list of variables for machine learning names = ('Lithium', 'Manganese') variables = df.loc[:, names] # Define a Pipeline that scales the data and applies the model reg_avgv = Pipeline([('scl', StandardScaler()), ('clf', svm.SVR(kernel='rbf', gamma=0.8))]) # Fit the variables to the avgv reg_avgv.fit(variables, df.avgv) # get variables from ternary.helpers import simplex_iterator variables = [] for (i, j, k) in simplex_iterator(100): variables.append([i, j, k]) variables = np.array(variables) / 100 # print(variables.shape) # Get the predicted average voltage from the model and save it to the DataFrame pred = reg_avgv.predict(variables[:, 0:2]) # print(pred) d = {} for index in range(variables.shape[0]): d[(variables[index][0] * 100, variables[index][1] * 100)] = pred[index] # print(d) figure, tax = ternary.figure(scale=100)
def generate_heatmap_data(scale=5): from ternary.helpers import simplex_iterator d = dict() for (i, j, k) in simplex_iterator(scale): d[(i, j, k)] = color_point(i, j, k, scale) return d
def plot_ternary_hull(hull, axis=None, show=True, plot_points=True, hull_cutoff=None, fig_height=None, label_cutoff=None, label_corners=True, expecting_cbar=True, labels=None, plot_fname=None, hull_dist_unit="meV", efmap=None, sampmap=None, capmap=None, pathways=False, **kwargs): """ Plot calculated ternary hull as a 2D projection. Parameters: hull (matador.hull.QueryConvexHull): matador hull object. Keyword arguments: axis (matplotlib.axes.Axes): matplotlib axis object on which to plot. show (bool): whether or not to show plot in X window. plot_points (bool): whether or not to plot each structure as a point. label_cutoff (float/:obj:`tuple` of :obj:`float`): draw labels less than or between these distances form the hull, also read from hull.args. expecting_cbar (bool): whether or not to space out the plot to preserve aspect ratio if a colourbar is present. labels (bool): whether or not to label on-hull structures label_corners (bool): whether or not to put axis labels on corners or edges. hull_dist_unit (str): either "eV" or "meV", png/pdf/svg (bool): whether or not to write the plot to a file. plot_fname (str): filename to write plot to. efmap (bool): plot heatmap of formation energy, sampmap (bool): plot heatmap showing sampling density, capmap (bool): plot heatmap showing gravimetric capacity. pathways (bool): plot the pathway from the starting electrode to active ion. Returns: matplotlib.axes.Axes: matplotlib axis with plot. """ import ternary import matplotlib.pyplot as plt import matplotlib.colors as colours from matador.utils.chem_utils import get_generic_grav_capacity plt.rcParams['axes.linewidth'] = 0 plt.rcParams['xtick.major.size'] = 0 plt.rcParams['ytick.major.size'] = 0 plt.rcParams['xtick.minor.size'] = 0 plt.rcParams['ytick.minor.size'] = 0 if efmap is None: efmap = hull.args.get('efmap') if sampmap is None: sampmap = hull.args.get('sampmap') if capmap is None: capmap = hull.args.get('capmap') if pathways is None: pathways = hull.args.get('pathways') if labels is None: labels = hull.args.get('labels') if label_cutoff is None: label_cutoff = hull.args.get('label_cutoff') if label_cutoff is None: label_cutoff = 0 else: labels = True if hull_cutoff is None and hull.hull_cutoff is None: hull_cutoff = 0 else: hull_cutoff = hull.hull_cutoff print('Plotting ternary hull...') if capmap or efmap: scale = 100 elif sampmap: scale = 20 else: scale = 1 if axis is not None: fig, ax = ternary.figure(scale=scale, ax=axis) else: fig, ax = ternary.figure(scale=scale) # maintain aspect ratio of triangle if fig_height is None: _user_height = plt.rcParams.get("figure.figsize", (8, 6))[0] else: _user_height = fig_height if capmap or efmap or sampmap: fig.set_size_inches(_user_height, 5 / 8 * _user_height) elif not expecting_cbar: fig.set_size_inches(_user_height, _user_height) else: fig.set_size_inches(_user_height, 5 / 6.67 * _user_height) ax.boundary(linewidth=2.0, zorder=99) ax.clear_matplotlib_ticks() chempot_labels = [ get_formula_from_stoich(get_stoich_from_formula(species, sort=False), sort=False, tex=True) for species in hull.species ] ax.gridlines(color='black', multiple=scale * 0.1, linewidth=0.5) ticks = [float(val) for val in np.linspace(0, 1, 6)] if label_corners: # remove 0 and 1 ticks when labelling corners ticks = ticks[1:-1] ax.left_corner_label(chempot_labels[2], fontsize='large') ax.right_corner_label(chempot_labels[0], fontsize='large') ax.top_corner_label(chempot_labels[1], fontsize='large', offset=0.16) else: ax.left_axis_label(chempot_labels[2], fontsize='large', offset=0.12) ax.right_axis_label(chempot_labels[1], fontsize='large', offset=0.12) ax.bottom_axis_label(chempot_labels[0], fontsize='large', offset=0.08) ax.set_title('-'.join(['{}'.format(label) for label in chempot_labels]), fontsize='large', y=1.02) ax.ticks(axis='lbr', linewidth=1, offset=0.025, fontsize='small', locations=(scale * np.asarray(ticks)).tolist(), ticks=ticks, tick_formats='%.1f') concs = np.zeros((len(hull.structures), 3)) concs[:, :-1] = hull.structures[:, :-1] for i in range(len(concs)): # set third triangular coordinate concs[i, -1] = 1 - concs[i, 0] - concs[i, 1] stable = concs[np.where(hull.hull_dist <= 0 + EPS)] # sort by hull distances so things are plotting the right order concs = concs[np.argsort(hull.hull_dist)].tolist() hull_dist = np.sort(hull.hull_dist) filtered_concs = [] filtered_hull_dists = [] for ind, conc in enumerate(concs): if conc not in filtered_concs: if hull_dist[ind] <= hull.hull_cutoff or (hull.hull_cutoff == 0 and hull_dist[ind] < 0.1): filtered_concs.append(conc) filtered_hull_dists.append(hull_dist[ind]) if hull.args.get('debug'): print('Trying to plot {} points...'.format(len(filtered_concs))) concs = np.asarray(filtered_concs) hull_dist = np.asarray(filtered_hull_dists) min_cut = 0.0 max_cut = 0.2 if hull_dist_unit.lower() == "mev": hull_dist *= 1000 min_cut *= 1000 max_cut *= 1000 hull.colours = list(plt.rcParams['axes.prop_cycle'].by_key()['color']) hull.default_cmap_list = get_linear_cmap(hull.colours[1:4], list_only=True) hull.default_cmap = get_linear_cmap(hull.colours[1:4], list_only=False) n_colours = len(hull.default_cmap_list) colours_hull = hull.default_cmap_list cmap = hull.default_cmap cmap_full = plt.cm.get_cmap('Pastel2') pastel_cmap = colours.LinearSegmentedColormap.from_list( 'Pastel2', cmap_full.colors) for plane in hull.convex_hull.planes: plane.append(plane[0]) plane = np.asarray(plane) ax.plot(scale * plane, c=hull.colours[0], lw=1.5, alpha=1, zorder=98) if pathways: for phase in stable: if phase[0] == 0 and phase[1] != 0 and phase[2] != 0: ax.plot([scale * phase, [scale, 0, 0]], c='r', alpha=0.2, lw=6, zorder=99) # add points if plot_points: colours_list = [] colour_metric = hull_dist for i, _ in enumerate(colour_metric): if hull_dist[i] >= max_cut: colours_list.append(n_colours - 1) elif hull_dist[i] <= min_cut: colours_list.append(0) else: colours_list.append( int((n_colours - 1) * (hull_dist[i] / max_cut))) colours_list = np.asarray(colours_list) ax.scatter(scale * stable, marker='o', color=hull.colours[1], edgecolors='black', zorder=9999999, s=150, lw=1.5) ax.scatter(scale * concs, colormap=cmap, colorbar=True, cbarlabel='Distance from hull ({}eV/atom)'.format( "m" if hull_dist_unit.lower() == "mev" else ""), c=colour_metric, vmax=max_cut, vmin=min_cut, zorder=1000, s=40, alpha=0) for i, _ in enumerate(concs): ax.scatter(scale * concs[i].reshape(1, 3), color=colours_hull[colours_list[i]], marker='o', zorder=10000 - colours_list[i], s=70 * (1 - float(colours_list[i]) / n_colours) + 15, lw=1, edgecolors='black') # add colourmaps if capmap: capacities = dict() from ternary.helpers import simplex_iterator for (i, j, k) in simplex_iterator(scale): capacities[(i, j, k)] = get_generic_grav_capacity([ float(i) / scale, float(j) / scale, float(scale - i - j) / scale ], hull.species) ax.heatmap(capacities, style="hexagonal", cbarlabel='Gravimetric capacity (mAh/g)', vmin=0, vmax=3000, cmap=pastel_cmap) elif efmap: energies = dict() fake_structures = [] from ternary.helpers import simplex_iterator for (i, j, k) in simplex_iterator(scale): fake_structures.append([float(i) / scale, float(j) / scale, 0.0]) fake_structures = np.asarray(fake_structures) plane_energies = hull.get_hull_distances(fake_structures, precompute=False) ind = 0 for (i, j, k) in simplex_iterator(scale): energies[(i, j, k)] = -1 * plane_energies[ind] ind += 1 if isinstance(efmap, str): efmap = efmap else: efmap = 'BuPu_r' ax.heatmap(energies, style="hexagonal", cbarlabel='Formation energy (eV/atom)', vmax=0, cmap=efmap) elif sampmap: sampling = dict() from ternary.helpers import simplex_iterator eps = 1.0 / float(scale) for (i, j, k) in simplex_iterator(scale): sampling[(i, j, k)] = np.size( np.where((concs[:, 0] <= float(i) / scale + eps) * (concs[:, 0] >= float(i) / scale - eps) * (concs[:, 1] <= float(j) / scale + eps) * (concs[:, 1] >= float(j) / scale - eps) * (concs[:, 2] <= float(k) / scale + eps) * (concs[:, 2] >= float(k) / scale - eps))) ax.heatmap(sampling, style="hexagonal", cbarlabel='Number of structures', cmap='afmhot') # add labels if labels: label_cursor = _get_hull_labels(hull, label_cutoff=label_cutoff) if len(label_cursor) == 1: label_coords = [[0.25, 0.5]] else: label_coords = [[ 0.1 + (val - 0.5) * 0.3, val ] for val in np.linspace(0.5, 0.8, int(round(len(label_cursor) / 2.) + 1))] label_coords += [[0.9 - (val - 0.5) * 0.3, val + 0.2] for val in np.linspace( 0.5, 0.8, int(round(len(label_cursor) / 2.)))] from matador.utils.hull_utils import barycentric2cart for ind, doc in enumerate(label_cursor): conc = np.asarray(doc['concentration'] + [1 - sum(doc['concentration'])]) formula = get_formula_from_stoich(doc['stoichiometry'], sort=False, tex=True, latex_sub_style=r'\mathregular', elements=hull.species) arrowprops = dict(arrowstyle="-|>", color='k', lw=2, alpha=0.5, zorder=1, shrinkA=2, shrinkB=4) cart = barycentric2cart([doc['concentration'] + [0]])[0][:2] min_dist = 1e20 closest_label = 0 for coord_ind, coord in enumerate(label_coords): dist = np.sqrt((cart[0] - coord[0])**2 + (cart[1] - coord[1])**2) if dist < min_dist: min_dist = dist closest_label = coord_ind ax.annotate( formula, scale * conc, textcoords='data', xytext=[scale * val for val in label_coords[closest_label]], ha='right', va='bottom', arrowprops=arrowprops) del label_coords[closest_label] plt.tight_layout(w_pad=0.2) # important for retaining labels if exporting to PDF # see https://github.com/marcharper/python-ternary/issues/36 ax._redraw_labels() # noqa if hull.savefig: fname = plot_fname or ''.join(hull.species) + '_hull' for ext in SAVE_EXTS: if hull.args.get(ext) or kwargs.get(ext): plt.savefig('{}.{}'.format(fname, ext), bbox_inches='tight', transparent=True) print('Wrote {}.{}'.format(fname, ext)) elif show: print('Showing plot...') plt.show() return ax
def _generate_heatmap_data(scale=5): from ternary.helpers import simplex_iterator d = dict() for (i, j, k) in simplex_iterator(scale): d[(i, j, k)] = _color_point(i, j, k, scale) return d
def generate_random_heatmap_data(scale=5): from ternary.helpers import simplex_iterator d = dict() for (i,j,k) in simplex_iterator(scale): d[(i,j)] = random.random() return d
def quat_slice_heatmap2(tuple_scale, zfunc, slice_val, zfunc_kwargs={}, style='triangular', slice_axis='Y', tern_axes=['Co', 'Fe', 'Zr'], labelsize=14, add_labeloffset=0, cmap=plt.cm.viridis, ax=None, figsize=None, vmin=None, vmax=None, Ba=1, multiple=0.1, tick_kwargs={ 'tick_formats': '%.1f', 'offset': 0.02 }): """ get zvals from formula instead of tup """ axis_scale = 1 - slice_val tuples = [] zvals = [] for tup in simplex_iterator(scale=tuple_scale): tuples.append(tup) formula = sliceformula_from_tuple(tup, slice_val=slice_val, slice_axis=slice_axis, tern_axes=tern_axes, Ba=Ba) zvals.append(zfunc(formula, **zfunc_kwargs)) if vmin == None: vmin = min(zvals) if vmax == None: vmax = max(zvals) d = dict(zip([t[0:2] for t in tuples], zvals)) if ax == None: fig, ax = plt.subplots(figsize=figsize) tfig, tax = ternary.figure(scale=tuple_scale, ax=ax) else: tax = ternary.TernaryAxesSubplot(scale=tuple_scale, ax=ax) tax.heatmap(d, style=style, colorbar=False, cmap=cmap, vmin=vmin, vmax=vmax) rescale_ticks(tax, new_scale=axis_scale, multiple=multiple, **tick_kwargs) tax.boundary() tax.ax.axis('off') tax.right_corner_label(tern_axes[0], fontsize=labelsize, offset=0.08 + add_labeloffset) tax.top_corner_label(tern_axes[1], fontsize=labelsize, offset=0.2 + add_labeloffset) tax.left_corner_label(tern_axes[2], fontsize=labelsize, offset=0.08 + add_labeloffset) tax._redraw_labels() return tax, vmin, vmax