Beispiel #1
2
def interactive_multiple_plot(functions, num_sample_points=10, axes=None, **kwargs):
    """Create an interactive plot for multiple 1D functions to be viewed in
    Jupyter Notebook

    :arg functions: 1D Functions to be plotted
    :arg num_sample_points: Number of sample points per element, ignore if
        degree < 4 where Bezier curve is used for an exact plot
    :arg kwargs: Additional key word arguments to be passed to
        ``matplotlib.plot``
    """
    import matplotlib.pyplot as plt
    try:
        from ipywidgets import interact, IntSlider
    except ImportError:
        raise RuntimeError("Not in notebook")

    if axes is None:
        axes = plt.subplot(111)

    def display_plot(index):
        axes.clear()
        return plot(functions[index], num_sample_points, axes=axes, **kwargs).figure

    interact(display_plot, index=IntSlider(min=0, max=len(functions)-1,
                                           step=1, value=0),
             continuous_update=False)
    return axes
def cholera():
    with open('deaths.csv', 'rt') as f:
        reader = csv.reader(f)
        Coordlist = list(reader)
        
    CList = [[float(column) for column in row] for row in Coordlist]
    
    XYdist = []
    
    for row in CList:
        x = row[0]
        y = row[1]
        dist = math.sqrt(((x-12.5713596)**2)+((y-11.7271700)**2))
        XYdist.append(dist)
    
    distxy = [x for (y,x) in sorted(zip(XYdist,CList))]
    
    def deathcount(n=1):
        deaths = 3
        for n in np.arange(n):
            deaths = deaths + (math.sqrt(deaths))
            
            dist = distxy[:int(deaths)]
            
            x,y = zip(*dist)
            
            plt.plot(12.5713596,11.7271700,'r.')
            plt.axis([0, 20, 0, 18])
            plt.scatter(x,y)
    
    deathcount()
    
    interact(deathcount,n=(1,60))
def myshow(img, title=None, margin=0.05, dpi=80 ):
    nda = sitk.GetArrayFromImage(img)

    spacing = img.GetSpacing()
    slicer = False

    if nda.ndim == 3:
        # fastest dim, either component or x
        c = nda.shape[-1]

        # the the number of components is 3 or 4 consider it an RGB image
        if not c in (3,4):
            slicer = True

    elif nda.ndim == 4:
        c = nda.shape[-1]

        if not c in (3,4):
            raise Runtime("Unable to show 3D-vector Image")

        # take a z-slice
        slicer = True

    if (slicer):
        ysize = nda.shape[1]
        xsize = nda.shape[2]
    else:
        ysize = nda.shape[0]
        xsize = nda.shape[1]


    # Make a figure big enough to accomodate an axis of xpixels by ypixels
    # as well as the ticklabels, etc...
    figsize = (1 + margin) * ysize / dpi, (1 + margin) * xsize / dpi
    def callback(z=None):

        extent = (0, xsize*spacing[1], ysize*spacing[0], 0)

        fig = plt.figure(figsize=figsize, dpi=dpi)

        # Make the axis the right size...
        ax = fig.add_axes([margin, margin, 1 - 2*margin, 1 - 2*margin])

        plt.set_cmap("gray")

        if z is None:
            ax.imshow(nda,extent=extent,interpolation=None)
        else:
            ax.imshow(nda[z,...],extent=extent,interpolation=None)

        if title:
            plt.title(title)

        plt.show()

    if slicer:
        interact(callback, z=(0,nda.shape[0]-1))
    else:
        callback()
Beispiel #4
1
        def mk_interact(handle):
            def update(smoothing=smoothing):
                final = f(x_d, round1, smoothing)
                l.data_source.data = {'x': x_d, 'y': final}
                bokeh.io.push_notebook(handle)

            from ipywidgets import interact
            interact(update, smoothing=(.02, .8, .005))
Beispiel #5
0
def myinteract(img):
    min_ = round(np.nanmin(img), 4)
    max_ = round(np.nanmax(img), 4)
    p30, p70 = np.percentile(img[~np.isnan(img)], (30, 70))
    delta = round((p30-min_)/50, 5)
    interact(myimshow, img=fixed(img), vmin=(min_, p30, delta),
             vmax=(p70, max_, delta), i=(0, len(interpolators)-1))
    def __init__(
        self,
        r,
        paramIds=None,
        minFactor=0,
        maxFactor=2,
        sliderStepFactor=10,
        selection=None,
        simulateAndPlot=simulateAndPlot,
    ):

        if paramIds is None:
            paramIds = r.model.getGlobalParameterIds()
        if selection is not None:
            r.selections = selection

        kwargs = {}

        def runSimulation(start=0, stop=100, steps=100, **kwargs):
            # full model reset
            r.reset(SelectionRecord.ALL)
            # set parameters, key:value pairs
            for k, v in kwargs.items():
                try:
                    key = k.encode("ascii", "ignore")
                    r[key] = v
                except RuntimeError:
                    # error in setting model variable, variable probably not in model
                    e = sys.exc_info()
                    warnings.warn(e)
            # simulate
            try:
                simulateAndPlot(r, start, stop, steps)
            except:
                # error in simulation
                e = sys.exc_info()
                warnings.warn(e)

        # create FloatSlider for all parameters
        for i, pid in enumerate(paramIds):
            val = r[pid]
            try:
                r[pid] = val
                kwargs[pid] = ipywidgets.FloatSlider(
                    min=minFactor * val, max=maxFactor * val, step=val / sliderStepFactor, value=val
                )
            except:
                e = sys.exc_info()
                print(e)

        # create the widget
        ipywidgets.interact(
            runSimulation,
            start=ipywidgets.FloatText(min=0, value=0),
            stop=ipywidgets.FloatText(min=0, value=100),
            steps=ipywidgets.IntText(min=0, value=100),
            **kwargs
        )
Beispiel #7
0
def display_plots(filebase, directory=None, width=700, height=500, **kwargs):
    """Display a series of plots controlled by sliders. The function relies on Python string format functionality to index through a series of plots."""
    def show_figure(filebase, directory, **kwargs):
        """Helper function to load in the relevant plot for display."""
        filename = filebase.format(**kwargs)
        if directory is not None:
            filename = directory + '/' + filename
        display(HTML("<img src='{filename}'>".format(filename=filename)))
    interact(show_figure, filebase=fixed(filebase), directory=fixed(directory), **kwargs)
Beispiel #8
0
def demo():
    numberCount = widgets.IntSlider(description='Number of Dice',min=1,max=12,step=1,value=4,continuous_update=False)
    faceCount = widgets.IntSlider(description='Dice Type',min=2,max=20,step=1,value=4,continuous_update=False)
    modifier = widgets.IntSlider(description='Modifier',min=-5,max=10,step=1,value=2,continuous_update=False)
    dropCount = widgets.IntSlider(description='Number of Removed Low Rolls',min=0,max=3,step=1,value=1,continuous_update=False)

    def update_max_drop(*args):
        dropCount.max = numberCount.value - 1
    numberCount.on_trait_change(update_max_drop,name="value")

    interact(plotD,num=numberCount,faces=faceCount,mod=modifier,drop=dropCount)
    def __init__(self):
        

        interact(self.solve_and_plot,
                          SL = FloatSlider(value=1.85, min=1.4, max=2.4, step=0.05),
                          Fmax = FloatSlider(value=0.17, min=0.17, max=0.92, step=0.05),
                          Ca50 = FloatSlider(value=3.0, min=0.87, max=3.0, step=0.05),
                          n = FloatSlider(value=7.6, min=3, max=10, step=0.5)


                     )
Beispiel #10
0
    def waveform_line(self, ind=None, ref_ind=None):
        """
        Draw waveform 2D line plot.

        :param ind: Time index
        :param ref_ind: Reference time index
        """
        if ind is None and self._interactive:
            interact(self._plot_waveform_line, ind=(0, self._inspector.num_times - 1), ref_ind=fixed(ref_ind))
        else:
            self._plot_waveform_line(ind=ind if ind else 0, ref_ind=ref_ind)
Beispiel #11
0
def browse_images(obsid):
    df = io.DBManager().get_image_name_markings(obsid)
    xmax = df.x_tile.max()
    ymax = df.y_tile.max()

    def view_image(xtile=1, ytile=1):
        img = get_four_tiles_img(obsid, xtile, ytile)
        print(img.shape)
        plt.imshow(img, origin='upper', aspect='auto')
        plt.title(f'x_tile: {xtile}, y_tile: {ytile}')
        plt.show()
    interact(view_image, xtile=(1, xmax - 1), ytile=(1, ymax - 1))
def browse_weights(model):
    """Creates a IPython Widget to visualize convolution layer weights"""
    config = model.get_config(verbose=0)
    weights = model.get_weights()

    conv_layers = get_layers(config, layer_type="Convolution2D")
    
    def view_layer(conv_layer):
        n_weight = conv_layers[conv_layer][0]
        plot_weights(weights[n_weight])
        
    interact(view_layer, conv_layer=(0, len(conv_layers) - 1))
Beispiel #13
0
def plot_pca_interactive(data, n_components=6):
    from sklearn.decomposition import PCA
    from ipywidgets import interact

    pca = PCA(n_components=n_components)
    Xproj = pca.fit_transform(data)

    def show_decomp(i=0):
        plot_image_components(data[i], Xproj[i],
                              pca.mean_, pca.components_)
    
    interact(show_decomp, i=(0, data.shape[0] - 1));
 def __init__(self):
     interact(self.solve_and_plot,
                  SL = FloatSlider(value=1.85, min=1.4, max=2.4, step=0.05),
                  Ca_amplitude = FloatSlider(value=1.45, min=1.0, max=1.9, step=0.05),
                  tau1 = FloatSlider(value=20, min=10, max=30, step=1),
                  tau2 = FloatSlider(value=110, min=80, max=140, step=5),
                  kn_p = FloatSlider(value=0.5, min=0.25, max=1.0, step=0.05),
                  kp_n = FloatSlider(value=0.05, min=0.025, max=0.1, step=0.02),
                  f_app = FloatSlider(value=0.5, min=0.2, max=1.0, step=0.05),
                  g_app = FloatSlider(value=0.07, min=0.03, max=0.14, step=0.01),
                  h_f = FloatSlider(value=2.0, min=1.0, max=3.0, step=0.1),
                  h_b = FloatSlider(value=0.4, min=0.2, max=0.8, step=0.05),
                  gxb = FloatSlider(value=0.07, min=0.02, max=0.1, step=0.01))
