コード例 #1
0
    def __init__(self, starting_values=None, limits=(-3.0, 5.0), linewidth=3):
        self.linewidth = linewidth
        self.starting_values = starting_values
        self.limits = limits

        # Default values
        if starting_values is None:
            starting_values = [[1, 2], [3, 1]]

        # Make widgets
        self.widgets = [
            FloatSlider(
                value=val,
                min=limits[0],
                max=limits[1],
                step=0.1,
                description='${}_{{{}}}$'.format(["v", "w"][nr], d),
                disabled=False,
                continuous_update=True,
                orientation='vertical',
                readout=True,
                readout_format='.1f',
            ) for nr, vector in enumerate(starting_values)
            for d, val in enumerate(vector)
        ]

        # Make widget box
        self.box = HBox(self.widgets)

        # Set fields
        self.fig = self.ax = None

        # Make figure when widgets are shown
        self.box.on_displayed(self.plot_function)

        # Make widgets pass data to plotting function
        for widget in self.widgets:
            widget.observe(self.plot_function)
コード例 #2
0
ファイル: replay.py プロジェクト: bollwyvl/jupyter-cadquery
def replay(cad_obj, index=-1, debug=False, cad_width=600, height=600):

    if not REPLAY:
        print("Replay is not enabled. To do so call 'enable_replay()'. Falling back to 'show()'")
        return show(cad_obj, cad_width=cad_width, height=height)
    else:
        print("Use the multi select box below to select one or more steps you want to examine")

    r = Replay(debug, cad_width, height)

    if isinstance(cad_obj, cq.Workplane):
        workplane = cad_obj
    elif is_cqparts_part(cad_obj):
        workplane = convert_cqparts(cad_obj, replay=True)
    else:
        print("Cannot replay", cad_obj)
        return None

    r.stack = r.format_steps(r.to_array(workplane, result_name=getattr(workplane, "name", None)))
    if index == -1:
        r.indexes = [len(r.stack) - 1]
    else:
        r.indexes = [index]

    r.select_box = SelectMultiple(
        options=["[%02d] %s" % (i, code) for i, (code, obj) in enumerate(r.stack)],
        index=r.indexes,
        rows=len(r.stack),
        description="",
        disabled=False,
        layout=Layout(width="600px"),
    )
    r.select_box.add_class("monospace")
    r.select_box.observe(r.select_handler)
    display(HBox([r.select_box, r.debug_output]))

    r.select(r.indexes)
    return r
コード例 #3
0
def sum_of_squares():

    csldr = IntSlider(value=50,
                      description='$c$',
                      min=10,
                      max=100,
                      step=10,
                      continuous_update=False)
    ksldr = IntSlider(value=13,
                      description='$k$',
                      min=2,
                      max=27,
                      step=2,
                      continuous_update=False)
    wgts = Checkbox(value=False, description='downweight bad measurements')
    return VBox([
        HBox([csldr, ksldr, wgts]),
        interactive_output(plot_suspension_model2, {
            'cm': csldr,
            'km': ksldr,
            'weights': wgts
        })
    ])
コード例 #4
0
 def on_click(_: Button) -> None:
     text_input = Textarea(
         value=text,
         placeholder="Enter text",
         disabled=False,
         layout=Layout(height="auto", width="auto"),
     )
     save_button = button(
         "",
         "success",
         on_click=_save_button(box, ds),
         button_kwargs=dict(icon="save"),
         layout_kwargs=dict(width="50%"),
     )
     cancel_button = button(
         "",
         "danger",
         on_click=_save_button(box, ds, do_save=False),
         button_kwargs=dict(icon="close"),
         layout_kwargs=dict(width="50%"),
     )
     subbox = HBox([save_button, cancel_button], )
     box.children = (text_input, subbox)
コード例 #5
0
    def show(self):
        "actually show the graphical tool and the interactive spectrum"
        # .^..+
        # <=>.=
        # .v..-
        blank = widgets.Button(description=" ", layout=self.vlayout)
        zmbox1 = VBox([self.b_back,  self.b_left, self.b_zin])
        zmbox2 = VBox([self.b_up, self.b_reset, self.b_down])
        zmbox3 = VBox([self.b_forw,  self.b_right, self.b_zout])
        zmbox4 = VBox([self.b_scup, self.b_screset, self.b_scdown])
        spacer = HTML('&nbsp;&nbsp;&nbsp;&nbsp;')
        zbox = self.zoom_box()
        display(HBox([zmbox1,zmbox2, zmbox3, spacer, zmbox4, spacer, zbox],
            layout=Layout(height='100px')))
