def notebook_extension(*, _inline_js=True):
    """Enable ipywidgets, holoviews, and asyncio notebook integration."""
    if not in_ipynb():
        raise RuntimeError('"adaptive.notebook_extension()" may only be run '
                           'from a Jupyter notebook.')

    global _async_enabled, _holoviews_enabled, _ipywidgets_enabled

    # Load holoviews
    try:
        _holoviews_enabled = False  # After closing a notebook the js is gone
        if not _holoviews_enabled:
            import holoviews
            holoviews.notebook_extension('bokeh',
                                         logo=False,
                                         inline=_inline_js)
            _holoviews_enabled = True
    except ModuleNotFoundError:
        warnings.warn("holoviews is not installed; plotting "
                      "is disabled.", RuntimeWarning)

    # Load ipywidgets
    try:
        if not _ipywidgets_enabled:
            import ipywidgets
            _ipywidgets_enabled = True
    except ModuleNotFoundError:
        warnings.warn("ipywidgets is not installed; live_info "
                      "is disabled.", RuntimeWarning)

    # Enable asyncio integration
    if not _async_enabled:
        get_ipython().magic('gui asyncio')
        _async_enabled = True
Beispiel #2
0
def init_notebook(mpl=True):
    # Enable inline plotting in the notebook
    if mpl:
        try:
            get_ipython().enable_matplotlib(gui='inline')
        except NameError:
            pass

    print('Populated the namespace with:\n' +
        ', '.join(init_mooc_nb) +
        '\nfrom code/edx_components:\n' +
        ', '.join(edx_components.__all__) +
        '\nfrom code/functions:\n' +
        ', '.join(functions.__all__))

    holoviews.notebook_extension('matplotlib')

    Store.renderers['matplotlib'].fig = 'svg'

    holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.usetex'] = True
    
    latex_packs = [r'\usepackage{amsmath}',
                   r'\usepackage{amssymb}'
                   r'\usepackage{bm}']

    holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.latex.preamble'] = latex_packs

    # Set plot style.
    options = Store.options(backend='matplotlib')
    options.Contours = Options('style', linewidth=2, color='k')
    options.Contours = Options('plot', aspect='square')
    options.HLine = Options('style', linestyle='--', color='b', linewidth=2)
    options.VLine = Options('style', linestyle='--', color='r', linewidth=2)
    options.Image = Options('style', cmap='RdBu_r')
    options.Image = Options('plot', title_format='{label}')
    options.Path = Options('style', linewidth=1.2, color='k')
    options.Path = Options('plot', aspect='square', title_format='{label}')
    options.Curve = Options('style', linewidth=2, color='k')
    options.Curve = Options('plot', aspect='square', title_format='{label}')
    options.Overlay = Options('plot', show_legend=False, title_format='{label}')
    options.Layout = Options('plot', title_format='{label}')
    options.Surface = Options('style', cmap='RdBu_r', rstride=1, cstride=1, lw=0.2)
    options.Surface = Options('plot', azimuth=20, elevation=8)

    # Turn off a bogus holoviews warning.
    # Temporary solution to ignore the warnings
    warnings.filterwarnings('ignore', r'All-NaN (slice|axis) encountered')

    module_dir = os.path.dirname(__file__)
    matplotlib.rc_file(os.path.join(module_dir, "matplotlibrc"))

    np.set_printoptions(precision=2, suppress=True,
                        formatter={'complexfloat': pretty_fmt_complex})

    # Patch a bug in holoviews
    if holoviews.__version__.release <= (1, 4, 3):
        from patch_holoviews import patch_all
        patch_all()
Beispiel #3
0
    def setUp(self):
        notebook_extension(*BACKENDS)
        Store.current_backend = 'matplotlib'
        Store.renderers['matplotlib'] = mpl.MPLRenderer.instance()
        if bokeh:
            Store.renderers['bokeh'] = bokeh.BokehRenderer.instance()
        OutputSettings.options = OrderedDict(OutputSettings.defaults.items())

        super(TestOutputUtil, self).setUp()
