示例#1
0
    def __init__(self, callback_function, default_cmap):
        """
        Initialize a set of widgets that select a colorbar.

        Parameters:
        -----------
        callback_function: callable
            The function to call when activating/deactivating the range,
            or when changing the colormap
        default_cmap: string
            The name of the colormap that will be used when the widget is
            initialized
        """
        # Create the colormap widget
        available_cmaps = sorted(plt.colormaps())
        if default_cmap not in available_cmaps:
            default_cmap = 'jet'
        self.cmap = widgets.Select(options=available_cmaps, value=default_cmap)

        # Create the widgets for the range
        self.active = widgets.Checkbox(value=False)
        self.low_bound = widgets.FloatText(value=-5.)
        self.up_bound = widgets.FloatText(value=5.)
        self.exponent = widgets.FloatText(value=9.)

        # Add the callback function
        self.active.observe(callback_function, 'value', 'change')
        self.exponent.observe(callback_function, 'value', 'change')
        self.cmap.observe(callback_function, 'value', 'change')
示例#2
0
    def __init__(self, *args, **kwargs):
        super(Heartbeat, self).__init__(*args,
                                        **kwargs)  # initializes traitlets

        self.pulseout = widgets.FloatText(value=time.time())  #发出脉冲
        self.pulsein = widgets.FloatText(value=time.time())  #读取引脚脉冲
        self.link = widgets.jsdlink((self.pulseout, 'value'),
                                    (self.pulsein, 'value'))
        self.start()
示例#3
0
    def __init__(self, units: Units, trials: pynwb.epoch.TimeIntervals = None, unit_index=0, unit_controller=None,
                 sigma_in_secs=.05, ntt=1000):

        self.units = units

        super().__init__()

        if trials is None:
            self.trials = self.get_trials()
            if self.trials is None:
                self.children = [widgets.HTML('No trials present')]
                return
        else:
            self.trials = trials

        if unit_controller is None:
            nunits = len(units['spike_times'].data)
            unit_controller = widgets.Dropdown(options=[x for x in range(nunits)], value=unit_index,
                                               description='unit',
                                               layout=Layout(width='200px'))

        trial_event_controller = make_trial_event_controller(self.trials, layout=Layout(width='200px'))
        before_ft = widgets.FloatText(.5, min=0, description='before (s)', layout=Layout(width='200px'))
        after_ft = widgets.FloatText(2., min=0, description='after (s)', layout=Layout(width='200px'))

        self.gas = self.make_group_and_sort(window=False, control_order=False)

        self.controls = dict(
            units=fixed(units),
            trials=fixed(self.trials),
            sigma_in_secs=fixed(sigma_in_secs),
            ntt=fixed(ntt),
            index=unit_controller,
            after=after_ft,
            before=before_ft,
            start_label=trial_event_controller,
            gas=self.gas,
            # progress_bar=fixed(progress_bar)
        )

        out_fig = interactive_output(trials_psth, self.controls)

        self.children = [
            widgets.HBox([
                self.gas,
                widgets.VBox([
                    unit_controller,
                    trial_event_controller,
                    before_ft,
                    after_ft,
                ])
            ]),
            out_fig
        ]
示例#4
0
 def make_sources_tab(self):
     v = []
     for i in range(self.source_number.value):
         row_inputs = [
             widgets.FloatText(description="X", value=i),
             widgets.FloatText(description="Y", value=3),
             widgets.BoundedFloatText(description="Weight",
                                      min=.001,
                                      value=1)
         ]
         v.append(widgets.HBox(row_inputs))
     self.source_inputs = widgets.VBox(v)
     return self.source_inputs
示例#5
0
 def scale_dropdown_controller(change):
     if change['type'] == 'change' and change['name'] == 'value':
         self.convert_container.children = ()
         self.operation_data['scale'] = change['new']
         i = 0
         if change['new'] == 'ordinal':
             feature_values = self.scales_manager[
                 self.features_dropdown.value].aggregated_data.keys()
             for _ in feature_values:
                 i += 1
                 ordinal_dropdown = widgets.Dropdown(
                     value=None,
                     description=f'{i}. ',
                     options=feature_values)
                 ordinal_dropdown.observe(self.get_values_controller())
                 self.convert_container.children += (ordinal_dropdown, )
         elif change['new'] == 'interval':
             feature_values = self.scales_manager[
                 self.features_dropdown.value].aggregated_data.keys()
             for val in feature_values:
                 i += 1
                 interval_dropdown = widgets.FloatText(
                     value=1.0 + round(i / 10, 1),
                     step=0.1,
                     description=f'{val} :',
                     disabled=False,
                     style={'description_width': '50%'},
                 )
                 interval_dropdown.observe(self.get_values_controller())
                 self.convert_container.children += (
                     interval_dropdown, )
         self.convert_button.disabled = not (self.is_data_correct())
示例#6
0
    def make_gui(self):
        self.signature = signature(self.process)

        label = f"<b>{self.name}</b>"

        display(widgets.HTML(value=label))

        for i, arg_name in enumerate(self.signature.parameters):
            if i == 0:
                continue

            arg_type = self.signature.parameters[arg_name].annotation

            wd = dict(description=arg_name, value=self.params[arg_name])

            if arg_type is str:
                w = widgets.Text(**wd)
            elif arg_type is int:
                w = widgets.IntText(**wd)
            elif arg_type is float:
                w = widgets.FloatText(**wd)
            else:
                return

            w.observe(self.set_param)

            display(w)
