def __plot_all(self, spectrum): total = len(spectrum) count = 0.0 for timeStamp in spectrum: if self.settings.fadeScans: alpha = (count + 1) / total else: alpha = 1 data = list(spectrum[timeStamp].items()) peakF, peakL = self.extent.get_peak_fl() segments, levels = self.__create_segments(data) if segments is not None: lc = LineCollection(segments) lc.set_array(numpy.array(levels)) lc.set_norm(self.__get_norm(self.settings.autoL, self.extent)) lc.set_cmap(self.colourMap) lc.set_linewidth(self.lineWidth) lc.set_gid('plot') lc.set_alpha(alpha) self.axes.add_collection(lc) count += 1 return peakF, peakL
class Visualize: def __init__(self, v, t, e, fig, win, axesLimit=[-3,3.5,-2,2]): self.e = e.copy() self.p = [Polygon(v[ti]) for ti in t] self.p = PatchCollection(self.p, edgecolors='none') self.l = LineCollection(v[e[:,:2]]) win = win or fig.canvas.manager.window if fig is None: fig = gcf() fig.clf() ax = fig.add_axes([0.02,0.02,.98,.98]) ax.axis('scaled') ax.axis(axesLimit) ax.set_autoscale_on(False) self.axis, self.fig, self.win = ax, fig, win ax.add_collection(self.p) ax.add_collection(self.l) # ax.add_collection(self.l1) # ax.add_collection(self.l2) def update(self, title, phi): norm = Normalize(phi.min(), phi.max()) self.p.set_norm(norm) self.l.set_norm(norm) self.p.set_array(phi) self.l.set_array(phi[self.e[:,2:]].mean(1)) if not self.__dict__.has_key('colorbar'): self.colorbar = self.fig.colorbar(self.p) self.win.set_title(title) #self.fig.canvas.set_window_title(title) self.fig.canvas.draw()
def __plot_all(self, spectrum): total = len(spectrum) count = 0.0 for timeStamp in spectrum: if self.settings.fadeScans: alpha = (total - count) / total else: alpha = 1 data = spectrum[timeStamp].items() peakF, peakL = self.extent.get_peak_fl() segments, levels = self.__create_segments(data) if segments is not None: lc = LineCollection(segments) lc.set_array(numpy.array(levels)) lc.set_norm(self.__get_norm(self.settings.autoL, self.extent)) lc.set_cmap(self.colourMap) lc.set_linewidth(self.lineWidth) lc.set_gid('plot') lc.set_alpha(alpha) self.axes.add_collection(lc) count += 1 return peakF, peakL
def __plot_all(self): total = len(self.data) count = 0.0 for timeStamp in self.data: if len(self.data[timeStamp]) < 2: self.parent.threadPlot = None return None, None if self.fade: alpha = (total - count) / total else: alpha = 1 data = self.data[timeStamp].items() peakF, peakL = self.extent.get_peak_fl() segments, levels = self.__create_segments(data) lc = LineCollection(segments) lc.set_array(numpy.array(levels)) lc.set_norm(self.__get_norm(self.autoL, self.extent)) lc.set_cmap(self.colourMap) lc.set_linewidth(self.lineWidth) lc.set_gid('plot') lc.set_alpha(alpha) self.axes.add_collection(lc) count += 1 return peakF, peakL
def create_line_collection(net, lines=None, use_line_geodata=True, infofunc=None, cmap=None, norm=None, picker=False, z=None, cbar_title="Line Loading [%]", **kwargs): """ Creates a matplotlib line collection of pandapower lines. Input: **net** (pandapowerNet) - The pandapower network OPTIONAL: **lines** (list, None) - The lines for which the collections are created. If None, all lines in the network are considered. *use_line_geodata** (bool, True) - defines if lines patches are based on net.line_geodata of the lines (True) or on net.bus_geodata of the connected buses (False) **infofunc** (function, None) - infofunction for the patch element **kwargs - key word arguments are passed to the patch function """ lines = net.line_geodata.index.tolist() if lines is None and use_line_geodata else \ net.line.index.tolist() if lines is None and not use_line_geodata else list(lines) if len(lines) == 0: return None if use_line_geodata: data = [(net.line_geodata.coords.loc[line], infofunc(line) if infofunc else []) for line in lines if line in net.line_geodata.index] else: data = [([(net.bus_geodata.x.at[a], net.bus_geodata.y.at[a]), (net.bus_geodata.x.at[b], net.bus_geodata.y.at[b])], infofunc(line) if infofunc else []) for line, (a, b) in net.line[["from_bus", "to_bus"]].iterrows() if line in lines and a in net.bus_geodata.index and b in net.bus_geodata.index] data, info = list(zip(*data)) # This would be done anyways by matplotlib - doing it explicitly makes it a) clear and # b) prevents unexpected behavior when observing colors being "none" lc = LineCollection(data, picker=picker, **kwargs) lc.line_indices = np.array(lines) if cmap: if z is None: z = net.res_line.loading_percent.loc[lines] lc.set_cmap(cmap) lc.set_norm(norm) lc.set_array(z) lc.has_colormap = True lc.cbar_title = "Line Loading [%]" lc.info = info return lc
def create_trafo_connection_collection(net, trafos=None, bus_geodata=None, infofunc=None, cmap=None, clim=None, norm=None, z=None, cbar_title="Transformer Loading", **kwargs): """ Creates a matplotlib line collection of pandapower transformers. Input: **net** (pandapowerNet) - The pandapower network OPTIONAL: **trafos** (list, None) - The transformers for which the collections are created. If None, all transformers in the network are considered. **bus_geodata** (DataFrame, None) - coordinates to use for plotting If None, net["bus_geodata"] is used **infofunc** (function, None) - infofunction for the patch element **kwargs - key word arguments are passed to the patch function OUTPUT: **lc** - line collection """ trafos = net.trafo if trafos is None else net.trafo.loc[trafos] if bus_geodata is None: bus_geodata = net["bus_geodata"] hv_geo = list(zip(bus_geodata.loc[trafos["hv_bus"], "x"].values, bus_geodata.loc[trafos["hv_bus"], "y"].values)) lv_geo = list(zip(bus_geodata.loc[trafos["lv_bus"], "x"].values, bus_geodata.loc[trafos["lv_bus"], "y"].values)) tg = list(zip(hv_geo, lv_geo)) info = [infofunc(tr) if infofunc is not None else [] for tr in trafos.index.values] lc = LineCollection([(tgd[0], tgd[1]) for tgd in tg], **kwargs) lc.info = info if cmap is not None: if z is None: z = net.res_trafo.loading_percent.loc[trafos.index] lc.set_cmap(cmap) lc.set_norm(norm) if clim is not None: lc.set_clim(clim) lc.set_array(np.ma.masked_invalid(z)) lc.has_colormap = True lc.cbar_title = cbar_title return lc
def __plot_single(self, points): data = points.items() peakF, peakL = max(data, key=lambda item: item[1]) segments, levels = self.__create_segments(data) lc = LineCollection(segments) lc.set_array(numpy.array(levels)) lc.set_norm(self.__get_norm(self.settings.autoL, self.extent)) lc.set_cmap(self.colourMap) lc.set_linewidth(self.lineWidth) lc.set_gid('plot') self.axes.add_collection(lc) return peakF, peakL
def __plot_single(self, points): data = points.items() peakF, peakL = max(data, key=lambda item: item[1]) segments, levels = self.__create_segments(data) lc = LineCollection(segments) lc.set_array(numpy.array(levels)) lc.set_norm(self.__get_norm(self.autoL, self.extent)) lc.set_cmap(self.colourMap) lc.set_linewidth(self.lineWidth) lc.set_gid('plot') self.axes.add_collection(lc) return peakF, peakL
def plot(self, time, beam=None, maxground=2000, maxalt=500, iscat=True, gscat=True, title=False, weighted=False, cmap='hot_r', fig=None, rect=111, ax=None, aax=None, zorder=4): """Plot scatter on ground/altitude profile Parameters ---------- time : datetime.datetime time of profile beam : Optional[ ] beam number maxground : Optional[int] maximum ground range [km] maxalt : Optional[int] highest altitude limit [km] iscat : Optional[bool] show ionospheric scatter gscat : Optional[bool] show ground scatter title : Optional[bool] Show default title weighted : Optional[bool] plot ionospheric scatter relative strength (based on background density and range) cmap : Optional[str] colormap used for weighted ionospheric scatter fig : Optional[pylab.figure] object (default to gcf) rect : Optional[int] subplot spcification ax : Optional[ ] Existing main axes aax : Optional[ ] Existing auxialary axes zorder : Optional[int] Returns ------- ax : matplotlib.axes object containing formatting aax : matplotlib.axes object containing data cbax : matplotlib.axes object containing colorbar Example ------- # Show ionospheric scatter import datetime as dt from models import raydarn sTime = dt.datetime(2012, 11, 18, 5) rto = raydarn.RtRun(sTime, rCode='bks', beam=12) rto.readRays() # read rays into memory ax, aax, cbax = rto.rays.plot(sTime, title=True) rto.readScatter() # read scatter into memory rto.scatter.plot(sTime, ax=ax, aax=aax) ax.grid() written by Sebastien, 2013-04 """ from davitpy.utils import plotUtils from matplotlib.collections import LineCollection import matplotlib.pyplot as plt import numpy as np # Set up axes if not ax and not aax: ax, aax = plotUtils.curvedEarthAxes(fig=fig, rect=rect, maxground=maxground, maxalt=maxalt) else: ax = ax aax = aax if hasattr(ax, 'beam'): beam = ax.beam # make sure that the required time and beam are present assert (time in self.isc.keys() or time in self.gsc.keys()), logging.error('Unkown time %s' % time) if beam: assert (beam in self.isc[time].keys()), logging.error('Unkown beam %s' % beam) else: beam = self.isc[time].keys()[0] if gscat and time in self.gsc.keys(): for ir, (el, rays) in enumerate( sorted(self.gsc[time][beam].items()) ): if len(rays['r']) == 0: continue _ = aax.scatter(rays['th'], ax.Re*np.ones(rays['th'].shape), color='0', zorder=zorder) if iscat and time in self.isc.keys(): if weighted: wmin = np.min( [ r['w'].min() for r in self.isc[time][beam].values() if r['nstp'] > 0] ) wmax = np.max( [ r['w'].max() for r in self.isc[time][beam].values() if r['nstp'] > 0] ) for ir, (el, rays) in enumerate( sorted(self.isc[time][beam].items()) ): if rays['nstp'] == 0: continue t = rays['th'] r = rays['r']*1e-3 spts = np.array([t, r]).T.reshape(-1, 1, 2) h = rays['h']*1e-3 rel = np.radians( rays['rel'] ) r = np.sqrt( r**2 + h**2 + 2*r*h*np.sin( rel ) ) t = t + np.arcsin( h/r * np.cos( rel ) ) epts = np.array([t, r]).T.reshape(-1, 1, 2) segments = np.concatenate([spts, epts], axis=1) lcol = LineCollection( segments, zorder=zorder ) if weighted: _ = lcol.set_cmap( cmap ) _ = lcol.set_norm( plt.Normalize(0, 1) ) _ = lcol.set_array( ( rays['w'] - wmin ) / wmax ) else: _ = lcol.set_color('0') _ = aax.add_collection( lcol ) # Plot title with date ut time and local time if title: stitle = _getTitle(time, beam, self.header, None) ax.set_title( stitle ) # If weighted, plot ionospheric scatter with colormap if weighted: # Add a colorbar cbax = plotUtils.addColorbar(lcol, ax) _ = cbax.set_ylabel("Ionospheric Scatter") else: cbax = None ax.beam = beam return ax, aax, cbax
def create_line_collection(net, lines=None, line_geodata=None, bus_geodata=None, use_bus_geodata=False, infofunc=None, cmap=None, norm=None, picker=False, z=None, cbar_title="Line Loading [%]", clim=None, **kwargs): """ Creates a matplotlib line collection of pandapower lines. Input: **net** (pandapowerNet) - The pandapower network OPTIONAL: **lines** (list, None) - The lines for which the collections are created. If None, all lines in the network are considered. **line_geodata** (DataFrame, None) - coordinates to use for plotting. If None, net["line_geodata"] is used **bus_geodata** (DataFrame, None) - coordinates to use for plotting If None, net["bus_geodata"] is used **use_bus_geodata** (bool, False) - Defines whether bus or line geodata are used. **infofunc** (function, None) - infofunction for the patch element **cmap** - colormap for the patch colors **norm** (matplotlib norm object, None) - matplotlib norm object **picker** (bool, False) - picker argument passed to the patch collection **z** (array, None) - array of bus voltage magnitudes for colormap. Used in case of given cmap. If None net.res_bus.vm_pu is used. **cbar_title** (str, "Bus Voltage [pu]") - colormap bar title in case of given cmap **clim** (tuple of floats, None) - setting the norm limits for image scaling **kwargs - key word arguments are passed to the patch function OUTPUT: **lc** - line collection """ if use_bus_geodata: linetab = net.line if lines is None else net.line.loc[lines] lines = net.line.index.tolist() if lines is None else list(lines) if len(lines) == 0: return None if line_geodata is None: line_geodata = net["line_geodata"] if bus_geodata is None: bus_geodata = net["bus_geodata"] if len(lines) == 0: return None lines_with_geo = [] if use_bus_geodata: data = [] buses_with_geodata = bus_geodata.index.values bg_dict = bus_geodata.to_dict() #transforming to dict to make lookup faster for line, fb, tb in zip(linetab.index, linetab.from_bus.values, linetab.to_bus.values): if fb in buses_with_geodata and tb in buses_with_geodata: lines_with_geo.append(line) data.append(([(bg_dict["x"][fb], bg_dict["y"][fb]), (bg_dict["x"][tb], bg_dict["y"][tb])], infofunc(line) if infofunc else[])) lines_without_geo = set(lines)-set(lines_with_geo) if lines_without_geo: logger.warning("Could not plot lines %s. Bus geodata is missing for those lines!" % lines_without_geo) else: data = [] for line in lines: if line in line_geodata.index.values: lines_with_geo.append(line) data.append((line_geodata.loc[line, "coords"], infofunc(line) if infofunc else [])) lines_without_geo = set(lines)-set(lines_with_geo) if len(lines_without_geo) > 0: logger.warning("Could not plot lines %s. Line geodata is missing for those lines!" % lines_without_geo) if len(data) == 0: return None data, info = list(zip(*data)) # This would be done anyways by matplotlib - doing it explicitly makes it a) clear and # b) prevents unexpected behavior when observing colors being "none" lc = LineCollection(data, picker=picker, **kwargs) lc.line_indices = np.array(lines_with_geo) if cmap is not None: if z is None: z = net.res_line.loading_percent.loc[lines_with_geo] lc.set_cmap(cmap) lc.set_norm(norm) if clim is not None: lc.set_clim(clim) lc.set_array(np.array(z)) lc.has_colormap = True lc.cbar_title = cbar_title lc.info = info return lc
def plot(self, time, beam=None, maxground=2000, maxalt=500, step=1, showrefract=False, nr_cmap='jet_r', nr_lim=[0.8, 1.], raycolor='0.3', title=False, zorder=2, alpha=1, fig=None, rect=111, ax=None, aax=None): """Plot ray paths **Args**: * **time** (datetime.datetime): time of rays * [**beam**]: beam number * [**maxground**]: maximum ground range [km] * [**maxalt**]: highest altitude limit [km] * [**step**]: step between each plotted ray (in number of ray steps) * [**showrefract**]: show refractive index along ray paths (supersedes raycolor) * [**nr_cmap**]: color map name for refractive index coloring * [**nr_lim**]: refractive index plotting limits * [**raycolor**]: color of ray paths * [**rect**]: subplot spcification * [**fig**]: A pylab.figure object (default to gcf) * [**title**]: Show default title * [**ax**]: Existing main axes * [**aax**]: Existing auxialary axes **Returns**: * **ax**: matplotlib.axes object containing formatting * **aax**: matplotlib.axes object containing data * **cbax**: matplotlib.axes object containing colorbar **Example**: :: # Show ray paths with colored refractive index along path import datetime as dt from models import raydarn sTime = dt.datetime(2012, 11, 18, 5) rto = raydarn.RtRun(sTime, rCode='bks', beam=12, title=True) rto.readRays() # read rays into memory ax, aax, cbax = rto.rays.plot(sTime, step=10, showrefract=True, nr_lim=[.85,1]) ax.grid() written by Sebastien, 2013-04 """ from utils import plotUtils from matplotlib.collections import LineCollection import matplotlib.pyplot as plt import numpy as np from types import MethodType # Set up axes if not ax and not aax: ax, aax = plotUtils.curvedEarthAxes(fig=fig, rect=rect, maxground=maxground, maxalt=maxalt) else: ax = ax aax = aax if hasattr(ax, 'time'): time = ax.time if hasattr(ax, 'beam'): beam = ax.beam # make sure that the required time and beam are present assert (time in self.paths.keys()), 'Unkown time %s' % time if beam: assert (beam in self.paths[time].keys()), 'Unkown beam %s' % beam else: beam = self.paths[time].keys()[0] for ir, (el, rays) in enumerate( sorted(self.paths[time][beam].items()) ): if not ir % step: if not showrefract: aax.plot(rays['th'], rays['r']*1e-3, c=raycolor, zorder=zorder, alpha=alpha) else: points = np.array([rays['th'], rays['r']*1e-3]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lcol = LineCollection( segments, zorder=zorder, alpha=alpha) _ = lcol.set_cmap( nr_cmap ) _ = lcol.set_norm( plt.Normalize(*nr_lim) ) _ = lcol.set_array( rays['nr'] ) _ = aax.add_collection( lcol ) # Plot title with date ut time and local time if title: stitle = _getTitle(time, beam, self.header, self.name) ax.set_title( stitle ) # Add a colorbar when plotting refractive index if showrefract: cbax = plotUtils.addColorbar(lcol, ax) _ = cbax.set_ylabel("refractive index") else: cbax = None # Declare a new method to show range markers # This method is only available after rays have been plotted # This ensures that the markers match the plotted rays def showRange(self, markers=None, color='.8', s=2, zorder=3, **kwargs): """Plot ray paths **Args**: * [**markers**]: range markers. Defaults to every 250 km * All other keywords are borrowed from :func:`matplotlib.pyplot.scatter` **Returns**: * **coll**: a collection of range markers **Example**: :: # Add range markers to an existing ray plot ax, aax, cbax = rto.rays.plot(sTime, step=10) rto.rays.showRange() written by Sebastien, 2013-04 """ if not markers: markers = np.arange(0, 5000, 250) x, y = [], [] for el, rays in self.paths[time][beam].items(): for rm in markers: inds = (rays['gran']*1e-3 >= rm) if inds.any(): x.append( rays['th'][inds][0] ) y.append( rays['r'][inds][0]*1e-3 ) coll = aax.scatter(x, y, color=color, s=s, zorder=zorder, **kwargs) return coll # End of new method # Assign new method self.showRange = MethodType(showRange, self) ax.beam = beam return ax, aax, cbax
def plot(self, time, beam=None, maxground=2000, maxalt=500, iscat=True, gscat=True, title=False, weighted=False, cmap='hot_r', fig=None, rect=111, ax=None, aax=None, zorder=4): """Plot scatter on ground/altitude profile **Args**: * **time** (datetime.datetime): time of profile * [**beam**]: beam number * [**iscat**] (bool): show ionospheric scatter * [**gscat**] (bool): show ground scatter * [**maxground**]: maximum ground range [km] * [**maxalt**]: highest altitude limit [km] * [**rect**]: subplot spcification * [**fig**]: A pylab.figure object (default to gcf) * [**ax**]: Existing main axes * [**aax**]: Existing auxialary axes * [**title**]: Show default title * [**weighted**] (bool): plot ionospheric scatter relative strength (based on background density and range) * [**cmap**]: colormap used for weighted ionospheric scatter **Returns**: * **ax**: matplotlib.axes object containing formatting * **aax**: matplotlib.axes object containing data * **cbax**: matplotlib.axes object containing colorbar **Example**: :: # Show ionospheric scatter import datetime as dt from models import raydarn sTime = dt.datetime(2012, 11, 18, 5) rto = raydarn.RtRun(sTime, rCode='bks', beam=12) rto.readRays() # read rays into memory ax, aax, cbax = rto.rays.plot(sTime, title=True) rto.readScatter() # read scatter into memory rto.scatter.plot(sTime, ax=ax, aax=aax) ax.grid() written by Sebastien, 2013-04 """ from davitpy.utils import plotUtils from matplotlib.collections import LineCollection import matplotlib.pyplot as plt import numpy as np # Set up axes if not ax and not aax: ax, aax = plotUtils.curvedEarthAxes(fig=fig, rect=rect, maxground=maxground, maxalt=maxalt) else: ax = ax aax = aax if hasattr(ax, 'beam'): beam = ax.beam # make sure that the required time and beam are present assert (time in self.isc.keys() or time in self.gsc.keys()), 'Unkown time %s' % time if beam: assert (beam in self.isc[time].keys()), 'Unkown beam %s' % beam else: beam = self.isc[time].keys()[0] if gscat and time in self.gsc.keys(): for ir, (el, rays) in enumerate(sorted(self.gsc[time][beam].items())): if len(rays['r']) == 0: continue _ = aax.scatter(rays['th'], ax.Re * np.ones(rays['th'].shape), color='0', zorder=zorder) if iscat and time in self.isc.keys(): if weighted: wmin = np.min([ r['w'].min() for r in self.isc[time][beam].values() if r['nstp'] > 0 ]) wmax = np.max([ r['w'].max() for r in self.isc[time][beam].values() if r['nstp'] > 0 ]) for ir, (el, rays) in enumerate(sorted(self.isc[time][beam].items())): if rays['nstp'] == 0: continue t = rays['th'] r = rays['r'] * 1e-3 spts = np.array([t, r]).T.reshape(-1, 1, 2) h = rays['h'] * 1e-3 rel = np.radians(rays['rel']) r = np.sqrt(r**2 + h**2 + 2 * r * h * np.sin(rel)) t = t + np.arcsin(h / r * np.cos(rel)) epts = np.array([t, r]).T.reshape(-1, 1, 2) segments = np.concatenate([spts, epts], axis=1) lcol = LineCollection(segments, zorder=zorder) if weighted: _ = lcol.set_cmap(cmap) _ = lcol.set_norm(plt.Normalize(0, 1)) _ = lcol.set_array((rays['w'] - wmin) / wmax) else: _ = lcol.set_color('0') _ = aax.add_collection(lcol) # Plot title with date ut time and local time if title: stitle = _getTitle(time, beam, self.header, None) ax.set_title(stitle) # If weighted, plot ionospheric scatter with colormap if weighted: # Add a colorbar cbax = plotUtils.addColorbar(lcol, ax) _ = cbax.set_ylabel("Ionospheric Scatter") else: cbax = None ax.beam = beam return ax, aax, cbax
def plot(self, time, beam=None, maxground=2000, maxalt=500, step=1, showrefract=False, nr_cmap='jet_r', nr_lim=[0.8, 1.], raycolor='0.3', title=False, zorder=2, alpha=1, fig=None, rect=111, ax=None, aax=None): """Plot ray paths **Args**: * **time** (datetime.datetime): time of rays * [**beam**]: beam number * [**maxground**]: maximum ground range [km] * [**maxalt**]: highest altitude limit [km] * [**step**]: step between each plotted ray (in number of ray steps) * [**showrefract**]: show refractive index along ray paths (supersedes raycolor) * [**nr_cmap**]: color map name for refractive index coloring * [**nr_lim**]: refractive index plotting limits * [**raycolor**]: color of ray paths * [**rect**]: subplot spcification * [**fig**]: A pylab.figure object (default to gcf) * [**title**]: Show default title * [**ax**]: Existing main axes * [**aax**]: Existing auxialary axes **Returns**: * **ax**: matplotlib.axes object containing formatting * **aax**: matplotlib.axes object containing data * **cbax**: matplotlib.axes object containing colorbar **Example**: :: # Show ray paths with colored refractive index along path import datetime as dt from davitpy.models import raydarn sTime = dt.datetime(2012, 11, 18, 5) rto = raydarn.RtRun(sTime, rCode='bks', beam=12, title=True) rto.readRays() # read rays into memory ax, aax, cbax = rto.rays.plot(sTime, step=10, showrefract=True, nr_lim=[.85,1]) ax.grid() written by Sebastien, 2013-04 """ import datetime as dt from davitpy.utils import plotUtils from matplotlib.collections import LineCollection import matplotlib.pyplot as plt import numpy as np from types import MethodType # Set up axes if not ax and not aax: ax, aax = plotUtils.curvedEarthAxes(fig=fig, rect=rect, maxground=maxground, maxalt=maxalt) else: ax = ax aax = aax if hasattr(ax, 'time'): time = ax.time if hasattr(ax, 'beam'): beam = ax.beam # make sure that the required time and beam are present # Allow a 60 second difference between the requested time and the time # available. keys = np.array(self.paths.keys()) diffs = np.abs(keys - time) if diffs.min() < dt.timedelta(minutes=1): time = keys[diffs.argmin()] assert (time in self.paths.keys()), 'Unkown time %s' % time if beam: assert (beam in self.paths[time].keys()), 'Unkown beam %s' % beam else: beam = self.paths[time].keys()[0] for ir, (el, rays) in enumerate(sorted(self.paths[time][beam].items())): if not ir % step: if not showrefract: aax.plot(rays['th'], rays['r'] * 1e-3, c=raycolor, zorder=zorder, alpha=alpha) else: points = np.array([rays['th'], rays['r'] * 1e-3]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lcol = LineCollection(segments, zorder=zorder, alpha=alpha) _ = lcol.set_cmap(nr_cmap) _ = lcol.set_norm(plt.Normalize(*nr_lim)) _ = lcol.set_array(rays['nr']) _ = aax.add_collection(lcol) # Plot title with date ut time and local time if title: stitle = _getTitle(time, beam, self.header, self.name) ax.set_title(stitle) # Add a colorbar when plotting refractive index if showrefract: cbax = plotUtils.addColorbar(lcol, ax) _ = cbax.set_ylabel("refractive index") else: cbax = None # Declare a new method to show range markers # This method is only available after rays have been plotted # This ensures that the markers match the plotted rays def showRange(self, markers=None, color='.8', s=2, zorder=3, **kwargs): """Plot ray paths **Args**: * [**markers**]: range markers. Defaults to every 250 km * All other keywords are borrowed from :func:`matplotlib.pyplot.scatter` **Returns**: * **coll**: a collection of range markers **Example**: :: # Add range markers to an existing ray plot ax, aax, cbax = rto.rays.plot(sTime, step=10) rto.rays.showRange() written by Sebastien, 2013-04 """ if not markers: markers = np.arange(0, 5000, 250) x, y = [], [] for el, rays in self.paths[time][beam].items(): for rm in markers: inds = (rays['gran'] * 1e-3 >= rm) if inds.any(): x.append(rays['th'][inds][0]) y.append(rays['r'][inds][0] * 1e-3) coll = aax.scatter(x, y, color=color, s=s, zorder=zorder, **kwargs) return coll # End of new method # Assign new method self.showRange = MethodType(showRange, self) ax.beam = beam return ax, aax, cbax
def create_line_collection(net, lines=None, line_geodata=None, bus_geodata=None, use_bus_geodata=False, infofunc=None, cmap=None, norm=None, picker=False, z=None, cbar_title="Line Loading [%]", clim=None, **kwargs): """ Creates a matplotlib line collection of pandapower lines. Input: **net** (pandapowerNet) - The pandapower network OPTIONAL: **lines** (list, None) - The lines for which the collections are created. If None, all lines in the network are considered. **line_geodata** (DataFrame, None) - coordinates to use for plotting If None, net["line_geodata"] is used **infofunc** (function, None) - infofunction for the patch element **kwargs - key word arguments are passed to the patch function OUTPUT: **lc** - line collection """ lines = net.line.index.tolist() if lines is None else list(lines) if len(lines) == 0: return None if line_geodata is None: line_geodata = net["line_geodata"] if bus_geodata is None: bus_geodata = net["bus_geodata"] if len(lines) == 0: return None if use_bus_geodata: data = [ ([(bus_geodata.at[a, "x"], bus_geodata.at[a, "y"]), (bus_geodata.at[b, "x"], bus_geodata.at[b, "y"])], infofunc(line) if infofunc else []) for line, (a, b) in net.line.loc[lines, ["from_bus", "to_bus"]].iterrows() if a in bus_geodata.index.values and b in bus_geodata.index.values ] else: data = [(line_geodata.loc[line, "coords"], infofunc(line) if infofunc else []) for line in lines if line in line_geodata.index.values] if len(data) == 0: return None data, info = list(zip(*data)) # This would be done anyways by matplotlib - doing it explicitly makes it a) clear and # b) prevents unexpected behavior when observing colors being "none" lc = LineCollection(data, picker=picker, **kwargs) lc.line_indices = np.array(lines) if cmap: if z is None: z = net.res_line.loading_percent.loc[lines] lc.set_cmap(cmap) lc.set_norm(norm) if clim is not None: lc.set_clim(clim) lc.set_array(np.array(z)) lc.has_colormap = True lc.cbar_title = cbar_title lc.info = info return lc
def create_trafo3w_collection(net, trafo3ws=None, picker=False, infofunc=None, cmap=None, norm=None, z=None, clim=None, cbar_title="3W-Transformer Loading", plot_colormap=True, **kwargs): """ Creates a matplotlib line collection of pandapower transformers. Input: **net** (pandapowerNet) - The pandapower network OPTIONAL: **trafo3ws** (list, None) - The three winding transformers for which the collections are created. If None, all three winding transformers in the network are considered. **picker** (bool, False) - picker argument passed to the patch collection **infofunc** (function, None) - infofunction for the patch element **kwargs - key word arguments are passed to the patch function OUTPUT: **lc** - line collection **pc** - patch collection """ trafo3ws = get_index_array(trafo3ws, net.trafo3w.index) trafo3w_table = net.trafo3w.loc[trafo3ws] lines = [] circles = [] infos = [] color = kwargs.pop("color", "k") linewidth = kwargs.pop("linewidths", 2.) if cmap is not None and z is None: z = net.res_trafo3w.loading_percent for i, idx in enumerate(trafo3w_table.index): # get bus geodata p1 = net.bus_geodata[["x", "y"]].loc[net.trafo3w.at[idx, "hv_bus"]].values p2 = net.bus_geodata[["x", "y"]].loc[net.trafo3w.at[idx, "mv_bus"]].values p3 = net.bus_geodata[["x", "y"]].loc[net.trafo3w.at[idx, "lv_bus"]].values if np.all(p1 == p2) and np.all(p1 == p3): continue p = np.array([p1, p2, p3]) # determine center of buses and minimum distance center-buses center = sum(p) / 3 d = np.linalg.norm(p - center, axis=1) r = d.min() / 3 # determine closest bus to center and vector from center to circle midpoint in closest # direction closest = d.argmin() to_closest = (p[closest] - center) / d[closest] * 2 * r / 3 # determine vectors from center to circle midpoint order = list(range(closest, 3)) + list(range(closest)) cm = np.empty((3, 2)) cm[order.pop(0)] = to_closest ang = 2 * np.pi / 3 # 120 degree cm[order.pop(0)] = _rotate_dim2(to_closest, ang) cm[order.pop(0)] = _rotate_dim2(to_closest, -ang) # determine midpoints of circles m = center + cm # determine endpoints of circles e = (center - p) * (1 - 5 * r / 3 / d).reshape(3, 1) + p # save circle and line collection data ec = color if cmap is None else cmap(norm(z.at[idx])) for j in range(3): circles.append(Circle(m[j], r, fc=(1, 0, 0, 0), ec=ec)) lines.append([p[j], e[j]]) if infofunc is not None: infos.append(infofunc(i)) infos.append(infofunc(i)) if len(circles) == 0: return None, None lc = LineCollection(lines, color=color, picker=picker, linewidths=linewidth, **kwargs) lc.info = infos pc = PatchCollection(circles, match_original=True, picker=picker, linewidth=linewidth, **kwargs) pc.info = infos if cmap is not None: z_duplicated = np.repeat(z.values, 3) lc.set_cmap(cmap) lc.set_norm(norm) if clim is not None: lc.set_clim(clim) lc.set_array(np.ma.masked_invalid(z_duplicated)) lc.has_colormap = plot_colormap lc.cbar_title = cbar_title return lc, pc
def run(self): if self.data is None: self.parent.threadPlot = None return peakF = None peakL = None total = len(self.data) if total > 0: self.parent.clear_plots() lc = None if self.average: avg = OrderedDict() count = len(self.data) for timeStamp in self.data: if len(self.data[timeStamp]) < 2: return for x, y in self.data[timeStamp].items(): if x in avg: avg[x] = (avg[x] + y) / 2 else: avg[x] = y data = avg.items() peakF, peakL = max(data, key=lambda item: item[1]) segments, levels = self.create_segments(data) lc = LineCollection(segments) lc.set_array(numpy.array(levels)) lc.set_norm(self.get_norm(self.autoL, self.extent)) lc.set_cmap(self.colourMap) lc.set_linewidth(self.lineWidth) lc.set_gid('plot') self.axes.add_collection(lc) self.parent.lc = lc else: count = 0.0 for timeStamp in self.data: if len(self.data[timeStamp]) < 2: self.parent.threadPlot = None return if self.fade: alpha = (total - count) / total else: alpha = 1 data = self.data[timeStamp].items() peakF, peakL = self.extent.get_peak_fl() segments, levels = self.create_segments(data) lc = LineCollection(segments) lc.set_array(numpy.array(levels)) lc.set_norm(self.get_norm(self.autoL, self.extent)) lc.set_cmap(self.colourMap) lc.set_linewidth(self.lineWidth) lc.set_gid('plot') lc.set_alpha(alpha) self.axes.add_collection(lc) count += 1 if self.annotate: self.annotate_plot(peakF, peakL) if total > 0: self.parent.scale_plot() self.parent.redraw_plot() self.parent.threadPlot = None
def plot(self, time, beam=None, maxground=2000, maxalt=500, step=1, showrefract=False, nr_cmap='jet_r', nr_lim=[0.8, 1.], raycolor='0.3', title=False, zorder=2, alpha=1, fig=None, rect=111, ax=None, aax=None): """Plot ray paths Parameters ---------- time : datetime.datetime time of rays beam: Optional[ ] beam number maxground : Optional[int] maximum ground range [km] maxalt : Optional[int] highest altitude limit [km] step : Optional[int] step between each plotted ray (in number of ray steps) showrefract : Optional[bool] show refractive index along ray paths (supersedes raycolor) nr_cmap : Optional[str] color map name for refractive index coloring nr_lim : Optional[list, float] refractive index plotting limits raycolor : Optional[float] color of ray paths title : Optional[bool] Show default title zorder : Optional[int] alpha : Optional[int] fig : Optional[pylab.figure] object (default to gcf) rect : Optional[int] subplot spcification ax : Optional[ ] Existing main axes aax : Optional[ ] Existing auxialary axes Returns ------- ax : matplotlib.axes object containing formatting aax : matplotlib.axes object containing data cbax : matplotlib.axes object containing colorbar Example ------- # Show ray paths with colored refractive index along path import datetime as dt from davitpy.models import raydarn sTime = dt.datetime(2012, 11, 18, 5) rto = raydarn.RtRun(sTime, rCode='bks', beam=12, title=True) rto.readRays() # read rays into memory ax, aax, cbax = rto.rays.plot(sTime, step=10, showrefract=True, nr_lim=[.85,1]) ax.grid() written by Sebastien, 2013-04 """ import datetime as dt from davitpy.utils import plotUtils from matplotlib.collections import LineCollection import matplotlib.pyplot as plt import numpy as np from types import MethodType # Set up axes if not ax and not aax: ax, aax = plotUtils.curvedEarthAxes(fig=fig, rect=rect, maxground=maxground, maxalt=maxalt) else: ax = ax aax = aax if hasattr(ax, 'time'): time = ax.time if hasattr(ax, 'beam'): beam = ax.beam # make sure that the required time and beam are present # Allow a 60 second difference between the requested time and the time # available. keys = np.array(self.paths.keys()) diffs = np.abs(keys-time) if diffs.min() < dt.timedelta(minutes=1): time = keys[diffs.argmin()] assert (time in self.paths.keys()), logging.error('Unkown time %s' % time) if beam: assert (beam in self.paths[time].keys()), logging.error('Unkown beam %s' % beam) else: beam = self.paths[time].keys()[0] for ir, (el, rays) in enumerate( sorted(self.paths[time][beam].items()) ): if not ir % step: if not showrefract: aax.plot(rays['th'], rays['r']*1e-3, c=raycolor, zorder=zorder, alpha=alpha) else: points = np.array([rays['th'], rays['r']*1e-3]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lcol = LineCollection( segments, zorder=zorder, alpha=alpha) _ = lcol.set_cmap( nr_cmap ) _ = lcol.set_norm( plt.Normalize(*nr_lim) ) _ = lcol.set_array( rays['nr'] ) _ = aax.add_collection( lcol ) # Plot title with date ut time and local time if title: stitle = _getTitle(time, beam, self.header, self.name) ax.set_title( stitle ) # Add a colorbar when plotting refractive index if showrefract: cbax = plotUtils.addColorbar(lcol, ax) _ = cbax.set_ylabel("refractive index") else: cbax = None # Declare a new method to show range markers # This method is only available after rays have been plotted # This ensures that the markers match the plotted rays def showRange(self, markers=None, color='.8', s=2, zorder=3, **kwargs): """Plot ray paths Parameters ---------- markers : Optional[ ] range markers. Defaults to every 250 km color : Optional[float] s : Optional[int] zorder : Optional[int] **kwargs : Returns ------- coll : a collection of range markers Notes ----- Parameters other than markers are borrowed from matplotlib.pyplot.scatter Example ------- # Add range markers to an existing ray plot ax, aax, cbax = rto.rays.plot(sTime, step=10) rto.rays.showRange() written by Sebastien, 2013-04 """ if not markers: markers = np.arange(0, 5000, 250) x, y = [], [] for el, rays in self.paths[time][beam].items(): for rm in markers: inds = (rays['gran']*1e-3 >= rm) if inds.any(): x.append( rays['th'][inds][0] ) y.append( rays['r'][inds][0]*1e-3 ) coll = aax.scatter(x, y, color=color, s=s, zorder=zorder, **kwargs) return coll # End of new method # Assign new method self.showRange = MethodType(showRange, self) ax.beam = beam return ax, aax, cbax
def plot(self, time, beam=None, maxground=2000, maxalt=500, step=1, showrefract=False, nr_cmap='jet_r', nr_lim=[0.8, 1.], raycolor='0.4', fig=None, rect=111): """Plot ray paths **Args**: * **time** (datetime.datetime): time of rays * [**beam**]: beam number * [**maxground**]: maximum ground range [km] * [**maxalt**]: highest altitude limit [km] * [**step**]: step between each plotted ray (in number of ray steps) * [**showrefract**]: show refractive index along ray paths (supersedes raycolor) * [**nr_cmap**]: color map name for refractive index coloring * [**nr_lim**]: refractive index plotting limits * [**raycolor**]: color of ray paths * [**rect**]: subplot spcification * [**fig**]: A pylab.figure object (default to gcf) **Returns**: * **ax**: matplotlib.axes object containing formatting * **aax**: matplotlib.axes object containing data * **cbax**: matplotlib.axes object containing colorbar **Example**: :: # Show ray paths with colored refractive index along path import datetime as dt from models import raydarn sTime = dt.datetime(2012, 11, 18, 5) rto = raydarn.rtRun(sTime, rCode='bks', beam=12) rto.readRays() # read rays into memory ax, aax, cbax = rto.rays.plot(sTime, step=2, showrefract=True, nr_lim=[.85,1]) ax.grid() written by Sebastien, 2013-04 """ from utils import plotUtils from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib.collections import LineCollection import matplotlib.pyplot as plt import numpy as np ax, aax = plotUtils.curvedEarthAxes(fig=fig, rect=rect, maxground=maxground, maxalt=maxalt) # make sure that the required time and beam are present assert (time in self.paths.keys()), 'Unkown time %s' % time if beam: assert (beam in self.paths[time].keys()), 'Unkown beam %s' % beam else: beam = self.paths[time].keys()[0] for ir, (el, rays) in enumerate( sorted(self.paths[time][beam].items()) ): if not ir % step: if not showrefract: aax.plot(rays['th'], rays['r']*1e-3, c=raycolor, zorder=2) else: points = np.array([rays['th'], rays['r']*1e-3]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lcol = LineCollection( segments ) lcol.set_cmap( nr_cmap ) lcol.set_norm( plt.Normalize(*nr_lim) ) lcol.set_array( rays['nr'] ) aax.add_collection( lcol ) # Add a colorbar when plotting refractive index if showrefract: from mpl_toolkits.axes_grid1 import SubplotDivider, LocatableAxes, Size fig1 = ax.get_figure() divider = SubplotDivider(fig1, *ax.get_geometry(), aspect=True) # axes for colorbar cbax = LocatableAxes(fig1, divider.get_position()) h = [Size.AxesX(ax), # main axes Size.Fixed(0.1), # padding Size.Fixed(0.2)] # colorbar v = [Size.AxesY(ax)] divider.set_horizontal(h) divider.set_vertical(v) ax.set_axes_locator(divider.new_locator(nx=0, ny=0)) cbax.set_axes_locator(divider.new_locator(nx=2, ny=0)) fig1.add_axes(cbax) cbax.axis["left"].toggle(all=False) cbax.axis["top"].toggle(all=False) cbax.axis["bottom"].toggle(all=False) cbax.axis["right"].toggle(ticklabels=True, label=True) plt.colorbar(lcol, cax=cbax) cbax.set_ylabel("refractive index") return ax, aax, cbax