예제 #1
0
def Tabs(obj, **kwargs):
    """Convert a nested (ordered) dictionary to a Bokeh tabs widget

    Args:
        obj: a nested (ordered) dictionary where the keys are tab
            titles and the values are children of panels

    Returns:
        An instance of Bokeh Tabs

    Examples:
        >>> import bokeh.plotting as bp
        >>> import interview as iv
        >>> fig = bp.figure()
        >>> bp.show(iv.widget.Tabs({'title':fig}))
    """
    import bokeh.plotting as bp
    import bokeh.models.widgets as bw
    import bokeh.models.layouts as bl

    if isinstance(obj, bp.Figure) or isinstance(obj, bl.LayoutDOM):
        return obj
    elif isinstance(obj, dict):
        return bw.Tabs(tabs=[
            bw.Panel(child=Tabs(v, **kwargs), title=k) for k, v in obj.items()
        ],
                       **kwargs)
    else:
        raise ValueError("Input must be a dictionary or a Bokeh figure")
    def __init__(self,
                 limits_panel,
                 timeouts_panel,
                 pid_panel,
                 errors_plotter,
                 errors_plotter_clear_button,
                 title,
                 nest_level,
                 width=960):
        """Initialize member variables."""
        super().__init__()

        self.limits_panel = limits_panel.make_document_layout()
        self.timeouts_panel = timeouts_panel.make_document_layout()
        self.pid_panel = pid_panel.make_document_layout()
        self.errors_plotter = errors_plotter.make_document_layout()
        self.errors_plotter_clear_button = \
            errors_plotter_clear_button.make_document_layout()

        heading_level = 1 + nest_level
        column = []
        if title:
            column += [
                layouts.widgetbox([
                    widgets.Div(text='<h{}>Feedback Controller</h{}>'.format(
                        heading_level, heading_level))
                ])
            ]
        column += [
            widgets.Tabs(tabs=[
                widgets.Panel(title='Limits', child=self.limits_panel.layout),
                widgets.Panel(title='Timeouts',
                              child=self.timeouts_panel.layout),
                widgets.Panel(title='PID', child=self.pid_panel.layout),
                widgets.Panel(title='Errors',
                              child=layouts.column([
                                  self.errors_plotter.layout,
                                  self.errors_plotter_clear_button
                              ]))
            ],
                         width=width)
        ]
        self.column_layout = layouts.column(column)
예제 #3
0
def pages_rankingtable():
    df_all = ranking_df()
    autoTable = ranking_auto(df_all)
    generalTable = ranking_general(df_all)
    match = sme.EventDal.get_current_match()
    tab1 = bmw.Panel(child=generalTable, title='General Table')
    tab2 = bmw.Panel(child=autoTable, title='Auto Table')
    tabs = bmw.Tabs(tabs=[tab1, tab2])
    div1 = blt.WidgetBox(bmw.Div(text='<a href="index.html">Home Page</a>'))
    div2 = blt.WidgetBox(
        bmw.Div(text='<h1>Ranking Table</h1>' + 'updated at match:' + match))
    os.chdir(sc.output_path())
    bokeh.io.output_file('rankingtable.html')
    col = blt.column([div1, div2, tabs])
    title = 'Ranking Table: Match ' + match
    # LocalResource needed to load JS and CSS files from local folder
    res = server.view.bokeh_res.LocalResource(
        os.path.join(sc.output_path(), 'static'))
    bokeh.io.save(col, title=title, resources=res)
    source=staSource,
    legend=[value(y) for y in years],
)


def updateStatistics(attr, old, new):
    STAdata = {
        'gpa': gpa,
        '2015': [0] * 9,
        '2016': [0] * 9,
        '2017': [0] * 9,
    }
    rows = fetchRows(
        "select gpa, year from lgu.student where dept_name = '{}'".format(new))
    for stu in rows:
        yr, g = stu['year'], dct[stu['gpa']]
        STAdata[yr][g] += 1
    staSource.data = STAdata


deptSelect.on_change('value', updateStatistics)

# statistics page layout
statistics = layout([[deptSelect, p]])

tab1 = wd.Panel(child=courseInfo, title='Course Info')
tab2 = wd.Panel(child=statistics, title='Statistics')
tabs = wd.Tabs(tabs=[tab1, tab2])

