def __init__(self):

        subprocess.call("nrnivmodl")
        warnings.filterwarnings('ignore')

        self.RB = widgets.RadioButtons(options=[])
        self.RB1 = widgets.RadioButtons(description='Select mod file',
                                        options=['default', 'local'],
                                        style={'description_width': 'initial'})
        self.RB1.disabled = True
        self.RBHPC = widgets.RadioButtons(
            description='Run on:', options=['NSG', 'Service Account - NSG'])
        self.RBHPC.disabled = True
        self.RBM = widgets.RadioButtons(
            options=['all_traces', 'singletrace', 'demo'], description='run')
        self.RBM.disabled = True
        self.file_widget = widgets.FileUpload()
        self.KEY = 'Application_Fitting-DA5A3D2F8B9B4A5D964D4D2285A49C57'
        self.TOOL = 'NEURON77_TG'

        self.create_folder("GUI")
        os.chdir("GUI")
        self.prepare_transfer_folder()
        self.create_cell_selection()
        self.create_mod_radio()
        self.create_submission_panel()
    def _stack(self, network: str, node: str):
        """
        Display stack graphics. Manage user interaction with scn slider and prod, cons choices.

        :param network: network name
        :param node: node name
        :return:
        """
        def changes(scn, prod, cons):
            display(
                go.FigureWidget(
                    self.plotting.network(network).node(node).stack(
                        scn=scn, prod_kind=prod, cons_kind=cons)))

        scn = widgets.IntSlider(value=0,
                                min=0,
                                description='scn',
                                max=self.plotting.agg.nb_scn - 1,
                                continuous_update=False,
                                disabled=False)
        cons = widgets.RadioButtons(options=['asked', 'given'],
                                    value='asked',
                                    description='Consumption')
        prod = widgets.RadioButtons(options=['avail', 'used'],
                                    value='used',
                                    description='Production')
        hbox = widgets.HBox([scn, cons, prod])

        inter = interactive_output(changes, {
            'scn': scn,
            'prod': prod,
            'cons': cons
        })
        return widgets.VBox([hbox, inter])
Example #3
0
    def __init__(self, path=tumblrsPath):
        self.path = path
        self.AC = AccountCollection(path)
        self.A = self.AC[random.randint(0, len(self.AC))]

        self.accountSelector = widgets.Dropdown(
            options=self.AC.names,
            value=self.A.name,
            description='Account:',
        )

        self.tagsSelector = widgets.Dropdown(
            options=[f'{len(self.A)} None'] + self.A.sortedTags(count=True),
            value=f'{len(self.A)} None',
            description='tags:',
        )

        self.typesSelector = widgets.RadioButtons(
            options=self.A.postTypes,
            value=self.A.currentType,
            description='Post type:',
        )

        self.postSlider = widgets.IntSlider(min=0,
                                            max=len(self.A) - 1,
                                            value=0,
                                            description=str(len(self.A)) +
                                            ' posts')

        self.mainCaption = widgets.HTML(value=self.A(0))

        self.nextButton = widgets.Button(description="Next")

        self.previousButton = widgets.Button(description="Previous")

        self.tagSearchEnable = widgets.Button(description="Enable tag search")

        self.globalTagSelector = widgets.RadioButtons(
            options=['None'],
            value='None',
            description='Global tag filter:',
            disabled=True,
            display=False,
        )

        self.controls = HBox([
            VBox([
                HBox([self.accountSelector, self.tagsSelector]),
                HBox([self.postSlider, self.previousButton, self.nextButton])
            ]), self.typesSelector
        ])
Example #4
0
def plot_timeseries(datamart,
                    rows_df=None,
                    plot_fcst=False,
                    use_log_values=False):
    """Plot meter readings vs time interactively."""
    if use_log_values:
        fact_column = 'fact_log'
        leak_column = 'leak_log'
        target_column = 'target_log'
        fcst_column = 'fcst_log'
    else:
        fact_column = 'fact'
        leak_column = 'leak'
        target_column = 'target'
        fcst_column = 'fcst'
    if plot_fcst:
        cols = [target_column, fcst_column]
    else:
        cols = [leak_column, fact_column, target_column]
    df_to_plot = datamart.loc[:, ['meter', 'building_id', 'timestamp'] + cols]
    if rows_df is None:
        rows_df = datamart[['meter', 'building_id',
                            'site_id']].drop_duplicates()
    else:
        rows_df = rows_df.reset_index()[['meter', 'building_id', 'site_id']]
        df_to_plot = df_to_plot.merge(rows_df, on=['meter', 'building_id'])
    df_to_plot.set_index('timestamp', inplace=True)
    meter_widget = widgets.RadioButtons(
        options=[('Electricity (0)', 0), ('Chilled water (1)',
                                          1), ('Steam (2)',
                                               2), ('Hot water (3)', 3)])
    building_id_widget = widgets.Select()

    def update_buildings_list(*args):
        building_id_widget.options = [
            (f"{row['building_id']}, site {row['site_id']}",
             row['building_id']) for _, row in rows_df[
                 rows_df.meter == meter_widget.value].iterrows()
        ]

    meter_widget.observe(update_buildings_list, 'value')
    update_buildings_list()

    def plot_meter(meter, building_id):
        df_to_plot_selected = df_to_plot[(df_to_plot['meter'] == meter) & (
            df_to_plot['building_id'] == building_id)][cols]
        if df_to_plot_selected[cols[0]].isna().all():
            df_to_plot_selected.loc['01.01.2016 00:00', cols[0]] = 0
        plot = df_to_plot_selected.iplot(
            asFigure=True,
            kind='scatter',
            width=1,
            theme='ggplot',
            dimensions=(None, None),
            margin=(0, 0, 30, 30),  # l,r,b,t
        )
        plot['layout']['legend_orientation'] = 'h'
        display(plot)

    interact(plot_meter, meter=meter_widget, building_id=building_id_widget)
Example #5
0
    def preview(self):
        #figure, axis = plt.subplots()

        [height, width] = np.shape(self.images_array[0])
        text_y = 0.1 * height
        text_x = 0.6 * width

        def display_selected_image(index, text_x, text_y, pre_text, post_text,
                                   color):

            font = {
                'family': 'serif',
                'color': color,
                'weight': 'normal',
                'size': 16
            }

            fig = plt.figure(figsize=(15, 10))
            gs = gridspec.GridSpec(1, 1)
            ax = plt.subplot(gs[0, 0])
            im = ax.imshow(self.images_array[index], interpolation='nearest')
            plt.title("image index {}".format(index))
            plt.text(text_x,
                     text_y,
                     "{} {:.2f}{}".format(pre_text,
                                          self.list_time_offset[index],
                                          post_text),
                     fontdict=font)
            fig.colorbar(im)
            plt.show()

            return {
                'text_x': text_x,
                'text_y': text_y,
                'pre_text': pre_text,
                'post_text': post_text,
                'color': color
            }

        self.preview = interact(
            display_selected_image,
            index=widgets.IntSlider(min=0,
                                    max=len(self.list_files),
                                    continuous_update=False),
            text_x=widgets.IntSlider(min=0,
                                     max=width,
                                     value=text_x,
                                     description='Text x_offset',
                                     continuous_update=False),
            text_y=widgets.IntSlider(min=0,
                                     max=height,
                                     value=text_y,
                                     description='Text y_offset',
                                     continuous_upadte=False),
            pre_text=widgets.Text(value='Time Offset', description='Pre text'),
            post_text=widgets.Text(value='(s)', description='Post text'),
            color=widgets.RadioButtons(
                options=['red', 'blue', 'white', 'black', 'yellow'],
                value='red',
                description='Text Color'))