#        zmbox1 = HBox([blank,       self.b_up, blank, blank, self.b_scup])
#        zmbox2 = HBox([self.b_left, self.b_full, self.b_right, blank, self.b_sc1])
#        zmbox3 = HBox([blank,  self.b_down, blank,  blank, self.b_down])

#        display(VBox([zmbox1, zmbox2, zmbox3]))
        self.update()
        # fg,ax = plt.subplots()
        # self.pltaxe = ax
        self.display()
コード例 #6
0
ファイル: player.py プロジェクト: biochunan/nglview
    def _make_add_widget_repr(self, component_slider):
        dropdown_repr_name = Dropdown(options=REPRESENTATION_NAMES,
                                      value='cartoon')
        repr_selection = Text(value='*', description='')
        repr_button = Button(description='Add',
                             tooltip="""Add representation.
        You can also hit Enter in selection box""")
        repr_button.layout = Layout(width='auto', flex='1 1 auto')

        dropdown_repr_name.layout.width = repr_selection.layout.width = default.DEFAULT_TEXT_WIDTH

        def on_click_or_submit(button_or_text_area):
            self._view.add_representation(
                selection=repr_selection.value.strip(),
                repr_type=dropdown_repr_name.value,
                component=component_slider.value)

        repr_button.on_click(on_click_or_submit)
        repr_selection.on_submit(on_click_or_submit)
        add_repr_box = HBox([repr_button, dropdown_repr_name, repr_selection])
        add_repr_box._ngl_name = 'add_repr_box'

        return add_repr_box
コード例 #7
0
ファイル: datasaurus.py プロジェクト: ned2/melbviz
def show_datasaurus(datasauraus_df, column):
    if column == "all":
        df = datasauraus_df
    else:
        df = datasauraus_df[datasauraus_df["dataset"] == column]
    stats_df = pd.DataFrame({
        "statistic": ["x_mean", "y_mean", "x_std", "y_std", "corr"],
        "value": [
            df["x"].mean(), df["y"].mean(), df["x"].std(), df["y"].std(), df["x"].corr(df["y"])
        ],
    })
    if column == "all":
        fig = px.scatter(datasauraus_df, facet_col_wrap=5, facet_col="dataset", x="x", y="y")
        fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
    else:
        fig = px.scatter(df, x="x", y="y")
    fig.update_layout(
        margin={"r": 10, "t": 40, "b": 10},
        font_size=18,
        width=600,
        height=500,
    )
    return HBox([object_as_widget(stats_df), go.FigureWidget(fig)])
コード例 #8
0
def show_eps_vs_cost(player_gw_next_eps_ext: DF, players_gw_team_eps_ext: DF, teams: DF, ctx: Context):
    # Define the event handlers
    def update_eps_chart(out, horizon, position, team, player) -> None:
        with out:
            display(player_strength_by_horizon(player_gw_next_eps_ext, players_gw_team_eps_ext, horizon, position,
                                               team, player, ctx))

    teams_sel = [SEL_ALL] + list(teams['Team Name'])
    positions_sel = [SEL_ALL] + list(ctx.position_by_type.values())

    # Define the selector controls
    horizons = [col.replace('Expected Points ', '') for col in player_gw_next_eps_ext.columns if col.startswith('Expected Points Next ')]
    horizons += [col.replace('Expected Points ', '') for col in player_gw_next_eps_ext.columns if col.startswith('Expected Points GW ')]
    horizon_dropdown = Dropdown(description='Horizon ', options=horizons)
    position_dropdown = Dropdown(description='Position ', options=positions_sel)
    team_dropdown = Dropdown(description='Team ', options=teams_sel)
    player_text = Text(description='Player ', placeholder='Enter player name')

    # Add the change value listeners
    selectors = HBox([horizon_dropdown, position_dropdown, team_dropdown, player_text])

    out = interactive(update_eps_chart, {'horizon': horizon_dropdown, 'position': position_dropdown, 'team': team_dropdown, 'player': player_text})
    return VBox([selectors, out])