Beispiel #4
0
    def setUp(self):
        notebook_extension(*BACKENDS)
        Store.current_backend = 'matplotlib'
        Store.renderers['matplotlib'] = mpl.MPLRenderer.instance()
        if bokeh:
            Store.renderers['bokeh'] = bokeh.BokehRenderer.instance()
        OutputSettings.options =  OrderedDict(OutputSettings.defaults.items())

        super(TestOutputUtil, self).setUp()
def init_notebook():
    # Enable inline plotting in the notebook
    try:
        get_ipython().enable_matplotlib(gui='inline')
    except NameError:
        pass

    print('Populated the namespace with:\n' + ', '.join(__all__))
    holoviews.notebook_extension('matplotlib')
    holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.usetex'] = True

    # Set plot style.
    options = Store.options(backend='matplotlib')
    options.Contours = Options('style', linewidth=2, color='k')
    options.Contours = Options('plot', aspect='square')
    options.HLine = Options('style', linestyle='--', color='b', linewidth=2)
    options.VLine = Options('style', linestyle='--', color='r', linewidth=2)
    options.Image = Options('style', cmap='RdBu_r')
    options.Image = Options('plot', title_format='{label}')
    options.Path = Options('style', linewidth=1.2, color='k')
    options.Path = Options('plot', aspect='square', title_format='{label}')
    options.Curve = Options('style', linewidth=2, color='k')
    options.Curve = Options('plot', aspect='square', title_format='{label}')
    options.Overlay = Options('plot', show_legend=False, title_format='{label}')
    options.Layout = Options('plot', title_format='{label}')
    options.Surface = Options('style', cmap='RdBu_r', rstride=1, cstride=1, lw=0.2)
    options.Surface = Options('plot', azimuth=20, elevation=8)

    # Turn off a bogus holoviews warning.
    # Temporary solution to ignore the warnings
    warnings.filterwarnings('ignore', r'All-NaN (slice|axis) encountered')

    module_dir = os.path.dirname(__file__)
    matplotlib.rc_file(os.path.join(module_dir, "matplotlibrc"))

    np.set_printoptions(precision=2, suppress=True,
                        formatter={'complexfloat': pretty_fmt_complex})

    # In order to make the notebooks readable through nbviewer we want to hide
    # the code by default. However the same code is executed by the students,
    # and in that case we don't want to hide the code. So we check if the code
    # is executed by one of the mooc developers. Here we do by simply checking
    # for some files that belong to the internal mooc repository, but are not
    # published.  This is a temporary solution, and should be improved in the
    # long run.

    developer = os.path.exists(os.path.join(module_dir, os.path.pardir,
                                            'scripts'))

    display_html(display.HTML(nb_html_header +
                              (hide_outside_ipython if developer else '')))

    # Patch a bug in holoviews
    from patch_holoviews import patch_all
    patch_all()