Example #6
0
    def create_search_params(self):
        start_date = widgets.DatePicker(description="Pick a start date",
                                        style={"description_width": "initial"})
        end_date = widgets.DatePicker(description="Pick an end date",
                                      style={"description_width": "initial"})
        sensors = widgets.RadioButtons(
            options=["pleiades", "spot"],
            value="pleiades",
            description="Sensor",  #
        )
        max_cloudcover = widgets.IntSlider(
            value=20,
            min=0,
            max=100,
            step=1,
            description="Max Cloud Cover (%)",
            style={"description_width": "initial"},
        )
        limit = widgets.IntSlider(
            value=10,
            min=1,
            max=500,
            step=1,
            description="Limit",
        )

        button = widgets.Button(description="Save search params!")

        def create_search_params(start_date, end_date, sensors, max_cloudcover,
                                 limit):
            assert self.ensure_variables(
                (self.catalog,
                 self.aoi)), "Please select an AOI and/or authenticate!"
            search_parameters = self.catalog.construct_parameters(
                geometry=self.aoi,
                start_date=start_date.value,
                end_date=end_date.value,
                sensors=[sensors.value],
                max_cloudcover=max_cloudcover.value,
                sortby="cloudCoverage",
                limit=limit.value,
            )
            search_parameters["query"]["deliveryTime"] = {"in": ["MINUTES"]}
            display(search_parameters)

            self.search_parameters = search_parameters
            self.sensors = sensors.value

        self.process_template(
            [start_date, end_date, sensors, max_cloudcover, limit],
            button,
            create_search_params,
            start_date=start_date,
            end_date=end_date,
            sensors=sensors,
            max_cloudcover=max_cloudcover,
            limit=limit,
        )
Example #7
0
def create_mcq(description, options, correct_answer, hint):
    if correct_answer not in options:
        options.append(correct_answer)

    correct_answer_index = options.index(correct_answer)

    radio_options = [(words, i) for i, words in enumerate(options)]
    alternativ = widgets.RadioButtons(
        options=radio_options,
        description='',
        layout={'width': 'max-content'},
        disabled=False,
        indent=False,
        align='center',
    )

    description_out = widgets.Output(layout=Layout(width='auto'))

    with description_out:
        print(description)

    feedback_out = widgets.Output()

    def check_selection(b):
        a = int(float(alternativ.value))
        if a == correct_answer_index:
            s = '\x1b[6;30;42m' + "correct" + '\x1b[0m' + "\n"
        else:
            s = '\x1b[5;30;41m' + "try again" + '\x1b[0m' + "\n"
        with feedback_out:
            feedback_out.clear_output()
            print(s)
        return

    check = widgets.Button(description="check")
    check.on_click(check_selection)

    #    hint_out = widgets.Output()

    #     def hint_selection(b):
    #         with hint_out:
    #             print(hint)

    #         with feedback_out:
    #             feedback_out.clear_output()
    #             print(hint)

    #hintbutton = widgets.Button(description="hint")
    #hintbutton.on_click(hint_selection)

    return widgets.VBox(
        [description_out, alternativ,
         widgets.HBox([check]), feedback_out],
        layout=Layout(display='flex',
                      flex_flow='column',
                      align_items='stretch',
                      width='auto'))
Example #8
0
def RadioButtons(question, options=['1', '2', '3', '4', '5']):
    start_time = time.time()
    widget = widgets.RadioButtons(options=options,
                                  description='Answer:',
                                  disabled=False)
    display(widget)

    def on_value_change(change):
        # Appends to the dictionary answer
        Answer_Dict[question].append(change["new"])

    widget.observe(on_value_change, names='value')

    button(question, start_time)
Example #9
0
 def with_or_without_roi(self):
     label1 = widgets.Label(
         "Do you want to select a region of interest (ROI) that will make sure that the "
         + "sample background matches the OB background")
     label2 = widgets.Label(
         "-> Make sure your selection do not overlap your sample!")
     box = widgets.HBox([
         widgets.Label("With or Without ROI?"),
         widgets.RadioButtons(options=['yes', 'no'],
                              value='yes',
                              layout=widgets.Layout(width='50%'))
     ])
     self.with_or_without_radio_button = box.children[1]
     vertical = widgets.VBox([label1, label2, box])
     display(vertical)
Example #10
0
 def _generate_widgets(self):
     data = [
         {
             'x': self.eng_strain,
             'y': self.eng_stress / 1e6,
             'name': self.meta.get('name') or '',
             'line': {
                 'color': DEFAULT_PLOTLY_COLORS[0],
             },
         },
     ]
     layout = {
         'title': 'Tensile test',
         'width': TensileTest.FIG_WIDTH,
         'height': TensileTest.FIG_HEIGHT,
         'margin': TensileTest.FIG_MARG,
         'xaxis': {
             'title':
             'Engineering strain, ε',
             'range': [
                 -TensileTest.FIG_PAD[0],
                 TensileTest.FIG_PAD[0] + self.max_strain
             ],
         },
         'yaxis': {
             'title':
             'Engineering stress, σ / MPa',
             'range': [
                 -TensileTest.FIG_PAD[1],
                 TensileTest.FIG_PAD[1] + self.max_stress / 1e6
             ],
         },
     }
     fig_wig = go.FigureWidget(data=data, layout=layout)
     widget_ss_type = widgets.RadioButtons(
         options=['Engineering', 'True'],
         description='Stress/strain:',
         value='Engineering',
     )
     widget_ss_type.observe(self._update_widgets_stress_strain_type,
                            names='value')
     widget_dict = {
         'figure': fig_wig,
         'stress_strain_type': widget_ss_type,
     }
     return widget_dict
 def _radioGraphStyle(self):
     label = widgets.Label(value="Axe Type",
                           layout=Layout(width="95%")).add_class('space')
     rad = widgets.RadioButtons(options=[
         'Single Axe X/Y', 'Double X Axe (twinx)', 'Double Y Axe (twiny)'
     ],
                                value='Single Axe X/Y',
                                disabled=False,
                                layout=Layout(
                                    width="98%",
                                    justify_content="space-between",
                                    align_self="center"))
     rad.observe(self.changed, names="value")
     self._y2Label.layout.visibility = 'hidden'
     self._x2Label.layout.visibility = 'hidden'
     return widgets.VBox([label, rad],
                         layout=Layout(width="99%",
                                       justify_content="space-between",
                                       align_items="flex-start"))
Example #12
0
    def how_to_combine(self):
        _file = open("__docs/combine_images/geometric_mean.png", 'rb')
        _geo_image = _file.read()
        geo_box = widgets.HBox([widgets.Label("Geometric Mean",
                                              layout=widgets.Layout(width='20%')),
                                widgets.Image(value=_geo_image,
                                              format='png')])
        _file = open("__docs/combine_images/algebric_mean.png", 'rb')
        _alge_image = _file.read()
        alge_box = widgets.HBox([widgets.Label("Arithmetic Mean",
                                              layout=widgets.Layout(width='20%')),
                                widgets.Image(value=_alge_image,
                                              format='png')])

        self.combine_method = widgets.RadioButtons(options=['add', 'arithmetic mean', 'geometric mean'],
                                                   value='arithmetic mean')

        vertical = widgets.VBox([alge_box, geo_box, self.combine_method])
        display(vertical)