コード例 #9
0
    def add_row(self):
        newchildren = []
        for c in self.childinnotationconfigs:
            if isinstance(c, tuple) or isinstance(c, list):
                kwargs = {} if len(c) <= 2 else c[2]

                kwargs['repeat_index'] = self.rows_count
                if 'name' in kwargs:
                    kwargs['name'] = '{}_{}'.format(kwargs['name'], self.rows_count)
                newchildren.append(c[0](c[1], **kwargs))
            else:
                newchildren.append(c(self.data))

        self.rows_count += 1
        self.children_changed(newchildren)

        self.get_widget().children = tuple(list(self.get_widget().children)+[HBox([c.get_widget() for c in newchildren])])


        self.childinnotations.extend(newchildren)

        if self.max_repeats == self.rows_count:
            self.addbtn.disabled = True
コード例 #10
0
ファイル: gdf_viewer.py プロジェクト: jpn--/mapped
    def __init__(self,
                 gdf,
                 color=None,
                 color_continuous_scale='Cividis',
                 color_discrete_sequence='Plotly'):

        self.gdf = gdf
        if color is not None and color not in self.gdf.columns:
            raise KeyError(color)

        self.fig = plotly_choropleth(gdf,
                                     color=color,
                                     color_continuous_scale='Cividis')

        self.color_continuous_scale = color_continuous_scale
        self.color_discrete_sequence = color_discrete_sequence

        self.col_dropdown = Dropdown(
            options=[i for i in self.gdf.columns if i != 'geometry'],
            value=color,
        )

        self.panel = HBox([
            Label("Color"),
            self.col_dropdown,
        ])

        self.col_dropdown.observe(self._change_column, names='value')

        self.col_name = None

        self.change_view(col_name=self.col_dropdown.value, )

        super().__init__(children=(
            self.fig,
            self.panel,
        ))
コード例 #11
0
    def __init__(self, querier, citation_var, citation_file=None, debug=False, start=None, load=True):
        from .selenium_scholar import URLQuery
        reload()
        self.querier = querier
        work = work_by_varname(citation_var)
        citation_file = citation_file or oget(work, "citation_file", citation_var)
        self.navigator = ArticleNavigator(citation_var, citation_file, backward=False, force_citation_file=False)
        self.query = URLQuery(
            oget(self.navigator.work, "scholar", cvar=config.SCHOLAR_MAP),
            start
        )
        self.next_page_widget = Button(description="Next Page", icon="fa-arrow-right")
        self.reload_widget = Button(description="Reload", icon="fa-refresh")
        self.previous_page_widget = Button(description="Previous Page", icon="fa-arrow-left")
        self.debug_widget = ToggleButton(value=debug, description="Debug")
        self.page_number_widget = Label(value="")
        self.next_page_widget.on_click(self.next_page)
        self.reload_widget.on_click(self.reload)
        self.previous_page_widget.on_click(self.previous_page)

        self.view = Tab([
            VBox([
                HBox([
                    self.previous_page_widget,
                    self.reload_widget,
                    self.next_page_widget,
                    self.debug_widget,
                    self.page_number_widget
                ]),
                self.navigator.output_widget,
            ]),
            self.navigator.view
        ])
        self.view.set_title(0, "Page")
        self.view.set_title(1, "Article")
        if load:
            self.reload(None)
コード例 #12
0
    def interactive_plot(*args, **kwargs):
        dct, *args = args  # arg0 must be dict of line data to plot
        kwargs["legend"] = False  # Turn off legend

        handles = []

        def plot_these(**labels):
            included = {k: v for k, v in dct.items() if labels[k]}
            hh = plotter(included, *args, **kwargs)
            if not handles:
                handles.extend(hh)

        widget = interactive(plot_these, **{label: True for label in dct})
        widget.update()
        # Could end function here. The rest is adjustments.

        # Place checkmarks to the right
        *checkmarks, figure = widget.children
        widget = HBox([figure, VBox(checkmarks)])
        ip_disp.display(widget)

        # Narrower checkmark boxes
        widget.children[1].layout.width = "15ex"
        for CX in widget.children[1].children:
            CX.layout.width = '10ex'
            CX.style.description_width = '0ex'

        # Hack to color borders of checkmarks.
        # Did not find how to color background/face.
        # Anyways, there is no general/good way to style widgets, ref:
        # https://github.com/jupyter-widgets/ipywidgets/issues/710#issuecomment-409448282
        import matplotlib as mpl
        for cm, lh in zip(checkmarks, handles):
            c = mpl.colors.to_hex(lh.get_color(), keep_alpha=False)
            cm.layout.border = "solid 5px" + c

        return widget
