def plot_series(self, out_widget, variable, loc_id):
        """
        """
        dim_id = None
        if dim_id is None:
            dim_id = self.key
        tts = self.x_data['q_obs_mm'].sel({dim_id: loc_id})
        # if using bqplot down the track:
        # points = gpx.get_points_data(distance_2d=True)
        # px = [p.distance_from_start / 1000 for p in points]
        # py = [p.point.elevation for p in points]

        # x_scale, y_scale = LinearScale(), LinearScale()
        # x_scale.allow_padding = False
        # x_ax = Axis(label='Time', scale=x_scale)
        # y_ax = Axis(label='Value', scale=y_scale, orientation='vertical')

        # lines = Lines(x=px, y=py, scales={'x': x_scale, 'y': y_scale})

        # elevation = Figure(title='Elevation Chart', axes=[x_ax, y_ax], marks=[lines])
        # elevation.layout.width = 'auto'
        # elevation.layout.height = 'auto'
        # elevation.layout.min_height = '500px'
        # elevation.interaction = IndexSelector(scale=x_scale)
        # with(out_widget):
        #     plt.plot(tts)
        out_widget.clear_output()
        with(out_widget):
            display(tts.plot(figsize=(16,8)))
            show_inline_matplotlib_plots()
Beispiel #2
0
 def on_button_clicked(b):
     with output:
         clear_output(True)
         m_true,d_true,prob,TDsurvey = create_prob(rho_sliders,dep_cells)
         plot_data(d_true,TDsurvey)
         show_inline_matplotlib_plots()
     return
Beispiel #3
0
 def on_button_clicked(b):
     with output:
         clear_output(True)
         m_true,d_true,prob,TDsurvey = create_prob(res_model_app)
         plot_data(d_true,TDsurvey)
         show_inline_matplotlib_plots()
     return
    def disp_plot(self, *args):

        self.plot_out.clear_output()
        if self.graph_type.value == None:
            return
        with self.plot_out:
            if self.graph_type.value == "describe":
                display(self.df.describe())
            else:
                try:
                    if self.graph_type.value == 'categorical':
                        g = sns.catplot(data=self.df,
                                        kind=self.kind.value,
                                        x=self.xsel.value,
                                        y=self.ysel.value,
                                        row=self.rsel.value,
                                        col=self.csel.value,
                                        hue=self.hsel.value)
                        g.set_xticklabels(rotation=45)
                    #)
                    else:
                        g = sns.displot(self.df,
                                        x=self.xsel.value,
                                        hue=self.hsel.value)
                except:
                    pass

            show_inline_matplotlib_plots()
Beispiel #5
0
def on_mpl_clicked(b):
    with output_mpl:
        clear_output(wait=True)
        hdbdata_fil = filter_HDB(**{k: v.value for k,v in filterdict.items()})
        fnc_out = resale_price_mean(hdbdata_fil)
        plot_mpl(fnc_out)
        show_inline_matplotlib_plots()
Beispiel #6
0
    def plot_results(self, b):

        self.out.clear_output()
        show_inline_matplotlib_plots()

        with self.out:
            plot(self.cache)
Beispiel #7
0
 def on_button_clicked(b):
     print('Running inversion...')
     with output:
         clear_output(True)
         mopt = prob_and_run(rho_sliders,dep_cells)
         ax = plot_results(mopt,expmap,rho_sliders,dep_cells)
         show_inline_matplotlib_plots()
     return
Beispiel #8
0
 def on_button_clicked(b):
     print('Running inversion...')
     with output:
         clear_output(True)
         mopt = prob_and_run(res_model_app)
         f,ax = plot_results(mopt,expmap,res_model_app)
         show_inline_matplotlib_plots()
     return
 def widget_change():
     with self.out:
         clear_output(wait=True)
         arguments = dict()
         for key, widget in additional_widgets.iteritems():
             arguments[key] = widget.value
         self.plotfunction(quantity, **arguments)
         show_inline_matplotlib_plots()
Beispiel #10
0
 def on_value_change(change):
     with output:
         clear_output(wait=True)
         ideas_[idx] = change['new']
         ideas_tensor = torch.from_numpy(ideas_)
         res = model(ideas_tensor)
         plt.plot(res.data.numpy())
         show_inline_matplotlib_plots()