Beispiel #6
0
def init_notebook():
    print_information()
    check_versions()

    code_dir = os.path.dirname(os.path.realpath(__file__))
    hv_css = os.path.join(code_dir, 'hv_widgets_settings.css')
    holoviews.plotting.widgets.SelectionWidget.css = hv_css

    holoviews.notebook_extension('matplotlib')

    # Enable inline plotting in the notebook
    get_ipython().enable_matplotlib(gui='inline')

    Store.renderers['matplotlib'].fig = 'svg'
    Store.renderers['matplotlib'].dpi = 100

    holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.usetex'] = True

    latex_packs = [r'\usepackage{amsmath}',
                   r'\usepackage{amssymb}'
                   r'\usepackage{bm}']

    holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.latex.preamble'] = \
        latex_packs

    # Set plot style.
    options = Store.options(backend='matplotlib')
    options.Contours = Options('style', linewidth=2, color='k')
    options.Contours = Options('plot', aspect='square')
    options.HLine = Options('style', linestyle='--', color='b', linewidth=2)
    options.VLine = Options('style', linestyle='--', color='r', linewidth=2)
    options.Image = Options('style', cmap='RdBu_r')
    options.Image = Options('plot', title_format='{label}')
    options.Path = Options('style', linewidth=1.2, color='k')
    options.Path = Options('plot', aspect='square', title_format='{label}')
    options.Curve = Options('style', linewidth=2, color='k')
    options.Curve = Options('plot', aspect='square', title_format='{label}')
    options.Overlay = Options('plot', show_legend=False, title_format='{label}')
    options.Layout = Options('plot', title_format='{label}')
    options.Surface = Options('style', cmap='RdBu_r', rstride=2, cstride=2,
                              lw=0.2, edgecolors='k')
    options.Surface = Options('plot', azimuth=20, elevation=8)

    # Set slider label formatting
    for dimension_type in [float, np.float64, np.float32]:
        holoviews.Dimension.type_formatters[dimension_type] = pretty_fmt_complex

    matplotlib.rc_file(os.path.join(code_dir, "matplotlibrc"))

    np.set_printoptions(precision=2, suppress=True,
                        formatter={'complexfloat': pretty_fmt_complex})
Beispiel #7
0
def init_notebook():
    print_information()
    check_versions()

    code_dir = os.path.dirname(os.path.realpath(__file__))
    hv_css = os.path.join(code_dir, 'hv_widgets_settings.css')
    holoviews.plotting.widgets.SelectionWidget.css = hv_css

    holoviews.notebook_extension('matplotlib')

    # Enable inline plotting in the notebook
    get_ipython().enable_matplotlib(gui='inline')

    Store.renderers['matplotlib'].fig = 'svg'
    Store.renderers['matplotlib'].dpi = 100

    holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.usetex'] = True

    latex_packs = [r'\usepackage{amsmath}',
                   r'\usepackage{amssymb}'
                   r'\usepackage{bm}']

    holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.latex.preamble'] = \
        latex_packs

    # Set plot style.
    options = Store.options(backend='matplotlib')
    options.Contours = Options('style', linewidth=2, color='k')
    options.Contours = Options('plot', aspect='square')
    options.HLine = Options('style', linestyle='--', color='b', linewidth=2)
    options.VLine = Options('style', linestyle='--', color='r', linewidth=2)
    options.Image = Options('style', cmap='RdBu_r')
    options.Image = Options('plot', title_format='{label}')
    options.Path = Options('style', linewidth=1.2, color='k')
    options.Path = Options('plot', aspect='square', title_format='{label}')
    options.Curve = Options('style', linewidth=2, color='k')
    options.Curve = Options('plot', aspect='square', title_format='{label}')
    options.Overlay = Options('plot', show_legend=False, title_format='{label}')
    options.Layout = Options('plot', title_format='{label}')
    options.Surface = Options('style', cmap='RdBu_r', rstride=2, cstride=2,
                              lw=0.2, edgecolors='k')
    options.Surface = Options('plot', azimuth=20, elevation=8)

    # Set slider label formatting
    for dimension_type in [float, np.float64, np.float32]:
        holoviews.Dimension.type_formatters[dimension_type] = pretty_fmt_complex

    matplotlib.rc_file(os.path.join(code_dir, "matplotlibrc"))

    np.set_printoptions(precision=2, suppress=True,
                        formatter={'complexfloat': pretty_fmt_complex})
Beispiel #8
0
def manage_display_import():
    global MPLRenderer
    import matplotlib as mpl
    if os.environ.get('DISPLAY', '') == '':
        log.info('no display found. Using non-interactive Agg backend')
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            mpl.use('Agg')

    from holoviews.plotting.mpl import MPLRenderer  # noqa

    if is_interactive():
        from holoviews import notebook_extension
        notebook_extension("bokeh")