コード例 #13
0
    def __init__(self):
        self.t = 0
        self.plotter = None

        self.pid = PID()

        self.timer = tornado.ioloop.PeriodicCallback(self.update, 1000)
        self.mode = 'manual'

        self.usemodel = Checkbox(description="Use model")

        # buttons
        self.start = actionbutton('Start', self.action_start)
        self.start.disabled = False
        self.manual = actionbutton('Manual', self.action_manual)
        self.auto = actionbutton('Auto', self.action_auto)
        self.stop = actionbutton('Stop', self.action_stop)
        buttons = HBox(
            [self.usemodel, self.start, self.auto, self.manual, self.stop])

        # Sliders for heaters
        self.gain = slider('Gain', self.action_gain, maxvalue=10)
        self.gain.value = 1
        self.tau_i = slider(r'$\tau_I$', self.action_tau_i, minvalue=0)
        self.tau_i.value = 100
        self.tau_d = slider(r'$\tau_D$', self.action_tau_d, maxvalue=10)

        parameters = VBox([self.gain, self.tau_i, self.tau_d])

        # Setpoint
        self.setpoint = slider('Setpoint',
                               self.action_setpoint,
                               minvalue=20,
                               maxvalue=70)
        self.setpoint.value = 30
        self.Q1 = slider('Q1', self.action_Q1, disabled=False)
        self.gui = VBox([buttons, parameters, self.setpoint, self.Q1])
コード例 #14
0
    def _widget(self):
        """ Create IPython widget for display within a notebook """
        try:
            return self._cached_widget
        except AttributeError:
            pass

        from ipywidgets import Layout, VBox, HBox, IntText, Button, HTML

        client = self._dask_client()

        layout = Layout(width='150px')

        title = HTML('<h2>YarnCluster</h2>')

        status = HTML(self._widget_status(), layout=Layout(min_width='150px'))

        request = IntText(0, description='Workers', layout=layout)
        scale = Button(description='Scale', layout=layout)

        @scale.on_click
        def scale_cb(b):
            with log_errors():
                self.scale(request.value)

        box = VBox([title,
                    HBox([status, request, scale])])

        self._cached_widget = box

        def update():
            status.value = self._widget_status()

        pc = PeriodicCallback(update, 500, io_loop=client.loop)
        pc.start()

        return box
コード例 #15
0
    def __init__(self, n=10, a_h=1.3, a_g=1.1, delay=2000):
        self.out = Output(layout={'width': '1000px', 'height': '600px'})
        self.out_static = Output(layout={'width': '1000px', 'height': '300px'})
        self.axs = []
        
        self.n = n
        self.a_h = a_h
        self.a_g = a_g
        self.k = np.linspace(0, self.n-1, self.n)
        self.k_m = np.linspace(-self.n, self.n-1, 2*self.n)
        
        self.formula = r'$(h \ast g)[n] = \sum_{m=-\infty}^{\infty}h[m]g[n-m]$'
        
        self.update_signals(-1)
        
        # Inizializate the figure
        self.init_figure()

        # Play widget for animation
        self.play = widgets.Play(value=-1, min=-1, max=self.n-1, step=1, interval=delay, description="Play")
        # Slider widget for manual change
        self.slider = widgets.IntSlider(min=-1, max=self.n-1, description='n', style={'description_width':'50px'})
        # Link the two widgets
        widgets.jslink((self.play, 'value'), (self.slider, 'value'))
        # Add callback function
        self.play.observe(self.update, names='value')
        # Float widgets for a_h and a_g
        self.a_h_widget = widgets.BoundedFloatText(value=self.a_h, min=0, max=10.0, step=0.01, description=r'$a_h:$', style={'description_width':'initial'}, layout={'width':'100px'})
        self.a_g_widget = widgets.BoundedFloatText(value=self.a_g, min=0, max=10.0, step=0.01, description=r'$a_g:$', style={'description_width':'initial'}, layout={'width':'100px'})
        self.a_h_widget.observe(self.a_h_callback, names='value')
        self.a_g_widget.observe(self.a_g_callback, names='value')
        # +1 button
        self.p1_button = widgets.Button(description='+1', layout={'width':'40px'})
        self.p1_button.on_click(self.p1_callback)
        
        # Display
        display(VBox([self.out_static, self.out, HBox([self.play, self.p1_button, self.slider, self.a_h_widget, self.a_g_widget])]))