Example #13
0
    def __init__(self,
                 on_interact=None,
                 output=None,
                 overwrite_previous_output=True,
                 feedback=False,
                 run=True,
                 action_kws={},
                 *args,
                 **kwargs):
        super().__init__(on_interact=on_interact,
                         output=output,
                         overwrite_previous_output=overwrite_previous_output,
                         feedback=feedback,
                         action_kws=action_kws)

        self.widget = widgets.RadioButtons(*args, **kwargs)

        if run:
            self.run()
Example #14
0
def plot_derivatives(datamart, target_col, derivatives_cols):
    """Plot derivatives interactively."""
    cols = [target_col] + derivatives_cols
    df_to_plot = datamart.loc[:,
                              ['meter', 'site_id', 'building_id', 'timestamp'] +
                              cols]
    df_to_plot.set_index('timestamp', inplace=True)
    rows_df = datamart[['meter', 'building_id', 'site_id']].drop_duplicates()
    meter_widget = widgets.RadioButtons(
        options=[('Electricity (0)', 0), ('Chilled water (1)',
                                          1), ('Steam (2)',
                                               2), ('Hot water (3)', 3)])
    building_id_widget = widgets.Select()

    def update_buildings_list(*args):
        building_id_widget.options = [
            (f"{row['building_id']}, site {row['site_id']}",
             row['building_id']) for _, row in rows_df[
                 rows_df.meter == meter_widget.value].iterrows()
        ]

    meter_widget.observe(update_buildings_list, 'value')
    update_buildings_list()

    def plot_meter(meter, building_id):
        df_to_plot_selected = df_to_plot[(df_to_plot['meter'] == meter) & (
            df_to_plot['building_id'] == building_id)][cols]
        if df_to_plot_selected[cols[0]].isna().all():
            df_to_plot_selected.loc['01.01.2016 00:00', cols[0]] = 0
        plot = df_to_plot_selected.iplot(
            asFigure=True,
            kind='scatter',
            width=1,
            theme='ggplot',
            dimensions=(None, None),
            margin=(0, 0, 30, 30),  # l,r,b,t
        )
        plot['layout']['legend_orientation'] = 'h'
        display(plot)

    interact(plot_meter, meter=meter_widget, building_id=building_id_widget)
    def gaussian(self, plot):
        """
        Plot gaussian graphics manage user interactions with time ans scn sliders

        :param plot: plotElement to use
        :return:
        """
        def change(choice, time_v, scn_v):
            if choice == 'time':
                scn.disabled = True
                time.disabled = False
                display(go.FigureWidget(plot.gaussian(t=time_v)))
            if choice == 'scn':
                scn.disabled = False
                time.disabled = True
                display(go.FigureWidget(plot.gaussian(scn=scn_v)))

        choice = widgets.RadioButtons(options=['time', 'scn'],
                                      value='time',
                                      description='')
        time = widgets.IntSlider(value=0,
                                 min=0,
                                 description='time',
                                 max=self.plotting.agg.horizon - 1,
                                 continuous_update=False,
                                 disabled=False)
        scn = widgets.IntSlider(value=0,
                                min=0,
                                description='scn',
                                max=self.plotting.agg.nb_scn - 1,
                                continuous_update=False,
                                disabled=True)
        hbox = widgets.HBox([choice, time, scn])

        inter = interactive_output(change, {
            'choice': choice,
            'time_v': time,
            'scn_v': scn
        })
        return widgets.VBox([hbox, inter])
Example #16
0
def seismic_app():
    v1 = widgets.FloatSlider(description="v1",
                             min=300,
                             max=2000,
                             step=1,
                             continuous_update=False,
                             value=400)
    v2 = widgets.FloatSlider(description="v2",
                             min=300,
                             max=5000,
                             step=1,
                             continuous_update=False,
                             value=1000)
    v3 = widgets.FloatSlider(description="v3",
                             min=300,
                             max=5000,
                             step=1,
                             continuous_update=False,
                             value=1500)
    z1 = widgets.FloatSlider(description="z1",
                             min=5,
                             max=50,
                             step=1,
                             continuous_update=False,
                             value=5)
    z2 = widgets.FloatSlider(description="z2",
                             min=5,
                             max=50,
                             step=1,
                             continuous_update=False,
                             value=10)
    x_loc = widgets.FloatSlider(
        description="offset",
        min=1,
        max=100,
        step=0.5,
        continuous_update=False,
        value=80,
    )
    t_star = widgets.FloatSlider(
        description="time",
        min=0.001,
        max=0.25,
        step=0.001,
        continuous_update=False,
        value=0.1,
        orientation="vertical",
        readout_format=".3f",
    )
    show = widgets.RadioButtons(
        description="plot",
        options=["direct", "reflection", "refraction1", "refraction2", "all"],
        value="all",
        disabled=False,
    )
    out = widgets.interactive_output(
        interact_refraction,
        {
            "v1": v1,
            "v2": v2,
            "v3": v3,
            "z1": z1,
            "z2": z2,
            "x_loc": x_loc,
            "t_star": t_star,
            "show": show,
        },
    )
    left = widgets.VBox(
        [t_star],
        layout=widgets.Layout(width="10%",
                              height="400px",
                              margin="300px 0px 0px 0px"),
    )
    right = widgets.VBox(
        [show, v1, v2, v3, z1, z2],
        layout=widgets.Layout(width="50%",
                              height="400px",
                              margin="20px 0px 0px 0px"),
    )
    image = widgets.VBox(
        [out, x_loc],
        layout=widgets.Layout(width="70%",
                              height="600px",
                              margin="0px 0px 0px 0px"),
    )
    return widgets.HBox([left, image, right])
    probs = {}
    for lbl in counts.keys():
        probs[lbl] = str(int(counts[lbl] / total * 100)) + "%"
    return probs

if __name__ == '__main__':
    my_tree = build_tree(training_data1)
    print_tree(my_tree)
    #following is a 2-D array
    #loan id
    text0=widgets.Text(description="Loan ID:",placeholder='Enter Loan ID')
    display(text0)
    #gender
    w0=widgets.RadioButtons(
        options=['Male', 'Female'],
        description='\nGender:\n',
        layout=Layout(width='100%', height='100%'),
        disabled=False
    )
    def on_change(change):
        if change['type'] == 'change' and change['name'] == 'value':
            print(change['new'])
    w0.observe(on_change)
    display(w0)

#marital status
    w1=widgets.RadioButtons(
        options=['Yes', 'No'],
        description='\nMarried?\n',
        disabled=False
    )
    def on_change(change):
