def plot_decision_boundaries2(preds, tn, q1, q2, loc='upper left', title=None, colors=None): if colors == None: colors = [ '#96ceb4', 'gold', 'lawngreen', 'black', 'green', 'red', 'purple', 'blue', 'grey' ] fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 4)) for id_, label in enumerate(list(tn['Particle_class'])): obs = preds[preds['True FFT Label'] == label] if len(obs) == 0: continue points = obs[[q1, q2]].values hull = ConvexHull(points) cent = np.mean(points, 0) pts = [] for pt in points[hull.simplices]: pts.append(pt[0].tolist()) pts.append(pt[1].tolist()) pts.sort(key=lambda p: np.arctan2(p[1] - cent[1], p[0] - cent[0])) pts = pts[0::2] # Deleting duplicates pts.insert(len(pts), pts[0]) k = 1.1 #color = 'green' poly = Polygon(k*(np.array(pts)- cent) + cent, facecolor=colors[id_], alpha=0.2,\ label = label) poly.set_capstyle('round') ax1.add_patch(poly) #ax1.fill(obs[q1], obs[q2], c = colors[id_], label = label) ax1.legend(loc=loc, shadow=True, fancybox=True, prop={'size': 8}) ax1.set_title('True :' + q1 + ' vs ' + q2) ax1.set_xscale('log') ax1.set_yscale('log') ax1.set_xlabel(q1) ax1.set_ylabel(q2) ax1.set_xlim(1, 10**6) ax1.set_ylim(1, 10**6) for id_, label in enumerate(list(tn['Particle_class'])): obs = preds[preds['Pred FFT Label'] == label] if len(obs) == 0: continue points = obs[[q1, q2]].values hull = ConvexHull(points) cent = np.mean(points, 0) pts = [] for pt in points[hull.simplices]: pts.append(pt[0].tolist()) pts.append(pt[1].tolist()) pts.sort(key=lambda p: np.arctan2(p[1] - cent[1], p[0] - cent[0])) pts = pts[0::2] # Deleting duplicates pts.insert(len(pts), pts[0]) k = 1.1 #color = 'green' poly = Polygon(k*(np.array(pts)- cent) + cent, facecolor=colors[id_], alpha=0.2,\ label = label) poly.set_capstyle('round') ax2.add_patch(poly) #ax1.fill(obs[q1], obs[q2], c = colors[id_], label = label) ax2.legend(loc=loc, shadow=True, fancybox=True, prop={'size': 8}) ax2.set_title('Pred :' + q1 + ' vs ' + q2) ax2.set_xscale('log') ax2.set_yscale('log') ax2.set_xlabel(q1) ax2.set_ylabel(q2) ax2.set_xlim(1, 10**6) ax2.set_ylim(1, 10**6) if title != None: plt.savefig(title)
@license: MIT Licence @file: plot_convex_hull.py @time: 2020/10/18 """ import numpy as np from scipy.spatial import ConvexHull import matplotlib.pyplot as plt from matplotlib.patches import Polygon points = np.random.rand(30, 2) # 30 random points in 2-D hull = ConvexHull(points) plt.plot(points[:, 0], points[:, 1], 'o') cent = np.mean(points, 0) pts = [] for pt in points[hull.simplices]: pts.append(pt[0].tolist()) pts.append(pt[1].tolist()) pts.sort(key=lambda p: np.arctan2(p[1] - cent[1], p[0] - cent[0])) pts = pts[0::2] # Deleting duplicates pts.insert(len(pts), pts[0]) k = 1 color = 'green' poly = Polygon(k * (np.array(pts) - cent) + cent, facecolor=color, alpha=0.2) poly.set_capstyle('round') plt.gca().add_patch(poly) plt.show()
def compare_prms_models(models, mode='trace', hold=0): '''Compare prms from analytics''' import pandas as pd #spaces=[('mu','sigma'),('sigma','gamma'),('sigma','zeta') ] spaces = [('mu', 'sigma'), ('gamma', 'zeta')] nbpanels = len(spaces) panel = MutableInt(0) if mode == 'hull': plt.figure() for space in spaces: xrge, yrge = np.array([0, 0]), np.array([0, 0]) auto_subplot(plt, nbpanels, panel, rows=1) X = space[0] Y = space[1] plt.xlabel(r'$\{}$'.format(X)) plt.ylabel(r'$\{}$'.format(Y)) legends = [] for im, m in enumerate(models): color = get_cmap(im, len(models)) model, mdict = m plotopts = mdict.get('options', {}) var1, var2 = mdict['vars'] ms = [] for v2 in mdict[var2]: table = [] for v1 in mdict[var1]: #for var in itertools.product(*[mdict[l] for l in vlabels] ) : dico = {} dico.update(mdict) dico[var1] = v1 dico[var2] = v2 #for lab,val in zip(vlabels,var): #dico[lab]=val table.append(dict(model(**dico))) #print table[-1] measure = pd.DataFrame(table) x = measure[X] y = measure[Y] ms.append((x, y)) if mode == 'trace': plot(x, y, hold=1, color=color, **plotopts) elif mode == 'scatter': scatter(x, y, hold=1, c=color, alpha=0.1, edgecolors='none', **plotopts) if mode == 'fill': x, y = zip(*ms) plt.fill_between(x[0], np.min(y, axis=0), np.max(y, axis=0), facecolor=color) elif mode == 'hull': from scipy.spatial import ConvexHull from matplotlib.patches import Polygon points = np.concatenate(ms, axis=1).T if Y == 'zeta' and model == model_trophic_satur: points[:, 1] = np.random.randint(0, 2, points.shape[0]) #points=np.array((np.array(x).ravel(),np.array(y).ravel())).T hull = ConvexHull(points) #print points[hull.simplices] #scatter(points[:,0],points[:,1],hold=1,c=color,alpha=1.,edgecolors='none',**plotopts) cent = np.mean(points, 0) pts = [] for pt in points[hull.simplices]: pts.append(pt[0].tolist()) pts.append(pt[1].tolist()) pts.sort( key=lambda p: np.arctan2(p[1] - cent[1], p[0] - cent[0])) pts = pts[0::2] # Deleting duplicates pts.insert(len(pts), pts[0]) k = 1.1 poly = Polygon(k * (np.array(pts) - cent) + cent, alpha=0.5, facecolor=color) #facecolor=color, alpha=1) poly.set_capstyle('round') plt.gca().add_patch(poly) xrge = [f(points[:, 0]) for f in (np.min, np.max)] yrge = [f(points[:, 1]) for f in (np.min, np.max)] xspan = xrge[1] - xrge[0] yspan = yrge[1] - yrge[0] plt.xlim(xmin=xrge[0] - xspan / 2., xmax=xrge[1] + xspan / 2.) plt.ylim(ymin=yrge[0] - yspan / 2., ymax=yrge[1] + yspan / 2.) plt.tight_layout() if 'legend' in mdict: legends.append(mdict['legend']) if legends: plt.legend(legends) if not hold: plt.show()
def main(): tic = time.perf_counter() gn = Granatum() sample_coords = gn.get_import("viz_data") value = gn.get_import("value") coloring_type = gn.get_arg("coloring_type") bounding_stdev = gn.get_arg("bounding_stdev") label_location = gn.get_arg("label_location") label_transform = gn.get_arg("label_transform") labelXaxis = gn.get_arg("labelXaxis") labelYaxis = gn.get_arg("labelYaxis") sigfigs = gn.get_arg("sigfigs") numticks = gn.get_arg("numticks") font = gn.get_arg('font') coords = sample_coords.get("coords") dim_names = sample_coords.get("dimNames") seed = gn.get_arg('random_seed') random.seed(seed) np.random.seed(seed) df = pd.DataFrame( { "x": [a[0] for a in coords.values()], "y": [a[1] for a in coords.values()], "value": pd.Series(value) }, index=coords.keys()) target_dpi = 300 target_width = 7.5 # inches target_height = 6.5 # inches font_size_in_in = font / 72.0 # inches font_size_in_px = font_size_in_in * target_dpi try: if coloring_type == "categorical": uniq = df["value"].unique() uniq.sort(kind="stable") num = uniq.shape[0] COLORS2 = plt.get_cmap('gist_rainbow') carr = [0] * df.shape[0] listcats = list(df["value"]) miny = min(list(df["y"])) maxy = max(list(df["y"])) scaley = (maxy - miny) / (target_height * target_dpi) print("Scaley = {}".format(scaley)) colorhash = {} colorstep = np.ceil(256.0 / num) coffset = randrange(colorstep) grouptocolor = np.random.choice(np.arange(num), num, replace=False) for i, cat in enumerate(uniq): dff = df[df["value"] == cat] xs = list(dff["x"]) ys = list(dff["y"]) #avgx = sum(dff["x"]) / len(dff["x"]) #avgy = sum(dff["y"]) / len(dff["y"]) #plt.scatter(x=dff["x"], y=dff["y"], s=5000 / df.shape[0], c=COLORS[i].hex_l, label=cat) #plt.scatter(x=dff["x"], y=dff["y"], s=5000 / df.shape[0], c=[abs(hash(cat)) % 256]*len(dff["x"]), cmap=COLORS2, label=cat) #plt.scatter(x=dff["x"], y=dff["y"], s=5000 / df.shape[0], c=abs(hash(cat)) % 256, cmap=COLORS2, label=cat) #abs(hash(cat)) colorindex = (coffset + grouptocolor[i] * colorstep) % 256 colorhash[cat] = colorindex craw = COLORS2((colorindex + 0.0) / 256.0) clr = [craw[0], craw[1], craw[2], 0.2] whitetransparent = [1.0, 1.0, 1.0, 0.5] coloropaque = [craw[0], craw[1], craw[2], 1.0] if len(xs) > 3: pts = list(zip(xs, ys)) cent = np.mean(pts, axis=0) lengs = list( map( lambda p: math.sqrt( (p[0] - cent[0]) * (p[0] - cent[0]) + (p[1] - cent[1]) * (p[1] - cent[1])), pts)) avgleng = st.mean(lengs) stdleng = st.stdev(lengs) * bounding_stdev rpts = [] if (stdleng > 0.0): for j, ln in enumerate(lengs): if (ln - avgleng < stdleng): rpts.append(pts[j]) pts = rpts cent = np.mean(pts, axis=0) hull = ConvexHull(pts) ptslist = [] for pt in hull.simplices: ptslist.append(pts[pt[0]]) ptslist.append(pts[pt[1]]) ptslist.sort(key=lambda p: np.arctan2( p[1] - cent[1], p[0] - cent[0])) ptslist = ptslist[0::2] ptslist.insert(len(ptslist), ptslist[0]) lowestpt = ptslist[0] if label_location == 'bottom': for pt in ptslist: if (pt[1] < lowestpt[1]): lowestpt = pt else: lowestpt = ptslist[randrange(len(ptslist))] if (bounding_stdev >= 0.0): poly = Polygon(1.1 * (np.array(ptslist) - cent) + cent, facecolor=clr) poly.set_capstyle('round') plt.gca().add_patch(poly) poly.set_color(clr) label_text = cat if label_transform == "numbers": label_text = re.sub("[^0-9]", "", cat) txt = plt.text(lowestpt[0], lowestpt[1] - scaley * font_size_in_px * 1.2, label_text, fontsize=font, fontname="Arial", ha="center", va="center", color="black", bbox=dict(boxstyle="round", fc=whitetransparent, ec=coloropaque)) # plt.gca().add_artist(txt) for j, x in enumerate(listcats): if x == cat: carr[j] = colorhash[cat] #carr[j] = colorhash[cat] / 256.0 #int(abs(hash(cat)) % 256) plt.scatter(x=df["x"], y=df["y"], s=5000 / df.shape[0], c=carr, cmap=COLORS2) lgd = plt.legend(markerscale=6, loc='upper center', bbox_to_anchor=(0.5, -0.05), ncol=5) #60 / (5000 / df.shape[0]) elif coloring_type == "continuous": plt.scatter(x=df["x"], y=df["y"], s=5000 / df.shape[0], c=df["value"], cmap="Reds") plt.colorbar() xmin, xmax = plt.gca().get_xlim() ymin, ymax = plt.gca().get_ylim() # stepsizex=(xmax-xmin)/numticks # stepsizey=(ymax-ymin)/numticks xtickArray = resetArray(xmin, xmax, numticks, sigfigs) ytickArray = resetArray(ymin, ymax, numticks, sigfigs) # plt.xticks(np.arange(xmin, xmax+stepsizex, step=stepsizex), fontsize=font, fontname="Arial") # plt.yticks(np.arange(ymin, ymax+stepsizey, step=stepsizey), fontsize=font, fontname="Arial") plt.xlim(xtickArray[0], xtickArray[-1]) plt.ylim(ytickArray[0], ytickArray[-1]) plt.xticks(xtickArray, fontsize=font, fontname="Arial") plt.yticks(ytickArray, fontsize=font, fontname="Arial") if labelXaxis == "": plt.xlabel(dim_names[0], fontsize=font, fontname="Arial") else: plt.xlabel(labelXaxis, fontsize=font, fontname="Arial") if labelYaxis == "": plt.ylabel(dim_names[1], fontsize=font, fontname="Arial") else: plt.ylabel(labelYaxis, fontsize=font, fontname="Arial") # plt.tight_layout() gn.add_current_figure_to_results( "Scatter-plot", dpi=target_dpi, width=target_width * target_dpi, height=target_height * target_dpi, savefig_kwargs={'bbox_inches': 'tight'}) toc = time.perf_counter() time_passed = round(toc - tic, 2) timing = "* Finished sample coloring step in {} seconds*".format( time_passed) gn.add_result(timing, "markdown") gn.commit() except Exception as e: plt.figure() plt.text( 0.05, 0.7, 'Values used as colors and type of sample metadata are incompatible with each other' ) if coloring_type == 'categorical': new_coloring_type = 'continuous' else: new_coloring_type = 'categorical' plt.text( 0.05, 0.5, 'Retry the step with ' + new_coloring_type + ' instead of ' + coloring_type) plt.axis('off') gn.add_current_figure_to_results('Scatter-plot') gn.commit()
def plot_constraints(solver, solution_point): variables = solver.variables() list_of_constraints = solver.constraints() x_coeffs = [] y_coeffs = [] rhs_values = [] lines = [] for constraint in list_of_constraints: low_bound = constraint.lb() upp_bound = constraint.ub() if (low_bound != solver.infinity() and low_bound != -solver.infinity()): rhs = low_bound else: rhs = upp_bound x_coeff = constraint.GetCoefficient(variables[0]) y_coeff = constraint.GetCoefficient(variables[1]) new_line = Line(x_coeff, y_coeff, rhs) lines.append(new_line) x_coeffs.append(x_coeff) y_coeffs.append(y_coeff) rhs_values.append(rhs) numEquations = len(solver.constraints()) y_vals = [] #Display lines of constraints for i in range(numEquations): x_coeff = x_coeffs[i - 1] y_coeff = y_coeffs[i - 1] rhs = rhs_values[i - 1] x = np.linspace(-20, 20, 2000) #solve constraint in terms of x if (y_coeff == 0): y = 0 else: y = (rhs - (x_coeff * x)) / y_coeff y_vals.append(y) points = [] #Find points of intersection for lineOne in lines: for lineTwo in lines: if (lineOne != lineTwo): (x, y) = find_intersect(lineOne, lineTwo) points.append([x, y]) points = np.array(points) #Shade feasible region chull = ConvexHull(points) for simplex in chull.simplices: plt.plot(points[simplex, 0], points[simplex, 1], 'k-') cent = np.mean(points, 0) pts = [] for pt in points[chull.simplices]: pts.append(pt[0].tolist()) pts.append(pt[1].tolist()) pts.sort(key=lambda p: np.arctan2(p[1] - cent[1], p[0] - cent[0])) pts = pts[0::2] # Deleting duplicates pts.insert(len(pts), pts[0]) k = 1.0 color = 'red' poly = Polygon(k * (np.array(pts) - cent) + cent, facecolor=color, alpha=0.2) poly.set_capstyle('round') plt.gca().add_patch(poly) plt.arrow(3, 2, -2, -2, shape='full', head_width=0.05, head_length=0.05, color='blue') plt.arrow(3.2, 1, -2.2, -2, shape='full', head_width=0.05, head_length=0.05, color='blue') #Plot solution point plt.plot(solution_point[0], solution_point[1], color='green', marker='x', markersize=10.0) plt.show()