示例#7
0
def InteractiveDipoleDecay(
    self, xyz_loc, Field, compvalue, sig=1e-2, Tmin=1e-5, Tmax=1e-2, Waveform="stepoff"
):
    ntime = 200
    srcLoc = np.r_[0.0, 0.0, 0.0]
    # orientation = "z"

    def foo(Component, Sigma, Scale):  # , Waveform="stepoff"):
        orientation = "z"
        # vals = []

        if Field == "E":
            unit = " (V/m)"
        elif Field == "H":
            unit = " (A/m)"
        elif Field == "dHdt":
            unit = " (A/m-s)"
        elif Field == "J":
            unit = " (A/m $^2$)"

        label = Field + Component + "-field " + unit
        t = np.logspace(np.log10(Tmin), np.log10(Tmax), ntime)
        valx, valy, valz = self.dataview.eval_TD(
            xyz_loc, srcLoc, np.r_[Sigma], t, orientation, self.dataview.func2D
        )
        if Component == "x" or Component == "X":
            val = valx.copy()
        elif Component == "y" or Component == "Y":
            val = valy.copy()
        elif Component == "z" or Component == "Z":
            val = valz.copy()

        plt.figure(figsize=(7, 5))
        ax = plt.subplot(111)
        if Scale == "log":
            valp, valn = DisPosNegvalues(val)
            ax.plot(t, valp, "k-")
            ax.plot(t, valn, "k--")

        elif Scale == "linear":
            ax.plot(t, val, "k-")
        ax.set_xscale("log")
        ax.set_yscale(Scale)
        ax.set_ylabel(label)
        ax.set_xlabel("Time (sec)")
        ax.grid(True)
        plt.show()

    Q3 = widgetify(
        foo,
        Component=widgets.ToggleButtons(
            options=["x", "y", "z"], value=compvalue, description="Comp."
        ),
        Sigma=widgets.FloatText(
            value=sig, continuous_update=False, description="$\sigma$ (S/m)"
        ),
        Scale=widgets.ToggleButtons(options=["log", "linear"])
        # ,Waveform=widgets.ToggleButtons(options=['stepoff','stepon','rampoff'], value='stepoff')
    )
    return Q3
示例#8
0
def msd_menu():
    input = widgets.Dropdown(description='Input data',
                             options=['Dictionary', 'Pickle', 'Text file'],
                             value='Dictionary')
    plot = widgets.Checkbox(description='Plot', value=True)
    fit = widgets.Checkbox(description='Fit MSD', value=True)
    points = widgets.IntText(description='Points', value=100)
    vel = widgets.FloatText(description='$ \\upsilon$ (px $s^{-1}$)',
                            value=100)
    tau = widgets.FloatText(description='$ \\tau $', value=0.5)
    refs = widgets.Checkbox(description='Slope reference', value=True)
    kind = widgets.Dropdown(options=['ABP', 'Quincke', 'Passive'],
                            description='MSD fit type',
                            value='ABP')
    save = widgets.Checkbox(description='Save', value=True)
    return widgets.VBox([input, plot, fit, kind, points, tau, vel, refs, save])
示例#9
0
 def get_widgets_per_param(param, value):
     if isinstance(value, float):
         return (param, widgets.FloatText(
             value=value,
             step=0.05,
             description=param.split('__')[1],
             continuous_update=False,
             disabled=False
         ))
     elif isinstance(value, int):
         return (param, widgets.IntText(
             value=value,
             step=1,
             description=param.split('__')[1],
             continuous_update=False,
             disabled=False
         ))
     elif isinstance(value, str):
         return (param, widgets.Text(
             value=value,
             description=param.split('__')[1],
             continuous_update=False,
             disabled=False
         ))
     else:
         return None
示例#10
0
    def main(self):
        self.media_wid = widgets.ToggleButtons(options=['Lif', 'Images'],
                                               description='Media Input',
                                               value='Lif')
        self.media_wid.observe(self.media_update, ['value'])

        # self.mode_wid = widgets.ToggleButtons(options=['multi', 'single'], description='Tracking mode',tooltips=['Multiple frame tracking', 'Single frame tracking. Which singles must be specified'])
        # self.mode_wid.observe(self.mode_update, ['value'])

        self.fmt = widgets.Dropdown(options=['.tif', '.png', '.jpg'],
                                    description='Frame format')

        self.initial_frame = widgets.IntText(description='Initial frame')

        self.nframes = widgets.IntText(description='Z Frames', value=5)

        self.k = widgets.FloatSlider(min=1,
                                     max=10,
                                     step=0.2,
                                     description='k (Blur)',
                                     value=1.6)

        self.edge_cutoff = widgets.FloatText(description='Edge cut')

        self.plot = widgets.Checkbox(description='Show plots', value=True)

        self.options.children = [self.media_wid]
    def define_pixel_size(self):

        box = widgets.HBox([widgets.Label("Size/Pixel Ratio"),
                            widgets.FloatText(value=1,
                                              step=0.1,
                                              layout=widgets.Layout(width='10%')),
                            widgets.Label("mm/px")])

        display(box)
        self.ratio_widget = box.children[1]
