Beispiel #1
0
 def beforeClicked(self, event, button: Button, graphId: int,
                   metadata: Metadata):
     button.disabled = True
     button.label = 'Working!'
     UnlockedDocumentProxy(button.document).add_next_tick_callback(
         partial(self.calculate_datapoints,
                 graphId=graphId,
                 button=button,
                 metadata=metadata))
Beispiel #2
0
def make_tab():
    # Slider to select width of bin
    pastdays_select = RangeSlider(start=0,
                                  end=999,
                                  value=(0, 999),
                                  step=1,
                                  title='Past Days',
                                  sizing_mode="stretch_both")
    # Slider to select buffer size
    bufferdays_select = Slider(start=.01,
                               end=9,
                               value=0.01,
                               step=.1,
                               title='Buffer Size (days)',
                               sizing_mode="stretch_both")
    # Re-read
    refresh_button = Button(label="Time window and buffer are up to date",
                            button_type="success",
                            sizing_mode="stretch_both")
    refresh_button.disabled = True

    # read data
    flights, available_carriers = read(pastdays_select, bufferdays_select)

    # CheckboxGroup to select carrier to display
    locationcodes = np.unique(
        ['.'.join(seedid.split('.')[:3]) for seedid in available_carriers])
    selections = []
    for locationcode in locationcodes[:maxnstation]:
        matching = [s for s in available_carriers if locationcode in s]
        active = [i for i, m in enumerate(matching)]  # if "Z" == m[-1]]
        selections += [
            CheckboxButtonGroup(labels=matching,
                                active=active,
                                sizing_mode="stretch_both")
        ]
        #selections += [MultiSelect(#title="Option:",
        #                           value=matching,
        #                           active=active)

    # Find the initially selected carrieres
    initial_carriers = [s.labels[i] for s in selections for i in s.active]

    # Slider to select width of bin
    binwidth_select = Slider(start=16,
                             end=160,
                             step=16,
                             value=80,
                             title='Bin number',
                             sizing_mode="stretch_both")

    # RangeSlider control to select start and end of plotted delays
    range_select = RangeSlider(start=-1,
                               end=999,
                               value=(-.2, 99),
                               step=.1,
                               title='Range (sec)',
                               sizing_mode="stretch_both")

    # Switch from lines to hists
    type_switch = RadioButtonGroup(labels=["Histogram", "Cumulated dist."],
                                   active=0,
                                   sizing_mode="stretch_both")

    # Find the initially selected carrieres
    plottype = type_switch.labels[type_switch.active]

    src = {}
    for output in ['Latencies', 'Delays', 'PSD']:
        src[output] = make_dataset(flights,
                                   initial_carriers,
                                   range_start=range_select.value[0],
                                   range_end=range_select.value[1],
                                   bin_width=binwidth_select.value,
                                   output=output,
                                   plottype=plottype)

    callback = partial(update,
                       output='Delays',
                       type_switch=type_switch,
                       flights=flights,
                       src=src,
                       selections=selections,
                       range_select=range_select,
                       binwidth_select=binwidth_select)

    callbacklat = partial(update,
                          output='Latencies',
                          type_switch=type_switch,
                          flights=flights,
                          src=src,
                          range_select=range_select,
                          selections=selections,
                          binwidth_select=binwidth_select)

    callbackpsd = partial(update,
                          output='PSD',
                          type_switch=type_switch,
                          flights=flights,
                          src=src,
                          range_select=range_select,
                          selections=selections,
                          binwidth_select=binwidth_select)

    callbackneedsread = partial(needsreadupdate, refresh_button=refresh_button)

    callbackread = partial(readupdate,
                           src=src,
                           selections=selections,
                           range_select=range_select,
                           type_switch=type_switch,
                           binwidth_select=binwidth_select,
                           pastdays_select=pastdays_select,
                           bufferdays_select=bufferdays_select,
                           refresh_button=refresh_button)

    [
        s.on_change('active', callback, callbacklat, callbackpsd)
        for s in selections
    ]
    type_switch.on_change('active', callback, callbacklat, callbackpsd)
    binwidth_select.on_change('value', callback, callbacklat, callbackpsd)
    range_select.on_change('value', callback, callbacklat, callbackpsd)
    pastdays_select.on_change('value', callbackneedsread)
    bufferdays_select.on_change('value', callbackneedsread)
    refresh_button.on_click(callbackread)

    p = {}
    for output in ['PSD', 'Latencies', 'Delays']:
        p[output] = make_plot(src[output], output=output)

    # Create a row layout
    graphs = [p[k] for k in p]
    controls = [
        type_switch, binwidth_select, range_select, refresh_button,
        pastdays_select, bufferdays_select, *selections[:maxnstation]
    ]
    graphslayout = column(children=graphs, sizing_mode="stretch_both")
    controlslayout = column(
        children=controls,
        sizing_mode='fixed',  #stretch_width',
        width=400,
    )
    layout = row(children=[graphslayout, controlslayout],
                 sizing_mode='stretch_both')

    # Make a tab with the layout
    return Panel(child=layout, title='Channels')