Beispiel #11
0
def on_plot_fwd_clicked(b):
    try:
        out_fwd_curve.clear_output()
        curve = read_fwd_curve()
        with out_fwd_curve:
            curve.plot()
            show_inline_matplotlib_plots()
    except Exception as e:
        logger.exception(e)
Beispiel #12
0
 def display_plot(self, *_):
     """
     Display the plot object associated with the UI state, unless the
     user does not want interactive updates
     """
     if not self.auto_update.value:
         return
     show_inline_matplotlib_plots()
     with self.output:
         clear_output(wait=True)
         self.gen_plot()
         show_inline_matplotlib_plots()
Beispiel #13
0
    def on_clicked(b):
        output_plot.clear_output()
        with output_plot:
            self.update_rm()

            self.rm_original.fig_image_list = self.rm.get_images(
                legend_list=w_legend.update(),
                n_images=w_n_images.update(),
                n_exps=w_n_exps.update(),
                figsize=w_figsize.update(),
                dirname=w_dirname.update())
            show_inline_matplotlib_plots()
Beispiel #14
0
    def on_clicked(b):
        if d_style.value == 'True':
            from IPython import get_ipython
            ipython = get_ipython()
            ipython.magic("matplotlib widget")
        output_plot.clear_output()
        with output_plot:
            self.update_rm()

            self.vars['y_metrics'] = list(t_y_metric.value)
            self.vars['x_metric'] = d_x_metric_columns.value

            w, h = 10, 5
            if len(self.vars['y_metrics']) > 1:
                figsize = (2 * int(w), int(h))
                self.vars['figsize'] = figsize
            else:
                self.vars['figsize'] = (int(w), int(h))

            self.vars['legend_list'] = list(llegend_list.value)
            self.vars['legend_format'] = llegend_format.value
            self.vars['log_metric_list'] = hu.get_list_from_str(
                llog_metric_list.value)
            self.vars['groupby_list'] = list(t_groupby_list.value)
            self.vars['mode'] = t_mode.value
            self.vars['title_list'] = list(t_title_list.value)
            self.vars['bar_agg'] = t_bar_agg.value
            self.vars['title_format'] = ltitle_format.value
            self.vars['cmap'] = lcmap.value
            self.vars['avg_across'] = d_avg_across_columns.value

            avg_across_value = self.vars['avg_across']
            if avg_across_value == "None":
                avg_across_value = None

            self.rm_original.fig_list = self.rm.get_plot_all(
                y_metric_list=self.vars['y_metrics'],
                x_metric=self.vars['x_metric'],
                groupby_list=self.vars['groupby_list'],
                legend_list=self.vars['legend_list'],
                log_metric_list=self.vars['log_metric_list'],
                mode=self.vars['mode'],
                bar_agg=self.vars['bar_agg'],
                figsize=self.vars['figsize'],
                title_list=self.vars['title_list'],
                legend_format=self.vars['legend_format'],
                title_format=self.vars['title_format'],
                cmap=self.vars['cmap'],
                avg_across=avg_across_value)

            show_inline_matplotlib_plots()
Beispiel #15
0
def plot_iteration(line: str):
    """call a registered plotter function for the given repetition and iteration"""
    args = parse_argstring(plot_iteration, line)

    items = []

    from ipywidgets.widgets.interaction import show_inline_matplotlib_plots

    global __instances, __instantiated_experiments
    for exp_instance, exp_config in zip(__instances, __instantiated_experiments):
        out = Output()
        items.append(out)
        with out:
            # clear_output(wait=True)
            figures = __iteration_plot_functions[args.plotter_name](exp_instance, args.args)
            show_inline_matplotlib_plots()
            if args.save_figures:
                if args.format is None:
                    args.format = plt.rcParams['savefig.format']
                os.makedirs('plots/{}'.format(exp_config['name']), exist_ok=True)
                for i, f in enumerate(figures):
                    filename = 'plots/{}/{}figure_{}.{}'.format(exp_config['name'], args.prefix, i, args.format)
                    if args.format == 'tikz':
                        try:
                            from matplotlib2tikz import save as tikz_save
                            with Output():
                                tikz_save(filename, figureheight='\\figureheight', figurewidth='\\figurewidth')
                        except ModuleNotFoundError:
                            warnings.warn('Saving figure as tikz requires the module matplotlib2tikz.')
                    else:
                        f.savefig(filename, format=args.format)

    if len(items) > 1:
        tabs = Tab(children=items)
        for i, exp in enumerate(__instantiated_experiments):
            if args.tab_title:
                if (args.tab_title[0] == args.tab_title[-1]) and args.tab_title.startswith(("'", '"')):
                    selectors = args.tab_title[1:-1]
                else:
                    selectors = args.tab_title
                selectors = selectors.split(' ')
                values = [reduce(lambda a, b: a[b], [exp['params'], *selector.split('.')]) for selector in
                          selectors]
                tabs.set_title(i, ' '.join(map(str, values)))
            else:
                tabs.set_title(i, '...' + exp['name'][-15:])
        display(tabs)
    elif len(items) == 1:
        return items[0]
    else:
        warnings.warn('No plots available for {} with args {}'.format(args.plotter_name, args.args))