Beispiel #9
0
def notebook_extension():
    get_ipython().magic('gui asyncio')
    try:
        import holoviews as hv
        return hv.notebook_extension('bokeh')
    except ModuleNotFoundError:
        warnings.warn(
            "The holoviews package is not installed so plotting"
            "will not work.", RuntimeWarning)
Beispiel #10
0
def notebook_extension():
    if not in_ipynb():
        raise RuntimeError('"adaptive.notebook_extension()" may only be run '
                           'from a Jupyter notebook.')

    global _plotting_enabled
    _plotting_enabled = False
    try:
        import ipywidgets
        import holoviews
        holoviews.notebook_extension('bokeh')
        _plotting_enabled = True
    except ModuleNotFoundError:
        warnings.warn("holoviews and (or) ipywidgets are not installed; plotting "
                      "is disabled.", RuntimeWarning)

    global _async_enabled
    get_ipython().magic('gui asyncio')
    _async_enabled = True
Beispiel #11
0
def interactive_crop(
    video_path,
    frame=0,
):
    """
    Loads and displays a frame for a video to be used for cropping.

    Cropping automatically updated using holoviews stream object.

    Args:
        video_path (str): Path to the video
        frame (int): The index of the frame to be used for cropping
    Returns:
        image, stream
    """

    hv.notebook_extension("bokeh")
    cap = cv2.VideoCapture(video_path)
    cap.set(cv2.CAP_PROP_POS_FRAMES, frame)
    _, frame = cap.read()
    print(frame.shape)
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # frame = frame[::-1, :]  # inverse y axis for plotting
    cap.release()

    image = hv.Image(
        (np.arange(frame.shape[1]), np.arange(frame.shape[0]), frame))
    image.opts(
        width=frame.shape[1],
        height=frame.shape[0],
        cmap="gray",
        colorbar=True,
        toolbar="below",
        title="First Frame.  Crop if Desired",
    )
    box = hv.Polygons([])
    box.opts(alpha=0.5)
    box_stream = streams.BoxEdit(source=box, num_objects=1)
    return (image * box), box_stream
Beispiel #12
0
import os
import sys

sys.path.insert(0, os.path.abspath('..'))  # to get adaptive on the path

import adaptive
import holoviews
import matplotlib.pyplot as plt
import matplotlib.tri as mtri
from PIL import Image, ImageDraw
holoviews.notebook_extension('matplotlib')


def create_and_run_learner():
    def ring(xy):
        import numpy as np
        x, y = xy
        a = 0.2
        return x + np.exp(-(x**2 + y**2 - 0.75**2)**2/a**4)

    learner = adaptive.Learner2D(ring, bounds=[(-1, 1), (-1, 1)])
    adaptive.runner.simple(learner, goal=lambda l: l.loss() < 0.01)
    return learner


def plot_learner_and_save(learner, fname):
    fig, ax = plt.subplots()
    tri = learner.ip().tri
    triang = mtri.Triangulation(*tri.points.T, triangles=tri.vertices)
    ax.triplot(triang, c='k', lw=0.8)
    ax.imshow(learner.plot().Image.I.data, extent=(-0.5, 0.5, -0.5, 0.5))
Beispiel #13
0
import collections
import threading
from concurrent.futures import ThreadPoolExecutor
import warnings
import glob
import os

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt  # noqa: F401
import matplotlib.cbook
import holoviews as hv
from holoviews import opts

hv.extension("bokeh")
hv.notebook_extension(width=90)  # For showing wide plots

# Get rid of matplotlib deprecation warnings.
warnings.filterwarnings("ignore", category=matplotlib.cbook.mplDeprecation)


# +
def load_config(path: str) -> typing.Dict:
    """Loads run metadata."""
    with open(f"{path}/meta.json", "r") as f:
        try:
            config = json.load(f)
            return config
        except Exception as e:  # noqa: F841
            print(f"Error parsing {path}")
Beispiel #14
0
# coding: utf-8

# # System of 2 particles

# In[2]:

import numpy as np
import scipy.linalg as la
import matplotlib.pyplot as plt
import holoviews as hv

hv.notebook_extension('matplotlib')
get_ipython().magic('matplotlib inline')

# In[3]:

m = 1  #particle mass
n = 2  #number of particles
h = .01  #time step
L = 100  #box size
eps = 1
sigma = 0.01

# In[73]:

pos0 = np.random.rand(n, 2)  # one particle each row: [x y ]
print(pos0)

vel0 = np.array([[1, 1], [-2, -1]])  #one particle each row: [px py]
mom0 = m * vel0
print(mom0, vel0)
Beispiel #15
0
def init_notebook(mpl=True):
    # Enable inline plotting in the notebook
    if mpl:
        try:
            get_ipython().enable_matplotlib(gui='inline')
        except NameError:
            pass

    print('Populated the namespace with:\n' + ', '.join(init_mooc_nb) +
          '\nfrom code/edx_components:\n' + ', '.join(edx_components.__all__) +
          '\nfrom code/functions:\n' + ', '.join(functions.__all__))

    holoviews.notebook_extension('matplotlib')

    Store.renderers['matplotlib'].fig = 'svg'

    holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.usetex'] = True

    latex_packs = [
        r'\usepackage{amsmath}', r'\usepackage{amssymb}'
        r'\usepackage{bm}'
    ]

    holoviews.plotting.mpl.MPLPlot.fig_rcparams[
        'text.latex.preamble'] = latex_packs

    # Set plot style.
    options = Store.options(backend='matplotlib')
    options.Contours = Options('style', linewidth=2, color='k')
    options.Contours = Options('plot', aspect='square')
    options.HLine = Options('style', linestyle='--', color='b', linewidth=2)
    options.VLine = Options('style', linestyle='--', color='r', linewidth=2)
    options.Image = Options('style', cmap='RdBu_r')
    options.Image = Options('plot', title_format='{label}')
    options.Path = Options('style', linewidth=1.2, color='k')
    options.Path = Options('plot', aspect='square', title_format='{label}')
    options.Curve = Options('style', linewidth=2, color='k')
    options.Curve = Options('plot', aspect='square', title_format='{label}')
    options.Overlay = Options('plot',
                              show_legend=False,
                              title_format='{label}')
    options.Layout = Options('plot', title_format='{label}')
    options.Surface = Options('style',
                              cmap='RdBu_r',
                              rstride=1,
                              cstride=1,
                              lw=0.2)
    options.Surface = Options('plot', azimuth=20, elevation=8)

    # Turn off a bogus holoviews warning.
    # Temporary solution to ignore the warnings
    warnings.filterwarnings('ignore', r'All-NaN (slice|axis) encountered')

    module_dir = os.path.dirname(__file__)
    matplotlib.rc_file(os.path.join(module_dir, "matplotlibrc"))

    np.set_printoptions(precision=2,
                        suppress=True,
                        formatter={'complexfloat': pretty_fmt_complex})

    # Patch a bug in holoviews
    if holoviews.__version__.release <= (1, 4, 3):
        from patch_holoviews import patch_all
        patch_all()
Beispiel #16
0
from holoviews import notebook_extension
from holoviews.element.comparison import ComparisonTestCase
from holoviews import Store
from holoviews.util import output, opts, OutputSettings
from holoviews.core import OrderedDict

from holoviews.core.options import OptionTree

from holoviews.plotting import mpl
try:
    from holoviews.plotting import bokeh
except:
    bokeh = None

BACKENDS = ['matplotlib'] + (['bokeh'] if bokeh else [])
notebook_extension(*BACKENDS)


class TestOutputUtil(ComparisonTestCase):

    def setUp(self):
        Store.current_backend = 'matplotlib'
        Store.renderers['matplotlib'] = mpl.MPLRenderer.instance()
        if bokeh:
            Store.renderers['bokeh'] = bokeh.BokehRenderer.instance()
        OutputSettings.options =  OrderedDict(OutputSettings.defaults.items())

        super(TestOutputUtil, self).setUp()

    def tearDown(self):
        Store.renderers['matplotlib'] = mpl.MPLRenderer.instance()