curdoc().add_root(tabs)
예제 #5
0
def plot_spectrum(spectrum_id, rebin=1, normalize=True, porder=3):
    '''
    Plot spectrum

    Parameters:
    -----------
    spectrum_id
        ID of the spectrum
    rebin               int()
        Bin size
    normalize           bool()
        Normalize spectrum yes/no

    Returns:
    --------
    tabs

    '''

    #   Load spectrum, individual spectra (specfiles), and instrument
    spectrum = Spectrum.objects.get(pk=spectrum_id)
    specfiles = spectrum.specfile_set.order_by('filetype')
    instrument = spectrum.instrument

    #   Determine flux unit
    funit_str = spectrum.flux_units

    #   Set flux unit
    if funit_str == 'ADU':
        funit = u.adu
    elif funit_str == 'ergs/cm/cm/s/A':
        funit = u.erg / u.cm / u.cm / u.s / u.AA
    else:
        funit = u.ct

    #   Prepare list for tabs in the figure
    tabs = []

    #   Loop over spectra
    for specfile in specfiles:
        #   Extract data
        wave, flux, header = specfile.get_spectrum()

        #   Barycentric correction
        if not spectrum.barycor_bool:
            #   Set value for barycenter correction
            barycor = spectrum.barycor
            #   Apply barycenter correction
            wave = spectools.doppler_shift(wave, barycor)

        #   Instrument specific settings
        if instrument == 'HERMES' or instrument == 'FEROS':
            #   Restrict wavelength range
            sel = np.where(wave > 3860)
            wave, flux = wave[sel], flux[sel]

        #   Rebin spectrum
        #   If the spectrum is already normalized, set 'mean' to True to keep
        #   the continuum at ~1.
        if spectrum.normalized:
            wave, flux = spectools.rebin_spectrum(
                wave,
                flux,
                binsize=rebin,
                mean=True,
            )
        else:
            wave, flux = spectools.rebin_spectrum(wave, flux, binsize=rebin)

        ###
        #   Normalize & merge spectra

        #   Identify echelle spectra
        #   -> wave is a np.ndarray of np.ndarrays
        if isinstance(wave[0], np.ndarray):
            #   Set normalize to true if current value is 'None'
            if normalize == None:
                normalize = True

            #   Normalize & merge spectra
            if normalize:
                #   Prepare list for echelle orders
                orders = []

                #   Loop over each order
                for i, w in enumerate(wave):
                    #   Create Spectrum1D objects
                    orders.append(
                        Spectrum1D(
                            spectral_axis=w * u.AA,
                            flux=flux[i] * funit,
                        ))

                #   Normalize & merge spectra
                wave, flux = spectools.norm_merge_spectra(orders, order=porder)
                wave = wave.value

                #   Set flux unit to 'normalized'
                funit_str = 'normalized'
            else:
                #   Merge spectra
                wave, flux = spectools.merge_spectra(wave, flux)
        else:
            #   Normalize & merge spectra
            if normalize:
                #   Create Spectrum1D objects
                spec = Spectrum1D(spectral_axis=wave * u.AA, flux=flux * funit)

                #   Normalize spectrum
                spec, std = spectools.norm_spectrum(spec, order=porder)

                #   Split spectrum in 10 segments,
                #   if standard deviation is too high
                if std > 0.05:
                    nsegment = 10
                    nwave = len(wave)
                    step = int(nwave / nsegment)
                    segments = []

                    #   Loop over segments
                    i_old = 0
                    for i in range(step, step * nsegment, step):
                        #   Cut segments and add overlay range to the
                        #   segments, so that the normalization afterburner
                        #   can take effect
                        overlap = int(step * 0.15)
                        if i == step:
                            flux_seg = flux[i_old:i + overlap]
                            wave_seg = wave[i_old:i + overlap]
                        elif i == nsegment - 1:
                            flux_seg = flux[i_old - overlap:]
                            wave_seg = wave[i_old - overlap:]
                        else:
                            flux_seg = flux[i_old - overlap:i + overlap]
                            wave_seg = wave[i_old - overlap:i + overlap]
                        i_old = i

                        #   Create Spectrum1D objects for the segments
                        segments.append(
                            Spectrum1D(
                                spectral_axis=wave_seg * u.AA,
                                flux=flux_seg * funit,
                            ))
                    #   Normalize & merge spectra
                    wave, flux = spectools.norm_merge_spectra(
                        segments,
                        order=porder,
                    )
                    wave = wave.value

                else:
                    wave = np.asarray(spec.spectral_axis)
                    flux = np.asarray(spec.flux)

                #   Set flux unit to 'normalized'
                funit_str = 'normalized'

        #   Set the maximum and minimum so that weird peaks
        #   are cut off automatically.
        fsort = np.sort(flux)[::-1]
        maxf = fsort[int(np.floor(len(flux) / 100.))] * 1.2
        minf = np.max([np.min(flux) * 0.95, 0])

        #   Initialize figure
        #, sizing_mode='scale_width'
        fig = bpl.figure(plot_width=1550,
                         plot_height=400,
                         y_range=[minf, maxf])

        #   Plot spectrum
        fig.line(wave, flux, line_width=1, color="blue")

        #   Annotate He and H lines
        #   Define lines:
        Lines = [
            (3204.11, 'darkblue', 'HeII'),
            (3835.39, 'red', 'Hη'),
            (3888.05, 'red', 'Hζ'),
            (3970.07, 'red', 'Hε'),
            (4103., 'red', 'Hδ'),
            (4201., 'darkblue', 'HeII'),
            (4340.49, 'red', 'Hγ'),
            #(4339, 'darkblue', 'HeII'),
            (4471, 'blue', 'HeI'),
            (4542, 'darkblue', 'HeII'),
            (4687, 'darkblue', 'HeII'),
            (4861.36, 'red', 'Hβ'),
            (4922, 'blue', 'HeI'),
            (5412., 'darkblue', 'HeII'),
            (5877, 'blue', 'HeI'),
            (6562.1, 'red', 'Hα'),
            (6685, 'darkblue', 'HeII'),
        ]
        Annot = []

        #   For each line make an annotation box and and a label
        for h in Lines:
            #   Restrict to lines in plot range
            if h[0] > wave[0] and h[0] < wave[-1]:
                #   Make annotation
                Annot.append(
                    mpl.BoxAnnotation(left=h[0] - 2,
                                      right=h[0] + 2,
                                      fill_alpha=0.3,
                                      fill_color=h[1]))
                #   Make label
                lab = mpl.Label(
                    x=h[0],
                    y=345.,
                    y_units='screen',
                    text=h[2],
                    angle=90,
                    angle_units='deg',
                    text_align='right',
                    text_color=h[1],
                    text_alpha=0.6,
                    text_font_size='14px',
                    border_line_color='white',
                    border_line_alpha=1.0,
                    background_fill_color='white',
                    background_fill_alpha=0.3,
                )
                fig.add_layout(lab)
        #   Render annotations
        fig.renderers.extend(Annot)

        #   Set figure labels
        fig.toolbar.logo = None
        fig.yaxis.axis_label = 'Flux (' + funit_str + ')'
        fig.xaxis.axis_label = 'Wavelength (AA)'
        fig.yaxis.axis_label_text_font_size = '10pt'
        fig.xaxis.axis_label_text_font_size = '10pt'
        fig.min_border = 5

        #   Fill tabs list
        tabs.append(widgets.Panel(child=fig, title=specfile.filetype))

    #   Make figure from tabs list
    tabs = widgets.Tabs(tabs=tabs)
    return tabs