Beispiel #15
0
def displayer(directories=[os.getcwd()], time=(), openfoam=False):
  """
  Interactively displays multiple images in a Jupyter Notebook with ipywidgets.

  Parameters
  ----------
  directories: list of strings, optional
    Path of folders containing images to display;
    default: current directory.
  time: 3-tuple, optional
    Temporal limits and time-increment to choose which images to display;
    default: empty tuple (all images in the folder).
  openfoam: boolean, optional
    Set 'True' if OpenFOAM simulation;
    default: False (not an OpenFOAM simulation).

  Returns
  -------
  The interactive display.
  """
  # check parameter is a list, if not convert into a list
  try:
    assert isinstance(directories, (list, tuple))
    assert not isinstance(directories, basestring)
  except:
    directories = [directories]
  all_images = []
  if not time:
    for directory in directories:
      all_images.append(get_images(directory))
    slider = create_slider(description='index',
                           values=numpy.arange(len(all_images[0])))
  else:
    times = numpy.arange(time[0], time[1] + time[2] / 2.0, time[2])
    if openfoam:
      steps = times
    else:
      steps = numpy.rint(times / time[3]).astype(int)
    for directory in directories:
      all_images.append(get_images(directory, steps=steps))
    slider = create_slider(description='time', values=times)

  def create_view(tic):
    if not time:
      index = int(round(tic))
    else:
      index = numpy.where(numpy.abs(times - tic) <= 1.0E-06)[0][0]
    for images in all_images:
      display(Image(filename=images[index]))

  ipywidgets.interact(create_view, tic=slider)
Beispiel #16
0
        def mk_interact(handle):
            def update(bins=bins, phase=0):
                if phase > 0 and phase < 1:
                    bins = bins + 1
                    delta = (cdf.values[-1] - cdf.values[0]) / bins
                    edges = np.linspace(cdf.values[0] - (1 - phase) * delta, cdf.values[-1] + phase * delta, bins)
                else:
                    edges = np.linspace(cdf.values[0], cdf.values[-1], bins)
                hist, edges = np.histogram(cdf.values, bins=edges, weights=np.diff(cdf.ranks), density=True)
                new_data = {'top': hist, 'left': edges[:-1], 'right': edges[1:], 'bottom': np.full(len(hist), 0)}
                q.data_source.data = new_data
                bokeh.io.push_notebook(handle)

            from ipywidgets import interact
            interact(update, bins=(0, 5*bins), phase=(0, 1, .01))
Beispiel #17
0
	def create_sliders(self,R_i,V_i):
		# Records the initial position and velocity
		self.R_i = R_i
		self.V_i = V_i

		self.run_button = widgets.Button(description="Run (with new values)")
		display(self.run_button)
		self.run_button.on_click(self.mainloop)

		self.trace_button = widgets.Button(description="Tracer On/Off")
		display(self.trace_button)
		self.trace_button.on_click(self.t_onoff)

		widgets.interact(self.q_update,val = FloatSlider(min=1000., max=10000., step=0.1, value=self.q, description='Charge Factor'))
		widgets.interact(self.r_update,val = FloatSlider(min=0.01, max=1., step=0.001, value=self.R_i[2], description='Particle Height'))
def randomized_tree_interactive(X, y):
    N = int(0.75 * X.shape[0])
    
    xlim = (X[:, 0].min(), X[:, 0].max())
    ylim = (X[:, 1].min(), X[:, 1].max())
    
    def fit_randomized_tree(random_state=0):
        clf = DecisionTreeClassifier(max_depth=15)
        i = np.arange(len(y))
        rng = np.random.RandomState(random_state)
        rng.shuffle(i)
        visualize_tree(clf, X[i[:N]], y[i[:N]], boundaries=False,
                       xlim=xlim, ylim=ylim)
    
    interact(fit_randomized_tree, random_state=[0, 100]);
Beispiel #19
0
 def im(self, z=None, zmin=None, zmax=None, cmap='jet'):
     if z is None:
         if self._interactive:
             name_options = list()
             for dim_names, var_names in self._inspector.dim_names_to_var_names.items():
                 no_zero_dim = all([self._inspector.dim_name_to_size[dim] > 0 for dim in dim_names])
                 if no_zero_dim and len(dim_names) == 2:
                     name_options.extend(var_names)
             name_options = sorted(name_options)
             # TODO (forman, 20160709): add sliders for zmin, zmax
             interact(self._plot_im, z_name=name_options, zmin=fixed(zmax), zmax=fixed(zmax), cmap=fixed(cmap))
         else:
             raise ValueError('name must be given')
     else:
         self._plot_im(z_name=z, zmin=zmin, zmax=zmax, cmap=cmap)
Beispiel #20
0
def interactive_phase_plane(ql=(10.0, -5.0), qr=(40.0, 5.0), rho=2.0, bulk=1.0):
    """Plots interactive phase plane plot."""

    # Create plot function for interact
    pp_plot = phase_plane_plot()

    # Declare all widget sliders
    ql1_widget = widgets.FloatSlider(value=ql[0],min=0.01,max=50.0, description='$p_l$')
    ql2_widget = widgets.FloatSlider(value=ql[1],min=-30,max=30.0, description='$u_l$')
    qr1_widget = widgets.FloatSlider(value=qr[0],min=0.01,max=50.0, description='$p_r$')
    qr2_widget = widgets.FloatSlider(value=qr[1],min=-30,max=30.0, description='$u_r$')
    rho_widget = widgets.FloatSlider(value=rho,min=0.01,max=10.0, description=r'$\rho$')
    bulk_widget = widgets.FloatSlider(value=bulk,min=0.01,max=10.0, description='$K$')
    xmin_widget = widgets.BoundedFloatText(value=0.0000001, description='$p_{min}:$')
    xmax_widget = widgets.FloatText(value=50, description='$p_{max}:$')
    ymin_widget = widgets.FloatText(value=-30, description='$u_{min}:$')
    ymax_widget = widgets.FloatText(value=30, description='$u_{max}:$')
    show_physical = widgets.Checkbox(value=True, description='Physical solution')
    show_unphysical = widgets.Checkbox(value=True, description='Unphysical solution')

    # Allow for dependent widgets to update
    def update_xmin(*args):
        ql1_widget.min = xmin_widget.value
        qr1_widget.min = xmin_widget.value
    def update_xmax(*args):
        ql1_widget.max = xmax_widget.value
        qr1_widget.max = xmax_widget.value
    def update_ymin(*args):
        ql2_widget.min = ymin_widget.value
        qr2_widget.min = ymin_widget.value
    def update_ymax(*args):
        ql2_widget.max = ymax_widget.value
        qr2_widget.max = ymax_widget.value
    xmin_widget.observe(update_xmin, 'value')
    xmax_widget.observe(update_xmax, 'value')
    ymin_widget.observe(update_ymin, 'value')
    ymax_widget.observe(update_ymax, 'value')

    # Organize slider widgets into boxes
    qleftright = widgets.VBox([widgets.HBox([ql1_widget, ql2_widget, rho_widget]),
                               widgets.HBox([qr1_widget, qr2_widget, bulk_widget])])
    plot_opts = widgets.VBox([widgets.HBox([show_physical, show_unphysical]),
                              widgets.HBox([xmin_widget, xmax_widget]),
                              widgets.HBox([ymin_widget, ymax_widget])])

    # Set up interactive GUI (tab style)
    interact_gui = widgets.Tab(children=[qleftright, plot_opts])
    interact_gui.set_title(0, 'Left and right states')
    interact_gui.set_title(1, 'Plot options')

    # Define interactive widget and run GUI
    ppwidget = interact(pp_plot, pl=ql1_widget, ul=ql2_widget,
                        pr=qr1_widget, ur=qr2_widget,
                        rho=rho_widget, bulk=bulk_widget,
                        xmin=xmin_widget, xmax=xmax_widget,
                        ymin=ymin_widget, ymax=ymax_widget,
                        show_phys=show_physical, show_unphys=show_unphysical)
    ppwidget.widget.close()
    display(interact_gui)
    display(ppwidget.widget.out)
Beispiel #21
0
def interact_animate_images(images, figsize=(10,6), manual=False, TextInput=False):

    def display_frame(frameno): 
        imshow_noaxes(images[frameno], figsize=figsize)

    if TextInput:
        if TextInput:
            print("Valid frameno values: from %i to %i" % (0,len(images)-1))
        widget = ipywidgets.IntText(min=0,max=len(images)-1, value=0)
    else:
        widget = ipywidgets.IntSlider(min=0,max=len(images)-1, value=0)

    if manual:
        interact_manual(display_frame, frameno=widget)
    else:
        interact(display_frame, frameno=widget)
Beispiel #22
0
 def display(self):
   widget = interact(self.solve_and_plot,
           gamma = FloatSlider(value = 4.17, min = 0, max = 10, step= 0.5),
           k_1 = FloatSlider(value = 2*10**(-5), min = 0, max = 2*10**(-5) * 2, step= 10**(-5)),
           k_2 = FloatSlider(value = 0.13, min = 0.05, max = 0.13*2, step= 0.02),
           k_4 = FloatSlider(value = 0.9, min = 0, max = 0.9*2, step= 0.2),
           k_31 = FloatSlider(value = 1, min = 0, max = 2, step= 0.2))
Beispiel #23
0
def interact_animate_figs(figs, manual=False, TextInput=False):

    def display_frame(frameno): 
        display(figs[frameno])

    if TextInput:
        widget = ipywidgets.IntText(min=0,max=len(figs)-1, value=0)
    else:
        widget = ipywidgets.IntSlider(min=0,max=len(figs)-1, value=0)

    if manual:
        if TextInput:
            print("Valid frameno values: from %i to %i" % (0,len(figs)-1))
        interact_manual(display_frame, frameno=widget)
    else:
        interact(display_frame, frameno=widget)
Beispiel #24
0
    def show(self, viewer='mpl', ds9options=None, **kwargs):
        """
        Show sky cube in image viewer.

        Parameters
        ----------
        viewer : {'mpl', 'ds9'}
            Which image viewer to use. Option 'ds9' requires ds9 to be installed.
        ds9options : list, optional
            List of options passed to ds9. E.g. ['-cmap', 'heat', '-scale', 'log'].
            Any valid ds9 command line option can be passed.
            See http://ds9.si.edu/doc/ref/command.html for details.
        **kwargs : dict
            Keyword arguments passed to `~matplotlib.pyplot.imshow`.
        """
        import matplotlib.pyplot as plt
        from ipywidgets import interact

        if viewer == 'mpl':
            max_ = self.data.shape[0] - 1

            def show_image(idx):
                image = self.sky_image(idx)
                image.data = image.data.value
                image.show(**kwargs)

            return interact(show_image, idx=(0, max_, 1))
        elif viewer == 'ds9':
            raise NotImplementedError
Beispiel #25
0
def show(obj, interact=None):
    """Immediately display a Bokeh object or application.  Calls
    :func:`bokeh.io.show`.

    Parameters
    ----------
    obj
        A Bokeh object to display.
    interact
        A handle returned by a plotting method with `interactive=True`.
    """
    if interact is None:
        bokeh.io.show(obj)
    else:
        handle = bokeh.io.show(obj, notebook_handle=True)
        interact(handle)
