示例#1
1
def _default_toolbar(figure):
    pz = panzoom(figure.marks)
    normal_btn = ToggleButton(icon='fa-circle-o', tooltip='Normal', value=True)
    pz_btn = ToggleButton(icon='fa-arrows', tooltip='Pan and Zoom', value=False)
    snapshot_btn = Button(icon='fa-thumb-tack', tooltip='Snapshot View')
    reset_btn = Button(icon='fa-refresh', tooltip='Reset View')
    save_btn = Button(icon='fa-save', tooltip='Save as .png Image')

    def tog(btn, *args):
        # Traitlets closure
        def cb():
            for other in args:
                other.value = not btn.value
        return cb

    def overl(btn, value):
        # Traitlets closure
        def cb():
            if btn.value:
                figure.interaction = value
        return cb

    def snapshot(_):
        pz.snapshot()

    def reset(_):
        pz.reset()

    def save(_):
        figure.save()

    pz_btn.on_trait_change(tog(pz_btn, normal_btn))
    pz_btn.on_trait_change(overl(pz_btn, pz))

    normal_btn.on_trait_change(tog(normal_btn, pz_btn))
    normal_btn.on_trait_change(overl(normal_btn, None))

    snapshot_btn.on_click(snapshot)
    reset_btn.on_click(reset)
    save_btn.on_click(save)
    figure.interaction = None

    button_group = HBox([normal_btn, pz_btn, snapshot_btn, reset_btn, save_btn])
    button_group._dom_classes = list(button_group._dom_classes) + ['btn-group']
    return button_group
示例#2
1
 def __init__(self, gen, display=True, leave=True, parent=None):
     self.progress, self.text = IntProgress(min=0, max=len(gen)), HTML()
     self.box = HBox([self.progress, self.text])
     super().__init__(gen, display, leave, parent)
示例#3
1
    def resultsTab(self):
        self.dt_widget = widgets.FloatText(value=0.01,
                                           description='dt:',
                                           disabled=False)
        self.dx_widget = widgets.FloatText(value=0.1,
                                           description='dx:',
                                           disabled=False)
        self.tend_widget = widgets.FloatText(value=10.0,
                                             description='tend:',
                                             disabled=False)
        self.minXlim_widget = widgets.FloatText(value=-4.0,
                                                description='x-min:',
                                                disabled=False)
        self.maxXlim_widget = widgets.FloatText(value=4.0,
                                                description='x-max:',
                                                disabled=False)

        self.CFL_widget = widgets.FloatText(value=0.1,
                                            description='CFL:',
                                            disabled=True)

        self.Fr_widget = widgets.FloatText(value=0.0,
                                           description='Fr:',
                                           disabled=True)

        self.progressBar_widget = widgets.IntProgress(
            value=0,
            min=0,
            max=int(self.tend_widget.value / self.dt_widget.value),
            step=1,
            description='Progress:',
            bar_style='',  # 'success', 'info', 'warning', 'danger' or ''
            orientation='horizontal')

        self.generate_button_widget = widgets.Button(description='Generate')

        self.edit_button_widget = widgets.Button(description='Edit',
                                                 disabled=True)

        self.savefig_button_widget = widgets.Button(description='save fig',
                                                    disabled=True)

        self.timestep_widget = widgets.IntSlider(
            description='Timestep',
            min=0,
            max=int(self.tend_widget.value / self.dt_widget.value) - 1,
            step=1,
            value=0)
        self.resultTab = \
            VBox(children=[
                HBox(children=[
                    self.dt_widget,
                    self.tend_widget
                ]),
                HBox(children=[
                    self.dx_widget,
                    self.minXlim_widget,
                    self.maxXlim_widget]),
                HBox(children=[
                    self.CFL_widget,
                    self.Fr_widget
                ]),
                HBox(children=[
                    self.generate_button_widget,
                    self.edit_button_widget,
                    self.progressBar_widget
                ]),
                HBox(children=[self.timestep_widget,
                               self.savefig_button_widget])
            ])
        self.tabs.append(self.resultTab)
示例#4
1
def main(conn):
    def clear_map():
        if 'm' in globals():
            m.close()
        else:
            pass

    def clear_lat_longs():
        if 'lat_longs' in globals():
            lat_longs = None
        else:
            pass

    def clear_time_slider():
        if 'time_slider' in globals():
            time_slider = None
        else:
            pass

    def draw_update_map(b):
        clear_map()
        clear_lat_longs()
        plate = plate_dropdown.value
        start_date_time = str(
            start_date.value) + ' ' + start_time_dropdown.value
        end_date_time = str(end_date.value) + ' ' + end_time_dropdown.value
        global locations
        locations = sfmta.get_points_for_shuttle(conn, plate, start_date_time,
                                                 end_date_time)

        zip_locations = zip(locations['lng'], locations['lat'],
                            locations.index)
        global lat_longs
        lat_longs = [(x[0], x[1]) for x in zip_locations]
        index_value = find_index(lat_longs, time_slider.value)
        global m
        m = draw_map(lat_longs[:index_value])
        display(m)

    button = Button(description="Draw/Update Map")
    button.on_click(draw_update_map)
    time_slider = IntSlider(min=0,
                            max=100,
                            step=1,
                            description='% of Data',
                            value=100)

    def find_index(lat_longs, value):
        length = len(lat_longs)
        index = int(length * value / 100)
        return index

    def draw_map(lat_longs):
        center = [37.79481, -122.41186]
        zoom = 12
        m = Map(center=center, zoom=zoom, basemap=basemaps.Hydda.Full)
        m.layout.height = '650px'
        pl = Polyline(locations=lat_longs)
        pl.color = path_color.value
        pl.fill_color = path_color.value
        m.add_layer(pl)
        return m

    plates = sfmta.get_all_shuttles(conn)['LICENSE_PLATE'].unique()
    plate_dropdown = Dropdown(options=plates, description='Plate')

    def show_restrictions(b):
        polygons = './vehiclerestrictions_wgs.json'

        with open(polygons) as f:
            polygons_json = json.load(f)

        global geojson
        geojson = GeoJSON(data=polygons_json)
        m.add_layer(geojson)

    def remove_restrictions(b):
        if 'geojson' in globals():
            m.remove_layer(geojson)
        else:
            pass

    def download_data(b):
        if 'lat_longs' in globals():
            df = pd.DataFrame(data=lat_longs)
            df.to_excel('output.xlsx')
        else:
            pass

    button_restrictions = Button(description="Show Restrictions")
    button_restrictions.on_click(show_restrictions)

    button_remove_restrictions = Button(description="Hide Restrictions")
    button_remove_restrictions.on_click(remove_restrictions)

    path_color = ColorPicker(description='Color')

    export_data = Button(description="Download Data")
    export_data.on_click(download_data)

    def top_n_stops(b):
        from collections import Counter
        count_lat_longs = Counter(lat_longs).most_common()
        for lat_long in count_lat_longs[0:10]:
            location = lat_long[0]
            circle = Circle(location=location, radius=300)
            m.add_layer(circle)
        return m

    button_add_top_stops = Button(description="Display Bus Idling")
    button_add_top_stops.on_click(top_n_stops)

    # Remove map button needs its own function with a single argument
    def remove_map(b):
        clear_map()

    button_clear_map = Button(description="Remove Map")
    button_clear_map.on_click(remove_map)

    start = datetime.date.today()
    end = datetime.date.today()
    start_date = DatePicker(description='Start Date', value=start)
    end_date = DatePicker(description='End Date', value=end)

    start_time_dropdown = time_drop_down()
    start_time_dropdown.description = 'Start Time'
    end_time_dropdown = time_drop_down()
    end_time_dropdown.description = 'End Time'

    companies = sfmta.get_shuttles_companies(conn)['NAME'].unique()
    company = Dropdown(options=companies,
                       value='WeDriveU',
                       description='Company')

    return VBox([
        HBox(
            [company, button, button_restrictions,
             button_remove_restrictions]),
        HBox([
            plate_dropdown, export_data, button_add_top_stops, button_clear_map
        ]),
        HBox([path_color]),
        HBox([start_date, start_time_dropdown]),
        HBox([end_date, end_time_dropdown]),
        HBox([time_slider]),
    ])
示例#5
1
 def _dock_add_layout(self, vertical=True):
     return VBox() if vertical else HBox()
示例#6
1
    def actualiza_layout():
        if animacion_on:
            anim.event_source.stop()
        clear()
        #Mostrar estadisticas de las variables
        max_value= "Max value: "+ str(propiedades[4])
        min_value= "Min value: "+ str(propiedades[3])
        mean_value= "Mean value: "+ str(propiedades[5])

        #Muestra, si la hay, la descripcion de las variables
        des=""
        try:
            des=(variables[0][propiedades[0]]+": "+dataset.variables[variables[0][propiedades[0]]].long_name)
        except:
            des=("Variable sin descripcion")
        label= widgets.Label(des)
        label_min= widgets.Label(min_value)
        label_max= widgets.Label(max_value)
        label_mean= widgets.Label(mean_value)
        hb_max_min= HBox([label_min, label_max,label_mean])


        hb_range= HBox([min_range, max_range, boton_range])

        #Comprueba de que depende las variables, y escoge que pasarle dependiendo de eso
        if variables[1][propiedades[0]]==4:
            depth_wid.max= dataset.variables[variables[0][propiedades[0]]].shape[-3]-1
            display(hb_3d, label, hb_max_min, hb_range)
            prof=propiedades[2]
            if tipo==0:
                dimz=dataset.variables[variables[0][propiedades[0]]].shape[-3]-1
                prof=dimz-prof
            aux=dataset.variables[variables[0][propiedades[0]]][propiedades[1],prof,:,:]
            ev=vb_ev_3d

        if variables[1][propiedades[0]]==-1:
            depth_wid.max= dataset.variables["R1"].shape[-3]-1
            display(hb_3d, label, hb_max_min, hb_range)
            prof=propiedades[2]
            dimz=dataset.variables["R1"].shape[-3]-1
            prof=dimz-prof
            aux=dataset.variables["R1"][propiedades[1],1,prof,:,:]
            ev=vb_ev_3d

        if variables[1][propiedades[0]]==3:
            display(hb_2d, label, hb_max_min, hb_range)
            aux=dataset.variables[variables[0][propiedades[0]]][propiedades[1],:,:]
            ev=vb_ev_2d

        aux= np.transpose(aux)


        #Convierte los valores de relleno en nan para que no se pinten en el mapa
        v_m= np.nanmin(aux[:])
        try:
            aux[ aux==v_m ] = np.nan
        except:
            print("fallo")




        fig=imshow_rango(aux,min_range.value, max_range.value)

        #Se crea un evento para coger las coordenadas escogidas
        cid = fig.canvas.mpl_connect('button_press_event', onclick)

        display(ev)
示例#7
1
                             description=r'$\overline{B}$$\to$$\overline{f}$',
                             disabled=False)
b_fbar = widgets.Checkbox(value=True,
                          description=r'$B$$\to$$\overline{f}$',
                          disabled=False)
fold_amix = widgets.Checkbox(value=True,
                             description=r'fold $A_{mix}$',
                             disabled=False)
k_acc = widgets.Checkbox(value=True, description=r'Acceptance', disabled=False)
k_res = widgets.Checkbox(value=True, description=r'Resolution', disabled=False)