예제 #6
0
    def tool_handler_2d(self, doc):
        from bokeh import events
        from bokeh.layouts import row, column, widgetbox, Spacer
        from bokeh.models import ColumnDataSource, widgets
        from bokeh.models.mappers import LinearColorMapper
        from bokeh.models.widgets.markups import Div
        from bokeh.plotting import figure

        arr = self.arr
        # Set up the data
        x_coords, y_coords = arr.coords[arr.dims[0]], arr.coords[arr.dims[1]]

        # Styling
        default_palette = self.default_palette
        if arr.S.is_subtracted:
            default_palette = cc.coolwarm

        error_alpha = 0.3
        error_fill = '#3288bd'

        # Application Organization
        self.app_context.update({
            'data': arr,
            'data_range': {
                'x': (np.min(x_coords.values), np.max(x_coords.values)),
                'y': (np.min(y_coords.values), np.max(y_coords.values)),
            },
            'show_stat_variation': False,
            'color_mode': 'linear',
        })

        def stats_patch_from_data(data, subsampling_rate=None):
            if subsampling_rate is None:
                subsampling_rate = int(min(data.values.shape[0] / 50, 5))
                if subsampling_rate == 0:
                    subsampling_rate = 1

            x_values = data.coords[data.dims[0]].values[::subsampling_rate]
            values = data.values[::subsampling_rate]
            sq = np.sqrt(values)
            lower, upper = values - sq, values + sq

            return {
                'x': np.append(x_values, x_values[::-1]),
                'y': np.append(lower, upper[::-1]),
            }

        def update_stat_variation(plot_name, data):
            patch_data = stats_patch_from_data(data)
            if plot_name != 'right':  # the right plot is on transposed axes
                plots[plot_name +
                      '_marginal_err'].data_source.data = patch_data
            else:
                plots[plot_name + '_marginal_err'].data_source.data = {
                    'x': patch_data['y'],
                    'y': patch_data['x'],
                }

        figures, plots, app_widgets = self.app_context[
            'figures'], self.app_context['plots'], self.app_context['widgets']

        if self.cursor_default is not None and len(self.cursor_default) == 2:
            self.cursor = self.cursor_default
        else:
            self.cursor = [
                np.mean(self.app_context['data_range']['x']),
                np.mean(self.app_context['data_range']['y'])
            ]  # try a sensible default

        # create the main inset plot
        main_image = arr
        prepped_main_image = self.prep_image(main_image)
        self.app_context['color_maps']['main'] = LinearColorMapper(
            default_palette,
            low=np.min(prepped_main_image),
            high=np.max(prepped_main_image),
            nan_color='black')

        main_tools = ["wheel_zoom", "tap", "reset", "save"]
        main_title = 'Bokeh Tool: WARNING Unidentified'
        try:
            main_title = "Bokeh Tool: %s" % arr.S.label[:60]
        except:
            pass
        figures['main'] = figure(tools=main_tools,
                                 plot_width=self.app_main_size,
                                 plot_height=self.app_main_size,
                                 min_border=10,
                                 min_border_left=50,
                                 toolbar_location='left',
                                 x_axis_location='below',
                                 y_axis_location='right',
                                 title=main_title,
                                 x_range=self.app_context['data_range']['x'],
                                 y_range=self.app_context['data_range']['y'])
        figures['main'].xaxis.axis_label = arr.dims[0]
        figures['main'].yaxis.axis_label = arr.dims[1]
        figures['main'].toolbar.logo = None
        figures['main'].background_fill_color = "#fafafa"
        plots['main'] = figures['main'].image(
            [prepped_main_image.T],
            x=self.app_context['data_range']['x'][0],
            y=self.app_context['data_range']['y'][0],
            dw=self.app_context['data_range']['x'][1] -
            self.app_context['data_range']['x'][0],
            dh=self.app_context['data_range']['y'][1] -
            self.app_context['data_range']['y'][0],
            color_mapper=self.app_context['color_maps']['main'])

        app_widgets['info_div'] = Div(text='',
                                      width=self.app_marginal_size,
                                      height=100)

        # Create the bottom marginal plot
        bottom_marginal = arr.sel(**dict([[arr.dims[1], self.cursor[1]]]),
                                  method='nearest')
        figures['bottom_marginal'] = figure(
            plot_width=self.app_main_size,
            plot_height=200,
            title=None,
            x_range=figures['main'].x_range,
            y_range=(np.min(bottom_marginal.values),
                     np.max(bottom_marginal.values)),
            x_axis_location='above',
            toolbar_location=None,
            tools=[])
        plots['bottom_marginal'] = figures['bottom_marginal'].line(
            x=bottom_marginal.coords[arr.dims[0]].values,
            y=bottom_marginal.values)
        plots['bottom_marginal_err'] = figures['bottom_marginal'].patch(
            x=[],
            y=[],
            color=error_fill,
            fill_alpha=error_alpha,
            line_color=None)

        # Create the right marginal plot
        right_marginal = arr.sel(**dict([[arr.dims[0], self.cursor[0]]]),
                                 method='nearest')
        figures['right_marginal'] = figure(
            plot_width=200,
            plot_height=self.app_main_size,
            title=None,
            y_range=figures['main'].y_range,
            x_range=(np.min(right_marginal.values),
                     np.max(right_marginal.values)),
            y_axis_location='left',
            toolbar_location=None,
            tools=[])
        plots['right_marginal'] = figures['right_marginal'].line(
            y=right_marginal.coords[arr.dims[1]].values,
            x=right_marginal.values)
        plots['right_marginal_err'] = figures['right_marginal'].patch(
            x=[],
            y=[],
            color=error_fill,
            fill_alpha=error_alpha,
            line_color=None)

        cursor_lines = self.add_cursor_lines(figures['main'])

        # Attach tools and callbacks
        toggle = widgets.Toggle(label="Show Stat. Variation",
                                button_type="success",
                                active=False)

        def set_show_stat_variation(should_show):
            self.app_context['show_stat_variation'] = should_show

            if should_show:
                main_image_data = arr
                update_stat_variation(
                    'bottom',
                    main_image_data.sel(**dict([[arr.dims[1],
                                                 self.cursor[1]]]),
                                        method='nearest'))
                update_stat_variation(
                    'right',
                    main_image_data.sel(**dict([[arr.dims[0],
                                                 self.cursor[0]]]),
                                        method='nearest'))
                plots['bottom_marginal_err'].visible = True
                plots['right_marginal_err'].visible = True
            else:
                plots['bottom_marginal_err'].visible = False
                plots['right_marginal_err'].visible = False

        toggle.on_click(set_show_stat_variation)

        scan_keys = [
            'x', 'y', 'z', 'pass_energy', 'hv', 'location', 'id', 'probe_pol',
            'pump_pol'
        ]
        scan_info_source = ColumnDataSource({
            'keys': [k for k in scan_keys if k in arr.attrs],
            'values': [
                str(v) if isinstance(v, float) and np.isnan(v) else v
                for v in [arr.attrs[k] for k in scan_keys if k in arr.attrs]
            ],
        })
        scan_info_columns = [
            widgets.TableColumn(field='keys', title='Attr.'),
            widgets.TableColumn(field='values', title='Value'),
        ]

        POINTER_MODES = [
            (
                'Cursor',
                'cursor',
            ),
            (
                'Path',
                'path',
            ),
        ]

        COLOR_MODES = [
            (
                'Adaptive Hist. Eq. (Slow)',
                'adaptive_equalization',
            ),
            # ('Histogram Eq.', 'equalization',), # not implemented
            (
                'Linear',
                'linear',
            ),
            # ('Log', 'log',), # not implemented
        ]

        def on_change_color_mode(attr, old, new_color_mode):
            self.app_context['color_mode'] = new_color_mode
            if old is None or old != new_color_mode:
                right_image_data = arr.sel(**dict(
                    [[arr.dims[0], self.cursor[0]]]),
                                           method='nearest')
                bottom_image_data = arr.sel(**dict(
                    [[arr.dims[1], self.cursor[1]]]),
                                            method='nearest')
                main_image_data = arr
                prepped_right_image = self.prep_image(right_image_data)
                prepped_bottom_image = self.prep_image(bottom_image_data)
                prepped_main_image = self.prep_image(main_image_data)
                plots['right'].data_source.data = {
                    'image': [prepped_right_image]
                }
                plots['bottom'].data_source.data = {
                    'image': [prepped_bottom_image.T]
                }
                plots['main'].data_source.data = {
                    'image': [prepped_main_image.T]
                }
                update_main_colormap(None, None, main_color_range_slider.value)

        color_mode_dropdown = widgets.Dropdown(label='Color Mode',
                                               button_type='primary',
                                               menu=COLOR_MODES)
        color_mode_dropdown.on_change('value', on_change_color_mode)

        symmetry_point_name_input = widgets.TextInput(
            title='Symmetry Point Name', value="G")
        snap_checkbox = widgets.CheckboxButtonGroup(labels=['Snap Axes'],
                                                    active=[])
        place_symmetry_point_at_cursor_button = widgets.Button(
            label="Place Point", button_type="primary")

        def update_symmetry_points_for_display():
            pass

        def place_symmetry_point():
            cursor_dict = dict(zip(arr.dims, self.cursor))
            skip_dimensions = {'eV', 'delay', 'cycle'}
            if 'symmetry_points' not in arr.attrs:
                arr.attrs['symmetry_points'] = {}

            snap_distance = {
                'phi': 2,
                'beta': 2,
                'kx': 0.01,
                'ky': 0.01,
                'kz': 0.01,
                'kp': 0.01,
                'hv': 4,
            }

            cursor_dict = {
                k: v
                for k, v in cursor_dict.items() if k not in skip_dimensions
            }
            snapped = copy.copy(cursor_dict)

            if 'Snap Axes' in [
                    snap_checkbox.labels[i] for i in snap_checkbox.active
            ]:
                for axis, value in cursor_dict.items():
                    options = [
                        point[axis]
                        for point in arr.attrs['symmetry_points'].values()
                        if axis in point
                    ]
                    options = sorted(options, key=lambda x: np.abs(x - value))
                    if options and np.abs(options[0] -
                                          value) < snap_distance[axis]:
                        snapped[axis] = options[0]

            arr.attrs['symmetry_points'][
                symmetry_point_name_input.value] = snapped

        place_symmetry_point_at_cursor_button.on_click(place_symmetry_point)

        main_color_range_slider = widgets.RangeSlider(
            start=0, end=100, value=(
                0,
                100,
            ), title='Color Range (Main)')

        layout = row(
            column(figures['main'], figures['bottom_marginal']),
            column(figures['right_marginal'], Spacer(width=200, height=200)),
            column(
                widgetbox(
                    widgets.Dropdown(label='Pointer Mode',
                                     button_type='primary',
                                     menu=POINTER_MODES)),
                widgets.Tabs(tabs=[
                    widgets.Panel(child=widgetbox(
                        Div(text='<h2>Colorscale:</h2>'),
                        color_mode_dropdown,
                        main_color_range_slider,
                        Div(text=
                            '<h2 style="padding-top: 30px;">General Settings:</h2>'
                            ),
                        toggle,
                        self._cursor_info,
                        sizing_mode='scale_width'),
                                  title='Settings'),
                    widgets.Panel(child=widgetbox(
                        app_widgets['info_div'],
                        Div(text=
                            '<h2 style="padding-top: 30px; padding-bottom: 10px;">Scan Info</h2>'
                            ),
                        widgets.DataTable(source=scan_info_source,
                                          columns=scan_info_columns,
                                          width=400,
                                          height=400),
                        sizing_mode='scale_width',
                        width=400),
                                  title='Info'),
                    widgets.Panel(child=widgetbox(
                        Div(text='<h2>Preparation</h2>'),
                        symmetry_point_name_input,
                        snap_checkbox,
                        place_symmetry_point_at_cursor_button,
                        sizing_mode='scale_width'),
                                  title='Preparation'),
                ],
                             width=400)))

        update_main_colormap = self.update_colormap_for('main')

        def on_click_save(event):
            save_dataset(arr)
            print(event)

        def click_main_image(event):
            self.cursor = [event.x, event.y]

            right_marginal_data = arr.sel(**dict(
                [[arr.dims[0], self.cursor[0]]]),
                                          method='nearest')
            bottom_marginal_data = arr.sel(**dict(
                [[arr.dims[1], self.cursor[1]]]),
                                           method='nearest')
            plots['bottom_marginal'].data_source.data = {
                'x': bottom_marginal_data.coords[arr.dims[0]].values,
                'y': bottom_marginal_data.values,
            }
            plots['right_marginal'].data_source.data = {
                'y': right_marginal_data.coords[arr.dims[1]].values,
                'x': right_marginal_data.values,
            }
            if self.app_context['show_stat_variation']:
                update_stat_variation('right', right_marginal_data)
                update_stat_variation('bottom', bottom_marginal_data)
            figures['bottom_marginal'].y_range.start = np.min(
                bottom_marginal_data.values)
            figures['bottom_marginal'].y_range.end = np.max(
                bottom_marginal_data.values)
            figures['right_marginal'].x_range.start = np.min(
                right_marginal_data.values)
            figures['right_marginal'].x_range.end = np.max(
                right_marginal_data.values)

            self.save_app()

        figures['main'].on_event(events.Tap, click_main_image)
        main_color_range_slider.on_change('value', update_main_colormap)

        doc.add_root(layout)
        doc.title = "Bokeh Tool"
        self.load_app()
        self.save_app()