Beispiel #26
0
    def show(self, viewer='mpl', ds9options=None, **kwargs):
        """Show sky cube in image viewer.

        Parameters
        ----------
        viewer : {'mpl', 'ds9'}
            Which image viewer to use. Option 'ds9' requires ds9 to be installed.
        ds9options : list, optional
            List of options passed to ds9. E.g. ['-cmap', 'heat', '-scale', 'log'].
            Any valid ds9 command line option can be passed.
            See http://ds9.si.edu/doc/ref/command.html for details.
        **kwargs : dict
            Keyword arguments passed to `matplotlib.pyplot.imshow`.
        """
        from ipywidgets import interact

        if viewer == 'mpl':
            max_ = self.data.shape[0] - 1

            def show_image(idx):
                energy = self.energy_axis.wcs_pix2world(idx)
                image = self.sky_image(energy)
                image.data = image.data.value
                try:
                    norm = kwargs['norm']
                    norm.vmax = np.nanmax(image.data)
                except KeyError:
                    pass
                image.show(**kwargs)

            return interact(show_image, idx=(0, max_, 1))
        elif viewer == 'ds9':
            raise NotImplementedError
        else:
            raise ValueError('Invalid viewer: {}'.format(viewer))
Beispiel #27
0
def show_image_stack(images, minmax, fontsize=18, cmap='CMRmap',
                     zlabel=r'Intensty [ADU]', figsize=(12, 10)):
    """Show an Interactive Image Stack in an IPython Notebook

    Parameters
    ----------
    images : array_like
        Stack of images of shape (N, y, x) where N is the number of images
        to show.
    minmax : tuple
        Value for the minimum and maximum of the stack in the form
        ``(min, max)``
    fontsize : int
        Fontsize for axis labels.
    cmap : string
        Colormap to use for image (from matplotlib)
    zlabel : string
        Axis label for the color bar (z-axis)
    figsize : tuple
        Figure size (from matplotlib)


    """
    n = images.shape[0]

    def view_frame(i, vmin, vmax):
        fig = plt.figure(figsize=figsize)
        ax = fig.add_subplot(111)

        im = ax.imshow(images[i], cmap=cmap, interpolation='none',
                       vmin=vmin, vmax=vmax)

        cbar = fig.colorbar(im)
        cbar.ax.tick_params(labelsize=fontsize)
        cbar.set_label(zlabel, size=fontsize, weight='bold')

        ax.set_title('Frame {} Min = {} Max = {}'.format(i, vmin, vmax),
                     fontsize=fontsize, fontweight='bold')

        for item in ([ax.xaxis.label, ax.yaxis.label] +
                     ax.get_xticklabels() + ax.get_yticklabels()):
            item.set_fontsize(fontsize)
            item.set_fontweight('bold')

        plt.show()

    interact(view_frame, i=(0, n-1), vmin=minmax, vmax=minmax)
    def interactive_correlations(self):
        def do_interact(data_type='expression',
                        sample_subset=self.default_sample_subsets,
                        feature_subset=self.default_feature_subset,
                        metric='euclidean', method='average',
                        list_link='',
                        scale_fig_by_data=True,
                        fig_width='', fig_height='', featurewise=False):

            for k, v in locals().iteritems():
                if k == 'self':
                    continue
                sys.stdout.write('{} : {}\n'.format(k, v))

            if feature_subset != "custom" and list_link != "":
                raise ValueError(
                    "set feature_subset to \"custom\" to use list_link")

            if feature_subset == "custom" and list_link == "":
                raise ValueError("use a custom list name please")

            if feature_subset == 'custom':
                feature_subset = list_link
            elif feature_subset not in self.default_feature_subsets[data_type]:
                warnings.warn("This feature_subset ('{}') is not available in "
                              "this data type ('{}'). Falling back on all "
                              "features.".format(feature_subset, data_type))
            return self.plot_correlations(
                sample_subset=sample_subset, feature_subset=feature_subset,
                data_type=data_type, scale_fig_by_data=scale_fig_by_data,
                method=method, metric=metric, featurewise=featurewise)

        feature_subsets = Interactive.get_feature_subsets(self,
                                                          ['expression',
                                                           'splicing'])
        method = ('average', 'weighted', 'single', 'complete', 'ward')
        metric = ('euclidean', 'seuclidean', 'sqeuclidean', 'chebyshev',
                  'cosine', 'cityblock', 'mahalonobis', 'minowski', 'jaccard')
        gui = interact(do_interact,
                       data_type=('expression', 'splicing'),
                       sample_subset=self.default_sample_subsets,
                       feature_subset=feature_subsets,
                       metric=metric,
                       method=method,
                       featurewise=False)

        def save(w):
            filename, extension = os.path.splitext(savefile.value)
            self.maybe_make_directory(savefile.value)
            gui.widget.result.savefig(savefile.value,
                                      format=extension.lstrip('.'))

        savefile = Text(description='savefile',
                        value='figures/correlations.pdf')
        save_widget = Button(description='save')
        gui.widget.children = list(gui.widget.children) + [savefile,
                                                           save_widget]
        save_widget.on_click(save)
        return gui
Beispiel #29
0
    def im_line(self, z=None, zmin=None, zmax=None, xind=None, yind=None, cmap='jet'):
        if self._interactive:
            has_xind = xind is not None
            has_yind = yind is not None
            if not z or not has_xind or not has_yind:
                if xind is None:
                    widget_xind = widgets.IntSlider(min=0, max=10, step=1, description='X:')
                else:
                    widget_xind = fixed(xind)

                if yind is None:
                    widget_yind = widgets.IntSlider(min=0, max=10, step=1, description='Y:')
                else:
                    widget_yind = fixed(yind)

                if not z:
                    valid_var_names = list()
                    for dim_names, var_names in self._inspector.dim_names_to_var_names.items():
                        no_zero_dim = all([self._inspector.dim_name_to_size[dim] > 0 for dim in dim_names])
                        if no_zero_dim and len(dim_names) == 2:
                            valid_var_names.extend(var_names)
                    valid_var_names = sorted(valid_var_names)
                    value = z if z and z in valid_var_names else valid_var_names[0]
                    widget_var = widgets.Dropdown(options=valid_var_names, value=value, description='Var:')

                    # noinspection PyUnusedLocal
                    def on_widget_var_change(change):
                        variable = self._inspector.dataset[widget_var.value]
                        if xind is None:
                            widget_xind.max = variable.shape[1] - 1
                        if yind is None:
                            widget_yind.max = variable.shape[0] - 1

                    widget_var.observe(on_widget_var_change, names='value')
                else:
                    widget_var = fixed(z)

                # TODO (forman, 20160709): add sliders for zmin, zmax
                interact(self._plot_im_line, z_name=widget_var,
                         xind=widget_xind, yind=widget_yind,
                         zmin=fixed(zmax), zmax=fixed(zmax), cmap=fixed(cmap))
        else:
            if not z:
                raise ValueError('z_name must be given')
            self._plot_im_line(z, zmin=zmin, zmax=zmin, xind=xind, yind=yind, cmap=cmap)
def plot_tree_interactive(X, y):
    from sklearn.tree import DecisionTreeClassifier

    def interactive_tree(depth=1):
        clf = DecisionTreeClassifier(max_depth=depth, random_state=0)
        visualize_tree(clf, X, y)

    from IPython.html.widgets import interact
    return interact(interactive_tree, depth=[1, 5])
Beispiel #31
0
def myshow(img, title=[], margin=0.05, dpi=80 ):
    nda = sitk.GetArrayViewFromImage(img)

    spacing = img.GetSpacing()
    slicer = False

    if nda.ndim == 3:
        # fastest dim, either component or x
        c = nda.shape[-1]

        # the the number of components is 3 or 4 consider it an RGB image
        if not c in (3,4):
            slicer = True

    elif nda.ndim == 4:
        c = nda.shape[-1]

        if not c in (3,4):
            raise Runtime("Unable to show 3D-vector Image")

        # take a z-slice
        slicer = True
    

    if (slicer):
        ysize = nda.shape[1]
        xsize = nda.shape[2]
    else:
        ysize = nda.shape[0]
        xsize = nda.shape[1]


    # Make a figure big enough to accomodate an axis of xpixels by ypixels
    # as well as the ticklabels, etc...
    figsize = (1 + margin) * ysize / dpi, (1 + margin) * xsize / dpi
    def callback(z=None):        

        extent = (0, xsize*spacing[1], ysize*spacing[0], 0)

        fig = plt.figure(figsize=figsize, dpi=dpi)

        # Make the axis the right size...
        ax = fig.add_axes([margin, margin, 1 - 2*margin, 1 - 2*margin])

        plt.set_cmap("gray")

        if z is None:
            ax.imshow(nda,extent=extent,interpolation=None)
        else:
            ax.imshow(nda[z,...],extent=extent,interpolation=None)
            if title:
                plt.title(title[z])
            
        plt.show()

    if slicer:
        if title:
            interact(callback, z=(0,nda.shape[0]-1))
        else:
            interact(callback, z=(0,nda.shape[0]-1))
    else:
        callback()
Beispiel #32
0
    def interact(
        self,
        key_field=None,
        dt_frame_in_sec=0.3,
        dt_equations=None,
        tmin=None,
        tmax=None,
        fig_kw={},
        **kwargs,
    ):
        """Launches an interactive plot.

        Parameters
        ----------
        key_field : str
            Specifies which field to animate
        dt_frame_in_sec : float
            Interval between animated frames in seconds
        dt_equations : float
            Approx. interval between saved files to load in simulation time
            units
        tmax : float
            Animate till time `tmax`.
        fig_kw : dict
            Dictionary of arguments for arguments for the figure.

        Other Parameters
        ----------------
        All `kwargs` are passed on to `init_animation` and `_ani_save`

        xmax : float
            Set x-axis limit for 1D animated plots
        ymax : float
            Set y-axis limit for 1D animated plots
        clim : tuple
            Set colorbar limits for 2D animated plots
        step : int
            Set step value to get a coarse 2D field
        QUIVER : bool
            Set quiver on or off on top of 2D pcolor plots

        Notes
        -----
        Installation instructions for notebook::

          pip install ipywidgets
          jupyter nbextension enable --py widgetsnbextension

        Restart the notebook and call the function using::

          >>> %matplotlib notebook

        For JupyterLab::

          pip install ipywidgets ipympl
          jupyter labextension install @jupyter-widgets/jupyterlab-manager

        Restart JupyterLab and call the function using::

          >>> %matplotlib widget

        """
        try:
            from ipywidgets import interact, widgets
        except ImportError:
            raise ImportError(
                "See fluidsim.base.output.movies.interact docstring."
            )

        if not is_run_from_jupyter():
            raise ValueError("Works only inside Jupyter.")

        self.init_animation(
            key_field, 0, dt_equations, tmin, tmax, fig_kw, **kwargs
        )
        if tmin is None:
            tmin = self.ani_times[0]
        if tmax is None:
            tmax = self.ani_times[-1]
        if dt_equations is None:
            dt_equations = self.ani_times[1] - self.ani_times[0]

        slider = widgets.FloatSlider(
            min=float(tmin),
            max=float(tmax),
            step=float(dt_equations),
            value=float(tmin),
        )

        def widget_update(time):
            frame = np.argmin(abs(self.ani_times - time))
            self.update_animation(frame)
            self.fig.canvas.draw()

        interact(widget_update, time=slider)
def fourier_linearity_demo1():
    interact(fourier_linearity_demo1_plot, a=(0, 1.0, 0.1),
             b=(0, 1.0, 0.1),
             continuous_update=False)