Beispiel #17
0
def init_notebook():
    print_information()
    check_versions()

    holoviews.notebook_extension("matplotlib")
    holoviews.output(widget_location='bottom')

    # Enable inline plotting in the notebook
    get_ipython().enable_matplotlib(gui="inline")

    Store.renderers["matplotlib"].fig = "svg"
    Store.renderers["matplotlib"].dpi = 100

    holoviews.plotting.mpl.MPLPlot.fig_rcparams["text.usetex"] = False

    latex_packs = [
        r"\usepackage{amsmath}", r"\usepackage{amssymb}"
        r"\usepackage{bm}"
    ]

    holoviews.plotting.mpl.MPLPlot.fig_rcparams[
        "text.latex.preamble"] = latex_packs

    # Set plot style.
    options = Store.options(backend="matplotlib")
    options.Contours = Options("style", linewidth=2, color="k")
    options.Contours = Options("plot", padding=0, aspect="square")
    options.HLine = Options("style", linestyle="--", color="b", linewidth=2)
    options.VLine = Options("style", linestyle="--", color="r", linewidth=2)
    options.Image = Options("style", cmap="RdBu_r")
    options.Image = Options("plot", padding=0, title="{label}")
    options.Path = Options("style", linewidth=1.2, color="black")
    options.Path = Options("plot", padding=0, aspect="square", title="{label}")
    options.Curve = Options("style", linewidth=2, color="black")
    options.Curve = Options("plot",
                            padding=0,
                            aspect="square",
                            title="{label}")
    options.Overlay = Options("plot",
                              padding=0,
                              show_legend=False,
                              title="{label}")
    options.Layout = Options("plot", title="{label}")
    options.Surface = Options("style",
                              cmap="RdBu_r",
                              rstride=2,
                              cstride=2,
                              lw=0.2,
                              edgecolor="black")
    options.Surface = Options("plot", azimuth=20, elevation=8)

    # Set slider label formatting
    for dimension_type in [float, np.float64, np.float32]:
        holoviews.Dimension.type_formatters[
            dimension_type] = lambda x: pretty_fmt_complex(x, 4)

    code_dir = os.path.dirname(os.path.realpath(__file__))
    matplotlib.rc_file(os.path.join(code_dir, "matplotlibrc"))

    np.set_printoptions(precision=2,
                        suppress=True,
                        formatter={"complexfloat": pretty_fmt_complex})

    # Silence Kwant warnings from color scale overflow
    warnings.filterwarnings("ignore",
                            category=RuntimeWarning,
                            message="The plotted data contains")
Beispiel #18
0
import os

import subprocess

from parfile import *

# display
# (M2,P)
# (3,4) | (3,8) | (3,12)
# (2,4) | (2,8) | (2,12)
# (1,4) | (1,8) | (1,12)
# => M2[i//3] and P[i%3]
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

hv.notebook_extension("matplotlib")