예제 #7
0
login = layout( [
        [ wb(name) ],
        [ wb(pwd) ],
        [ wb(btnLogin), wb(btnReset) ]  # side by side
    ] )

major = layout( [
        [ wb(majors, width=800) ],
        [ wb(text, btnRandom, answer) ]
    ] )

page1 = wd.Panel(child=login, title="Login")
page2 = wd.Panel(child=major, title="Major")

tabs = wd.Tabs( tabs=[page1, page2] )

def choose():
    cnt=5
    for i in range(cnt):
        answer.text = "your answer is .... {}".format(cnt-i)
        time.sleep(2)
        idx = random.randint(0,len(majors.labels)-1)
        majors.active = idx
    answer.text = "your answer is " + majors.labels[idx]

btnRandom.on_click(choose)

# show(tabs)
curdoc().add_root(tabs)
예제 #8
0
def main():
    # session = bp.Session(load_from_config=False)
    # bp.output_server(docname='simple_precoded_srs_AN1', session=session)
    bp.output_file('simple_precoded_srs.html', title="Simple Precoded SRS")

    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    # xxxxxxxxxxxxxxx Scenario Description xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    # 3 Base Stations, each sending data to its own user while interfering
    # with the other users.

    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    # xxxxxxxxxxxxxxx Configuration xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    num_prbs = 25  # Number of PRBs to simulate
    Nsc = 12 * num_prbs  # Number of subcarriers
    Nzc = 149  # Size of the sequence
    u1 = 1  # Root sequence index of the first user
    u2 = 2  # Root sequence index of the first user
    u3 = 3  # Root sequence index of the first user
    numAnAnt = 4  # Number of Base station antennas
    numUeAnt = 2  # Number of UE antennas

    num_samples = 1  # Number of simulated channel samples (from
    # Jakes process)

    # Channel configuration
    speedTerminal = 0 / 3.6  # Speed in m/s
    fcDbl = 2.6e9  # Central carrier frequency (in Hz)
    timeTTIDbl = 1e-3  # Time of a single TTI
    subcarrierBandDbl = 15e3  # Subcarrier bandwidth (in Hz)
    numOfSubcarriersPRBInt = 12  # Number of subcarriers in each PRB
    L = 16  # The number of rays for the Jakes model.

    # Dependent parameters
    lambdaDbl = 3e8 / fcDbl  # Carrier wave length
    Fd = speedTerminal / lambdaDbl  # Doppler Frequency
    Ts = 1. / (Nsc * subcarrierBandDbl)  # Sampling time

    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    # xxxxxxxxxxxxxxx Generate the root sequence xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    a_u1 = get_extended_ZF(calcBaseZC(Nzc, u1), Nsc / 2)
    a_u2 = get_extended_ZF(calcBaseZC(Nzc, u2), Nsc / 2)
    a_u3 = get_extended_ZF(calcBaseZC(Nzc, u3), Nsc / 2)

    print("Nsc: {0}".format(Nsc))
    print("a_u.shape: {0}".format(a_u1.shape))

    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    # xxxxxxxxxxxxxxx Create shifted sequences for 3 users xxxxxxxxxxxxxxxxxxxx
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    # We arbitrarily choose some cyclic shift index and then we call
    # zadoffchu.get_srs_seq to get the shifted sequence.
    shift_index = 4
    r1 = get_srs_seq(a_u1, shift_index)
    r2 = get_srs_seq(a_u2, shift_index)
    r3 = get_srs_seq(a_u3, shift_index)

    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    # xxxxxxxxxxxxxxx Generate channels from users to the BS xxxxxxxxxxxxxx
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    jakes_all_links = np.empty([3, 3], dtype=object)
    tdlchannels_all_links = np.empty([3, 3], dtype=object)
    impulse_responses = np.empty([3, 3], dtype=object)
    # Dimension: `UEs x ANs x num_subcarriers x numUeAnt x numAnAnt`
    freq_responses = np.empty([3, 3, Nsc, numUeAnt, numAnAnt], dtype=complex)

    for ueIdx in range(3):
        for anIdx in range(3):
            jakes_all_links[ueIdx,
                            anIdx] = JakesSampleGenerator(Fd,
                                                          Ts,
                                                          L,
                                                          shape=(numUeAnt,
                                                                 numAnAnt))

            tdlchannels_all_links[ueIdx, anIdx] = TdlChannel(
                jakes_all_links[ueIdx, anIdx],
                tap_powers_dB=COST259_TUx.tap_powers_dB,
                tap_delays=COST259_TUx.tap_delays)

            tdlchannels_all_links[ueIdx,
                                  anIdx].generate_impulse_response(num_samples)

            impulse_responses[ueIdx, anIdx] \
                = tdlchannels_all_links[
                ueIdx, anIdx].get_last_impulse_response()

            freq_responses[ueIdx, anIdx] = \
                impulse_responses[ueIdx, anIdx].get_freq_response(Nsc)[:, :, :,
                0]

    # xxxxxxxxxx Channels in downlink direction xxxxxxxxxxxxxxxxxxxxxxxxxxx
    # Dimension: `Nsc x numUeAnt x numAnAnt`
    dH11 = freq_responses[0, 0]
    dH12 = freq_responses[0, 1]
    dH13 = freq_responses[0, 2]
    dH21 = freq_responses[1, 0]
    dH22 = freq_responses[1, 1]
    dH23 = freq_responses[1, 2]
    dH31 = freq_responses[2, 0]
    dH32 = freq_responses[2, 1]
    dH33 = freq_responses[2, 2]

    # xxxxxxxxxx Principal dimension in downlink direction xxxxxxxxxxxxxxxx
    sc_idx = 124  # Index of the subcarrier we are interested in
    [dU11, _, _] = np.linalg.svd(dH11[sc_idx])
    [dU22, _, _] = np.linalg.svd(dH22[sc_idx])
    [dU33, _, _] = np.linalg.svd(dH33[sc_idx])

    # xxxxxxxxxx Users precoders xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    # Users' precoders are the main column of the U matrix
    F11 = dU11[:, 0].conj()
    F22 = dU22[:, 0].conj()
    F33 = dU33[:, 0].conj()

    # xxxxxxxxxx Channels in uplink direction xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    # int_path_loss = 0.05  # Path loss of the interfering links
    # int_g = math.sqrt(int_path_loss)  # Gain of interfering links
    # dir_d = 1.0                   #  Gain of direct links

    pl = np.array([[2.21e-08, 2.14e-09, 1.88e-08],
                   [3.45e-10, 2.17e-08, 4.53e-10],
                   [4.38e-10, 8.04e-10, 4.75e-08]])
    # pl = np.array([[  1,   0.1,   0.1],
    #                [  0.1,   1,   0.1],
    #                [  0.1,   0.1,   1]])

    # Dimension: `Nsc x numAnAnt x numUeAnt`
    uH11 = math.sqrt(pl[0, 0]) * np.transpose(dH11, axes=[0, 2, 1])
    uH12 = math.sqrt(pl[0, 1]) * np.transpose(dH12, axes=[0, 2, 1])
    uH13 = math.sqrt(pl[0, 2]) * np.transpose(dH13, axes=[0, 2, 1])
    uH21 = math.sqrt(pl[1, 0]) * np.transpose(dH21, axes=[0, 2, 1])
    uH22 = math.sqrt(pl[1, 1]) * np.transpose(dH22, axes=[0, 2, 1])
    uH23 = math.sqrt(pl[1, 2]) * np.transpose(dH23, axes=[0, 2, 1])
    uH31 = math.sqrt(pl[2, 0]) * np.transpose(dH31, axes=[0, 2, 1])
    uH32 = math.sqrt(pl[2, 1]) * np.transpose(dH32, axes=[0, 2, 1])
    uH33 = math.sqrt(pl[2, 2]) * np.transpose(dH33, axes=[0, 2, 1])

    # Compute the equivalent uplink channels
    uH11_eq = uH11.dot(F11)
    uH12_eq = uH12.dot(F22)
    uH13_eq = uH13.dot(F33)
    uH21_eq = uH21.dot(F11)
    uH22_eq = uH22.dot(F22)
    uH23_eq = uH23.dot(F33)
    uH31_eq = uH31.dot(F11)
    uH32_eq = uH32.dot(F22)
    uH33_eq = uH33.dot(F33)

    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    # xxxxxxxxxxxxxxx Compute Received Signals xxxxxxxxxxxxxxxxxxxxxxxxxxxx
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    # Calculate the received signals
    comb_indexes = np.r_[0:Nsc:2]
    Y1_term11 = uH11_eq[comb_indexes] * r1[:, np.newaxis]
    Y1_term12 = uH12_eq[comb_indexes] * r2[:, np.newaxis]
    Y1_term13 = uH13_eq[comb_indexes] * r3[:, np.newaxis]
    Y1 = Y1_term11 + Y1_term12 + Y1_term13

    Y2_term21 = uH21_eq[comb_indexes] * r1[:, np.newaxis]
    Y2_term22 = uH22_eq[comb_indexes] * r2[:, np.newaxis]
    Y2_term23 = uH23_eq[comb_indexes] * r3[:, np.newaxis]
    Y2 = Y2_term21 + Y2_term22 + Y2_term23

    Y3_term31 = uH31_eq[comb_indexes] * r1[:, np.newaxis]
    Y3_term32 = uH32_eq[comb_indexes] * r2[:, np.newaxis]
    Y3_term33 = uH33_eq[comb_indexes] * r3[:, np.newaxis]
    Y3 = Y3_term31 + Y3_term32 + Y3_term33

    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    # xxxxxxxxxxxxxxx Estimate the equivalent channel xxxxxxxxxxxxxxxxxxxxx
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    (uH11_eq_est, uH12_eq_est, uH13_eq_est, uH21_eq_est, uH22_eq_est,
     uH23_eq_est, uH31_eq_est, uH32_eq_est,
     uH33_eq_est) = estimate_channels_remove_only_direct(
         Y1, Y2, Y3, r1, r2, r3, Nsc, comb_indexes)

    (uH11_eq_est_SIC, uH12_eq_est_SIC, uH13_eq_est_SIC, uH21_eq_est_SIC,
     uH22_eq_est_SIC, uH23_eq_est_SIC, uH31_eq_est_SIC, uH32_eq_est_SIC,
     uH33_eq_est_SIC) = estimate_channels_remove_direct_and_perform_SIC(
         Y1, Y2, Y3, r1, r2, r3, Nsc, comb_indexes)

    # Compute the MSE reduction due to SIC
    improve11 = compute_channel_estimation_error_dB(
        uH11_eq, uH11_eq_est) - compute_channel_estimation_error_dB(
            uH11_eq, uH11_eq_est_SIC)
    improve12 = compute_channel_estimation_error_dB(
        uH12_eq, uH12_eq_est) - compute_channel_estimation_error_dB(
            uH12_eq, uH12_eq_est_SIC)
    improve13 = compute_channel_estimation_error_dB(
        uH13_eq, uH13_eq_est) - compute_channel_estimation_error_dB(
            uH13_eq, uH13_eq_est_SIC)

    improve21 = compute_channel_estimation_error_dB(
        uH21_eq, uH21_eq_est) - compute_channel_estimation_error_dB(
            uH21_eq, uH21_eq_est_SIC)
    improve22 = compute_channel_estimation_error_dB(
        uH22_eq, uH22_eq_est) - compute_channel_estimation_error_dB(
            uH22_eq, uH22_eq_est_SIC)
    improve23 = compute_channel_estimation_error_dB(
        uH23_eq, uH23_eq_est) - compute_channel_estimation_error_dB(
            uH23_eq, uH23_eq_est_SIC)

    improve31 = compute_channel_estimation_error_dB(
        uH31_eq, uH31_eq_est) - compute_channel_estimation_error_dB(
            uH31_eq, uH31_eq_est_SIC)
    improve32 = compute_channel_estimation_error_dB(
        uH32_eq, uH32_eq_est) - compute_channel_estimation_error_dB(
            uH32_eq, uH32_eq_est_SIC)
    improve33 = compute_channel_estimation_error_dB(
        uH33_eq, uH33_eq_est) - compute_channel_estimation_error_dB(
            uH33_eq, uH33_eq_est_SIC)
    print(improve11)
    print(improve12)
    print(improve13)
    print(improve21)
    print(improve22)
    print(improve23)
    print(improve31)
    print(improve32)
    print(improve33)

    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    # xxxxxxxxxxxxxxx Plot the true and estimated channels xxxxxxxxxxxxxxxx
    # xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    p1 = plot_true_and_estimated_channel_with_bokeh_all_antennas(
        uH11_eq, uH11_eq_est, title='Direct Channel from UE1 to AN1')
    p2 = plot_true_and_estimated_channel_with_bokeh_all_antennas(
        uH12_eq, uH12_eq_est, title='Interfering Channel from UE2 to AN1')
    p3 = plot_true_and_estimated_channel_with_bokeh_all_antennas(
        uH13_eq, uH13_eq_est, title='Interfering Channel from UE3 to AN1')
    tab1 = bw.Panel(child=p1, title="UE1 to AN1")
    tab2 = bw.Panel(child=p2, title="UE2 to AN1")
    tab3 = bw.Panel(child=p3, title="UE3 to AN1")
    tabs_an1 = bw.Tabs(tabs=[tab1, tab2, tab3])

    p1 = plot_true_and_estimated_channel_with_bokeh_all_antennas(
        uH21_eq, uH21_eq_est, title='Interfering Channel from UE1 to AN2')
    p2 = plot_true_and_estimated_channel_with_bokeh_all_antennas(
        uH22_eq, uH22_eq_est, title='Direct Channel from UE2 to AN2')
    p3 = plot_true_and_estimated_channel_with_bokeh_all_antennas(
        uH23_eq, uH23_eq_est, title='Interfering Channel from UE3 to AN2')
    tab1 = bw.Panel(child=p1, title="UE1 to AN2")
    tab2 = bw.Panel(child=p2, title="UE2 to AN2")
    tab3 = bw.Panel(child=p3, title="UE3 to AN2")
    tabs_an2 = bw.Tabs(tabs=[tab1, tab2, tab3])

    p1 = plot_true_and_estimated_channel_with_bokeh_all_antennas(
        uH31_eq, uH31_eq_est, title='Interfering Channel from UE1 to AN3')
    p2 = plot_true_and_estimated_channel_with_bokeh_all_antennas(
        uH32_eq, uH32_eq_est, title='Interfering Channel from UE2 to AN3')
    p3 = plot_true_and_estimated_channel_with_bokeh_all_antennas(
        uH33_eq, uH33_eq_est, title='Direct Channel from UE3 to AN3')
    tab1 = bw.Panel(child=p1, title="UE1 to AN3")
    tab2 = bw.Panel(child=p2, title="UE2 to AN3")
    tab3 = bw.Panel(child=p3, title="UE3 to AN3")
    tabs_an3 = bw.Tabs(tabs=[tab1, tab2, tab3])

    # Put each AN tab as a panel of an "ANs tab" and show it
    tabs1 = bw.Panel(child=tabs_an1, title="AN1")
    tabs2 = bw.Panel(child=tabs_an2, title="AN2")
    tabs3 = bw.Panel(child=tabs_an3, title="AN3")
    tabs_all = bw.Tabs(tabs=[tabs1, tabs2, tabs3])
    bp.show(tabs_all)