Beispiel #16
0
 def display_plot(self, *_):
     """Close the current figure, get the widgets states to a kwargs dict
     then call the .plot method"""
     # close current figure
     plt.close(self.fig)
     show_inline_matplotlib_plots()   
     with self.output:
         # clear_output de IPython.display
         clear_output(wait=True)
         # get all widgets names and values in a dict
         kwargs = self.retrieve_enabled_kwargs()
         # actual plot call
         self.plot(kwargs)
         show_inline_matplotlib_plots()   
Beispiel #17
0
 def plot_series(self,
                 out_widget: Output,
                 variable: str,
                 loc_id: str,
                 dim_id: str = None):
     """
     """
     tts = self.get_data(variable=variable, loc_id=loc_id, dim_id=dim_id)
     # if using bqplot down the track, see https://github.com/jtpio/voila-gpx-viewer
     out_widget.clear_output()
     with out_widget:
         _ = tts.plot(figsize=(16, 8))
         # do not use display(blah) which then displays the obnoxious matplotlib.lines.Line2D object at etc.>]
         ax = plt.gca()
         ax.set_title(loc_id)
         show_inline_matplotlib_plots()
Beispiel #18
0
 def on_clicked(b):
     self.update_rm()
     output_plot.clear_output()
     with output_plot:
         w, h = tfigsize.value.strip('(').strip(')').split(',')
         self.vars['figsize_images'] = (int(w), int(h))
         self.vars['legend_list'] = get_list_from_str(llegend_list.value)
         self.vars['n_images'] = int(t_n_images.value)
         self.vars['n_exps'] = int(t_n_exps.value)
         self.vars['dirname'] = t_dirname.value
         self.rm.get_images(legend_list=self.vars['legend_list'], 
                 n_images=self.vars['n_images'],
                 n_exps=self.vars['n_exps'],
                 figsize=self.vars['figsize_images'],
                 dirname=self.vars['dirname'])
         show_inline_matplotlib_plots()
Beispiel #19
0
def interactive_fwd(rho_sliders,dep_cells):

    button = Button(description="Acquire AEM data!")
    output = Output()
    display(button, output)

    def on_button_clicked(b):
        with output:
            clear_output(True)
            m_true,d_true,prob,TDsurvey = create_prob(rho_sliders,dep_cells)
            plot_data(d_true,TDsurvey)
            show_inline_matplotlib_plots()
        return
    button.on_click(on_button_clicked)

    show_inline_matplotlib_plots()
    return button,output
Beispiel #20
0
def interactive_inversion(rho_sliders,dep_cells):

    button = Button(description="Run inversion!")
    output = Output()
    display(button, output)

    def on_button_clicked(b):
        print('Running inversion...')
        with output:
            clear_output(True)
            mopt = prob_and_run(rho_sliders,dep_cells)
            ax = plot_results(mopt,expmap,rho_sliders,dep_cells)
            show_inline_matplotlib_plots()
        return
    button.on_click(on_button_clicked)

    show_inline_matplotlib_plots()
    return button,output
