OutputPane

After OptiPass has completed the last optimization run the GUI creates an instance of this class and saves it in the Output tab of the top level display.

The first part of the panel has a set of ROI curves (displayed in a tab widget showing one figure at a time), the second part has tables showing data about barriers included in solutions.

Parameters:
  • op

    the main TideGatesApp object containing the optimization parameters

  • bf

    the Project object that has barrier data

Source code in src/tidegates/widgets.py
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
def __init__(self, op, bf):
    """
    Use the optimization parameters (region names, target names, budget
    levels) and barrier data to format the output from OptiPass.  
    The first part of the panel has a set of ROI curves
    (displayed in a tab widget showing one figure at a time), the second
    part has tables showing data about barriers included in solutions.

    Arguments:
      op:  the main TideGatesApp object containing the optimization parameters
      bf:  the Project object that has barrier data
    """
    super(OutputPane, self).__init__()
    self.op = op
    self.bf = bf
    # self.figures = []

    self.append(pn.pane.HTML('<h3>Optimization Complete</h3>', styles=header_styles))
    self.append(self._make_title())

    if op.budget_max > op.budget_delta:
        self.append(pn.pane.HTML('<h3>ROI Curves</h3>'))
        self.append(self._make_figures_tab())

    self.append(pn.pane.HTML('<h3>Budget Summary</h3>'))
    self.gate_count = self.op.summary.gates.apply(len).sum()
    if self.gate_count == 0:
        self.append(pn.pane.HTML('<i>No barriers selected -- consider increasing the budget</i>'))
    else:
        self.append(self._make_budget_table())
        self.append(pn.Accordion(
            ('Barrier Details', self._make_gate_table()),
            stylesheets = [accordion_style_sheet],
        ))

_make_budget_table()

Display a table that has one column for each budget level, showing which barriers were included in the solution for that level. Attach a callback function that is called when the user clicks on a row in the table (the callback updates the map to show gates used in a solution).

src/tidegates/widgets.py
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
def _make_budget_table(self):
    """
    Display a table that has one column for each budget level, showing
    which barriers were included in the solution for that level.  Attach
    a callback function that is called when the user clicks on a row
    in the table (the callback updates the map to show gates used in a
    solution).
    """
    df = self.op.summary[['budget','habitat', 'gates']]
    colnames = ['Budget', 'Net Gain', 'gates']
    formatters = { 
        'Budget': {'type': 'money', 'symbol': '$', 'precision': 0},
        'Net Gain': NumberFormatter(format='0.0', text_align='center'),
    }
    alignment = { 
        'Budget': 'right',
        'Net Gain': 'center',
    }
    df = pd.concat([
        df,
        pd.Series(self.op.summary.gates.apply(len))
    ], axis=1)
    colnames.append('# Barriers')
    alignment['# Barriers'] = 'center'
    for i, t in enumerate(self.op.targets):
        if t.abbrev in self.op.summary.columns:
            df = pd.concat([df, self.op.summary[t.abbrev]], axis=1)
            col = t.short
            if self.op.weighted:
                col += f'⨉{self.op.weights[i]}'
            colnames.append(col)
            formatters[col] = NumberFormatter(format='0.0', text_align='center')
    df.columns = colnames
    table = pn.widgets.Tabulator(
        df,
        show_index = False,
        hidden_columns = ['gates'],
        editors = { c: None for c in colnames },
        text_align = alignment,
        header_align = {c: 'center' for c in colnames},
        formatters = formatters,
        selectable = True,
        configuration = {'columnDefaults': {'headerSort': False}},
    )
    table.on_click(self.budget_table_cb)
    self.budget_table = df
    return table

_make_figures_tab()

Create a Tabs object with one tab for each ROI curve.

src/tidegates/widgets.py
518
519
520
521
522
523
524
525
526
527
528
529
def _make_figures_tab(self):
    """
    Create a Tabs object with one tab for each ROI curve.
    """
    tabs = pn.Tabs(
        tabs_location='left',
        stylesheets = [tab_style_sheet],
    )
    self.op.make_roi_curves()
    for p in self.op.display_figures:
        tabs.append(p)
    return tabs

_make_gate_table()

Make a table showing details about gates used in solutions.