예제 #9
0
파일: hcsvr.py 프로젝트: HyperloopML/ML_AID
    def initialize_layout(self):

        self._logger("!!! LAYOUT PREPARATION...")

        #labels = list(np.unique(self.df_rfm[self.cfc]))

        self.color_mapper = CategoricalColorMapper(factors=list(self.levels),
                                                   palette=pal)

        # Make a slider object: slider
        self.slider = Slider(start=2,
                             end=6,
                             step=1,
                             value=self.nr_clusters,
                             title='Numarul de clustere',
                             width=200)
        # Attach the callback to the 'value' property of slider
        self.slider.on_change('value', self.on_cluster_change)

        self.DivText1 = Div(text="")
        self.DivText2 = Div(text="")

        self.slider_tree = Slider(start=2,
                                  end=4,
                                  step=1,
                                  value=self.nr_tree_lvl,
                                  title='Numarul de nivele arbore',
                                  width=200)
        self.slider_tree.on_change('value', self.on_update_tree_lvl)

        self.slider_table = Slider(start=10,
                                   end=10000,
                                   step=100,
                                   value=self.nr_shown_records,
                                   title='Numarul de inregistrari afisate',
                                   width=200)
        self.slider_table.on_change('value', self.on_update_table)

        if self.nr_fields > 2:
            opt = ["F1/F2", "F1/F3", "F2/F3"]
        else:
            opt = ["F1/F2"]
        self.cb_select_rfm = Select(title="Option:",
                                    value=self.default_cluster_view,
                                    options=opt)

        self.cb_select_rfm.on_change('value', self.on_sel_img_change)

        self.cluster_figure = figure(webgl=True,
                                     tools='box_select',
                                     plot_width=500,
                                     plot_height=500)
        tip1 = self.tooltip1
        tip2 = self.tooltip2
        self.hover = HoverTool(tooltips=[
            ("Segment", "@" + self.cfc),
            ("Client", "@" + self.cID),
            (tip1, "@" + self.hover_fields[tip1]),
            (tip2, "@" + self.hover_fields[tip2]),
        ])
        if self.FULL_DEBUG:
            self._logger(" Tooltips: {}".format(self.hover.tooltips))

        self.cluster_figure.add_tools(self.hover)

        self.update_cluster_image(self.current_cluster_view)

        self.empty_selection = self.current_cluster_glph_renderer.data_source.selected

        self.btn_reset = Button(label="Deselectare", width=20)
        self.btn_reset.on_click(self.on_reset_selection)

        self.btn_save = Button(label="Salvare", width=50)
        self.btn_save.on_click(self.on_save)

        self.btn_save_local = Button(label="Salvare doar local", width=50)
        self.btn_save_local.on_click(self.on_save_local)

        columns = list()
        for col in self.df_rfm.columns:
            if col == self.cfc:
                tblcol = TableColumn(
                    field=col,
                    title=col,
                    width=200,
                    formatter=StringFormatter(font_style="bold"))
            else:
                tblcol = TableColumn(
                    field=col,
                    title=col,
                    width=50,
                    formatter=NumberFormatter(format="0[.]00"))
            columns.append(tblcol)

        self.data_table = DataTable(source=self.cds_select,
                                    columns=columns,
                                    width=1200,
                                    height=500,
                                    fit_columns=False)

        self.cb_select_k = Select(title="Vizualizare segment:",
                                  value=self.current_segment,
                                  options=self.segments)
        self.cb_select_k.on_change("value", self.on_view_cluster)

        self.cb_scaling = Select(title="Metoda de scalare/normalizare:",
                                 value="MinMax",
                                 options=['MinMax', 'ZScore'])
        self.cb_scaling.on_change("value", self.on_cb_scaling)

        self.TableViewText = Div(text="N/A")

        self.ckbox_transf = CheckboxGroup(
            labels=["F1 LogTransform", "F2 LogTransform", "F3 LogTransform"],
            active=self.scale_cf)
        self.ckbox_transf.on_click(self.on_log_check)

        self.text_ClusterName = TextInput(
            value=self.cluster_config['Name'] +
            " ({} segments)".format(self.nr_clusters),
            title="Nume model:",
            width=400)

        self.cb_ClusterGrade = Select(title="Calitatea output:",
                                      value='PRODUCTION',
                                      width=300,
                                      options=['TESTS', 'PRODUCTION'])

        self.text_ClusterDesc = TextInput(value=self.ClusterDescription,
                                          title="Descriere:",
                                          width=700)

        self.text_Author = TextInput(value='Andrei Ionut Damian',
                                     title="Autor:")

        self.text_Algorithm = TextInput(value=self.sAlgorithm,
                                        title="Algoritm:",
                                        width=700)

        self.text_F1 = TextInput(value=self.cluster_config['Fields'][0],
                                 title="Descriere camp F1:")

        self.text_F2 = TextInput(value=self.cluster_config['Fields'][1],
                                 title="Descriere camp F2:")

        self.text_F3 = TextInput(value=self.cluster_config['Fields'][2],
                                 title="Descriere camp F3:")

        ##
        ## done with the controls
        ##

        ##
        ## now to layout preparation
        ##
        self.row_btns = row(self.btn_reset, self.btn_save)

        self.mytabs = list()

        # tab1: clusters

        self.tab1_col1_controls = column(widgetbox(self.slider),
                                         widgetbox(self.cb_select_rfm),
                                         widgetbox(self.slider_tree),
                                         widgetbox(self.cb_scaling),
                                         widgetbox(self.ckbox_transf),
                                         self.DivText1, self.DivText2,
                                         self.btn_reset, self.text_ClusterName,
                                         widgetbox(self.cb_ClusterGrade),
                                         self.text_Author)

        self.tab1_col2_controls = column(self.cluster_figure,
                                         self.text_ClusterDesc,
                                         self.text_Algorithm, self.text_F1,
                                         self.text_F2, self.text_F3,
                                         self.btn_save, self.btn_save_local)

        self.tab1_layout = row(self.tab1_col1_controls,
                               self.tab1_col2_controls)

        self.tab1 = widgets.Panel(child=self.tab1_layout, title='Segmentare')
        self.mytabs.append(self.tab1)

        #tab 2 table view
        self.tab2_controls = row(widgetbox(self.slider_table),
                                 widgetbox(self.cb_select_k),
                                 self.TableViewText)
        self.tab2_layout = column(self.tab2_controls, self.data_table)

        self.tab2 = widgets.Panel(child=self.tab2_layout,
                                  title='Vizualizare date')
        self.mytabs.append(self.tab2)

        # tab 3 tree view

        #self.tab3_empty_tree_fig =  figure(x_range=(0,40), y_range=(0,10))

        self.DivTreeImage = Div(text="")
        dt3 = "Arborele de decizie al segmentarii clientilor."
        #dt3+= " 'Value' reprezinta numarul de elemente din clasele {}".format(self.class_names)
        self.DivText3 = Div(text=dt3, width=1000, height=50)
        self.tab3_layout = column(self.DivText3, self.DivTreeImage)

        self.tab3 = widgets.Panel(child=self.tab3_layout,
                                  title='Vizualizare arbore')
        self.mytabs.append(self.tab3)

        # finalizare layout
        self.update_png()
        self.update_texts(self.last_tree_accuracy, self.last_clustering_error)

        self.final_layout = widgets.Tabs(tabs=self.mytabs)

        self._logger("!!! DONE LAYOUT PREPARATION.\n")

        if self.FastSave:
            self.on_save()
            self._logger("SHUTTING DOWN ...")
            os.kill(os.getpid(), 9)

        return