Beispiel #21
0
    def on_clicked(b):
        # if d_style.value == 'True':
        #     from IPython import get_ipython
        #     ipython = get_ipython()
        #     ipython.magic("matplotlib widget")
        output_plot.clear_output()
        with output_plot:
            self.update_rm()


            w, h = 10, 5
            if len(w_y_metrics.update()) == 0:
                display('No results saved yet.')
                return

            elif len(w_y_metrics.update()) > 1:
                figsize = (2*int(w), int(h))
                self.vars['figsize'] = figsize
            else:
                self.vars['figsize'] = (int(w), int(h))

            self.vars['legend_format'] = llegend_format.value
            self.vars['log_metric_list'] = hu.get_list_from_str(
                llog_metric_list.value)

            self.vars['title_format'] = ltitle_format.value
            self.vars['cmap'] = lcmap.value


            self.rm_original.fig_list = self.rm.get_plot_all(y_metric_list=w_y_metrics.update(),
                                                             x_metric=w_x_metric.update(),
                                                             groupby_list=w_groupby.update(),
                                                             legend_list=w_legend.update(),
                                                             log_metric_list=self.vars['log_metric_list'],
                                                             mode=w_mode.update(),
                                                             bar_agg=w_bar_agg.update(),
                                                             figsize=self.vars['figsize'],
                                                             title_list=w_title.update(),
                                                             legend_format=self.vars['legend_format'],
                                                             title_format=self.vars['title_format'],
                                                             cmap=self.vars['cmap'],
                                                             avg_across=w_avg_across.update())

            show_inline_matplotlib_plots()
Beispiel #22
0
 def __call__(self, fetch_tuples):
     """ render the window data 
     Args:
       fetch_tuples: callback to get the next tuples from the ClassificationMetrics view
       returns a list of tuples or None to terminate
 """
     notDone = True
     display(self.class_dashboard)
     cnt = 1
     while notDone:
         try:
             view_metrics = fetch_tuples()
             if view_metrics is None:
                 notDone = False
                 return
             for raw_metrics in view_metrics:
                 #metrics = json.loads(raw_metrics)
                 metrics = raw_metrics
                 for camera in self.cameras:
                     with self.class_widgets[camera]:
                         certain = metrics['camera_metrics'][camera][
                             'certain']
                         uncertain = metrics['camera_metrics'][camera][
                             'uncertain']
                         IPython.display.clear_output(wait=True)
                         df = pd.DataFrame(
                             {
                                 'uncertain counts': uncertain,
                                 'certain counts': certain
                             },
                             index=range(len(uncertain)))
                         ax = df.plot.bar(rot=0, title=camera)
                         ax.plot(figsize=[8, 1])
                         show_inline_matplotlib_plots()
                 self.class_status_widget.value = "{} of {} ts: {}".format(
                     cnt, len(view_metrics), metrics['timestamp'])
                 cnt += 1
                 time.sleep(2)
         except KeyboardInterrupt:
             notDone = False
             raise
Beispiel #23
0
def btn_plot_vol_clicked(b):
    out_vols.clear_output()
    with out_vols:
        if val_date_wgt.value is None or end_wgt.value is None:
            print('Enter val date and storage end date.')
            return
        vol_model = MultiFactorModel.for_3_factor_seasonal(
            freq, spot_mr_wgt.value, spot_vol_wgt.value, lt_vol_wgt.value,
            seas_vol_wgt.value, val_date_wgt.value, end_wgt.value)
        start_vol_period = pd.Period(val_date_wgt.value, freq=freq)
        end_vol_period = start_vol_period + 1
        periods = pd.period_range(start=end_vol_period,
                                  end=end_wgt.value,
                                  freq=freq)
        fwd_vols = [
            vol_model.integrated_vol(start_vol_period, end_vol_period, period)
            for period in periods
        ]
        fwd_vol_series = pd.Series(data=fwd_vols, index=periods)
        fwd_vol_series.plot()
        show_inline_matplotlib_plots()
Beispiel #24
0
def interactive_output(f, controls, process_controls=lambda x: x):
    """Connect widget controls to a function.

    This function does not generate a user interface for the widgets (unlike `interact`).
    This enables customisation of the widget user interface layout.
    The user interface layout must be defined and displayed manually.
    """

    out = Output()

    def observer(change):
        show_inline_matplotlib_plots()
        with out:
            clear_output(wait=True)
            f(**unpack_controls(controls, process_controls))
            show_inline_matplotlib_plots()
    for k, w in controls.items():
        w.observe(observer, 'value')
    show_inline_matplotlib_plots()
    observer(None)
    return out