Example #18
0
    def test_workflow(self):
        selected_blocks = widgets.RadioButtons(
            options=[
                ["oneatlas-pleiades-fullscene", "pansharpen"],
                ["oneatlas-pleiades-display", "data-conversion-dimap"],
                ["oneatlas-pleiades-aoiclipped"],
                ["oneatlas-spot-fullscene", "pansharpen"],
                ["oneatlas-spot-display", "data-conversion-dimap"],
                ["oneatlas-spot-aoiclipped"],
            ],
            value=["oneatlas-pleiades-fullscene", "pansharpen"],
            layout={"width": "max-content"},
            description="Blocks to use",
        )
        button = widgets.Button(description="Run test queries!")

        def test_workflow(selected_blocks):
            assert self.ensure_variables(
                (self.full_coverage,
                 self.catalog)), "Please run steps before (optimize coverage)!"

            self.project = up42.initialize_project()
            self.project.update_project_settings(max_concurrent_jobs=10)
            self.workflow = self.project.create_workflow("mosaicking",
                                                         use_existing=True)

            blocks = up42.get_blocks(basic=True)
            self.workflow.add_workflow_tasks(
                [blocks[selected] for selected in selected_blocks.value])

            # Test workflow & availability of sections
            parameters = []
            for _, row in self.full_coverage.iterrows():

                test_parameters = self.workflow.construct_parameters(
                    geometry=row.geometry,
                    geometry_operation="intersects",
                    scene_ids=[row["sceneId"]],
                )
                parameters.append(test_parameters)

            test_jobs = self.workflow.test_jobs_parallel(
                parameters, name="mosaicking_tests")

            test_jobs_df = {}
            for i, test_job in enumerate(test_jobs):
                estimation = self.workflow.estimate_job(parameters[i])
                test_df = test_job.get_results_json(as_dataframe=True)
                test_df["minEstimatedCredits"] = sum([
                    block["blockConsumption"]["credit"]["min"] +
                    block["machineConsumption"]["credit"]["min"]
                    for block in estimation.values()
                ])
                test_df["maxEstimatedCredits"] = sum([
                    block["blockConsumption"]["credit"]["max"] +
                    block["machineConsumption"]["credit"]["max"]
                    for block in estimation.values()
                ])
                display(test_df)

                test_jobs_df[test_job.job_id] = test_df

            test_jobs_df = pd.concat(test_jobs_df.values(),
                                     keys=test_jobs_df.keys())
            display(test_jobs)
            print("=======================================================")
            print("Generating this mosaic is estimated to cost:")
            print(
                f"{test_jobs_df['minEstimatedCredits'].sum()} - {test_jobs_df['maxEstimatedCredits'].sum()} "
                "UP42 credits")
            print("=======================================================")

            self.selected_blocks = selected_blocks.value

            print("finished")

        self.process_template([selected_blocks],
                              button,
                              test_workflow,
                              selected_blocks=selected_blocks)
Example #19
0
 def which_math(self):
     self.math_method = widgets.RadioButtons(options=['substract', 'add'],
                                             value='substract')
     display(self.math_method)
    def _calculate_sample_size_interactive(metric):
        style = {'description_width': 'initial'}
        desc_layout = widgets.Layout(width='50%')
        if metric == 'continuous':
            mde_widget = widgets.FloatText(
                value=0.01,
                description='',
            )

            mde_desc = widgets.HTML("""
                <small>
                    This is the smallest absolute difference in averages that
                    any of your comparisons can detect at the given statistical
                    rigour.
                </small>
            """,
                                    layout=desc_layout)

            baseline_title = widgets.HTML("<strong>Baseline variance</strong>")
            baseline_widget = widgets.BoundedFloatText(
                value=1.0,
                min=0.00001,
                max=1000000000.0,
                description='',
            )
            baseline_desc = widgets.HTML("""
                    <small>
                        This is the expected variance of the metric among
                        users in your control group.
                    </small>
                """,
                                         layout=desc_layout)

        elif metric == 'binomial':
            mde_widget = widgets.FloatLogSlider(value=0.003,
                                                base=10,
                                                min=-4,
                                                max=np.log10(0.5),
                                                step=0.001,
                                                description='',
                                                readout_format='.4f')

            mde_desc = widgets.HTML("""
                <small>
                    This is the smallest absolute difference (percentage
                    point / 100) that any of your comparisons can detect
                    at the given statistical rigour.
                </small>
            """,
                                    layout=desc_layout)

            baseline_title = widgets.HTML("<strong>Baseline "
                                          "proportion</strong>")
            baseline_widget = widgets.FloatSlider(value=0.5,
                                                  min=0.00001,
                                                  max=0.99999,
                                                  step=0.01,
                                                  description='')
            baseline_desc = widgets.HTML("""
                    <small>
                        This is the expected value of the metric among
                        users in your control group.
                    </small>
                """,
                                         layout=desc_layout)

        else:
            raise ValueError('metric must be `continuous` or `binomial`')

        alpha_widget = widgets.FloatSlider(value=0.05,
                                           min=0.001,
                                           max=0.10,
                                           step=0.001,
                                           description=r'\(\alpha\)',
                                           readout_format='.3f')

        power_widget = widgets.FloatSlider(value=0.85,
                                           min=0.8,
                                           max=0.99,
                                           step=0.01,
                                           description=r'Power, \( 1-\beta\)')

        treatments_widget = widgets.IntSlider(
            value=2,
            min=2,
            max=20,
            step=1,
            description='Groups (including control)',
            style=style)

        comparisons_widget = widgets.RadioButtons(
            options=['Control vs. All', 'All vs. All'],
            value='Control vs. All',
            description='Groups to compare',
            style=style)

        control_group_widget = widgets.FloatLogSlider(
            value=1,
            step=0.1,
            base=10,
            min=0,
            max=4,
            description='Control group advantage',
            readout=False,
            style=style,
        )
        control_group_description = widgets.HTML("""
            <small>
                Sometime we want the control group to be bigger than what is
                strictly optimal. This can be either because we can collect
                samples quickly enough anyway or because we believe the
                treatment variants are riskier. Boosting the size of the
                control group comes at the cost of an increased total
                required sample.
            </small>
        """,
                                                 layout=desc_layout)

        bonferroni_widget = widgets.Checkbox(
            value=False, description='Apply Bonferroni correction')

        risk_reset_btn = widgets.Button(description=' ',
                                        disabled=False,
                                        button_style='',
                                        tooltip='Reset variant risk',
                                        icon='repeat',
                                        layout=widgets.Layout(width="40px"))

        def reset_widget(b):
            control_group_widget.value = 1

        risk_reset_btn.on_click(reset_widget)

        ui = widgets.VBox([
            widgets.HTML('<h4>Target metric</h4>'),
            widgets.VBox(children=[
                widgets.HTML("<strong>Minimal Detectable Effect "
                             "size</strong>"), mde_widget, mde_desc
            ], ),
            widgets.VBox(
                children=[baseline_title, baseline_widget, baseline_desc], ),
            widgets.HTML('<h4>Statistical rigour</h4>'), alpha_widget,
            power_widget, bonferroni_widget,
            widgets.HTML('<h4>Treatment groups</h4>'), treatments_widget,
            comparisons_widget,
            widgets.VBox(children=[
                widgets.HBox([control_group_widget, risk_reset_btn]),
                control_group_description
            ])
        ])

        def show_samplesize(mde, baseline, alpha, power, treatments,
                            comparisons_readable, bonferroni_correction,
                            relative_risk):
            if comparisons_readable == 'Control vs. All':
                comparisons = 'control_vs_all'
            else:
                comparisons = 'all_vs_all'

            treatment_costs = np.ones(treatments)
            treatment_costs[1:] = relative_risk
            treatment_allocations = None

            if metric == 'continuous':
                n_optimal, _, _ = SampleSize.continuous(
                    mde, baseline, alpha, power, treatments, comparisons, None,
                    treatment_allocations, bonferroni_correction)
                n_tot, n_cell, prop_cell = SampleSize.continuous(
                    mde, baseline, alpha, power, treatments, comparisons,
                    treatment_costs, treatment_allocations,
                    bonferroni_correction)
                code_html = widgets.HTML(
                    "<pre><code>"
                    f"SampleSize.continuous(average_absolute_mde={ mde },\n"
                    f"                      baseline_variance={ baseline },\n"
                    f"                      alpha={ alpha },\n"
                    f"                      power={ power },\n"
                    f"                      treatments={ treatments },\n"
                    f"                      comparisons="
                    f"'{ comparisons }',\n"
                    f"                      treatment_costs="
                    f"{ list(treatment_costs) },\n"
                    f"                      treatment_allocations=None,\n"
                    f"                      bonferroni_correction="
                    f"{ bonferroni_correction })"
                    "<code></pre>")
            else:
                n_tot, n_cell, prop_cell = SampleSize.binomial(
                    mde, baseline, alpha, power, treatments, comparisons,
                    treatment_costs, treatment_allocations,
                    bonferroni_correction)
                n_optimal, _, _ = SampleSize.binomial(mde, baseline, alpha,
                                                      power, treatments,
                                                      comparisons, None,
                                                      treatment_allocations,
                                                      bonferroni_correction)
                code_html = widgets.HTML(
                    "<pre><code>"
                    f"SampleSize.binomial(absolute_percentage_mde={ mde },\n"
                    f"                    baseline_proportion="
                    f"{ baseline },\n"
                    f"                    alpha={ alpha },\n"
                    f"                    power={ power },\n"
                    f"                    treatments={ treatments },\n"
                    f"                    comparisons="
                    f"'{ comparisons }',\n"
                    f"                    treatment_costs="
                    f"{ list(treatment_costs) },\n"
                    f"                    treatment_allocations=None,\n"
                    f"                    bonferroni_correction="
                    f"{ bonferroni_correction })"
                    "<code></pre>")

            def compare_against_optimal(current, optimal):
                if current == optimal:
                    return ''
                else:
                    return (f"<br><small><em>{current/optimal:.1f}x "
                            f"optimal group allocation of {optimal:,}."
                            f"</em></small>")

            display(
                widgets.HTML(f"<h4>Required sample size</h4>"
                             f"<strong>Total:</strong><br>{n_tot:,}"
                             f"{compare_against_optimal(n_tot, n_optimal)}"))
            cell_str = '<strong>Sample size in each cell</strong>'
            for i in range(len(n_cell)):
                if i == 0:
                    treatment = 'Control'
                else:
                    treatment = 'Variant ' + str(i)

                cell_str += (f"<br><em>{treatment}:</em> "
                             f"{n_cell[i]:,} ({prop_cell[i]*100:.1f}%)")

            display(widgets.HTML(cell_str))
            display(code_html)

        out = widgets.interactive_output(
            show_samplesize, {
                'mde': mde_widget,
                'baseline': baseline_widget,
                'alpha': alpha_widget,
                'power': power_widget,
                'treatments': treatments_widget,
                'comparisons_readable': comparisons_widget,
                'bonferroni_correction': bonferroni_widget,
                'relative_risk': control_group_widget
            })

        display(ui, out)