# x = np.arange(0, np.pi, 0.1)
# y = np.arange(0, 2*np.pi, 0.1)
# X, Y = np.meshgrid(x, y)
# Z = np.cos(X) * np.sin(Y) * 10
# colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 1)]  # R -> G -> B
# n_bins = [4, 6, 10, 100]  # Discretizes the interpolation into bins
# cmap_name = 'my_list'
# # fig, ax = plt.subplots(1, 1, figsize=(6, 6))
# vmax=25
# cm = LinearSegmentedColormap.from_list(cmap_name, [(0,    'blue'),
#                                               (0.2/vmax, 'red'),
#                                               (0.6/vmax, 'green'),
# 											  (2./vmax, 'black'),
# 											  (6./vmax, 'yellow'),
Beispiel #19
0
def init_notebook():
    # Enable inline plotting in the notebook
    try:
        get_ipython().enable_matplotlib(gui='inline')
    except NameError:
        pass

    print('Populated the namespace with:\n' + ', '.join(init_mooc_nb) +
          '\nfrom code/edx_components:\n' + ', '.join(edx_components.__all__) +
          '\nfrom code/functions:\n' + ', '.join(functions.__all__))

    holoviews.notebook_extension('matplotlib')
    holoviews.plotting.mpl.MPLPlot.fig_rcparams['text.usetex'] = True

    # Set plot style.
    options = Store.options(backend='matplotlib')
    options.Contours = Options('style', linewidth=2, color='k')
    options.Contours = Options('plot', aspect='square')
    options.HLine = Options('style', linestyle='--', color='b', linewidth=2)
    options.VLine = Options('style', linestyle='--', color='r', linewidth=2)
    options.Image = Options('style', cmap='RdBu_r')
    options.Image = Options('plot', title_format='{label}')
    options.Path = Options('style', linewidth=1.2, color='k')
    options.Path = Options('plot', aspect='square', title_format='{label}')
    options.Curve = Options('style', linewidth=2, color='k')
    options.Curve = Options('plot', aspect='square', title_format='{label}')
    options.Overlay = Options('plot',
                              show_legend=False,
                              title_format='{label}')
    options.Layout = Options('plot', title_format='{label}')
    options.Surface = Options('style',
                              cmap='RdBu_r',
                              rstride=1,
                              cstride=1,
                              lw=0.2)
    options.Surface = Options('plot', azimuth=20, elevation=8)

    # Turn off a bogus holoviews warning.
    # Temporary solution to ignore the warnings
    warnings.filterwarnings('ignore', r'All-NaN (slice|axis) encountered')

    module_dir = os.path.dirname(__file__)
    matplotlib.rc_file(os.path.join(module_dir, "matplotlibrc"))

    np.set_printoptions(precision=2,
                        suppress=True,
                        formatter={'complexfloat': pretty_fmt_complex})

    # In order to make the notebooks readable through nbviewer we want to hide
    # the code by default. However the same code is executed by the students,
    # and in that case we don't want to hide the code. So we check if the code
    # is executed by one of the mooc developers. Here we do by simply checking
    # for some files that belong to the internal mooc repository, but are not
    # published.  This is a temporary solution, and should be improved in the
    # long run.

    developer = os.path.exists(
        os.path.join(module_dir, os.path.pardir, 'scripts'))

    display_html(
        display.HTML(nb_html_header +
                     (hide_outside_ipython if developer else '')))

    # Patch a bug in holoviews
    from patch_holoviews import patch_all
    patch_all()
def init_imports():
    """Initialize speedups and bokeh"""
    speedups.enable()
    hv.notebook_extension('bokeh')
Beispiel #21
0
import numpy as np
from netCDF4 import Dataset
import time
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from ipyleaflet import Map, ImageOverlay, Marker, TileLayer
import os
from pyproj import Proj, transform
import holoviews as hv

hv.notebook_extension()


class OLCIprocessing:
    def __init__(self, ProductName, OutputName=True):
        '''ProductName; contains the path to the Sentinel-3 product that is being processed/of interest.
            OutputName; will be the name of the later on generated png file. If set to True, this function will set this variable to 'S3A_' followed by the date and time of the products retrieval.'''

        self.prodName = ProductName

        if OutputName == True:
            self.out = self.prodName[44:47] + '_' + self.prodName[60:75]
        else:
            self.out = OutputName

    def importNetCDF(self, NumBand=21):
        '''
        This function imports the variables (radiance and coordinates) of a Sentinel-3 OLCI EFR Product
        NumBand; The number of bands that want to be imported. Currently just increasing band numbers are supported, i.e. if NumBand is set to 13, the band Oa01 - Oa13 are imported. Note: CalcRGB method requires the first 10 bands.
        '''
Beispiel #22
0
import os
import sys

import holoviews
import matplotlib.pyplot as plt
import matplotlib.tri as mtri
from PIL import Image, ImageDraw