Beispiel #25
0
    def on_clicked(b):
        output_plot.clear_output()
        with output_plot:
            self.update_rm()

            w, h = 10, 5
            if len(w_y_metrics.update()) == 0:
                display("No results saved yet.")
                return

            elif len(w_y_metrics.update()) > 1:
                figsize = (2 * int(w), int(h))
                self.vars["figsize"] = figsize
            else:
                self.vars["figsize"] = (int(w), int(h))

            self.vars["legend_format"] = llegend_format.value
            self.vars["log_metric_list"] = hu.get_list_from_str(
                llog_metric_list.value)

            self.vars["title_format"] = ltitle_format.value
            self.vars["cmap"] = lcmap.value

            self.rm_original.fig_list = self.rm.get_plot_all(
                y_metric_list=w_y_metrics.update(),
                x_metric=w_x_metric.update(),
                groupby_list=w_groupby.update(),
                legend_list=w_legend.update(),
                log_metric_list=self.vars["log_metric_list"],
                mode=w_mode.update(),
                bar_agg=w_bar_agg.update(),
                figsize=self.vars["figsize"],
                title_list=w_title.update(),
                legend_format=self.vars["legend_format"],
                title_format=self.vars["title_format"],
                cmap=self.vars["cmap"],
                avg_across=w_avg_across.update(),
            )

            show_inline_matplotlib_plots()
Beispiel #26
0
        def on_clicked(b):
            self.update_rm()

            output_plot.clear_output()
            with output_plot:
                self.vars['y_metrics'] = get_list_from_str(t_y_metric.value)
                self.vars['x_metric'] = t_x_metric.value

                w, h = 10, 5
                if len(self.vars['y_metrics']) > 1:
                    figsize = (2 * int(w), int(h))
                    self.vars['figsize'] = figsize
                else:
                    self.vars['figsize'] = (int(w), int(h))

                self.vars['legend_list'] = get_list_from_str(
                    llegend_list.value)

                self.vars['log_metric_list'] = get_list_from_str(
                    llog_metric_list.value)
                self.vars['groupby_list'] = get_list_from_str(
                    t_groupby_list.value)
                self.vars['mode'] = t_mode.value
                self.vars['title_list'] = get_list_from_str(t_title_list.value)
                self.vars['bar_agg'] = t_bar_agg.value

                self.rm.get_plot_all(
                    y_metric_list=self.vars['y_metrics'],
                    x_metric=self.vars['x_metric'],
                    groupby_list=self.vars['groupby_list'],
                    legend_list=self.vars['legend_list'],
                    log_metric_list=self.vars['log_metric_list'],
                    mode=self.vars['mode'],
                    bar_agg=self.vars['bar_agg'],
                    figsize=self.vars['figsize'],
                    title_list=self.vars['title_list'])

                show_inline_matplotlib_plots()
Beispiel #27
0
 def _plot(self, field_name: str, output: widgets.Output):
     dim_selection = {
         name: slider.value
         for name, slider in self.dim_sliders.items()
     }
     self.figure_display.clear_output()
     with output:
         try:
             if field_name == 'Scalars':
                 plt.figure(figsize=(12, 5))
                 for name in self.app.curve_names:
                     plt.plot(*self.app.get_curve(name),
                              label=display_name(name))
                 plt.legend()
                 plt.tight_layout()
                 show_inline_matplotlib_plots()
             else:
                 value = self.app.get_field(field_name, dim_selection)
                 if isinstance(value, SampledField):
                     try:
                         value = select_channel(value, {
                             '🡡': None,
                             '⬤': 'abs'
                         }.get(self.vector_select.value,
                               self.vector_select.value))
                         plot(value,
                              lib='matplotlib',
                              **self.config.get('plt_args', {}))
                         show_inline_matplotlib_plots()
                     except ValueError as err:
                         self.figure_display.append_stdout(f"{err}")
                 else:
                     self.figure_display.append_stdout(
                         f"{field_name} = {value}")
         except Exception:
             self.figure_display.append_stdout(traceback.format_exc())
     self._last_plot_update_time = time.time()