예제 #10
0
#pwave1.line('time','B',color=wave1.colour,source=sw1)
pwave1.line('time', 'B', color=wave2.colour, source=sw2)
#pwave1.line('time','B',color=wave3.colour,source=sw3)
pwave2.line('freq', 'B', color=wave1.colour, source=sf1)
pwave2.line('freq', 'B', color=wave2.colour, source=sf2)
pwave2.line('freq', 'B', color=wave3.colour, source=sf3)

waveletslayout = bkl.row(pwave1, pwave2)

x, y = makeLowPass(100, 1., 10, 15)
u, v = makeHighPass(100, 1., 40, 55)
s, t = makeBandPass(100, 1., 10, 15, 40, 55)

lpplot = bkp.Figure(title='Low Pass', x_axis_label='Freq (Hz)', webgl=True)
hpplot = bkp.Figure(title='High Pass', x_axis_label='Freq (Hz)', webgl=True)
bpplot = bkp.Figure(title='Band Pass', x_axis_label='Freq (Hz)', webgl=True)

slp = bkm.ColumnDataSource(data=dict(freq=x, Amp=y))
shp = bkm.ColumnDataSource(data=dict(freq=u, Amp=v))
sbp = bkm.ColumnDataSource(data=dict(freq=s, Amp=t))