src/tidegates/widgets.py
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
def _make_gate_table(self):
    """
    Make a table showing details about gates used in solutions.
    """
    formatters = { }
    alignment = { }
    df = self.op.table_view()
    hidden = ['Count']
    for col in df.columns:
        if col.startswith('$') or col in ['Primary','Dominant']:
            formatters[col] = {'type': 'tickCross', 'crossElement': ''}
            alignment[col] = 'center'
        elif col.endswith('hab'):
            c = col.replace('_hab','')
            formatters[c] = NumberFormatter(format='0.0', text_align='center')
            # alignment[c] = 'center'
        elif col.endswith('tude'):
            formatters[col] = NumberFormatter(format='0.00', text_align='center')
            # alignment[col] = 'right'
        elif col.endswith('gain'):
            hidden.append(col)
        elif col == 'Cost':
            formatters[col] = {'type': 'money', 'symbol': '$', 'precision': 0}
            alignment[col] = 'right'
    colnames = [c.replace('_hab','') for c in df.columns]
    if self.op.weighted:
        for i, t in enumerate(self.op.targets):
            if t.short not in colnames:             # shouldn't happen, but just in case...
                continue
            j = colnames.index(t.short)
            colnames[j] += f'⨉{self.op.weights[i]}'
            formatters[colnames[j]] = NumberFormatter(format='0.0', text_align='center')
    df.columns = colnames

    table = pn.widgets.Tabulator(
        df, 
        show_index=False, 
        frozen_columns=['ID'],
        hidden_columns=hidden,
        formatters=formatters,
        text_align=alignment,
        configuration={'columnDefaults': {'headerSort': False}},
        header_align={c: 'center' for c in df.columns},
        selectable = False,
    )
    table.disabled = True
    self.gate_table = df
    return table

_make_title()

The top section of the output pane is a title showing the optimization parameters.

src/tidegates/widgets.py
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
def _make_title(self):
    """
    The top section of the output pane is a title showing the optimization parameters.
    """
    regions = self.op.regions
    targets = [t.short for t in self.op.targets]
    if self.op.weighted:
        targets = [f'{targets[i]}{self.op.weights[i]}' for i in range(len(targets))]
    bmax = self.op.budget_max
    binc = self.op.budget_delta
    if bmax > binc:
        title_template = '<p><b>Regions:</b> {r}; <b>Targets:</b> {t}; <b>Climate:</b> {c}; <b>Budgets:</b> {min} to {max}</p>'
        return pn.pane.HTML(title_template.format(
            r = ', '.join(regions),
            t = ', '.join(targets),
            c = self.op.climate,
            min = OP.format_budget_amount(binc),
            max = OP.format_budget_amount(bmax),
        ))
    else:
        title_template = '<p><b>Regions:</b> {r}; <b>Targets:</b> {t}; <b>Climate:</b> {c}; <b>Budget:</b> {b}'
        return pn.pane.HTML(title_template.format(
            r = ', '.join(regions),
            t = ', '.join(targets),
            c = self.op.climate,
            b = OP.format_budget_amount(bmax),
        ))

budget_table_cb(e)

The callback function invoked when the user clicks a row in the budget table. Use the event to figure out which row was clicked. Hide any dots that were displayed previously, then make the dots for the selected row visible.

src/tidegates/widgets.py
645
646
647
648
649
650
651
652
653
654
def budget_table_cb(self, e):
    """
    The callback function invoked when the user clicks a row in the budget table.
    Use the event to figure out which row was clicked.  Hide any dots that were displayed
    previously, then make the dots for the selected row visible.
    """
    if n := self.selected_row:
        self.dots[n].visible = False
    self.selected_row = e.row
    self.dots[self.selected_row].visible = True

hide_dots()

Callback function invoked when users click on a region name in the start panel to hide any dots that might be on the map.

src/tidegates/widgets.py
656
657
658
659
660
661
662
663
def hide_dots(self):
    """
    Callback function invoked when users click on a region name in the start panel to hide
    any dots that might be on the map.
    """
    if self.selected_row:
        self.dots[self.selected_row].visible = False
    self.selected_row = None

make_dots(plot)

Called after the output panel is initialized, make a set of glyphs to display for each budget level.

src/tidegates/widgets.py
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
def make_dots(self, plot):
    """
    Called after the output panel is initialized, make a set of glyphs to display
    for each budget level.
    """
    if hasattr(self, 'budget_table'):
        self.selected_row = None
        self.dots = []
        for row in self.budget_table.itertuples():
            df = self.bf.map_info[self.bf.data.BARID.isin(row.gates)]
            c = plot.circle_dot('x', 'y', size=12, line_color='blue', fill_color='white', source=df)
            # c = plot.star_dot('x', 'y', size=20, line_color='blue', fill_color='white', source=df)
            # c = plot.star('x', 'y', size=12, color='blue', source=df)
            # c = plot.hex('x', 'y', size=12, color='green', source=df)
            c.visible = False
            self.dots.append(c)