Example #21
0
    def _generate_widgets_macro_stress_strain(self):

        data = [{
            'x': self.exp_tensile_test.eng_strain,
            'y': self.exp_tensile_test.eng_stress,
            'name': 'Experimental',
            'line': {
                'color': DEFAULT_PLOTLY_COLORS[0],
            },
        }, {
            'x': [self.exp_tensile_test.plastic_range[0]] * 2 + [None] +
            [self.exp_tensile_test.plastic_range[1]] * 2,
            'y': [
                -HardeningLawFitter.FIG_PAD[1],
                HardeningLawFitter.FIG_PAD[1] +
                self.exp_tensile_test.max_stress,
                None,
                -HardeningLawFitter.FIG_PAD[1],
                HardeningLawFitter.FIG_PAD[1] +
                self.exp_tensile_test.max_stress,
            ],
            'mode':
            'lines',
            'line': {
                'color': '#888',
                'width': 2,
            },
            'showlegend':
            False,
        }]
        layout = {
            'title': 'Experimental Data',
            'width': HardeningLawFitter.FIG_WIDTH,
            'height': HardeningLawFitter.FIG_HEIGHT,
            'margin': HardeningLawFitter.FIG_MARG,
            'xaxis': {
                'title':
                'Engineering strain, ε',
                'range': [
                    -HardeningLawFitter.FIG_PAD[0],
                    HardeningLawFitter.FIG_PAD[0] +
                    self.exp_tensile_test.max_strain
                ],
            },
            'yaxis': {
                'title':
                'Engineering stress, σ / MPa',
                'range': [
                    -HardeningLawFitter.FIG_PAD[1],
                    HardeningLawFitter.FIG_PAD[1] +
                    self.exp_tensile_test.max_stress
                ],
            },
        }

        widget_ss_type = widgets.RadioButtons(
            options=['Engineering', 'True'],
            description='Stress/strain:',
            value='Engineering',
        )
        plastic_range_widget = widgets.FloatRangeSlider(
            value=self.exp_tensile_test.plastic_range,
            step=0.005,
            min=self.exp_tensile_test.min_true_strain,
            max=self.exp_tensile_test.max_true_strain,
            description='Plastic range:',
            disabled=False,
            continuous_update=False,
            orientation='horizontal',
            readout_format='.4f',
            layout=widgets.Layout(width='90%'),
        )
        widget_ss_type.observe(self._update_widgets_stress_strain_type,
                               names='value')
        plastic_range_widget.observe(self._update_widgets_plastic_range,
                                     names='value')
        out = {
            'fig': go.FigureWidget(data=data, layout=layout),
            'fig_trace_idx': {
                'macro_stress_strain': [0],
                'plastic_range_boundaries': [1],
            },
            'controls': {
                'stress_strain_type': widget_ss_type,
                'plastic_range': plastic_range_widget,
            },
        }

        return out
Example #22
0
    def build_layout(self, dset_id: str):
        """
        :param dset_id:
        :return:
        """
        all_fields = list(self.get_data(dset_id=dset_id).keys())

        try:
            field_reference = self.skd[dset_id].attrs('target')
        except:
            field_reference = all_fields[0]

        fields_comparison = [all_fields[1]]

        # chart type widget
        self.register_widget(
            chart_type=widgets.RadioButtons(
                options=['individual', 'grouped'],
                value='individual',
                description='Chart Type:'
            )
        )

        # bins widget
        self.register_widget(
            bins=IntSlider(
                description='Bins:',
                min=2, max=10, value=2,
                continuous_update=False
            )
        )

        # fields comparison widget
        self.register_widget(
            xs=widgets.SelectMultiple(
                description='Xs:',
                options=[f for f in all_fields if not f == field_reference],
                value=fields_comparison
            )
        )

        # field reference widget
        self.register_widget(
            y=widgets.Dropdown(
                description='Y:',
                options=all_fields,
                value=field_reference
            )
        )
        # used to internal flow control
        y_changed = [False]

        self.register_widget(
            box_filter_panel=widgets.VBox([
                self._('y'), self._('xs'), self._('bins')
            ])
        )

        # layout widgets
        self.register_widget(
            table=widgets.HTML(),
            chart=widgets.HTML()
        )

        self.register_widget(vbox_chart=widgets.VBox([
            self._('chart_type'), self._('chart')
        ]))

        self.register_widget(
            tab=widgets.Tab(
                children=[
                    self._('box_filter_panel'),
                    self._('table'),
                    self._('vbox_chart')
                ]
            )
        )

        self.register_widget(dashboard=widgets.HBox([self._('tab')]))

        # observe hooks
        def w_y_change(change: dict):
            """
            When y field was changed xs field should be updated and data table
            and chart should be displayed/updated.

            :param change:
            :return:
            """
            # remove reference field from the comparison field list
            _xs = [
                f for f in all_fields
                if not f == change['new']
            ]

            y_changed[0] = True  # flow control variable
            _xs_value = list(self._('xs').value)

            if change['new'] in self._('xs').value:
                _xs_value.pop(_xs_value.index(change['new']))
                if not _xs_value:
                    _xs_value = [_xs[0]]

            self._('xs').options = _xs
            self._('xs').value = _xs_value

            self._display_result(y=change['new'], dset_id=dset_id)

            y_changed[0] = False  # flow control variable

        # widgets registration

        # change tab settings
        self._('tab').set_title(0, 'Filter')
        self._('tab').set_title(1, 'Data')
        self._('tab').set_title(2, 'Chart')

        # data panel
        self._('table').value = '...'

        # chart panel
        self._('chart').value = '...'

        # create observe callbacks
        self._('bins').observe(
            lambda change: (
                self._display_result(bins=change['new'], dset_id=dset_id)
            ), 'value'
        )
        self._('y').observe(w_y_change, 'value')
        # execute display result if 'y' was not changing.
        self._('xs').observe(
            lambda change: (
                self._display_result(xs=change['new'], dset_id=dset_id)
                if not y_changed[0] else None
            ), 'value'
        )
        self._('chart_type').observe(
            lambda change: (
                self._display_result(chart_type=change['new'], dset_id=dset_id)
            ), 'value'
        )