コード例 #16
0
def prediction(var):
    mtrue, ctrue = [2, 3]
    cmin, c0, cmax = [2.55, 3.05, 3.55]
    mmin, m0, mmax = [1.3, 2.1, 2.9]
    cmin, c0, cmax = [1.55, 3.05, 4.55]
    mmin, m0, mmax = [0.3, 2.1, 4.9]
    p = Posterior(cmin=cmin,
                  cmax=cmax,
                  Nc=101,
                  mmin=mmin,
                  mmax=mmax,
                  Nm=101,
                  ctrue=ctrue,
                  mtrue=mtrue,
                  var=var)
    zoom = Checkbox(value=False, description='zoom')
    Nsamples = FloatLogSlider(value=16,
                              base=4,
                              description='samples',
                              min=0,
                              max=5,
                              step=1,
                              continuous_update=False)
    xf = FloatSlider(value=3,
                     description=r'$x_f$',
                     min=2,
                     max=5,
                     step=0.5,
                     continuous_update=False)
    io = interactive_output(plot_predictions, {
        'zoom': zoom,
        'N': Nsamples,
        'xf': xf,
        'p': fixed(p)
    })
    return VBox([HBox([zoom, Nsamples, xf]), io])
コード例 #17
0
def superposition_fun(T=0.025):
    center = [-43.51876443245584, 172.66858981519297]
    m = GroundwaterMap(basemap=basemaps.Esri.WorldImagery,
                       center=center,
                       zoom=13)
    Qs = []
    bs = []
    for c in ['green', 'lightblue', 'red', 'pink']:
        icon = AwesomeIcon(name='fa-tint',
                           marker_color=c,
                           icon_color='black',
                           spin=False)
        m.add_well([
            -43.51876443245584 + (random() - 0.5) * 0.01, 172.66858981519297 +
            (random() - 0.5) * 0.01
        ],
                   icon=icon)
        Q = FloatSlider(value=10,
                        description=r'$Q$ [L/s]',
                        min=0,
                        max=40,
                        step=5,
                        continuous_update=False,
                        layout=Layout(max_width='230px'),
                        style={'description_width': '60px'})
        b = Button(disabled=False,
                   icon='fa-tint',
                   layout=Layout(max_width='230px'))
        b.style.button_color = c
        Qs.append(Q)
        bs.append(b)

    m.configure(widgets=dict([('Q{:d}'.format(i), Q)
                              for i, Q in enumerate(Qs)]),
                func=partial(m.superposition, T))
    return VBox([m, HBox([VBox([b, Q]) for Q, b in zip(Qs, bs)])])
コード例 #18
0
def generate_reset_strip_hbox(on_click_reset_button):

    children = []

    reset_button = Button(disabled=False,
                          style=ButtonStyle(button_color='gray'),
                          tooltip='Reset the dataset to its initial state',
                          icon='undo',
                          layout=Layout(width='auto', height='auto'))
    reset_button.on_click(on_click_reset_button)
    children.append(reset_button)
    stripped_columns_label = Label(layout=Layout(width='auto', height='auto'),
                                   value='Stripped columns for the dataset: ')
    children.append(stripped_columns_label)

    return HBox(
        children=children,
        layout=Layout(
            width='auto',
            grid_template_columns="50% 50%",
            align_items='center',
            # grid_template_columns='auto auto auto',
            grid_template_rows='auto',
            grid_gap='3px 3px'))
コード例 #19
0
def question7_2d(reponse):
    d = sp.Matrix([[4, 6, -3], [-1, 2, 3], [-8, 10, -2]])

    if np.abs(reponse - sp.det(d)) != 0:
        display("Dans ce cas, la troisième rangée est multipliée par -2 ")
        display(Latex("$ Soit: -2 \\times R_3 \\rightarrow R_3 $"))
        display("Le déterminant est donc:")
        display(Latex("$ det|d| = (-2) \cdot det|A| = -2 \cdot 155 = - 310 $"))

        button = widgets.Button(description='Solution', disabled=False)
        box = HBox(children=[button])
        out = widgets.Output()

        @out.capture()
        def solution(e):
            out.clear_output()
            Determinant_3x3(d, step_by_step=True)

        button.on_click(solution)

        display(box)
        display(out)
    else:
        display("Bravo! Vous avez trouvé la réponse.")