示例#12
0
    def __init__(self, n_rules, avail_records, refresh_ptcl):
        """
        Initialize a set of particle selection widgets

        Parameters:
        -----------
        n_rules: int
            The number of selection rules to display

        avail_records: list of strings
            The list of available records for the current species

        refresh_ptcl: callable
            The callback function to execute when the widget is changed
        """
        self.n_rules = n_rules

        # Create widgets that determines whether the rule is used
        self.active = [widgets.Checkbox(value=False) for i in range(n_rules)]
        # Create widgets that determines the quantity on which to select
        # (The Dropdown menu is empty, but is later populated by the
        # function refresh_species)
        self.quantity = [
            widgets.Dropdown(options=avail_records, description='Select ')
            for i in range(n_rules)
        ]
        # Create widgets that determines the lower bound and upper bound
        self.low_bound = [
            widgets.FloatText(value=-1.e-1, description='from ')
            for i in range(n_rules)
        ]
        self.up_bound = [
            widgets.FloatText(value=1.e-1, description='to ')
            for i in range(n_rules)
        ]

        # Add the callback function refresh_ptcl to each widget
        for i in range(n_rules):
            self.active[i].observe(refresh_ptcl, 'value', 'change')
            self.quantity[i].observe(refresh_ptcl, 'value', 'change')
            self.low_bound[i].observe(refresh_ptcl, 'value', 'change')
            self.up_bound[i].observe(refresh_ptcl, 'value', 'change')
示例#13
0
def InteractivePlaneProfile():
    nRx = 100

    def foo(Field, Sigma, Scale, Time):

        plt.figure(figsize=(8, 4))
        ax1 = plt.subplot(111)

        r = np.linspace(-1000.0, 0.0, nRx)
        val_ex, val_hy = PlaneEHfield(r, t=Time, sig=Sigma)

        if Field == "Ex":
            val = val_ex.flatten()
            label = "Ex-field (V/m)"

        elif Field == "Hy":
            val = val_hy.flatten()
            label = "Hy-field (A/m)"

        if Scale == "log":
            val_p, val_n = DisPosNegvalues(val)
            ax1.plot(r, val_p, "k-", lw=2)
            ax1.plot(r, val_n, "k--", lw=2)
            ax1.set_yscale(Scale)

        elif Scale == "linear":
            ax1.plot(r, val, "k-", lw=2)
            ax1.set_yscale(Scale)
            y = ax1.yaxis.get_majorticklocs()
            yticksa = np.linspace(y.min(), y.max(), 3)
            ax1.yaxis.set_ticks(yticksa)
            ax1.yaxis.set_major_formatter(ticker.FormatStrFormatter("%.1e"))

        ax1.set_xlim(0, -1000)
        ax1.set_ylabel(label, color="k")
        ax1.set_xlabel("Z (m)")

        ax1.grid(True)
        plt.show()

    Q2 = widgets.interactive(
        foo,
        Field=widgets.ToggleButtons(options=["Ex", "Hy"], value="Ex"),
        Sigma=widgets.FloatText(value=1,
                                continuous_update=False,
                                description="$\sigma$ (S/m)"),
        Scale=widgets.ToggleButtons(options=["log", "linear"], value="linear"),
        Time=widgets.FloatSlider(min=0.01,
                                 max=1.0,
                                 step=0.01,
                                 value=0.0,
                                 description="$t$ (s)"),
    )
    return Q2
示例#14
0
    def __init__(self, n_rules, avail_ptcl_quantities, refresh_ptcl):
        """
        Initialize a set of particle selection widgets

        Parameters:
        -----------
        n_rules: int
            The number of selection rules to display

        avail_ptcl_quantities: list of string
            The particle quantities in the present openPMD timeseries

        refresh_ptcl: callable
            The callback function to execute when the widget is changed
        """
        self.n_rules = n_rules

        # Create widgets that determines whether the rule is used
        self.active = [ widgets.Checkbox(value=False) \
                         for i in range(n_rules) ]
        # Create widgets that determines the quantity on which to select
        self.quantity = [
            widgets.Dropdown(options=avail_ptcl_quantities,
                             description='Select ') for i in range(n_rules)
        ]
        # Create widgets that determines the lower bound and upper bound
        self.low_bound = [
            widgets.FloatText(value=-1.e-1, width=90, description='from ')
            for i in range(n_rules)
        ]
        self.up_bound = [
            widgets.FloatText(value=1.e-1, width=90, description='to ')
            for i in range(n_rules)
        ]

        # Add the callback function refresh_ptcl to each widget
        for i in range(n_rules):
            self.active[i].on_trait_change(refresh_ptcl)
            self.quantity[i].on_trait_change(refresh_ptcl)
            self.low_bound[i].on_trait_change(refresh_ptcl)
            self.up_bound[i].on_trait_change(refresh_ptcl)
示例#15
0
def g6r_menu():
    '''
    generates a menu for specific parameters to compute and fit the time correlation of the hexagonal order. See src.characterisation.g6.py for details
    '''
    input = widgets.Dropdown(description='Input data',
                             options=['Dictionary', 'Pickle', 'Text file'],
                             value='Dictionary')
    nbins = widgets.IntText(description='Nbins', value=100)
    bs = widgets.FloatText(description='Binwidth', value=0.25)
    plot = widgets.Checkbox(description='Plot', value=True)
    save = widgets.Checkbox(description='Save', value=True)
    return widgets.VBox([input, nbins, bs, plot, save])