Example #23
0
    def interact_plot_model_prism(self):
        plot = widgets.RadioButtons(
            options=["field", "model"],
            value="field",
            description="plot",
            disabled=False,
        )
        component = widgets.RadioButtons(
            options=["Bt", "Bx", "By", "Bz"],
            value="Bt",
            description="field",
            disabled=False,
        )

        inclination = widgets.FloatSlider(description="I",
                                          continuous_update=False,
                                          min=-90,
                                          max=90,
                                          step=1,
                                          value=90)
        declination = widgets.FloatSlider(description="D",
                                          continuous_update=False,
                                          min=-180,
                                          max=180,
                                          step=1,
                                          value=0)
        length = widgets.FloatSlider(
            description="length",
            continuous_update=False,
            min=2,
            max=200,
            step=1,
            value=72,
        )
        dx = widgets.FloatSlider(
            description="data spacing",
            continuous_update=False,
            min=0.1,
            max=15,
            step=0.1,
            value=2,
        )
        kappa = widgets.FloatText(description="$\kappa$", value=0.1)
        B0 = widgets.FloatText(description="B$_0$", value=56000)
        depth = widgets.FloatSlider(
            description="depth",
            continuous_update=False,
            min=0,
            max=50,
            step=1,
            value=10,
        )
        profile = widgets.RadioButtons(
            options=["East", "North", "None"],
            value="East",
            description="profile",
            disabled=False,
        )
        fixed_scale = widgets.Checkbox(value=False,
                                       description="fixed scale",
                                       disabled=False)

        show_halfwidth = widgets.Checkbox(value=False,
                                          description="half width",
                                          disabled=False)
        prism_dx = widgets.FloatText(description="$\\triangle x$", value=1)
        prism_dy = widgets.FloatText(description="$\\triangle y$", value=1)
        prism_dz = widgets.FloatText(description="$\\triangle z$", value=1)
        prism_inclination = widgets.FloatSlider(
            description="I$_{prism}$",
            continuous_update=False,
            min=-90,
            max=90,
            step=1,
            value=0,
        )
        prism_declination = widgets.FloatSlider(
            description="D$_{prism}$",
            continuous_update=False,
            min=0,
            max=180,
            step=1,
            value=0,
        )

        out = widgets.interactive_output(
            self.magnetic_prism_applet,
            {
                "plot": plot,
                "component": component,
                "inclination": inclination,
                "declination": declination,
                "length": length,
                "dx": dx,
                "kappa": kappa,
                "B0": B0,
                "depth": depth,
                "profile": profile,
                "fixed_scale": fixed_scale,
                "show_halfwidth": show_halfwidth,
                "prism_dx": prism_dx,
                "prism_dy": prism_dy,
                "prism_dz": prism_dz,
                "prism_inclination": prism_inclination,
                "prism_declination": prism_declination,
            },
        )
        left = widgets.VBox(
            [plot, component, profile],
            layout=Layout(width="20%",
                          height="400px",
                          margin="60px 0px 0px 0px"),
        )
        right = widgets.VBox(
            [
                inclination,
                declination,
                length,
                dx,
                B0,
                kappa,
                depth,
                prism_dx,
                prism_dy,
                prism_dz,
                prism_inclination,
                prism_declination,
                fixed_scale,
                show_halfwidth,
            ],
            layout=Layout(width="50%",
                          height="400px",
                          margin="20px 0px 0px 0px"),
        )
        widgets.VBox([out],
                     layout=Layout(width="70%",
                                   height="400px",
                                   margin="0px 0px 0px 0px"))
        return widgets.HBox([left, out, right])