Beispiel #34
0
    def transform(self,
                  dataset,
                  alpha_selection='auto',
                  n_alphas=40,
                  max_log_alpha=3,
                  n_alphas_to_return=4,
                  plot=False,
                  gui=False,
                  active_labels=None,
                  colors=None,
                  legend=None,
                  alpha_value=None,
                  return_alphas=False):
        if (self.fitted == False):
            raise ValueError(
                "This model has not been fit to a foreground/background dataset yet. Please run the fit() or fit_transform() functions first."
            )
        if not (alpha_selection == 'auto' or alpha_selection == 'manual'
                or alpha_selection == 'all'):
            raise ValueError(
                "Invalid argument for parameter alpha_selection: must be 'auto' or 'manual' or 'all'"
            )
        if (alpha_selection == 'all' and plot == True):
            raise ValueError(
                'The plot parameter cannot be set to True if alpha_selection is set to "all"'
            )
        if ((alpha_selection == 'all' or alpha_selection == 'manual')
                and gui == True):
            raise ValueError(
                'The gui parameter cannot be set to True if alpha_selection is set to "all" or "manual"'
            )
        if ((gui == True or plot == True) and not (self.n_components == 2)):
            raise ValueError(
                'The gui and plot parameters modes cannot be used if the number of components is not 2'
            )
        if (not (alpha_value) and alpha_selection == 'manual'):
            raise ValueError(
                'The the alpha_selection parameter is set to "manual", the alpha_value parameter must be provided'
            )
        #you can't be plot or gui with non-2 components
        # Handle the plotting variables
        if (plot or gui):
            if active_labels is None:
                active_labels = np.ones(dataset.shape[0])
            self.active_labels = active_labels
            if colors is None:
                self.colors = ['k', 'r', 'b', 'g', 'c']

        if gui:
            try:
                import matplotlib.pyplot as plt
                from matplotlib.gridspec import GridSpec
            except ImportError:
                raise ImportError(
                    "Something wrong while loading matplotlib.pyplot! You probably don't have plotting libraries installed."
                )
            try:
                from ipywidgets import widgets, interact, Layout
                from IPython.display import display
            except ImportError:
                raise ImportError(
                    "To use the GUI, you must be running this code in a jupyter notebook that supports ipywidgets"
                )

            transformed_data_auto, alphas_auto = self.automated_cpca(
                dataset, n_alphas_to_return, n_alphas, max_log_alpha)
            transformed_data_manual, alphas_manual = self.all_cpca(
                dataset, n_alphas, max_log_alpha)
            if (self.n_fg > 1000):
                print(
                    "The GUI may be slow to respond with large numbers of data points. Consider using a subset of the original data."
                )
            """
            Handles the plotting
            """
            def graph_foreground(ax, fg, active_labels, alpha):
                for i, l in enumerate(np.sort(np.unique(active_labels))):
                    ax.scatter(fg[np.where(active_labels == l), 0],
                               fg[np.where(active_labels == l), 1],
                               color=self.colors[i % len(self.colors)],
                               alpha=0.6)
                if (alpha == 0):
                    ax.annotate(r'$\alpha$=' + str(np.round(alpha, 2)) +
                                " (PCA)", (0.05, 0.05),
                                xycoords='axes fraction')
                else:
                    ax.annotate(r'$\alpha$=' + str(np.round(alpha, 2)),
                                (0.05, 0.05),
                                xycoords='axes fraction')

            """
            This code gets run whenever the widget slider is moved
            """

            def update(value):
                fig = plt.figure(figsize=[10, 4])
                gs = GridSpec(2, 4)

                for i in range(4):
                    ax1 = fig.add_subplot(gs[int(i // 2),
                                             i % 2])  # First row, first column
                    fg = transformed_data_auto[i]
                    graph_foreground(ax1, fg, self.active_labels,
                                     alphas_auto[i])

                    ax5 = fig.add_subplot(
                        gs[:, 2:])  # Second row, span all columns

                    alpha_idx = np.abs(alphas_manual - 10**value).argmin()
                    fg = transformed_data_manual[alpha_idx]
                    graph_foreground(ax5, fg, self.active_labels,
                                     alphas_manual[alpha_idx])

                #if len(np.unique(self.active_labels))>1:
                #plt.legend()

                plt.tight_layout()
                plt.show()

            widg = interact(update,
                            value=widgets.FloatSlider(
                                description=r'\(\log_{10}{\alpha} \)',
                                min=-1,
                                max=3,
                                step=4 / 40,
                                continuous_update=False,
                                layout=Layout(width='80%')))

            return

        elif plot:
            try:
                import matplotlib.pyplot as plt
            except ImportError:
                raise ImportError(
                    "Something wrong while loading matplotlib.pyplot! You probably don't have plotting libraries installed."
                )
            if (alpha_selection == 'auto'):
                transformed_data, best_alphas = self.automated_cpca(
                    dataset, n_alphas_to_return, n_alphas, max_log_alpha)
                plt.figure(figsize=[14, 3])
                for j, fg in enumerate(transformed_data):
                    plt.subplot(1, 4, j + 1)
                    for i, l in enumerate(
                            np.sort(np.unique(self.active_labels))):
                        idx = np.where(self.active_labels == l)
                        plt.scatter(fg[idx, 0],
                                    fg[idx, 1],
                                    color=self.colors[i % len(self.colors)],
                                    alpha=0.6,
                                    label='Class ' + str(i))
                    plt.title('Alpha=' + str(np.round(best_alphas[j], 2)))
                if len(np.unique(self.active_labels)) > 1:
                    plt.legend()
                plt.show()
            elif (alpha_selection == 'manual'):
                transformed_data, best_alphas = self.automated_cpca(
                    dataset, n_alphas_to_return, n_alphas, max_log_alpha)
                plt.figure(figsize=[14, 3])
                for j, fg in enumerate(transformed_data):
                    plt.subplot(1, 4, j + 1)
                    for i, l in enumerate(
                            np.sort(np.unique(self.active_labels))):
                        idx = np.where(self.active_labels == l)
                        plt.scatter(fg[idx, 0],
                                    fg[idx, 1],
                                    color=self.colors[i % len(self.colors)],
                                    alpha=0.6,
                                    label='Class ' + str(i))
                    plt.title('Alpha=' + str(np.round(best_alphas[j], 2)))
                if len(np.unique(self.active_labels)) > 1:
                    plt.legend()
                plt.show()

            return

        else:
            if (alpha_selection == 'auto'):
                transformed_data, best_alphas = self.automated_cpca(
                    dataset, n_alphas_to_return, n_alphas, max_log_alpha)
                alpha_values = best_alphas
            elif (alpha_selection == 'all'):
                transformed_data, all_alphas = self.all_cpca(
                    dataset, n_alphas, max_log_alpha)
                alpha_values = all_alphas
            else:
                transformed_data = self.cpca_alpha(dataset, alpha_value)
                alpha_values = alpha_value
        if return_alphas:
            return transformed_data, alpha_values
        else:
            return transformed_data
Beispiel #35
0
from ipywidgets import interact, interactive, fixed
import ipywidgets as widgets


def f(x):
    return x


interact(
    f,
    x=10,
)
Beispiel #36
0
col2 = widgets.VBox([maxhits, sortby]) # second column: Maximum Hits and drop-down menu.
box = widgets.HBox([col1, col2]) # put first and second column next to each other in a row
widgets.VBox([box,out]) # add ouput below the widgets.


# ## 2.4.2.10 Alternative Interface
# The following alterative interface is much simpler in its coding (essentially letting the `interact` function do all the work). To be useful, this interface requires a fairly fast machine because the search will update live while you type. The interface uses the same search function as above, so search instructions and results are the same.

# In[19]:


interact(search, Search = '',
        Max_hits = widgets.BoundedIntText(
        value=25,
        min=0,
        max=len(bdtns),
        step=1,
        description='Max hits:',
        continuous_update = True), 
        Links = True, 
        Sortby = ['id_text', 'text', 'date', 'provenance', 'publication'] );


# ## 2.4.2.11 Search Instructions
# 
# Search for a sequence of sign values in any transliteration system recognized by [OGSL](http://oracc.org/ogsl). Thus, sugal₇, sukkal, or luh, in upper or lower case will all return the same results.
# 
# - Determinatives (semantic classifiers) may be entered between curly brackets or as regular signs. Thus, gesz taškarin, gesz-taskarin, {ŋesz}taskarin, and {ŋeš}tug₂ will all yield the same results. 
# 
# - Signs may be connected with spaces or hyphens.
# 
# - The Shin may be represented by š, c, or sz in upper or lower case; nasal g may be represented as j, ŋ, or ĝ.
    def _default_plotter(self, mask_background=False, **kwargs):
        """Plot three orthogonal views.

        This is called by nifti_plotter, you shouldn't call it directly.
        """
        plt.gcf().clear()
        plt.ioff()  # disable interactive mode

        data_array = self.data.get_data()

        if not ((data_array.ndim == 3) or (data_array.ndim == 4)):
            raise ValueError("Input image should be 3D or 4D")

        # mask the background
        if mask_background:
            # TODO: add the ability to pass 'mne' to use a default brain mask
            # TODO: split this out into a different function
            if data_array.ndim == 3:
                labels, n_labels = scipy.ndimage.measurements.label(
                    (np.round(data_array) == 0)
                )
            else:  # 4D
                labels, n_labels = scipy.ndimage.measurements.label(
                    (np.round(data_array).max(axis=3) == 0)
                )

            mask_labels = [
                lab
                for lab in range(1, n_labels + 1)
                if (
                    np.any(labels[[0, -1], :, :] == lab)
                    | np.any(labels[:, [0, -1], :] == lab)
                    | np.any(labels[:, :, [0, -1]] == lab)
                )
            ]

            if data_array.ndim == 3:
                data_array = np.ma.masked_where(
                    np.isin(labels, mask_labels), data_array
                )
            else:
                data_array = np.ma.masked_where(
                    np.broadcast_to(
                        np.isin(labels, mask_labels)[:, :, :, np.newaxis],
                        data_array.shape,
                    ),
                    data_array,
                )

        # init sliders for the various dimensions
        for dim, label in enumerate(["x", "y", "z"]):
            if label not in kwargs.keys():
                kwargs[label] = IntSlider(
                    value=(data_array.shape[dim] - 1) / 2,
                    min=0,
                    max=data_array.shape[dim] - 1,
                    continuous_update=False,
                )

        if (data_array.ndim == 3) or (data_array.shape[3] == 1):
            kwargs["t"] = fixed(None)  # time is fixed
        else:
            kwargs["t"] = IntSlider(
                value=0,
                min=0,
                max=data_array.shape[3] - 1,
                continuous_update=False,
            )

        widgets.interact(self._plot_slices, data=fixed(data_array), **kwargs)

        plt.close()  # clear plot
        plt.ion()  # return to interactive state
Beispiel #38
0
def hpf_demo2():
    interact(hpf_demo2_plot,
             fb=(10, 400, 10),
             zeta=(0, 10, 0.1),
             mode=spectrum_modes,
             continuous_update=False)
Beispiel #39
0
    def tool(self, default_params=None, **kwargs):
        if default_params is None:
            default_params = {}
        preference = self.display_params['preference']

        def _calc_start_values(rng):
            """Get starting values for sliders use a data range"""
            lowstart = ((rng[1] - rng[0]) * 0.25) + rng[0]
            highstart = ((rng[1] - rng[0]) * 0.75) + rng[0]
            return lowstart, highstart

        # Now set up the widgets
        lowstart, highstart = _calc_start_values(self.valid_range)
        lowstart = default_params.get("dmin", lowstart)
        highstart = default_params.get("dmax", highstart)
        minsl = widgets.FloatSlider(min=self.valid_range[0],
                            max=self.valid_range[1],
                            value=lowstart,
                            continuous_update=self.continuous_update)
        maxsl = widgets.FloatSlider(min=self.valid_range[0],
                            max=self.valid_range[1],
                            value=highstart,
                            continuous_update=self.continuous_update)

        def _update_slider_ranges(new_rng):
            """Updates the slider ranges when switching scalars"""
            vmin, vmax = np.nanmin([new_rng[0], minsl.min]), np.nanmax([new_rng[1], minsl.max])
            # Update to the total range
            minsl.min = vmin
            minsl.max = vmax
            maxsl.min = vmin
            maxsl.max = vmax
            lowstart, highstart = _calc_start_values(new_rng)
            minsl.value = lowstart
            maxsl.value = highstart
            minsl.min = new_rng[0]
            minsl.max = new_rng[1]
            maxsl.min = new_rng[0]
            maxsl.max = new_rng[1]
            return lowstart, highstart


        def update(dmin, dmax, invert, continuous, **kwargs):
            """Update the threshold"""
            if dmax < dmin:
                # If user chooses a min that is more than max, correct them:
                # Set max threshold as 1 percent of the range more than min
                dmax = dmin + (self.valid_range[1] - self.valid_range[0]) * 0.01
                maxsl.value = dmax

            scalars = kwargs.get('scalars')

            # Update the sliders if scalar is changed
            self.valid_range = self.input_dataset.get_data_range(arr=scalars, preference=preference)
            if self._last_scalars != scalars:
                self._last_scalars = scalars
                # Update to the new range
                dmin, dmax = _update_slider_ranges(self.input_dataset.get_data_range(scalars))

            # Run the threshold
            self.output_dataset = self.input_dataset.threshold([dmin, dmax],
                    scalars=scalars, continuous=continuous, preference=preference,
                    invert=invert)

            # Update the plotter
            self.plotter.subplot(*self.loc)
            self._update_plotting_params(**kwargs)
            self.plotter.remove_actor(self._data_to_update, reset_camera=False)
            if self.output_dataset.n_points == 0 and self.output_dataset.n_cells == 0:
                pass
            else:
                self._data_to_update = self.plotter.add_mesh(self.output_dataset,
                    reset_camera=False, loc=self.loc, **self.display_params)

            self._need_to_update = False


        # Create/display the widgets
        scalars = self._get_scalar_names()
        name = default_params.get("scalars", scalars[0])
        idx = scalars.index(name)
        del scalars[idx]
        scalars.insert(0, name)
        return interact(update, dmin=minsl, dmax=maxsl,
                        scalars=scalars,
                        invert=default_params.get('invert', False),
                        continuous=False)
Beispiel #40
0
def interactive_budgetset(budgetsettype, **kwargs):

    kwargs.setdefault("x1max", 10)
    kwargs.setdefault("x2max", 10)

    if budgetsettype == "exogenous":

        widgets.interact(
            _interactive_budgetset_exogenous,
            p1=widgets.FloatSlider(description="$p_1$",
                                   min=0.1,
                                   max=5,
                                   step=0.05,
                                   value=2),
            p2=widgets.FloatSlider(description="$p_2$",
                                   min=0.1,
                                   max=5,
                                   step=0.05,
                                   value=1),
            I=widgets.FloatSlider(description="$I$",
                                  min=0.1,
                                  max=20,
                                  step=0.10,
                                  value=5),
            par=widgets.fixed(kwargs),
        )

    elif budgetsettype == "endogenous":

        widgets.interact(
            _interactive_budgetset_endogenous,
            p1=widgets.FloatSlider(description="$p_1$",
                                   min=0.1,
                                   max=5,
                                   step=0.05,
                                   value=2),
            p2=widgets.FloatSlider(description="$p_2$",
                                   min=0.1,
                                   max=5,
                                   step=0.05,
                                   value=1),
            e1=widgets.FloatSlider(description="$e_1$",
                                   min=0.0,
                                   max=5,
                                   step=0.05,
                                   value=3),
            e2=widgets.FloatSlider(description="$e_2$",
                                   min=0.0,
                                   max=5,
                                   step=0.05,
                                   value=4),
            par=widgets.fixed(kwargs),
        )

    elif budgetsettype == "kinked":

        widgets.interact(
            _interactive_budgetset_kink,
            p1=widgets.FloatSlider(description="$p_1$",
                                   min=0.1,
                                   max=5,
                                   step=0.05,
                                   value=1),
            kink_point=widgets.FloatSlider(description="$\\overline{x}_1$",
                                           min=0.1,
                                           max=5,
                                           step=0.05,
                                           value=2),
            kink_slope=widgets.FloatSlider(description="$\\Delta_1$",
                                           min=-5,
                                           max=5,
                                           step=0.10,
                                           value=-1),
            p2=widgets.FloatSlider(description="$p_2$",
                                   min=0.1,
                                   max=5,
                                   step=0.05,
                                   value=1),
            I=widgets.FloatSlider(description="$I$",
                                  min=0.10,
                                  max=20,
                                  step=0.10,
                                  value=10),
            par=widgets.fixed(kwargs),
        )
Beispiel #41
0
def manual_ps(data, notebook=False):
    """
    Manual Phase correction using matplotlib

    A matplotlib widget is used to manually correct the phase of a Fourier
    transformed dataset. If the dataset has more than 1 dimensions, the first
    trace will be picked up for phase correction.  Clicking the 'Set Phase'
    button will print the current linear phase parameters to the console.
    A ipywidget is provided for use with Jupyter Notebook to avoid changing
    backends. This can be accessed with notebook=True option in this function

    .. note:: Needs matplotlib with an interactive backend.

    Parameters
    ----------
    data : ndarray
        Array of NMR data.
    notebook : Bool
        True for plotting interactively in Jupyter Notebook
        Uses ipywidgets instead of matplotlib widgets

    Returns
    -------
    p0, p1 : float
        Linear phase correction parameters. Zero and first order phase
        corrections in degrees calculated from pc0, pc1 and pivot displayed
        in the interactive window.

    Examples
    --------
    >>> import nmrglue as ng
    >>> p0, p1 = ng.process.proc_autophase.manual_ps(data)
    >>> # do manual phase correction and close window
    >>> phased_data = ng.proc_base.ps(data, p0=p0, p1=p1)

    In  [1] # if you are using the Jupyter Notebook
    In  [2] ng.process.proc_autophase.manual_ps(data)
    Out [2] # do manual phase correction. p0 and p1 values will be updated
            # continuously as you do so and are printed below the plot
    In  [3] phased_data = ng.proc_base.ps(data, p0=p0, p1=p1)

    """

    if len(data.shape) == 2:
        data = data[0, ...]
    elif len(data.shape) == 3:
        data = data[0, 0, ...]
    elif len(data.shape) == 4:
        data = data[0, 0, 0, ...]

    if notebook:
        from ipywidgets import interact, fixed
        import matplotlib.pyplot as plt

        def phasecorr(dataset, phcorr0, phcorr1, pivot):
            fig, ax = plt.subplots(figsize=(10, 7))
            phaseddata = dataset * np.exp(
                1j *
                (phcorr0 + phcorr1 *
                 (np.arange(-pivot, -pivot + dataset.size) / dataset.size)))

            ax.plot(np.real(phaseddata))
            ax.set(ylim=(np.min(np.real(data)) * 2, np.max(np.real(data)) * 2))
            ax.axvline(pivot, color='r', alpha=0.5)
            plt.show()

            p0 = np.round(
                (phcorr0 - phcorr1 * pivot / dataset.size) * 360 / 2 / np.pi,
                3)
            p1 = np.round(phcorr1 * 360 / 2 / np.pi, 3)

            print('p0 =', p0, 'p1 =', p1)

        interact(phasecorr,
                 dataset=fixed(data),
                 phcorr0=(-np.pi, np.pi, 0.01),
                 phcorr1=(-10 * np.pi, 10 * np.pi, 0.01),
                 pivot=(0, data.size, 1))

    else:

        from matplotlib.widgets import Slider, Button
        import matplotlib.pyplot as plt

        plt.subplots_adjust(left=0.25, bottom=0.35)

        interactive, = plt.plot(data.real, lw=1, color='black')

        axcolor = 'white'
        axpc0 = plt.axes([0.25, 0.10, 0.65, 0.03], facecolor=axcolor)
        axpc1 = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)
        axpiv = plt.axes([0.25, 0.20, 0.65, 0.03], facecolor=axcolor)
        axpst = plt.axes([0.25, 0.25, 0.15, 0.04], facecolor=axcolor)

        spc0 = Slider(axpc0, 'p0', -360, 360, valinit=0)
        spc1 = Slider(axpc1, 'p1', -360, 360, valinit=0)
        spiv = Slider(axpiv, 'pivot', 0, data.size, valinit=0)
        axps = Button(axpst, 'Set Phase', color=axcolor)

        def update(val):
            pc0 = spc0.val * np.pi / 180
            pc1 = spc1.val * np.pi / 180
            pivot = spiv.val
            interactive.set_ydata(
                (data * np.exp(1.0j *
                               (pc0 +
                                (pc1 * np.arange(-pivot, -pivot + data.size) /
                                 data.size))).astype(data.dtype)).real)
            plt.draw()

        def setphase(val):
            p0 = spc0.val - spc1.val * spiv.val / data.size
            p1 = spc1.val
            print(p0, p1)

        spc0.on_changed(update)
        spc1.on_changed(update)
        spiv.on_changed(update)
        axps.on_clicked(setphase)

        plt.show(block=True)

        p0 = spc0.val - spc1.val * spiv.val / data.size
        p1 = spc1.val
        return p0, p1