示例#16
0
def ov_menu():
    '''
    generates a menu for specific parameters to compute and fit the overlap Q(t) functions. See src.characterisation.overlap.py for details
    '''
    input = widgets.Dropdown(description='Input data',
                             options=['Dictionary', 'Pickle', 'Text file'],
                             value='Dictionary')
    plot = widgets.Checkbox(description='Plot', value=True)
    fit = widgets.Checkbox(description='Fit', value=True)
    points = widgets.IntText(description='No. of points', value=100)
    tau = widgets.FloatText(description='$ \\tau $', value=1.)
    save = widgets.Checkbox(description='Save', value=True)
    return widgets.VBox([input, plot, fit, points, tau, save])
示例#17
0
    def __init__(self, callback_function, default_cmap, default_vmin,
                 default_vmax):
        """
        Initialize a set of widgets that select a colorbar.

        Parameters:
        -----------
        callback_function: callable
            The function to call when activating/deactivating the range,
            or when changing the colormap
        default_cmap: string
            The name of the colormap that will be used when the widget is
            initialized
        default_vmin, default_vmax: float
            The default value for the initial value of vmin and vmax
        """
        # Create the colormap widget
        available_cmaps = sorted(plt.colormaps())
        if default_cmap not in available_cmaps:
            default_cmap = 'jet'
        self.cmap = widgets.Select(options=available_cmaps, value=default_cmap)

        # Convert default_vmin, default vmax to scientific format
        max_abs = max(abs(default_vmin), abs(default_vmax))
        default_exponent = math.floor(math.log10(max_abs))
        default_upbound = default_vmax * 10.**(-default_exponent)
        default_lowbound = default_vmin * 10.**(-default_exponent)

        # Create the widgets for the range
        self.active = create_checkbox(value=False)
        self.low_bound = widgets.FloatText(value=default_lowbound)
        self.up_bound = widgets.FloatText(value=default_upbound)
        self.exponent = widgets.FloatText(value=default_exponent)

        # Add the callback function
        self.active.observe(callback_function, 'value', 'change')
        self.exponent.observe(callback_function, 'value', 'change')
        self.cmap.observe(callback_function, 'value', 'change')
示例#18
0
    def __init__(self, callback_function, default_value, title):
        """
        Initialize a set of widgets that select a range of (float) values

        Parameters:
        -----------
        callback_function: callable
            The function to call when activating/deactivating the range
        default_value:
            The default value of the upper bound of the range at initialization
            (The default lower bound is the opposite of this value.)
        title:
            The title that is displayed on top of the widgets
        """
        # Register title
        self.title = title

        # Create the widgets
        self.active = create_checkbox(value=False)
        self.low_bound = widgets.FloatText(value=-default_value)
        self.up_bound = widgets.FloatText(value=default_value)

        # Add the callback function
        self.active.observe(callback_function, 'value', 'change')
示例#19
0
def cl_menu():
    input = widgets.Dropdown(description='Input data',
                             options=['Dictionary', 'Pickle', 'Text file'],
                             value='Dictionary')
    dc = widgets.FloatSlider(min=0.5,
                             max=2.0,
                             description='Dist cut',
                             value=1.25,
                             step=0.25)
    mn = widgets.IntSlider(min=3, max=7, description='Num neigh', value=5)
    mcs = widgets.FloatText(description='Min cluster size', value=10)
    ids = widgets.Checkbox(description='Cluster Id', value=False)
    iso = widgets.Checkbox(description='Isolated', value=False)
    save = widgets.Checkbox(description='Save', value=False)
    return widgets.VBox([input, dc, mn, mcs, ids, iso])
示例#20
0
    def _build_sed_form(self):
        self.sed_select = widgets.Dropdown(
            description="SED type: ",
            options=['power-law', 'blackbody', 'star', 'extragalactic'],
            value='power-law',
            layout={'width': '20rem'},
        )
        self.pl_index = widgets.FloatText(
            description="Index:",
            value=1.0,
            layout={'width': '14rem'},
        )
        self.bb_temp = widgets.BoundedFloatText(
            description="Temp (K):",
            min=0.0, max=99999.0, value=6500.0,
            layout={'width': '14rem'},
        )
        _hide(self.bb_temp)


        self.star_config = STAR_CONFIG
        self.stars = widgets.Dropdown(
            options=sorted(self.star_config.keys()),
            layout={'width': '18rem'},
        )
        _hide(self.stars)

        self.gal_config = GALAXIES_CONFIG
        self.galaxies = widgets.Dropdown(
            options=sorted(self.gal_config.keys()),
            layout={'width': '26rem'},
        )
        _hide(self.galaxies)

        self.redshift = widgets.BoundedFloatText(
            description="Redshift: z=",
            min=0.0, max=99999.0, value=0.0,
            layout={'width': '14rem'},
        )

        self.sed_select.observe(self.on_sed_select, names='value')
        return widgets.HBox([
            self.sed_select, self.pl_index, self.bb_temp,
            self.stars, self.galaxies, self.redshift,
        ])