コード例 #20
0
ファイル: XPLAIN_utils.py プロジェクト: elianap/X-PLAIN-Demo
def interactiveModelComparison(le1, le2, instID):
    from ipywidgets import Button, HBox, VBox
    from IPython.display import display
    import ipywidgets as widgets
    from IPython.display import clear_output

    classes1 = ["predicted", "trueLabel"] + le1.classes[:]
    wcl1 = widgets.Dropdown(options=classes1,
                            description='1º',
                            value="predicted",
                            disabled=False)
    classes2 = ["predicted", "trueLabel"] + le2.classes[:]
    wcl2 = widgets.Dropdown(options=classes2,
                            description='2º',
                            value="predicted",
                            disabled=False)
    hClasses = VBox([wcl1, wcl2])
    l = widgets.Label(value='Select models and target classes:')
    display(l)
    display(hClasses)

    def clearAndShow(btNewObj):
        clear_output()
        display(l)
        display(hClasses)
        display(h)

    def getExplainInteractiveButton(btn_object):
        getModelExplanationComparison(instID, le1, le2, wcl1.value, wcl2.value)

    btnTargetC = widgets.Button(description='Compute')
    btnTargetC.on_click(getExplainInteractiveButton)
    btnNewSel = widgets.Button(description='Clear')
    btnNewSel.on_click(clearAndShow)
    h = HBox([btnTargetC, btnNewSel])
    display(h)
コード例 #21
0
 def __create_all_losses_tab(self) -> HBox:
     skeleton_labels: VBox = VBox(children=[
         Label(value='Skeleton {:d} loss:'.format(i + 1))
         for i in range(self.number_of_skeletons)
     ])
     skeleton_losses: VBox = VBox(children=self.skeleton_loss_labels)
     statistics_labels_column: List[Label] = [
         Label(value='All losses:'),
         Label(value='Min loss skeleton index:'),
         Label(value='Max loss skeleton index:')
     ]
     statistics_values_column: List[Label] = [
         self.all_loss_label, self.min_loss_index_label,
         self.max_loss_index_label
     ]
     jump_buttons: List[Button] = self.__create_frame_jump_buttons(
         statistics_labels_column, statistics_values_column)
     statistics_labels: VBox = VBox(children=statistics_labels_column)
     statistics_values: VBox = VBox(children=statistics_values_column)
     all_losses_tab: HBox = HBox(children=[
         skeleton_labels, skeleton_losses, statistics_labels,
         statistics_values
     ] + ([VBox(children=jump_buttons)] if len(jump_buttons) > 0 else []))
     return all_losses_tab
コード例 #22
0
def edit_sheet(system, model: str):
    """
    Use ipysheet to edit parameters of one model.
    """

    sh = system.to_ipysheet(model, vin=True)
    header = widgets.Output()
    output = widgets.Output()

    button_upd = widgets.Button(description="Update")
    button_upd.on_click(on_update)
    button_upd.system = system
    button_upd.model = model
    button_upd.sheet = sh
    button_upd.output = output

    button_close = widgets.Button(description="Close")
    button_close.on_click(on_close)
    button_close.objects = [header, sh, button_upd, button_close, output]

    hbox = HBox((button_upd, button_close))
    ret = VBox((header, sh, hbox, output))

    return ret