sys.path.insert(0, os.path.abspath(".."))  # to get adaptive on the path

import adaptive  # noqa: E402, isort:skip

holoviews.notebook_extension("matplotlib")


def create_and_run_learner():
    def ring(xy):
        import numpy as np

        x, y = xy
        a = 0.2
        return x + np.exp(-((x**2 + y**2 - 0.75**2)**2) / a**4)

    learner = adaptive.Learner2D(ring, bounds=[(-1, 1), (-1, 1)])
    adaptive.runner.simple(learner, goal=lambda l: l.loss() < 0.01)
    return learner


def plot_learner_and_save(learner, fname):
    fig, ax = plt.subplots()
    tri = learner.interpolator(scaled=True).tri
Beispiel #23
0
sys.path.append(minian_path)
import itertools as itt
import numpy as np
import xarray as xr
import holoviews as hv
import pandas as pd
from holoviews.operation.datashader import datashade, regrid
from minian.cross_registration import (calculate_centroids,
                                       calculate_centroid_distance,
                                       calculate_mapping, group_by_session,
                                       resolve_mapping, fill_mapping)
from minian.motion_correction import estimate_shifts, apply_shifts
from minian.utilities import open_minian, open_minian_mf
from minian.visualization import AlignViewer

hv.notebook_extension('bokeh', width=100)

# # Allign Videos

# ## open datasets

# In[4]:

minian_ds = open_minian_mf(dpath, id_dims, pattern=f_pattern, backend='zarr')

# ## estimate shifts

# In[5]:

temps = minian_ds['Y'].max('frame').compute().rename('temps')
shifts = estimate_shifts(temps, max_sh=param_t_dist, dim='session').compute()
Beispiel #24
0
from holoviews import notebook_extension
from holoviews.element.comparison import ComparisonTestCase
from holoviews import Store
from holoviews.util import output, opts, OutputSettings
from holoviews.core import OrderedDict

from holoviews.core.options import OptionTree

from holoviews.plotting import mpl
try:
    from holoviews.plotting import bokeh
except:
    bokeh = None

BACKENDS = ['matplotlib'] + (['bokeh'] if bokeh else [])
notebook_extension(*BACKENDS)


class TestOutputUtil(ComparisonTestCase):
    def setUp(self):
        Store.current_backend = 'matplotlib'
        Store.renderers['matplotlib'] = mpl.MPLRenderer.instance()
        if bokeh:
            Store.renderers['bokeh'] = bokeh.BokehRenderer.instance()
        OutputSettings.options = OrderedDict(OutputSettings.defaults.items())

        super(TestOutputUtil, self).setUp()

    def tearDown(self):
        Store.renderers['matplotlib'] = mpl.MPLRenderer.instance()
        if bokeh:
Beispiel #25
0
import pandas as pd
import holoviews as hv
import geoviews as gv
import geoviews.feature as gf
import geoviews.tile_sources as gts
import geopandas

from bokeh.palettes import YlOrBr3 as palette

import cartopy
from cartopy import crs as ccrs

from bokeh.tile_providers import STAMEN_TONER
from bokeh.models import WMTSTileSource

hv.notebook_extension('bokeh')

DATA_PATH = "data/"
MAP_PATH = DATA_PATH + "world.geo.json/countries/"
COUNTRY_CODE_DATA = DATA_PATH + "country-codes/data/country-codes.csv"

try:
    from_day = int(sys.argv[1])
    to_day = int(sys.argv[2])
    out_name = "./results/" + str(from_day) + "to" + str(to_day)
except:
    print("Arguemnts should be like :")
    print("python scraper.py 'From' 'to'")

def isNaN(num):
    return num != num
Beispiel #26
0
import numpy as np
import holoviews as hv 
hv.notebook_extension("bokeh")
xs = np.linspace(0,np.pi*4,100)
data = (xs,np.sin(xs))
hv.Curve(data)