示例#21
0
    def __init__(self,
                 on_interact=None,
                 output=None,
                 overwrite_previous_output=True,
                 feedback=False,
                 run=True,
                 action_kws={},
                 *args,
                 **kwargs):
        super().__init__(on_interact=on_interact,
                         output=output,
                         overwrite_previous_output=overwrite_previous_output,
                         feedback=feedback,
                         action_kws=action_kws)

        self.widget = widgets.FloatText(*args, **kwargs)

        if run:
            self.run()
示例#22
0
 def get_cluster_params_widgets(param, value):
     if isinstance(value, float):
         return (param, widgets.FloatText(
                 value=value,
                 step=0.1,
                 description=param.split('__')[1],
                 disabled=False
                 ))
     elif isinstance(value, int):
         return (param, widgets.IntText(
             value=value,
             step=1,
             description=param.split('__')[1],
             disabled=False
         ))
     elif isinstance(value, str):
         return (param, widgets.Text(
             value=value,
             description=param.split('__')[1],
             disabled=False
         ))
     else:
         return None
示例#23
0
 def get_widgets_per_param(params):
     for key, value in params.items():
         style = {'description_width': 'initial'}
         description = key.split("__")[1] if "__" in key else key
         if isinstance(value, float):
             yield (key,
                    widgets.FloatText(value=value,
                                      step=0.05,
                                      description=description,
                                      continuous_update=False,
                                      disabled=False,
                                      layout=Layout(width="90%"),
                                      style=style))
         elif isinstance(value, bool):
             yield (key,
                    widgets.ToggleButton(value=value,
                                         description=description,
                                         disabled=False,
                                         layout=Layout(width="90%"),
                                         style=style))
         elif isinstance(value, int):
             yield (key,
                    widgets.IntText(value=value,
                                    step=1,
                                    description=description,
                                    continuous_update=False,
                                    disabled=False,
                                    layout=Layout(width="90%"),
                                    style=style))
         elif isinstance(value, str):
             yield (key,
                    widgets.Text(value=value,
                                 description=description,
                                 continuous_update=False,
                                 disabled=False,
                                 layout=Layout(width="90%"),
                                 style=style))
示例#24
0
    def interact_plot_model_prism(self):
        plot = widgets.RadioButtons(
            options=["field", "model"],
            value="field",
            description="plot",
            disabled=False,
        )
        component = widgets.RadioButtons(
            options=["Bt", "Bx", "By", "Bz"],
            value="Bt",
            description="field",
            disabled=False,
        )

        inclination = widgets.FloatSlider(description="I",
                                          continuous_update=False,
                                          min=-90,
                                          max=90,
                                          step=1,
                                          value=90)
        declination = widgets.FloatSlider(description="D",
                                          continuous_update=False,
                                          min=-180,
                                          max=180,
                                          step=1,
                                          value=0)
        length = widgets.FloatSlider(
            description="length",
            continuous_update=False,
            min=2,
            max=200,
            step=1,
            value=72,
        )
        dx = widgets.FloatSlider(
            description="data spacing",
            continuous_update=False,
            min=0.1,
            max=15,
            step=0.1,
            value=2,
        )
        kappa = widgets.FloatText(description="$\kappa$", value=0.1)
        B0 = widgets.FloatText(description="B$_0$", value=56000)
        depth = widgets.FloatSlider(
            description="depth",
            continuous_update=False,
            min=0,
            max=50,
            step=1,
            value=10,
        )
        profile = widgets.RadioButtons(
            options=["East", "North", "None"],
            value="East",
            description="profile",
            disabled=False,
        )
        fixed_scale = widgets.Checkbox(value=False,
                                       description="fixed scale",
                                       disabled=False)

        show_halfwidth = widgets.Checkbox(value=False,
                                          description="half width",
                                          disabled=False)
        prism_dx = widgets.FloatText(description="$\\triangle x$", value=1)
        prism_dy = widgets.FloatText(description="$\\triangle y$", value=1)
        prism_dz = widgets.FloatText(description="$\\triangle z$", value=1)
        prism_inclination = widgets.FloatSlider(
            description="I$_{prism}$",
            continuous_update=False,
            min=-90,
            max=90,
            step=1,
            value=0,
        )
        prism_declination = widgets.FloatSlider(
            description="D$_{prism}$",
            continuous_update=False,
            min=0,
            max=180,
            step=1,
            value=0,
        )

        out = widgets.interactive_output(
            self.magnetic_prism_applet,
            {
                "plot": plot,
                "component": component,
                "inclination": inclination,
                "declination": declination,
                "length": length,
                "dx": dx,
                "kappa": kappa,
                "B0": B0,
                "depth": depth,
                "profile": profile,
                "fixed_scale": fixed_scale,
                "show_halfwidth": show_halfwidth,
                "prism_dx": prism_dx,
                "prism_dy": prism_dy,
                "prism_dz": prism_dz,
                "prism_inclination": prism_inclination,
                "prism_declination": prism_declination,
            },
        )
        left = widgets.VBox(
            [plot, component, profile],
            layout=Layout(width="20%",
                          height="400px",
                          margin="60px 0px 0px 0px"),
        )
        right = widgets.VBox(
            [
                inclination,
                declination,
                length,
                dx,
                B0,
                kappa,
                depth,
                prism_dx,
                prism_dy,
                prism_dz,
                prism_inclination,
                prism_declination,
                fixed_scale,
                show_halfwidth,
            ],
            layout=Layout(width="50%",
                          height="400px",
                          margin="20px 0px 0px 0px"),
        )
        widgets.VBox([out],
                     layout=Layout(width="70%",
                                   height="400px",
                                   margin="0px 0px 0px 0px"))
        return widgets.HBox([left, out, right])