Beispiel #3
0
    with xr.open_dataset(db_path) as db:
        path = get_full_path(image_select.value)
        fitting_results = (['time'], fitting_results)
        cross_correlation_results = (['time',
                                      'distance'], cross_correlation_results)
        # TODO: Needs to be associated with an ROI
        db.loc[{
            'path': path
        }].assign(cross_correlation_results=cross_correlation_results)
        db.loc[{'path': path}].assign(fitting_results=fitting_results)
        os.remove(db_path)
        db.to_netcdf(db_path, mode='w')


run_roi_button = Button(label='Run ROI', button_type='primary')
run_roi_button.disabled = True
run_roi_button.on_click(run_flics_on_roi)

run_flics_button = Button(label='Run FLICS', button_type='primary')

message_paragraph = Paragraph(text='')
analysis_status_paragraph = Paragraph(text='')


def get_roi_params(index: int) -> list:
    values = roi_source.data
    return [
        values['x'][index],
        values['y'][index],
        values['width'][index],
        values['height'][index],
Beispiel #4
0
        if rssi < statistics['min']:
            statistics['min'] = rssi
        elif rssi > statistics['max']:
            statistics['max'] = rssi
        statistics['sum'] = statistics['sum'] + rssi
        label2.text = "min=%s, max=%s, avg=%.3f" % (
            statistics['min'], statistics['max'],
            statistics['sum'] / saving_num)

        if saving_num == conf.SAVED_DATA_NUMBER:
            saving = False
            label1.text = label1.text + " finished! " + str(
                len(statistics['data']))
            label2.text = label2.text + ", median=" + str(
                np.median(statistics['data']))
            write_raw_data("end saving")
            show_statistics()
            os.system('say "completed"')

        # update plot


def update_plot(client_data):
    doc.add_next_tick_callback(partial(update, client_data=client_data))


if len(conf.BEACONS) > 1:
    button.disabled = True
button.on_click(save_data)
curdoc().add_root(column([row([button])], width=150))
Beispiel #5
0
def TabModels():
    """available_modelscales = ['cells', 'microcircuit', 'network']
    """
    def get_select_menu(menu_type, menu_list):
        if menu_type == "modelscales":
            title = "Modeling Scale Options"
        elif menu_type == "models":
            title = "Choose a model name"
        elif menu_type == "responses":
            title = "Choose a response (file)"
        return Select(title=title, value=menu_list[0][0], options=menu_list)

    def get_menu_modelscales():
        #NOTE: available_modelscale & scale_and_models are global variables
        menu = [("None", "None")]
        for modelscale in available_modelscales:
            # tag the modelscale as first element in the value = modellist
            modellist = ' '.join([modelscale] + scale_and_models[modelscale])
            menu.append(
                (modellist, modelscale))  # tuple (string of models, scale)
        return menu

    def get_menu_models(modellist):
        #NOTE: models_with_filenames is a global variable
        menu = [("None", "Below are available models")]
        if modellist[1] == "No_Models":  #modellist[0]=modelname
            menu[0] = (modellist[1], modellist[1].replace("_", " ")
                       )  #tuple (scale, string of models)
        else:
            for modelname in modellist[1:]:
                # tag modelscale & modelname as 1st-two elements in the value
                itsvalue = ' '.join([modellist[0], modelname])
                menu.append(
                    (itsvalue, modelname))  # tuple (string of models, scale)
        return menu

    def update_models_list(attr, old, new):
        if new == "No_Models":
            menu_list = [''.join(list(new))]  # ["No Models"]
        else:
            menu_list = new.split()
        models_select.options = get_menu_models(menu_list)
        runmodel.disabled = True
        #print new
        #print modelscales_select.value
        #print menu_list
        #print menu_list[0]

    def update_global_model(attr, old, new):
        menu_list = new.split()
        modelscale = menu_list[0]  # update global modelscale
        modelname = menu_list[1]  # update glocal modelname
        #print modelscale, modelname
        sys.path.append(pwd)  # uncomment only when using executiveViz
        chosenmodel = ExecutiveControl.choose_model(modelscale=str(modelscale),
                                                    modelname=str(modelname))
        modeltitle.text = chosenmodel.name
        modeldescr.text = chosenmodel.description
        modelregions.text = "Potential stimulation sites: " + str(
            chosenmodel.regions)
        runmodel.disabled = False

    def update_stimulation_parameters_input_status(attr, old, new):
        if new == "no":
            stim_type_input.disabled = True
            stim_list_input.disabled = True
            stim_loc_input.disabled = True
        else:
            stim_type_input.disabled = False
            stim_list_input.disabled = False
            stim_loc_input.disabled = False

    def clicked():
        print "clicked"

    def simulate():
        print "running"
        #if modelscales_select.value == "No_Models":
        #print modelscales_select.value
        #else:
        #print modelscales_select.value
        print pwd
        sys.path.append(pwd)  # uncomment only when using executiveViz
        ec = ExecutiveControl()
        modelscale = models_select.value.split()[0]
        modelname = models_select.value.split()[1]
        chosenmodel = ec.choose_model(modelscale=modelscale,
                                      modelname=modelname)
        parameters = ast.literal_eval(runtime_input.value)
        print parameters
        print stimulation.value
        if stimulation.value == "yes":
            stimparameters = ast.literal_eval(stim_type_input.value)
            stimparameters.update(
                {"stimlist": ast.literal_eval(stim_list_input.value)})
            ec.launch_model(parameters=parameters,
                            onmodel=chosenmodel,
                            stimparameters=stimparameters,
                            stimloc=stim_loc_input.value)
            #with Profiler() as prof, ResourceProfiler() as rprof:
            #    ec.launch_model ( parameters=parameters, onmodel=chosenmodel,
            #                      stimparameters=stimparameters, stimloc=stim_loc_input.value )
        else:
            ec.launch_model(parameters=parameters, onmodel=chosenmodel)
            #with Profiler() as prof, ResourceProfiler() as rprof:
            #    ec.launch_model( parameters=parameters, onmodel=chosenmodel )
            #myplot = visualize([prof, rprof])
        ec.save_response()
        print "done running"
        #viz_source.data['diagnostic'][0] = prof
        #viz_source.data['diagnostic'][1] = rprof
        #viz_source.data['diagnostic'] = [prof, rprof]
        #viz_source.data['diagnostic'][0].results[0] = prof.results[0]
        #myplot.data['diagplots'][0] = visualize([prof, rprof])

        #return visualize([prof, rprof])

    #
    ### +++++++++++++++++++GENERATE DATA FOR THE OPTIONS MENU++++++++++++++++++
    # available_modelscales -- list
    # scale_and_models -- dictionary with list as key value
    # models_with_filenames -- dictionary with list as key value
    # responses_with_filepaths -- dictionary with string as key value
    # Generate Model Info
    #os.chdir("..") # line required for calling ~/managers/bokehtest.py
    #available_modelscales = fm.available_modelscales()
    #os.chdir(rootwd) # for running it from ~/managers
    available_modelscales = ExecutiveControl.list_modelscales()
    scale_and_models = {}
    for modelscale in available_modelscales:  # get list of models in each scale
        try:
            #modelslist = fm.modelscale_inventory(model_scale=modelscale)
            modelslist = ExecutiveControl.list_models(modelscale=modelscale)
        except:
            modelslist = ["No_Models"]
        scale_and_models.update({modelscale: modelslist})
    #os.chdir(pwd) # for running it from ~/managers
    #print scale_and_models
    ### ++++++++++++++++++++END GENERATE DATA FOR THE OPTIONS++++++++++++++++++
    #
    modelscale = None
    modelname = None
    chosenmodel = None
    #
    menu = get_menu_modelscales()
    modelscales_select = get_select_menu("modelscales", menu)
    #
    dummy_model_menu = [('None', "First select a model scale")]
    models_select = get_select_menu("models", dummy_model_menu)
    #
    runtime_input = TextInput(
        value="{'dt': 0.1, 'celsius': 30, 'tstop': 10, 'v_init': 65}",
        title="Runtime Parameters:")
    #print runtime_input.value
    #print type(runtime_input.value)
    #
    stimulation_menu = [("No", "no"), None, ("Yes", "yes")]
    stimulation = Dropdown(label="Stimulation Yes/No",
                           button_type="warning",
                           menu=stimulation_menu)
    stim_type_input = TextInput(
        value="{'type': ['current', 'IClamp']}",
        title="Stimulation Parameters (Stimulation Type):")
    stim_list_input = TextInput(
        value="[{'amp': 0.5, 'dur': 10.0, 'delay': 5.0}, "
        " {'amp': 1.0, 'dur': 20.0, 'delay': 15.0}]",
        title="Stimulation Parameters (Stimuli):")
    stim_loc_input = TextInput(value='soma', title="Stimulation location:")
    # disable stimulation by DEFAULT
    stim_type_input.disabled = True
    stim_list_input.disabled = True
    stim_loc_input.disabled = True
    #
    runmodel = Button(label="Run Simulation", button_type="success")
    runmodel.disabled = True
    #
    modeltitle = Div(text="""No Model has been selected yet.""",
                     width=290,
                     height=40)
    modeldescr = Paragraph(text="""There is no Model Description.""",
                           width=290,
                           height=200)
    modelregions = Div(
        text="""Main Locations within the model for stimulation""",
        width=290,
        height=50)
    # disable the model texts by DEFAULT
    modeltitle.disabled = True
    modeldescr.disabled = True
    modelregions.disabled = True

    def viz():
        return visualize(viz_source.data['diagnostic'])

    # Put controls in a single element
    viz_source = ColumnDataSource(
        data={'diagnostic': [Profiler(), ResourceProfiler()]})
    myplot = viz()
    #diagplot = visualize( viz_source.data['diagnostic'] )
    #myplot = ColumnDataSource(data={'diagplots': [diagplot]})
    #myplot = ColumnDataSource(data={'diagplots': [visualize([Profiler(), ResourceProfiler()])]})

    # INTERACTION
    modelscales_select.on_change("value", update_models_list)
    models_select.on_change("value", update_global_model)
    #responses_select.on_change("value", update_plot)
    stimulation.on_change("value", update_stimulation_parameters_input_status)
    runmodel.on_click(simulate)

    # Create a row layout
    mylayout = row(
        WidgetBox(modelscales_select, models_select, runtime_input,
                  stimulation, stim_type_input, stim_list_input,
                  stim_loc_input, runmodel),
        WidgetBox(modeltitle, modeldescr, modelregions),
        #row(viz_source.data['diagnostic'][0].visualize()))
        #row(myplot.data['diagplots'][0]))
        row(myplot))
    # Make a tab with the layout
    tab = Panel(child=mylayout, title='Choose Model')

    return tab
Beispiel #6
0
 def calculate_datapoints(self, graphId: int, button: Button,
                          metadata: Metadata):
     # Thread(target=lambda: UnlockedDocumentProxy(button.document).add_next_tick_callback()).start()
     self.threadCorelate(graphId, button, metadata)
     button.label = 'Find Similarities'
     button.disabled = False
Beispiel #7
0
 def uploadFile(self, file_source, button: Button):
     button.label = "Upload"
     button.disabled = False
Beispiel #8
0
 def disableButton(self, event, button: Button):
     button.label = "Uploading"
     button.disabled = True
     UnlockedDocumentProxy(button.document)\
         .add_next_tick_callback(partial(self.uploadFile, file_source=self.file_source, button=button))
Beispiel #9
0
    if not run_thread.pause:
        run_thread.pause = True
        print("Simulation paused")
        pause_button.label = "Resume simulation"
    else:
        run_thread.pause = False
        print("Simulation resumed")
        pause_button.label = "Pause simulation"


start_button = Button(label="Start simulation")
start_button.on_click(run_sim)

pause_button = Button(label="Pause simulation")
pause_button.on_click(pause_sim)
pause_button.disabled = True

stop_button = Button(label="Stop simulation")
stop_button.on_click(stop_sim)
stop_button.disabled = True

generations_input = TextInput(value="1000", title="Number of generations:")
population_input = TextInput(value="1000", title="Population size:")

doc.add_root(
    row(
        widgetbox(population_input,
                  generations_input,
                  start_button,
                  pause_button,
                  stop_button,
Beispiel #10
0
    y_axis_location="left",
    y_axis_label="Density",
    toolbar_location=None,
)
DensitySource = ColumnDataSource({
    "x": np.array(range(a, a + n + 1)),
    "normalized": np.zeros(n + 1, dtype="int")
})
DensityPanel.vbar(x="x", top="normalized", width=0.2, source=DensitySource)
DensityPanel.min_border, WalkPanel.min_border = 5, 5
DensityPanel.xaxis.visible = False
DensityPanel.yaxis.visible = True

start_button = Button(label="Go", button_type="success", width=100)
stop_button = Button(label="Stop", button_type="success", width=100)
stop_button.disabled = True

print("!!!!!!!!!")
a_field = Spinner(high=10.0,
                  low=1.0,
                  step=1.0,
                  value=a,
                  title="White Balls",
                  width=100)
b_field = Spinner(high=10.0,
                  low=1.0,
                  step=1.0,
                  value=b,
                  title="Black Balls",
                  width=100)