def hvplot(self): # noqa F811 opts.defaults( opts.Overlay( width=self.width, height=self.height, active_tools=["wheel_zoom"] ) ) return self._hvplot_trajectory(self.data)
def hvplot(self): opts.defaults(opts.Overlay(width=self.width, height=self.height, active_tools=['wheel_zoom'])) for traj in self.data.trajectories: overlay = self._hvplot_trajectory(traj) if self.overlay: self.overlay = self.overlay * overlay else: self.overlay = overlay self.hvplot_tiles = False # has to be removed after the first iteration, otherwise tiles will cover trajectories! return self.overlay
def run_experiment(n_iters, model_gen, dl, loss_fn, optim_gen, lr_scheduler, device, print_every=None, seed=1, to_show=True): """ Args: - model_generator (Callable): returns a new model - Must accept two arguments, `device` and `seed` - It returns a model object put in `device` with any weight initialization random-seeded at `seed - optim_gen (Callable): Must take in 'model.parameters()' - eg: functools.partial(torch.optim.Adam, lr=1e-3) - seed (None or int): random seed for clean model (model weights) - None if randomness in initializing model weights is desired - any other int to set the seed - lr_scheduler: TriangleLR or ConstLR """ model = model_gen(device=device, seed=seed) optimizer = optim_gen(model.parameters()) lrs, losses, avg_losses = lr_range_test(model, dl, loss_fn, optimizer, lr_scheduler, device, n_iters=n_iters, print_every=print_every) # Visualization if to_show: hv_lr = show_lr_generator(lr_scheduler, n_iters) layout = (hv_lr.opts(color='red', ylim=(lr_scheduler.min_lr, lr_scheduler.max_lr)) + hv.Curve(losses, label='loss').opts(color='blue')) display( layout.opts( opts.Overlay(shared_axes=False), opts.Curve(padding=0.1, width=800, axiswise=True, shared_axes=False)).cols(1)) return model, lrs, losses, avg_losses
def _plot_overlay(elevation, shadows): ''' ''' shadows = hv.Dataset( (np.arange(shadows.shape[2]), np.arange( shadows.shape[0]), np.arange(shadows.shape[1]), shadows), ['Time', 'x', 'y'], 'Shadows') elevation = hv.Dataset((np.arange( elevation.shape[0]), np.arange(elevation.shape[1]), elevation), ['x', 'y'], 'Elevation') opts.defaults( opts.Image('elevation', cmap='viridis', invert_yaxis=True), opts.Image('shadows', cmap='binary', invert_yaxis=True, alpha=0.7), opts.Overlay(show_legend=False)) elevation = elevation.to(hv.Image, ['x', 'y'], group='elevation') shadows = shadows.to(hv.Image, ['x', 'y'], group='shadows') return elevation * shadows
import pandas as pd import numpy as np import holoviews as hv from holoviews import opts, dim hv.extension('bokeh') macro_df = pd.read_csv('http://assets.holoviews.org/macro.csv', '\t') key_dimensions = [('year', 'Year'), ('country', 'Country')] value_dimensions = [('unem', 'Unemployment'), ('capmob', 'Capital Mobility'), ('gdp', 'GDP Growth'), ('trade', 'Trade')] macro = hv.Table(macro_df, key_dimensions, value_dimensions) gdp_curves = macro.to.curve('Year', 'GDP Growth') gdp_unem_scatter = macro.to.scatter('Year', ['GDP Growth', 'Unemployment']) annotations = hv.Arrow(1973, 8, 'Oil Crisis', 'v') * hv.Arrow(1975, 6, 'Stagflation', 'v') *\ hv.Arrow(1979, 8, 'Energy Crisis', 'v') * hv.Arrow(1981.9, 5, 'Early Eighties\n Recession', 'v') composition=(gdp_curves * gdp_unem_scatter* annotations) composition.opts( opts.Curve(color='k'), opts.Scatter(cmap='Blues', color='Unemployment', line_color='k', size=dim('Unemployment')*1.5), opts.Text(text_font_size='13px'), opts.Overlay(height=400, show_frame=False, width=700)) hv.save(composition, 'holomap.html')
def __call__(self, dset, **params): self.p = ParamOverrides(self, params) if self.p.vdim is None: vdim = dset.vdims[0].name else: vdim = self.p.vdim ra_range = (ra0, ra1) = dset.range("ra") if self.p.ra_sampling: xsampling = (ra1 - ra0) / self.p.ra_sampling else: xsampling = None dec_range = (dec0, dec1) = dset.range("dec") if self.p.dec_sampling: ysampling = (dec1 - dec0) / self.p.dec_sampling else: ysampling = None if self.p.aggregator == "mean": aggregator = ds.mean(vdim) elif self.p.aggregator == "std": aggregator = ds.std(vdim) elif self.p.aggregator == "count": aggregator = ds.count() sky_range = RangeXY() if self.p.range_stream: def redim(dset, x_range, y_range): ranges = {} if x_range and all(isfinite(v) for v in x_range): ranges["ra"] = x_range if y_range and all(isfinite(v) for v in x_range): ranges["dec"] = y_range return dset.redim.range(**ranges) if ranges else dset dset = dset.apply(redim, streams=[self.p.range_stream]) link_streams(self.p.range_stream, sky_range) streams = [sky_range, PlotSize()] pts = dset.apply(skypoints, streams=[self.p.filter_stream]) reset = PlotReset(source=pts) reset.add_subscriber(partial(reset_stream, None, [self.p.range_stream])) rasterize_inst = rasterize.instance(aggregator=aggregator, streams=streams, x_sampling=xsampling, y_sampling=ysampling) raster_pts = apply_when( pts, operation=rasterize_inst, predicate=lambda pts: len(pts) > self.p.max_points) return raster_pts.opts( opts.Image( bgcolor="black", colorbar=True, cmap=self.p.cmap, min_height=100, responsive=True, tools=["hover"], symmetric=True, ), opts.Points( color=vdim, cmap=self.p.cmap, framewise=True, size=self.p.decimate_size, tools=["hover"], symmetric=True, ), opts.Overlay(hooks=[ partial(reset_hook, x_range=ra_range, y_range=dec_range) ]), )
def __call__(self, dset, **params): self.p = ParamOverrides(self, params) if self.p.xdim not in dset.dimensions(): raise ValueError("{} not in Dataset.".format(self.p.xdim)) if self.p.ydim not in dset.dimensions(): raise ValueError("{} not in Dataset.".format(self.p.ydim)) if ("ra" not in dset.dimensions()) or ("dec" not in dset.dimensions()): raise ValueError("ra and/or dec not in Dataset.") # Compute sampling ra_range = (ra0, ra1) = dset.range("ra") if self.p.ra_sampling: ra_sampling = (ra1 - ra0) / self.p.x_sampling else: ra_sampling = None dec_range = (dec0, dec1) = dset.range("dec") if self.p.dec_sampling: dec_sampling = (dec1 - dec0) / self.p.y_sampling else: dec_sampling = None x_range = (x0, x1) = dset.range(self.p.xdim) if self.p.x_sampling: x_sampling = (x1 - x0) / self.p.x_sampling else: x_sampling = None y_range = (y0, y1) = dset.range(self.p.ydim) if self.p.y_sampling: y_sampling = (y1 - y0) / self.p.y_sampling else: y_sampling = None # Set up scatter plot scatter_range = RangeXY() if self.p.scatter_range_stream: def redim_scatter(dset, x_range, y_range): ranges = {} if x_range and all(isfinite(v) for v in x_range): ranges[self.p.xdim] = x_range if y_range and all(isfinite(v) for v in x_range): ranges[self.p.ydim] = y_range return dset.redim.range(**ranges) if ranges else dset dset_scatter = dset.apply(redim_scatter, streams=[self.p.scatter_range_stream]) link_streams(self.p.scatter_range_stream, scatter_range) else: dset_scatter = dset scatter_pts = dset_scatter.apply(filterpoints, streams=[self.p.filter_stream], xdim=self.p.xdim, ydim=self.p.ydim) scatter_streams = [scatter_range, PlotSize()] scatter_rasterize = rasterize.instance(streams=scatter_streams, x_sampling=x_sampling, y_sampling=y_sampling) cmap = (process_cmap(self.p.scatter_cmap)[:250] if self.p.scatter_cmap == "fire" else self.p.scatter_cmap) scatter_rasterized = apply_when( scatter_pts, operation=scatter_rasterize, predicate=lambda pts: len(pts) > self.p.max_points ).opts( opts.Image(clim=(1, np.nan), clipping_colors={"min": "transparent"}, cmap=cmap), opts.Points(clim=(1, np.nan), clipping_colors={"min": "transparent"}, cmap=cmap), opts.Overlay( hooks=[partial(reset_hook, x_range=x_range, y_range=y_range)]), ) # Set up sky plot sky_range = RangeXY() if self.p.sky_range_stream: def redim_sky(dset, x_range, y_range): ranges = {} if x_range and all(isfinite(v) for v in x_range): ranges["ra"] = x_range if y_range and all(isfinite(v) for v in x_range): ranges["dec"] = y_range return dset.redim.range(**ranges) if ranges else dset dset_sky = dset.apply(redim_sky, streams=[self.p.sky_range_stream]) link_streams(self.p.sky_range_stream, sky_range) else: dset_sky = dset sky_pts = dset_sky.apply(filterpoints, xdim="ra", ydim="dec", set_title=False, streams=[self.p.filter_stream]) skyplot_streams = [sky_range, PlotSize()] sky_rasterize = rasterize.instance( aggregator=ds.mean(self.p.ydim), streams=skyplot_streams, x_sampling=ra_sampling, y_sampling=dec_sampling, ) sky_rasterized = apply_when( sky_pts, operation=sky_rasterize, predicate=lambda pts: len(pts) > self.p.max_points).opts( opts.Image(bgcolor="black", cmap=self.p.sky_cmap, symmetric=True), opts.Points(bgcolor="black", cmap=self.p.sky_cmap, symmetric=True), opts.Overlay(hooks=[ partial(reset_hook, x_range=ra_range, y_range=dec_range) ]), ) # Set up BoundsXY streams to listen to box_select events and notify FilterStream scatter_select = BoundsXY(source=scatter_pts) scatter_notifier = partial(notify_stream, filter_stream=self.p.filter_stream, xdim=self.p.xdim, ydim=self.p.ydim) scatter_select.add_subscriber(scatter_notifier) sky_select = BoundsXY(source=sky_pts) sky_notifier = partial(notify_stream, filter_stream=self.p.filter_stream, xdim="ra", ydim="dec") sky_select.add_subscriber(sky_notifier) # Reset reset = PlotReset(source=sky_pts) reset.add_subscriber( partial(reset_stream, self.p.filter_stream, [self.p.sky_range_stream, self.p.scatter_range_stream])) raw_scatterpts = filterpoints(dset, xdim=self.p.xdim, ydim=self.p.ydim) raw_scatter = datashade( raw_scatterpts, cmap=list(Greys9[::-1][:5]), streams=scatter_streams, x_sampling=x_sampling, y_sampling=y_sampling, ) scatter_p = raw_scatter * scatter_rasterized if self.p.show_rawsky: raw_skypts = filterpoints(dset, xdim=self.p.xdim, ydim=self.p.ydim) raw_sky = datashade( rawskypts, cmap=list(Greys9[::-1][:5]), streams=skyplot_streams, x_sampling=ra_sampling, y_sampling=dec_sampling, ) sky_p = raw_sky * sky_rasterized else: sky_p = sky_rasterized if self.p.show_table: table = dset.apply(summary_table, ydim=self.p.ydim, streams=[self.p.filter_stream]) table = table.opts() layout = table + scatter_p + sky_p else: layout = (scatter_p + sky_p).opts(sizing_mode="stretch_width") return layout.opts( opts.Image(colorbar=True, responsive=True, tools=["box_select", "hover"]), opts.Layout(sizing_mode="stretch_width"), opts.Points(color=self.p.ydim, tools=["hover"]), opts.RGB(alpha=0.5), opts.Table(width=200), )
class BasemapModule: """ NAME ---- BasemapModule DESCRIPTION ----------- Blueprint for Basemap objects. Plots seismic survey elements such as polygon, wells, lines and the intersection of these lines while providing interactive tools to improve the experience between data and users. These plots are not images but objects that can be modified by the user and exported as images. ATTRIBUTES ---------- basemap_dataframe : (Pandas)DataFrame Matrix compounded by the coordinates and lines of the seismic survey's corners. Empty by default. wells_dataframe : (Pandas)DataFrame Matrix compounded by wells related information. Empty by default. polygon : Holviews element [Curve] Plot of the seismic survey polygon. wells : Holviews element [Scatter] Plot of the wells inside the seismic survey. seismic_lines : Holviews element [Overlay] Plot of the seismic lines (Inline referred as iline and Crossline referred as xline) and its intersection. basemap : Holviews element [Overlay] Combination of the plots: polygon, wells and seismic_lines. METHODS ------- polygon_plot(**kwargs) Constructs the polygon attribute. wells_plot(**kwargs) Constructs the wells attribute. seismic_line_plot(**kwargS) Constructs the seismic_lines attribute. get_basemap(**kwargs) Constructs the Basemap attribute and provides interactive methods to inspect the plotted data. LIBRARIES --------- Holoviews: BSD open source Python library designed to simplify the visualization of data. More information available at: http://holoviews.org/ Numpy: BSD licensed package for scientific computing with Python. More information available at: https://numpy.org/ Pandas: BSD 3 licensed open source data analysis and manipulation tool, built on top of the Python programming language. More information available at: https://pandas.pydata.org/ Panel: BSD open source Python library that allows to create custom interactive dashboards by connecting user defined widgets to plots. More information available at: https://panel.holoviz.org/index.html ON PROGRESS ----------- Include a GIS element into plots. """ # Holoviews default config plot_tools = ['pan', 'wheel_zoom', 'reset'] font_s = {"title": 16, "labels": 14, "xticks": 10, "yticks": 10} opts.defaults(opts.Curve(tools=plot_tools, default_tools=[], xformatter='%.0f', yformatter='%.0f', fontsize=font_s, height=400, width=400, padding=0.1, toolbar='right'), opts.Scatter(tools=plot_tools, default_tools=[], xformatter='%.0f', yformatter='%.0f', fontsize=font_s, height=400, width=400, padding=0.1, toolbar='right', framewise=True, show_grid=True), opts.GridSpace(fontsize=font_s, shared_yaxis=True, plot_size=(120, 380), toolbar="left"), opts.Overlay(xformatter='%.0f', yformatter='%.0f', fontsize=font_s, toolbar="left", show_grid=True), opts.Points(tools=['box_select', 'lasso_select'], default_tools=[], active_tools=["box_select"], size=3, width=500, height=400, padding=0.01, fontsize={ 'title': 16, 'ylabel': 14, 'xlabel': 14, 'ticks': 10 }, framewise=True, show_grid=True), toolbar="left") def __init__(self, basemap_dataframe, wells_dataframe): """ DESCRIPTION ----------- Instantiates BasemapModule's attributes. For more information, please refer to BasemapModule's docstring. """ self.basemap_dataframe = basemap_dataframe self.wells_dataframe = wells_dataframe self.iline_step = 1 self.xline_step = 1 self.hover_format = [("Utmx", "$x{(0.00)}"), ("Utmy", "$y{(0.00)}")] self.hover_attributes = { "show_arrow": True, "point_policy": "follow_mouse", "anchor": "bottom_right", "attachment": "above", "line_policy": "none" } def polygon_plot(self): """ NAME ---- polygon_plot DESCRIPTION ----------- Constructs the polygon attribute. Plots the boundaries of the seismic survey using Holoviews and bokeh as backend. ARGUMENTS --------- BasemapModule.basemap_dataframe : (Pandas)DataFrame Matrix compounded by the coordinates and lines of the seismic survey's corners. RETURN ------ BasemapModule.polygon : Holviews element [Curve] instance attribute Plot of the seismic survey polygon. """ #Plotting the boundaries of the Seismic Survey. Holoviews Curve element BasemapModule.polygon = hv.Curve(self.basemap_dataframe, ["utmx", "utmy"], label="Polygon") BasemapModule.polygon.opts(line_width=2, color="black") return BasemapModule.polygon def wells_plot(self): """ NAME ---- wells_plot DESCRIPTION ----------- Constructs the wells attribute Plots the wells inside the Seismic Survey's polygon using Holoviews and bokeh as backend. ARGUMENTS --------- BasemapModule.wells_dataframe : (Pandas)DataFrame Matrix compounded by wells related information. RETURN ------ BasemapModule.wells : Holviews element [Scatter] instance attribute Plot of the wells inside the seismic survey. """ # Declaring the Hover tools (each line will use one) wells_hover = HoverTool(tooltips=[("Well", "@name")] + self.hover_format + [("Depth", "@depth{(0)}")]) # Plotting Wells. Holoviews Scatter element BasemapModule.wells = hv.Scatter( self.wells_dataframe, ["utmx", "utmy"], ["name", "cdp_iline", "cdp_xline", "depth"], label="Wells") BasemapModule.wells.opts(line_width=1, color="green", size=10, marker="^") return (BasemapModule.wells) def seismic_line_plot(self, iline_number, xline_number): """ NAME ---- seismic_line_plot DESCRIPTION ----------- Constructs the seismic_lines attribute. Plots seismic lines (given a set of inline and crossline numbers) and the intersection of these using Holoviews and bokeh as backend. ARGUMENTS --------- iline_number : int Number of the chosen inline. The value can be given manually or by Panel's slider widget. xline_number : int Number of the chosen crossline. The value can be given manually or by Panel's slider widget. RETURN ------ BasemapModule.seismic_lines : Holviews element [Overlay] instance attribute Plot of the seismic lines and its intersection. FUNCTIONS --------- seismic_lines_dataframe(**kwargs) Builds a DataFrame for the first line either along inline or crossline direction. seismic_intersection(**kwargs) Computes the coordinates and tracf of the intersection between two seismic lines. REFERENCES ---------- bokeh.pydata.org. Change the attributes of the hover tool. Online document: https://bokeh.pydata.org/en/latest/docs/reference/models/tools.html#bokeh.models.tools.HoverTool.point_policy """ def seismic_lines_dataframe(line_direction, perpendicular_direction): """ NAME ---- seismic_lines_dataframe DESCRIPTION ----------- Builds a DataFrame for the first line either along inline or crossline direction. The coordinates represent the lower end of a seismic line; therefore, these shall be used to draft seismic lines after the computation of the higher end. If the users want to plot a line along inline direction, the code will compute the coordinates of the traces within the first crossline and vice versa. ARGUMENTS --------- basemap_dataframe : (Pandas)DataFrame Matrix compounded by the coordinates and lines of the seismic survey's corners. line_direction : str Seismic line direction. perpendicular_direction : str Direction in which the points are going to be calculated. Is perpendicular to line_direction argument. RETURN ------ dlines : (Pandas)DataFrame Contains the trace coordinates within the first seismic line. """ # Less stresful to read the code df, ld, p_d = self.basemap_dataframe, line_direction, perpendicular_direction #Measure the amount of perpendicular lines within line_direction dif_lines = abs( int(df[f"{perpendicular_direction}"].min() - df[f"{perpendicular_direction}"].max())) + 1 #Computing the coordinates of each utmx = np.linspace( float(df[(df[ld] == df[ld].min()) & (df[p_d] == df[p_d].min())]["utmx"].unique()), float(df[(df[ld] == df[ld].min()) & (df[p_d] == df[p_d].max())]["utmx"].unique()), num=dif_lines, endpoint=True) utmy = np.linspace( float(df[(df[ld] == df[ld].min()) & (df[p_d] == df[p_d].min())]["utmy"].unique()), float(df[(df[ld] == df[ld].min()) & (df[p_d] == df[p_d].max())]["utmy"].unique()), num=dif_lines, endpoint=True) #Array of perpendiculars array = np.arange(df[f"{p_d}"].min(), df[f"{p_d}"].max() + 1, 1) # Making dataframes to ease further calculations dlines = pd.DataFrame({ ld: df[f"{ld}"].min(), p_d: array, "utmx": utmx, "utmy": utmy }) return (dlines) def seismic_intersection(iline_df, xline_df, iline_number, xline_number): """ NAME ---- seismic_intersection DESCRIPTION ----------- Computes the coordinates and tracf of the intersection between two seismic lines. The computation of the intersection uses vector differences. ARGUMENTS --------- iline_df : (Pandas)DataFrame Coordinates of the traces within the first crossline. xline_df : (Pandas)DataFrame Coordinates of the traces within the first inline. iline_number : int Number of the chosen inline. xline_number : int Number of the chosen crossline. RETURN ------ list List of tracf and coordinates of the intersection. """ # Amount of CDP within crosslines dif_lines = abs(self.basemap_dataframe["xline"].max() - self.basemap_dataframe["xline"].min()) + 1 # tracf tracf = (iline_number - self.basemap_dataframe["iline"].min()) * dif_lines + ( xline_number - self.basemap_dataframe["xline"].min()) + 1 # vector diferences. Formula utm = b - a + c tutmx = float( xline_df[xline_df["xline"] == xline_number] ["utmx"]) - xline_df["utmx"].iloc[0] + float( iline_df[iline_df["iline"] == iline_number]["utmx"]) tutmy = float( xline_df[xline_df["xline"] == xline_number] ["utmy"]) - xline_df["utmy"].iloc[0] + float( iline_df[iline_df["iline"] == iline_number]["utmy"]) return [int(tracf), tutmx, tutmy] df = self.basemap_dataframe # Assigning a variable for each dataframe in seismic_lines_dataframe ilines, xlines = seismic_lines_dataframe( df.keys()[1], df.keys()[0]), seismic_lines_dataframe(df.keys()[0], df.keys()[1]) # Extracting the intersection coordinates intersection = seismic_intersection(ilines, xlines, iline_number, xline_number) # Computing the second point to plot the seismic lines (By using vector differences) ## This can be refactored iutmx = float(xlines["utmx"].iloc[-1] - xlines["utmx"].iloc[0] + ilines[ilines["iline"] == iline_number]["utmx"]) iutmy = float(xlines["utmy"].iloc[-1] - xlines["utmy"].iloc[0] + ilines[ilines["iline"] == iline_number]["utmy"]) xutmx = float(ilines["utmx"].iloc[-1] - ilines["utmx"].iloc[0] + xlines[xlines["xline"] == xline_number]["utmx"]) xutmy = float(ilines["utmy"].iloc[-1] - ilines["utmy"].iloc[0] + xlines[xlines["xline"] == xline_number]["utmy"]) # hovers for lines and interception iline_hover = HoverTool(tooltips=[("Inline", f"{iline_number}")] + self.hover_format) xline_hover = HoverTool(tooltips=[("Crossline", f"{xline_number}")] + self.hover_format) int_hover = HoverTool( tooltips=[("Intersection", f"({iline_number}/{xline_number})")] + self.hover_format) #Updating hover attributes for item in [iline_hover, xline_hover, int_hover]: item._property_values.update(self.hover_attributes) # Plotting the Inline. Holoviews Curve element iline = hv.Curve( [(float(ilines[ilines["iline"] == iline_number]["utmx"]), float(ilines[ilines["iline"] == iline_number]["utmy"])), (iutmx, iutmy)], label="I-Line") # Plotting the Crossline. Holoviews Curve element xline = hv.Curve( [(float(xlines[xlines["xline"] == xline_number]["utmx"]), float(xlines[xlines["xline"] == xline_number]["utmy"])), (xutmx, xutmy)], label="C-Line") # Plot the intersection. Holovies Scatter element. intersection = hv.Scatter((intersection[1], intersection[2]), label="Intersection") # Adding the hover tool in to the plots iline.opts(line_width=2, color="red", tools=self.plot_tools + [iline_hover]) xline.opts(line_width=2, color="blue", tools=self.plot_tools + [xline_hover]) intersection.opts(size=7, line_color="black", line_width=2, color="yellow", tools=self.plot_tools + [int_hover]) # Making the overlay of the seismic plot to deploy BasemapModule.seismic_lines = iline * xline * intersection return BasemapModule.seismic_lines def get_basemap(self): """ NAME ---- get_basemap DESCRIPTION ----------- Constructs the basemap attribute and provides interactive methods to inspect the plotted data. Merges polygon, wells and seismic_lines attributes into one object using Holoviews and bokeh as backend. It also includes Panel's widgets and methods to add elements that ease data management. ARGUMENTS --------- BasemapModule.basemap_dataframe : (Pandas)DataFrame Matrix compounded by the coordinates and lines of the seismic survey's corners. Survey.survey_name : str Name of the seismic survey. RETURN ------ Panel Layout [Row] Container of the following indexed elements: [0] WidgetBox [0] Markdown for Survey.survey_name [1] IntSlider for inline number selection [2] IntSlider for crossline number selection [3] Select for well selection [1] basemap attribute FUNCTIONS --------- basemap_plot(**kwargs) Constructs the basemap attribute. update_plot(**kwargs) Links Panel's selection widgets to the basemap attribute. """ df = self.basemap_dataframe # Widgets iline_number = pn.widgets.IntSlider(name="Inline number", start=int(df["iline"].min()), end=int(df["iline"].max()), step=self.iline_step, value=int(df["iline"].min())) xline_number = pn.widgets.IntSlider(name="Crossline number", start=int(df["xline"].min()), end=int(df["xline"].max()), step=self.xline_step, value=int(df["xline"].min())) select_well = pn.widgets.Select(name="Select the well to inspect", options=["None"] + list(self.wells_dataframe["name"]), value="None") @pn.depends(iline_number.param.value, xline_number.param.value, select_well.param.value) def basemap_plot(iline_number, xline_number, select_well): """ NAME ---- basemap_plot DESCRIPTION ----------- Constructs the basemap attribute. Merges seismic survey related plots using Holoviews and bokeh as backend. ARGUMENTS --------- Arguments are given by Panel's widgets through the panel's depend decorator: iline_number : int Number of the chosen inline. xline_number : int Number of the chosen crossline. select_well : str Automatically gives well's line numbers when selected. RETURN ------ basemap : Holviews element [Overlay] instance attribute Combination of the plots: polygon, wells and seismic_lines. """ #new attributes WiggleModule.inline_number = iline_number WiggleModule.crossline_number = xline_number # First element BasemapModule.polygon = BasemapModule.polygon_plot(self) # Second element BasemapModule.wells = BasemapModule.wells_plot(self) # Third element BasemapModule.seismic_lines = BasemapModule.seismic_line_plot( self, iline_number, xline_number) # Final Overlay BasemapModule.basemap = BasemapModule.polygon * BasemapModule.wells * BasemapModule.seismic_lines BasemapModule.basemap.opts(legend_position='top', height=600, width=600) return (BasemapModule.basemap) widgets = pn.WidgetBox(f"## {Survey.survey} Basemap", iline_number, xline_number, select_well) def update_plot(event): """ NAME ---- update_plot DESCRIPTION ----------- Links Panel's selection widgets to the basemap attribute. Modifies the target plot when a well is selected through Panel's selector widget. ARGUMENTS --------- event : str Panel's selector widget value. RETURN ------ basemap : Holviews element [Overlay] instance attribute Combination of the plots: polygon, wells and seismic_lines. """ if select_well.value != "None": iline_number.value = int( self.wells_dataframe["cdp_iline"].loc[str( select_well.value)]) xline_number.value = int( self.wells_dataframe["cdp_xline"].loc[str( select_well.value)]) WiggleModule.inline_number = iline_number.value WiggleModule.crossline_number = xline_number.value select_well.param.watch(update_plot, 'value') return pn.Row(widgets, basemap_plot).servable()
def plot_scatter(df, x, y, x_round_val=1, y_round_val=1, x_tooltip='', y_tooltip=''): ''' Returns a HoloViews plot layout. Arguments: df - Dataframe to process, must have the column 'Country' adn the columns x and y within. x - Column in Dataframe where values are evaluated for the x-axis y - Column in Dataframe where values are evaluated for the y-axis x_round_val (optional) - single numeric value to set the x axis limits on max found within x y_round_val (optional) - single numeric value to set the y axis limits on max found within y x_tooltip (optional) - tooltip to be set in the plots for the x values y_tooltip (optional) - tooltip to be set in the plots for the y values ''' max_y = np.ceil(np.nanmax(df[y].values)) max_y = max_y - max_y % y_round_val + 2 * y_round_val max_x = np.ceil(np.nanmax(df[x].values)) max_x = max_x - max_x % x_round_val + 2 * x_round_val ''' if max_x > max_y: max_y = max_x else: max_x=max_y ''' if x_tooltip == '': x_tooltip = '@{' + x + '}{0,0.0}' if y_tooltip == '': y_tooltip = '@{' + y + '}{0,0.0}' # Plot settings and parameters hover = HoverTool(tooltips=[('Country', '@Country'), (x, x_tooltip), (y, y_tooltip)]) padding = dict(x=(-1.2, 1.2), y=(-1.2, 1.2)) options_shared = dict(width=700, height=700, xlim=(0, max_x), ylim=(0, max_y), hooks=[axis_not_scientific], active_tools=['wheel_zoom'], padding=(0.1, 0.1), show_grid=True, show_legend=True, legend_position='bottom', legend_cols=3) options = [ opts.Scatter(marker='o', size=10, fill_alpha=0.6, tools=[hover], color=hv.Palette('Set2'), **options_shared), opts.Points(color='Country', cmap=cc.cm.fire, size=8, tools=[hover], **options_shared), opts.Labels(text_font_size='8pt', yoffset=y_round_val / 5), opts.Overlay(**options_shared) ] ds = hv.Table(df) # Create the plot layout = ( #hv.Scatter(df, kdims=[x], vdims=[y, 'Country'])* ds.to(hv.Scatter, x, y, 'Country').overlay() * hv.Labels(ds, kdims=[x, y], vdims=['Country'])).opts(options) return layout
frame_width=600, invert_yaxis=True, xaxis='bare', yaxis='bare', bgcolor='black', active_tools=['pan', 'wheel_zoom'], show_title=False), opts.HLine('orthoview', line_dash='dashed', line_width=1, line_color='white'), opts.VLine('orthoview', line_dash='dashed', line_width=1, line_color='white'), opts.Overlay('orthoview', shared_axes=False, show_title=False), opts.Overlay('segmentation', show_title=False), opts.Image('segmentation', frame_width=600, invert_yaxis=True, xaxis='bare', yaxis='bare', bgcolor='black', active_tools=['pan', 'wheel_zoom'], show_title=False), ) class BaseViewer(param.Parameterized): return_panel = param.Boolean( False,
clr_pls = 'lightseagreen' clr_inSample = 'steelblue' clr_5cv = 'tomato' clr_20x5cv = 'gold' clr_5cvMean = 'maroon' clr_20x5cvMean = 'darkgoldenrod' default_fontsizes = dict(title=8, labels=8, ticks=7, minor_ticks=7, legend=7) fig_opts = [ opts.Layout(aspect_weight=1, fig_inches=(3.42, None), sublabel_size=10, fontsize=8), opts.Overlay(fontsize=default_fontsizes, ), opts.Area(fontsize=default_fontsizes), opts.Arrow(textsize=default_fontsizes), opts.Curve(fontsize=default_fontsizes), opts.HexTiles(fontsize=default_fontsizes), opts.Histogram(fontsize=default_fontsizes), opts.Raster(fontsize=default_fontsizes), opts.Scatter(fontsize=default_fontsizes), opts.Text(fontsize=default_fontsizes), opts.QuadMesh(fontsize=default_fontsizes), opts.Violin(fontsize=default_fontsizes), opts.VLine(fontsize=default_fontsizes), ] # hv hooks
nx, ny, nz = mat.shape rock = hv.Dataset((np.arange(nx), np.arange(ny), np.arange(nz), mat), ["x", "y", "z"], ["value"]) rock = rock.clone(datatype=['xarray']) rock.data from holoviews import opts opts.defaults( opts.GridSpace(shared_xaxis=True, shared_yaxis=True), opts.Image(cmap='Gray', width=400, height=400), opts.Labels(text_color='white', text_font_size='8pt', text_align='left', text_baseline='bottom'), opts.Path(color='white'), opts.Spread(width=600), opts.Overlay(show_legend=False)) # Data has three dimensions. We can easily visualise two using an image, and use a slider to change the third dimension. rock.to(hv.Image, ['x', 'y'], datatype=["xarray"], dynamic=True).hist() # To make it more interesting we can create three plots and each having one of the dimensions on the slider. # # Here's we use the [Turbo](https://ai.googleblog.com/2019/08/turbo-improved-rainbow-colormap-for.html) colormap which is often better than viridis or plasma for highlighting differences import bokeh.palettes as pal # %%opts Image {+axiswise} [xaxis=None yaxis=None width=200 height=200] cmap = pal.Turbo256 hmx = rock.to(hv.Image, ['z', 'y'], dynamic=True).opts(cmap=cmap) hmy = rock.to(hv.Image, ['z', 'x'], dynamic=True).opts(cmap=cmap)
# %% st, sc, sy, sx = xp.shape # %% ds = hv.Dataset((np.arange(sy), np.arange(sx), np.arange(st), xp[:,1,:,:]), ['x','y', 'Frame'], 'movie') # %% #ds.clone(datatype=['xarray']).data # %% opts.defaults( opts.GridSpace(shared_xaxis=True, shared_yaxis=True), opts.Image(cmap='viridis', width=400, height=400), opts.Labels(text_color='white', text_font_size='8pt', text_align='left', text_baseline='bottom'), opts.Path(color='white'), opts.Spread(width=600), opts.Overlay(show_legend=False)) # %% ds.to(hv.Image, ['x', 'y']).hist() # %% #np.save('xp.npy', xp) # %%