示例#25
0
    def interact_plot_model_two_monopole(self):
        component = widgets.RadioButtons(
            options=["Bt", "Bx", "By", "Bz", "Bg"],
            value="Bt",
            description="field",
            disabled=False,
        )

        inclination = widgets.FloatSlider(description="I",
                                          continuous_update=False,
                                          min=-90,
                                          max=90,
                                          step=1,
                                          value=90)
        declination = widgets.FloatSlider(description="D",
                                          continuous_update=False,
                                          min=-180,
                                          max=180,
                                          step=1,
                                          value=0)
        length = widgets.FloatSlider(
            description="length",
            continuous_update=False,
            min=2,
            max=200,
            step=1,
            value=10,
        )
        dx = widgets.FloatSlider(
            description="data spacing",
            continuous_update=False,
            min=0.1,
            max=15,
            step=0.1,
            value=0.1,
        )
        moment = widgets.FloatText(description="M", value=30)
        depth_n = widgets.FloatSlider(
            description="depth$_{-Q}$",
            continuous_update=False,
            min=0,
            max=200,
            step=1,
            value=0,
        )
        depth_p = widgets.FloatSlider(
            description="depth$_{+Q}$",
            continuous_update=False,
            min=0,
            max=200,
            step=1,
            value=1,
        )
        profile = widgets.RadioButtons(
            options=["East", "North", "None"],
            value="East",
            description="profile",
            disabled=False,
        )
        fixed_scale = widgets.Checkbox(value=False,
                                       description="fixed scale",
                                       disabled=False)
        show_halfwidth = widgets.Checkbox(value=False,
                                          description="half width",
                                          disabled=False)

        out = widgets.interactive_output(
            self.magnetic_two_monopole_applet,
            {
                "component": component,
                "inclination": inclination,
                "declination": declination,
                "length": length,
                "dx": dx,
                "moment": moment,
                "depth_n": depth_n,
                "depth_p": depth_p,
                "profile": profile,
                "fixed_scale": fixed_scale,
                "show_halfwidth": show_halfwidth,
            },
        )
        left = widgets.VBox(
            [component, profile],
            layout=Layout(width="20%",
                          height="400px",
                          margin="60px 0px 0px 0px"),
        )
        right = widgets.VBox(
            [
                inclination,
                declination,
                length,
                dx,
                moment,
                depth_n,
                depth_p,
                fixed_scale,
                show_halfwidth,
            ],
            layout=Layout(width="50%",
                          height="400px",
                          margin="20px 0px 0px 0px"),
        )
        widgets.VBox([out],
                     layout=Layout(width="70%",
                                   height="400px",
                                   margin="0px 0px 0px 0px"))
        return widgets.HBox([left, out, right])
示例#26
0
文件: by_date.py 项目: hagne/qclib
    def _plot_settings_axes(self, axes_content, key):
        # vmin = -1e100
        # vmax = 1e100
        a = axes_content['a']

        def on_change(change, set_lim, vmin, vmax):
            if self.controller.initiation_in_progress:
                return
            # self.tester = change
            param = change['owner'].description
            self.controller.database.set_plot_settings(key, param,
                                                       change['new'])
            set_lim(vmin.value, vmax.value)

        step = 1
        xlim_min = widgets.FloatText(
            value=7.5,
            # min=vmin,
            # max=vmax,
            step=step,
            description='x_min',
            disabled=False)

        xlim_max = widgets.FloatText(
            value=7.5,
            # min=vmin,
            # max=vmax,
            step=step,
            description='x_max',
            disabled=False)

        # xlim_min.observe(lambda x: on_change(x, a.set_xlim(), xlim_min, xlim_max), names='value')
        # ylim_max.observe(lambda x: on_change(x, set_lim_z, xlim_min, xlim_max), names='value')

        xhbox = widgets.HBox([xlim_min, xlim_max])
        # display(xhbox)

        ylim_min = widgets.FloatText(
            value=7.5,
            # min=vmin,
            # max=vmax,
            step=step,
            description='y_min',
            disabled=False)
        ylim_max = widgets.FloatText(
            value=7.5,
            # min=vmin,
            # max=vmax,
            step=step,
            description='y_max',
            disabled=False)

        ylim_min.observe(
            lambda x: on_change(x, a.set_ylim, ylim_min, ylim_max),
            names='value')
        ylim_max.observe(
            lambda x: on_change(x, a.set_ylim, ylim_min, ylim_max),
            names='value')
        yhbox = widgets.HBox([ylim_min, ylim_max])
        # display(hbox)

        zlim_min = widgets.FloatText(
            # value=7.5,
            # min=vmin,
            # max=vmax,
            step=step,
            description='z_min',
            disabled=False)

        def set_lim_z(vmin, vmax):
            # for zo  in axes_content['zobjects']:
            for zo in a.zobjects:
                zo.set_clim(vmin, vmax)

        zlim_max = widgets.FloatText(
            # value=7.5,
            # min=vmin,
            # max=vmax,
            step=step,
            description='z_max',
            disabled=False)
        zlim_min.observe(lambda x: on_change(x, set_lim_z, zlim_min, zlim_max),
                         names='value')
        zlim_max.observe(lambda x: on_change(x, set_lim_z, zlim_min, zlim_max),
                         names='value')

        zhbox = widgets.HBox([zlim_min, zlim_max])

        vbox = widgets.VBox([xhbox, yhbox, zhbox])
        return vbox, {
            'x': (xlim_min, xlim_max),
            'y': (ylim_min, ylim_max),
            'z': (zlim_min, zlim_max)
        }