Beispiel #28
0
    def show_image(rb_inst):
        with out:
            clear_output()

            if select_img.value == 'Notebook Dashboard':
                if select_feat.value == 'Select an item':
                    w_img = mpimg.imread(
                        os.path.join('img', 'Jupyter_select.png'))
                else:
                    w_img = mpimg.imread(
                        os.path.join('img', 'Jupyter_dashboard.png'))

            if select_img.value == 'Notebook':
                w_img = mpimg.imread(
                    os.path.join('img', 'Jupyter_notebook_head.png'))

            if select_img.value == 'Notebook Cells':
                w_img = mpimg.imread(os.path.join('img', 'Jupyter_cells.png'))

            if select_img.value == 'Select':
                feat_desc.value = ''
                return

            plt.figure(figsize=(20, 5))
            plt.imshow(w_img)
            plt.axis('off')

            rect_patch = None

            if select_feat.value == "'Files' tab":
                rect_patch = plt.Rectangle((20, 60),
                                           50,
                                           30,
                                           fill=None,
                                           edgecolor='r',
                                           linewidth=2)
                feat_desc.value = '<b>Feature Description</b>: This tab displays a window where you can view your files.'
            if select_feat.value == "Files list":
                rect_patch = plt.Rectangle((20, 170),
                                           300,
                                           75,
                                           fill=None,
                                           edgecolor='r',
                                           linewidth=2)
                feat_desc.value = '<b>Feature Description</b>: All of your notebooks, files, and folders are displayed here.'
            if select_feat.value == 'Select an item':
                rect_patch = plt.Rectangle((0, 90),
                                           350,
                                           35,
                                           fill=None,
                                           edgecolor='r',
                                           linewidth=2)
                feat_desc.value = '<b>Feature Description</b>: This menu shows actions you can take with an item - these actions will change depending on what you have selected (notebook, file, or folder) and if the notebook is currently running. Actions include duplicating, renaming, moving, downloading, viewing, editing, or deleting an item, or shutting down a notebook.'

            if select_feat.value == "'New' button":
                rect_patch = plt.Rectangle((1080, 100),
                                           50,
                                           26,
                                           fill=None,
                                           edgecolor='r',
                                           linewidth=2)
                feat_desc.value = '<b>Feature Description</b>: You can create a new notebook, text file, or folder using this button.'
            if select_feat.value == 'Notebook title':
                rect_patch = plt.Rectangle((135, 0),
                                           400,
                                           35,
                                           fill=None,
                                           edgecolor='r',
                                           linewidth=2)
                feat_desc.value = '<b>Feature Description</b>: The notebook title is displayed here. You can click to rename it.'
            if select_feat.value == 'Save status':
                rect_patch = plt.Rectangle((520, 0),
                                           330,
                                           35,
                                           fill=None,
                                           edgecolor='r',
                                           linewidth=2)
                feat_desc.value = '<b>Feature Description</b>: This indicates when the notebook was last saved. Save often!'
            if select_feat.value == 'Menu bar':
                rect_patch = plt.Rectangle((5, 43),
                                           500,
                                           35,
                                           fill=None,
                                           edgecolor='r',
                                           linewidth=2)
                feat_desc.value = '<b>Feature Description</b>: Various actions can be taken from the menu bar. A common action is restarting the kernel.'
            if select_feat.value == 'Tool bar':
                rect_patch = plt.Rectangle((5, 75),
                                           540,
                                           35,
                                           fill=None,
                                           edgecolor='r',
                                           linewidth=2)
                feat_desc.value = '<b>Feature Description</b>: Shortcuts for common actions are located here. Save using the left-most button often!'
            if select_feat.value == 'Cell type selector':
                rect_patch = plt.Rectangle((380, 74),
                                           120,
                                           35,
                                           fill=None,
                                           edgecolor='r',
                                           linewidth=2)
                feat_desc.value = "<b>Feature Description</b>: You can use this dropdown to change the type of your selected cell(s). The two most common cell types are 'Code' and 'Markdown'."
            if select_feat.value == 'Command palette':
                rect_patch = plt.Rectangle((500, 74),
                                           45,
                                           35,
                                           fill=None,
                                           edgecolor='r',
                                           linewidth=2)
                feat_desc.value = '<b>Feature Description</b>: Clicking here will bring up a useful list of keyboard shortcuts.'

            if select_feat.value == 'Markdown cell':
                rect_patch = plt.Rectangle((110, 24),
                                           1000,
                                           90,
                                           fill=None,
                                           edgecolor='r',
                                           linewidth=2)
                feat_desc.value = '<b>Feature Description</b>: This is a markdown cell. Use it for descriptive text and headings. Both HTML and Jupyter Markdown formatting can be used to style text.'
            if select_feat.value == 'Code cell':
                rect_patch = plt.Rectangle((110, 120),
                                           1000,
                                           100,
                                           fill=None,
                                           edgecolor='r',
                                           linewidth=2)
                feat_desc.value = '<b>Feature Description</b>: This is a code cell. You can run script snippets here.'
            if select_feat.value == 'Cell status':
                rect_patch = plt.Rectangle((45, 120),
                                           70,
                                           30,
                                           fill=None,
                                           edgecolor='r',
                                           linewidth=2)
                feat_desc.value = "<b>Feature Description</b>: This number tells you the order that the cells have been run in. If it is blank, the cell hasn't been run. If it has an *, the cell is currently running."

            if rect_patch:
                plt.gca().add_patch(rect_patch)

            show_inline_matplotlib_plots()