コード例 #23
0
def lpm_posterior():
    a0, b0, c0 = [2.2e-3, 1.1e-1, 6.8e-3]
    dlog = 0.1
    sa = FloatSlider(value=dlog * a0 / 2,
                     description=r'$\sigma_a$',
                     min=0.,
                     max=dlog * a0,
                     step=dlog * a0 / 10.,
                     continuous_update=False)
    sb = FloatSlider(value=dlog * b0 / 2,
                     description=r'$\sigma_b$',
                     min=0.,
                     max=dlog * b0,
                     step=dlog * b0 / 10.,
                     continuous_update=False)
    dlog *= 5
    sc = FloatSlider(value=dlog * c0 / 2,
                     description=r'$\sigma_c$',
                     min=0.,
                     max=dlog * c0,
                     step=dlog * c0 / 10.,
                     continuous_update=False)
    Nmods = FloatLogSlider(value=4,
                           base=2,
                           description='samples',
                           min=0,
                           max=8,
                           step=1,
                           continuous_update=False)
    io = interactive_output(plot_lpm_posterior, {
        'sa': sa,
        'sb': sb,
        'sc': sc,
        'Nmods': Nmods
    })
    return VBox([HBox([sa, sb, sc, Nmods]), io])
コード例 #24
0
ファイル: utils.py プロジェクト: fbaumgardt/eeg-projects
def select_dataset(directory,
                   ext_in,
                   ext_out=None,
                   show_all=False,
                   single=False):
    files = [
        os.path.join(dp, f)
        for dp, dn, fn in os.walk(os.path.expanduser(directory)) for f in fn
        if os.path.isfile(os.path.join(dp, f)) and ext_in in f
    ]
    done = [] if ext_out is None else [
        os.path.join(dp, f)
        for dp, dn, fn in os.walk(os.path.expanduser(directory)) for f in fn
        if os.path.isfile(os.path.join(dp, f)) and ext_out in f
    ]
    subjects = [
        f[len(directory):-len(ext_in)] for f in files
        if show_all or ext_out is None or (f[:-len(ext_in)] +
                                           ext_out not in done)
    ]
    if single:
        widget = [
            Dropdown(options=subjects, description='Subject: ', disabled=False)
        ]
    else:
        widget = [
            Checkbox(True,
                     description=f[len(directory):-len(ext_in)],
                     indent=False) for f in files
            if show_all or ext_out is None or (f[:-len(ext_in)] +
                                               ext_out not in done)
        ]
    return HBox(widget,
                layout=Layout(width='100%',
                              display='inline-flex',
                              flex_flow='row wrap'))
コード例 #25
0
    def __init__(self, npkd, pkname):
        if not isinstance(npkd, FTMSData):
            raise Exception('This modules requires a FTMS Dataset')
        self.npkd = npkd
        self.pkname = pkname
        self.zoom = widgets.FloatRangeSlider(value=[npkd.axis1.lowmass, npkd.axis1.highmass],
            min=npkd.axis1.lowmass, max=npkd.axis1.highmass, step=0.1,
            layout=Layout(width='100%'), description='zoom',
            continuous_update=False, readout=True, readout_format='.1f',)
        self.zoom.observe(self.display)
        self.tlabel = Label('threshold (x noise level):')
        self.thresh = widgets.FloatLogSlider(value=20.0,
            min=np.log10(3), max=2.0, base=10, step=0.01, layout=Layout(width='30%'),
            continuous_update=False, readout=True, readout_format='.1f')
        self.thresh.observe(self.pickpeak)
        self.peak_mode = widgets.Dropdown(options=['marker', 'bar'],value='marker',description='show as')
        self.peak_mode.observe(self.display)
        self.bexport = widgets.Button(description="Export",layout=Layout(width='7%'),
                button_style='success', # 'success', 'info', 'warning', 'danger' or ''
                tooltip='Export to csv file')
        self.bexport.on_click(self.pkexport)
        self.bprint = widgets.Button(description="Print", layout=Layout(width='7%'),
                button_style='success', tooltip='Print to screen')
        self.bprint.on_click(self.pkprint)
        self.bdone = widgets.Button(description="Done", layout=Layout(width='7%'),
                button_style='warning', tooltip='Fix results')
        self.bdone.on_click(self.done)
#        self.spec = Output(layout={'border': '1px solid black'})
        self.out = Output(layout={'border': '1px solid red'})
        display( VBox([self.zoom,
                      HBox([self.tlabel, self.thresh, self.peak_mode, self.bprint, self.bexport, self.bdone])
                      ]) )
        self.fig, self.ax = plt.subplots()
        self.npkd.set_unit('m/z').peakpick(autothresh=self.thresh.value, verbose=False, zoom=self.zoom.value).centroid()
        self.display()
        display(self.out)
