Python ipywidgets.FloatSlider() Examples

The following are 28 code examples of ipywidgets.FloatSlider(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ipywidgets , or try the search function .
Example #1
Source File: test_interaction.py    From pySINDy with MIT License 6 votes vote down vote up
def test_single_value_float():
    for a in (2.25, 1.0, -3.5, 0.0):
        if not a:
            expected_min = 0.0
            expected_max = 1.0
        elif a > 0:
            expected_min = -a
            expected_max = 3*a
        else:
            expected_min = 3*a
            expected_max = -a
        c = interactive(f, a=a)
        w = c.children[0]
        check_widget(w,
            cls=widgets.FloatSlider,
            description='a',
            value=a,
            min=expected_min,
            max=expected_max,
            step=0.1,
            readout=True,
        ) 
Example #2
Source File: test_interaction.py    From pySINDy with MIT License 6 votes vote down vote up
def test_defaults():
    @annotate(n=10)
    def f(n, f=4.5, g=1):
        pass

    c = interactive(f)
    check_widgets(c,
        n=dict(
            cls=widgets.IntSlider,
            value=10,
        ),
        f=dict(
            cls=widgets.FloatSlider,
            value=4.5,
        ),
        g=dict(
            cls=widgets.IntSlider,
            value=1,
        ),
    ) 
Example #3
Source File: test_interaction.py    From pySINDy with MIT License 6 votes vote down vote up
def test_default_out_of_bounds():
    @annotate(f=(0, 10.), h={'a': 1}, j=['hi', 'there'])
    def f(f='hi', h=5, j='other'):
        pass

    c = interactive(f)
    check_widgets(c,
        f=dict(
            cls=widgets.FloatSlider,
            value=5.,
        ),
        h=dict(
            cls=widgets.Dropdown,
            options={'a': 1},
            value=1,
        ),
        j=dict(
            cls=widgets.Dropdown,
            options=('hi', 'there'),
            value='hi',
        ),
    ) 
Example #4
Source File: pylab.py    From ipyvolume with MIT License 6 votes vote down vote up
def controls_light(return_widget=False):
    fig = gcf()
    ambient_coefficient = ipywidgets.FloatSlider(
        min=0, max=1, step=0.001, value=fig.ambient_coefficient, description="ambient"
    )
    diffuse_coefficient = ipywidgets.FloatSlider(
        min=0, max=1, step=0.001, value=fig.diffuse_coefficient, description="diffuse"
    )
    specular_coefficient = ipywidgets.FloatSlider(
        min=0, max=1, step=0.001, value=fig.specular_coefficient, description="specular"
    )
    specular_exponent = ipywidgets.FloatSlider(
        min=0, max=10, step=0.001, value=fig.specular_exponent, description="specular exp"
    )
    ipywidgets.jslink((fig, 'ambient_coefficient'), (ambient_coefficient, 'value'))
    ipywidgets.jslink((fig, 'diffuse_coefficient'), (diffuse_coefficient, 'value'))
    ipywidgets.jslink((fig, 'specular_coefficient'), (specular_coefficient, 'value'))
    ipywidgets.jslink((fig, 'specular_exponent'), (specular_exponent, 'value'))
    widgets_bottom = [
        ipywidgets.HBox([ambient_coefficient, diffuse_coefficient]),
        ipywidgets.HBox([specular_coefficient, specular_exponent]),
    ]
    current.container.children += tuple(widgets_bottom)
    if return_widget:
        return widgets_bottom 
Example #5
Source File: components.py    From notebook-molecular-visualization with Apache License 2.0 6 votes vote down vote up
def __init__(self, format=None, *args, **kwargs):
        description = kwargs.pop('description', 'FloatSlider')
        min = kwargs.setdefault('min', 0.0)
        max = kwargs.setdefault('max', 10.0)
        self.formatstring = format
        self.header = ipy.HTML()
        self.readout = ipy.Text(layout=ipy.Layout(width='100px'))
        self.readout.on_submit(self.parse_value)

        kwargs.setdefault('readout', False)
        self.slider = ipy.FloatSlider(*args, **process_widget_kwargs(kwargs))
        self.minlabel = ipy.HTML(u'<font size=1.5>{}</font>'.format(self.formatstring.format(min)))
        self.maxlabel = ipy.HTML(u'<font size=1.5>{}</font>'.format(self.formatstring.format(max)))
        self.sliderbox = HBox([self.minlabel, self.slider, self.maxlabel])
        traitlets.link((self, 'description'), (self.header, 'value'))
        traitlets.link((self, 'value'), (self.slider, 'value'))
        self.description = description
        self.update_readout()
        super().__init__([self.header,
                                                  self.readout,
                                                  self.sliderbox]) 
Example #6
Source File: rtlsdr_helper.py    From scikit-dsp-comm with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _interact_frequency(self,freq_val,min_freq=87.5,max_freq=108,freq_step=0.2):
        '''
        Sets up tuning frequency slider widget for Mono FM Example
        '''
        self.slider = FloatSlider(
            value=freq_val,
            min=min_freq,
            max=max_freq,
            step=freq_step,
            description=r'$f_c\;$',
            continuous_update=False,
            orientation='horizontal',
            readout_format='0.1f',
            layout=Layout(
                width='90%',
            ) 
        )
        self.slider.style.handle_color = 'lightblue'

        self.center_freq_widget = interactive(self.set_fc_mhz, fc = self.slider)
        display(self.center_freq_widget) 
Example #7
Source File: rtlsdr_helper.py    From scikit-dsp-comm with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _interact_audio_gain(self,gain_val=0,min_gain=-60,max_gain=6,gain_step=0.1):
        '''
        Sets up audio gain slider widget for Mono FM Example
        '''
        self.gain_slider = FloatSlider(
            value=gain_val,
            min=min_gain,
            max=max_gain,
            step=gain_step,
            description='Gain (dB)',
            continuous_update=True,
            orientation='horizontal',
            readout_format='0.1f',
            layout=Layout(
                width='90%',
            )
        )
        self.gain_slider.style.handle_color = 'lightgreen'

        self.audio_gain_widget = interactive(self.set_audio_gain_db,gain=self.gain_slider)
        display(self.audio_gain_widget) 
Example #8
Source File: dashboards.py    From ray-optics with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_focus_dashboard(figs, ray_data_items, foc, dfoc_rng, shift_rng,
                           on_axis_pt, continuous_update=True):
    defocus = widgets.FloatSlider(min=-dfoc_rng, max=+dfoc_rng,
                                  step=.01*dfoc_rng,
                                  description='defocus', value=foc,
                                  readout_format='.4f',
                                  continuous_update=continuous_update)
    x_shift = widgets.FloatSlider(min=-shift_rng, max=+shift_rng,
                                  step=.01*shift_rng,
                                  description='x shift', value=on_axis_pt[0],
                                  readout_format='.4f',
                                  continuous_update=continuous_update)
    y_shift = widgets.FloatSlider(min=-shift_rng, max=+shift_rng,
                                  step=.01*shift_rng,
                                  description='y shift', value=on_axis_pt[1],
                                  readout_format='.4f',
                                  continuous_update=continuous_update)

    def slider_update(change):
        dfoc_val = defocus.value
        dx = x_shift.value
        dy = y_shift.value

        # apply changes to fans and grids
        for ray_data in ray_data_items:
            ray_data.foc = dfoc_val
            ray_data.image_pt_2d = np.array([dx, dy])
            ray_data.update_data(build='update')

        # update and plot results
        for fig in figs:
            fig.clf()
            fig.plot()

    defocus.observe(slider_update, names='value')
    x_shift.observe(slider_update, names='value')
    y_shift.observe(slider_update, names='value')

    return defocus, x_shift, y_shift 
Example #9
Source File: widgets.py    From SlicerJupyter with MIT License 5 votes vote down vote up
def __init__(self, view=None, **kwargs):
        if view:
            self.viewName=view

        self.offsetSlider = FloatSlider(description='Offset')

        self.updateImage()

        self._updateOffsetRange()
        self.l1 = link((self.offsetSlider, 'value'), (self, 'offset'))
        self.l2 = link((self, 'offsetMin'), (self.offsetSlider, 'min'))
        self.l3 = link((self, 'offsetMax'), (self.offsetSlider, 'max'))

        super().__init__(**kwargs) 
Example #10
Source File: ABuWGSellFactor.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def _init_widget(self):
        """构建AbuFactorPreAtrNStop策略参数界面"""
        self.description = widgets.Textarea(
            value=u'风险控制止损策略:\n'
                  u'1. 单日最大跌幅n倍atr止损\n'
                  u'2. 当今日价格下跌幅度 > 当日atr 乘以 pre_atr_n(下跌止损倍数)卖出操作',
            description=u'风险止损',
            disabled=False,
            layout=self.description_layout
        )

        self.pre_atr_n_label = widgets.Label(u'当今天价格开始剧烈下跌,采取果断平仓措施',
                                             layout=self.label_layout)
        self.pre_atr_n = widgets.FloatSlider(
            value=1.5,
            min=0.10,
            max=10.0,
            step=0.1,
            description='pre_atr_n',
            disabled=False,
            orientation='horizontal',
            readout=True,
            readout_format='.1f',
        )
        self.pre_atr_n_box = widgets.VBox([self.pre_atr_n_label, self.pre_atr_n])
        self.widget = widgets.VBox([self.description, self.pre_atr_n_box, self.add_box],  # border='solid 1px',
                                   layout=self.widget_layout) 
Example #11
Source File: ABuWGSellFactor.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def _init_widget(self):
        """构建AbuFactorCloseAtrNStop策略参数界面"""
        self.description = widgets.Textarea(
            value=u'利润保护止盈策略:\n'
                  u'1. 买入后最大收益价格 - 今日价格 > 一定收益\n'
                  u'2. 买入后最大收益价格 - 今日价格 < close_atr_n * 当日atr\n'
                  u'3. 当买入有一定收益后,如果下跌幅度超过close_atr_n乘以当日atr->保护止盈卖出',
            description=u'保护止盈',
            disabled=False,
            layout=self.description_layout
        )

        self.close_atr_n_label = widgets.Label(u'收益下跌超过close_atr_n乘以当日atr->保护止盈',
                                               layout=self.label_layout)
        self.close_atr_n = widgets.FloatSlider(
            value=1.5,
            min=0.10,
            max=10.0,
            step=0.1,
            description='close_atr_n',
            disabled=False,
            orientation='horizontal',
            readout=True,
            readout_format='.1f',
        )
        self.close_atr_n_box = widgets.VBox([self.close_atr_n_label, self.close_atr_n])
        self.widget = widgets.VBox([self.description, self.close_atr_n_box, self.add_box],  # border='solid 1px',
                                   layout=self.widget_layout) 
Example #12
Source File: ABuWGTLTool.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def _init_tip_label_with_step_x(self, callback_analyse, analyse_name, with_step_x=True):
        """step_x需要的地方比较多,统一构建,外部接收赋予名字"""
        if not callable(callback_analyse):
            raise TabError('callback_analyse must callable!')

        tip_label = widgets.Label(self.map_tip_target_label(n_target=1), layout=self.label_layout)
        widget_list = [tip_label]
        step_x = None
        if with_step_x:
            step_x_label = widgets.Label(u'时间步长控制参数step_x,默认1.0',
                                         layout=self.label_layout)
            step_x = widgets.FloatSlider(
                value=1.0,
                min=0.1,
                max=2.6,
                step=0.1,
                description=u'步长',
                disabled=False,
                orientation='horizontal',
                readout=True,
                readout_format='.1f',
            )
            # 返回给需要的ui,命名独有的step_x
        yield widget_list, step_x

        if with_step_x:
            # noinspection PyUnboundLocalVariable
            step_x_box = widgets.VBox([step_x_label, step_x])
            # noinspection PyTypeChecker
            widget_list.append(step_x_box)

        analyse_bt = widgets.Button(description=analyse_name, layout=widgets.Layout(width='98%'),
                                    button_style='info')
        analyse_bt.on_click(callback_analyse)
        widget_list.append(analyse_bt) 
Example #13
Source File: cad_display.py    From jupyter-cadquery with Apache License 2.0 5 votes vote down vote up
def slider(self, value, min, max, step, description):
        label = Label(description)
        self.labels.append(label)
        ind = len(self.normals)
        button = ImageButton(
            width=36,
            height=28,
            image_path="%s/plane.png" % (self.image_path),
            tooltip="Set clipping plane",
            type=str(ind),
            layout=Layout(margin="0px 10px 0px 0px"))
        button.on_click(self.handler)
        button.add_class("view_button")

        slider = FloatSlider(
            value=value,
            min=min,
            max=max,
            step=step,
            description="",
            disabled=False,
            continuous_update=False,
            orientation='horizontal',
            readout=True,
            readout_format='.2f',
            layout=Layout(width="%dpx" % (self.width - 20)))

        slider.observe(self.cq_view.clip(ind), "value")
        return [HBox([button, label]), slider] 
Example #14
Source File: test_widget_float.py    From pySINDy with MIT License 5 votes vote down vote up
def test_construction_invalid_readout_format(self):
        with self.assertRaises(TraitError):
            FloatSlider(readout_format='broken') 
Example #15
Source File: test_widget_float.py    From pySINDy with MIT License 5 votes vote down vote up
def test_construction_readout_format(self):
        slider = FloatSlider(readout_format='$.1f')
        assert slider.get_state()['readout_format'] == '$.1f' 
Example #16
Source File: test_widget_float.py    From pySINDy with MIT License 5 votes vote down vote up
def test_construction(self):
        FloatSlider() 
Example #17
Source File: explorer.py    From scqubits with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def interact(self):
        """Drives the interactive display of the plot explorer panels"""
        param_min = self.param_vals[0]
        param_max = self.param_vals[-1]
        param_step = self.param_vals[1] - self.param_vals[0]

        qbt_indices = [index for (index, subsystem) in self.sweep.qbt_subsys_list]
        osc_indices = [index for (index, subsystem) in self.sweep.osc_subsys_list]

        param_slider = ipywidgets.FloatSlider(min=param_min, max=param_max, step=param_step,
                                              description=self.param_name, continuous_update=False)
        photon_slider = ipywidgets.IntSlider(value=1, min=1, max=4, description='photon number')
        initial_slider = ipywidgets.IntSlider(value=0, min=0, max=self.evals_count, description='initial state index')
        final_slider = ipywidgets.IntSlider(value=1, min=1, max=self.evals_count, description='final state index')

        qbt_dropdown = ipywidgets.Dropdown(options=qbt_indices, description='qubit subsys')
        osc_dropdown = ipywidgets.Dropdown(options=osc_indices, description='oscillator subsys')

        def update_min_final_index(*args):
            final_slider.min = initial_slider.value + 1

        initial_slider.observe(update_min_final_index, 'value')

        out = ipywidgets.interactive_output(self.plot_explorer_panels,
                                            {'param_val': param_slider,
                                             'photonnumber': photon_slider,
                                             'initial_index': initial_slider,
                                             'final_index': final_slider,
                                             'qbt_index': qbt_dropdown,
                                             'osc_index': osc_dropdown
                                             })

        left_box = ipywidgets.VBox([param_slider])
        mid_box = ipywidgets.VBox([initial_slider, final_slider, photon_slider])
        right_box = ipywidgets.VBox([qbt_dropdown, osc_dropdown])

        user_interface = ipywidgets.HBox([left_box, mid_box, right_box])
        display(user_interface, out) 
Example #18
Source File: pylab.py    From ipyvolume with MIT License 4 votes vote down vote up
def animation_control(object, sequence_length=None, add=True, interval=200):
    """Animate scatter, quiver or mesh by adding a slider and play button.

    :param object: :any:`Scatter` or :any:`Mesh` object (having an sequence_index property), or a list of these to
                   control multiple.
    :param sequence_length: If sequence_length is None we try try our best to figure out, in case we do it badly,
            you can tell us what it should be. Should be equal to the S in the shape of the numpy arrays as for instance
            documented in :any:`scatter` or :any:`plot_mesh`.
    :param add: if True, add the widgets to the container, else return a HBox with the slider and play button. Useful when you
            want to customise the layout of the widgets yourself.
    :param interval: interval in msec between each frame
    :return: If add is False, if returns the ipywidgets.HBox object containing the controls
    """
    if isinstance(object, (list, tuple)):
        objects = object
    else:
        objects = [object]
    del object
    if sequence_length is None:
        # get all non-None arrays
        sequence_lengths = []
        for object in objects:
            sequence_lengths_previous = list(sequence_lengths)
            values = [getattr(object, name) for name in "x y z aux vx vy vz".split() if hasattr(object, name)]
            values = [k for k in values if k is not None]
            # sort them such that the higest dim is first
            values.sort(key=lambda key: -len(key.shape))
            try:
                sequence_length = values[0].shape[0]  # assume this defines the sequence length
                if isinstance(object, ipv.Mesh):  # for a mesh, it does not make sense to have less than 1 dimension
                    if len(values[0].shape) >= 2:  # if just 1d, it is most likely not an animation
                        sequence_lengths.append(sequence_length)
                else:
                    sequence_lengths.append(sequence_length)
            except IndexError:  # scalars get ignored
                pass
            if hasattr(object, 'color'):
                color = object.color
                if color is not None:
                    shape = color.shape
                    if len(shape) == 3:  # would be the case for for (frame, point_index, color_index)
                        sequence_lengths.append(shape[0])
                    # TODO: maybe support arrays of string type of form (frame, point_index)
            if len(sequence_lengths) == len(sequence_lengths_previous):
                raise ValueError('no frame dimension found for object: {}'.format(object))
        sequence_length = max(sequence_lengths)
    fig = gcf()
    fig.animation = interval
    fig.animation_exponent = 1.0
    play = ipywidgets.Play(min=0, max=sequence_length - 1, interval=interval, value=0, step=1)
    slider = ipywidgets.FloatSlider(min=0, max=play.max, step=1)
    ipywidgets.jslink((play, 'value'), (slider, 'value'))
    for object in objects:
        ipywidgets.jslink((slider, 'value'), (object, 'sequence_index'))
    control = ipywidgets.HBox([play, slider])
    if add:
        current.container.children += (control,)
    else:
        return control 
Example #19
Source File: pointcloud.py    From AlignNet-3D with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def show(self, show_point_color=False):
        initial_point_size = 0.03
        point_materials = []
        for idx, (name, points) in enumerate(self.points.items()):
            if idx == 0:
                cloud = PyntCloud(points.get_points(show_point_color=show_point_color))
                #  print(clean_polylines(self.polylines))
                self.scene = cloud.plot(return_scene=True, initial_point_size=initial_point_size, polylines=clean_polylines(self.polylines), background=self.background)
                pss = [ps for ps in self.scene.children if type(ps) == pythreejs.objects.Points_autogen.Points]
                assert len(pss) > 0
                pss[0].name = name
                if points.opacity is not None:
                    pss[0].material.opacity = points.opacity
                    pss[0].material.transparent = True
                point_materials.append(pss[0].material)
            else:
                ppoints = get_points(points.points, points.color, show_point_color=show_point_color)
                ps = pyntcloud.plot.pythreejs_backend.get_pointcloud_pythreejs(ppoints[["x", "y", "z"]].values, ppoints[['red', 'green', 'blue']].values / 255.)
                ps.name = name
                ps.material.size = initial_point_size
                self.scene.children = [ps] + list(self.scene.children)
                if points.opacity is not None:
                    ps.material.opacity = points.opacity
                    ps.material.transparent = True
                #  if name == 'original':
                #      ps.material.opacity = 0.3
                #      ps.material.transparent = True
                point_materials.append(ps.material)

        for idx, (name, mesh) in enumerate(self.meshes.items()):
            # https://render.githubusercontent.com/view/ipynb?commit=645ea6bea758555978f83bd0004ce561fa58d99c&enc_url=68747470733a2f2f7261772e67697468756275736572636f6e74656e742e636f6d2f6a7570797465722d776964676574732f707974687265656a732f363435656136626561373538353535393738663833626430303034636535363166613538643939632f6578616d706c65732f4578616d706c65732e6970796e62&nwo=jupyter-widgets%2Fpythreejs&path=examples%2FExamples.ipynb&repository_id=15400194&repository_type=Repository#Buffer-Geometries
            vertices = mesh.get_vertices()
            faces = mesh.get_faces()
            vertexcolors = ['#ff0000' for _ in range(len(vertices))]
            # Map the vertex colors into the 'color' slot of the faces
            faces = [f + [None, [vertexcolors[i] for i in f], None] for f in faces]
            geometry = pythreejs.Geometry(vertices=vertices, faces=faces, colors=vertexcolors)
            geometry.exec_three_obj_method('computeFaceNormals')
            mesh_obj = pythreejs.Mesh(geometry=geometry, material=pythreejs.MeshBasicMaterial(color='white', side='DoubleSide'), position=[0, 0, 0])
            mesh_obj.name = name
            self.scene.children = [mesh_obj] + list(self.scene.children)

        for key, value in self.visibility_dict.items():
            self.change_visibility(key, value)

        widgets = []
        size = ipywidgets.FloatSlider(value=initial_point_size, min=0.0, max=initial_point_size * 10, step=initial_point_size / 100)
        for point_materials in point_materials:
            ipywidgets.jslink((size, 'value'), (point_materials, 'size'))
        widgets.append(ipywidgets.Label('Point size:'))
        widgets.append(size)
        display(ipywidgets.HBox(children=widgets))


#  if __name__ == '__main__':
#      test() 
Example #20
Source File: dashboards.py    From ray-optics with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def create_mirror_tilt_dashboard(mirror, app_mgr, figs, ray_data_items,
                                 foc, tilt_rng, shift_rng, oa_ray=None,
                                 continuous_update=True):
    tilt0 = mirror.decenter.euler[0]
    alpha_tilt = widgets.FloatSlider(min=tilt0-tilt_rng, max=tilt0+tilt_rng,
                                     step=.05*tilt_rng,
                                     description='alpha tilt', value=tilt0,
                                     readout_format='.4f',
                                     continuous_update=continuous_update)
    x_shift = widgets.FloatSlider(min=-shift_rng, max=+shift_rng,
                                  step=.05*shift_rng, description='x shift',
                                  value=0., readout_format='.4f',
                                  continuous_update=continuous_update)
    y_shift = widgets.FloatSlider(min=-shift_rng, max=+shift_rng,
                                  step=.05*shift_rng, description='y shift',
                                  value=0., readout_format='.4f',
                                  continuous_update=continuous_update)

    def make_slider_callback(changer):
        def slider_update(change):
            changer.set(change['new'])

            app_mgr.refresh_gui(build='update')

            if oa_ray is not None:
                oa_ray.update_data(build='rebuild')

            # apply changes to fans and grids
            for ray_data in ray_data_items:
                # if oa_ray is not None:
                #     ray_data.image_pt_2d = oa_ray.t_abr
                ray_data.update_data(build='rebuild')

            # update and plot results
            for fig in figs:
                fig.clf()
                fig.plot()

        return slider_update

    alpha_tilt.observe(make_slider_callback(AttrChanger(mirror.decenter,
                                                        'euler', index=0)),
                       names='value')
    x_shift.observe(make_slider_callback(AttrChanger(mirror.decenter,
                                                     'dec', index=0)),
                    names='value')
    y_shift.observe(make_slider_callback(AttrChanger(mirror.decenter,
                                                     'dec', index=1)),
                    names='value')

    return alpha_tilt, x_shift, y_shift 
Example #21
Source File: pylab.py    From ipyvolume with MIT License 4 votes vote down vote up
def figure(
    key=None,
    width=400,
    height=500,
    lighting=True,
    controls=True,
    controls_vr=False,
    controls_light=False,
    debug=False,
    **kwargs
):
    """Create a new figure if no key is given, or return the figure associated with key.

    :param key: Python object that identifies this figure
    :param int width: pixel width of WebGL canvas
    :param int height:  .. height ..
    :param bool lighting: use lighting or not
    :param bool controls: show controls or not
    :param bool controls_vr: show controls for VR or not
    :param bool debug: show debug buttons or not
    :return: :any:`Figure`
    """
    if key is not None and key in current.figures:
        current.figure = current.figures[key]
        current.container = current.containers[key]
    elif isinstance(key, ipv.Figure) and key in current.figures.values():
        key_index = list(current.figures.values()).index(key)
        key = list(current.figures.keys())[key_index]
        current.figure = current.figures[key]
        current.container = current.containers[key]
    else:
        current.figure = ipv.Figure(width=width, height=height, **kwargs)
        current.container = ipywidgets.VBox()
        current.container.children = [current.figure]
        if key is None:
            key = uuid.uuid4().hex
        current.figures[key] = current.figure
        current.containers[key] = current.container
        if controls:
            # stereo = ipywidgets.ToggleButton(value=current.figure.stereo, description='stereo', icon='eye')
            # l1 = ipywidgets.jslink((current.figure, 'stereo'), (stereo, 'value'))
            # current.container.children += (ipywidgets.HBox([stereo, ]),)
            pass  # stereo and fullscreen are now include in the js code (per view)
        if controls_vr:
            eye_separation = ipywidgets.FloatSlider(value=current.figure.eye_separation, min=-10, max=10, icon='eye')
            ipywidgets.jslink((eye_separation, 'value'), (current.figure, 'eye_separation'))
            current.container.children += (eye_separation,)
        if controls_light:
            globals()['controls_light']()
        if debug:
            show = ipywidgets.ToggleButtons(options=["Volume", "Back", "Front", "Coordinate"])
            current.container.children += (show,)
            # ipywidgets.jslink((current.figure, 'show'), (show, 'value'))
            traitlets.link((current.figure, 'show'), (show, 'value'))
    return current.figure 
Example #22
Source File: orbital_viewer.py    From notebook-molecular-visualization with Apache License 2.0 4 votes vote down vote up
def _make_ui_pane(self, hostheight):
        layout = ipy.Layout(width='325px',
                            height=str(int(hostheight.rstrip('px')) - 50) + 'px')
        #element_height = str(int(hostheight.rstrip('px')) - 125) + 'px'
        element_height = None
        # NOTE - element_height was used for the listbox-style orblist.
        #   HOWEVER ipywidgets 6.0 only displays those as a dropdown.
        #   This is therefore disabled until we can display listboxes again. -- AMV 7/16

        # Orbital set selector
        self.status_element = ipy.HTML(layout=ipy.Layout(width='inherit', height='20px'))
        orbtype_label = ipy.Label("Orbital set:")
        self.type_dropdown = ipy.Dropdown(options=list(self.wfn.orbitals.keys()))
        initialtype = 'canonical'
        if initialtype not in self.type_dropdown.options:
            initialtype = next(iter(self.type_dropdown.options.keys()))
        self.type_dropdown.value = initialtype
        self.type_dropdown.observe(self.new_orb_type, 'value')

        # List of orbitals in this set
        orblist_label = ipy.Label("Orbital:")
        self.orblist = ipy.Dropdown(options={None: None},
                                    layout=ipy.Layout(width=layout.width, height=element_height))
        traitlets.link((self.orblist, 'value'), (self, 'current_orbital'))

        # Isovalue selector
        isoval_label = ipy.Label('Isovalue:')
        self.isoval_selector = ipy.FloatSlider(min=0.0, max=0.075,
                                               value=0.01, step=0.00075,
                                               readout_format='.4f',
                                               layout=ipy.Layout(width=layout.width))
        traitlets.link((self.isoval_selector, 'value'), (self, 'isoval'))

        # Opacity selector
        opacity_label = ipy.Label('Opacity:')
        self.opacity_selector = ipy.FloatSlider(min=0.0, max=1.0,
                                               value=0.8, step=0.01,
                                               readout_format='.2f',
                                               layout=ipy.Layout(width=layout.width))
        traitlets.link((self.opacity_selector, 'value'), (self, 'orb_opacity'))

        # Resolution selector
        resolution_label = ipy.Label("Grid resolution:", layout=ipy.Layout(width=layout.width))
        self.orb_resolution = ipy.Text(layout=ipy.Layout(width='75px',
                                                         positioning='bottom'))
        self.orb_resolution.value = str(self.numpoints)
        self.resolution_button = ipy.Button(description='Update resolution')
        self.resolution_button.on_click(self.change_resolution)
        traitlets.directional_link((self, 'numpoints'), (self.orb_resolution, 'value'),
                                   transform=str)

        self.uipane = ipy.VBox([self.status_element,
                                orbtype_label, self.type_dropdown,
                                orblist_label, self.orblist,
                                isoval_label, self.isoval_selector,
                                opacity_label, self.opacity_selector,
                                resolution_label, self.orb_resolution, self.resolution_button])
        self.new_orb_type()
        self.type_dropdown.observe(self.new_orb_type, 'value')
        return self.uipane 
Example #23
Source File: ABuWGTLTool.py    From abu with GNU General Public License v3.0 4 votes vote down vote up
def init_jump_ui(self):
        """跳空分析ui"""

        with self._init_tip_label_with_step_x(
                self._jump_line_analyse, u'跳空技术分析', with_step_x=False) as (widget_list, _):
            self.jump_mode = widgets.RadioButtons(
                options={u'跳空统计分析': 0, u'跳空缺口筛选': 1, u'缺口时间加权筛选': 2},
                value=0,
                description=u'分析模式:',
                disabled=False
            )
            widget_list.append(self.jump_mode)

            power_threshold_label = widgets.Label(u'缺口能量阀值,默认2.0(只对缺口筛选生效)',
                                                  layout=self.label_layout)
            self.power_threshold = widgets.FloatSlider(
                value=2.0,
                min=1.5,
                max=3.5,
                step=0.1,
                description=u'能量',
                disabled=False,
                orientation='horizontal',
                readout=True,
                readout_format='.1f',
            )
            power_threshold_box = widgets.VBox([power_threshold_label, self.power_threshold])
            widget_list.append(power_threshold_box)

            jump_diff_factor_label = widgets.Label(u'设置调节跳空阀值的大小',
                                                   layout=self.label_layout)
            self.jump_diff_factor = widgets.FloatSlider(
                value=1.0,
                min=0.1,
                max=5.0,
                step=0.1,
                description=u'阀值',
                disabled=False,
                orientation='horizontal',
                readout=True,
                readout_format='.1f',
            )
            jump_diff_factor_box = widgets.VBox([jump_diff_factor_label, self.jump_diff_factor])
            widget_list.append(jump_diff_factor_box)

        return widgets.VBox(widget_list,
                            # border='solid 1px',
                            layout=self.tool_layout) 
Example #24
Source File: ABuWGPosition.py    From abu with GNU General Public License v3.0 4 votes vote down vote up
def _init_widget(self):
        """构建AbuAtrPosition策略参数界面"""

        description = widgets.Textarea(
            value=u'atr资金仓位管理策略:\n'
                  u'默认的仓位资金管理全局策略\n'
                  u'根据决策买入当天的价格波动决策资金仓位配比\n'
                  u'注意不同于卖策,选股,一个买入因子只能有唯一个资金仓位管理策略',
            description=u'atr资管',
            disabled=False,
            layout=self.description_layout
        )

        atr_pos_base_label = widgets.Label(u'仓位基础配比:默认0.1即资金10%为仓位基数',
                                           layout=self.label_layout)
        # 需要精确到小数点后5位
        self.atr_pos_base = widgets.FloatSlider(
            value=0.10,
            min=0.00001,
            max=1.0,
            step=0.00001,
            description=u'基配',
            disabled=False,
            orientation='horizontal',
            readout=True,
            readout_format='.5f'
        )
        atr_pos_base_box = widgets.VBox([atr_pos_base_label, self.atr_pos_base])

        atr_base_price_label = widgets.Label(u'常数价格设定:默认15,建议在12-20之间',
                                             layout=self.label_layout)
        self.atr_base_price = widgets.IntSlider(
            value=15,
            min=12,
            max=20,
            step=1,
            description=u'常价',
            disabled=False,
            orientation='horizontal',
            readout=True,
            readout_format='d'
        )
        atr_base_price_box = widgets.VBox([atr_base_price_label, self.atr_base_price])

        # TODO AbuAtrPosition策略中std_atr_threshold的设置

        self.widget = widgets.VBox([description, atr_pos_base_box, atr_base_price_box,
                                    self.add_box], layout=self.widget_layout) 
Example #25
Source File: ABuWGPosition.py    From abu with GNU General Public License v3.0 4 votes vote down vote up
def _init_widget(self):
        """构建AbuKellyPosition策略参数界面"""

        description = widgets.Textarea(
            value=u'kelly资金仓位管理策略:\n'
                  u'根据策略历史胜率期望,盈利期望,亏损期望决策资金仓位配比\n'
                  u'仓位资金配比 = 胜率 - 败率/(盈利期望/亏损期望)\n'
                  u'注意不同于卖策,选股,一个买入因子只能有唯一个资金仓位管理策略',
            description=u'kelly资管',
            disabled=False,
            layout=self.description_layout
        )

        win_rate_label = widgets.Label(u'策略历史胜率期望,默认0.5即50%胜率',
                                       layout=self.label_layout)
        # 需要精确到小数点后5位
        self.win_rate = widgets.FloatSlider(
            value=0.50,
            min=0.01,
            max=1.00,
            step=0.0001,
            description=u'胜率期望',
            disabled=False,
            orientation='horizontal',
            readout=True,
            readout_format='.4f'
        )
        win_rate_box = widgets.VBox([win_rate_label, self.win_rate])

        gains_mean_label = widgets.Label(u'策略历史盈利期望,默认0.1即10%',
                                         layout=self.label_layout)
        self.gains_mean = widgets.FloatSlider(
            value=0.10,
            min=0.01,
            max=100.00,
            step=0.0001,
            description=u'盈利期望',
            disabled=False,
            orientation='horizontal',
            readout=True,
            readout_format='.4f'
        )
        gains_mean_box = widgets.VBox([gains_mean_label, self.gains_mean])

        losses_mean_label = widgets.Label(u'策略历史亏损期望,默认0.05即5%',
                                          layout=self.label_layout)
        self.losses_mean = widgets.FloatSlider(
            value=0.05,
            min=0.01,
            max=100.00,
            step=0.0001,
            description=u'亏损期望',
            disabled=False,
            orientation='horizontal',
            readout=True,
            readout_format='.4f'
        )
        losses_mean_box = widgets.VBox([losses_mean_label, self.losses_mean])

        self.widget = widgets.VBox([description, win_rate_box, gains_mean_box,
                                    losses_mean_box, self.add_box], layout=self.widget_layout) 
Example #26
Source File: ABuWGPosition.py    From abu with GNU General Public License v3.0 4 votes vote down vote up
def _init_widget(self):
        """构建AbuPtPosition策略参数界面"""

        description = widgets.Textarea(
            value=u'价格位置仓位管理策略:\n'
                  u'针对均值回复类型策略的仓位管理策略\n'
                  u'根据买入价格在之前一段时间的价格位置来决策仓位大小\n'
                  u'假设过去一段时间的价格为[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]\n'
                  u'如果当前买入价格为2元:则买入仓位配比很高(认为均值回复有很大向上空间)\n'
                  u'如果当前买入价格为9元:则买入仓位配比很低(认为均值回复向上空间比较小)',
            description=u'价格位置',
            disabled=False,
            layout=self.description_layout
        )

        pos_base_label = widgets.Label(u'仓位基础配比:默认0.1即资金10%为仓位基数',
                                       layout=self.label_layout)
        # 需要精确到小数点后5位
        self.pos_base = widgets.FloatSlider(
            value=0.10,
            min=0.00001,
            max=1.0,
            step=0.00001,
            description=u'基配',
            disabled=False,
            orientation='horizontal',
            readout=True,
            readout_format='.5f'
        )
        pos_base_box = widgets.VBox([pos_base_label, self.pos_base])
        past_day_cnt_label = widgets.Label(u'根据过去多长一段时间的价格趋势做为参考,默认20',
                                           layout=self.label_layout)
        self.past_day_cnt = widgets.IntSlider(
            value=20,
            min=5,
            max=250,
            step=1,
            description=u'参考天数',
            disabled=False,
            orientation='horizontal',
            readout=True,
            readout_format='d'
        )
        past_day_cnt_box = widgets.VBox([past_day_cnt_label, self.past_day_cnt])

        self.widget = widgets.VBox([description, pos_base_box,
                                    past_day_cnt_box, self.add_box], layout=self.widget_layout) 
Example #27
Source File: ABuWGBuyFactor.py    From abu with GNU General Public License v3.0 4 votes vote down vote up
def _init_widget(self):
        """构建AbuFactorBuyWD策略参数界面"""

        self.description = widgets.Textarea(
            value=u'日胜率均值回复策略:\n'
                  u'1. 默认以40天为周期(8周)结合涨跌阀值计算周几适合买入\n'
                  u'2. 回测运行中每一月重新计算一次上述的周几适合买入\n'
                  u'3. 在策略日任务中买入信号为:昨天下跌,今天开盘也下跌,且明天是计算出来的上涨概率大的\'周几\'',
            description=u'周涨胜率',
            disabled=False,
            layout=self.description_layout
        )

        self.buy_dw_label = widgets.Label(u'代表周期胜率阀值,默认0.55即55%的胜率',
                                          layout=self.label_layout)
        self.buy_dw = widgets.FloatSlider(
            value=0.55,
            min=0.50,
            max=0.99,
            step=0.01,
            description=u'胜率',
            disabled=False,
            orientation='horizontal',
            readout=True,
            readout_format='.2f',
        )
        self.buy_dw_box = widgets.VBox([self.buy_dw_label, self.buy_dw])

        self.buy_dwm_label = widgets.Label(u'代表涨幅比例阀值系数,默认0.618',
                                           layout=self.label_layout)
        self.buy_dwm = widgets.FloatSlider(
            value=0.618,
            min=0.50,
            max=1.0,
            step=0.01,
            description=u'系数',
            disabled=False,
            orientation='horizontal',
            readout=True,
            readout_format='.3f'
        )
        self.buy_dwm_box = widgets.VBox([self.buy_dwm_label, self.buy_dwm])

        self.dw_period_label = widgets.Label(u'代表分所使用的交易周期,默认40天周期(8周)',
                                             layout=self.label_layout)
        self.dw_period = widgets.IntSlider(
            value=40,
            min=20,
            max=120,
            step=1,
            description=u'周期',
            disabled=False,
            orientation='horizontal',
            readout=True,
            readout_format='d'
        )
        self.dw_period_box = widgets.VBox([self.dw_period_label, self.dw_period])
        self.widget = widgets.VBox([self.description, self.buy_dw_box,
                                    self.buy_dwm_box, self.dw_period_box, self.add],  # border='solid 1px',
                                   layout=self.widget_layout) 
Example #28
Source File: ABuWGPickStock.py    From abu with GNU General Public License v3.0 4 votes vote down vote up
def _init_widget(self):
        """构建AbuPickStockShiftDistance策略参数界面"""

        self.description = widgets.Textarea(
            value=u'位移路程比选股因子策略:\n'
                  u'将交易目标走势每月计算价格位移路程比,根据比值进行选股,选取波动程度不能太大,也不太小的目标:\n'
                  u'1. 定义位移路程比大于参数阀值的月份为大波动月\n'
                  u'2. 一年中大波动月数量 < 最大波动月个数\n'
                  u'3. 一年中大波动月数量 > 最小波动月个数\n',
            description=u'位移路程',
            disabled=False,
            layout=self.description_layout
        )

        threshold_sd_label1 = widgets.Label(u'设大波动位移路程比阀值,期货市场建议2.0及以上', layout=self.label_layout)
        threshold_sd_label2 = widgets.Label(u'设大波动位移路程比阀值,股票市场建议3.0及以上', layout=self.label_layout)
        self.threshold_sd = widgets.FloatSlider(
            value=2.0,
            min=1.0,
            max=6.0,
            step=0.1,
            description=u'阀值',
            disabled=False,
            orientation='horizontal',
            readout=True,
            readout_format='.1f',
        )
        self.threshold_sd_box = widgets.VBox([threshold_sd_label1, threshold_sd_label2, self.threshold_sd])

        max_cnt_label = widgets.Label(u'选取大波动月数量 < 下面设定的最大波动月个数', layout=self.label_layout)
        min_cnt_label = widgets.Label(u'选取大波动月数量 > 下面设定的最小波动月个数', layout=self.label_layout)
        self.min_max_range = widgets.IntRangeSlider(
            value=[1, 4],
            min=0,
            max=10,
            step=1,
            description=u'范围',
            disabled=False,
            continuous_update=False,
            orientation='horizontal',
            readout=True,
            readout_format='d',
        )
        self.min_max_box = widgets.VBox([max_cnt_label, min_cnt_label, self.min_max_range])
        # 这个策略不要可自定义xd,限定选股周期为1年
        self.widget = widgets.VBox([self.description, self.threshold_sd_box,
                                    self.min_max_range, self.reversed_box, self.add_box],
                                   # border='solid 1px',
                                   layout=self.widget_layout)