def hyperExplore(df,initial_axis,initial_surface_axis,legend_group,hover_items):

    data = df.assign(x=df[initial_axis[0]],y=df[initial_axis[1]])\
       .sort_values(legend_group)\
       .reset_index(drop=True)

    group_ops = data[legend_group].sort_values().unique()
    num_groups = len(group_ops)
    axis_ops = data.columns.values
    lenSlide = '500px'

    fig = px.scatter(data, x="x", y="y", color=legend_group,hover_data=hover_items,
                 log_x=True, title='Hyperparameter Exploration',height=600)

    fig.update_layout(
        legend=dict(
        orientation="v",
        yanchor="top",
        y=1.02,
        xanchor="left",
        x=1),
        xaxis=dict(title=initial_axis[0],
                   titlefont=dict(size=14)),
        yaxis=dict(title=initial_axis[1],
                    titlefont=dict(size=14))
        )

    fig.update_traces(marker=dict(size=20,line=dict(width=1.5,
                                            color='DarkSlateGrey')),
                      selector=dict(mode='markers'))

    fig.update_layout(plot_bgcolor='rgba(0,0,0,0)')
    fig.update_xaxes(showgrid=True, gridwidth=.1, gridcolor='lightgrey')
    fig.update_yaxes(showgrid=True, gridwidth=.1, gridcolor='lightgrey')

    param_drop1 = Dropdown(
        value='None',
        options=np.insert(axis_ops,0,'None'),
        description='Parameter 1:'
    )

    slider1 = widgets.SelectionSlider(
        options=['Select Parameter'],
        value='Select Parameter',
        layout=Layout(width=lenSlide),
        continuous_update=True
    )

    size_drop = Dropdown(
        value='None',
        options=np.insert(axis_ops,0,'None'),
        description='Size:'
    )

    size_slider = widgets.IntSlider(
        value=20,
        min=10,
        max=50,
        step=1,
        disabled=False,
        continuous_update=True,
        orientation='horizontal',
        layout=Layout(width=lenSlide),
        readout=True,
        readout_format='d'
    )

    slider_group1 = widgets.HBox([param_drop1, slider1])
    slider_group2 = widgets.HBox([size_drop, size_slider])

    xaxis = Dropdown(
        value=initial_axis[0],
        options=axis_ops,
        description='X-axis:'
    )

    yaxis = Dropdown(
        value=initial_axis[1],
        options=axis_ops,
        description='Y-axis:'
    )

    container = widgets.VBox(children=[slider_group1,slider_group2,xaxis,yaxis])

    g = go.FigureWidget(data=fig,
                        layout=go.Layout(
                            title=dict(
                                text='Hyperparameter Exploration'
                            )
                        ))

    x_surface = Dropdown(
        value=initial_surface_axis[0],
        options=axis_ops,
        description='X-axis'
    )
    y_surface = Dropdown(
        value=initial_surface_axis[1],
        options=axis_ops,
        description='Y-axis'
    )
    z_surface = Dropdown(
        value=initial_surface_axis[2],
        options=axis_ops,
        description='Z-axis'
    )

    surface_buttons = widgets.RadioButtons(
        options=group_ops,
        value=group_ops[0], # Defaults to 'pineapple'
        description=legend_group+":",
        disabled=False
    )


    z_vals = data.query('{} == "{}"'\
            .format(legend_group,surface_buttons.value))[[x_surface.value,y_surface.value,z_surface.value]]\
            .groupby([x_surface.value,y_surface.value])\
            .median().reset_index()\
            .pivot(index=x_surface.value,columns=y_surface.value,values=z_surface.value)

    fig2 = go.Figure(data=[go.Surface(z=z_vals)])
    fig2.update_layout(title='Hyperparameter Surface: '+surface_buttons.value, autosize=False,
                      margin=dict(l=65, r=50, b=65, t=90),
                      height=600)

    layout = go.Layout(
                    scene = dict(
                        xaxis = dict(
                            title = initial_surface_axis[0]),
                        yaxis = dict(
                            title = initial_surface_axis[1]),
                        zaxis = dict(
                            title = initial_surface_axis[2]),
                                ))
    fig2.update_layout(layout)

    container2 = widgets.HBox(children=[surface_buttons,x_surface,y_surface,z_surface])


    g2 = go.FigureWidget(data=fig2,
                        layout=go.Layout(
                            title=dict(
                                text='Hyperparameter Surface: '+surface_buttons.value
                            )
                        ))


    def axis_response(change):
        with g.batch_update():
            #Gets the widget that was altered
            modified = change.owner.description

            if modified == xaxis.description:
                for i in range(num_groups):
                    #Get data for legend group
                    filtered_data = data.query("{} == '{}'".format(legend_group,g.data[i].name))

                    #Query filtered data for slider specs
                    query_filt(filtered_data,i)

                    g.layout.xaxis.title = xaxis.value

            elif modified == yaxis.description:
                for i in range(num_groups):
                    #Get data for legend group
                    filtered_data = data.query("{} == '{}'".format(legend_group,g.data[i].name))

                    #Query filtered data for slider specs
                    query_filt(filtered_data,i)

                    g.layout.yaxis.title = yaxis.value

    def slider1_response(change):
        with g.batch_update():
            for i in range(num_groups):
                #Get data for legend group
                filtered_data = data.query("{} == '{}'".format(legend_group,g.data[i].name))#make key var that iters

                #Query filtered data for slider specs
                query_filt(filtered_data,i)

    def query_filt(filtered_data,i):
        #Query filtered data for slider specs
    #     filt_bool = (filtered_data.learning_rate == lr_slider.value)#make learning_rate var
        if param_drop1.value == 'None':
            #Assign data to graph
            g.data[i].x = filtered_data[xaxis.value]
            g.data[i].y = filtered_data[yaxis.value]
        else:
            filt_bool = (filtered_data[param_drop1.value] == slider1.value)#make learning_rate var
            #Filter out data
            xfilt = [v if b else None for v,b in zip(filtered_data[xaxis.value],filt_bool)]
            yfilt = [v if b else None for v,b in zip(filtered_data[yaxis.value],filt_bool)]
            #Assign data to graph
            g.data[i].x = xfilt
            g.data[i].y = yfilt

    def create_slider_options(drop_value):
        if drop_value == 'None':
            slide_ops = ['Select Parameter']
        else:
            slide_ops = data[drop_value].sort_values().unique()
        return slide_ops

    def param_update(change):
        #everytime we change param, update the slider options and current value
        slider1.options = create_slider_options(param_drop1.value)
        slider1.value = slider1.options[0]

    def size_response(change):
         with g.batch_update():
                if size_drop.value == 'None':
                    g.update_traces(marker=dict(size=size_slider.value))
                else:
                    sizeFig = px.scatter(data, x="x", y="y", color="model",
                                         size=size_drop.value, size_max=size_slider.value)
                    traceSizes = [x.marker.size for x in sizeFig.data]

                    for i in range(num_groups):
                        g.data[i].marker.size = traceSizes[i]
                        g.data[i].marker.sizeref = sizeFig.data[0].marker.sizeref
                        g.data[i].marker.sizemode = sizeFig.data[0].marker.sizemode
                        g.data[i].marker.sizemin = 4

    def surface_response(change):
        with g.batch_update():
            z_vals = data.query('{} == "{}"'\
            .format(legend_group,surface_buttons.value))[[x_surface.value,y_surface.value,z_surface.value]]\
            .groupby([x_surface.value,y_surface.value])\
            .median().reset_index()\
            .pivot(index=x_surface.value,columns=y_surface.value,values=z_surface.value)

            g2.data[0].z = z_vals.values

            layout = go.Layout(
                        scene = dict(
                            xaxis = dict(
                                title = x_surface.value),
                            yaxis = dict(
                                title = y_surface.value),
                            zaxis = dict(
                                title = z_surface.value),
                                    ),
                         title=dict(
                                text='Hyperparameter Surface: '+surface_buttons.value
                            ))

            g2.update_layout(layout)

    surface_buttons.observe(surface_response,"value")
    x_surface.observe(surface_response,"value")
    y_surface.observe(surface_response,"value")
    z_surface.observe(surface_response,"value")

    size_drop.observe(size_response,"value")
    size_slider.observe(size_response, "value")
    slider1.observe(slider1_response, names="value")
    xaxis.observe(axis_response, names="value")
    yaxis.observe(axis_response, names="value")
    param_drop1.observe(param_update, names="value")

    scatterTab = widgets.VBox([container,g])
    surfaceTab = widgets.VBox([container2,g2])
    tab = widgets.Tab([scatterTab,surfaceTab])
    tab.set_title(0,'Scatter')
    tab.set_title(1,'Surface')

    return tab
Example #25
0
                               max=90.0,
                               value=0.0,
                               step=0.01,
                               continuous_update=continuous_update,
                               orientation='horizontal',
                               description='Pipe Inclination [deg]',
                               layout=layout)

# Pipe Roughness
k_s_button = widgets.FloatSlider(min=0.0,
                                 max=1e-3,
                                 value=1e-5,
                                 step=1e-6,
                                 continuous_update=continuous_update,
                                 description='Pipe Roughness [m]',
                                 readout_format='.2e',
                                 layout=layout)

interface_button = widgets.Dropdown(options={
    'Smooth': 1,
    'Wavy': 2
},
                                    value=1,
                                    description='Interface:',
                                    layout=layout)

plot_mesh_button = widgets.RadioButtons(options=['True', 'False'],
                                        value='False',
                                        description='Plot grid points:',
                                        disabled=False)