コード例 #26
0
def question7_2b(reponse):
    b = sp.Matrix([[4, 6, -3], [7, 14, -3], [4, -5, 1]])

    if np.abs(reponse - sp.det(b)) != 0:
        display(
            "Dans ce cas, la première rangée a été multiplié par deux et elle a été ajouté à la deuxième rangée"
        )
        display(Latex("$ Soit: 2 \\times R_1 + R_2 \\rightarrow R_2 $"))
        display("Le déterminant est le même")
        button = widgets.Button(description='Solution', disabled=False)
        box = HBox(children=[button])
        out = widgets.Output()

        @out.capture()
        def solution(e):
            out.clear_output()
            Determinant_3x3(b, step_by_step=True)

        button.on_click(solution)

        display(box)
        display(out)
    else:
        display("Bravo! Vous avez trouvé la réponse")
コード例 #27
0
def gradient_descent():
    csldr = IntSlider(value=10,
                      description='$c$',
                      min=0,
                      max=20,
                      step=1,
                      readout=False,
                      continuous_update=False)
    ksldr = IntSlider(value=10,
                      description='$k$',
                      min=3,
                      max=17,
                      step=1,
                      readout=False,
                      continuous_update=False)
    Nsldr = IntSlider(value=0,
                      description='steps',
                      min=0,
                      max=10,
                      step=1,
                      continuous_update=False)
    asldr = FloatSlider(value=0.05,
                        description=r'$\alpha$',
                        min=0,
                        max=0.10,
                        step=0.02,
                        continuous_update=False)
    return VBox([
        HBox([csldr, ksldr, Nsldr, asldr]),
        interactive_output(plot_parameter_space3, {
            'ic': csldr,
            'ik': ksldr,
            'N': Nsldr,
            'alpha': asldr
        })
    ])
コード例 #28
0
    def add_bar(self, job):
        self.bars[job] = FloatProgress(
            value=0.0,
            min=0.0,
            max=100.0,
            description="Job: %04d Stage: %04d" % (job, 0),
            bar_style="info",
            orientation="horizontal",
            style=self.style,
        )
        self.bars[job].add_class("db-bar")
        self.labels[job] = Label(
            value="",
            description="Code:",
            disabled=False,
            layout=Layout(width="800px", height="100%", margin="0 0 0 5px"),
        )
        self.labels[job].add_class("db-label")

        progressbar = HBox([self.bars[job], self.labels[job]])
        self.progressbars.children = self.progressbars.children + (progressbar,)
        if not self.progressbar_showing:
            self.progressbar_showing = True
            display(self.indicator)
コード例 #29
0
ファイル: visualization.py プロジェクト: miroenev/rapids
def append_label_buttons(swarm, ipvFig, container=None):

    xyzLabelsButton = widgets.Button(description="x, y, z labels")
    paramNamesLabelsButton = widgets.Button(description="parameter labels")

    def xyz_labels(_):
        ipv.figure(ipvFig).set_trait('xlabel', 'x')
        ipv.figure(ipvFig).set_trait('ylabel', 'y')
        ipv.figure(ipvFig).set_trait('zlabel', 'z')

    def param_labels(_):
        ipv.figure(ipvFig).set_trait('xlabel', str(swarm.paramRanges[0][0]))
        ipv.figure(ipvFig).set_trait('ylabel', str(swarm.paramRanges[1][0]))
        ipv.figure(ipvFig).set_trait('zlabel', str(swarm.paramRanges[2][0]))

    xyzLabelsButton.on_click(xyz_labels)
    paramNamesLabelsButton.on_click(param_labels)

    if container is None:
        container = ipvFig
    comboBox = VBox(
        [container, HBox([xyzLabelsButton, paramNamesLabelsButton])])
    comboBox.layout.align_items = 'center'
    return comboBox
コード例 #30
0
def sensitivity():
    csldr = IntSlider(value=10,
                      description='$c$',
                      min=0,
                      max=20,
                      step=1,
                      readout=False,
                      continuous_update=False)
    ksldr = IntSlider(value=10,
                      description='$k$',
                      min=3,
                      max=17,
                      step=1,
                      readout=False,
                      continuous_update=False)
    check = Checkbox(value=False, description='check my answer')
    return VBox([
        HBox([csldr, ksldr, check]),
        interactive_output(plot_parameter_space2, {
            'ic': csldr,
            'ik': ksldr,
            'check': check
        })
    ])