Beispiel #29
0
def runMorris(control_rows, output_dropdown, trajectories_text, levels_text,
              grid_jump_text, run_morris_button, results_output):
    inputs = [(control_row[0].value, control_row[1].value,
               control_row[2].value) for control_row in control_rows
              if control_row[0].value != no_selection]

    target_parameters = dict([(input[0], (input[1], input[2]))
                              for input in inputs])

    target_output_name = output_dropdown.value

    n_trajectories = trajectories_text.value
    num_levels = levels_text.value
    grid_jump = grid_jump_text.value

    run_morris_button.disabled = True

    try:
        problem, parameter_values, sis = hdm.run_salib_morris(
            target_parameters,
            target_output_name,
            n_trajectories,
            num_levels,
            grid_jump,
            1  # os.cpu_count()
        )
    except:
        with results_output:
            print("Invalid input", file=sys.stderr)
        return
    finally:
        run_morris_button.disabled = False

    from base64 import b64encode
    header = ','.join([name for name in target_parameters.keys()])
    lines = [','.join([str(d) for d in inputs]) for inputs in parameter_values]
    csv = header + os.linesep + os.linesep.join(lines)
    payload = b64encode(csv.encode())
    payload = payload.decode()
    fileName = "parameter_values.csv"
    title = "Download design"
    html = f'<a download="{fileName}" href="data:text/csv;charset=utf-8;base64,{payload}" target="_blank">{title}</a>'
    link = widgets.HTML(html)

    results_output.clear_output()

    with results_output:
        print("{0:<30} {1:>10} {2:>10} {3:>15} {4:>10}".format(
            "Parameter", "Mu_Star", "Mu", "Mu_Star_Conf", "Sigma"))
        num_vars = problem['num_vars']
        for j in list(range(num_vars)):
            print("{0:30} {1:10.3f} {2:10.3f} {3:15.3f} {4:10.3f}".format(
                sis['names'][j], sis['mu_star'][j], sis['mu'][j],
                sis['mu_star_conf'][j], sis['sigma'][j]))

        display(link)

        fig1, (ax1, ax2) = plt.subplots(1, 2)
        horizontal_bar_plot(ax1, sis, {}, sortby='mu_star')
        covariance_plot(ax2, sis, {})

        fig2 = plt.figure()
        sample_histograms(fig2, parameter_values, problem, {'color': 'y'})

        fig1.tight_layout()

        show_inline_matplotlib_plots()
