def draw(which, instr, scramble=True): arrow_params = {'length_includes_head': True, 'shape': 'full', 'head_starts_at_zero': False} fig, ax = plt.subplots(1) plt.axis('off') ax.set_xlim((0,120)) ax.set_ylim((0,100)) plt.text(5,50,"Genotype",fontsize=16,horizontalalignment='center',verticalalignment='center',rotation=90) if which <= 3: ax.add_patch( Rectangle((90,0), 10, 30, fill=False, color='red', hatch='////') ) ax.add_patch( Rectangle((90,35), 10, 30, fill=True, color='green', hatch=None) ) ax.add_patch( Rectangle((90,70), 10, 30, fill=True, color='blue', hatch=None) ) plt.text(110,50,"Phenotype",fontsize=16,rotation=90,horizontalalignment='center',verticalalignment='center') for x,y,__ in instr: if any(xc == x+10 and yc == y for xc,yc,__ in instr): ax.add_line(Line([x, x+10],[y, y],color='black',zorder=-1)) if any(xc == x and yc == y+10 for xc,yc,__ in instr): ax.add_line(Line([x, x],[y, y+10],color='black',zorder=-1)) shuffle(instr) instr.sort(key=lambda i: i[0],reverse=True) for x,y,color in instr: ax.add_patch( Circle((x,y), radius=3, fill=True, color='white') ) ax.add_patch( Circle((x,y), radius=3, fill=True if which <= 2 or color != 'red' else False, color='black' if which <= 2 else color, hatch=None if which <= 2 or color != 'red' else '////') ) if which > 3 or which <= 1: return for x,y,color in instr: ax.arrow(x, y, 95-x+(uniform(-2,2) if scramble else 0), (50 if color == 'green' else 15 if color == 'red' else 85 if color == 'blue' else None)-y+(uniform(-10,10) if scramble else 0), width=1.5, fill=True, color='gray' if which == 2 else color, ec='white', lw=0.5, **arrow_params)
def check(self, msize=10): self.id = '|'.join([L[0] for L in self.label_id]) if self.left_color and self.right_color: self.vals = { 'color': self.left_color, 'fillstyle': 'left', 'marker': 'o', 'markerfacecoloralt': self.right_color, 'mew': 0.0 } elif self.left_color: self.vals = { 'color': self.left_color, 'marker': 'o', 'mew': 0.0 } #, 'markersize': self.size} else: self.vals = {'mew': 0.0} if self.marker: self.vals['marker'] = self.marker self.proxy = Line([0], [0], linestyle='none', markersize=msize, **self.vals) self.vals['markersize'] = self.size return self
def __init__(self, label, handles, color='k'): if label not in SortFail.labels: marker = SortFail.markers[len(SortFail.labels)] SortFail.labels.append(label) handles.append( Line([0], [0], marker=marker, label=label, color=color)) self.marker = SortFail.markers[SortFail.labels.index(label)] self.color = color
def create_time_line(self, axes, t, y, time_value, label): if time_value != t[-1]: time_line = Line([time_value, time_value], [np.min(y), y[np.where(t == time_value)][0]], ls=self.line_style, c=self.line_color) axes.add_line(time_line) axes.text(time_value + self.spacing, self.label_positions[self.counter], label, size=self.font_size) self.counter += 1
def line(self, origin, dest): if not self.drawing: return origin = self._to_canvas(origin) dest = self._to_canvas(dest) line = Line( [origin[0], dest[0]], [origin[1], dest[1]], transform=self.figure.transFigure, **self.attributes, ) self.figure.lines.append(line) self.figure.canvas.draw()
def load_plot(self): """ loads the plot lines from the variables assigned to the class """ x = [] y = [] for v in self.variables: for i in v.get_all_points(): x.append(i[0]) y.append(i[1]) x.sort() y.sort() sp = self.figure.add_subplot(111, title=self.variables[0].label) """ create a set of points that represent continuous lines ex: [(x1,y1),(x2,y2)], [(x2,y2),(x3,y3)] """ for k, v in enumerate(self.variables): for i, f in enumerate(v.functions): fx = [] fy = [] for p in f.points: fx.append(p[0]) fy.append(p[1]) if i == len(v.functions) - 1: fx.append(fx[len(fx) - 1] + 10) fy.append(f.membership(fx[len(fx) - 1])) if k != 0: line = Line(fx, fy, linewidth=2, c=[1, 0, 0]) else: line = Line(fx, fy, linewidth=2) sp.add_line(line) sp.plot() sp.axis([x[0], x[len(x) - 1] + 10, y[0], y[len(y) - 1] + 0.5])
def main(): # Define the two coordinate systems with different ellipses. wgs84 = ccrs.PlateCarree(globe=ccrs.Globe(datum='WGS84', ellipse='WGS84')) sphere = ccrs.PlateCarree( globe=ccrs.Globe(datum='WGS84', ellipse='sphere')) # Define the coordinate system of the data we have from Natural Earth and # acquire the 1:10m physical coastline shapefile. geodetic = ccrs.Geodetic(globe=ccrs.Globe(datum='WGS84')) dataset = cfeature.NaturalEarthFeature(category='physical', name='coastline', scale='10m') # Create a Stamen map tiler instance, and use its CRS for the GeoAxes. tiler = StamenTerrain() fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection=tiler.crs) ax.set_title('The effect of incorrectly referencing the Solomon Islands') # Pick the area of interest. In our case, roughly the Solomon Islands, and # get hold of the coastlines for that area. extent = [155, 163, -11.5, -6] ax.set_extent(extent, geodetic) geoms = list(dataset.intersecting_geometries(extent)) # Add the Stamen aerial imagery at zoom level 7. ax.add_image(tiler, 7) # Transform the geodetic coordinates of the coastlines into the two # projections of differing ellipses. wgs84_geoms = [ geom_transform(transform_fn_factory(wgs84, geodetic), geom) for geom in geoms ] sphere_geoms = [ geom_transform(transform_fn_factory(sphere, geodetic), geom) for geom in geoms ] # Using these differently referenced geometries, assume that they are # both referenced to WGS84. ax.add_geometries(wgs84_geoms, wgs84, edgecolor='white', color='none') ax.add_geometries(sphere_geoms, wgs84, edgecolor='gray', color='none') # Create a legend for the coastlines. legend_artists = [ Line([0], [0], color=color, linewidth=3) for color in ('white', 'gray') ] legend_texts = ['Correct ellipse\n(WGS84)', 'Incorrect ellipse\n(sphere)'] legend = ax.legend(legend_artists, legend_texts, fancybox=True, loc='lower left', framealpha=0.75) legend.legendPatch.set_facecolor('wheat') # Create an inset GeoAxes showing the location of the Solomon Islands. sub_ax = fig.add_axes([0.7, 0.625, 0.2, 0.2], projection=ccrs.PlateCarree()) sub_ax.set_extent([110, 180, -50, 10], geodetic) # Make a nice border around the inset axes. effect = Stroke(linewidth=4, foreground='wheat', alpha=0.5) sub_ax.outline_patch.set_path_effects([effect]) # Add the land, coastlines and the extent of the Solomon Islands. sub_ax.add_feature(cfeature.LAND) sub_ax.coastlines() extent_box = sgeom.box(extent[0], extent[2], extent[1], extent[3]) sub_ax.add_geometries([extent_box], ccrs.PlateCarree(), color='none', edgecolor='blue', linewidth=2) plt.show()
sort.counting_sort, sort.selection_sort, sort.bubble_sort, sort.max_heap_sort, sort.bucket_sort, # for the brave hearted sort.gnome_sort, sort.bogo_sort ] labels = [alg.__name__ for alg in algs] colors = [ cm.get_cmap('gist_rainbow')(i) for i in np.linspace(0.0, 1.0, len(labels)) ] handles = [ Line([0], [0], color=color, lw=4, label=label) for label, color in zip(labels, colors) ] fig, axs = plt.subplots(1, 5, sharey=True, figsize=(25, 5)) for plot in range(5): limit = plot * 2 for alg, color in zip(algs, colors): durations = [] error_flag = False measurement_count = 3 measurements = np.empty(measurement_count) for idx, length in enumerate(lengths): arr = np.random.randint(pow(10, limit), pow(10, limit + 1), length) try: for measurement in range(measurement_count):
def run(self, data): # dict for calculated values output = {} # reset counter self.counter = 0 # calculate data sets t = data["results"]["time"] y = data["results"]["Model"][:, 0] yd = data["results"]["Trajectory"][-1][0] self.label_positions = np.arange(np.min(y) + 0.1 * yd, yd, (yd - np.min(y)) / 4) # create plot fig = Figure() axes = fig.add_subplot(111) axes.set_title(r"\textbf{Sprungantwort}") axes.plot(t, y, c='k') axes.set_xlim(left=0, right=t[-1]) axes.set_xlabel(r"\textit{Zeit [s]}") axes.set_ylabel(r"\textit{Systemausgang [m]}") # create desired line desired_line = Line([0, t[-1]], [yd, yd], lw=1, ls=self.line_style, c='k') axes.add_line(desired_line) # calc rise-time (Anstiegszeit) try: t_rise = t[np.where(y > 0.9*yd)][0] self.create_time_line(axes, t, y, t_rise, r"$T_r$") output.update({"t_rise": t_rise}) except IndexError: output.update({"t_rise": None}) # calc correction-time (Anregelzeit) try: t_corr = t[np.where(y > yd)][0] self.create_time_line(axes, t, y, t_corr, r"$T_{anr}$") output.update({"t_corr": t_corr}) except IndexError: output.update({"t_corr": None}) # calc overshoot-time and overshoot in percent (Überschwingzeit und Überschwingen) if output["t_corr"]: if yd > 0: y_max = np.max(y[np.where(t > output["t_corr"])]) else: y_max = np.min(y[np.where(t > output["t_corr"])]) t_over = t[np.where(y == y_max)][0] overshoot = y_max - yd overshoot_per = overshoot/yd * 100 self.create_time_line(axes, t, y, t_over, r"$T_o$") output.update(dict(t_over=t_over, overshoot=overshoot, overshoot_percent=overshoot_per)) else: output.update(dict(t_over=None, overshoot=None, overshoot_percent=None)) # calc damping-time (Beruhigungszeit) try: enter_idx = -1 for idx, val in enumerate(y): if enter_idx == -1: if abs(val - yd) < self.eps: enter_idx = idx else: if abs(val - yd) >= self.eps: enter_idx = -1 t_damp = t[enter_idx] self.create_time_line(axes, t, y, t_damp, r"$T_{\epsilon}$") output.update({"t_damp": t_damp}) except IndexError: output.update({"t_damp": None}) # create epsilon tube upper_bound_line = Line([0, t[-1]], [yd + self.eps, yd + self.eps], ls="--", c=self.line_color) axes.add_line(upper_bound_line) lower_bound_line = Line([0, t[-1]], [yd - self.eps, yd - self.eps], ls="--", c=self.line_color) axes.add_line(lower_bound_line) # calc stationary control deviation control_deviation = y[-1] - yd output.update({"stationary_error": control_deviation}) self.calc_metrics(data, output) # check for sim success if not data["results"]["finished"]: for key in output.keys(): output[key] = None # add settings and metrics to dictionary results results = {} results.update({"metrics": output}) results.update({"modules": data["modules"]}) canvas = FigureCanvas(fig) self.write_output_files(data["regime name"], fig, results) return [dict(name='_'.join([data["regime name"], self.name]), figure=canvas)]
mpl.rcParams['toolbar'] = 'None' lengths = [int(10 ** (x+1/2)) for x in range(9)] algs = [search.binary_search, search.first_occurrence, search.interpolation_search, search.jump_search, search.last_occurrence, search.linear_search, search.search_insert, search.search_rotate ] labels = [alg.__name__ for alg in algs] colors = [cm.get_cmap('gist_rainbow')(i) for i in np.linspace(0.0, 1.0, len(labels))] handles = [Line([0], [0], color=color, lw=4, label=label) for label, color in zip(labels, colors)] fig, axs = plt.subplots(1, 5, sharey=True, figsize=(25, 5)) for plot in range(5): step = (plot+1) ** 5 for alg, color in zip(algs, colors): rand_gen = np.random.default_rng(0) durations = [] error_flag = False measurement_count = 3 measurements = np.empty(measurement_count) for idx, length in enumerate(lengths): arr = np.arange(0, step*length, step) try: for measurement in range(measurement_count): index = rand_gen.choice(length)
def render_map(time_current, ships, margin, plot=False): # Get base map # cimgt.StamenTerrain() zoom-level 12 or 13 # cimgt.GoogleTiles(style="satellite") # cimgt.GoogleTiles(style="terrain") # cimgt.MapboxTiles ! (More args required) # cimgt.MapQuestOpenAerial (Error downloading tiles) # cimgt.MapQuestOSM # cimgt.QuadtreeTiles # cimgt.OSM basemap_tiles = CachedTiler(cimgt.StamenTerrain()) zoom_level = 12 min_lon = min([s[0].min_lon for s in ships]) max_lon = max([s[0].max_lon for s in ships]) min_lat = min([s[0].min_lat for s in ships]) max_lat = max([s[0].max_lat for s in ships]) d_lon = max_lon - min_lon d_lat = max_lat - min_lat # set up axes fig = plt.figure() fig.set_size_inches(20, 10) ax = plt.axes(projection=basemap_tiles.crs) # Create a GeoAxes in the tile's projection. ax.set_extent([min_lon - margin * d_lon, max_lon + margin * d_lon, min_lat - margin * d_lat, max_lat + margin * d_lat]) # Limit extent to track bounding box. ax.add_image(basemap_tiles, zoom_level) # Add the basemap data at zoom level 8. # Use the cartopy interface to create a matplotlib transform object # for the Geodetic coordinate system. We will use this along with # matplotlib's offset_copy function to define a coordinate system which # translates the text by 25 pixels to the left. # geodetic_transform = ccrs.Geodetic()._as_mpl_transform(ax) # text_transform = offset_copy(geodetic_transform, units='dots', x=-25) # Add Title, Legend, Time indicator plt.title(time_current.strftime("%Y-%m-%d")) ship_names = [s[0].meta["name"] for s in ships] ship_colors = [s[0].meta["color"] for s in ships] legend_artists = [Line([0], [0], color=color, linewidth=1) for color in ship_colors] legend = plt.legend(legend_artists, ship_names, fancybox=True, loc='lower left', framealpha=0.75) legend.legendPatch.set_facecolor('none') plt.annotate(str(time_current.strftime("%H:%M UTM")), xy=(0.5, 0.05), xycoords='axes fraction') # Add ship tracks for ship in ships: vertices = sgeom.LineString(zip(ship[0].lons(max_time=time_current), ship[0].lats(max_time=time_current))) ax.add_geometries([vertices], ccrs.PlateCarree(), facecolor='none', edgecolor=ship[0].meta["color"]) # Add a marker for the ships last location last_pos = ship[0].last_position_at_time(time_current) last_info = ship[0].last_info_at_time(time_current) plt.plot(last_pos[0], last_pos[1], marker=(3, 0, last_info[0]), color=ship[0].meta["color"], markersize=5, alpha=1, transform=ccrs.PlateCarree()) # plt.annotate("Shelby: {:.1f} kts".format(last_info[1] * 1.94384), xy=(0.9, 0.05), xycoords='axes fraction') # plt.annotate("Elixir: {:.1f} kts".format(last_info[1] * 1.94384), xy=(0.9, 0.05), xycoords='axes fraction') # finalize if plot: plt.show() return fig
def plot_legend(cols, legend_texts, legend_styles, plot_vars=[], plot_dict=[], bbox_loc=[]): "Plot legend box" # Default number of legend columns ncols = 1 if not legend_texts: legend_texts = [] for ivar in plot_vars: if plot_dict['fig_ens_col'] == [] or ivar['ens'] != 'member': legend_texts.append(ivar['legend']) bbox_loc = (0.6, 1.2, 0, 0) if len(plot_vars) > 18: ncols = 4 bbox_loc = (0.9, 1.15, 0, 0) elif len(plot_vars) > 12: ncols = 3 bbox_loc = (0.8, 1.15, 0, 0) elif len(plot_vars) > 6: ncols = 2 bbox_loc = (0.7, 1.15, 0, 0) if not legend_styles: legend_styles = ['-' for x in cols] # Create a legend istyle = 0 legend_artists = [] for color in cols: legend_artists.append( Line([0], [0], color=color, linewidth=2, linestyle=legend_styles[istyle])) istyle += 1 #legend_artists = [Line([0], [0], color=color, linewidth=2) # for color in cols] if bbox_loc: legend = plt.legend(legend_artists, legend_texts, fancybox=True, loc='upper right', framealpha=0.75, ncol=ncols, bbox_to_anchor=bbox_loc) else: legend = plt.legend(legend_artists, legend_texts, fancybox=True, loc='upper right', framealpha=0.75, ncol=ncols) legend.legendPatch.set_facecolor('wheat')
def run(self, data): # dict for calculated values output = {} # reset counter self.counter = 0 # calculate data sets t = data["results"]["time"] y = data["results"]["Model"][:, self.model_idx] traj_data = data["results"]["Trajectory"] if traj_data.ndim == 2: yd = data["results"]["Trajectory"][-1, self.trajectory_idx] elif traj_data.ndim == 3: yd = data["results"]["Trajectory"][-1, self.trajectory_idx, 0] else: raise ValueError("unknown Trajectory type.") self.label_positions = np.arange(y.min() + 0.1 * yd, yd, (yd - y.min()) / 4) # create plot fig = Figure() axes = fig.add_subplot(111) axes.grid() axes.set_title(r"Step Response") axes.plot(t, y, c=colors.HKS44K100, linewidth=self.line_width) axes.set_xlim(left=0, right=t[-1]) axes.set_xlabel(r"Time in $\si{\second}$") axes.set_ylabel(r"System Output in $\si{\metre}$") # create desired line desired_line = Line([0, t[-1]], [yd, yd], lw=1, ls=self.line_style, c='k') axes.add_line(desired_line) # calc rise-time (Anstiegszeit) try: t_rise = t[np.where(y > 0.9 * yd)][0] self.create_time_line(axes, t, y, t_rise, r"$T_r$") output.update({"t_rise": t_rise}) except IndexError: output.update({"t_rise": None}) # calc correction-time (Anregelzeit) try: t_corr = t[np.where(y > yd)][0] self.create_time_line(axes, t, y, t_corr, r"$T_{c}$") output.update({"t_corr": t_corr}) except IndexError: output.update({"t_corr": None}) # calc overshoot-time and overshoot in percent # (Überschwingzeit und Überschwingen) if output["t_corr"]: if yd > 0: y_max = np.max(y[np.where(t > output["t_corr"])]) else: y_max = np.min(y[np.where(t > output["t_corr"])]) t_over = t[np.where(y == y_max)][0] overshoot = y_max - yd overshoot_per = overshoot / yd * 100 self._logger.info("Overshoot: {}%".format(overshoot_per)) self.create_time_line(axes, t, y, t_over, r"$T_o$") output.update( dict(t_over=t_over, overshoot=overshoot, overshoot_percent=overshoot_per)) else: output.update( dict(t_over=None, overshoot=None, overshoot_percent=None)) # calc damping-time (Beruhigungszeit) try: enter_idx = -1 for idx, val in enumerate(y): if enter_idx == -1: if abs(val - yd) < self.eps: enter_idx = idx else: if abs(val - yd) >= self.eps: enter_idx = -1 t_damp = t[enter_idx] self.create_time_line(axes, t, y, t_damp, r"$T_{\epsilon}$") output.update({"t_damp": t_damp}) except IndexError: output.update({"t_damp": None}) # create epsilon tube upper_bound_line = Line([0, t[-1]], [yd + self.eps, yd + self.eps], ls="--", c=self.line_color) axes.add_line(upper_bound_line) lower_bound_line = Line([0, t[-1]], [yd - self.eps, yd - self.eps], ls="--", c=self.line_color) axes.add_line(lower_bound_line) # calc stationary control deviation control_deviation = y[-1] - yd output.update({"stationary_error": control_deviation}) # check for sim success if not data["results"]["finished"]: for key in output.keys(): output[key] = None # add settings and metrics to dictionary results results = {} y_des = np.ones_like(y) * yd step_width = 1 / data["modules"]["Solver"]["measure rate"] results.update( {"metrics": self.calc_metrics(y, y_des, step_width, output)}) results.update({"modules": data["modules"]}) canvas = FigureCanvas(fig) self.write_output_files(data["regime name"], fig, results) return [ dict(name='_'.join([data["regime name"], self.name]), figure=canvas) ]