示例#27
0
    def __init__(
        self,
        time_series: TimeSeries,
        trials: TimeIntervals = None,
        trace_index=0,
        trace_controller=None,
        trace_controller_kwargs=None,
        sem=True,
    ):

        self.time_series = time_series
        self.time_series_data = time_series.data[()]
        self.time_series_timestamps = None
        if time_series.rate is None:
            self.time_series_timestamps = time_series.timestamps[()]
        super().__init__()

        if trials is None:
            self.trials = self.get_trials()
            if self.trials is None:
                self.children = [widgets.HTML("No trials present")]
                return
        else:
            self.trials = trials

        if trace_controller is None:
            ntraces = self.time_series.data.shape[1]
            input_trace_controller_kwargs = dict(
                options=[x for x in range(ntraces)],
                value=trace_index,
                description="trace",
                layout=Layout(width="200px"),
            )
            if trace_controller_kwargs is not None:
                input_trace_controller_kwargs.update(trace_controller_kwargs)
            self.trace_controller = widgets.Dropdown(
                **input_trace_controller_kwargs)
        else:
            self.trace_controller = trace_controller

        self.trial_event_controller = make_trial_event_controller(
            self.trials, layout=Layout(width="200px"))

        self.before_ft = widgets.FloatText(0.5,
                                           min=0,
                                           description="before (s)",
                                           layout=Layout(width="200px"))
        self.after_ft = widgets.FloatText(2.0,
                                          min=0,
                                          description="after (s)",
                                          layout=Layout(width="200px"))

        self.gas = self.make_group_and_sort(window=False, control_order=False)

        self.align_to_zero_cb = widgets.Checkbox(description="align to zero")

        self.controls = dict(
            index=self.trace_controller,
            after=self.after_ft,
            before=self.before_ft,
            start_label=self.trial_event_controller,
            gas=self.gas,
            align_to_zero=self.align_to_zero_cb,
        )
        vbox_cols = [
            [self.gas, self.align_to_zero_cb],
            [
                self.trace_controller,
                self.trial_event_controller,
                self.before_ft,
                self.after_ft,
            ],
        ]
        if sem:
            self.sem_cb = widgets.Checkbox(description="show SEM")
            self.controls.update(sem=self.sem_cb)
            vbox_cols[0].append(self.sem_cb)
        out_fig = set_plotly_callbacks(self.update, self.controls)

        self.children = [
            widgets.HBox([widgets.VBox(i) for i in vbox_cols]), out_fig
        ]
示例#28
0
 def make_sink_tab(self):
     self.sink_input = widgets.HBox([widgets.FloatText(description="X", \
         value = (self.source_number.value - 1)/2),\
              widgets.FloatText(description="Y", value = 0)])
     return self.sink_input