## Flavoure Tagging
wbox_tag = HBox([
    VBox([omega, d_omega, eff, d_eff]),
    VBox([xmin, xmax, y_tag, y_untag, y_mix]),
    VBox([k_acc, k_res, fold_amix]),
    VBox([b_f, bbar_f, bbar_fbar, b_fbar]),
    VBox([name, save])
])
tag_pars = interactive_output(
    plot_tagging, {
        'omega': omega,
        'd_omega': d_omega,
        'eff': eff,
        'd_eff': d_eff,
        'sigma_t': sigma_t,
        'a_acc': a_acc,
        'n_acc': n_acc,
        'b_acc': b_acc,
        'beta_acc': beta_acc,
        'cutoff_acc': cutoff_acc,
示例#8
1
    def _widget(self):
        """ Create IPython widget for display within a notebook """
        try:
            return self._cached_widget
        except AttributeError:
            pass

        try:
            from ipywidgets import Layout, VBox, HBox, IntText, Button, HTML, Accordion
        except ImportError:
            self._cached_widget = None
            return None

        layout = Layout(width="150px")

        if self.dashboard_link:
            link = '<p><b>Dashboard: </b><a href="%s" target="_blank">%s</a></p>\n' % (
                self.dashboard_link,
                self.dashboard_link,
            )
        else:
            link = ""

        title = "<h2>%s</h2>" % self._cluster_class_name
        title = HTML(title)
        dashboard = HTML(link)

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

        if self._supports_scaling:
            request = IntText(0, description="Workers", layout=layout)
            scale = Button(description="Scale", layout=layout)

            minimum = IntText(0, description="Minimum", layout=layout)
            maximum = IntText(0, description="Maximum", layout=layout)
            adapt = Button(description="Adapt", layout=layout)

            accordion = Accordion(
                [HBox([request, scale]),
                 HBox([minimum, maximum, adapt])],
                layout=Layout(min_width="500px"),
            )
            accordion.selected_index = None
            accordion.set_title(0, "Manual Scaling")
            accordion.set_title(1, "Adaptive Scaling")

            def adapt_cb(b):
                self.adapt(minimum=minimum.value, maximum=maximum.value)
                update()

            adapt.on_click(adapt_cb)

            def scale_cb(b):
                with log_errors():
                    n = request.value
                    with suppress(AttributeError):
                        self._adaptive.stop()
                    self.scale(n)
                    update()

            scale.on_click(scale_cb)
        else:
            accordion = HTML("")

        box = VBox([title, HBox([status, accordion]), dashboard])

        self._cached_widget = box

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

        cluster_repr_interval = parse_timedelta(
            dask.config.get("distributed.deploy.cluster-repr-interval",
                            default="ms"))
        pc = PeriodicCallback(update, cluster_repr_interval * 1000)
        self.periodic_callbacks["cluster-repr"] = pc
        pc.start()

        return box
示例#9
1
    def create_param_widget(self, param, value):
        from ipywidgets import Layout, HBox
        children = (HBox(),)
        if isinstance(value, bool):
            from ipywidgets import Label, ToggleButton
            p = Label(value=param, layout=Layout(width='10%'))
            t = ToggleButton(description=str(value), value=value)

            def on_bool_change(change):
                t.description = str(change['new'])
                self.params[self._method][param] = change['new']
                self.replot_peaks()

            t.observe(on_bool_change, names='value')

            children = (p, t)

        elif isinstance(value, float):
            from ipywidgets import FloatSlider, FloatText, BoundedFloatText, \
                Label
            from traitlets import link
            p = Label(value=param, layout=Layout(flex='0 1 auto', width='10%'))
            b = BoundedFloatText(value=0, min=1e-10,
                                 layout=Layout(flex='0 1 auto', width='10%'),
                                 font_weight='bold')
            a = FloatText(value=2 * value,
                          layout=Layout(flex='0 1 auto', width='10%'))
            f = FloatSlider(value=value, min=b.value, max=a.value,
                            step=np.abs(a.value - b.value) * 0.01,
                            layout=Layout(flex='1 1 auto', width='60%'))
            l = FloatText(value=f.value,
                          layout=Layout(flex='0 1 auto', width='10%'),
                          disabled=True)
            link((f, 'value'), (l, 'value'))

            def on_min_change(change):
                if f.max > change['new']:
                    f.min = change['new']
                    f.step = np.abs(f.max - f.min) * 0.01

            def on_max_change(change):
                if f.min < change['new']:
                    f.max = change['new']
                    f.step = np.abs(f.max - f.min) * 0.01

            def on_param_change(change):
                self.params[self._method][param] = change['new']
                self.replot_peaks()

            b.observe(on_min_change, names='value')
            f.observe(on_param_change, names='value')
            a.observe(on_max_change, names='value')
            children = (p, l, b, f, a)

        elif isinstance(value, int):
            from ipywidgets import IntSlider, IntText, BoundedIntText, \
                Label
            from traitlets import link
            p = Label(value=param, layout=Layout(flex='0 1 auto', width='10%'))
            b = BoundedIntText(value=0, min=1e-10,
                               layout=Layout(flex='0 1 auto', width='10%'),
                               font_weight='bold')
            a = IntText(value=2 * value,
                        layout=Layout(flex='0 1 auto', width='10%'))
            f = IntSlider(value=value, min=b.value, max=a.value,
                          step=1,
                          layout=Layout(flex='1 1 auto', width='60%'))
            l = IntText(value=f.value,
                        layout=Layout(flex='0 1 auto', width='10%'),
                        disabled=True)
            link((f, 'value'), (l, 'value'))

            def on_min_change(change):
                if f.max > change['new']:
                    f.min = change['new']
                    f.step = 1

            def on_max_change(change):
                if f.min < change['new']:
                    f.max = change['new']
                    f.step = 1

            def on_param_change(change):
                self.params[self._method][param] = change['new']
                self.replot_peaks()

            b.observe(on_min_change, names='value')
            f.observe(on_param_change, names='value')
            a.observe(on_max_change, names='value')
            children = (p, l, b, f, a)
        container = HBox(children)
        return container
示例#10
0
    def __init__(self, keys, scheduler=None, minimum=0, dt=0.1, func=key_split,
                 complete=False):
        self.func = func
        keys = {k.key if hasattr(k, 'key') else k for k in keys}
        self.setup_pre(keys, scheduler, minimum, dt, complete)

        def clear_errors(errors):
            for k in errors:
                self.task_erred(None, k, None, True)

        # Get keys and all-keys
        if self.scheduler.loop._thread_ident == threading.current_thread().ident:
            errors = self.setup(keys, complete)
        else:
            errors = sync(self.scheduler.loop, self.setup, keys, complete)

        # Set up widgets
        from ipywidgets import FloatProgress, VBox, HTML, HBox
        self.bars = {key: FloatProgress(min=0, max=1, description=key)
                        for key in self.all_keys}
        self.texts = {key: HTML() for key in self.all_keys}
        self.boxes = {key: HBox([self.bars[key], self.texts[key]])
                        for key in self.all_keys}
        self.time = HTML()
        self.widget = HBox([self.time, VBox([self.boxes[key] for key in
                                            sorted(self.bars, key=str)])])

        from tornado.ioloop import IOLoop
        loop = IOLoop.instance()
        self.pc = PeriodicCallback(self._update, 1000 * self._dt, io_loop=loop)
        self.pc.start()

        # Clear out errors
        clear_errors(errors)
示例#11
0
def test_widget_utils():
    box = HBox()
    i0 = IntText()
    i0._ngl_name = 'i0'
    i1 = IntText()
    i1._ngl_name = 'i1'
    box.children = [i0, i1]

    assert i0 is widget_utils.get_widget_by_name(box, 'i0')
    assert i1 is widget_utils.get_widget_by_name(box, 'i1')

    box.children = [i1, i0]
    assert i0 is widget_utils.get_widget_by_name(box, 'i0')
    assert i1 is widget_utils.get_widget_by_name(box, 'i1')

    assert widget_utils.get_widget_by_name(box, 'i100') is None
    assert widget_utils.get_widget_by_name(None, 'i100') is None
示例#12
0
class ProgressIPy(ProgressBase):  # pragma: no cover
    HTMLBOX = '<div class="widget-hbox widget-progress"><div class="widget-label" style="display:block;">{0}</div></div>'

    def __init__(self, *args, **kargs):

        # Ipython gives warnings when using widgets about the API potentially changing
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            try:
                from ipywidgets import IntProgress, HTML, HBox  # type: ignore
            except ImportError:  # Support IPython < 4.0
                from IPython.html.widgets import IntProgress, HTML, HBox  # type: ignore

        super(ProgressIPy, self).__init__(*args, **kargs)
        self.prog = IntProgress(max=self.length)
        self._label = HTML()
        self._box = HBox((self.prog, self._label))

    def start(self):
        from IPython.display import display  # type: ignore
        display(self._box)
        super(ProgressIPy, self).start()

    @property
    def value(self):
        """This is the current value, -1 allowed (automatically fixed for display)"""
        return self._value

    @value.setter
    def value(self, val):
        self._value = val
        self.prog.value = max(val, 0)
        self.prog.description = "{0:.2%}".format(self.value / self.length)
        if self.timer and val > 0:
            self._label.value = self.HTMLBOX.format(self.str_time_remaining())

    def display(self):
        pass

    def done(self):
        if self.clear:
            self._box.close()
示例#13
0
    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
示例#14
0
    def __init__(self, *args, **kargs):

        # Ipython gives warnings when using widgets about the API potentially changing
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            try:
                from ipywidgets import IntProgress, HTML, HBox
            except ImportError: # Support IPython < 4.0
                from IPython.html.widgets import IntProgress, HTML, HBox

        super(ProgressIPy, self).__init__(*args, **kargs)
        self.prog = IntProgress(max=self.length)
        self._label = HTML()
        self._box = HBox((self.prog, self._label))
示例#15
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, Accordion

        layout = Layout(width='150px')

        if 'bokeh' in self.scheduler.services:
            template = config.get('diagnostics-link', 'http://{host}:{port}/status')

            host = self.scheduler.address.split('://')[1].split(':')[0]
            port = self.scheduler.services['bokeh'].port
            link = template.format(host=host, port=port, **os.environ)
            link = '<p><b>Dashboard: </b><a href="%s" target="_blank">%s</a></p>\n' % (link, link)
        else:
            link = ''

        title = '<h2>%s</h2>' % type(self).__name__
        title = HTML(title)
        dashboard = HTML(link)

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

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

        minimum = IntText(0, description='Minimum', layout=layout)
        maximum = IntText(0, description='Maximum', layout=layout)
        adapt = Button(description='Adapt', layout=layout)

        accordion = Accordion([HBox([request, scale]),
                               HBox([minimum, maximum, adapt])],
                               layout=Layout(min_width='500px'))
        accordion.selected_index = None
        accordion.set_title(0, 'Manual Scaling')
        accordion.set_title(1, 'Adaptive Scaling')

        box = VBox([title,
                    HBox([status,
                          accordion]),
                    dashboard])

        self._cached_widget = box

        def adapt_cb(b):
            self.adapt(minimum=minimum.value, maximum=maximum.value)

        adapt.on_click(adapt_cb)

        def scale_cb(b):
            with log_errors():
                n = request.value
                with ignoring(AttributeError):
                    self._adaptive.stop()
                self.scale(n)

        scale.on_click(scale_cb)

        scheduler_ref = ref(self.scheduler)

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

        pc = PeriodicCallback(update, 500, io_loop=self.scheduler.loop)
        self.scheduler.periodic_callbacks['cluster-repr'] = pc
        pc.start()

        return box
示例#16
0
def log_progress(sequence, every=None, size=None, start_time=None, name='Items'):
    """
        Function to provide a progress bar.
        ---
        This function is useful only when this program is run
        as a Jupyter notebook.

        In order to use this, run
            `jupyter nbextension enable --py --sys-prefix widgetsnbextension`
        prior to launching the notebook server.
    """
    from ipywidgets import IntProgress, HTML, VBox, HBox
    from IPython.display import display, Javascript
    from IPython.display import HTML as html
    import datetime
    import uuid
    image_id = "loading_image_{}".format(str(uuid.uuid4()))
    is_iterator = False
    if size is None:
        try:
            size = len(sequence)
        except TypeError:
            is_iterator = True
    if size is not None:
        if every is None:
            if size <= 200:
                every = 1
            else:
                every = int(size / 200)     # every 0.5%
    else:
        assert every is not None, 'sequence is iterator, set every'
    if start_time is None:
        start_time = datetime.datetime.now()
    if is_iterator:
        progress = IntProgress(min=0, max=1, value=1)
        progress.bar_style = 'info'
    else:
        progress = IntProgress(min=0, max=size, value=0)
    label = HTML()
    
    loading_image = HTML("<img id='{}'  src='images/loading.gif' width=50 align=right alt='Loading Image.' />".format(image_id))
    box = VBox(children=[label, HBox([progress, loading_image])])
    display(box)
    #display(loading_image)
    index = 0
    try:
        for index, record in enumerate(sequence, 1):
            if start_time is not None:
                time_elapsed = datetime.datetime.now() - start_time
            else:
                time_elapsed = datetime.datetime.now()
            if index == 1 or index % every == 0:
                if is_iterator:
                    label.value = '{name}: {index} / ? | Time Elapsed: {time_elapsed}'.format(
                        name=name,
                        index=index,
                        time_elapsed=time_elapsed
                    )
                else:
                    progress.value = index
                    if index == size:
                        progress.value = index-1
                    label.value = u'{name}: {index} / {size} | Time Elapsed: {time_elapsed}'.format(
                        name=name,
                        index=index,
                        size=size,
                        time_elapsed=time_elapsed
                    )
            yield record
    except:
        progress.bar_style = 'danger'
        hide_command = """document.getElementById('{}').style.display='none';""".format(image_id)
        display(Javascript(hide_command))
    else:
        progress.bar_style = 'success'
        hide_command = """document.getElementById('{}').style.display='none';""".format(image_id)

        display(Javascript(hide_command))

        if start_time is not None:
            time_elapsed = datetime.datetime.now() - start_time
        else:
            time_elapsed = datetime.datetime.now()
        progress.value = index
        label.value = "{name}: {index} | Total Time: {time_elapsed}".format(
                name=name,
                index=str(index or '?'),
                time_elapsed=time_elapsed
            )
def manual_qc_interface(
    df,
    variable_list: list,
    flags: dict or str,
    review_flag: str = "_review_flag",
    comment_column: str = "_review_comment",
    default_flag=None,
):
    """
    Manually QC interface to manually QC oceanographic data, through a Jupyter notebook.
    :param default_flag:
    :param comment_column:
    :param df: DataFrame input to QC
    :param variable_list: Variable List to review
    :param flags: Flag convention used
    :param review_flag:
    """
    #     # Generate a copy of the provided dataframe which will be use for filtering and plotting data|
    #     df_temp = df

    # Retrieve Flag Convention
    if type(flags) is str:
        flag_convention = flags
        flags = flag_conventions[flags]
        flag_descriptor = f"{flag_convention}\n" + "\n".join([
            f"{key} = {item['Meaning']}"
            for key, item in flag_conventions[flag_convention].items()
        ])

    else:
        flag_descriptor = "\n".join(
            [f"{key} = {item}" for key, item in flags.items()])

    # Set Widgets of the interface
    yaxis = widgets.Dropdown(
        options=variable_list,
        value=variable_list[0],
        description="Y Axis:",
        disabled=False,
    )

    xaxis = widgets.Dropdown(
        options=["depth", "time"],
        value="time",
        description="X Axis:",
        disabled=False,
    )

    filter_by = widgets.Text(
        value=None,
        description="Filter by",
        placeholder="ex: 20<depth<30",
        disabled=False,
    )

    filter_by_result = filter_by_result = widgets.HTML(
        value="{0} records available".format(len(df)), )

    apply_filter = widgets.Button(
        value=False,
        description="Apply Filter",
        disabled=False,
        button_style="success",  # 'success', 'info', 'warning', 'danger' or ''
        tooltip="Apply Filter to the full dataset.",
    )

    flag_selection = widgets.Dropdown(options=list(flags.keys()),
                                      description=flag_descriptor,
                                      disabled=False)
    flag_comment = widgets.Textarea(
        value="",
        placeholder="Add review comment",
        description="Comment:",
        disabled=False,
    )

    apply_flag = widgets.Button(
        value=False,
        description="Apply Flag",
        disabled=False,
        button_style="success",  # 'success', 'info', 'warning', 'danger' or ''
        tooltip="Apply Flag to select records.",
    )

    accordion = widgets.Accordion()
    accordion.selected_index = None

    show_selection = widgets.Button(
        value=False,
        description="Show Selection",
        disabled=False,
        button_style="success",  # 'success', 'info', 'warning', 'danger' or ''
        tooltip="Present selected records in table.",
    )

    selected_table = widgets.Output()

    def get_filtered_data(df):
        """Apply query if available otherwise give back the full dataframe"""
        try:
            return df.query(filter_by.value)
        except ValueError:
            return df

    # Create the initial plots
    # Plot widget with
    def _get_plots():
        """Generate plots based on the dataframe df, yaxis and xaxis values present
        within the respective widgets and flags in seperate colors"""
        plots = []
        for flag_name, flag_value in flags.items():
            if type(flag_value) is dict and "Color" in flag_value:
                flag_color = flag_value["Color"]
                flag_meaning = flag_value["Meaning"]
            else:
                flag_color = flag_value
                flag_meaning = flag_value

            df_temp = get_filtered_data(df)

            df_flag = df_temp.loc[df_temp[yaxis.value +
                                          review_flag] == flag_name]
            plots += [
                go.Scattergl(
                    x=df_flag[xaxis.value],
                    y=df_flag[yaxis.value],
                    mode="markers",
                    name=flag_meaning,
                    marker={
                        "color": flag_color,
                        "opacity": 1
                    },
                )
            ]

        return tuple(plots)

    # Initialize Figure Widget and layout
    f = go.FigureWidget(data=_get_plots(), layout=go.Layout(barmode="overlay"))
    f.update_layout(margin=dict(l=50, r=20, t=50, b=20))
    f.layout.xaxis.title = xaxis.value
    f.layout.yaxis.title = yaxis.value
    f.layout.title = "Review"
    f.update_layout(
        showlegend=True,
        legend={
            "orientation": "h",
            "yanchor": "bottom",
            "y": 1.02,
            "xanchor": "right",
            "x": 1,
        },
    )

    # Set the update to figure if the drop menu is changed
    figure_data = f.data

    def update_filter(query_string=None):
        """Update filter report below the filter_by cell"""
        df_temp = get_filtered_data(df)

        if len(df_temp) == 0:
            # Give a message back saying no match and don't change anything else
            filter_by_result.value = "<p style='color:red;'>0 records found</p>"
        else:
            # Update text back and update plot with selection
            filter_by_result.value = "{0} records found".format(len(df_temp))

    def update_figure(_):
        """Update figure with present x and y items in menu"""
        update_axes(xaxis.value, yaxis.value)

    def update_axes(xvar, yvar):
        """
        Update figure, based on x,y axis provided
        :param xvar:
        :param yvar:
        """
        kk = 0
        with f.batch_update():
            f.layout.xaxis.title = xvar
            f.layout.yaxis.title = yvar
            for plot in _get_plots():
                f.data[kk].x = plot.x
                f.data[kk].y = plot.y
                kk += 1

    def _get_selected_records():
        """Method to retrieve the x and y coordinates of the records selected with the plotly lasso tool."""
        xs = []
        ys = []
        for layer in figure_data:
            if layer["selectedpoints"]:
                xs += list(layer.x[list(layer["selectedpoints"])])
                ys += list(layer.y[list(layer["selectedpoints"])])
        return xs, ys

    def _get_selected_indexes(xs, ys):
        """Method to retrieve dataframe indexes of the selected x,y records shown on the figure."""
        df_temp = get_filtered_data(df)
        is_indexes_selected = (df_temp[[xaxis.value, yaxis.value]].apply(
            tuple, axis=1).isin(tuple(zip(xs, ys))))
        return df_temp.index[is_indexes_selected].tolist()

    def selection_fn(_):
        """Method to update the table showing the selected records."""
        xs, ys = _get_selected_records()
        selected_indexes = _get_selected_indexes(xs, ys)
        if selected_indexes:
            with selected_table:
                selected_table.clear_output()
                display(df.loc[selected_indexes])

    def update_flag_in_dataframe(_):
        """Tool triggered  when flag is applied to selected records."""
        # Retrieve selected records and flag column
        xs, ys = _get_selected_records()
        selected_indexes = _get_selected_indexes(xs, ys)
        flag_name = yaxis.value + review_flag
        comment_name = yaxis.value + comment_column

        # Create a column for the manual flag if it doesn't exist
        if flag_name not in df:
            df[flag_name] = default_flag
        # Print below the interface what's happening
        print(
            "Apply {0} to {1} records to {2}".format(flag_selection.value,
                                                     len(selected_indexes),
                                                     flag_name),
            end="",
        )
        if flag_comment.value:
            print(" and add comment: {0}".format(flag_comment.value), end="")
        print(" ... ", end="")

        # Update flag value within the data frame
        df.loc[selected_indexes, flag_name] = flag_selection.value

        # Update comment
        if flag_comment.value:
            df.loc[selected_indexes, comment_name] = flag_comment.value

        # Update figure with the new flags
        update_figure(True)
        print("Completed")

    # Setup the interaction between the different components
    axis_dropdowns = interactive(update_axes, yvar=yaxis, xvar=xaxis)
    show_selection.on_click(selection_fn)
    apply_filter.on_click(update_figure)
    apply_flag.on_click(update_flag_in_dataframe)
    filter_data = interactive(update_filter, query_string=filter_by)

    # Create the interface layout
    plot_interface = VBox(axis_dropdowns.children)
    flag_interface = VBox(
        (flag_selection, flag_comment, apply_flag),
        layout={"align_items": "flex-end"},
    )
    filter_by_interface = VBox((filter_by, filter_by_result),
                               layout={"align_items": "flex-end"})
    filter_interface = HBox((filter_by_interface, apply_filter))
    upper_menu_left = VBox((plot_interface, filter_interface))
    upper_menu = HBox((upper_menu_left, flag_interface),
                      layout={"justify_content": "space-between"})
    selection_table = VBox((show_selection, selected_table))

    return VBox((
        upper_menu,
        f,
        selection_table,
    ))
示例#18
0
 def _make_export_image_widget(self):
     if self.widget_export_image is None:
         self.widget_export_image = HBox([self._make_button_export_image()])
     return self.widget_export_image
示例#19
0
def imgs_grid(path):
    def show_imgs():
        print(f"Crop name: {crop_name},  Area: {area:.2f} sqm")

        def multi_bands_imgs(bands, fname):
            df = raster_utils.create_df(ci_path, pid, ci_band.value)
            rows = round((df.shape[0] / columns) + 0.5)
            fig = plt.figure(figsize=(16, 4 * rows))
            for i, row in df.iterrows():
                fig.add_subplot(rows, columns, i + 1)

                str_date = str(row['date'].date()).replace('-', '')
                img_png = normpath(join(ci_path, f'{fname}_{str_date}.png'))

                # Create color image if it does not exist
                # Merge bands (images path, export image path, bands list)
                if not isfile(img_png):
                    imgs_path = normpath(join(ci_path, row['imgs']))
                    raster_utils.merge_bands(imgs_path, img_png, bands)

                with rasterio.open(img_png, format='PNG') as img:
                    overlay_date(img, row['date'].date())  # Add date overlay.
                    ax = plt.gca()
                    if show_parcel.value:
                        ax.add_patch(overlay_parcel(img, info_data))

                    plt.axis('off')  # Turn of axis.
                    pA, pB = np.percentile(img.read(1),
                                           tuple(ci_percent.value))

                    # Strech image to A - B percentile.
                    stack = [
                        exposure.rescale_intensity(img.read()[i, :, :],
                                                   in_range=(pA, pB))
                        for i in range(len(bands))
                    ]
                    rgb_enhanced = np.dstack(stack)

                    show(np.uint16(rgb_enhanced.transpose(2, 0, 1) / 300),
                         ax=ax,
                         transform=img.transform)
            return plt.show()

        def ndvi_imgs(bands, fname):
            df = raster_utils.create_df(ci_path, pid, ci_band.value)
            rows = round((df.shape[0] / columns) + 0.5)
            fig = plt.figure(figsize=(16, 4 * rows))
            for i, row in df.iterrows():
                fig.add_subplot(rows, columns, i + 1)

                str_date = str(row['date'].date()).replace('-', '')
                img_png = normpath(join(ci_path, f'{fname}_{str_date}.png'))

                imgs_path = normpath(join(ci_path, row['imgs']))
                b4f = f"{imgs_path}.B04.tif"
                b4 = rasterio.open(b4f, format='GTiff')

                ndvi = raster_utils.calc_ndvi(imgs_path, img_png, bands)
                overlay_date(b4, row['date'].date())  # Add date overlay.
                ax = plt.gca()
                if show_parcel.value:
                    ax.add_patch(overlay_parcel(b4, info_data))

                plt.axis('off')  # Turn of axis.
                pA, pB = np.percentile(ndvi, tuple(ci_percent.value))

                show(ndvi,
                     ax=ax,
                     transform=b4.transform,
                     cmap=ci_cmaps.value,
                     vmin=pA,
                     vmax=pB)

                b4.close()
            return plt.show()

        def single_band(band):
            df = raster_utils.create_df(ci_path, pid, ci_band.value)
            rows = round((df.shape[0] / columns) + 0.5)
            fig = plt.figure(figsize=(16, 4 * rows))
            for i, row in df.iterrows():
                img_gtif = normpath(
                    join(ci_path, f"{row['imgs']}.{ci_band.value[0]}.tif"))
                with rasterio.open(img_gtif, format='GTiff') as img:
                    fig.add_subplot(rows, columns, i + 1)
                    overlay_date(img, row['date'].date())
                    plt.axis('off')
                    ax = plt.gca()
                    if show_parcel.value:
                        ax.add_patch(overlay_parcel(img, info_data))

                    img_read = img.read(1)

                    pA, pB = np.percentile(img_read, tuple(ci_percent.value))
                    show(img.read(1),
                         ax=ax,
                         transform=img.transform,
                         cmap=data_options.cmaps(ci_band.value[0]),
                         vmin=pA,
                         vmax=pB)

            return plt.show()

        if len(ci_band.value) == 1:
            single_band(ci_band.value[0])
        elif ci_band.value == ['B04', 'B08']:
            ndvi_imgs(ci_band.value, 'NDVI')
        else:
            multi_bands_imgs(ci_band.value, ('').join(ci_band.value))

    def overlay_date(img, date):
        date_text = plt.text(
            img.bounds.left + ((img.bounds.right - img.bounds.left) / 6.5),
            img.bounds.top - ((img.bounds.top - img.bounds.bottom) / 6.5),
            date,
            color='yellow',
            weight='bold',
            size=12,
            bbox=dict(boxstyle="round", ec='yellow', fc='black', alpha=0.2))

        return date_text

    def overlay_parcel(img, geom):
        with open(file_info, 'r') as f:
            info_data = json.loads(f.read())
        img_epsg = img.crs.to_epsg()
        geo_json = spatial_utils.transform_geometry(info_data, img_epsg)
        patche = [
            PolygonPatch(feature,
                         edgecolor="yellow",
                         facecolor="none",
                         linewidth=2) for feature in [geo_json['geom'][0]]
        ]
        return patche[0]

    # Images options.
    file_info = normpath(join(path, 'info.json'))
    with open(file_info, 'r') as f:
        info_data = json.loads(f.read())
    # print(info_data)
    pid = info_data['pid'][0]
    crop_name = info_data['cropname'][0]
    area = info_data['area'][0]
    ci_path = normpath(join(path, 'chip_images'))
    columns = 4

    available_options = raster_utils.available_options(path, pid)
    ci_band = Dropdown(
        options=available_options,
        description='Select band:',
        disabled=False,
    )

    ci_cmaps = Dropdown(options=data_options.color_maps(),
                        value='RdYlGn_r',
                        description='Color map:',
                        disabled=False,
                        layout=Layout(width='15%'))

    ci_percent = IntRangeSlider(
        value=[2, 98],
        min=0,
        max=100,
        step=1,
        description='%:',
        disabled=False,
        continuous_update=False,
        orientation='horizontal',
        readout=True,
        readout_format='d',
    )

    show_parcel = Checkbox(value=True,
                           description='Show parcel',
                           disabled=False,
                           indent=False,
                           layout=Layout(width='100px'))

    ci_cloud = Checkbox(value=False,
                        description='Cloud free',
                        disabled=True,
                        indent=False,
                        layout=Layout(width='140px'))

    btn_ci = Button(value=False,
                    description='Show images',
                    disabled=False,
                    button_style='info',
                    tooltip='Refresh output',
                    icon='')

    ci_out = Output()

    @btn_ci.on_click
    def btn_ci_on_click(b):
        btn_ci.description = 'Refresh'
        btn_ci.icon = 'refresh'
        with ci_out:
            ci_out.clear_output()
            show_imgs()

    wbox_ci_cloud = HBox([])
    if len([val for key, val in available_options if 'SCL' in val]) > 0:
        wbox_ci_cloud = HBox([ci_cloud])

    wbox_ci = HBox([btn_ci, ci_band, show_parcel, ci_percent, wbox_ci_cloud])

    def ci_band_change(change):
        if len(ci_band.value) == 1:
            if ci_band.value[0] in ['B02', 'B03', 'B04', 'B08']:
                wbox_ci.children = [btn_ci, ci_band, show_parcel, ci_percent]
                show_parcel.value = True
            else:
                wbox_ci.children = [btn_ci, ci_band, ci_percent]
                show_parcel.value = False
        elif ci_band.value == ['B04', 'B08']:
            wbox_ci.children = [
                btn_ci, ci_band, show_parcel, ci_cmaps, ci_percent,
                wbox_ci_cloud
            ]
            show_parcel.value = True
        else:
            wbox_ci.children = [
                btn_ci, ci_band, show_parcel, ci_percent, wbox_ci_cloud
            ]
            show_parcel.value = True

    ci_band.observe(ci_band_change, 'value')

    wbox = VBox([wbox_ci, ci_out])

    return wbox
示例#20
0
    def _widget(self):
        """ Create IPython widget for display within a notebook """
        try:
            return self._cached_widget
        except AttributeError:
            pass

        if self.asynchronous:
            return None

        try:
            from ipywidgets import Layout, VBox, HBox, IntText, Button, HTML, Accordion
        except ImportError:
            self._cached_widget = None
            return None

        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)

        minimum = IntText(0, description="Minimum", layout=layout)
        maximum = IntText(0, description="Maximum", layout=layout)
        adapt = Button(description="Adapt", layout=layout)

        accordion = Accordion(
            [HBox([request, scale]),
             HBox([minimum, maximum, adapt])],
            layout=Layout(min_width="500px"),
        )
        accordion.selected_index = None
        accordion.set_title(0, "Manual Scaling")
        accordion.set_title(1, "Adaptive Scaling")

        @adapt.on_click
        def adapt_cb(b):
            self.adapt(minimum=minimum.value, maximum=maximum.value)

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

        app_id = HTML("<p><b>Application ID: </b>{0}</p>".format(self.app_id))

        elements = [title, HBox([status, accordion]), app_id]

        if self.dashboard_link is not None:
            link = HTML(
                '<p><b>Dashboard: </b><a href="{0}" target="_blank">{0}'
                "</a></p>\n".format(self.dashboard_link))
            elements.append(link)

        self._cached_widget = box = VBox(elements)
        self._status_widget = status

        return box
示例#21
0
    def __init__(self, show=True, style=True):
        # header
        #   filechooser
        self.base = BASE
        self.filechooser = FileChooser(self.base, accept=('MS', 'fid', 'FID'))
        self.datap = None
        self.MAX_DISP_PEAKS = NbMaxDisplayPeaks

        #   buttons
        #       load
        self.bload = Button(description='Load',
                            layout=Layout(width='15%'),
                            tooltip='load and display experiment')
        self.bload.on_click(self.load)
        #       FT
        self.bproc = Button(description='Process',
                            layout=Layout(width='15%'),
                            tooltip='Fourier transform of the fid')
        self.bproc.on_click(self.process)
        #       pp
        self.bpeak = Button(description='Peak Pick',
                            layout=Layout(width='15%'),
                            tooltip='Detect Peaks')
        self.bpeak.on_click(self.peakpick)
        self.bsave = Button(description='Save',
                            layout=Layout(width='15%'),
                            tooltip='Save processed data set in msh5 format')
        self.bsave.on_click(self.save)

        # GUI set-up and scene
        # tools
        self.header = Output()
        with self.header:
            self.waitarea = Output()
            self.buttonbar = HBox([
                self.bload, self.bproc, self.bpeak, self.bsave, self.waitarea
            ])
            display(
                Markdown('---\n# Select an experiment, and load to process'))
            display(self.filechooser)
            display(self.buttonbar)

        NODATA = HTML("<br><br><h3><i><center>No Data</center></i></h3>")
        # fid
        self.fid = Output()  # the area where 1D is shown
        with self.fid:
            display(NODATA)
            display(Markdown("use the `Load` button above"))
        # spectrum
        self.out1D = Output()  # the area where 1D is shown
        with self.out1D:
            display(NODATA)
            display(
                Markdown(
                    "After loading, use the `Process` or `Load` buttons above")
            )

        # peaklist
        self.peaklist = Output()  # the area where peak list is shown
        with self.peaklist:
            display(NODATA)
            display(
                Markdown("After Processing, use the `Peak Pick` button above"))

        # form
        self.outform = Output(
        )  # the area where processing parameters are displayed
        with self.outform:
            self.paramform()
            display(self.form)

        # Info
        self.outinfo = Output()  # the area where info is shown
        self.showinfo()

        #  tabs
        self.tabs = widgets.Tab()
        self.tabs.children = [
            self.fid, self.out1D, self.peaklist, self.outform, self.outinfo
        ]
        self.tabs.set_title(0, 'raw fid')
        self.tabs.set_title(1, 'Spectrum')
        self.tabs.set_title(2, 'Peak List')
        self.tabs.set_title(3, 'Processing Parameters')
        self.tabs.set_title(4, 'Info')

        #        self.tabs = VBox([ self.out2D, self.outpp2D, self.out1D, self.outinfo ])
        self.box = VBox([self.header, self.tabs])
        # self.box = VBox([self.title,
        #                 self.FC,
        #                 HBox([self.bdisp2D, self.bpp2D, self.bdisp1D])
        #                 ])
        if style:
            injectcss()
        if show:
            display(self.box)
示例#22
0
def view():
    info = Label("Select a parcel to display.")

    temppath = config.get_value(['paths', 'temp'])
    datapath = config.get_value(['paths', 'data'])

    method = ToggleButtons(options=[('From local storage', 0),
                                    ('Remote to memory', 1)],
                           value=0,
                           description='',
                           disabled=True,
                           button_style='info',
                           tooltips=[
                               'View data that are stored on the local drive.',
                               'View data from memory.'
                           ])

    paths = RadioButtons(options=[
        (f"Temporary folder: '{temppath}'.", temppath),
        (f"Personal data folder: '{datapath}'.", datapath)
    ],
                         layout={'width': 'max-content'},
                         value=temppath)

    paths_box = Box([Label(value="Select folder:"), paths])

    tables_first = [
        f for f in os.listdir(paths.value)
        if os.path.isdir(os.path.join(paths.value, f))
    ]

    select_table = Dropdown(
        options=[f for f in tables_first if not f.startswith('.')],
        value=None,
        description='Select tabe:',
        disabled=False,
    )

    select_option = RadioButtons(options=[(f"Single parcel selection.", 1),
                                          (f"Multiple parcels selection.", 2)],
                                 disabled=True,
                                 layout={'width': 'max-content'})

    button_refresh = Button(layout=Layout(width='35px'), icon='fa-refresh')

    select_option_box = HBox([
        select_table, button_refresh,
        Label(value="Selection method:"), select_option
    ])

    selection_single = Dropdown(
        options=[],
        value=None,
        description='Select parcel:',
        disabled=False,
    )

    selection_multi = SelectMultiple(
        options=[],
        value=[],
        description='Select parcels:',
        disabled=False,
    )

    view_method = ToggleButtons(
        options=[],
        value=None,
        description='',
        disabled=False,
        button_style='info',
        tooltips=[],
    )

    rm_parcel = Button(value=False,
                       disabled=False,
                       button_style='danger',
                       tooltip='Delete parcel data.',
                       icon='trash',
                       layout=Layout(width='35px'))

    code_info = Label()
    single_box = HBox([selection_single, rm_parcel])
    select_box = Box([single_box])

    method_0 = VBox([info, paths_box, select_option_box, select_box])
    method_1 = VBox([])
    view_box = Output(layout=Layout(border='1px solid black'))
    method_out = Output()
    with method_out:
        display(method_0)

    def method_options(obj):
        with method_out:
            method_out.clear_output()
            if obj['new'] == 0:
                display(method_0)
            elif obj['new'] == 1:
                display(method_1)

    method.observe(method_options, 'value')

    @button_refresh.on_click
    def button_refresh_on_click(b):
        view_box.clear_output()
        tables_first = [
            f for f in os.listdir(paths.value)
            if os.path.isdir(os.path.join(paths.value, f))
        ]
        select_table.options = [
            f for f in tables_first if not f.startswith('.')
        ]
        if select_table.value is not None:
            parcels = f"{paths.value}{select_table.value}"
            parcels_list = [
                f for f in os.listdir(parcels) if not f.startswith('.')
            ]
            selection_single.options = parcels_list
            selection_multi.options = parcels_list
        else:
            selection_single.options = []
            selection_single.value = None
            selection_multi.options = []
            selection_multi.value = []

    @rm_parcel.on_click
    def rm_parcel_on_click(b):
        try:
            parcel_to_rm = f"{paths.value}{select_table.value}/{selection_single.value}"
            try:
                shutil.rmtree(f'{parcel_to_rm}')
            except Exception:
                pass
            try:
                os.remove(f'{parcel_to_rm}')
            except Exception:
                pass
#             print(f"The parce: '{selection_single.value}' is deleted.")
            parcels = f"{paths.value}{select_table.value}"
            parcels_list = [
                f for f in os.listdir(parcels) if not f.startswith('.')
            ]
            selection_single.options = parcels_list
            view_box.clear_output()
        except Exception:
            pass

    def on_select_option_change(change):
        if select_option.value == 1:
            select_box.children = [single_box]
        else:
            select_box.children = [selection_multi]

    select_option.observe(on_select_option_change, 'value')

    def on_datapath_change(change):
        tables = [
            f for f in os.listdir(paths.value)
            if os.path.isdir(os.path.join(paths.value, f))
        ]
        tables = [f for f in tables if not f.startswith('.')]
        select_table.options = tables

    paths.observe(on_datapath_change, 'value')

    def on_table_change(change):
        if select_table.value is not None:
            parcels = f"{paths.value}{select_table.value}"
            parcels_list = [
                f for f in os.listdir(parcels) if not f.startswith('.')
            ]
            selection_single.options = parcels_list
            selection_multi.options = parcels_list
        else:
            selection_single.options = []
            selection_single.value = None
            selection_multi.options = []
            selection_multi.value = []
            view_method.options = []

    select_table.observe(on_table_change, 'value')

    def on_selection_change(obj):
        code_info.value = "Select how to view the dataset."
        options_list = [('Get example code', 1)]
        if obj['new'] is not None:
            parceldata = f"{paths.value}{select_table.value}/{selection_single.value}"
            data_list = [
                f for f in os.listdir(parceldata) if not f.startswith('.')
            ]
            if any("time_series" in s for s in data_list):
                options_list.append(('Plot time series', 2))
            if any("chip_images" in s for s in data_list):
                options_list.append(('View images', 3))
            options_list.append(("Show on map", 4))
            if select_option.value == 2:
                options_list.append(('Comparison', 5))
            view_method.options = options_list
            view_method.value = None

    selection_single.observe(on_selection_change, 'value')
    selection_multi.observe(on_selection_change, 'value')

    def method_options(obj):
        view_box.clear_output()
        with view_box:
            if selection_single.value is None:
                with view_box:
                    print("Please select a parcel")

            elif select_option.value == 1:
                data_path = f'{paths.value}{select_table.value}/{selection_single.value}/'
                if obj['new'] == 1:
                    from src.ipycbm.ui_view import view_code
                    display(view_code.code(data_path))
                elif obj['new'] == 2:
                    from src.ipycbm.ui_view import view_time_series
                    display(view_time_series.time_series(data_path))
                elif obj['new'] == 3:
                    from src.ipycbm.ui_view import view_calendar
                    display(view_calendar.calendar(data_path))
                elif obj['new'] == 4:
                    from src.ipycbm.ui_view import view_map
                    display(view_map.widget_box(data_path))

            elif select_option.value == 2 and len(selection_multi.value) > 0:
                data_path = f'{paths.value}{select_table.value}/'
                data_paths = [
                    f'{data_path}{s}/' for s in selection_multi.value
                ]
                if obj['new'] == 1:
                    from src.ipycbm.ui_view import view_code
                    display(view_code.code(data_paths[0]))
                    pass
                elif obj['new'] == 2:
                    from src.ipycbm.ui_view import view_time_series
                    # display(view_time_series.time_series(data_list[0]))
                    pass
                elif obj['new'] == 3:
                    from src.ipycbm.ui_view import view_calendar
                    # display(view_chip_images.calendar(data_path))
                    pass
                elif obj['new'] == 4:
                    from src.ipycbm.ui_view import view_maps
                    display(view_maps.with_polygons(data_paths))

    selection_single.observe(method_options, 'value')
    selection_multi.observe(method_options, 'value')
    view_method.observe(method_options, 'value')

    notes_info = Label("Add a note for the parcel")
    notes_bt = Button(value=False,
                      description='Add note',
                      disabled=False,
                      button_style='info',
                      tooltip='Add a note.',
                      icon='sticky-note')
    notes_box = VBox([])

    @notes_bt.on_click
    def notes_bt_on_click(b):
        if notes_box.children == ():
            notes_box.children = [
                view_notes.notes(f"{paths.value}{select_table.value}/",
                                 select_table.value,
                                 selection_single.value.replace('parcel_', ''))
            ]
        else:
            notes_box.children = []

    wbox = VBox([
        method_out, code_info, view_method, view_box,
        HBox([notes_info, notes_bt]), notes_box
    ])

    return wbox
示例#23
0
    def status_printer(_, total=None, desc=None):
        # Prepare IPython progress bar
        from ipywidgets import IntProgress, HTML, HBox, Layout, Label

        if total:
            pbar = IntProgress(min=0, max=total)
        else:  # No total? Show info style bar with no progress tqdm status
            pbar = IntProgress(min=0, max=1)
            pbar.value = 1
            pbar.bar_style = 'info'
        if desc:
            description = Label(desc)
            description_box = HBox(children=[description])
            description_box.layout.min_width = '35%'
            description_box.layout.max_width = '35%'
        else:
            description_box = None

        # Prepare status text
        ptext = HTML()
        inner = HBox([pbar, ptext], layout=Layout(padding='0 0 0 20px'))
        # Only way to place text to the right of the bar is to use a container
        box_layout = Layout(display='flex', width='100%')
        container = HBox(
            children=[description_box, inner] if description_box else [inner],
            layout=box_layout)
        from IPython.core.display import display
        display(container)

        # HTML encoding
        try:  # Py3
            from html import escape
        except ImportError:  # Py2
            from cgi import escape

        def print_status(s='', close=False, bar_style=None, desc=None):
            # Note: contrary to native tqdm, s='' does NOT clear bar
            # goal is to keep all infos if error happens so user knows
            # at which iteration the loop failed.

            # Clear previous output (really necessary?)
            # clear_output(wait=1)

            # Get current iteration value from format_meter string
            if total:
                # n = None
                if s:
                    npos = s.find(r'/|/')  # cause we use bar_format=r'{n}|...'
                    # Check that n can be found in s (else n > total)
                    if npos >= 0:
                        n = int(s[:npos])  # get n from string
                        s = s[npos + 3:]  # remove from string

                        # Update bar with current n value
                        if n is not None:
                            pbar.value = n

            # Print stats
            if s:  # never clear the bar (signal: s='')
                s = s.replace('||', '')  # remove inesthetical pipes
                s = escape(s)  # html escape special characters (like '?')
                ptext.value = s

            # Change bar style
            if bar_style:
                # Hack-ish way to avoid the danger bar_style being overriden by
                # success because the bar gets closed after the error...
                if not (pbar.bar_style == 'danger' and bar_style == 'success'):
                    pbar.bar_style = bar_style

            # Special signal to close the bar
            if close and pbar.bar_style != 'danger':  # hide only if no error
                try:
                    container.close()
                except AttributeError:
                    container.visible = False

            # Update description
            if desc:
                #nonlocal description
                description.value = desc

        return print_status
示例#24
0
    def __init__(self):

        micron_units = Label(
            'micron')  # use "option m" (Mac, for micro symbol)

        constWidth = '180px'
        tab_height = '500px'
        stepsize = 10

        #style = {'description_width': '250px'}
        style = {'description_width': '25%'}
        layout = {'width': '400px'}

        name_button_layout = {'width': '25%'}
        widget_layout = {'width': '15%'}
        widget_layout_long = {'width': '20%'}
        units_button_layout = {'width': '15%'}
        desc_button_layout = {'width': '45%'}
        divider_button_layout = {'width': '40%'}
        divider_button_layout = {'width': '60%'}
        box_layout = Layout(display='flex',
                            flex_flow='row',
                            align_items='stretch',
                            width='100%')

        self.cell_type_dropdown = Dropdown(description='Cell type:', )
        self.cell_type_dropdown.style = {
            'description_width':
            '%sch' % str(len(self.cell_type_dropdown.description) + 1)
        }

        cell_type_names_layout = {'width': '30%'}
        cell_type_names_style = {'description_width': 'initial'}
        self.parent_name = Text(
            value='None',
            description='inherits properties from parent type:',
            disabled=True,
            style=cell_type_names_style,
            layout=cell_type_names_layout)

        explain_inheritance = Label(
            value=
            '    This cell line inherits its properties from its parent type. Any settings below override those inherited properties.'
        )  # , style=cell_type_names_style, layout=cell_type_names_layout)

        self.cell_type_parent_row = HBox(
            [self.cell_type_dropdown, self.parent_name])
        self.cell_type_parent_dict = {}

        self.cell_type_dict = {}
        self.cell_type_dict['default'] = 'default'
        self.cell_type_dropdown.options = self.cell_type_dict

        self.cell_type_dropdown.observe(self.cell_type_cb)

        self.cell_type_parent_dict['default'] = 'None'

        self.cell_def_vboxes = []

        self.bnd_filenames = [None] * 1

        self.cfg_filenames = [None] * 1
        #  >>>>>>>>>>>>>>>>> <cell_definition> = default
        #  -------------------------
        div_row1 = Button(
            description=
            'phenotype:cycle (model: advanced_Ki67_cycle_model; code=0)',
            disabled=True,
            layout=divider_button_layout)
        div_row1.style.button_color = 'orange'
        name_btn = Button(description='Phase 0 -> Phase 1 transition rate',
                          disabled=True,
                          layout=name_button_layout)
        name_btn.style.button_color = 'lightgreen'
        self.float0 = FloatText(value='1e30',
                                step='100000000000000000000000000000',
                                style=style,
                                layout=widget_layout)
        units_btn = Button(description='1/min',
                           disabled=True,
                           layout=name_button_layout)
        units_btn.style.button_color = 'lightgreen'
        row = [
            name_btn,
            self.float0,
            units_btn,
        ]
        box0 = Box(children=row, layout=box_layout)

        name_btn = Button(description='Phase 1 -> Phase 2 transition rate',
                          disabled=True,
                          layout=name_button_layout)
        name_btn.style.button_color = 'tan'
        self.float1 = FloatText(value='1e30',
                                step='100000000000000000000000000000',
                                style=style,
                                layout=widget_layout)
        units_btn = Button(description='1/min',
                           disabled=True,
                           layout=name_button_layout)
        units_btn.style.button_color = 'tan'
        row = [
            name_btn,
            self.float1,
            units_btn,
        ]
        box1 = Box(children=row, layout=box_layout)

        name_btn = Button(description='Phase 2 -> Phase 0 transition rate',
                          disabled=True,
                          layout=name_button_layout)
        name_btn.style.button_color = 'lightgreen'
        self.float2 = FloatText(value='0.006666667',
                                step='0.001',
                                style=style,
                                layout=widget_layout)
        units_btn = Button(description='1/min',
                           disabled=True,
                           layout=name_button_layout)
        units_btn.style.button_color = 'lightgreen'
        row = [
            name_btn,
            self.float2,
            units_btn,
        ]
        box2 = Box(children=row, layout=box_layout)

        #  -------------------------
        div_row2 = Button(description='phenotype:death',
                          disabled=True,
                          layout=divider_button_layout)
        div_row2.style.button_color = 'orange'
        death_model1 = Button(description='model: apoptosis',
                              disabled=True,
                              layout={'width': '30%'})
        death_model1.style.button_color = '#ffde6b'
        name_btn = Button(description='death rate',
                          disabled=True,
                          layout=name_button_layout)
        name_btn.style.button_color = 'tan'
        self.float3 = FloatText(value='0.0',
                                step='0.01',
                                style=style,
                                layout=widget_layout)
        units_btn = Button(description='1/min',
                           disabled=True,
                           layout=name_button_layout)
        units_btn.style.button_color = 'tan'
        row = [
            name_btn,
            self.float3,
            units_btn,
        ]
        box3 = Box(children=row, layout=box_layout)

        death_model2 = Button(description='model: necrosis',
                              disabled=True,
                              layout={'width': '30%'})
        death_model2.style.button_color = '#ffde6b'
        name_btn = Button(description='death rate',
                          disabled=True,
                          layout=name_button_layout)
        name_btn.style.button_color = 'lightgreen'
        self.float4 = FloatText(value='0.0',
                                step='0.01',
                                style=style,
                                layout=widget_layout)
        units_btn = Button(description='1/min',
                           disabled=True,
                           layout=name_button_layout)
        units_btn.style.button_color = 'lightgreen'
        row = [
            name_btn,
            self.float4,
            units_btn,
        ]
        box4 = Box(children=row, layout=box_layout)

        #  -------------------------
        div_row3 = Button(description='phenotype:motility',
                          disabled=True,
                          layout=divider_button_layout)
        div_row3.style.button_color = 'orange'

        name_btn = Button(description='speed',
                          disabled=True,
                          layout=name_button_layout)
        name_btn.style.button_color = 'tan'
        self.float5 = FloatText(value='1',
                                step='0.1',
                                style=style,
                                layout=widget_layout)
        units_btn = Button(description='micron/min',
                           disabled=True,
                           layout=name_button_layout)
        units_btn.style.button_color = 'tan'
        row = [name_btn, self.float5, units_btn]
        box5 = Box(children=row, layout=box_layout)

        name_btn = Button(description='persistence_time',
                          disabled=True,
                          layout=name_button_layout)
        name_btn.style.button_color = 'lightgreen'
        self.float6 = FloatText(value='1',
                                step='0.1',
                                style=style,
                                layout=widget_layout)
        units_btn = Button(description='min',
                           disabled=True,
                           layout=name_button_layout)
        units_btn.style.button_color = 'lightgreen'
        row = [name_btn, self.float6, units_btn]
        box6 = Box(children=row, layout=box_layout)

        name_btn = Button(description='migration_bias',
                          disabled=True,
                          layout=name_button_layout)
        name_btn.style.button_color = 'tan'
        self.float7 = FloatText(value='0.3',
                                step='0.01',
                                style=style,
                                layout=widget_layout)
        units_btn = Button(description='dimensionless',
                           disabled=True,
                           layout=name_button_layout)
        units_btn.style.button_color = 'tan'
        row = [name_btn, self.float7, units_btn]
        box7 = Box(children=row, layout=box_layout)
        self.bool0 = Checkbox(description='enabled',
                              value=True,
                              layout=name_button_layout)
        self.bool1 = Checkbox(description='use_2D',
                              value=False,
                              layout=name_button_layout)
        #  -------------------------
        div_row4 = Button(description='phenotype:intracellular (maboss)',
                          disabled=True,
                          layout=divider_button_layout)
        div_row4.style.button_color = 'orange'
        bnd_filename = Button(description='bnd_filename',
                              disabled=True,
                              layout=name_button_layout)
        bnd_filename.style.button_color = 'lightgreen'
        self.bnd_filenames[0] = Text(
            value='../data/boolean_network/CCM_mod4_1.bnd',
            style=style,
            layout=widget_layout)
        row = [bnd_filename, self.bnd_filenames[0]]
        box8 = Box(children=row, layout=box_layout)
        cfg_filename = Button(description='cfg_filename',
                              disabled=True,
                              layout=name_button_layout)
        cfg_filename.style.button_color = 'tan'
        self.cfg_filenames[0] = Text(
            value='../data/boolean_network/CCM_mod4_1.cfg',
            style=style,
            layout=widget_layout)
        row = [cfg_filename, self.cfg_filenames[0]]
        box9 = Box(children=row, layout=box_layout)
        time_step = Button(description='time_step',
                           disabled=True,
                           layout=name_button_layout)
        time_step.style.button_color = 'lightgreen'
        self.float8 = FloatText(value='12', style=style, layout=widget_layout)
        units_btn = Button(description='min',
                           disabled=True,
                           layout=name_button_layout)
        units_btn.style.button_color = 'tan'
        row = [time_step, self.float8, units_btn]
        box10 = Box(children=row, layout=box_layout)
        intracellular_initial_values = Button(description='initial_values',
                                              disabled=True,
                                              layout={'width': '30%'})
        intracellular_initial_values.style.button_color = '#ffde6b'
        name_btn = Button(description='Single',
                          disabled=True,
                          layout=name_button_layout)
        name_btn.style.button_color = 'tan'
        self.float9 = FloatText(value='0.1',
                                step='0.01',
                                style=style,
                                layout=widget_layout)
        units_btn = Button(description='dimensionless',
                           disabled=True,
                           layout=name_button_layout)
        units_btn.style.button_color = 'tan'
        time_step = [
            name_btn,
            self.float9,
            units_btn,
        ]
        box11 = Box(children=time_step, layout=box_layout)

        intracellular_mutations = Button(description='mutations',
                                         disabled=True,
                                         layout={'width': '30%'})
        intracellular_mutations.style.button_color = '#ffde6b'
        name_btn = Button(description='GF',
                          disabled=True,
                          layout=name_button_layout)
        name_btn.style.button_color = 'lightgreen'
        self.float10 = FloatText(value='1',
                                 step='0.1',
                                 style=style,
                                 layout=widget_layout)
        units_btn = Button(description='dimensionless',
                           disabled=True,
                           layout=name_button_layout)
        units_btn.style.button_color = 'lightgreen'
        time_step = [
            name_btn,
            self.float10,
            units_btn,
        ]
        box12 = Box(children=time_step, layout=box_layout)

        name_btn = Button(description='Glucose',
                          disabled=True,
                          layout=name_button_layout)
        name_btn.style.button_color = 'tan'
        self.float11 = FloatText(value='1',
                                 step='0.1',
                                 style=style,
                                 layout=widget_layout)
        units_btn = Button(description='dimensionless',
                           disabled=True,
                           layout=name_button_layout)
        units_btn.style.button_color = 'tan'
        time_step = [
            name_btn,
            self.float11,
            units_btn,
        ]
        box13 = Box(children=time_step, layout=box_layout)

        #      ================== <custom_data>, if present ==================

        self.cell_def_vbox0 = VBox([
            div_row1,
            box0,
            box1,
            box2,
            div_row2,
            death_model1,
            box3,
            death_model2,
            box4,
            div_row3,
            box5,
            box6,
            box7,
            self.bool0,
            self.bool1,
            div_row4,
            box8,
            box9,
            box10,
            intracellular_initial_values,
            box11,
            intracellular_mutations,
            box12,
            box13,
        ])
        # ------------------------------------------
        self.cell_def_vboxes.append(self.cell_def_vbox0)

        row = [time_step, self.float8, units_btn]
        box13 = Box(children=time_step, layout=box_layout)

        self.tab = VBox([
            self.cell_type_parent_row,
            explain_inheritance,
            self.cell_def_vbox0,
        ])
        self.display_cell_type_default()
示例#25
0
    def __init__(self):
        tab_height = '520px'
        tab_height = '600px'
        tab_layout = Layout(width='900px',   # border='2px solid black',
                            height=tab_height, overflow_y='scroll')

        self.output_dir = '.'

        constWidth = '180px'

#        self.fig = plt.figure(figsize=(6, 6))
        # self.fig = plt.figure(figsize=(7, 7))

        max_frames = 1
        self.svg_plot = interactive(self.plot_svg, frame=(0, max_frames), continuous_update=False)
        plot_size = '500px'
        plot_size = '600px'
        self.svg_plot.layout.width = plot_size
        self.svg_plot.layout.height = plot_size
        self.use_defaults = True
        self.show_nucleus = 0  # 0->False, 1->True in Checkbox!
        self.show_edge = 1  # 0->False, 1->True in Checkbox!
        self.scale_radius = 1.0
        self.axes_min = 0.0
        self.axes_max = 2000   # hmm, this can change (TODO?)

        self.max_frames = BoundedIntText(
            min=0, max=99999, value=max_frames,
            description='Max',
            layout=Layout(width='160px'),
#            layout=Layout(flex='1 1 auto', width='auto'),  #Layout(width='160px'),
        )
        self.max_frames.observe(self.update_max_frames)

        self.show_nucleus_checkbox= Checkbox(
            description='nucleus', value=False, disabled=False,
            layout=Layout(width=constWidth),
#            layout=Layout(flex='1 1 auto', width='auto'),  #Layout(width='160px'),
        )
        self.show_nucleus_checkbox.observe(self.show_nucleus_cb)

        self.show_edge_checkbox= Checkbox(
            description='edge', value=True, disabled=False,
            layout=Layout(width=constWidth),
#            layout=Layout(flex='1 1 auto', width='auto'),  #Layout(width='160px'),
        )
        self.show_edge_checkbox.observe(self.show_edge_cb)

#        row1 = HBox([Label('(select slider: drag or left/right arrows)'), 
#            self.max_frames, VBox([self.show_nucleus_checkbox, self.show_edge_checkbox])])
#            self.max_frames, self.show_nucleus_checkbox], layout=Layout(width='500px'))

#        self.tab = VBox([row1,self.svg_plot], layout=tab_layout)

        items_auto = [Label('select slider: drag or left/right arrows'), 
            self.max_frames, 
            self.show_nucleus_checkbox,  
            self.show_edge_checkbox, 
         ]
#row1 = HBox([Label('(select slider: drag or left/right arrows)'), 
#            max_frames, show_nucleus_checkbox, show_edge_checkbox], 
#            layout=Layout(width='800px'))
        box_layout = Layout(display='flex',
                    flex_flow='row',
                    align_items='stretch',
                    width='70%')
        row1 = Box(children=items_auto, layout=box_layout)

        if (hublib_flag):
            self.download_button = Download('svg.zip', style='warning', icon='cloud-download', 
                                            tooltip='You need to allow pop-ups in your browser', cb=self.download_cb)
            download_row = HBox([self.download_button.w, Label("Download all cell plots (browser must allow pop-ups).")])
            self.tab = VBox([row1, self.svg_plot, self.download_button.w], layout=tab_layout)
    #        self.tab = VBox([row1, self.svg_plot, self.download_button.w])
#            self.tab = VBox([row1, self.svg_plot, download_row])
        else:
            self.tab = VBox([row1, self.svg_plot])
示例#26
0
    def set_widgets():
        global drop_var, drop_date, depth_wid, hb_3d, hb_2d, vb_ev_2d, vb_ev_3d, valor_x, valor_y, date, drop_date_range2, drop_date_range1

        #widgets para escoger que datos mostrar
        drop_var=widgets.Dropdown(
            options=[(variables[2][n], n) for n in range(len(variables[2]))],
            value=0,
            description='Variables:',
        )
        date= set_date()
        drop_date=widgets.Dropdown(
            options=[(str(date[i]), i) for i in range(len(date))],
            value=0,
            description='Date:',
        )
        drop_date.observe(date_on_change, names='value')
        drop_var.observe(variable_on_change, names='value')
        hb_3d= HBox([drop_var, drop_date, depth_wid])
        hb_2d= HBox([drop_var, drop_date])

        #cuadro de texto para donde se escoge el valor de coordenada x e y
        valor_x= widgets.BoundedFloatText(
        value=0,
        min=0,
        max=dataset.variables[variables[0][propiedades[0]]].shape[-2]-1,
        step=1,
        description='x:'
        )
        valor_y= widgets.BoundedFloatText(
            value=0,
            min=0,
            max=dataset.variables[variables[0][propiedades[0]]].shape[-1]-1,
            step=1,
            description='y:'
        )

        #widgets para ver mas info
        boton_tiempo= widgets.Button(
            description='Tiempo'
        )

        boton_animacion= widgets.Button(
            description='Animacion evolucion'
        )

        boton_prof= widgets.Button(
            description='Profundidad'
        )

        boton_corte_lon= widgets.Button(
            description='Longitudinal'
        )

        boton_corte_lat= widgets.Button(
            description='Latitudinal'
        )

        Label_cor= widgets.Label("Clicar en el mapa para escoger coordenadas:")
        Label_display= widgets.Label("Mostrar:")
        Label_date= widgets.Label("Rango de fechas:")
        Label_section= widgets.Label("Mapa con corte:")
        Label_plot= widgets.Label("Diagrama con evolucion en funcion:")


        drop_date_range1=widgets.Dropdown(
            options=[(str(date[i]), i) for i in range(0,len(date)-range_index)],
            value=0,
            description='Desde:',
        )

        drop_date_range2=widgets.Dropdown(
            options=[(str(date[i]), i) for i in range(range_index,len(date))],
            value=len(date)-range_index,
            description='Hasta:',
        )

        vb_cor=VBox([Label_cor,valor_x, valor_y])
        vb_date_range= VBox([Label_date,drop_date_range1,drop_date_range2])
        hb_options= HBox([vb_cor,vb_date_range])

        hb_corte= HBox([boton_corte_lat, boton_corte_lon], layout= box_layout)
        hb_plot= HBox([boton_tiempo, boton_prof], layout= box_layout)
        hb_time= HBox([boton_tiempo], layout= box_layout)

        vb_ev_3d= VBox([hb_options, Label_display,boton_animacion,Label_section, hb_corte, Label_plot,hb_plot])
        vb_ev_2d= VBox([hb_options, Label_display,boton_animacion,Label_plot, hb_time])

        widgets.interact(drop_date_range1 = drop_date_range1, drop_date_range2 = drop_date_range2)
        drop_date_range1.observe(range_on_change, names='value')
        boton_prof.on_click(on_button_clicked_ev_prof)
        boton_tiempo.on_click(on_button_clicked_ev_time)
        boton_animacion.on_click(on_button_clicked_animacion)
        boton_corte_lat.on_click(on_button_clicked_corte_lat)
        boton_corte_lon.on_click(on_button_clicked_corte_lon)
示例#27
0

output_items_left = [
    Box([jobListBtn]),
    Box([jobSelect], layout = Layout(width='100%')),
    Box([jobOutputBtn,abortBtn], layout = Layout(display = 'flex', justify_content = 'space-between', width='100%')),
    Box([outputSelect], layout = Layout(width='100%')),
    Box([downloadOpBtn])
]

output_items_right = [
    Box([jobHisBtn]),
    Box([jobHisSelect],layout = Layout(width='100%'))
]

outputBox = HBox([VBox(output_items_left, layout = Layout(width='50%')), VBox(output_items_right, layout = Layout(width='50%'))],
                layout = Layout(width='100%'))

#outputBox = HBox(output_items_right)

################################# Output tab end ###################################


################################# building tab  ###################################
build_item_layout = Layout(
    display = 'flex',
    flex_flow = 'row',
    justify_content = 'flex-start',
    width = '50%'
)

modelDd = Dropdown(options=['Swan','Funwave_tvd','OpenFoam', 'NHWAVE'])
示例#28
0
 def _tool_bar_initialize(self, name="default", window=None):
     self.actions = dict()
     self._tool_bar = self._tool_bar_layout = HBox()
     self._layout_initialize(None)
示例#29
0
class MultiProgressWidget(MultiProgress):
    """ Multiple progress bar Widget suitable for the notebook

    Displays multiple progress bars for a computation, split on computation
    type.

    See Also
    --------
    progress: User-level function <--- use this
    MultiProgress: Non-visualization component that contains most logic
    ProgressWidget: Single progress bar widget
    """
    def __init__(self, keys, scheduler=None, minimum=0, dt=0.1, func=key_split,
                 complete=False):
        self.func = func
        keys = {k.key if hasattr(k, 'key') else k for k in keys}
        self.setup_pre(keys, scheduler, minimum, dt, complete)

        def clear_errors(errors):
            for k in errors:
                self.task_erred(None, k, None, True)

        # Get keys and all-keys
        if self.scheduler.loop._thread_ident == threading.current_thread().ident:
            errors = self.setup(keys, complete)
        else:
            errors = sync(self.scheduler.loop, self.setup, keys, complete)

        # Set up widgets
        from ipywidgets import FloatProgress, VBox, HTML, HBox
        self.bars = {key: FloatProgress(min=0, max=1, description=key)
                        for key in self.all_keys}
        self.texts = {key: HTML() for key in self.all_keys}
        self.boxes = {key: HBox([self.bars[key], self.texts[key]])
                        for key in self.all_keys}
        self.time = HTML()
        self.widget = HBox([self.time, VBox([self.boxes[key] for key in
                                            sorted(self.bars, key=str)])])

        from tornado.ioloop import IOLoop
        loop = IOLoop.instance()
        self.pc = PeriodicCallback(self._update, 1000 * self._dt, io_loop=loop)
        self.pc.start()

        # Clear out errors
        clear_errors(errors)

    def _start(self):
        return self._update()

    def _ipython_display_(self, **kwargs):
        return self.widget._ipython_display_(**kwargs)

    def stop(self, exception=None, key=None):
        with ignoring(AttributeError):
            self.pc.stop()
        Progress.stop(self, exception, key)
        self._update()
        for k, v in self.keys.items():
            if not v:
                self.bars[k].bar_style = 'success'
        if exception:
            self.bars[self.func(key)].value = 1
            self.bars[self.func(key)].bar_style = 'danger'

    def _update(self):
        for k in self.all_keys:
            ntasks = len(self.all_keys[k])
            ndone = ntasks - len(self.keys[k])
            self.bars[k].value = ndone / ntasks if ntasks else 1.0
            self.texts[k].value = "%d / %d" % (ndone, ntasks)
            self.time.value = format_time(self.elapsed)
示例#30
0
def time_series(path):
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    from datetime import timedelta
    import pandas as pd
    import json
    import glob

    confvalues = config.read()
    inst = confvalues['set']['institution']
    file_info = glob.glob(f"{path}*_information.json")[0]

    with open(file_info, 'r') as f:
        info_data = json.loads(f.read())
    pid = info_data['ogc_fid'][0]
    crop_name = info_data['cropname'][0]
    area = info_data['area'][0]
    figure_dpi = 50

    def plot_ts_s2(cloud):
        file_ts = glob.glob(f"{path}*_time_series_s2.csv")[0]
        df = pd.read_csv(file_ts, index_col=0)

        df['date'] = pd.to_datetime(df['date_part'], unit='s')
        start_date = df.iloc[0]['date'].date()
        end_date = df.iloc[-1]['date'].date()
        print(f"From '{start_date}' to '{end_date}'.")

        pd.set_option('max_colwidth', 200)
        pd.set_option('display.max_columns', 20)

        # Plot settings are confirm IJRS graphics instructions
        plt.rcParams['axes.titlesize'] = 16
        plt.rcParams['axes.labelsize'] = 14
        plt.rcParams['xtick.labelsize'] = 12
        plt.rcParams['ytick.labelsize'] = 12
        plt.rcParams['legend.fontsize'] = 14

        df.set_index(['date'], inplace=True)

        dfB4 = df[df.band == 'B4'].copy()
        dfB8 = df[df.band == 'B8'].copy()
        datesFmt = mdates.DateFormatter('%-d %b %Y')
        if cloud is False:
            # Plot NDVI
            fig = plt.figure(figsize=(16.0, 10.0))
            axb = fig.add_subplot(1, 1, 1)

            axb.set_title(
                f"Parcel {pid} (crop: {crop_name}, area: {area:.2f} ha)")
            axb.set_xlabel("Date")
            axb.xaxis.set_major_formatter(datesFmt)

            axb.set_ylabel(r'DN')
            axb.plot(dfB4.index, dfB4['mean'], linestyle=' ', marker='s',
                     markersize=10, color='DarkBlue',
                     fillstyle='none', label='B4')
            axb.plot(dfB8.index, dfB8['mean'], linestyle=' ', marker='o',
                     markersize=10, color='Red',
                     fillstyle='none', label='B8')

            axb.set_xlim(start_date, end_date + timedelta(1))
            axb.set_ylim(0, 10000)

            axb.legend(frameon=False)  # loc=2)

            return plt.show()

        else:
            # Plot Cloud free NDVI.
            dfSC = df[df.band == 'SC'].copy()
            dfNDVI = (dfB8['mean'] - dfB4['mean']) / \
                (dfB8['mean'] + dfB4['mean'])

            cloudfree = ((dfSC['mean'] >= 4) & (dfSC['mean'] < 6))

            fig = plt.figure(figsize=(16.0, 10.0))
            axb = fig.add_subplot(1, 1, 1)

            axb.set_title(
                f"{inst}\nParcel {pid} (crop: {crop_name}, area: {area:.2f} sqm)")

            axb.set_xlabel("Date")
            axb.xaxis.set_major_formatter(datesFmt)

            axb.set_ylabel(r'NDVI')
            axb.plot(dfNDVI.index, dfNDVI, linestyle=' ', marker='s',
                     markersize=10, color='DarkBlue',
                     fillstyle='none', label='NDVI')
            axb.plot(dfNDVI[cloudfree].index, dfNDVI[cloudfree],
                     linestyle=' ', marker='P',
                     markersize=10, color='Red',
                     fillstyle='none', label='Cloud free NDVI')

            axb.set_xlim(start_date, end_date + timedelta(1))
            axb.set_ylim(0, 1.0)

            axb.legend(frameon=False)  # loc=2)

            return plt.show()

    def plot_ts_bs():
        import numpy as np
        file_ts = glob.glob(f"{path}*_time_series_bs.csv")[0]
        df = pd.read_csv(file_ts, index_col=0)

        df['date'] = pd.to_datetime(df['date_part'], unit='s')
        start_date = df.iloc[0]['date'].date()
        end_date = df.iloc[-1]['date'].date()
        print(f"From '{start_date}' to '{end_date}'.")

        pd.set_option('max_colwidth', 200)
        pd.set_option('display.max_columns', 20)

        # Plot settings are confirm IJRS graphics instructions
        plt.rcParams['axes.titlesize'] = 16
        plt.rcParams['axes.labelsize'] = 14
        plt.rcParams['xtick.labelsize'] = 12
        plt.rcParams['ytick.labelsize'] = 12
        plt.rcParams['legend.fontsize'] = 14

        df.set_index(['date'], inplace=True)
        datesFmt = mdates.DateFormatter('%-d %b %Y')
        # Plot Backscattering coefficient

        datesFmt = mdates.DateFormatter('%-d %b %Y')
        df = df[df['mean'] >= 0]  # to remove negative values

        dfVV = df[df.band == 'VV'].copy()
        dfVH = df[df.band == 'VH'].copy()
        fig = plt.figure(figsize=(16.0, 10.0))
        axb = fig.add_subplot(1, 1, 1)

        dfVV['mean'] = dfVV['mean'].map(lambda s: 10.0 * np.log10(s))
        dfVH['mean'] = dfVH['mean'].map(lambda s: 10.0 * np.log10(s))

        axb.set_title(
            f"{inst}\nParcel {pid} (crop: {crop_name}, area: {area:.2f} sqm)")
        axb.set_xlabel("Date")
        axb.xaxis.set_major_formatter(datesFmt)

        axb.set_ylabel(r'Backscattering coefficient, $\gamma\degree$ (dB)')
        axb.plot(dfVH.index, dfVH['mean'], linestyle=' ', marker='s',
                 markersize=10, color='DarkBlue', fillstyle='none', label='VH')
        axb.plot(dfVV.index, dfVV['mean'], linestyle=' ', marker='o',
                 markersize=10, color='Red', fillstyle='none', label='VV')

        axb.set_xlim(start_date, end_date + timedelta(1))
        axb.set_ylim(-25, 0)

        axb.legend(frameon=False)  # loc=2)

        return plt.show()

    def plot_ts_c6():
        file_ts = glob.glob(f"{path}*_time_series_c6.csv")[0]
        df = pd.read_csv(file_ts, index_col=0)

        df['date'] = pd.to_datetime(df['date_part'], unit='s')
        start_date = df.iloc[0]['date'].date()
        end_date = df.iloc[-1]['date'].date()
        print(f"From '{start_date}' to '{end_date}'.")

        pd.set_option('max_colwidth', 200)
        pd.set_option('display.max_columns', 20)
        datesFmt = mdates.DateFormatter('%-d %b %Y')

        # Plot settings are confirm IJRS graphics instructions
        plt.rcParams['axes.titlesize'] = 16
        plt.rcParams['axes.labelsize'] = 14
        plt.rcParams['xtick.labelsize'] = 12
        plt.rcParams['ytick.labelsize'] = 12
        plt.rcParams['legend.fontsize'] = 14

        df.set_index(['date'], inplace=True)

        # Plot Coherence

        dfVV = df[df.band == 'VV'].copy()
        dfVH = df[df.band == 'VH'].copy()
        fig = plt.figure(figsize=(16.0, 10.0))
        axb = fig.add_subplot(1, 1, 1)

        axb.set_title(
            f"{inst}\nParcel {pid} (crop: {crop_name}, area: {area:.2f} sqm)")
        axb.set_xlabel("Date")
        axb.xaxis.set_major_formatter(datesFmt)

        axb.set_ylabel(r'Coherence')
        axb.plot(dfVH.index, dfVH['mean'], linestyle=' ', marker='s',
                 markersize=10, color='DarkBlue', fillstyle='none', label='VH')
        axb.plot(dfVV.index, dfVV['mean'], linestyle=' ', marker='o',
                 markersize=10, color='Red', fillstyle='none', label='VV')

        axb.set_xlim(start_date, end_date + timedelta(1))
        axb.set_ylim(0, 1)

        axb.legend(frameon=False)  # loc=2)

        return plt.show()

    ts_cloud = Checkbox(
        value=True,
        description='Cloud free',
        disabled=False,
        indent=False
    )

    ts_files = glob.glob(f"{path}*time_series*.csv")
    ts_file_types = [b.split('_')[-1].split('.')[0] for b in ts_files]
    ts_types = [t for t in data_options.pts_tstype() if t[1] in ts_file_types]

    ts_type = Dropdown(
        options=ts_types,
        description='Select type:',
        disabled=False,
    )

    btn_ts = Button(
        value=False,
        description='Plot TS',
        disabled=False,
        button_style='info',
        tooltip='Refresh output',
        icon=''
    )

    ts_out = Output()

    @btn_ts.on_click
    def btn_ts_on_click(b):
        btn_ts.description = 'Refresh'
        btn_ts.icon = 'refresh'
        with ts_out:
            ts_out.clear_output()
            if ts_type.value == 's2':
                plot_ts_s2(ts_cloud.value)
            elif ts_type.value == 'bs':
                plot_ts_bs()
            elif ts_type.value == 'c6':
                plot_ts_c6()

    def on_ts_type_change(change):
        if ts_type.value == 's2':
            wbox_ts.children = [btn_ts, ts_type, ts_cloud]
        else:
            wbox_ts.children = [btn_ts, ts_type]

    ts_type.observe(on_ts_type_change, 'value')

    wbox_ts = HBox([btn_ts, ts_type, ts_cloud])

    wbox = VBox([wbox_ts, ts_out])

    return wbox
示例#31
0
 def __init__(self, gen, total=None, display=True, leave=True, parent=None, auto_update=True):
     self.progress,self.text = IntProgress(min=0, max=len(gen) if total is None else total), HTML()
     self.box = HBox([self.progress, self.text])
     super().__init__(gen, total, display, leave, parent, auto_update)
示例#32
0
    def plot(self,
             absolute_value=False,
             digits=3,
             rounding_function=np.around,
             bar_width=25,
             width=1500,
             abbrev_labels=0,
             vcolors=None,
             title="Predict Triplot",
             widget=False,
             show=True):
        """Plot the Predict Triplot explanation (triplot visualization).

        Parameters
        ----------
        absolute_value : bool, optional
            If `True` aspect importance values are drawn as absolute values 
            (default is `False`).
        digits : int, optional
            Number of decimal places (`np.around`) to round contributions.
            See `rounding_function` parameter (default is `3`).
        rounding_function : function, optional
            A function that will be used for rounding numbers (default is `np.around`).
        bar_width : float, optional
            Width of bars in px (default is `25`).
        width : float, optional
            Width of triplot in px (default is `1500`).
        abbrev_labels : int, optional
            If greater than 0, labels for axis Y will be abbreviated according to this parameter
            (default is `0`, which means no abbreviation).
        vcolors : 2-tuple of str, optional
            Color of bars (default is `["#8bdcbe", "#f05a71"]`).
        title : str, optional
            Title of the plot (default is `"Predict Triplot"`).
        widget : bool, optional
            If `True` triplot interactive widget version is generated
            (default is `False`).
        show : bool, optional
            `True` shows the plot; `False` returns the plotly Figure object 
            (default is `True`).
            NOTE: Ignored if `widget` is `True`.

        Returns
        -------
        None or plotly.graph_objects.Figure or ipywidgets.HBox with plotly.graph_objs._figurewidget.FigureWidget
            Return figure that can be edited or saved. See `show` parameter.
        """
        _global_checks.global_check_import('kaleido', 'Predict Triplot')
        ## right plot
        hierarchical_clustering_dendrogram_plot_without_annotations = go.Figure(
            self._hierarchical_clustering_dendrogram)
        variables_order = list(
            hierarchical_clustering_dendrogram_plot_without_annotations.layout.
            yaxis.ticktext)

        ## middle plot
        (
            hierarchical_importance_dendrogram_plot_without_annotations,
            updated_dendro_traces,
        ) = plot.plot_predict_hierarchical_importance(
            hierarchical_clustering_dendrogram_plot_without_annotations,
            self.result,
            rounding_function,
            digits,
            absolute_value,
            self.type,
        )

        hierarchical_clustering_dendrogram_plot = plot.add_text_to_dendrogram(
            hierarchical_clustering_dendrogram_plot_without_annotations,
            updated_dendro_traces,
            rounding_function,
            digits,
            type="clustering",
        )

        hierarchical_importance_dendrogram_plot = plot.add_text_to_dendrogram(
            hierarchical_importance_dendrogram_plot_without_annotations,
            updated_dendro_traces,
            rounding_function,
            digits,
            type="importance",
        )

        ## left plot
        fig = plot.plot_single_aspects_importance(
            self.single_variable_importance,
            variables_order,
            rounding_function,
            digits,
            vcolors,
        )
        fig.layout["xaxis"]["range"] = (
            fig.layout["xaxis"]["range"][0],
            fig.layout["xaxis"]["range"][1] * 1.05,
        )
        m = len(variables_order)
        y_vals = [-5 - i * 10 for i in range(m)]
        fig.data[0]["y"] = y_vals

        ## triplot

        fig.add_shape(
            type="line",
            x0=0,
            x1=0,
            y0=-0.01,
            y1=1.01,
            yref="paper",
            xref="x2",
            line={
                "color": "#371ea3",
                "width": 1.5,
                "dash": "dot"
            },
        )

        min_x_imp, max_x_imp = np.Inf, -np.Inf
        for data in hierarchical_importance_dendrogram_plot["data"][::-1]:
            data["xaxis"] = "x2"
            data["hoverinfo"] = "text"
            data["line"] = {"color": "#46bac2", "width": 2}
            fig.add_trace(data)
            min_x_imp = np.min([min_x_imp, np.min(data["x"])])
            max_x_imp = np.max([max_x_imp, np.max(data["x"])])
        min_max_margin_imp = (max_x_imp - min_x_imp) * 0.15

        min_x_clust, max_x_clust = np.Inf, -np.Inf
        for data in hierarchical_clustering_dendrogram_plot["data"]:
            data["xaxis"] = "x3"
            data["hoverinfo"] = "text"
            data["line"] = {"color": "#46bac2", "width": 2}
            fig.add_trace(data)
            min_x_clust = np.min([min_x_clust, np.min(data["x"])])
            max_x_clust = np.max([max_x_clust, np.max(data["x"])])
        min_max_margin_clust = (max_x_clust - min_x_clust) * 0.15

        plot_height = 78 + 71 + m * bar_width + (m + 1) * bar_width / 4
        ticktext = plot.get_ticktext_for_plot(self.single_variable_importance,
                                              variables_order, abbrev_labels)

        fig.update_layout(xaxis={
            "autorange": False,
            "domain": [0, 0.33],
            "mirror": False,
            "showgrid": False,
            "showline": False,
            "zeroline": False,
            "ticks": "",
            "title_text": "Local variable importance",
        },
                          xaxis2={
                              "domain": [0.33, 0.66],
                              "mirror":
                              False,
                              "showgrid":
                              False,
                              "showline":
                              False,
                              "zeroline":
                              False,
                              "showticklabels":
                              True,
                              "tickvals": [0],
                              "ticktext": [""],
                              "ticks":
                              "",
                              "title_text":
                              "Hierarchical aspect importance",
                              "autorange":
                              False,
                              "fixedrange":
                              True,
                              "range": [
                                  min_x_imp - min_max_margin_imp,
                                  max_x_imp + min_max_margin_imp,
                              ],
                          },
                          xaxis3={
                              "domain": [0.66, 0.99],
                              "mirror":
                              False,
                              "showgrid":
                              False,
                              "showline":
                              False,
                              "zeroline":
                              False,
                              "showticklabels":
                              True,
                              "tickvals": [0],
                              "ticktext": [""],
                              "ticks":
                              "",
                              "title_text":
                              "Hierarchical clustering",
                              "autorange":
                              False,
                              "fixedrange":
                              True,
                              "range": [
                                  min_x_clust - min_max_margin_clust,
                                  max_x_clust + min_max_margin_clust,
                              ],
                          },
                          yaxis={
                              "mirror": False,
                              "ticks": "",
                              "fixedrange": True,
                              "gridwidth": 1,
                              "type": "linear",
                              "tickmode": "array",
                              "tickvals": y_vals,
                              "ticktext": ticktext,
                          },
                          title_text=title,
                          title_x=0.5,
                          font={"color": "#371ea3"},
                          template="none",
                          margin={
                              "t": 78,
                              "b": 71,
                              "r": 30
                          },
                          width=width,
                          height=plot_height,
                          showlegend=False,
                          hovermode="closest")

        fig, middle_point = plot._add_points_on_dendrogram_traces(fig)

        ##################################################################

        if widget:
            _global_checks.global_check_import('ipywidgets', 'Predict Triplot')
            from ipywidgets import HBox, Layout
            fig = go.FigureWidget(fig,
                                  layout={
                                      "autosize": True,
                                      "hoverdistance": 100
                                  })
            original_bar_colors = deepcopy(list(
                fig.data[0]["marker"]["color"]))
            original_text_colors = deepcopy(
                list(fig.data[0]["textfont"]["color"]))
            k = len(fig.data)
            updated_dendro_traces_in_full_figure = list(
                np.array(updated_dendro_traces) + (k - 1) / 2 +
                1) + list((k - 1) / 2 - np.array(updated_dendro_traces))

            def _update_childs(x, y, fig, k, selected, selected_y_cord):
                for i in range(1, k):
                    if middle_point[i] == (x, y):
                        fig.data[i]["line"]["color"] = "#46bac2"
                        fig.data[i]["line"]["width"] = 3
                        fig.data[k - i]["line"]["color"] = "#46bac2"
                        fig.data[k - i]["line"]["width"] = 3
                        selected.append(i)
                        selected.append(k - i)
                        if (fig.data[i]["y"][0] + 5) % 10 == 0:
                            selected_y_cord.append(
                                (fig.data[i]["y"][0] + 5) // -10)
                        if (fig.data[i]["y"][-1] - 5) % 10 == 0:
                            selected_y_cord.append(
                                (fig.data[i]["y"][-1] + 5) // -10)
                        _update_childs(
                            fig.data[i]["x"][0],
                            fig.data[i]["y"][0],
                            fig,
                            k,
                            selected,
                            selected_y_cord,
                        )
                        _update_childs(
                            fig.data[i]["x"][-1],
                            fig.data[i]["y"][-1],
                            fig,
                            k,
                            selected,
                            selected_y_cord,
                        )

            def _update_trace(trace, points, selector):
                if len(points.point_inds) == 1:
                    selected_ind = points.trace_index
                    with fig.batch_update():
                        if selected_ind not in updated_dendro_traces_in_full_figure:
                            for i in range(1, k):
                                fig.data[i]["line"]["color"] = "#46bac2"
                                fig.data[i]["line"]["width"] = 2
                                fig.data[i]["textfont"]["color"] = "#371ea3"
                                fig.data[i]["textfont"]["size"] = 12
                            fig.data[0]["marker"][
                                "color"] = original_bar_colors
                            fig.data[0]["textfont"][
                                "color"] = original_text_colors
                        else:
                            selected = [selected_ind, k - selected_ind]
                            selected_y_cord = []
                            if (fig.data[selected_ind]["y"][0] - 5) % 10 == 0:
                                selected_y_cord.append(
                                    (fig.data[selected_ind]["y"][0] + 5) //
                                    -10)
                            if (fig.data[selected_ind]["y"][-1] - 5) % 10 == 0:
                                selected_y_cord.append(
                                    (fig.data[selected_ind]["y"][-1] + 5) //
                                    -10)
                            fig.data[selected_ind]["line"]["color"] = "#46bac2"
                            fig.data[selected_ind]["line"]["width"] = 3
                            fig.data[selected_ind]["textfont"][
                                "color"] = "#371ea3"
                            fig.data[selected_ind]["textfont"]["size"] = 14
                            fig.data[k -
                                     selected_ind]["line"]["color"] = "#46bac2"
                            fig.data[k - selected_ind]["line"]["width"] = 3
                            fig.data[
                                k -
                                selected_ind]["textfont"]["color"] = "#371ea3"
                            fig.data[k - selected_ind]["textfont"]["size"] = 14
                            _update_childs(
                                fig.data[selected_ind]["x"][0],
                                fig.data[selected_ind]["y"][0],
                                fig,
                                k,
                                selected,
                                selected_y_cord,
                            )
                            _update_childs(
                                fig.data[selected_ind]["x"][-1],
                                fig.data[selected_ind]["y"][-1],
                                fig,
                                k,
                                selected,
                                selected_y_cord,
                            )
                            for i in range(1, k):
                                if i not in [selected_ind, k - selected_ind]:
                                    fig.data[i]["textfont"][
                                        "color"] = "#ceced9"
                                    fig.data[i]["textfont"]["size"] = 12
                                    if i not in selected:
                                        fig.data[i]["line"][
                                            "color"] = "#ceced9"
                                        fig.data[i]["line"]["width"] = 1

                            bars_colors_list = deepcopy(original_bar_colors)
                            text_colors_list = deepcopy(original_text_colors)
                            for i in range(m):
                                if i not in selected_y_cord:
                                    bars_colors_list[i] = "#ceced9"
                                    text_colors_list[i] = "#ceced9"
                            fig.data[0]["marker"]["color"] = bars_colors_list
                            fig.data[0]["textfont"]["color"] = text_colors_list

            for i in range(1, k):
                fig.data[i].on_click(_update_trace)
            return HBox([fig],
                        layout=Layout(overflow='scroll',
                                      width=f'{fig.layout.width}px'))
        if show:
            fig.show(config=_theme.get_default_config())
        else:
            return fig
示例#33
0
    def _widget(self):
        """ Create IPython widget for display within a notebook """
        try:
            return self._cached_widget
        except AttributeError:
            pass

        try:
            from ipywidgets import Layout, VBox, HBox, IntText, Button, HTML, Accordion
        except ImportError:
            self._cached_widget = None
            return None

        layout = Layout(width="150px")

        if self.dashboard_link:
            dashboard_link = (
                '<p><b>Dashboard: </b><a href="%s" target="_blank">%s</a></p>\n'
                % (self.dashboard_link, self.dashboard_link)
            )
        else:
            dashboard_link = ""

        if self.jupyter_link:
            jupyter_link = (
                '<p><b>Jupyter: </b><a href="%s" target="_blank">%s</a></p>\n'
                % (self.jupyter_link, self.jupyter_link)
            )
        else:
            jupyter_link = ""

        title = "<h2>%s</h2>" % self._cluster_class_name
        title = HTML(title)
        dashboard = HTML(dashboard_link)
        jupyter = HTML(jupyter_link)

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

        if self._supports_scaling:
            request = IntText(
                self.initial_node_count, description="Nodes", layout=layout
            )
            scale = Button(description="Scale", layout=layout)

            minimum = IntText(0, description="Minimum", layout=layout)
            maximum = IntText(0, description="Maximum", layout=layout)
            adapt = Button(description="Adapt", layout=layout)

            accordion = Accordion(
                [HBox([request, scale]), HBox([minimum, maximum, adapt])],
                layout=Layout(min_width="500px"),
            )
            accordion.selected_index = None
            accordion.set_title(0, "Manual Scaling")
            accordion.set_title(1, "Adaptive Scaling")

            def adapt_cb(b):
                self.adapt(minimum=minimum.value, maximum=maximum.value)
                update()

            adapt.on_click(adapt_cb)

            def scale_cb(b):
                with log_errors():
                    n = request.value
                    with suppress(AttributeError):
                        self._adaptive.stop()
                    self.scale(n)
                    update()

            scale.on_click(scale_cb)
        else:
            accordion = HTML("")

        box = VBox([title, HBox([status, accordion]), jupyter, dashboard])

        self._cached_widget = box

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

        pc = PeriodicCallback(update, 500)  # , io_loop=self.loop)
        self.periodic_callbacks["cluster-repr"] = pc
        pc.start()

        return box
示例#34
0
 def _status_bar_initialize(self, window=None):
     self._status_bar = self._status_bar_layout = HBox()
     self._layout_initialize(None)
示例#35
0
def interact_gravity_Dike():
    s1 = FloatSlider(
        description=r"$\Delta\rho$",
        min=-5.0,
        max=5.0,
        step=0.1,
        value=1.0,
        continuous_update=False,
    )
    s2 = FloatSlider(
        description=r"$z_1$",
        min=0.1,
        max=4.0,
        step=0.1,
        value=1 / 3,
        continuous_update=False,
    )
    s3 = FloatSlider(
        description=r"$z_2$",
        min=0.1,
        max=5.0,
        step=0.1,
        value=4 / 3,
        continuous_update=False,
    )
    s4 = FloatSlider(description="b",
                     min=0.1,
                     max=5.0,
                     step=0.1,
                     value=1.0,
                     continuous_update=False)
    s5 = FloatSlider(
        description=r"$\beta$",
        min=-85,
        max=85,
        step=5,
        value=45,
        continuous_update=False,
    )
    s6 = FloatSlider(
        description="Step",
        min=0.005,
        max=0.10,
        step=0.005,
        value=0.01,
        continuous_update=False,
        readout_format=".3f",
    )
    b1 = ToggleButton(
        value=True,
        description="keep previous plots",
        disabled=False,
        button_style="",  # 'success', 'info', 'warning', 'danger' or ''
        tooltip="Click me",
        layout=Layout(width="20%"),
    )
    v1 = VBox([s1, s2, s3])
    v2 = VBox([s4, s5, s6])
    out1 = HBox([v1, v2, b1])
    out = interactive_output(
        drawfunction,
        {
            "delta_rho": s1,
            "z1": s2,
            "z2": s3,
            "b": s4,
            "beta": s5,
            "stationSpacing": s6,
            "B": b1,
        },
    )
    return VBox([out1, out])
示例#36
0
    def __init__(self,
                 *,
                 bundle: Bundle,
                 default_token_filter: str = None,
                 **kwargs):
        global CURRENT_BUNDLE
        CURRENT_BUNDLE = bundle
        """Alternative implementation that uses VectorizedCorpus"""
        self.bundle: Bundle = bundle
        self.co_occurrences: pd.DataFrame = None
        self.pivot_column_name: str = 'time_period'

        if not isinstance(bundle.token2id, Token2Id):
            raise ValueError(
                f"Expected Token2Id, found {type(bundle.token2id)}")

        if not isinstance(bundle.compute_options, dict):
            raise ValueError(
                "Expected Compute Options in bundle but found no such thing.")
        """Current processed corpus"""
        self.corpus: VectorizedCorpus = bundle.corpus
        """Properties that changes current corpus"""
        self._pivot: Dropdown = Dropdown(
            options=["year", "lustrum", "decade"],
            value="decade",
            placeholder='Group by',
            layout=Layout(width='auto'),
        )
        """"Keyness source"""
        self._keyness_source: Dropdown = Dropdown(
            options={
                "Full corpus": KeynessMetricSource.Full,
                "Concept corpus": KeynessMetricSource.Concept,
                "Weighed corpus": KeynessMetricSource.Weighed,
            } if bundle.concept_corpus is not None else {
                "Full corpus": KeynessMetricSource.Full,
            },
            value=KeynessMetricSource.Weighed
            if bundle.concept_corpus is not None else KeynessMetricSource.Full,
            layout=Layout(width='auto'),
        )
        """Properties that changes current corpus"""
        self._keyness: Dropdown = Dropdown(
            options={
                "TF": KeynessMetric.TF,
                "TF (norm)": KeynessMetric.TF_normalized,
                "TF-IDF": KeynessMetric.TF_IDF,
                "HAL CWR": KeynessMetric.HAL_cwr,
                "PPMI": KeynessMetric.PPMI,
                "LLR": KeynessMetric.LLR,
                "LLR(Z)": KeynessMetric.LLR_Z,
                "LLR(N)": KeynessMetric.LLR_N,
                "DICE": KeynessMetric.DICE,
            },
            value=KeynessMetric.TF,
            layout=Layout(width='auto'),
        )
        """Properties that don't change current corpus"""
        self._token_filter: Text = Text(value=default_token_filter,
                                        placeholder='token match',
                                        layout=Layout(width='auto'))
        self._global_threshold_filter: Dropdown = Dropdown(
            options={
                f'>= {i}': i
                for i in (1, 2, 3, 4, 5, 10, 25, 50, 100, 250, 500)
            },
            value=5,
            layout=Layout(width='auto'),
        )
        self.concepts: Set[str] = set(self.bundle.context_opts.concept or [])
        self._largest: Dropdown = Dropdown(
            options=[10**i for i in range(0, 7)],
            value=10000,
            layout=Layout(width='auto'),
        )
        self._show_concept = ToggleButton(
            description='Show concept',
            value=False,
            icon='',
            layout=Layout(width='auto'),
        )
        self._message: HTML = HTML()
        self._compute: Button = Button(description="Compute",
                                       button_style='success',
                                       layout=Layout(width='auto'))
        self._save = Button(description='Save', layout=Layout(width='auto'))
        self._download = Button(description='Download',
                                layout=Layout(width='auto'))
        self._download_output: Output = Output()
        self._table_view = TableViewerClass(data=empty_data())

        self._button_bar = HBox(
            children=[
                VBox([HTML("<b>Token match</b>"), self._token_filter]),
                VBox([HTML("<b>Source</b>"), self._keyness_source]),
                VBox([HTML("<b>Keyness</b>"), self._keyness]),
                VBox([HTML("🙂"), self._show_concept]),
                VBox([HTML("<b>Group by</b>"), self._pivot]),
                VBox([HTML("<b>Threshold</b>"),
                      self._global_threshold_filter]),
                VBox([HTML("<b>Group limit</b>"), self._largest]),
                VBox([self._save, self._download]),
                VBox([self._compute, self._message]),
                self._download_output,
            ],
            layout=Layout(width='auto'),
        )
        super().__init__(
            children=[self._button_bar, self._table_view.container],
            layout=Layout(width='auto'),
            **kwargs)

        self._save.on_click(self.save)
        self._download.on_click(self.download)

        self.start_observe()
Quarantine_box = VBox([widgets.Label(value="1. Quarantine parameters"), ξ_base, \
                       rel_λ, A_rel], layout = box_layout_wide)
Timing_box = VBox([widgets.Label(value="2. Timing parameters"), d_vaccine, \
                       δ_param, ωR_param], layout = box_layout_wide)
Spread_box = VBox([widgets.Label(value="3. Contagion parameters"), R_0, rel_ρ], \
layout = box_layout_wide)
Disease_box = VBox([widgets.Label(value="4. Disease parameters"), initial_infect, π_D], \
layout = box_layout_wide)
slide_var_box = VBox([widgets.Label(value="5. Policy parameters"), slide_var, slide_varOut], \
layout = box_layout_wide)
# slide_var_box1 = VBox([widgets.Label(value="Plotting Parameters"), slide_var], \
# layout = box_layout_small)
# slide_var_box2 = VBox([widgets.Label(value="Plotting Parameters"), slide_varOut], \
# layout = box_layout_small)

line1 = HBox([Quarantine_box, Timing_box], layout=box_layout)
line2 = HBox([Disease_box, Spread_box], layout=box_layout)
line3 = HBox([slide_var_box], layout=box_layout)
paramsPanel = VBox([line1, line2, line3])
paramsPanel2d = VBox([line1, line2])
run_box = VBox([widgets.Label(value="Execute Model"), runModel, \
                displayPlotPanel])

#######################################################
#                      Functions                      #
#######################################################


def runModelFn(b):
    ## This is the function triggered by the runModel button.
    clear_output()  ## clear the output of the existing print-out