lpplot.line('freq', 'Amp', source=slp)
hpplot.line('freq', 'Amp', source=shp)
bpplot.line('freq', 'Amp', source=sbp)

filterplots = bkl.row(lpplot, hpplot, bpplot)

tab1 = bkw.Panel(child=waveletslayout, title='Wavelets')
tab2 = bkw.Panel(child=filterplots, title='Filters')
tabs = bkw.Tabs(tabs=[tab1, tab2])
bkp.show(tabs)
예제 #11
0
col_controls = column(widgetbox(slider), widgetbox(cb_select),
                      widgetbox(slider_tree), widgetbox(slider_table), text1,
                      text2, btn_reset)

upper_layout = row(col_controls, cluster_figure)

tab1_layout = column(upper_layout, data_table)  # , img)

mytabs = list()
tab1 = widgets.Panel(child=tab1_layout, title='Procesare')
mytabs.append(tab1)

tab2_empty_tree_fig = figure(x_range=(0, 40), y_range=(0, 10))
text3 = Div(text="Arborele de decizie al segmentarii clientilor")
tab2_layout = column(text3, tab2_empty_tree_fig)
tab2 = widgets.Panel(child=tab2_layout, title='Vizualizare arbore')
mytabs.append(tab2)
update_png('tree.png')

final_layout = widgets.Tabs(tabs=mytabs)

if __name__ == '__main__':
    html_output = os.path.basename(s_prefix + __file__ + '.html')
    output_file(html_output)
    show(final_layout)
else:
    document = curdoc()
    document.add_root(final_layout)
    document.title = 'RFM Server'