Example #26
0
def seismic_refraction_app():
    v1 = widgets.FloatSlider(description="v1",
                             min=300,
                             max=2000,
                             step=1,
                             continuous_update=False,
                             value=500)
    v2 = widgets.FloatSlider(description="v2",
                             min=300,
                             max=5000,
                             step=1,
                             continuous_update=False,
                             value=1000)
    v3 = widgets.FloatSlider(description="v3",
                             min=300,
                             max=5000,
                             step=1,
                             continuous_update=False,
                             value=2000)
    z1 = widgets.FloatSlider(description="z1",
                             min=5,
                             max=50,
                             step=1,
                             continuous_update=False,
                             value=10)
    z2 = widgets.FloatSlider(description="z2",
                             min=5,
                             max=50,
                             step=1,
                             continuous_update=False,
                             value=20)
    x_loc = widgets.FloatSlider(description="offset",
                                min=1,
                                max=100,
                                step=0.5,
                                continuous_update=False,
                                value=80)
    t_star = widgets.FloatSlider(
        description="time",
        min=0.001,
        max=0.25,
        step=0.001,
        continuous_update=False,
        value=0.1,
        orientation='vertical',
        readout_format='.3f',
    )
    show = widgets.RadioButtons(
        description='plot',
        options=['direct', 'refraction1', 'refraction2', 'all'],
        value='all',
        disabled=False)
    out = widgets.interactive_output(
        interact_refraction, {
            'v1': v1,
            'v2': v2,
            'v3': v3,
            'z1': z1,
            'z2': z2,
            'x_loc': x_loc,
            't_star': t_star,
            'show': show
        })
    left = widgets.VBox([t_star],
                        layout=widgets.Layout(width='10%',
                                              height='400px',
                                              margin='300px 0px 0px 0px'))
    right = widgets.VBox([show, v1, v2, v3, z1, z2],
                         layout=widgets.Layout(width='50%',
                                               height='400px',
                                               margin='20px 0px 0px 0px'))
    image = widgets.VBox([out, x_loc],
                         layout=widgets.Layout(width='70%',
                                               height='600px',
                                               margin='0px 0px 0px 0px'))
    return widgets.HBox([left, image, right])
Example #27
0
    def interact_plot_model_two_monopole(self):
        component = widgets.RadioButtons(
            options=["Bt", "Bx", "By", "Bz", "Bg"],
            value="Bt",
            description="field",
            disabled=False,
        )

        inclination = widgets.FloatSlider(description="I",
                                          continuous_update=False,
                                          min=-90,
                                          max=90,
                                          step=1,
                                          value=90)
        declination = widgets.FloatSlider(description="D",
                                          continuous_update=False,
                                          min=-180,
                                          max=180,
                                          step=1,
                                          value=0)
        length = widgets.FloatSlider(
            description="length",
            continuous_update=False,
            min=2,
            max=200,
            step=1,
            value=10,
        )
        dx = widgets.FloatSlider(
            description="data spacing",
            continuous_update=False,
            min=0.1,
            max=15,
            step=0.1,
            value=0.1,
        )
        moment = widgets.FloatText(description="M", value=30)
        depth_n = widgets.FloatSlider(
            description="depth$_{-Q}$",
            continuous_update=False,
            min=0,
            max=200,
            step=1,
            value=0,
        )
        depth_p = widgets.FloatSlider(
            description="depth$_{+Q}$",
            continuous_update=False,
            min=0,
            max=200,
            step=1,
            value=1,
        )
        profile = widgets.RadioButtons(
            options=["East", "North", "None"],
            value="East",
            description="profile",
            disabled=False,
        )
        fixed_scale = widgets.Checkbox(value=False,
                                       description="fixed scale",
                                       disabled=False)
        show_halfwidth = widgets.Checkbox(value=False,
                                          description="half width",
                                          disabled=False)

        out = widgets.interactive_output(
            self.magnetic_two_monopole_applet,
            {
                "component": component,
                "inclination": inclination,
                "declination": declination,
                "length": length,
                "dx": dx,
                "moment": moment,
                "depth_n": depth_n,
                "depth_p": depth_p,
                "profile": profile,
                "fixed_scale": fixed_scale,
                "show_halfwidth": show_halfwidth,
            },
        )
        left = widgets.VBox(
            [component, profile],
            layout=Layout(width="20%",
                          height="400px",
                          margin="60px 0px 0px 0px"),
        )
        right = widgets.VBox(
            [
                inclination,
                declination,
                length,
                dx,
                moment,
                depth_n,
                depth_p,
                fixed_scale,
                show_halfwidth,
            ],
            layout=Layout(width="50%",
                          height="400px",
                          margin="20px 0px 0px 0px"),
        )
        widgets.VBox([out],
                     layout=Layout(width="70%",
                                   height="400px",
                                   margin="0px 0px 0px 0px"))
        return widgets.HBox([left, out, right])
Example #28
0
    def __init__(
        self,
        input_data: Units,
        trials: pynwb.epoch.TimeIntervals = None,
        unit_index=0,
        unit_controller=None,
        ntt=1000,
    ):

        self.units = input_data

        super().__init__()

        if trials is None:
            self.trials = self.get_trials()
            if self.trials is None:
                self.children = [widgets.HTML("No trials present")]
                return
        else:
            self.trials = trials

        if unit_controller is None:
            self.unit_ids = self.units.id.data[:]
            n_units = len(self.unit_ids)
            self.unit_controller = widgets.Dropdown(
                options=[(str(self.unit_ids[x]), x) for x in range(n_units)],
                value=unit_index,
                description="unit",
                layout=Layout(width="200px"),
            )

        self.trial_event_controller = make_trial_event_controller(
            self.trials, layout=Layout(width="200px")
        )
        self.start_ft = widgets.FloatText(
            -0.5, step=0.1, description="start (s)", layout=Layout(width="200px"),
            description_tooltip = 'Start time for calculation before or after (negative or positive) the reference point (aligned to)'
        )
        
        self.end_ft = widgets.FloatText(
            1.0, step=0.1, description="end (s)", layout=Layout(width="200px"),
            description_tooltip = 'End time for calculation before or after (negative or positive) the reference point (aligned to).'
        )
        

        self.psth_type_radio = widgets.RadioButtons(
            options=["histogram", "gaussian"], layout=Layout(width="100px")
        )
        self.bins_ft = widgets.IntText(
            30, min=0, description="# bins", layout=Layout(width="150px")
        )
        self.gaussian_sd_ft = widgets.FloatText(
            0.05,
            min=0.001,
            description="sd (s)",
            layout=Layout(width="150px"),
            active=False,
            step=0.01,
        )

        self.gas = self.make_group_and_sort(window=False, control_order=False)

        self.controls = dict(
            ntt=fixed(ntt),
            index=self.unit_controller,
            end=self.end_ft,
            start=self.start_ft,
            start_label=self.trial_event_controller,
            gas=self.gas,
            plot_type=self.psth_type_radio,
            sigma_in_secs=self.gaussian_sd_ft,
            nbins=self.bins_ft
            # progress_bar=fixed(progress_bar)
        )

        out_fig = interactive_output(self.update, self.controls)

        self.children = [
            widgets.HBox(
                [
                    widgets.VBox(
                        [
                            self.gas,
                            widgets.HBox(
                                [
                                    self.psth_type_radio,
                                    widgets.VBox([self.gaussian_sd_ft, self.bins_ft]),
                                ]
                            ),
                        ]
                    ),
                    widgets.VBox(
                        [
                            self.unit_controller,
                            self.trial_event_controller,
                            self.start_ft,
                            self.end_ft,
                        ]
                    ),
                ]
            ),
            out_fig,
        ]
 def how_to_combine(self):
     self.combine_method = widgets.RadioButtons(options=['add', 'mean'],
                                                value='add')
     display(self.combine_method)
Example #30
0
                                max=2019,
                                step=1,
                                value=2003,
                                description='Year '),
         month=widgets.IntSlider(min=1,
                                 max=12,
                                 step=1,
                                 value=2,
                                 description='Month '),
         days=widgets.IntSlider(min=0,
                                max=10,
                                step=1,
                                value=0,
                                description='Day '),
         gearbox=widgets.RadioButtons(value='manuell',
                                      options=list(df_auto.gearbox.unique()),
                                      description="Gear Type "),
         damage=widgets.RadioButtons(value='no',
                                     options=list(
                                         df_auto.notRepairedDamage.unique()),
                                     description="Repaired "))

df_auto.head()

# Importing Necessary Libraries
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split

X = df_auto.drop(['price'], axis=1)
y = df_auto.price