Beispiel #42
0
lookuptype_widget.observe(update_by_type,'value')
location_widget.observe(update_geneid, 'value')
strand_widget.observe(update_geneid, 'value')
geneid_widget.observe(update_refseqid,'value')

display(widgets.HTML(value="<h5>Updates:</h5><p>" + updates))
display(widgets.HTML(value="<h3>Select Region</h3>"))

### Define INTERACT: All interdependent widgets must be in here ###
def printer(lookuptype,loc, strand, geneid,refseqid):
    print("")
interact(printer,
         lookuptype = lookuptype_widget,
         loc=location_widget,
         strand=strand_widget,
         geneid=geneid_widget,
         refseqid = refseqid_widget,
         continuous_update=False)


### Select File ###
all_files = os.listdir(default_track_folder)
file_types = ["bam","bw"]
file_names = []
for f in all_files:
    if f.split(".")[-1] in file_types:
        file_names.append(f)
file_widget = widgets.SelectMultiple(
    options=file_names,
    disabled=False
Beispiel #43
0
plot_mSS_widget = widgets.Checkbox(value=True,
                                   description='Plot sustainable $c$ line',
                                   disabled=False)

# Define a check box for whether to show the target annotation
show_targ_widget = widgets.Checkbox(value=True,
                                    description='Show target $(m,c)$',
                                    disabled=False)

# Make an interactive plot of the tractable buffer stock solution

# To make some of the widgets not appear, replace X_widget with fixed(desired_fixed_value) in the arguments below.
interact(
    makeTBSplot,
    DiscFac=DiscFac_widget,
    CRRA=CRRA_widget,
    # We can fix a parameter using the fixed() operator
    Rfree=fixed(TBS_dictionary['Rfree']),
    #         Rfree = Rfree_widget,   # This is the line which, when uncommented, would make Rfree a slider
    PermGroFac=PermGroFac_widget,
    UnempPrb=UnempPrb_widget,
    mMin=mMin_widget,
    mMax=mMax_widget,
    cMin=cMin_widget,
    cMax=cMax_widget,
    show_targ=show_targ_widget,
    plot_emp=plot_emp_widget,
    plot_ret=plot_ret_widget,
    plot_mSS=plot_mSS_widget,
)
Beispiel #44
0
def group_interaction_viewer(df, sortBy, metal = None):
    '''A wrapper function that zooms in to a group in a protein structure and
    highlight its interacting atoms. The input dataframe should be generated
    from the GroupInteractionExtractor class.

    References
    ----------
        GroupInteractionExtractor:
        https://github.com/sbl-sdsc/mmtf-pyspark/blob/master/mmtfPyspark/interactions/groupInteractionExtractor.py

    Attributes
    ----------
        df (dataframe): the dataframe generated from GroupIneteractionExtractor
        sort_by (str): the q value to sort by ['q4','q5','q6']
    '''

    # Filter by metal
    if metal is not None:
        df = df[df["element0"] == metal]

    # Sort dataframe based on sortBy parameter (q4-6 values)
    df = df.sort_values([sortBy], ascending = False).dropna(subset=[sortBy])
    if sortBy in ['q4','q5']:
        q = 'q' + str(int(sortBy[-1]) + 1)
        df = df[df[q] != np.nan]

    i_widget = IntSlider(
        min=0, max=df.shape[0] - 1, description='Structure', continuous_update=False)

    def get_neighbors_chain(i):
        return [df[f'chain{j}'].iloc[i] for j in range(1, 7) if df[f'element{j}'] is not None]

    def get_neighbors_group(i):
        return [df[f'groupNum{j}'].iloc[i] for j in range(1, 7) if df[f'element{j}'] is not None]

    def get_neighbors_elements(i):
        elements = [df[f'element{j}'].iloc[i]
                    for j in range(1, 7) if df[f'element{j}'] is not None]
        return [str(e).upper() for e in elements]

    def view3d(i=0):
        '''Simple structure viewer that uses py3Dmol to view PDB structure by
        indexing the list of PDBids
        Attributes
        ----------
        i (int): index of the protein if a list of PDBids
        '''

        structures = df['pdbId'].iloc
        groups = df['groupNum0'].iloc
        chains = df['chain0'].iloc
        elements = df['element0'].iloc
        ori = str(df[sortBy].iloc[i])[:5]

        print(f"PDBId: {structures[i]}    chain: {chains[i]}    element:    {elements[i]}")
        print(f"{sortBy}: {ori}")

        viewer = py3Dmol.view(query='pdb:' + structures[i], width=700, height=700)
        neighbors = {'resi': get_neighbors_group(i), 'chain': get_neighbors_chain(i)}
        metal = {'resi': groups[i], 'atom': str(elements[i]).upper(), 'chain': chains[i]}

        viewer.setStyle(neighbors, {'stick': {'colorscheme': 'orangeCarbon'}})
        viewer.setStyle(metal, {'sphere': {'radius': 0.5, 'color': 'gray'}})

        viewer.zoomTo(neighbors)
        return viewer.show()

    return interact(view3d, i=i_widget)
def CDM(L_dev,
        Y_dev,
        k=2,
        sig=0.01,
        policy='new',
        verbose=False,
        return_more_info=False):
    # create pd dataframe
    Complete_dev = np.concatenate((np.array([Y_dev]).T, L_dev), axis=1)
    df = pd.DataFrame(data=Complete_dev,
                      columns=["GT"] +
                      ["LF_" + str(i) for i in range(L_dev.shape[1])])

    def create_CT_tables(df, L_dev, k):
        """create all combinations of contingency table's of {LF_i, LF_j, GT}"""
        CT_list = []
        for i in range(L_dev.shape[1]):
            for j in [k for k in range(i, L_dev.shape[1]) if k != i]:
                CT = pd.crosstab([df['GT'], df['LF_' + str(i)]],
                                 df['LF_' + str(j)],
                                 margins=False)
                CT = CT.reindex(index=[(m, n) for m in range(0, k)
                                       for n in range(-1, k)],
                                columns=list(range(-1, k)),
                                fill_value=0)
                CT_list.append(CT)
        return CT_list

    def show_CT(q, CT_list):
        """function to return qth CT at index q-1 of CT_list"""
        return CT_list[q - 1]

    # create and show all CT's (if verbose) with slider applet
    CT_list = create_CT_tables(
        df, L_dev, k)  # create all combinations of Contingency Tables
    if verbose:
        print("No of tables = Choosing 2 from " + str(L_dev.shape[1]) +
              " LFs = " + str(L_dev.shape[1]) + "C2 = " + str(len(CT_list)))
        #print("Note: Showing subtables where CI is not clearly evident")
        interact(show_CT,
                 q=IntSlider(min=1, max=len(CT_list), value=0, step=1),
                 CT_list=fixed(CT_list))

    def get_conditional_dependencies(CT_list, sig, k, delta=0):
        """peform 3-way table chi-square independence test and obtain test statistic chi_square 
		(or corresponding p-value) for each CT table where each CT-table is a ({k+1}^{no of other LFs})x(k+1)x(k+1) matrix
		https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.chi2_contingency.html"""
        CD_edges = []
        CD_nodes = []
        CD_edges_p_vals = []
        p_vals_sum_dict = {}
        CT_reduced_list = []
        count = 0
        #n_bad = 0
        for CT in CT_list:
            count += 1
            Z = k  # there are (k) GT values
            CT_reshaped = np.reshape(CT.values, (Z, k + 1, k + 1))

            if policy == 'old':
                p_val_tot, CT_reduced = get_p_total_old_policy(
                    CT_reshaped, k, Z, delta, sig, count, verbose,
                    return_more_info
                )  # Older policy of one round of 0 row/col reduction and then adding delta
            else:
                p_val_tot, CT_reduced = get_p_total_new_policy(
                    CT_reshaped, k, Z, sig, count, verbose,
                    return_more_info)  # newer policy of complete reduction
            CT_reduced_list.append(CT_reduced)
            # checking if total p_value is lesser than chosen sig
            if p_val_tot < sig:
                digits_LF1 = CT.index.names[1][3:]
                digits_LF2 = CT.columns.name[
                    3:]  # 3rd index onwards to remove LF_ (3 characters)
                CD_edges.append((int(digits_LF1), int(digits_LF2)))
                CD_edges_p_vals.append(p_val_tot)

        #print info
        edges_info_dict = {}
        edges_info_dict['CD_edges'] = CD_edges
        edges_info_dict['CD_edges_p_vals'] = CD_edges_p_vals
        if verbose:
            edges_df = pd.DataFrame(edges_info_dict)
            print(edges_df)

        return edges_info_dict, CT_reduced_list

    # retrieve modified CTs & tuples of LFs that are conditionally independent
    edges_info_dict, CT_reduced_list = get_conditional_dependencies(CT_list,
                                                                    sig=sig,
                                                                    k=k,
                                                                    delta=1)

    # display reduced contingency tables' submatrices whose all elements = delta is not true
    if verbose:
        non_delta_tuple_indices = []
        for q in range(len(CT_reduced_list)):
            for r in range(len(CT_reduced_list[0])):
                delta = 1
                if ~(CT_reduced_list[q][r] == delta).all():
                    non_delta_tuple_indices.append(
                        ((q, r), (q, r))
                    )  # apending a tuple of tuples because first part of outer tuple is key and second is value passed gy slider to fn

        def show_CT_sub_matrices(t, CT_reduced_list):
            """function to return qth CT at index q-1 of CT_list"""
            return CT_reduced_list[t[0]][t[1]]

        print(
            "The reduced and modified contingency tables with non-delta values are given below"
        )
        interact(
            show_CT_sub_matrices,
            t=Dropdown(
                description='index tuples (table number, submatrix number)',
                options=non_delta_tuple_indices),
            CT_reduced_list=fixed(CT_reduced_list))

    if return_more_info:
        return edges_info_dict
    else:
        return edges_info_dict['CD_edges']
Beispiel #46
0
lGDP_Asia = lGDP_world[Asia_countries]
lCO2_Asia = lCO2_world[Asia_countries]

MAF_countries = list({
    'DZA', 'AGO', 'BHR', 'BEN', 'BWA', 'BFA', 'BDI', 'CMR', 'CPV', 'CAF',
    'TCD', 'COM', 'COD', 'COG', 'CIV', 'DJI', 'EGY', 'GNQ', 'ERI', 'ETH',
    'GAB', 'GMB', 'GHA', 'GIN', 'GNB', 'IRN', 'IRQ', 'ISR', 'JOR', 'KEN',
    'KWT', 'LBN', 'LSO', 'LBR', 'LBY', 'MDG', 'MWI', 'MLI', 'MRT', 'MUS',
    'MAR', 'MOZ', 'NAM', 'NER', 'NGA', 'PSE', 'OMN', 'QAT', 'RWA', 'SAU',
    'SEN', 'SLE', 'SOM', 'ZAF', 'SSD', 'SDN', 'SWZ', 'SYR', 'TGO', 'TUN',
    'UGA', 'ARE', 'TZA', 'YEM', 'ZMB', 'ZWE'
}.intersection(set(World_countries)))

lGDP_MAF = lGDP_world[MAF_countries]
lCO2_MAF = lCO2_world[MAF_countries]

LAM_countries = list({
    'ARG', 'ABW', 'BHS', 'BRB', 'BLZ', 'BOL', 'BRA', 'CHL', 'COL', 'CRI',
    'CUB', 'DOM', 'ECU', 'SLV', 'GRD', 'GTM', 'GUY', 'HTI', 'HND', 'JAM',
    'MEX', 'NIC', 'PAN', 'PRY', 'PER', 'SUR', 'TTO', 'VIR', 'URY', 'VEN'
}.intersection(set(World_countries)))

lGDP_LAM = lGDP_world[LAM_countries]
lCO2_LAM = lCO2_world[LAM_countries]

# In[30]:

interact(FlexPlot,
         region=['World', 'OECD', 'REF', 'Asia', 'MAF', 'LAM'],
         year=widgets.IntSlider(min=1960, max=2018, step=1, value=1960))
Beispiel #47
0
 def find_fibre_edges(self):
     interact(self.plot_fibre_edges,
              spacing=(10, 30, 0.1),
              offset=(0, 512, 1))
Beispiel #48
0
    def plot(self,
             input_image: Image or List[Image] = None,
             resolve_kwargs: dict = None,
             interval: float = None,
             **kwargs):
        ''' Visualizes the output of the feature
        Resolves the feature and visualizes the result. If the output is an Image,
        show it using `pyplot.imshow`. If the output is a list, create an `Animation`.
        For notebooks, the animation is played inline using `to_jshtml()`. For scripts,
        the animation is played using the matplotlib backend.

        Any parameters in kwargs will be passed to `pyplot.imshow`.

        Parameters
        ----------
        input_image : Image or List[Image], optional
            Passed as argument to `resolve` call
        resolve_kwargs : dict, optional
            Passed as kwarg arguments to `resolve` call
        interval : float
            The time between frames in animation in ms. Default 33.
        kwargs
            keyword arguments passed to the method pyplot.imshow()
        '''

        import matplotlib.pyplot as plt
        import matplotlib.animation as animation
        from IPython.display import HTML, display

        if input_image is not None:
            input_image = [Image(input_image)]

        output_image = self.resolve(input_image, **(resolve_kwargs or {}))

        # If a list, assume video
        if isinstance(output_image, Image):
            # Single image
            plt.imshow(output_image[:, :, 0], **kwargs)
            plt.show()

        else:
            # Assume video
            fig = plt.figure()
            images = []
            plt.axis("off")
            for image in output_image:
                images.append([plt.imshow(image[:, :, 0], **kwargs)])

            interval = (interval or output_image[0].get_property("interval")
                        or (1 / 30 * 1000))

            anim = animation.ArtistAnimation(fig,
                                             images,
                                             interval=interval,
                                             blit=True,
                                             repeat_delay=0)

            try:
                get_ipython  # Throws NameError if not in Notebook
                display(HTML(anim.to_jshtml()))
                return anim

            except NameError as e:
                # Not in an notebook
                plt.show()

            except RuntimeError as e:
                # In notebook, but animation failed
                import ipywidgets as widgets
                Warning(
                    "Javascript animation failed. This is a non-performant fallback."
                )

                def plotter(frame=0):
                    plt.imshow(output_image[frame][:, :, 0], **kwargs)
                    plt.show()

                return widgets.interact(plotter,
                                        frame=widgets.IntSlider(
                                            value=0,
                                            min=0,
                                            max=len(images) - 1,
                                            step=1))
Beispiel #49
0
def convolution_demo3():
    interact(convolution_demo3_plot,
             h=signals,
             T=(0.05, 0.8, 0.05),
             steps=(1, 10, 1),
             continuous_update=False)
Beispiel #50
0
                 title=titleFunc,
                 xTitle='hour (h)',
                 yTitle='$' + var1.lat + '(' + var1.unitVar + ')$',
                 showlegend=True)
    fig.write_image("../images/plot1VarDay.png")
    lol = fig.write_html("../images/plot1VarDay.html", include_mathjax='cdn')
    return fig


