def highlight_plot(self, param): color_select = [] for i in range(len(self.config_all)): if self.colors[i] != 'none' and param[1][i]: color_select.append(self.colors[i]) else: pass config_ = [] config_select = [] for i in range(len(self.config_all)): config = [] if param[0][i] and param[1][i]: current_row = param[2][i] for j in range(len(self.config_all[i])): if self.config_all[i][j]: config.append(self.config_all[i][j][current_row]) config_.append(config) config_select_ = list(map(list, zip(*config_))) config_select.append(config_select_) detect = Detection(self.obj, config_select) patches, paths = detect.plot() for i in range(len(patches)): p = PatchCollection(patches[i], color=color_select[i], edgecolor=color_select[i], alpha=0.6) p.set_zorder(6) self.ax.add_collection(p) for m in range(len(paths)): for n in range(len(paths[m])): patch_polygon = PathPatch(paths[m][n], facecolor=color_select[m], edgecolor=color_select[i], alpha=0.6) patch_polygon.set_zorder(6) self.ax.add_patch(patch_polygon) self.redraw()
def get_path(self, lines, color): path_data = [(Path.MOVETO, (lines[0][0], lines[0][1]))] for i in range(len(lines) - 1): path_data.append((Path.LINETO, (lines[i + 1][0], lines[i + 1][1]))) path_data.append((Path.CLOSEPOLY, (lines[0][0], lines[0][1]))) codes, verts = zip(*path_data) path = PathPatch(Path(verts, codes), facecolor=color) path.set_zorder(4) return path
def hash_fill_between(ax, x, y1, y2=0, **kargs): ''' For x, hash region between y1 and y2. Equivalent of ax.fill_between ''' p = ax.fill_between(x, y1, y2, **kargs) p.set_facecolors("none") p.set_edgecolors("none") for path in p.get_paths(): p1 = PathPatch(path, fc="none", hatch="//", alpha=1) ax.add_patch(p1) p1.set_zorder(p.get_zorder() - 0.1)
def hash_fill_between(ax, x, y1, y2=0, **kargs): ''' For x, hash region between y1 and y2. Equivalent of ax.fill_between ''' p = ax.fill_between(x, y1, y2, **kargs) p.set_facecolors("none") p.set_edgecolors("none") for path in p.get_paths(): p1 = PathPatch(path, fc="none", hatch="//", alpha=1) ax.add_patch(p1) p1.set_zorder(p.get_zorder() - 0.1)
def profiles_rigid_vs_el_mtrx(): r = 0.003 tau = 0.3 V_f = 0.11 E_f = 200e3 E_m = 25e10 Ll = 35. Lr = 35. Xxi = RV('weibull_min', shape=5., scale=.02) Xr = RV('uniform', loc=.002, scale=.002) Xtau = RV('uniform', loc=.02, scale=.98) reinf2 = Reinforcement(r=Xr, tau=Xtau, V_f=V_f, E_f=E_f, xi=Xxi, n_int=15) model2 = CompositeCrackBridge(E_m=E_m, reinforcement_lst=[reinf2], Ll=Ll, Lr=Lr) ccb_view2 = CompositeCrackBridgeView(model=model2) ccb_view2.sigma_c_max x2 = np.hstack((-Ll, ccb_view2.x_arr, Lr)) mu_epsf2 = np.hstack((ccb_view2.mu_epsf_arr[0], ccb_view2.mu_epsf_arr, ccb_view2.mu_epsf_arr[-1])) epsm2 = np.hstack((ccb_view2.epsm_arr[0], ccb_view2.epsm_arr, ccb_view2.epsm_arr[-1])) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(x2, mu_epsf2, lw=2, color='black') ax.plot(x2, epsm2, lw=2, color='black') p = ax.fill_between(x2, epsm2, mu_epsf2, facecolor='none') from matplotlib.patches import PathPatch path = p.get_paths()[0] p1 = PathPatch(path, fc="none", hatch="/") ax.add_patch(p1) p1.set_zorder(p.get_zorder()-0.1) p = ax.fill_between(x2, mu_epsf2, facecolor='none') path = p.get_paths()[0] p1 = PathPatch(path, fc="none", hatch="\\") ax.add_patch(p1) p1.set_zorder(p.get_zorder()-0.1) reinf1 = Reinforcement(r=r, tau=tau, V_f=V_f, E_f=E_f, xi=Xxi, n_int=15) model1 = CompositeCrackBridge(E_m=E_m, reinforcement_lst=[reinf1], Ll=Ll, Lr=Lr) ccb_view1 = CompositeCrackBridgeView(model=model1) ccb_view1.sigma_c_max x1 = np.hstack((-Ll, ccb_view1.x_arr, Lr)) mu_epsf1 = np.hstack((ccb_view1.mu_epsf_arr[0], ccb_view1.mu_epsf_arr, ccb_view1.mu_epsf_arr[-1])) epsm1 = np.hstack((ccb_view1.epsm_arr[0], ccb_view1.epsm_arr, ccb_view1.epsm_arr[-1])) ax.plot(x1, mu_epsf1, lw=2, color='black') ax.plot(x1, epsm1, lw=2, color='black') plt.xlabel('z [mm]') plt.xlim(-35, 35) plt.ylim(0) plt.ylabel('$\epsilon$ [-]')
def _initPatch(self): """ get pathPatches for plotting res for CRS of dedicate port :return: """ codes = [] vertices = [] for re in self.res: codes += re().codes vertices += re().vertices path = Path(vertices, codes) patch = PathPatch(path, facecolor='white', edgecolor='black', linewidth=0.2, fill='none') patch.set_zorder(90) return patch, codes, vertices
def getResPatchInReg(self, k___singleQuote:int, l___singleQuote:int): """ get pathPatches for plot res in dedicate Prb :return: """ codes = [] vertices = [] for re in self.reg(k___singleQuote,l___singleQuote).res: codes += re().codes vertices += re().vertices path = Path(vertices, codes) patch = PathPatch(path, facecolor='white', edgecolor='black', linewidth=0.2, linestyle='dotted', fill='none') patch.set_zorder(90) return patch
def getResPatchInPrb(self, n__PRB:int): """ get pathPatches for plot res in dedicate Prb :return: """ codes = [] vertices = [] for re in self.prb(n__PRB)().res: codes += re().codes vertices += re().vertices path = Path(vertices, codes) pathPatch = PathPatch(path, facecolor='white', edgecolor='black', linewidth=0.2, linestyle='dotted', fill='none') pathPatch.set_zorder(9) return pathPatch
def _initPatch(self, n__s:int, subFrameTypeName:str): """ generate path patch for this PRB :param n__s: :param subFrameTypeName: :return: """ vertices = [] codes = [] bottom = 0 left = 0 width = 0 height = 0 if subFrameTypeName == 'D': bottom = self.n__PRB * conf.N__sc___RB_DL left = 0 width = conf.N__symb___DL height = conf.N__sc___RB_DL if subFrameTypeName == 'U': bottom = self.n__PRB * conf.N__sc___RB_UL left = 0 width = conf.N__symb___UL height = conf.N__sc___RB_UL if subFrameTypeName == 'S': if n__s %1 == 0: bottom = self.n__PRB * conf.N__sc___RB_DL left = 0 width = conf.N__symb___DwPTS height = conf.N__sc___RB_DL if n__s %1 == 1: bottom = self.n__PRB * conf.N__sc___RB_UL left = conf.N__symb___UpPTS width = conf.N__symb___UL - conf.N__symb___DwPTS height = conf.N__sc___RB_UL codes = [Path.MOVETO] + [Path.LINETO]*3 + [Path.CLOSEPOLY] vertices = [(left,bottom), (left,bottom+height), (left+width,bottom+height), (left+width,bottom), (0,0)] path = Path(vertices, codes) patch = PathPatch(path, facecolor='white', edgecolor='black', linewidth=2.0, fill='none' ) patch.set_zorder(80) return patch, codes, vertices
def initPatch(self): """ plot based on matplotlib :return: """ vertices = [] codes = [] codes = [Path.MOVETO] + [Path.LINETO]*3 + [Path.CLOSEPOLY] vertices = [(self.l,self.k), ((self.l),(self.k+1)), ((self.l+1),(self.k+1)), ((self.l+1),(self.k)), (0,0)] path = Path(vertices, codes) patch = PathPatch(path, facecolor='white', edgecolor='black') patch.set_zorder(100) return patch, codes,vertices
def _initPatch(self): """ generate path patch for this SLOT :param n: :param subFrameTypeName: :return: """ vertices = [] codes = [] vertices += self.slots[0].vertices codes += self.slots[0].codes vertices += self.slots[1].vertices codes += self.slots[1].codes path = Path(vertices, codes) patch = PathPatch(path, facecolor='white', edgecolor='black', linewidth=2.0, fill='none' ) patch.set_zorder(60) return patch, codes, vertices
def plotStand(self, param, flag, stand_param): self.fig.clear() self.ax = self.fig.add_subplot(111) #添加子图 self.fig.subplots_adjust(left=0.05, right=0.85, top=0.95, bottom=0.05) #设置边距 # self.ax.clear() self.config_all = self.init_config(param) #获取参数 if param[0][0] != '-- Choose ODD please --': self.obj = self.odd_import(self.ax, param[0]) config_select = [] color_select = [] for i in range(len(self.config_all)): if self.colors[i] != 'none': config_select.append(self.config_all[i]) color_select.append(self.colors[i]) else: pass detect = Detection(self.obj, config_select) #opencv检测 patches, paths = detect.plot() # 路径点坐标 if flag: self.loadYaml(stand_param) else: pass # for sensorType in self.yFile.yamlData: # s=self.loadYaml(sensorType) # s.set_zorder(1) # 设置图层 # self.ax.add_collection(s) for i in range(len(patches)): p = PatchCollection(patches[i], color=color_select[i], edgecolor=color_select[i], alpha=0.15) p.set_zorder(6) #设置图层 self.ax.add_collection(p) #将PatchCollection添加进axes对象 for m in range(len(paths)): for n in range(len(paths[m])): patch_polygon = PathPatch(paths[m][n], facecolor=color_select[m], edgecolor=color_select[m], alpha=0.15) patch_polygon.set_zorder(6) self.ax.add_patch(patch_polygon) self.in_view = detect.postdetection_list self.in_scale_view = detect.detection_list self.draw_ego_vehicle()
def _render_on_subplot(self, subplot): """ Render this Bezier path in a subplot. This is the key function that defines how this Bezier path graphics primitive is rendered in matplotlib's library. TESTS:: sage: bezier_path([[(0,1),(.5,0),(1,1)]]) Graphics object consisting of 1 graphics primitive :: sage: bezier_path([[(0,1),(.5,0),(1,1),(-3,5)]]) Graphics object consisting of 1 graphics primitive """ from matplotlib.patches import PathPatch from matplotlib.path import Path from sage.plot.misc import get_matplotlib_linestyle options = dict(self.options()) del options['alpha'] del options['thickness'] del options['rgbcolor'] del options['zorder'] del options['fill'] del options['linestyle'] bpath = Path(self.vertices, self.codes) bpatch = PathPatch(bpath, **options) options = self.options() bpatch.set_linewidth(float(options['thickness'])) bpatch.set_fill(options['fill']) bpatch.set_zorder(options['zorder']) a = float(options['alpha']) bpatch.set_alpha(a) c = to_mpl_color(options['rgbcolor']) bpatch.set_edgecolor(c) bpatch.set_facecolor(c) bpatch.set_linestyle( get_matplotlib_linestyle(options['linestyle'], return_type='long')) subplot.add_patch(bpatch)
def _render_on_subplot(self, subplot): """ Render this Bezier path in a subplot. This is the key function that defines how this Bezier path graphics primitive is rendered in matplotlib's library. TESTS:: sage: bezier_path([[(0,1),(.5,0),(1,1)]]) Graphics object consisting of 1 graphics primitive :: sage: bezier_path([[(0,1),(.5,0),(1,1),(-3,5)]]) Graphics object consisting of 1 graphics primitive """ from matplotlib.patches import PathPatch from matplotlib.path import Path from sage.plot.misc import get_matplotlib_linestyle options = dict(self.options()) del options['alpha'] del options['thickness'] del options['rgbcolor'] del options['zorder'] del options['fill'] del options['linestyle'] bpath = Path(self.vertices, self.codes) bpatch = PathPatch(bpath, **options) options = self.options() bpatch.set_linewidth(float(options['thickness'])) bpatch.set_fill(options['fill']) bpatch.set_zorder(options['zorder']) a = float(options['alpha']) bpatch.set_alpha(a) c = to_mpl_color(options['rgbcolor']) bpatch.set_edgecolor(c) bpatch.set_facecolor(c) bpatch.set_linestyle(get_matplotlib_linestyle(options['linestyle'], return_type='long')) subplot.add_patch(bpatch)
def draw(fig, h, heid, row): ax = plt.subplot2grid(shape=(2,5), loc=(row,0), colspan=2) lbls = labels_count if row==1 else [_] ax.set_xticklabels(lbls) for t in ax.xaxis.get_major_ticks(): t.label.set_rotation(30) rplt.hist(h, axes=ax) npass = sum(list(h)[2:]) p = plt.fill_between([1.5,4.5],[npass,npass], [0.01,0.01]) p.set_facecolors('none') for path in p.get_paths(): p1 = PathPatch(path, fc='none', hatch='\\\\\\', color='blue') ax.add_patch(p1) p1.set_zorder(p.get_zorder()-0.1) ax.set_yscale('log') ylim((0.01,3*h.GetMaximum())) text(0.9, 0.75,'charge skim', fontsize=12, color='blue', transform=ax.transAxes, horizontalalignment='right', verticalalignment='bottom') text(0.9, 0.68, '%.1f'%(100*npass)+'$\%$', fontsize=14, color='blue', transform=ax.transAxes, horizontalalignment='right', verticalalignment='top') ax = plt.subplot2grid(shape=(2,5), loc=(row,2), colspan=3) lbls = labels_eid if row==1 else [_] ax.set_xticklabels(lbls) for t in ax.xaxis.get_major_ticks(): t.label.set_rotation(30) rplt.hist(heid, axes=ax) X = [0.5,6.5] Y1 = [npass,npass] Y2 = [heid.GetMinimum(), heid.GetMinimum()] # plot(X, Y2, 'r-.') p = plt.fill_between([0.5,1.5],[npass,npass]) p.set_facecolors('none') for path in p.get_paths(): p1 = PathPatch(path, fc='none', hatch='\\\\\\', color='blue') ax.add_patch(p1) p1.set_zorder(p.get_zorder()-0.1) p = plt.fill_between([5.5,6.5],Y2) p.set_facecolors('none') for path in p.get_paths(): p1 = PathPatch(path, fc='none', hatch='xxx', color='green') ax.add_patch(p1) p1.set_zorder(p.get_zorder()-0.1) ylim((0.5*heid.GetMinimum(),1.1*heid.GetMaximum())) text(0.95, 0.75, 'refined electron\nidentification', fontsize=12, color='green', transform=ax.transAxes, horizontalalignment='right', verticalalignment='bottom') text(0.95, 0.68, '%.1f'%(100*heid.GetMinimum())+'$\%$', fontsize=14, color='green', transform=ax.transAxes, horizontalalignment='right', verticalalignment='top') # subplots_adjust(bottom=0.5, wspace=0.6, hspace=0.1) subplots_adjust(left=0.1, bottom=0.15, wspace=0.6, hspace=0.1) if row==1: # text(0,-0.0025,'selection criteria', fontsize=12) text(0.5,0,'selection criteria', fontsize=12, transform=fig.transFigure, horizontalalignment='center') text(0, 0.5, 'events per trigger', fontsize=12, transform=fig.transFigure, verticalalignment='center', rotation=90)
def plot_dendrogram(neurite, axis=None, show_node_id=False, aspect_ratio=None, vertical_diam_frac=0.2, ignore_diameter=False, show=True, **kwargs): ''' Plot the dendrogram of a neurite. Parameters ---------- neurite : :class:`~dense.elements.Neurite` object Neurite for which the dendrogram should be plotted. axis : matplotlib.Axes.axis object, optional (default: new one) Axis on which the dendrogram should be plotted. show : bool, optional (default: True) Whether the figure should be shown right away. show_node_id : bool, optional (default: False) Display each node number on the branching points. aspect_ratio : float, optional (default: variable) Whether to use a fixed aspect ratio. Automatically set to 1 if `show_node_id` is True. vertical_diam_frac : float, optional (default: 0.2) Fraction of the vertical spacing taken by the branch diameter. ignore_diameter : bool, optional (default: False) Plot all the branches with the same width. **kwargs : arguments for :class:`matplotlib.patches.Rectangle` For instance `facecolor` or `edgecolor`. Returns ------- The axis on which the plot was done. See also -------- :func:`~dense.elements.Neurite.plot_dendrogram` ''' import matplotlib.pyplot as plt tree = neurite.get_tree() if axis is None: fig, axis = plt.subplots() fig = axis.get_figure() if "facecolor" not in kwargs: kwargs["facecolor"] = "k" if "edgecolor" not in kwargs: kwargs["edgecolor"] = "none" # get the number of tips num_tips = len(tree.tips) # compute the size of the vertical spacing between branches # this should be 5 times the diameter of the first section and there # are num_tips + 1 spacing in total. init_diam = tree.root.children[0].diameter vspace = init_diam / vertical_diam_frac tot_height = (num_tips + 0.5) * vspace # compute the total length which is 1.1 times the longest distance # to soma max_dts = np.max([n.distance_to_soma() for n in tree.tips]) tot_length = 1.02*max_dts # we need to find the number of up and down children for each node up_children = {} down_children = {} diams = [] root = tree.root tips = set(tree.tips) # if diameter is ignored, set all values to default_diam default_diam = vertical_diam_frac*vspace if ignore_diameter: tree.root.diameter = default_diam queue = deque([root]) while queue: node = queue.popleft() queue.extend(node.children) if ignore_diameter: node.diameter = default_diam if len(node.children) == 1 and node != root: # gc died there, transfer children and update them parent = node.parent child_pos = 0 for i, child in enumerate(parent.children): if child == node: parent.children[i] = node.children[0] child_pos = i break # use loop to keep child memory and update properties child = parent.children[child_pos] child.dist_to_parent += node.dist_to_parent child.parent = node.parent child.diameter = 0.5*(node.diameter + child.diameter) # check up/down_children and replace node by child for key, val in up_children.items(): if node in val: up_children[key] = {n for n in val if n is not node} up_children[key].add(child) for key, val in down_children.items(): if node in val: down_children[key] = { n for n in val if n is not node} down_children[key].add(child) else: if len(node.children) == 2: up_children[node] = {node.children[0]} down_children[node] = {node.children[1]} for val in up_children.values(): if node.parent in val: val.add(node) for val in down_children.values(): if node.parent in val: val.add(node) diams.append(node.diameter) # keep only tips in up/down_children up_tips, down_tips = {}, {} for key, val in up_children.items(): up_tips[key] = val.intersection(tips) for key, val in down_children.items(): down_tips[key] = val.intersection(tips) # get max diameter for node plotting max_d = np.max(diams) # aspect ratios vbar_diam_ratio = 0.5 hv_ratio = tot_length/tot_height if show_node_id: axis.set_aspect(1.) hv_ratio = 1. vbar_diam_ratio = 1. elif aspect_ratio is not None: axis.set_aspect(aspect_ratio) hv_ratio = aspect_ratio vbar_diam_ratio /= aspect_ratio # making horizontal branches x0 = 0.01*max_dts parent_x = {} parent_y = {} children_y = {tree.root: []} queue = deque([root]) while queue: node = queue.popleft() queue.extend(node.children) parent_diam = 0 if node.parent is None else node.parent.diameter x = x0 # skip for root (parent is None) if node.parent is not None: x += node.parent.distance_to_soma() \ - vbar_diam_ratio*parent_diam*hv_ratio # get parent y y = parent_y.get(node.parent, 0.) num_up, num_down = 0.5, 0.5 if node.children: num_up = 0 if node not in up_tips else len(up_tips[node]) num_down = 0 if node not in down_tips else len(down_tips[node]) children_y[node] = [] if node in up_children.get(node.parent, [node]): y += num_down*vspace - 0.5*node.diameter else: y -= num_up*vspace + 0.5*node.diameter parent_y[node] = y parent_x[node] = x + node.dist_to_parent # ignore root if node.parent is not None: children_y[node.parent].append(y) axis.add_artist( Rectangle((x, y), node.dist_to_parent, node.diameter, fill=True, **kwargs)) # last iteration for vertical connections # set root as last node with a single child while len(root.children) == 1: root = root.children[0] if ignore_diameter: root.diameter = default_diam queue = deque([root]) while queue: node = queue.popleft() queue.extend(node.children) if node.children: x = parent_x[node] y = parent_y[node] + 0.5*node.diameter y1, y2 = children_y[node] y1, y2 = min(y1, y2), max(y1, y2) dx = 0.5*vbar_diam_ratio*node.diameter*hv_ratio if show_node_id: circle = plt.Circle( (x + dx, y), max_d, color=kwargs["facecolor"]) artist = axis.add_artist(circle) artist.set_zorder(5) str_id = str(node) xoffset = len(str_id)*0.3*max_d text = TextPath((x + dx - xoffset, y - 0.3*max_d), str_id, size=max_d) textpatch = PathPatch(text, edgecolor="w", facecolor="w", linewidth=0.01*max_d) axis.add_artist(textpatch) textpatch.set_zorder(6) axis.add_artist( Rectangle((x, y1), vbar_diam_ratio*node.diameter*hv_ratio, (y2 - y1) + 0.5*node.diameter, fill=True, **kwargs)) axis.set_xlim(0, tot_length) axis.set_ylim(np.min(list(parent_y.values())) - 0.75*vspace, np.max(list(parent_y.values())) + 0.75*vspace) plt.axis('off') fig.patch.set_alpha(0.) if show: plt.show() return axis
def plot_hourly_generation_alt(ISO='DK', gamma=0.5, alpha_w=.5, CS=None, date_start=datestr2num('1-1-2000'), N_days=30, monday_offset=5, titletxt='Denmark, Jan. 2000', label='TestFigure'): #Load data t, L, Gw, Gs, datetime_offset, datalabel = get_ISET_country_data(ISO) mask = find((t+datetime_offset>=date_start)*(t+datetime_offset<=date_start+N_days)) if alpha_w==None: alpha_w = get_optimal_mix_balancing(L, Gw, Gs, gamma) print 'Mix not specified. Optimal mix alpha_w={0} chosen'.format(alpha_w) wind = gamma*alpha_w*Gw*mean(L) solar = gamma*(1-alpha_w)*Gs*mean(L) mismatch = (wind+solar) - L if CS!=None or CS==0: mismatch_r = get_policy_2_storage(mismatch, eta_in = 1., eta_out = 1., storage_capacity = CS)[0] else: mismatch_r = mismatch curtailment = get_positive(mismatch_r) filling = get_positive(mismatch - mismatch_r) extraction = get_positive(-(mismatch - mismatch_r)) wind_local = wind - (curtailment+filling)*wind/(wind+solar+1e-10) solar_local = solar - (curtailment+filling)*solar/(wind+solar+1e-10) #Set plot options matplotlib.rcParams['font.size'] = 10 close(1); figure(1); clf() gcf().set_dpi(300) gcf().set_size_inches([6.5,4.3]) fill_between(t[mask],wind_local[mask],color=color_wind,edgecolor=color_edge,lw=1) fill_between(t[mask],wind_local[mask]+solar_local[mask],wind_local[mask],color=color_solar,edgecolor=color_edge,lw=1) p = fill_between(t[mask],wind_local[mask]+solar_local[mask]+filling[mask],wind_local[mask]+solar_local[mask],color='g',edgecolor=color_edge,lw=1) fill_between(t[mask],wind_local[mask]+solar_local[mask]+extraction[mask],wind_local[mask]+solar_local[mask],color='g',edgecolor=color_edge,lw=1) fill_between(t[mask],wind_local[mask]+solar_local[mask]+filling[mask]+curtailment[mask],wind_local[mask]+solar_local[mask]+filling[mask],color='r',edgecolor=color_edge,lw=1) p.set_facecolors("none") from matplotlib.patches import PathPatch for path in p.get_paths(): p1 = PathPatch(path, fc="none", hatch="/") gca().add_patch(p1) p1.set_zorder(p.get_zorder()-0.1) pp_wind = Rectangle((0, 0), 1, 1, facecolor=color_wind) pp_solar = Rectangle((0, 0), 1, 1, facecolor=color_solar) pp_curtailment = Rectangle((0, 0), 1, 1, facecolor='r') pp_storage = Rectangle((0, 0), 1, 1, facecolor='g') pp_filling = Rectangle((0, 0), 1, 1, facecolor='none', hatch="/") pp_load = plot(t[mask],L[mask],color='k',lw=1.5) axis(xmin=t[mask[0]],xmax=t[mask[-1]],ymin=0,ymax=1.9*mean(L)) ylabel('Power [GW]') day_names = array([calendar.day_abbr[mod(i,7)] for i in arange(N_days)+monday_offset]) #day_names[find([d!='Mon' for d in day_names])] = '' xticks(t[mask[0]]+arange(N_days),day_names,rotation=-45,ha='left') if CS==None: pp = [pp_load[0],pp_wind,pp_solar,pp_curtailment] txtlabels = ['Load ({0})'.format(ISO),'Wind','Solar','Surplus'] leg = legend(pp,txtlabels,loc='upper left',ncol=5,title=titletxt); else: pp = [pp_load[0],pp_filling,pp_wind,pp_curtailment,pp_solar,pp_storage] txtlabels = ['Load ({0})'.format(ISO),'Stored surplus','Wind','Remainder surplus','Solar','Storage'] leg = legend(pp,txtlabels,loc='upper left',ncol=4,title=titletxt); ltext = leg.get_texts(); setp(ltext, fontsize='small') # the legend text fontsize tight_layout() save_file_name = 'plot_hourly_generation_alt_'+ISO+'_'+label+'.pdf' save_figure(save_file_name)
x0, x1 = plt.xlim() xr, yr = x1-x0, y1-y0 plt.text(x0+0.183*xr, y0+0.85*yr, r'$W = [%.3f, %.3f)\,\mathrm{GeV}$'%(wlo,whi), fontsize=16, horizontalalignment='left', verticalalignment='bottom') plt.text(x0+0.175*xr, y0+0.725*yr, r'$Q^2 = [%.3f, %.3f)\,\mathrm{GeV^2}$'%(q2lo,q2hi), fontsize=16, horizontalalignment='left', verticalalignment='bottom') f3 = h.GetListOfFunctions()[2] X = np.linspace(-1,1, num=500) Y = [f3.Eval(x) for x in X] # plt.plot(X,Y,'.r') p = plt.fill_between(X, 0, Y) p.set_facecolors('none') for path in p.get_paths(): p1 = PathPatch(path, fc='none', hatch='\\\\\\', color='red') sp.add_patch(p1) p1.set_zorder(p.get_zorder()-0.1) f1 = h.GetListOfFunctions()[0] Y = [f1.Eval(x) for x in X] plt.plot(X,Y,'-k') f2 = h.GetListOfFunctions()[1] Y = [f2.Eval(x) for x in X] plt.plot(X,Y,'--b', lw=2) plt.tight_layout() plt.text(-5.5,2600,'PRELIMINARY',fontsize=108,rotation=30,alpha=0.175) plt.text(-3.75,1600,'PRELIMINARY',fontsize=108,rotation=30,alpha=0.175) plt.savefig('cost_samples_tmp.pdf') plt.savefig('cost_samples_tmp.eps') # <codecell> dfm = pd.read_table('/home/ephelps/Dropbox/Notebooks/omega/Projects/Omega/Cross-sections/Morand/xsect_integrated_morand.txt')
def plot_neurons(gid=None, mode="sticks", show_nodes=False, show_active_gc=True, culture=None, show_culture=True, aspect=1., soma_radius=None, active_gc="d", gc_size=2., soma_color='k', scale=50*um, scale_text=True, axon_color="indianred", dendrite_color="royalblue", subsample=1, save_path=None, title=None, axis=None, show_density=False, dstep=20., dmin=None, dmax=None, colorbar=True, show_neuron_id=False, show=True, **kwargs): ''' Plot neurons in the network. Parameters ---------- gid : int or list, optional (default: all neurons) Id(s) of the neuron(s) to plot. mode : str, optional (default: "sticks") How to draw the neurons. By default, the "sticks" mode shows the real width of the neurites. Switching to "lines" only leaves the trajectory of the growth cones, without information about the neurite width. Eventually, the "mixed" mode shows both informations superimposed. culture : :class:`~dense.environment.Shape`, optional (default: None) Shape of the environment; if the environment was already set using :func:`~dense.CreateEnvironment`. show_nodes : bool, optional (default: False) Show the branching nodes. show_active_gc : bool, optional (default: True) If True, display the tip (growth cone) of actively growing branches. show_culture : bool, optional (default: True) If True, displays the culture in which the neurons are embedded. aspect : float, optional (default: 1.) Set the aspect ratio between the `x` and `y` axes. soma : str, optional (default: "o") Shape of the soma marker using the matplotlib conventions. soma_radius : float, optional (default: real neuron radius) Size of the soma marker. active_gc : str, optional (default: "d") Shape of the active growth cone marker using the matplotlib conventions. gc_size : float, optional (default: 2.) Size of the growth cone marker. axon_color : valid matplotlib color, optional (default: "indianred") Color of the axons. dendrite_color : valid matplotlib color, optional (default: "royalblue") Color of the dendrites. soma_color : valid matplotlib color, optional (default: "k") Color of the soma. scale : length, optional (default: 50 microns) Whether a scale bar should be displayed, with axes hidden. If ``None``, then spatial measurements will be given through standard axes. subsample : int, optional (default: 1) Subsample the neurites to save memory. save_path : str, optional (default: not saved) Path where the plot should be saved, including the filename, pdf only. title : str, optional (default: no title) Title of the plot. axis : :class:`matplotlib.pyplot.Axes`, optional (default: None) Axis on which the plot should be drawn, otherwise a new one will be created. show_neuron_id : bool, optional (default: False) Whether the GID of the neuron should be displayed inside the soma. show : bool, optional (default: True) Whether the plot should be displayed immediately or not. **kwargs : optional arguments Details on how to plot the environment, see :func:`plot_environment`. Returns ------- axes : axis or tuple of axes if `density` is True. ''' import matplotlib.pyplot as plt assert mode in ("lines", "sticks", "mixed"),\ "Unknown `mode` '" + mode + "'. Accepted values are 'lines', " +\ "'sticks' or 'mixed'." if show_density: subsample = 1 # plot fig, ax, ax2 = None, None, None if axis is None: fig, ax = plt.subplots() else: ax = axis fig = axis.get_figure() fig.patch.set_alpha(0.) new_lines = 0 # plotting options soma_alpha = kwargs.get("soma_alpha", 0.8) axon_alpha = kwargs.get("axon_alpha", 0.6) dend_alpha = kwargs.get("dend_alpha", 0.6) gc_color = kwargs.get("gc_color", "g") # get the objects describing the neurons if gid is None: gid = _pg.get_neurons(as_ints=True) elif not is_iterable(gid): gid = [gid] somas, growth_cones, nodes = None, None, None axon_lines, dend_lines = None, None axons, dendrites = None, None if mode in ("lines", "mixed"): somas, axon_lines, dend_lines, growth_cones, nodes = \ _pg._get_pyskeleton(gid, subsample) if mode in ("sticks", "mixed"): axons, dendrites, somas = _pg._get_geom_skeleton(gid) # get the culture if necessary env_required = _pg.get_kernel_status('environment_required') if show_culture and env_required: if culture is None: culture = _pg.get_environment() plot_environment(culture, ax=ax, show=False, **kwargs) new_lines += 1 # plot the elements if mode in ("sticks", "mixed"): for a in axons.values(): plot_shape(a, axis=ax, fc=axon_color, show_contour=False, zorder=2, alpha=axon_alpha, show=False) for vd in dendrites.values(): for d in vd: plot_shape(d, axis=ax, fc=dendrite_color, show_contour=False, alpha=dend_alpha, zorder=2, show=False) if mode in ("lines", "mixed"): ax.plot(axon_lines[0], axon_lines[1], ls="-", c=axon_color) ax.plot(dend_lines[0], dend_lines[1], ls="-", c=dendrite_color) new_lines += 2 # plot the rest if required if show_nodes and mode in ("lines", "mixed"): ax.plot(nodes[0], nodes[1], ls="", marker="d", ms="1", c="k", zorder=4) new_lines += 1 if show_active_gc and mode in ("lines", "mixed"): ax.plot(growth_cones[0], growth_cones[1], ls="", marker=active_gc, c=gc_color, ms=gc_size, zorder=4) new_lines += 1 # plot the somas n = len(somas[2]) radii = somas[2] if soma_radius is None else np.repeat(soma_radius, n) if mode in ("sticks", "mixed"): radii *= 1.05 r_max = np.max(radii) r_min = np.min(radii) size = (1.5*r_min if len(gid) <= 10 else (r_min if len(gid) <= 100 else 0.7*r_min)) for i, x, y, r in zip(gid, somas[0], somas[1], radii): circle = plt.Circle( (x, y), r, color=soma_color, alpha=soma_alpha) artist = ax.add_artist(circle) artist.set_zorder(5) if show_neuron_id: str_id = str(i) xoffset = len(str_id)*0.35*size text = TextPath((x-xoffset, y-0.35*size), str_id, size=size) textpatch = PathPatch(text, edgecolor="w", facecolor="w", linewidth=0.01*size) ax.add_artist(textpatch) textpatch.set_zorder(6) # set the axis limits if (not show_culture or not env_required) and len(ax.lines) == new_lines: if mode in ("lines", "mixed"): _set_ax_lim(ax, axon_lines[0] + dend_lines[0], axon_lines[1] + dend_lines[1], offset=2*r_max) else: xx = [] yy = [] for a in axons.values(): xmin, ymin, xmax, ymax = a.bounds xx.extend((xmin, xmax)) yy.extend((ymin, ymax)) for vd in dendrites.values(): for d in vd: xmin, ymin, xmax, ymax = d.bounds xx.extend((xmin, xmax)) yy.extend((ymin, ymax)) _set_ax_lim(ax, xx, yy, offset=2*r_max) ax.set_aspect(aspect) if title is not None: fig.suptitle(title) if save_path is not None: if not save_path.endswith('pdf'): save_path += ".pdf" plt.savefig(save_path, format="pdf", dpi=300) if show_density: from matplotlib.colors import LogNorm fig, ax2 = plt.subplots() x = np.concatenate( (np.array(axons[0])[~np.isnan(axons[0])], np.array(dendrites[0])[~np.isnan(dendrites[0])])) y = np.concatenate( (np.array(axons[1])[~np.isnan(axons[1])], np.array(dendrites[1])[~np.isnan(dendrites[1])])) xbins = int((np.max(x) - np.min(x)) / dstep) ybins = int((np.max(y) - np.min(y)) / dstep) cmap = get_cmap(kwargs.get("cmap", "viridis")) cmap.set_bad((0, 0, 0, 1)) norm = None if dmin is not None and dmax is not None: n = int(dmax-dmin) norm = matplotlib.colors.BoundaryNorm( np.arange(dmin-1, dmax+1, 0), cmap.N) elif dmax is not None: n = int(dmax) norm = matplotlib.colors.BoundaryNorm( np.arange(0, dmax+1, 1), cmap.N) counts, xbins, ybins = np.histogram2d(x, y, bins=(xbins, ybins)) lims = [xbins[0], xbins[-1], ybins[0], ybins[-1]] counts[counts == 0] = np.NaN data = ax2.imshow(counts.T, extent=lims, origin="lower", vmin=0 if dmin is None else dmin, vmax=dmax, cmap=cmap) if colorbar: extend = "neither" if dmin is not None and dmax is not None: extend = "both" elif dmax is not None: extend = "max" elif dmin is not None: extend = "min" cb = plt.colorbar(data, ax=ax2, extend=extend) cb.set_label("Number of neurites per bin") ax2.set_aspect(aspect) ax2.set_xlabel(r"x ($\mu$ m)") ax2.set_ylabel(r"y ($\mu$ m)") if scale is not None: xmin, xmax = ax.get_xlim() ymin, ymax = ax.get_ylim() length = scale.m_as("micrometer") if xmax - xmin < 2*length: scale *= 0.2 length = scale.m_as("micrometer") x = xmin + 0.2*length y = ymin + (ymax-ymin)*0.05 ax.add_artist( Rectangle((x, y), length, 0.1*length, fill=True, facecolor='k', edgecolor='none')) plt.axis('off') stext = "(scale is {} $\mu$m)".format(length) if title is not None and scale_text: fig.suptitle(title + " " + stext) elif scale_text: fig.suptitle(stext) if show: plt.show() if show_density: return ax, ax2 return ax
def _initPatch(self, n__s:int, subFrameTypeName:str): """ generate path patch for this SLOT :param n__s: :param subFrameTypeName: :return: """ vertices = [] codes = [] bottom = 0 left = 0 width = 0 height = 0 if subFrameTypeName == 'D': bottom = 0 left = 0 width = conf.N__symb___DL height = conf.N__RB___DL*conf.N__sc___RB_DL if subFrameTypeName == 'U': bottom = 0 left = 0 width = conf.N__symb___UL height = conf.N__RB___UL * conf.N__sc___RB_UL if subFrameTypeName == 'S': if n__s %2 == 0: bottom = 0 left = 0 if conf.N__symb___DwPTS > conf.N__symb___DL: width = conf.N__symb___DL height = conf.N__RB___DL*conf.N__sc___RB_DL if n__s %2 == 1: if (conf.N__symb___GP + conf.N__symb___UpPTS) < conf.N__symb___UL: #extended DwPTS in second slot region bottom = 0 left = 0 width = conf.N__symb___UL - conf.N__symb___UpPTS - conf.N__symb___GP height = conf.N__RB___UL*conf.N__sc___RB_UL codes = [Path.MOVETO] + [Path.LINETO]*3 + [Path.CLOSEPOLY] vertices = [(left,bottom), (left,bottom+height), (left+width,bottom+height), (left+width,bottom), (0,0)] if subFrameTypeName == 'S': if n__s %2 == 1: bottom = 0 left = conf.N__symb___UL - conf.N__symb___UpPTS width = conf.N__symb___UpPTS height = conf.N__RB___UL*conf.N__sc___RB_UL codes += [Path.MOVETO] + [Path.LINETO]*3 + [Path.CLOSEPOLY] vertices += [(left,bottom), (left,bottom+height), (left+width,bottom+height), (left+width,bottom), (0,0)] path = Path(vertices, codes) patch = PathPatch(path, facecolor='white', edgecolor='black', linewidth=3.0, fill='none' ) patch.set_zorder(60) return patch, codes, vertices