Beispiel #30
0
def btn_clicked(b):
    progress_wgt.value = 0.0
    for vw in value_wgts:
        vw.value = ''
    btn_calculate.disabled = True
    out_summary.clear_output()
    out_triggers.clear_output()
    try:
        global fwd_curve
        logger.debug('Reading forward curve.')
        fwd_curve = read_fwd_curve()
        logger.debug('Forward curve read successfully.')
        global storage
        global val_results_3f
        if stor_type_wgt.value == 'Simple':
            storage = CmdtyStorage(
                freq,
                storage_start=start_wgt.value,
                storage_end=end_wgt.value,
                injection_cost=inj_cost_wgt.value,
                withdrawal_cost=with_cost_wgt.value,
                min_inventory=invent_min_wgt.value,
                max_inventory=invent_max_wgt.value,
                max_injection_rate=inj_rate_wgt.value,
                max_withdrawal_rate=with_rate_wgt.value,
                cmdty_consumed_inject=inj_consumed_wgt.value,
                cmdty_consumed_withdraw=with_consumed_wgt.value)
        else:
            ratchets = read_ratchets()
            storage = CmdtyStorage(freq,
                                   storage_start=start_wgt.value,
                                   storage_end=end_wgt.value,
                                   injection_cost=inj_cost_wgt.value,
                                   withdrawal_cost=with_cost_wgt.value,
                                   constraints=ratchets)

        interest_rate_curve = pd.Series(index=pd.period_range(
            val_date_wgt.value,
            twentieth_of_next_month(pd.Period(end_wgt.value, freq='D')),
            freq='D'),
                                        dtype='float64')
        interest_rate_curve[:] = ir_wgt.value
        seed = None if seed_is_random_wgt.value else random_seed_wgt.value
        fwd_sim_seed = fwd_sim_seed_wgt.value if fwd_sim_seed_set_wgt.value else None
        logger.info('Valuation started.')
        val_results_3f = three_factor_seasonal_value(
            storage,
            val_date_wgt.value,
            inventory_wgt.value,
            fwd_curve=fwd_curve,
            interest_rates=interest_rate_curve,
            settlement_rule=twentieth_of_next_month,
            spot_mean_reversion=spot_mr_wgt.value,
            spot_vol=spot_vol_wgt.value,
            long_term_vol=lt_vol_wgt.value,
            seasonal_vol=seas_vol_wgt.value,
            num_sims=num_sims_wgt.value,
            basis_funcs=basis_funcs_input_wgt.value,
            discount_deltas=discount_deltas_wgt.value,
            seed=seed,
            fwd_sim_seed=fwd_sim_seed,
            extra_decisions=extra_decisions_wgt.value,
            num_inventory_grid_points=grid_points_wgt.value,
            on_progress_update=on_progress,
            numerical_tolerance=num_tol_wgt.value)
        logger.info('Valuation completed without error.')
        full_value_wgt.value = "{0:,.0f}".format(val_results_3f.npv)
        intr_value_wgt.value = "{0:,.0f}".format(val_results_3f.intrinsic_npv)
        extr_value_wgt.value = "{0:,.0f}".format(val_results_3f.extrinsic_npv)
        intr_delta = val_results_3f.intrinsic_profile['net_volume']

        active_fwd_curve = fwd_curve[storage.start:storage.end]
        with out_summary:
            ax_1 = val_results_3f.deltas.plot(legend=True)
            ax_1.set_ylabel('Delta')
            intr_delta.plot(legend=True, ax=ax_1)
            ax_2 = active_fwd_curve.plot(secondary_y=True,
                                         legend=True,
                                         ax=ax_1)
            ax_2.set_ylabel('Forward Price')
            ax_1.legend(['Full Delta', 'Intrinsic Delta'])
            ax_2.legend(['Forward Curve'])
            show_inline_matplotlib_plots()
        with out_triggers:
            trigger_prices = val_results_3f.trigger_prices
            ax_1 = trigger_prices['inject_trigger_price'].plot(legend=True)
            ax_1.set_ylabel('Price')
            trigger_prices['withdraw_trigger_price'].plot(legend=True, ax=ax_1)
            active_fwd_curve.plot(legend=True, ax=ax_1)
            ax_2 = val_results_3f.expected_profile['inventory'].plot(
                secondary_y=True, legend=True, ax=ax_1)
            ax_2.set_ylabel('Volume')
            box = ax_1.get_position()
            ax_1.set_position([
                box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9
            ])
            ax_1.legend([
                'Inject Trigger Price', 'Withdraw Trigger Price',
                'Forward Curve'
            ],
                        loc='upper center',
                        bbox_to_anchor=(0.2, -0.12))
            ax_2.legend(['Expected Inventory'],
                        loc='upper center',
                        bbox_to_anchor=(0.7, -0.12))
            show_inline_matplotlib_plots()
    except Exception as e:
        logger.error('Exception:')
        logger.error(e)
    finally:
        btn_calculate.disabled = False