示例#29
0
    def InteractivePlane_Sphere(self,
                                scale="log",
                                fieldvalue="B",
                                compvalue="z"):
        def foo(
            Field,
            AmpDir,
            Component,
            ComplexNumber,
            Sigma0,
            Sigmab,
            Sigma1,
            Sigma2,
            Sus,
            d1,
            h,
            d2,
            R,
            Scale,
            rxOffset,
            z,
            ifreq,
            Geometry=True,
        ):

            Frequency = 10**((ifreq - 1.0) / 3.0 - 2.0)

            if ComplexNumber == "Re":
                ComplexNumber = "real"
            elif ComplexNumber == "Im":
                ComplexNumber = "imag"
            elif ComplexNumber == "Amp":
                ComplexNumber = "amplitude"
            elif ComplexNumber == "Phase":
                ComplexNumber = "phase"

            if AmpDir == "Direction (B or Bsec)":
                # ComplexNumber = "real"
                Component = "vec"
            if Field == "Bsec":
                bType = "bSecondary"
                Field = "B"
            else:
                bType = "b"

            self.setLayerSphereParam(
                d1=d1,
                h=h,
                d2=d2,
                R=R,
                sig0=Sigma0,
                sigb=Sigmab,
                sig1=Sigma1,
                sig2=Sigma2,
                chi=Sus,
            )
            srcLoc = np.array([0.0, 0.0, z])
            rxLoc = np.array([[rxOffset, 0.0, z]])
            self.simulate(srcLoc, rxLoc, np.r_[Frequency])
            if Field != "Model":
                self.getFields(bType=bType)
            return self.plotField(
                Field=Field,
                ComplexNumber=ComplexNumber,
                Frequency=Frequency,
                view=Component,
                scale=Scale,
                Geometry=Geometry,
                Scenario="Sphere",
            )

        out = widgetify(
            foo,
            Field=widgets.ToggleButtons(
                options=["E", "B", "Bsec", "J", "Model"], value="E"),
            AmpDir=widgets.ToggleButtons(
                options=["None", "Direction (B or Bsec)"], value="None"),
            Component=widgets.ToggleButtons(options=["x", "y", "z"],
                                            value="y",
                                            description="Comp."),
            ComplexNumber=widgets.ToggleButtons(
                options=["Re", "Im", "Amp", "Phase"],
                value="Re",
                description="Re/Im"),
            Sigma0=widgets.FloatText(value=1e-8,
                                     continuous_update=False,
                                     description="$\sigma_0$ (S/m)"),
            Sigmab=widgets.FloatText(value=0.01,
                                     continuous_update=False,
                                     description="$\sigma_b$ (S/m)"),
            Sigma1=widgets.FloatText(value=0.01,
                                     continuous_update=False,
                                     description="$\sigma_1$ (S/m)"),
            Sigma2=widgets.FloatText(value=0.01,
                                     continuous_update=False,
                                     description="$\sigma_2$ (S/m)"),
            Sus=widgets.FloatText(value=0.0,
                                  continuous_update=False,
                                  description="$\chi$"),
            d1=widgets.FloatSlider(
                min=0.0,
                max=50.0,
                step=2.0,
                value=0.0,
                continuous_update=False,
                description="$d_1$ (m)",
            ),
            h=widgets.FloatSlider(
                min=2.0,
                max=20.0,
                step=2.0,
                value=10.0,
                continuous_update=False,
                description="$h$ (m)",
            ),
            d2=widgets.FloatSlider(
                min=10.0,
                max=50.0,
                step=2.0,
                value=30.0,
                continuous_update=False,
                description="$d_2$ (m)",
            ),
            R=widgets.FloatSlider(
                min=2.0,
                max=20.0,
                step=2.0,
                value=10.0,
                continuous_update=False,
                description="$R$ (m)",
            ),
            Scale=widgets.ToggleButtons(options=["log", "linear"],
                                        value="linear"),
            rxOffset=widgets.FloatSlider(
                min=0.0,
                max=50.0,
                step=2.0,
                value=10.0,
                continuous_update=False,
                description="$\Delta x$(m)",
            ),
            z=widgets.FloatSlider(
                min=0.0,
                max=50.0,
                step=2.0,
                value=0.0,
                continuous_update=False,
                description="$\Delta z$ (m)",
            ),
            ifreq=widgets.IntSlider(
                min=1,
                max=31,
                step=1,
                value=16,
                continuous_update=False,
                description="f index",
            ),
        )
        return out
示例#30
0
    def __init__(self, ncgridlasso, overplot_func=gridLassoOverplotDefault):
        """ The user may pass a function to overplot_func in order to 
            add additional features to the plot. That function is passed 
            the lasso widget instance which called it, as well as
            the matplotlib axes on which the grid's data was just plotted.
            The default function does nothing.
        
        """

        self.ncgridlasso = ncgridlasso
        self.overplot_func = overplot_func

        self.value_range_for_field = {
            'flash_extent': (1, 1000.0),
            'flash_initiation': (1, 100.0),
            'flash_footprint': (1, 100000.0),
            'default': (1, 1000.0),
        }
        self.value_colors_for_field = {
            'flash_extent': ct.NWSRef,
            'flash_initiation': ct.NWSRef,
            'flash_footprint': 'cubehelix',
        }

        field_type = widgets.Dropdown(description='Field:',
                                      options=[self.ncgridlasso.field])
        field_type.observe(self.change_field, 'value')

        initial_vmin, initial_vmax = self.value_range_for_field[
            ncgridlasso.field]

        toggle = widgets.Checkbox(description='Log Lasso?', value=False)
        toggle_log_scale = widgets.Checkbox(description='Logarithmic',
                                            value=True)
        toggle_log_scale.observe(self.redraw, 'value')

        draw = widgets.Button(description='Draw Lasso')
        draw.on_click(self.lasso_draw)

        N_frames = len(self.ncgridlasso.NCs.times)
        frame_selection = widgets.IntSlider(description="Frame",
                                            min=0,
                                            max=N_frames - 1)
        frame_selection.value = 0
        frame_selection.observe(self.change_frame, 'value')

        v_min = widgets.FloatText(description='Min')
        v_min.value = initial_vmin
        v_min.observe(self.v_min_set, 'value')

        v_max = widgets.FloatText(description='Max')
        v_max.value = initial_vmax
        v_max.observe(self.v_max_set, 'value')

        # view_mask = widgets.Button(description='View Masked Region', value=False)
        # view_mask.on_click(self.view_mask)
        #
        revert_plot = widgets.Button(description='Redraw', value=False)
        revert_plot.on_click(self.redraw)
        #
        # filtered = widgets.Button(description='View Filtered Data', value=False)
        # filtered.on_click(self.view_filter)

        contain = widgets.VBox(description='NetCDF grid tools')
        contain.children = [
            draw,
            toggle,
            v_min,
            v_max,
            frame_selection,
            # filtered, view_mask,
            revert_plot,
            toggle_log_scale
        ]

        self.draw = draw
        self.toggle = toggle
        self.field_type = field_type
        self.frame_selection = frame_selection
        self.v_min = v_min
        self.v_max = v_max
        self.revert_plot = revert_plot
        self.toggle_log_scale = toggle_log_scale
        # self.view_mask = view_mask
        # self.filtered = filtered
        self.container = contain

        self.plot_update()