# In[58]:

interact(plot1VarDay,
         NHour=fixed(96),
         ControlModel=[(tabNameDataFrame[i], i) for i in range(0, 5)],
         dayStart=IntSlider(min=0,
                            max=df['hour(h)'].size // 24 - 4,
                            step=1,
                            value=170),
         var1=[(tabVar[i].varDescription, tabVar[i])
               for i in range(1, len(nameColumns))])

# In[59]:

interactive_plot1VarDay = interactive(
    plot1VarDay,
    NHour=fixed(96),
    ControlModel=[(tabNameDataFrame[i], i) for i in range(0, 5)],
    dayStart=IntSlider(min=0,
                       max=df['hour(h)'].size // 24 - 4,
                       step=1,
                       value=170),
Beispiel #51
0
    def surface_plotter(self,
                        colormap=None,
                        figsize=np.array([600, 600]),
                        figlims=np.array(3 * [[-100, 100]]),
                        show_zeroes=True,
                        **kwargs):
        """
        Visualise a surface mesh (with overlay) inside notebooks.

        Basic functionality:
        Read mesh and overlay data
        Setup the interactive widget
        Set defaults for plotting

        Parameters
        ----------
        surface: str, gifti object
            Path to surface file in gifti or FS surface format or an
            already loaded gifti object of surface
        overlay: str, gifti object
            Path to overlay file in gifti or FS annot or anatomical
            (.curv,.sulc,.thickness) format or an already loaded
            gifti object of overlay, default None
        colormap: string
            A matplotlib colormap, default summer
        figsize: ndarray
            Size of the figure to display, default [600,600]
        figlims: ndarray
            x,y and z limits of the axes, default
            [[-100,100],[-100,100],[-100,100]]
        show_zeroes: bool
            Display vertices with intensity = 0, default True

        """
        # set default colormap options & add them to the kwargs
        if colormap is None:
            kwargs['colormap'] = ['viridis'] + \
                sorted(m for m in plt.cm.datad if not m.endswith("_r"))
        elif type(colormap) is str:
            # fix cmap if only one given
            kwargs['colormap'] = fixed(colormap)

        kwargs['figsize'] = fixed(figsize)
        kwargs['figlims'] = fixed(figlims)

        if isinstance(self.meshfile, Path):
            # if mesh has not been loaded before, load it
            if self.meshfile.suffix == '.gii':
                # load gifti file
                self.meshfile = nb.load(self.meshfile)
                try:
                    vertex_spatial = self.meshfile.darrays[0].data
                    vertex_edges = self.meshfile.darrays[1].data
                    x, y, z = vertex_spatial.T
                except:
                    raise ValueError('Please provide a valid gifti file.')
            else:
                # load freesurfer file
                fsgeometry = nb.freesurfer.read_geometry(self.meshfile)
                x, y, z = fsgeometry[0].T
                vertex_edges = fsgeometry[1]

        elif isinstance(self.meshfile, nb.gifti.gifti.GiftiImage):
            # if mesh has been loaded as a GiftiImage, format the data
            try:
                vertex_spatial = self.meshfile.darrays[0].data
                vertex_edges = self.meshfile.darrays[1].data
                x, y, z = vertex_spatial.T
            except:
                raise ValueError('Please provide a valid gifti file.')

        if len(self.overlayfiles) > 0:
            overlays = np.zeros((len(x), len(self.overlayfiles)))
            for i, overlayfile in enumerate(self.overlayfiles):

                filename, file_extension = os.path.splitext(overlayfile)

                if file_extension is '.gii':
                    overlay = nb.load(overlayfile)
                    try:
                        overlays[:, i] = overlay.darrays[0].data
                    except:
                        raise ValueError('Please provide a valid gifti file')

                elif (file_extension in ('.annot', '')):
                    annot = nb.freesurfer.read_annot(overlayfile)
                    overlays[:, i] = annot[0]

                elif (file_extension in ('.curv', '.thickness', '.sulc')):
                    overlays[:, i] = nb.freesurfer.read_morph_data(overlayfile)

                if isinstance(overlayfile, nb.gifti.gifti.GiftiImage):
                    try:
                        overlays[:, i] = overlayfile.darrays[0].data
                    except:
                        raise ValueError('Please provide a valid gifti file')

                if not show_zeroes:
                    pass
                    # try:
                    #     mkeep, mkill = self.zmask(surface, overlay)
                    # except:
                    #     raise ValueError(
                    #         'Overlay required for medial wall masking.'
                    #         )
        else:
            overlays = None

        kwargs['triangles'] = fixed(vertex_edges)
        kwargs['x'] = fixed(x)
        kwargs['y'] = fixed(y)
        kwargs['z'] = fixed(z)
        kwargs['overlays'] = fixed(overlays)

        if len(self.overlayfiles) < 2:
            frame = fixed(0)
        else:
            frame = IntSlider(value=0, min=0, max=len(self.overlayfiles) - 1)

        interact(self._plot_surface, frame=frame, **kwargs)
        display(self.fig)
Beispiel #52
0
def reset_plots_scan(corr, save_figure=False):
    global sour, expt, band, polar, basel, scan_id_loc, goo, goosc
    #goosc = 0
    widget_source = widgets.Dropdown(
        options=list(corr.source.unique()) + ['all sources'],
        value=sour,
        description='Source:',
        disabled=False,
    )
    widget_experiment = widgets.Dropdown(
        options=[3597, 3598, 3599, 3600, 3601, 'all expt'],
        value=expt,
        description='Experiment:',
        disabled=False,
    )
    widget_band = widgets.Dropdown(
        options=['lo', 'hi', 'both bands'],
        value=band,
        description='Band:',
        disabled=False,
    )
    widget_polarization = widgets.Dropdown(
        options=list(corr.polarization.unique()) + ['both pol', 'cross pol'],
        value=polar,
        description='Polarization:',
        disabled=False,
    )
    widget_baseline = widgets.Dropdown(
        options=sorted(list(corr.baseline.unique())),
        value=basel,
        description='Baseline:',
        disabled=False,
    )
    widget_scan = widgets.Dropdown(
        options=list(goo.scan_id.unique()),
        value=list(goo.scan_id.unique())[0],
        description='Scan ID:',
        disabled=False,
    )

    def interact_source(x):
        global sour
        sour = x

    def interact_experiment(x):
        global expt
        expt = x

    def interact_band(x):
        global band
        band = x

    def interact_polarization(x):
        global polar
        polar = x

    def interact_baseline(x):
        global basel
        basel = x

    def interact_scan(x):
        global scanid
        scanid = x

    interact(interact_source, x=widget_source)
    interact(interact_experiment, x=widget_experiment)
    interact(interact_band, x=widget_band)
    interact(interact_polarization, x=widget_polarization)
    interact(interact_baseline, x=widget_baseline)
    interact(interact_scan, x=widget_scan)
    button = widgets.Button(description="Add plot")
    display(button)

    def on_button_clicked(b):
        global goosc
        goosc = plot_scan_data(corr, save_figure)
        #print(goosc.source.unique())
        #return goosc

    button.on_click(on_button_clicked)
Beispiel #53
0
    def tool(self, default_params=None, **kwargs):
        if default_params is None:
            default_params = {}
        preference = self.display_params['preference']

        def _calc_start_value(rng):
            """Get starting value for slider using a data range"""
            return ((rng[1] - rng[0]) * 0.5) + rng[0]

        # Now set up the widget
        start = _calc_start_value(self.valid_range)
        start = default_params.get("value", start)
        valsl = widgets.FloatSlider(min=self.valid_range[0],
                            max=self.valid_range[1],
                            value=start,
                            continuous_update=self.continuous_update)

        def _update_slider_range(new_rng):
            """Updates the slider ranges when switching scalars"""
            vmin, vmax = np.nanmin([new_rng[0], valsl.min]), np.nanmax([new_rng[1], valsl.max])
            # Update to the total range
            valsl.min = vmin
            valsl.max = vmax
            start = _calc_start_value(new_rng)
            valsl.value = start
            valsl.min = new_rng[0]
            valsl.max = new_rng[1]
            return start


        def update(value, **kwargs):
            """Update the contour"""
            scalars = kwargs.get('scalars')

            # Update the sliders if scalar is changed
            self.valid_range = self.input_dataset.get_data_range(arr=scalars, preference=preference)
            if self._last_scalars != scalars:
                self._last_scalars = scalars
                # Update to the new range
                value = _update_slider_range(self.input_dataset.get_data_range(scalars))

            # Run the threshold
            self.output_dataset = self.input_dataset.contour([value],
                    scalars=scalars, preference=preference)

            # Update the plotter
            self.plotter.subplot(*self.loc)
            self._update_plotting_params(**kwargs)
            self.plotter.remove_actor(self._data_to_update, reset_camera=False)
            if self.output_dataset.n_points == 0 and self.output_dataset.n_cells == 0:
                pass
            else:
                self._data_to_update = self.plotter.add_mesh(self.output_dataset,
                    reset_camera=False, loc=self.loc, **self.display_params)

            self._need_to_update = False


        # Create/display the widgets
        # NOTE: Contour filter can only contour by point data
        scalars = self._get_scalar_names(limit='point')
        name = default_params.get("scalars", scalars[0])
        idx = scalars.index(name)
        del scalars[idx]
        scalars.insert(0, name)
        return interact(update, value=valsl, scalars=scalars)
Beispiel #54
0
def reset_plots_amplitude(corr, save_figure=False):
    global sour, expt, band, polar, basel
    widget_source = widgets.Dropdown(
        options=list(corr.source.unique()) + ['all sources'],
        value='3C279',
        description='Source:',
        disabled=False,
    )
    widget_experiment = widgets.Dropdown(
        options=[3597, 3598, 3599, 3600, 3601, 'all expt'],
        value=3597,
        description='Experiment:',
        disabled=False,
    )
    widget_band = widgets.Dropdown(
        options=['lo', 'hi', 'both bands'],
        value='lo',
        description='Band:',
        disabled=False,
    )
    widget_polarization = widgets.Dropdown(
        options=list(corr.polarization.unique()) + ['both pol', 'cross pol'],
        value='LL',
        description='Polarization:',
        disabled=False,
    )
    widget_baseline = widgets.Dropdown(
        options=sorted(list(corr.baseline.unique())),
        value=list(corr.baseline.unique())[0],
        description='Baseline:',
        disabled=False,
    )

    def interact_source(x):
        global sour
        sour = x

    def interact_experiment(x):
        global expt
        expt = x

    def interact_band(x):
        global band
        band = x

    def interact_polarization(x):
        global polar
        polar = x

    def interact_baseline(x):
        global basel
        basel = x

    interact(interact_source, x=widget_source)
    interact(interact_experiment, x=widget_experiment)
    interact(interact_band, x=widget_band)
    interact(interact_polarization, x=widget_polarization)
    interact(interact_baseline, x=widget_baseline)
    button = widgets.Button(description="Add plot")
    display(button)

    def on_button_clicked(b):
        plot_box_data_amplitude(corr, save_figure)

    button.on_click(on_button_clicked)
Beispiel #55
0
 def display(self):
     widget = interact(self.solve_and_plot,
                       g_Na=IntSlider(value=5, min=0, max=30, step=1),
                       g_Ca=IntSlider(value=5, min=0, max=30, step=1),
                       g_K=IntSlider(value=5, min=0, max=30, step=1))
from __future__ import print_function
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets


def f(x):
    return x


interact(f, x=True)
Beispiel #57
0
    def tool(self, step=None, generate_triangles=False, contour=False,
             default_params=None, **kwargs):
        if default_params is None:
            default_params = {}
        if self.clean and self.input_dataset.active_scalar is not None:
            # This will clean out the nan values
            self.input_dataset = self.input_dataset.threshold()

        self.contour = contour

        x, y, z = self.input_dataset.center
        x = default_params.get("x", x)
        y = default_params.get("y", y)
        z = default_params.get("z", z)

        self._data_to_update = [None, None, None]
        self.output_dataset = pyvista.MultiBlock()
        self._old = [None, None, None]

        axes = ['x', 'y', 'z']

        def _update_slice(index, x, y, z):
            name = self.display_params.pop('name')
            self.plotter.subplot(*self.loc)
            self.plotter.remove_actor(self._data_to_update[index], reset_camera=False)
            self.output_dataset[index] = self.input_dataset.slice(normal=axes[index],
                    origin=[x,y,z], generate_triangles=generate_triangles, contour=self.contour)
            self._data_to_update[index] = self.plotter.add_mesh(self.output_dataset[index],
                    reset_camera=False, name='{}-{}'.format(name, index), **self.display_params)
            self._old[index] = [x,y,z][index]
            self.display_params['name'] = name

        def update(x, y, z, **kwargs):
            """Update the slices"""
            self._update_plotting_params(**kwargs)
            if x != self._old[0] or self._need_to_update:
                _update_slice(0, x, y, z)
            if y != self._old[1] or self._need_to_update:
                _update_slice(1, x, y, z)
            if z != self._old[2] or self._need_to_update:
                _update_slice(2, x, y, z)
            self._need_to_update = False

        # Set up the step sizes for the sliders
        if step is None:
            stepx = 0.05 * (self.input_dataset.bounds[1] - self.input_dataset.bounds[0])
            stepy = 0.05 * (self.input_dataset.bounds[3] - self.input_dataset.bounds[2])
            stepz = 0.05 * (self.input_dataset.bounds[5] - self.input_dataset.bounds[4])
        elif isinstance(step, collections.Iterable):
            stepx = step[0]
            stepy = step[1]
            stepz = step[2]
        else:
            stepx = step
            stepy = step
            stepz = step

        # Now set up the widgets
        xsl = widgets.FloatSlider(min=self.input_dataset.bounds[0]+stepx,
                            max=self.input_dataset.bounds[1]-stepx,
                            step=stepx,
                            value=x,
                            continuous_update=self.continuous_update)
        ysl = widgets.FloatSlider(min=self.input_dataset.bounds[2]+stepy,
                            max=self.input_dataset.bounds[3]-stepy,
                            step=stepy,
                            value=y,
                            continuous_update=self.continuous_update)
        zsl = widgets.FloatSlider(min=self.input_dataset.bounds[4]+stepz,
                            max=self.input_dataset.bounds[5]-stepz,
                            step=stepz,
                            value=z,
                            continuous_update=self.continuous_update)

        # Create/display the widgets
        return interact(update, x=xsl, y=ysl, z=zsl,
                        scalars=self._get_scalar_names())
def FrameViewerLong(df,
                    title="EEG",
                    ylabel='voltage (mV)',
                    xlabel=None,
                    downsample=10,
                    units='s',
                    spread=0,
                    annotations=None):

    from oio.open_ephys_io import ContinuousFile, load_continuous_tsd, is_sequence
    from .interval_set import IntervalSet
    # from .time_series import TsdFrame
    from .time_series import TimeUnits as tu

    if xlabel is None:
        xlabel = 'Time (' + units + ')'
    max_time = 30

    if is_sequence(df):
        if isinstance(df[0], str):
            df = [ContinuousFile(f) for f in df]
        x_min_df = df[0].start_time(units=units)
        x_max_df = df[0].end_time(units=units)
    else:
        x_min_df = df.start_time(units=units)
        x_max_df = df.end_time(units=units)

    if isinstance(df, pd.DataFrame):
        df = df.as_units(units)
        df1 = df[df.index < x_min_df + max_time]  # TODO use restrict
    else:
        df1 = load_continuous_tsd(df,
                                  t_min=tu.format_timestamps(x_min_df,
                                                             units=units),
                                  t_max=tu.format_timestamps(x_min_df +
                                                             max_time,
                                                             units=units),
                                  downsample=downsample).as_units(units)

    default_interval = 1
    plot = figure(plot_height=400,
                  plot_width=700,
                  title=title,
                  tools="crosshair,pan,reset,save,box_zoom",
                  x_axis_label=xlabel,
                  y_axis_label=ylabel)

    lines = []
    l = 0
    t = df1.index

    spread_vec = np.arange(len(df1.columns)) * spread
    for ix, x in enumerate(df1.columns):
        dd = {'t': t, x: df1[x] + spread_vec[ix]}
        source = ColumnDataSource(data=dd)
        lines.append(
            plot.line('t',
                      x,
                      source=source,
                      line_color=Spectral11[l % len(Spectral11)]))
        l += 1

    if annotations:
        for col, i_set in annotations.items():
            i_set = IntervalSet(x_min_df,
                                x_min_df + max_time,
                                time_units=units)
            i_set = i_set.as_units(units)

            for l in i_set.iterrows():
                box = BoxAnnotation(left=l[1]['start'],
                                    right=l[1]['end'],
                                    fill_alpha=0.1,
                                    fill_color=col)
                plot.add_layout(box)

    # noinspection PyShadowingNames
    def update_in(x_min=x_min_df, x_interval=default_interval):
        nonlocal df1

        if df1.index[0] > x_min or df1.index[-1] < x_min + x_interval:
            if isinstance(df, pd.DataFrame):
                df1 = df[((x_min - max_time / 2) < df.index)
                         & (df.index < (x_min + max_time / 2))]
            else:
                df1 = load_continuous_tsd(
                    df,
                    t_min=tu.format_timestamps(x_min - max_time / 2,
                                               units=units),
                    t_max=tu.format_timestamps(x_min + max_time / 2,
                                               units=units),
                    downsample=downsample).as_units(units)
            t = df1.index
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                for ix, x in enumerate(df1.columns):
                    lines[ix].data_source.data['t'] = t
                    lines[ix].data_source.data[x] = df1[x] + spread_vec[ix]
            push_notebook()
        plot.x_range.start = x_min
        plot.x_range.end = x_min + x_interval
        push_notebook()

    show(plot, notebook_handle=True)
    interact(update_in,
             x_min=(x_min_df, x_max_df, 0.5),
             x_interval=(0.2, 5, 0.2))
def interpolation_demo1():
    interact(interpolation_demo1_plot,
             N=(64, 512),
             cycles=(0, 64, 1),
             Q=(1, 20),
             continuous_update=False)
Beispiel #60
0
def highlight_col(x):
    r = 'background-color: #f2493a'
    y = 'background-color: #5d73fc'
    g = 'background-color: #2bba0f'
    df1 = pd.DataFrame('', index=x.index, columns=x.columns)
    df1.iloc[:, 4] = y
    df1.iloc[:, 5] = r
    df1.iloc[:, 6] = g
    
    return df1

def show_latest_cases(TOP):
    TOP = int(TOP)
    return country_df.sort_values('confirmed', ascending= False).head(TOP).style.apply(highlight_col, axis=None)

interact(show_latest_cases, TOP='10')

ipywLayout = widgets.Layout(border='solid 2px green')
ipywLayout.display='none' # uncomment this, run cell again - then the graph/figure disappears
widgets.VBox([fig], layout=ipywLayout)

world_map = folium.Map(location=[11,0], tiles="cartodbpositron", zoom_start=2, max_zoom = 6, min_zoom = 2)


for i in range(0,len(confirmed_df)):
    folium.Circle(
        location=[confirmed_df.iloc[i]['lat'], confirmed_df.iloc[i]['long']],
        fill=True,
        radius=(int((np.log(confirmed_df.iloc[i,-1]+1.00001)))+0.2)*50000,
        color='red',
        fill_color='indigo',