bokeh.models.Label

Here are the examples of the python api bokeh.models.Label taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

17 Examples 7

3 Source : calendar.py
with GNU Affero General Public License v3.0
from andrewcooke

    def _add_labels(plot, start, finish, xlo, xhi, yhi, border_day, delta_year):
        for y in range(start.year, finish.year+1):
            plot.add_layout(Label(x=xhi + 1.1, y=(start.year - y - 0.4) * delta_year, text=str(y),
                                        text_align='center', text_baseline='bottom', angle=3*pi/2))
            for d, text in enumerate(day_abbr):
                plot.add_layout(Label(x=xlo - 1.5, y=(start.year - y) * delta_year - d * (1 + border_day),
                                      text=text, text_align='right', text_baseline='middle',
                                      text_font_size='7pt', text_color='grey'))
        dx = (xhi - xlo) / 12
        for m, text in enumerate(month_abbr[1:]):
            plot.add_layout(Label(x=xlo + dx * (m + 0.5), y=yhi + 1.5,
                                  text=text, text_align='center', text_baseline='bottom'))
        plot.toolbar.logo = None

    @staticmethod

3 Source : uibokeh_well.py
with Apache License 2.0
from OpendTect

    def addMarker(self, name, depth, color):
        marker_style = {'line_color': color,
                        'line_width': 2,
                        'line_dash': 'solid'
                       }
        xr = self.track.x_range
        self.track.add_layout(bm.Arrow(end=None,x_start=xr.start,y_start=depth,x_end=xr.end,y_end=depth,**marker_style))
        self.track.add_layout(bm.Label(x=xr.start,y=depth,text=name,text_color=color,render_mode='canvas'))

    def addMarkers(self, markers=None):

3 Source : test_plots.py
with MIT License
from rthorst

def test_plot_add_layout_adds_label_to_plot_renderers():
    plot = figure()
    label = Label()
    plot.add_layout(label)
    assert label in plot.center


def test_plot_add_layout_adds_axis_to_renderers_and_side_renderers():

3 Source : widgets.py
with MIT License
from smartyal

    def show_hide_scroll_label(self):
        self.logger.debug(f"show scroll label {self.width-165}, {self.height-50} {self.scrollLabel}, {self.streamingMode}")
        #creation
        if not self.scrollLabel:
            self.scrollLabel = Label(x=self.width-165, y=self.height-50, x_units='screen', y_units='screen',
                  text=' auto scroll mode on ', text_font_size="12px", text_color=themes.textcolor,
                  border_line_color=themes.textcolor, border_line_alpha=1.0,
                  background_fill_color='black', background_fill_alpha=1.0)
            if not self.streamingMode:
                self.scrollLabel.visible = False
            self.plot.add_layout(self.scrollLabel)
        if self.streamingMode:
            self.scrollLabel.visible = True
        else:
            self.scrollLabel.visible = False


    def annotation_drop_down_on_change_cb(self,attr,old,new):

0 Source : visual_midi.py
with MIT License
from dubreuia

    def plot(self, pm: PrettyMIDI):
        """
        Plots the pretty midi object as a plot object.

          :param pm: the PrettyMIDI instance to plot
          :return: the bokeh plot layout
        """
        preset = self._preset

        # Calculates the QPM from the MIDI file, might raise exception if confused
        qpm = self._get_qpm(pm)

        # Initialize the tools, those are present on the right hand side
        plot = bokeh.plotting.figure(
            tools="reset,hover,save,wheel_zoom,pan",
            toolbar_location=preset.toolbar_location)

        # Setup the hover and the data dict for bokeh,
        # each property must match a property in the data dict
        plot.select(dict(type=bokeh.models.HoverTool)).tooltips = ({
            "program": "@program",
            "pitch": "@top",
            "velocity": "@velocity",
            "duration": "@duration",
            "start_time": "@left",
            "end_time": "@right"})
        data = dict(
            program=[],
            top=[],
            bottom=[],
            left=[],
            right=[],
            duration=[],
            velocity=[],
            color=[])

        # Puts the notes in the dict for bokeh and saves first
        # and last note time, bigger and smaller pitch
        pitch_min = None
        pitch_max = None
        first_note_start = None
        last_note_end = None
        index_instrument = 0
        for instrument in pm.instruments:
            for note in instrument.notes:
                pitch_min = min(pitch_min or self._MAX_PITCH, note.pitch)
                pitch_max = max(pitch_max or self._MIN_PITCH, note.pitch)
                color = self._get_color(index_instrument, note)
                note_start = note.start
                note_end = note.start + (note.end - note.start)
                data["program"].append(instrument.program)
                data["top"].append(note.pitch)
                if self._show_velocity:
                    data["bottom"].append(note.pitch + (note.velocity / 127))
                else:
                    data["bottom"].append(note.pitch + 1)
                data["left"].append(note_start)
                data["right"].append(note_end)
                data["duration"].append(note_end - note_start)
                data["velocity"].append(note.velocity)
                data["color"].append(color)
                first_note_start = min(first_note_start or sys.maxsize, note_start)
                last_note_end = max(last_note_end or 0, note_end)
            index_instrument = index_instrument + 1

        # Shows an empty plot even if there are no notes
        if first_note_start is None or last_note_end is None or pitch_min is None or pitch_max is None:
            pitch_min = self._MIN_PITCH
            pitch_max = pitch_min + 5
            first_note_start = 0
            last_note_end = 0

        # Gets the pitch range (min, max) from either the provided arguments
        # or min and max values from the notes
        if self._plot_pitch_range_start is not None:
            pitch_min = self._plot_pitch_range_start
        else:
            pitch_min = min(self._MAX_PITCH, pitch_min)
        if self._plot_pitch_range_stop is not None:
            pitch_max = self._plot_pitch_range_stop
        else:
            pitch_max = max(self._MIN_PITCH, pitch_max)

        pitch_range = pitch_max + 1 - pitch_min

        # Draws the rectangles on the plot from the data
        source = ColumnDataSource(data=data)
        plot.quad(left="left",
                  right="right",
                  top="top",
                  bottom="bottom",
                  line_alpha=1,
                  line_color="black",
                  color="color",
                  source=source)

        # Draws the y grid by hand, because the grid has label on the ticks, but
        # for a plot like this, the labels needs to fit in between the ticks.
        # Also useful to change the background of the grid each line
        for pitch in range(pitch_min, pitch_max + 1):
            # Draws the background box and contours, on the underlay layer, so
            # that the rectangles and over the box annotations
            fill_alpha = (0.15 if pitch % 2 == 0 else 0.00)
            box = BoxAnnotation(bottom=pitch,
                                top=pitch + 1,
                                fill_color="gray",
                                fill_alpha=fill_alpha,
                                line_color="black",
                                line_alpha=0.3,
                                line_width=1,
                                level="underlay")
            plot.add_layout(box)
            label = Label(
                x=preset.label_y_axis_offset_x,
                y=pitch + preset.label_y_axis_offset_y,
                x_units="screen",
                text=str(pitch),
                render_mode="css",
                text_font_size=preset.label_text_font_size,
                text_font_style=preset.label_text_font_style)
            plot.add_layout(label)

        # Gets the time signature from pretty midi, or 4/4 if none
        if self._midi_time_signature:
            numerator, denominator = self._midi_time_signature.split("/")
            time_signature = TimeSignature(int(numerator), int(denominator), 0)
        else:
            if pm.time_signature_changes:
                if len(pm.time_signature_changes) > 1:
                    raise Exception("Multiple time signatures are not supported")
                time_signature = pm.time_signature_changes[0]
            else:
                time_signature = TimeSignature(4, 4, 0)

        # Gets seconds per bar and seconds per beat
        if len(pm.get_beats()) >= 2:
            seconds_per_beat = pm.get_beats()[1] - pm.get_beats()[0]
        else:
            seconds_per_beat = 0.5
        if len(pm.get_downbeats()) >= 2:
            seconds_per_bar = pm.get_downbeats()[1] - pm.get_downbeats()[0]
        else:
            seconds_per_bar = 2.0

        # Defines the end time of the plot in seconds
        if self._plot_bar_range_stop is not None:
            plot_end_time = self._plot_bar_range_stop * seconds_per_bar
        else:
            # Calculates the plot start and end time, the start time can start after
            # notes or truncate notes if the plot is too long (we left truncate the
            # plot with the bounds)
            # The plot start and plot end are a multiple of seconds per bar (closest
            # smaller value for the start time, closest higher value for the end time)
            plot_end_time = int((last_note_end) / seconds_per_bar) * seconds_per_bar
            # If the last note end is exactly on a multiple of seconds per bar,
            # we don't start a new one
            is_on_bar = math.isclose(last_note_end % seconds_per_bar, seconds_per_bar)
            is_on_bar_exact = math.isclose(last_note_end % seconds_per_bar, 0.0)
            if not is_on_bar and not is_on_bar_exact:
                plot_end_time += seconds_per_bar

        # Defines the start time of the plot in seconds
        if self._plot_bar_range_start is not None:
            plot_start_time = self._plot_bar_range_start * seconds_per_bar
        else:
            start_time = int(first_note_start / seconds_per_bar) * seconds_per_bar
            plot_max_length_time = self._plot_max_length_bar * seconds_per_bar
            plot_start_time = max(plot_end_time - plot_max_length_time, start_time)

        # Draws the vertical bar grid, with a different background color
        # for each bar
        if preset.show_bar:
            bar_count = 0
            for bar_time in pm.get_downbeats():
                fill_alpha_index = bar_count % len(self._bar_fill_alphas)
                fill_alpha = self._bar_fill_alphas[fill_alpha_index]
                box = BoxAnnotation(left=bar_time,
                                    right=bar_time + seconds_per_bar,
                                    fill_color="gray",
                                    fill_alpha=fill_alpha,
                                    line_color="black",
                                    line_width=2,
                                    line_alpha=0.5,
                                    level="underlay")
                plot.add_layout(box)
                bar_count += 1

        # Draws the vertical beat grid, those are only grid lines
        if preset.show_beat:
            for beat_time in pm.get_beats():
                box = BoxAnnotation(left=beat_time,
                                    right=beat_time + seconds_per_beat,
                                    fill_color=None,
                                    line_color="black",
                                    line_width=1,
                                    line_alpha=0.4,
                                    level="underlay")
                plot.add_layout(box)

        # Configure x axis
        plot.xaxis.bounds = (plot_start_time, plot_end_time)
        plot.xaxis.axis_label = "time (SEC)"
        plot.xaxis.axis_label_text_font_size = preset.axis_label_text_font_size
        plot.xaxis.ticker = bokeh.models.SingleIntervalTicker(interval=1)
        plot.xaxis.major_tick_line_alpha = 0.9
        plot.xaxis.major_tick_line_width = 1
        plot.xaxis.major_tick_out = preset.axis_x_major_tick_out
        plot.xaxis.minor_tick_line_alpha = 0
        plot.xaxis.major_label_text_font_size = preset.label_text_font_size
        plot.xaxis.major_label_text_font_style = preset.label_text_font_style

        # Configure y axis
        plot.yaxis.bounds = (pitch_min, pitch_max + 1)
        plot.yaxis.axis_label = "pitch (MIDI)"
        plot.yaxis.axis_label_text_font_size = preset.axis_label_text_font_size
        plot.yaxis.ticker = bokeh.models.SingleIntervalTicker(interval=1)
        plot.yaxis.major_label_text_alpha = 0
        plot.yaxis.major_tick_line_alpha = 0.9
        plot.yaxis.major_tick_line_width = 1
        plot.yaxis.major_tick_out = preset.axis_y_major_tick_out
        plot.yaxis.minor_tick_line_alpha = 0
        plot.yaxis.axis_label_standoff = preset.axis_y_label_standoff
        plot.outline_line_width = 1
        plot.outline_line_alpha = 1
        plot.outline_line_color = "black"

        # The x grid is deactivated because is draw by hand (see x grid code)
        plot.xgrid.grid_line_color = None

        # The y grid is deactivated because is draw by hand (see y grid code)
        plot.ygrid.grid_line_color = None

        # Configure the plot size and range
        if self._plot_title is None:
            plot_title_text = "Visual MIDI (%s QPM, %s/%s)" % (
                str(int(qpm)), time_signature.numerator, time_signature.denominator)
        else:
            plot_title_text = self._plot_title
        
        plot.title = Title(text=plot_title_text,
                           text_font_size=preset.title_text_font_size)
        plot.plot_width = preset.plot_width
        if preset.row_height:
            plot.plot_height = pitch_range * preset.row_height
        else:
            plot.plot_height = preset.plot_height
        plot.x_range = Range1d(plot_start_time, plot_end_time)
        plot.y_range = Range1d(pitch_min, pitch_max + 1)
        plot.min_border_right = 50

        if self._live_reload and preset.stop_live_reload_button:
            callback = CustomJS(code="clearInterval(liveReloadInterval)")
            button = Button(label="stop live reload")
            button.js_on_click(callback)
            layout = column(button, plot)
        else:
            layout = column(plot)

        return layout

    def save(self, pm: PrettyMIDI, filepath: str):

0 Source : classes.py
with GNU General Public License v3.0
from lucasbellinaso

  def __init__(self, Ts):
    from ipywidgets import Dropdown, Checkbox, BoundedFloatText, Button, Layout, Text, Label

    LayS = Layout(display='flex', align_items='stretch', width='50px')
    LayM = Layout(display='flex', align_items='stretch', width='110px')
    LayL = Layout(display='flex', align_items='stretch', width='300px')

    self.Ts = Ts
    self.relatOrderC = 0
    self.oldPZType = ''
    self.freq0_Hz = 100 if self.Ts in [0, None] else 0.1/self.Ts
    self.fNy_Hz = 1e6 if self.Ts in [0, None] else 0.5/self.Ts
    self.ENwgt = Checkbox(value=False, description='', disabled=False, indent=False, layout = LayS)
    self.ENwgt.observe(self.enable_disable_PZ, names='value')
    self.TYwgt = Dropdown( options=['','integrator', 'real pole', 'complex pole',
                                   'differentiator', 'real zero', 'complex zero'],
                           value='', description='',  disabled=True, layout = LayM)
    self.TYwgt.observe(self.change_PZtype, names='value')
    self.Fwgt = BoundedFloatText( value=self.freq0_Hz,  min=1e-3, max = self.fNy_Hz,
                                 continuous_update=True, step=1e-2,
                                 description='', disabled=True, layout = LayM)
    self.Fwgt.observe(self.change_freqOrCsi, names='value')
    self.CSIwgt = BoundedFloatText( value=self.csi0,  min=0, max=0.999, continuous_update=True,
                                step=1e-3,  description='', disabled=True,  layout = LayM)
    self.CSIwgt.observe(self.change_freqOrCsi, names='value')
    self.SETwgt = Button(description='Set',  disabled=True,
                        button_style='', # 'success', 'info', 'warning', 'danger' or ''
                        tooltip='Set', icon='check',
                        layout = Layout(display='flex', align_items='stretch', width='65px')) 
    self.SETwgt.on_click(self.set_button_on_click)
    self.SETwgt.observe(self.set_button_changes_status, names='button_style')

    self.TXTwgt = Label(description='', disabled = True, layout = LayL)
    from numpy import array
    self.PZnum, self.PZden = array([1]), array([1])
    self.Zeros, self.Poles = array([]), array([])

  def enable_disable_PZ(self, dict_observe):

0 Source : classes.py
with GNU General Public License v3.0
from lucasbellinaso

  def __init__(self, num, den, dt = 0, start_configWgt = False, quantity_PZs = 4):
    from numpy import arange, real, log, round, array
    super().__init__(num,den,dt)
    self.Poles = self.pole()
    self.Zeros = self.zero()
    self._update_num_norm_den_norm()
    self._update_Kdcgain()
    self.set_by_zpk_minreal(self.Zeros,self.Poles, self.Kdcgain)
    #print(f'1) SZeros = {self.SZeros} \n SPoles = {self.SPoles}')

    if start_configWgt:  #initialization
      self.PZwidgets = []
      #Create ipywidgets layout and events:
      from ipywidgets import VBox, Label, HBox, FloatSlider, Button, HTML, Layout
      from control import db2mag
      ENBox, TYBox, FBox = [Label('Enable')], [Label('Type')], [Label('Frequency (Hz)')]
      CSIBox = [Label('ζ (damping ratio)')]
      self.SETBox =  [Button(description='Set All',  disabled=False, button_style='', tooltip='Set', icon='check',
                 layout = Layout(display='flex', align_items='stretch', width='65px')) ]
      TXTBox = [Label('Transfer Function')]

      for q in range(quantity_PZs):
          PoleOrZeroClass.relatOrderC = 0
          self.PZwidgets.append(PoleOrZeroClass(self.dt))
          ENBox.append(self.PZwidgets[q].ENwgt)
          TYBox.append(self.PZwidgets[q].TYwgt)
          FBox.append(self.PZwidgets[q].Fwgt)
          CSIBox.append(self.PZwidgets[q].CSIwgt)
          self.SETBox.append(self.PZwidgets[q].SETwgt)
          TXTBox.append(self.PZwidgets[q].TXTwgt)

      minCGainIndB, maxCGainIndB, CGainStepIndB = -80, 80, 0.5
      self.kvectdB = list(arange(minCGainIndB,maxCGainIndB, CGainStepIndB ))
      self.kvect = list(db2mag( array(self.kvectdB)))
      self.dKdcgain = 1
      self.CgainInDBInteract = FloatSlider(value=0, min=minCGainIndB, 
                                       max=maxCGainIndB, step=CGainStepIndB, 
                                       layout=Layout(width='410px',display='flex', align_items='stretch'),
                                       description = '',
                                       #description = '|G  <  sub>c < /sub>| dB:',
                                       continuous_update=True)
      self.ControllerName = (f"G < sub>c < /sub>({'s' if self.dt in {0,None} else 'z'}) = 1")
      self.ControllerText = HTML(value = self.ControllerName,
                                 layout=Layout(width='450px',display='flex', align_items='stretch'))
      self.Appwidget = VBox([HBox([VBox(ENBox),VBox(TYBox),VBox(FBox),VBox(CSIBox),VBox(self.SETBox),VBox(TXTBox)]),
                           HBox([HTML(r'|G < sub>c < /sub>| dB:',layout=Layout(width='50px',display='flex', align_items='flex-start')),
                                 self.CgainInDBInteract, self.ControllerText])   ]  )
      
      #Put given controller to Widget:
      self._init_PZwidgets_by_given_controller()
      self.print_to_PZwidgets()
      if len(self.SPoles)>=1: self.SETBox[0].button_style = 'success'

      #Define events:
      self.CgainInDBInteract.observe(self.set_Kdcgain_by_PZwidgets,'value')
      for q in range(len(self.PZwidgets)):
        self.PZwidgets[q].SETwgt.observe(self.set_PZs_from_PZwidgets, names='button_style')
        self.PZwidgets[q].ENwgt.observe(self.enable_change_clear_set_all, names='value')
      self.SETBox[0].on_click(self.set_all_on_click)

  def print_latex(self,latex_raw_equation):

0 Source : classes.py
with GNU General Public License v3.0
from lucasbellinaso

  def __init__(self, tmax_s = 10, dt_s = 1e-5, freq0_Hz = 1, discrete=False, quantity_disturbances = 4):
    from ipywidgets import BoundedFloatText, HBox, VBox, Layout, Label, Dropdown, Checkbox, Button, Text
    from numpy import array

    self.waveVec_dict = {'t_s': array([]), 'r': array([]), 'du': array([]),
                         'dy': array([]), 'dm': array([]), 'u': array([]), 'y':array([])}

    #Requirements:
    self.OShotIn = BoundedFloatText(value = 10, min=0, max=100, continuous_update=False,
                            layout = Layout(width='100px'))
    self.RTimeIn = BoundedFloatText(value = 0.1, min=0, continuous_update=False,
                             layout = Layout(width='100px'))
    self.STimeIn = BoundedFloatText(value = 0.1, min=0, continuous_update=False,
                             layout = Layout(width='100px'))
    self.RequirementsTab = HBox([VBox([Label('Max Overshot (%)'), self.OShotIn  ])  ,
                           VBox([Label('Max Rise Time (s)'), self.RTimeIn  ]) ,
                           VBox([Label('Max Settling Time (s)'), self.STimeIn])] )
    
    #Input signals
    self.DistWgts = []  #DisturbancesWidget
    self.ENbox, self.INbox = [Label('Enable')]         , [Label('Input')]
    self.TYbox, self.Fbox  = [Label('Signal')]         , [Label('Freq (Hz)')]
    self.Tbox,  self.Abox  = [Label('Time points (s)')], [Label('Amplitude points')]
    self.dAdtbox = [Label('Max Ampl/s')]
    self.SETAllButton = Button(description='Set All',  disabled=False, button_style='', tooltip='Set', icon='check',
                                layout=Layout(align_items='stretch', width='65px') )
       
    self.SETbox = [self.SETAllButton]
    self.TXTbox = [Label('Description')]
    for q in range(quantity_disturbances):
        self.DistWgts.append(DisturbancesWidget())
        self.ENbox.append(self.DistWgts[q].ENwgt)
        self.INbox.append(self.DistWgts[q].INwgt)
        self.TYbox.append(self.DistWgts[q].TYwgt)
        self.Fbox.append(self.DistWgts[q].Fwgt)
        self.Tbox.append(self.DistWgts[q].Tvecwgt)
        self.Abox.append(self.DistWgts[q].Avecwgt)
        self.dAdtbox.append(self.DistWgts[q].dAdtwgt)
        self.SETbox.append(self.DistWgts[q].SETwgt)
        self.TXTbox.append(self.DistWgts[q].TXTwgt)
    
    self.TotalTimeWgt = BoundedFloatText(description = 'Total Time (s)',value = tmax_s, 
                      min=0, max=1e6, continuous_update=False, layout = Layout(width='180px'))
    self.StepTimeWgt = BoundedFloatText(description = 'Step Time (s)', value = dt_s, min=0, max=1, continuous_update=False,
                        layout = Layout(width='180px'), disable = discrete)
    self.PrintTimeWgt = BoundedFloatText(description = 'Print Time (s)', value = 0, min=0, max=10, continuous_update=False,
                        layout = Layout(width='180px'))
    self.SetTimeWgt =  Button(description='Set',  disabled=False, button_style='', tooltip='Set', icon='check',
                                layout=Layout(align_items='stretch', width='65px') )
    self.TimeconfigWgt = HBox([self.TotalTimeWgt, self.StepTimeWgt, self.PrintTimeWgt, self.SetTimeWgt])
    self.DistConfigApp = HBox([VBox(self.ENbox),VBox(self.INbox),VBox(self.TYbox),
                         VBox(self.Fbox),VBox(self.Tbox),VBox(self.Abox),
                         VBox(self.dAdtbox),VBox(self.SETbox),VBox(self.TXTbox)])
    self.DisturbSimulationTab = VBox([self.TimeconfigWgt, self.DistConfigApp])
    
    #Define events:
    for q in range(len(self.DistWgts)):
        self.DistWgts[q].SETwgt.observe(self.verify_complete_disturbs, names='button_style')
        self.DistWgts[q].ENwgt.observe(self.enable_change_clear_set_all, names='value')
    self.SETAllButton.on_click(self.set_all_on_click)
    self.SETAllButton.observe(self.set_disturbs_to_SisoApp, names = 'button_style')
    self.SetTimeWgt.on_click(self.set_time_configs_to_App)
    self.set_time_configs_to_App(0)
    self.TotalTimeWgt.observe(self.reset_set_time_button, names =  'value')
    self.StepTimeWgt.observe(self.reset_set_time_button,  names = 'value')
    #Events requirements:
    self.RTimeIn.observe(self.adjust_SettlingTime_requirements,  names = 'value')

  def enable_change_clear_set_all(self,b):

0 Source : classes.py
with GNU General Public License v3.0
from lucasbellinaso

  def buildBokehFigs(self):
    from bokeh.models import ColumnDataSource,Span,Band,Label
    from bokeh.plotting import figure as BkFig
    #BOKEH FIGURES:
    #Vector data:
    self.bodesource = ColumnDataSource( data={'omega':[], 'freqHz': [],
              'magdBT':[],'magT':[],'magdBG':[],'magG': [],'angT':[],'angG':[]})
    self.gpbodesource = ColumnDataSource(data ={'fHz':[],'magdB':[],'angdeg':[]})
    self.gzbodesource = ColumnDataSource(data ={'fHz':[],'magdB':[],'angdeg':[]})
    self.cpbodesource = ColumnDataSource(data ={'fHz':[],'magdB':[],'angdeg':[]})
    self.czbodesource = ColumnDataSource(data ={'fHz':[],'magdB':[],'angdeg':[]})
    self.PM_GMsource = ColumnDataSource( data = {'PMfcHz': [1.,1.],'GMfHz':[2.,2.],
                                 'ylimsmag':[-200,200], 'ylimsang':[-720,720] })
    self.rlocussource = ColumnDataSource(data={'x':[],'y':[],'K':[]})
    self.gprlocussource = ColumnDataSource(data={'x':[],'y':[],'K':[]})
    self.gzrlocussource = ColumnDataSource(data={'x':[],'y':[],'K':[]})
    self.cprlocussource = ColumnDataSource(data={'x':[],'y':[],'K':[]})
    self.czrlocussource = ColumnDataSource(data={'x':[],'y':[],'K':[]})
    self.krlocussource = ColumnDataSource(data={'x':[],'y':[],'K':[]})
    self.stepsource = ColumnDataSource(data={'t_s':[],'stepRYmf':[],'stepUYma':[],'stepRUmf':[]})
    #self.tRespsource = ColumnDataSource(data={'t_s':[],'r':[],'du':[],'dy':[],'dm':[],'u':[],'y':[]})
    self.tRespsource = ColumnDataSource(data=self.CtrAnWgt.waveVec_dict)

    #Shadows:
    MAX_OVERSHOT = 0.01*self.CtrAnWgt.OShotIn.value + 1
    MAX_RISE_TIME, MAX_SETTLING_TIME = self.CtrAnWgt.RTimeIn.value, self.CtrAnWgt.STimeIn.value
    _thetaZ = np.linspace(0,np.pi,100)
    _costh, _sinthN, _sinth = np.cos(_thetaZ), -np.sin(_thetaZ), np.sin(_thetaZ)
    self.shadowsource = ColumnDataSource(
        data={'x_s': [0,1e4],     'ylow': [-1e4,1e4],  'yup': [1e4,1e4],  
            'xn_z': [-1e4,-1], 'xp_z': [1,1e4] , 'zero':[0,0],
            'overshot':[MAX_OVERSHOT, MAX_OVERSHOT], 
            'risetime':[MAX_RISE_TIME,1e4] , 'riselevel':[0.9,0.9],
            'settlingtime':[MAX_SETTLING_TIME,1e4],
            'setlevel1':[0.98,0.98], 'setlevel2':[1.02,1.02]  } )
    self.shadowZsource=ColumnDataSource(
               data = {'x_z':_costh, 'ylow_z':_sinthN, 'yup_z':_sinth, 
                       'ylow': 100*[-1e4], 'yup': 100*[1e4]})

    self.shadows = {
    'rloc_s': Band(base='x_s', lower='ylow', upper='yup', level='underlay',
            source=self.shadowsource, fill_color='lightgrey', line_color='black'),
    'rloc_z1': Band(base='xn_z', lower='ylow', upper='yup', level='underlay', 
            source=self.shadowsource, fill_color='lightgrey'),
    'rloc_z2': Band(base='xp_z', lower='ylow', upper='yup', level='underlay', 
            source=self.shadowsource, fill_color='lightgrey'),
    'rloc_z3': Band(base='x_z', lower='ylow', upper='ylow_z', level='underlay',
           source=self.shadowZsource,fill_color='lightgrey',line_color='black'),
    'rloc_z4': Band(base='x_z', lower='yup_z', upper='yup', level='underlay',
           source=self.shadowZsource,fill_color='lightgrey',line_color='black'),
    'ovsht': Band(base='x_s', lower='overshot', upper='yup', level='underlay',
            source=self.shadowsource,fill_color='lightgrey', visible=True),
    'riset': Band(base='risetime', lower='ylow', upper='riselevel', 
            level='underlay', source=self.shadowsource,fill_color='lightgrey'),
    'sett1': Band(base='settlingtime', lower='riselevel', upper='setlevel1', 
                 level='underlay', source=self.shadowsource,fill_color='lightgrey'),
    'sett2': Band(base='settlingtime', lower='setlevel2', upper='overshot', 
                 level='underlay', source=self.shadowsource,fill_color='lightgrey') }                    

    _TTS_BD1 = [('sys',"$name"),("f","$x Hz"),("mag","$y dB")]
    _TTS_BD2 = [('sys',"$name"),("f","$x Hz"),("ang","$y°")]
    _TTS_RLOC= [("real","@x"),("imag","@y"),('K','@K{0.00 a}')]
    _TTS_TRESP = [('signal', "$name"), ("t", "$x s"), ("value", "$y") ]
    self.figMag = BkFig(title="Bode Magnitude", plot_height=300, plot_width=400,
               toolbar_location="above", tooltips = _TTS_BD1, x_axis_type="log",
               x_axis_label='f (Hz)', y_axis_label='mag (dB)')
    self.figAng =  BkFig(title="Bode Angle", plot_height=300, plot_width=400,
                toolbar_location="above", tooltips = _TTS_BD2, x_axis_type="log",
                x_axis_label='f (Hz)', y_axis_label='ang (°)')
    self.figAng.x_range  = self.figMag.x_range   #same axis
    self.figAng.yaxis.ticker=np.linspace(-720,720,17)
    self.figRLoc=  BkFig(title="Root Locus", plot_height=300, plot_width=400,
                toolbar_location="above", tooltips = _TTS_RLOC,
                x_axis_label='real', y_axis_label='imag')
    #self.figRLoc.hover.line_policy = 'interp'
    self.figTResp = BkFig(title="Step Response", plot_height=300, plot_width=400,
                toolbar_location="above", tooltips = _TTS_TRESP,
                x_axis_label='time (s)', y_axis_label='y') 
    self.figTResp2= BkFig(title="Disturbance Simulation", plot_height=300, plot_width=800, 
                toolbar_location="above", tooltips = _TTS_TRESP,
                x_axis_label='time (s)', y_axis_label='y, r, dy, dm')
 
    self.Bkgrid = bokeh.layouts.layout([[self.figMag, self.figRLoc],
                                        [self.figAng, self.figTResp],
                                        self.figTResp2])


    if self.dt in [None, 0.0]:   #continuous time
      self.figRLoc.add_layout(self.shadows['rloc_s'])
    else:                 #discrete time
        for strkey in ['rloc_z1', 'rloc_z2', 'rloc_z3', 'rloc_z4']:
          self.figRLoc.add_layout(self.shadows[strkey])
        self.Nyquistlimits = Span(location=0.5/self.dt,
                                 dimension='height', line_color='black',
                                 line_dash='dotted', line_width=1)
        self.figMag.add_layout(self.Nyquistlimits)
        self.figAng.add_layout(self.Nyquistlimits)
    for strkey in ['ovsht', 'riset', 'sett1', 'sett2']:
      self.figTResp.add_layout(self.shadows[strkey])
      #self.figTResp2.add_layout(self.shadows[strkey])


    #Bode Diagram:
    bodemagT=self.figMag.line(x='freqHz', y='magdBT',color="blue",line_width=1.5,
                alpha=0.8,name='|T(s)|',legend_label='T(s)',source=self.bodesource)
    bodemagG=self.figMag.line(x='freqHz', y='magdBG',color="green",line_width=1.5, 
                alpha=0.8,name='|Gp(s)|',line_dash='dashed',
                legend_label='Gp(s)',source=self.bodesource)
    bodeangT=self.figAng.line(x='freqHz', y='angT', color="blue", line_width=1.5,
                alpha=0.8, name='∡T(s)', source=self.bodesource)
    bodeangG=self.figAng.line(x='freqHz', y='angG',color="green", line_width=1.5,
                alpha=0.8,name='∡Gp(s)',line_dash='dashed',source=self.bodesource)
    bodeGpmag = self.figMag.x( x='fHz',y='magdB',line_color='blue', size=10,
                 name='Gp poles', source = self.gpbodesource)
    bodeGpang=self.figAng.x(x='fHz',y='angdeg',line_color='blue', size=10,
                 name='Gp poles angle', source = self.gpbodesource)
    bodeGzmag = self.figMag.circle(x='fHz',y='magdB',line_color='blue',size=8,
                 name='Gp zeros',fill_color=None, source = self.gzbodesource)
    bodeGzang=self.figAng.circle(x='fHz',y='angdeg',line_color='blue',size=8,
              name='Gp zeros angle', fill_color=None,source = self.gzbodesource)
    bodeCpmag = self.figMag.x(x='fHz',y='magdB',line_color='red',size=10,
                 name='C poles', source = self.cpbodesource)
    bodeCpang=self.figAng.x(x='fHz',y='angdeg',line_color='red',size=10,
                 name='C poles angle', source = self.cpbodesource)
    bodeCzmag = self.figMag.circle(x='fHz',y='magdB',line_color='red',size=8,
                 name='C zeros', fill_color=None, source = self.czbodesource)
    bodeCzang=self.figAng.circle(x='fHz',y='angdeg',line_color='red',size=8,
                name='C zeros angle',fill_color=None, source = self.czbodesource)
    self.GMSpan = Span(location=1, dimension='height',
                       line_color='black', line_dash='dotted', line_width=1)
    self.PMSpan = Span(location=1, dimension='height',
                       line_color='black', line_dash='dotted', line_width=1)
    self.PMtxt = Label(x=5, y=5, x_units='screen', y_units='screen', 
                         text=' ',  render_mode='css',border_line_color=None,
                        background_fill_color='white',text_font_size = '11px')
    self.GMtxt = Label(x=5, y=20, x_units='screen', y_units='screen', 
                         text=' ',  render_mode='css',border_line_color=None,
                        background_fill_color='white',text_font_size = '11px')
    #self.Clbltxt = Label(x=5, y=20, x_units='screen', y_units='screen', 
    #                     text=' ',  render_mode='css',border_line_color=None,
    #                    background_fill_color='white',text_font_size = '11px')
    #self.Clbltxt.text = 'C(s) = ' if self.dt in [None, 0.0] else 'C(z) = '
    #self.Cgaintxt = Label(x=40, y=20, x_units='screen', y_units='screen', 
    #                     text='K',  render_mode='css',border_line_color=None,
    #                    background_fill_color='white',text_font_size = '11px')
    #self.Cnumtxt = Label(x=100, y=30, x_units='screen', y_units='screen', 
    #                     text='N',  render_mode='css',border_line_color=None,
    #                    background_fill_color='white',text_font_size = '11px')
    #self.Cdentxt = Label(x=100, y=10, x_units='screen', y_units='screen', 
    #                     text='D',  render_mode='css',border_line_color=None,
    #                    background_fill_color='white',text_font_size = '11px')
    self.figMag.add_layout(self.GMSpan), self.figAng.add_layout(self.GMSpan)
    self.figMag.add_layout(self.PMSpan), self.figAng.add_layout(self.PMSpan)
    self.figAng.add_layout(self.PMtxt), self.figAng.add_layout(self.GMtxt)
    #self.figMag.add_layout(self.Clbltxt), self.figMag.add_layout(self.Cgaintxt)
    #self.figMag.add_layout(self.Cnumtxt), self.figMag.add_layout(self.Cdentxt)

    #Root Locus:
    rlocusline = self.figRLoc.dot(x='x',y='y',color='blue',
                                  name='rlocus', source = self.rlocussource)
    rlocusGpoles = self.figRLoc.x(x='x',y='y',color='blue', size=10,
                                name='Gp pole', source = self.gprlocussource)
    rlocusGzeros = self.figRLoc.circle(x='x',y='y',line_color='blue',size=8,
                 name='Gp zero', fill_color=None, source = self.gzrlocussource)
    rlocusCpoles = self.figRLoc.x(x='x',y='y',color='red', size=10,
                                name='C pole', source = self.cprlocussource)
    rlocusCzeros = self.figRLoc.circle(x='x',y='y',line_color='red',size=8,
                 name='C zero', fill_color=None, source = self.czrlocussource)
    rlocusMF = self.figRLoc.square(x='x',y='y', line_color='deeppink',size=8,
                 name='K', fill_color='deeppink', source = self.krlocussource)
    rlocuslinehv = self.figRLoc.line(x='x',y='y',line_alpha=0, 
                                  name='rlocus2', source = self.rlocussource)
    self.figRLoc.hover.renderers=[rlocuslinehv, rlocusGpoles, rlocusGzeros,
                                  rlocusCpoles, rlocusCzeros, rlocusMF]
    #self.figRLoc.hover.mode='mouse'   
    #self.figRLoc.hover.line_policy='next'
    #self.figRLoc.hover.point_policy='snap_to_data'
    self.Stabilitytxt = Label(x=10, y=200, x_units='screen', y_units='screen', 
                         text=' ',  render_mode='css',border_line_color=None,
                        background_fill_color='white',text_font_size = '11px')
    self.figRLoc.add_layout(self.Stabilitytxt)

    #Step response:
    self.figTResp.extra_y_ranges = {'u_range': bokeh.models.Range1d()}
    self.figTResp.add_layout(bokeh.models.LinearAxis(y_range_name="u_range",
                                                     axis_label='u'), 'right')
    self.figTResp.y_range = bokeh.models.Range1d(start = -0.1, end = 1.4)
    #add_graf = self.figTResp.line if self.dt in [None, 0.0] else self.figTResp.dot
    if self.dt in [None, 0.0]:
        stepR2Y=self.figTResp.line(x='t_s', y='stepRYmf',color="blue",line_width=1.5, name='y',
                        legend_label='y (closed loop)',  source=self.stepsource)
        stepU2Y=self.figTResp.line(x='t_s', y='stepUYma',color="green",
               legend_label='y (open loop)', line_dash='dashed', line_width=1.0,
                                name='y (ol)',source=self.stepsource, visible=False)
        stepR2U=self.figTResp.line(x='t_s', y='stepRUmf',color="red",
                       line_width=1.0, name='u',legend_label='u (closed loop)',
            line_dash='dashed', source=self.stepsource, y_range_name = 'u_range', visible=False)
    else:
        stepR2Y=self.figTResp.dot(x='t_s', y='stepRYmf',color="blue",
                                 line_width=1.5, name='y',  size=15,
                        legend_label='y (closed loop)',  source=self.stepsource)
        stepU2Y=self.figTResp.dot(x='t_s', y='stepUYma',color="green", size=15,
                                legend_label='y (open loop)', line_width=1.0,
                                name='y (ol)',source=self.stepsource, visible=False)
        stepR2U=self.figTResp.dot(x='t_s', y='stepRUmf',color="red", size=15,
                       line_width=1.0, name='u',legend_label='u (closed loop)',
                       source=self.stepsource, y_range_name = 'u_range', visible=False)
    self.figTResp.legend.location = 'bottom_right'
    self.figTResp.legend.click_policy = 'hide'

    #Disturbances response:
    self.figTResp2.extra_y_ranges = {'u_range': bokeh.models.Range1d()}
    self.figTResp2.add_layout(bokeh.models.LinearAxis(y_range_name="u_range",
                                                     axis_label='u, du'), 'right')
    self.figTResp2.y_range = bokeh.models.Range1d(start = -0.1, end = 1.4)
    if self.dt in [None, 0.0]:
        tRespY=self.figTResp2.line(x='t_s', y='y',color="blue", line_width=1.5, name='y',
                        legend_label='y',  source=self.tRespsource)
        tRespU=self.figTResp2.line(x='t_s', y='u',color="red", legend_label='u', line_width=1.5,
                      name='u',source=self.tRespsource, y_range_name = 'u_range', visible=False)
        tRespDU=self.figTResp2.line(x='t_s', y='du',color="indianred", line_width=1.0, name='du',legend_label='du',
                                    line_dash='dashed', source=self.tRespsource, y_range_name = 'u_range', visible=False)
        tRespR=self.figTResp2.line(x='t_s', y='r',color="green", line_width=1.0, name='r',legend_label='r',
                                  line_dash='dashed', source=self.tRespsource)
        tRespDY=self.figTResp2.line(x='t_s', y='dy',color="deepskyblue", line_width=1.0, name='dy',legend_label='dy',
                                    line_dash='dashed', source=self.tRespsource, visible=False)
        tRespDM=self.figTResp2.line(x='t_s', y='dm',color="lime", line_width=1.0, name='dm',legend_label='dm',
                                    line_dash='dashed', source=self.tRespsource, visible=False)
    else:
        tRespY=self.figTResp2.dot(x='t_s', y='y',color="blue", line_width=1.5, size=15, name='y',
                        legend_label='y',  source=self.tRespsource)
        tRespU=self.figTResp2.dot(x='t_s', y='u',color="red", legend_label='u', line_width=1.5, size=15,
                      name='u',source=self.tRespsource, y_range_name = 'u_range', visible=False)
        tRespDU=self.figTResp2.dot(x='t_s', y='du',color="indianred", line_width=1.0, name='du',legend_label='du',
                              size=15, line_dash='dashed', source=self.tRespsource, y_range_name = 'u_range', visible=False)
        tRespR=self.figTResp2.dot(x='t_s', y='r',color="green", line_width=1.0, name='r',legend_label='r',size=15,
                                  line_dash='dashed', source=self.tRespsource)
        tRespDY=self.figTResp2.dot(x='t_s', y='dy',color="deepskyblue", line_width=1.0, name='dy',legend_label='dy',
                                size=15,line_dash='dashed', source=self.tRespsource, visible=False)
        tRespDM=self.figTResp2.dot(x='t_s', y='dm',color="lime", line_width=1.0, name='dm',legend_label='dm',
                               size=15, line_dash='dashed', source=self.tRespsource, visible=False)
    self.figTResp2.legend.location = 'bottom_right'
    self.figTResp2.legend.click_policy = 'hide'

  def updateTFAndBokeh(self,b):

0 Source : bokeh_crossplot.py
with Apache License 2.0
from OpendTect

    def _init_markers(self):
        if not self.marker_props:
            self.marker_props = {'style': {'line_width': 2, 'line_dash': 'solid', 'line_color': 'red'}}
        markers = self.well.getMarkers().data
        mrkprops = {}
        mrkprops.update(self.marker_props['style'])
        for (name,depth,color) in zip( markers['name'],markers['depth'],markers['color']):
            mrkprops['line_color'] = color
            xr = self.datatrack.x_range
            self.marker_props[name] = {'Line': bm.Arrow(end=None,x_start=xr.start,y_start=depth,
                                                        x_end=xr.end,y_end=depth,**mrkprops,
                                                        visible=False),
                                       'Label': bm.Label(x=xr.start,y=depth,text=name,
                                                         text_color=color,render_mode='canvas',
                                                         text_font_size='8pt',visible=False)
                                      }
            self.datatrack.add_layout(self.marker_props[name]['Line'])
            self.datatrack.add_layout(self.marker_props[name]['Label'])

    def resetCB(self,ev):

0 Source : outputs.py
with MIT License
from PSLmodels

def liability_plot(df_base, df_reform, span, mtr_opt):
    df_base = ColumnDataSource(df_base)
    df_reform = ColumnDataSource(df_reform)
    tools = "pan, zoom_in, zoom_out, reset"
    fig = figure(plot_width=600, plot_height=500,
                 x_range=(-10000, 300000), y_range=(-20000, 100000), tools=tools, active_drag="pan")
    fig.yaxis.axis_label = "Tax Liabilities"
    fig.yaxis.formatter = NumeralTickFormatter(format="$0,000")

    filer_income = Span(location=span, dimension='height',
                        line_color='black', line_dash='dotted', line_width=1.5)
    fig.add_layout(filer_income)
    label_format = f'{span:,}'
    filer_income_label = Label(x=span, y=25, y_units='screen', x_offset=10, text="{}: $".format(mtr_opt) + label_format,
                               text_color='#303030', text_font="arial", text_font_style="italic", text_font_size="10pt")
    fig.add_layout(filer_income_label)
    axis = Span(location=0, dimension='width',
                line_color='#bfbfbf', line_width=1.5)
    fig.add_layout(axis)

    iitax_base = fig.line(x="Axis", y="Individual Income Tax", line_color='#2b83ba', muted_color='#2b83ba',
                          line_width=2, legend_label="Individual Income Tax Liability", muted_alpha=0.1, source=df_base)
    payroll_base = fig.line(x="Axis", y="Payroll Tax", line_color='#abdda4', muted_color='#abdda4',
                            line_width=2, legend_label='Payroll Tax Liability', muted_alpha=0.1, source=df_base)

    iitax_reform = fig.line(x="Axis", y="Individual Income Tax", line_color='#2b83ba', muted_color='#2b83ba',
                            line_width=2, line_dash='dashed', legend_label="Individual Income Tax Liability", muted_alpha=0.1, source=df_reform)
    payroll_reform = fig.line(x="Axis", y="Payroll Tax", line_color='#abdda4', muted_color='#abdda4',
                              line_width=2, line_dash='dashed', legend_label='Payroll Tax Liability', muted_alpha=0.1, source=df_reform)

    iitax_base.muted = False
    payroll_base.muted = False
    iitax_reform.muted = False
    payroll_reform.muted = False

    plot_js = """
    object1.visible = toggle.active
    object2.visible = toggle.active
    """
    base_callback = CustomJS(code=plot_js, args={})
    base_toggle = Toggle(label="Base (Solid)", button_type="default",
                         active=True)
    base_callback.args = {"toggle": base_toggle, "object1": iitax_base,
                          "object2": payroll_base}
    base_toggle.js_on_change('active', base_callback)

    reform_callback = CustomJS(code=plot_js, args={})
    reform_toggle = Toggle(label="Reform (Dashed)", button_type="default",
                           active=True)
    reform_callback.args = {"toggle": reform_toggle, "object1": iitax_reform,
                            "object2": payroll_reform}
    reform_toggle.js_on_change('active', reform_callback)

    fig.xaxis.formatter = NumeralTickFormatter(format="$0,000")
    fig.xaxis.axis_label = mtr_opt
    fig.xaxis.minor_tick_line_color = None

    fig.legend.click_policy = "mute"

    layout = column(fig, row(base_toggle, reform_toggle))

    data = json_item(layout)

    outputs = {
        "media_type": "bokeh",
        "title": "Tax Liabilities by {} (Holding Other Inputs Constant)".format(mtr_opt),
        "data": data
    }

    return outputs


def rate_plot(df_base, df_reform, span, mtr_opt):

0 Source : outputs.py
with MIT License
from PSLmodels

def rate_plot(df_base, df_reform, span, mtr_opt):
    df_base = ColumnDataSource(df_base)
    df_reform = ColumnDataSource(df_reform)
    tools = "pan, zoom_in, zoom_out, reset"
    fig = figure(plot_width=600, plot_height=500,
                 x_range=(-10000, 300000), y_range=(-0.3, 0.5), tools=tools, active_drag="pan")
    fig.yaxis.axis_label = "Tax Rate"
    fig.yaxis.formatter = NumeralTickFormatter(format="0%")

    filer_income = Span(location=span, dimension='height',
                        line_color='black', line_dash='dotted', line_width=1.5)
    fig.add_layout(filer_income)
    label_format = f'{span:,}'
    filer_income_label = Label(x=span, y=25, y_units='screen', x_offset=10, text="{}: $".format(mtr_opt) + label_format,
                               text_color='#303030', text_font="arial", text_font_style="italic", text_font_size="10pt")
    fig.add_layout(filer_income_label)
    axis = Span(location=0, dimension='width',
                line_color='#bfbfbf', line_width=1.5)
    fig.add_layout(axis)

    iitax_atr_base = fig.line(x="Axis", y="IATR", line_color='#2b83ba', muted_color='#2b83ba',
                              line_width=2, legend_label="Income Tax Average Rate", muted_alpha=0.1, source=df_base)
    payroll_atr_base = fig.line(x="Axis", y="PATR", line_color='#abdda4', muted_color='#abdda4',
                                line_width=2, legend_label='Payroll Tax Average Rate', muted_alpha=0.1, source=df_base)
    iitax_mtr_base = fig.line(x="Axis", y="Income Tax MTR", line_color='#fdae61', muted_color='#fdae61',
                              line_width=2, legend_label="Income Tax Marginal Rate", muted_alpha=0.1, source=df_base)
    payroll_mtr_base = fig.line(x="Axis", y="Payroll Tax MTR", line_color='#d7191c', muted_color='#d7191c',
                                line_width=2, legend_label='Payroll Tax Marginal Rate', muted_alpha=0.1, source=df_base)

    iitax_atr_reform = fig.line(x="Axis", y="IATR", line_color='#2b83ba', muted_color='#2b83ba', line_width=2,
                                line_dash='dashed', legend_label="Income Tax Average Rate", muted_alpha=0.1, source=df_reform)
    payroll_atr_reform = fig.line(x="Axis", y="PATR", line_color='#abdda4', muted_color='#abdda4', line_width=2,
                                  line_dash='dashed', legend_label='Payroll Tax Average Rate', muted_alpha=0.1, source=df_reform)
    iitax_mtr_reform = fig.line(x="Axis", y="Income Tax MTR", line_color='#fdae61', muted_color='#fdae61',
                                line_width=2, line_dash='dashed', legend_label="Income Tax Marginal Rate", muted_alpha=0.1, source=df_reform)
    payroll_mtr_reform = fig.line(x="Axis", y="Payroll Tax MTR", line_color='#d7191c', muted_color='#d7191c',
                                  line_width=2, line_dash='dashed', legend_label='Payroll Tax Marginal Rate', muted_alpha=0.1, source=df_reform)

    iitax_atr_base.muted = False
    iitax_mtr_base.muted = True
    payroll_atr_base.muted = True
    payroll_mtr_base.muted = True
    iitax_atr_reform.muted = False
    iitax_mtr_reform.muted = True
    payroll_atr_reform.muted = True
    payroll_mtr_reform.muted = True

    plot_js = """
    object1.visible = toggle.active
    object2.visible = toggle.active
    object3.visible = toggle.active
    object4.visible = toggle.active
    """
    base_callback = CustomJS(code=plot_js, args={})
    base_toggle = Toggle(label="Base (Solid)", button_type="default",
                         active=True)
    base_callback.args = {"toggle": base_toggle, "object1": iitax_atr_base,
                          "object2": payroll_atr_base, "object3": iitax_mtr_base,
                          "object4": payroll_mtr_base}
    base_toggle.js_on_change('active', base_callback)

    reform_callback = CustomJS(code=plot_js, args={})
    reform_toggle = Toggle(label="Reform (Dashed)", button_type="default",
                           active=True)
    reform_callback.args = {"toggle": reform_toggle, "object1": iitax_atr_reform,
                            "object2": payroll_atr_reform, "object3": iitax_mtr_reform,
                            "object4": payroll_mtr_reform}
    reform_toggle.js_on_change('active', reform_callback)

    fig.xaxis.formatter = NumeralTickFormatter(format="$0,000")
    fig.xaxis.axis_label = mtr_opt
    fig.xaxis.minor_tick_line_color = None

    fig.legend.click_policy = "mute"

    layout = column(fig, row(base_toggle, reform_toggle))

    data = json_item(layout)

    outputs = {
        "media_type": "bokeh",
        "title": "Tax Rates by {} (Holding Other Inputs Constant)".format(mtr_opt),
        "data": data
    }

    return outputs


def credit_plot(df_base, df_reform, span, mtr_opt):

0 Source : outputs.py
with MIT License
from PSLmodels

def credit_plot(df_base, df_reform, span, mtr_opt):
    df_base = ColumnDataSource(df_base)
    df_reform = ColumnDataSource(df_reform)
    tools = "pan, zoom_in, zoom_out, reset"
    fig = figure(plot_width=600, plot_height=500, x_range=(
        -2500, 70000), tools=tools, active_drag="pan")

    filer_income = Span(location=span, dimension='height',
                        line_color='black', line_dash='dotted', line_width=1.5)
    fig.add_layout(filer_income)
    label_format = f'{span:,}'
    filer_income_label = Label(x=span, y=45, y_units='screen', x_offset=10, text="{}: $".format(mtr_opt) + label_format,
                               text_color='#303030', text_font="arial", text_font_style="italic", text_font_size="10pt")
    fig.add_layout(filer_income_label)
    axis = Span(location=0, dimension='width',
                line_color='#bfbfbf', line_width=1.5)
    fig.add_layout(axis)

    eitc_base = fig.line(x="Axis", y="EITC", line_color='#2b83ba', muted_color='#2b83ba',
                         line_width=2, legend_label="Earned Income Tax Credit", muted_alpha=0.1, source=df_base)
    ctc_base = fig.line(x="Axis", y="CTC", line_color='#abdda4', muted_color='#abdda4',
                        line_width=2, legend_label='Nonrefundable Child Tax Credit', muted_alpha=0.1, source=df_base)
    ctc_refund_base = fig.line(x="Axis", y="CTC Refundable", line_color='#fdae61', muted_color='#fdae61',
                               line_width=2, legend_label='Refundable Child Tax Credit', muted_alpha=0.1, source=df_base)
    cdcc_base = fig.line(x="Axis", y="Child care credit", line_color='#d7191c', muted_color='#d7191c',
                         line_width=2, legend_label='Child and Dependent Care Credit', muted_alpha=0.1, source=df_base)

    eitc_reform = fig.line(x="Axis", y="EITC", line_color='#2b83ba', muted_color='#2b83ba', line_width=2,
                           line_dash='dashed', legend_label="Earned Income Tax Credit", muted_alpha=0.1, source=df_reform)
    ctc_reform = fig.line(x="Axis", y="CTC", line_color='#abdda4', muted_color='#abdda4', line_width=2,
                          line_dash='dashed', legend_label='Nonrefundable Child Tax Credit', muted_alpha=0.1, source=df_reform)
    ctc_refund_reform = fig.line(x="Axis", y="CTC Refundable", line_color='#fdae61', muted_color='#fdae61',
                                 line_width=2, line_dash='dashed', legend_label='Refundable Child Tax Credit', muted_alpha=0.1, source=df_reform)
    cdcc_reform = fig.line(x="Axis", y="Child care credit", line_color='#d7191c', muted_color='#d7191c', line_width=2,
                           line_dash='dashed', legend_label='Child and Dependent Care Credit', muted_alpha=0.1, source=df_reform)

    ctc_base.muted = True
    ctc_refund_base.muted = True
    cdcc_base.muted = True
    ctc_reform.muted = True
    ctc_refund_reform.muted = True
    cdcc_reform.muted = True

    plot_js = """
    object1.visible = toggle.active
    object2.visible = toggle.active
    object3.visible = toggle.active
    object4.visible = toggle.active
    """
    base_callback = CustomJS(code=plot_js, args={})
    base_toggle = Toggle(label="Base (Solid)", button_type="default",
                         active=True)
    base_callback.args = {"toggle": base_toggle, "object1": eitc_base,
                          "object2": cdcc_base, "object3": ctc_base,
                          "object4": ctc_refund_base}
    base_toggle.js_on_change('active', base_callback)

    reform_callback = CustomJS(code=plot_js, args={})
    reform_toggle = Toggle(label="Reform (Dashed)", button_type="default",
                           active=True)
    reform_callback.args = {"toggle": reform_toggle, "object1": eitc_reform,
                            "object2": cdcc_reform, "object3": ctc_reform,
                            "object4": ctc_refund_reform}
    reform_toggle.js_on_change('active', reform_callback)

    fig.yaxis.formatter = NumeralTickFormatter(format="$0,000")
    fig.yaxis.axis_label = "Tax Credits"
    fig.xaxis.formatter = NumeralTickFormatter(format="$0,000")
    fig.xaxis.axis_label = mtr_opt
    fig.xaxis.minor_tick_line_color = None

    fig.legend.click_policy = "mute"

    layout = column(fig, row(base_toggle, reform_toggle))

    data = json_item(layout)

    outputs = {
        "media_type": "bokeh",
        "title": "Tax Credits by {} (Holding Other Inputs Constant)".format(mtr_opt),
        "data": data
    }

    return outputs

0 Source : plots.py
with Apache License 2.0
from scaleoutsystems

    def make_single_node_plot(self):
        """
        Plot single node graph with reducer

        :return: Bokeh plot with the graph
        :rtype: bokeh.plotting.figure.Figure
        """
        HOVER_TOOLTIPS = [
            ("Name", "@name"),
            ("Role", "@role"),
            ("Status", "@status"),
            ("Id", "@index"),
            ]
        
        G = networkx.Graph()
        G.add_node("reducer", adjusted_node_size=20, role='reducer',
                    status='active', 
                    name='reducer',
                    color_by_this_attribute=Spectral8[0])
        network_graph = from_networkx(G, networkx.spring_layout)
        network_graph.node_renderer.glyph = Circle(size=20, fill_color = Spectral8[0])
        network_graph.node_renderer.hover_glyph = Circle(size=20, fill_color='white',
                                                         line_width=2)
        network_graph.node_renderer.selection_glyph = Circle(size=20,
                                                             fill_color='white', line_width=2)
        plot = figure(tooltips=HOVER_TOOLTIPS, tools="pan,wheel_zoom,save,reset", active_scroll='wheel_zoom',
                    width=725, height=460, sizing_mode='stretch_width',
                    x_range=Range1d(-1.5, 1.5), y_range=Range1d(-1.5, 1.5))
        
        plot.renderers.append(network_graph)

        plot.axis.visible = False
        plot.grid.visible = False
        plot.outline_line_color = None

        label = Label(x=0, y=0, text='reducer',
                     background_fill_color='#4bbf73', text_font_size='15px',
                     background_fill_alpha=.7, x_offset=-20, y_offset=10)
        
        plot.add_layout(label)
        return plot
        

        

    def make_netgraph_plot(self, df, df_nodes):

0 Source : metainfo_plots.py
with MIT License
from skiniry

def rust_dwell(codon_count_dict,short_code,background_col,title_size, axis_label_size, subheading_size,marker_size):
	aa_color_dict = {"gly":"white",
			"arg":"blue",
			"ser":"green",
			"trp":"lightgreen",
			"cys":"white",
			"glu":"red",
			"asp":"red",
			"lys":"blue",
			"asn":"green",
			"gln":"green",
			"his":"blue",
			"tyr":"lightgreen",
			"ala":"grey",
			"thr":"green",
			"pro":"white",
			"val":"grey",
			"met":"grey",
			"ile":"grey",
			"leu":"grey",
			"phe":"lightgreen"}
	
	min_count = float(min(codon_count_dict.values()))+0.000001
	max_count = float(max(codon_count_dict.values()))
	max_rust_ratio = (max_count/(min_count))
	aa_dict = {"gly":["GGT","GGC","GGA","GGG"],
			   "arg":["AGA","AGG","CGT","CGC","CGA","CGG"],
			   "ser":["AGT","AGC","TCT","TCC","TCA","TCG"],
			   "trp":["TGG"],
			   "cys":["TGT","TGC"],
			   "glu":["GAA","GAG"],
			   "asp":["GAT","GAC"],
			   "lys":["AAA","AAG"],
			   "asn":["AAT","AAC"],
			   "gln":["CAA","CAG"],
			   "his":["CAT","CAC"],
			   "tyr":["TAT","TAC"],
			   "ala":["GCT","GCC","GCA","GCG"],
			   "thr":["ACT","ACC","ACA","ACG"],
			   "pro":["CCT","CCC","CCA","CCG"],
			   "val":["GTT","GTC","GTA","GTG"],
			   "met":["ATG"],
			   "ile":["ATA","ATT","ATC"],
			   "leu":["CTT","CTC","CTA","CTG","TTA","TTG"],
			   "phe":["TTT","TTC"]}
	avg_dict = {}
	for aa in aa_dict:
		tot = 0.0
		for codon in aa_dict[aa]:
			tot += codon_count_dict[codon]
		avg = tot/len(aa_dict[aa])
		avg_dict[aa] = avg
	sorted_list = sorted(avg_dict.items(), key=lambda x: x[1])
	p = figure(plot_width=1300, plot_height=750, y_axis_label='RUST ratio (relative to min)',title="RUST: Relative codon dwell times ({})".format(short_code),toolbar_location="below",
			   tools = "reset,pan,box_zoom,hover",logo=None)#,y_range=Range1d(bounds=(0, max_rust_ratio)))
	p.y_range = Range1d(0,max_rust_ratio)
	p.x_range = Range1d(0,23)
	p.xaxis.visible = False
	p.title.align="center"
	p.title.text_font_size = "24pt"
	p.xaxis.axis_label_text_font_size = "22pt"
	p.xaxis.major_label_text_font_size = "17pt"
	p.yaxis.axis_label_text_font_size = "22pt"
	p.yaxis.major_label_text_font_size = "17pt"
	p.background_fill_color = background_col
	p.xgrid.grid_line_color = "white"
	p.ygrid.grid_line_color = "white"
	x_vals = []
	y_vals = []
	codons = []
	x_val = 1
	for tup in sorted_list:
		aa = tup[0]
		for codon in aa_dict[aa]:
			codons.append(codon)
			x_vals.append(x_val)
			rust_ratio = (float(codon_count_dict[codon]+0.000001)/min_count)
			y_vals.append(rust_ratio)
			mytext = Label(x=x_val-0.2, y=-10, text=aa,background_fill_color=aa_color_dict[aa],text_font_size="18pt")
			p.add_layout(mytext)
		x_val += 1
	p.legend.label_text_size = "30pt"
	p.scatter(-1,-1,color="red",legend="Acidic")
	p.scatter(-1,-1,color="lightgreen",legend="Aromatic")
	p.scatter(-1,-1,color="green",legend="Polar uncharged")
	p.scatter(-1,-1,color="grey",legend="Aliphatic")
	p.scatter(-1,-1,color="blue",legend="Basic")
	source = ColumnDataSource({'x': x_vals,'y':y_vals,'codons':codons})
	p.scatter('x','y',source=source, color="grey",size=16)
	p.y_range=Range1d(-10, max(y_vals)*1.1)
	hover = p.select(dict(type=HoverTool))
	hover.tooltips = [("Rust ratio", "@y"),
					  ("Codon","@codons")]
	output_file("scatter10k.html", title="RUST: Relative codon dwell times ({})".format(short_code))
	graph = "  <  style>.mpld3-xaxis {{font-size: {0}px;}} .mpld3-yaxis {{font-size: {0}px;}} < /style>".format(marker_size)
	graph += " < div style='padding-left: 55px;padding-top: 22px;'>  < a href='https://trips.ucc.ie/short/{0}' target='_blank' > < button class='button centerbutton' type='submit'> < b>Direct link to this plot < /b> < /button> < /a>  < /div>".format(short_code)
	graph += file_html(p,CDN)
	return graph




def codon_usage(codon_dict,short_code,title_size, axis_label_size, marker_size):

0 Source : riboflask_diff.py
with MIT License
from skiniry

def ribo_vs_rna(ribo_rna_dict,organism,transcriptome,riboseq1,riboseq2,rnaseq1,rnaseq2,background_col,short_code,normalized,filename,no_groups,title_size, axis_label_size, subheading_size,marker_size,ambiguous,gene_list,label):
	#Convert gene_list from string to list
	if gene_list != "":
		gene_list = gene_list.replace(","," ").replace("\t"," ")
		split_list = gene_list.split(" ")
		gene_list = []
		for item in split_list:
			gene_list.append(item.strip(" ").upper())
	x_values = []
	y_values = []
	genes = []
	trans = []
	
	hili_x_values = []
	hili_y_values = []
	hili_genes = []
	hili_trans = []
	for gene in ribo_rna_dict:
		if label == "TE":
			if gene not in gene_list:
				y_values.append(log(ribo_rna_dict[gene]["ribo2"]/ribo_rna_dict[gene]["ribo1"],2))
				x_values.append(log(ribo_rna_dict[gene]["rna2"]/ribo_rna_dict[gene]["rna1"],2))
				genes.append(gene)
				trans.append(ribo_rna_dict[gene]["tran"])
			else:
				hili_y_values.append(log(ribo_rna_dict[gene]["ribo2"]/ribo_rna_dict[gene]["ribo1"],2))
				hili_x_values.append(log(ribo_rna_dict[gene]["rna2"]/ribo_rna_dict[gene]["rna1"],2))
				hili_genes.append(gene)
				hili_trans.append(ribo_rna_dict[gene]["tran"])
		elif label == "Riboseq":
			if gene not in gene_list:
				if ribo_rna_dict[gene]["ribo1"] >= 1:
					y_values.append(log(ribo_rna_dict[gene]["ribo1"],2))
				else:
					y_values.append(0)
				if ribo_rna_dict[gene]["ribo2"] >=  1:
					x_values.append(log(ribo_rna_dict[gene]["ribo2"],2))
				else:
					x_values.append(0)
				genes.append(gene)
				trans.append(ribo_rna_dict[gene]["tran"])
			else:
				if ribo_rna_dict[gene]["ribo1"] >= 1:
					hili_y_values.append(log(ribo_rna_dict[gene]["ribo1"],2))
				else:
					hili_y_values.append(0)
				if ribo_rna_dict[gene]["ribo2"] >= 1:
					hili_x_values.append(log(ribo_rna_dict[gene]["ribo2"],2))
				else:
					hili_x_values.append(0)
				hili_genes.append(gene)
				hili_trans.append(ribo_rna_dict[gene]["tran"])
		elif label == "Rnaseq":
			if gene not in gene_list:
				if ribo_rna_dict[gene]["rna1"] != 0:
					y_values.append(log(ribo_rna_dict[gene]["rna1"],2))
				else:
					y_values.append(0)
				if ribo_rna_dict[gene]["rna2"] != 0:
					x_values.append(log(ribo_rna_dict[gene]["rna2"],2))
				else:
					x_values.append(0)
				genes.append(gene)
				trans.append(ribo_rna_dict[gene]["tran"])
			else:
				if ribo_rna_dict[gene]["rna1"] != 0:
					hili_y_values.append(log(ribo_rna_dict[gene]["rna1"],2))
				else:
					hili_y_values.append(0)
				if ribo_rna_dict[gene]["rna2"] != 0:
					hili_x_values.append(log(ribo_rna_dict[gene]["rna2"],2))
				else:
					hili_x_values.append(0)
				hili_genes.append(gene)
				hili_trans.append(ribo_rna_dict[gene]["tran"])
	source = ColumnDataSource({'x': x_values,'y':y_values,'trans':trans, 'genes':genes})
	if label == "TE":
		p = figure(plot_width=1300, plot_height=1300,x_axis_label="RNA-Seq FC (log2)",  y_axis_label='Ribo-Seq FC (log2)',title="Ribo-Seq FC vs RNA-Seq FC ({})".format(short_code),toolbar_location="below",
			tools = "reset,pan,box_zoom,save,hover,tap")
	elif label == "Riboseq":
		p = figure(plot_width=1300, plot_height=1300,x_axis_label="Ribo-Seq Cond2 count (log2)",  y_axis_label='Ribo-Seq Cond1 count (log2)',title="Ribo-Seq correlation ({})".format(short_code),toolbar_location="below",
			tools = "reset,pan,box_zoom,save,hover,tap")
	elif label == "Rnaseq":
		p = figure(plot_width=1300, plot_height=1300,x_axis_label="RNA-Seq Cond2 count (log2)",  y_axis_label='RNA-Seq Cond1 count (log2)',title="RNA-Seq correlation ({})".format(short_code),toolbar_location="below",
			tools = "reset,pan,box_zoom,save,hover,tap")
	p.title.align="center"
	p.title.text_font_size = title_size
	p.xaxis.axis_label_text_font_size = axis_label_size
	p.xaxis.major_label_text_font_size = marker_size
	p.yaxis.axis_label_text_font_size = axis_label_size
	p.yaxis.major_label_text_font_size = marker_size
	p.background_fill_color = background_col
	p.xgrid.grid_line_color = "#cccccc"
	p.ygrid.grid_line_color = "#cccccc"


	p.scatter('x','y', alpha=0.2,color="black",fill_alpha=1,size=12,source=source,fill_color='grey')
	source = ColumnDataSource({'x':hili_x_values, 'y':hili_y_values, 'trans':hili_trans,'genes':hili_genes})
	p.scatter('x','y', alpha=0.2,color="black",fill_alpha=1,size=12,source=source,fill_color='#4286f4')
	hover = p.select(dict(type=HoverTool))
	hover.mode = 'mouse'
	
	if label == "TE":
		p.line([-8,8], [-8,8], color="#cccccc",line_width=1)
		hover.tooltips = [("Ribo fc", "@y"),("RNA fc","@x"),("Genes","@genes"),("Transcript","@trans")]
	elif label == "Riboseq":
			p.line([0,16], [0,16], color="#cccccc",line_width=1)
			hover.tooltips = [("Ribo Cond 1 count (log2)", "@y"),("Ribo Cond 2 count (log2)","@x"),("Genes","@genes"),("Transcript","@trans")]
			#corr = spearmanr(x_values, y_values)
			pearson_corr = pearsonr(x_values, y_values)
			mytext = Label(x=0.1,y=max(y_values),text="Pearson correlation: {}".format(round(pearson_corr[0],2)),background_fill_color="white",text_font_size="13pt")
			p.add_layout(mytext)
	else:
			p.line([0,16], [0,16], color="#cccccc",line_width=1)
			hover.tooltips = [("Rna-seq Cond 1 count (log2)", "@y"),("Rna-seq Cond 2 count (log2)","@x"),("Genes","@genes"),("Transcript","@trans")]
			hover.tooltips = [("Ribo Cond 1 count (log2)", "@y"),("Ribo Cond 2 count (log2)","@x"),("Genes","@genes"),("Transcript","@trans")]
			#corr = spearmanr(x_values, y_values)
			pearson_corr = pearsonr(x_values, y_values)
			mytext = Label(x=0.1,y=max(y_values),text="Pearson correlation: {}".format(round(pearson_corr[0],2)),background_fill_color="white",text_font_size="13pt")
			p.add_layout(mytext)
	file_string = ""
	label_string="&labels=RIBO-Seq Cond 1,%23007a02_RIBO-Seq Cond 2,%23960000_mRNA-Seq Cond 1,%2374ed76_mRNA-seq Cond 2,%23ff6d6d"
	
	if riboseq1:
		if riboseq1[0] != "":
			for file_id in riboseq1:
				file_string += ("{},".format(file_id))
			file_string += ("%23007a02_")

	if riboseq2:
		if riboseq2[0] != "":
			for file_id in riboseq2:
				file_string += ("{},".format(file_id))
			file_string += ("%23960000_")
	if rnaseq1:
		if rnaseq1[0] != "":
			for file_id in rnaseq1:
				file_string += ("{},".format(file_id))
			file_string += ("%2374ed76_")
	if rnaseq2:
		if rnaseq2[0] != "":
			for file_id in rnaseq2:
				file_string += ("{},".format(file_id))
			file_string += ("%23ff6d6d_")
	# remove the trailing _ in file_string if it's been populated
	if file_string:
		file_string = file_string[:len(file_string)-1]
	if ambiguous == True:
		ambig = "T"
	else:
		ambig = "F"
	url = "http://0.0.0.0:5000/{}/{}/comparison/?files={}{}&transcript=@trans&normalize={}&cov=T&ambig={}&minread=25&maxread=150".format(organism, transcriptome,file_string,label_string,str(normalized)[0],ambig)
	taptool = p.select(type=TapTool)
	taptool.callback = OpenURL(url=url)
	graph = "  <  div style='padding-left: 55px;padding-top: 22px;'> < a href='https://0.0.0.0:5000/short/{0}' target='_blank' > < button class='button centerbutton' type='submit'> < b>Direct link to this plot < /b> < /button> < /a> < br> < a href='https://0.0.0.0:5000/static/tmp/{1}' target='_blank' > < button class='button centerbutton' type='submit'> < b>Download results as csv file < /b> < /button> < /a>  < /div>".format(short_code,filename)
	#graph = " < div style='padding-left: 55px;padding-top: 22px;'> < a href='https://0.0.0.0:5000/short/{0}' target='_blank' > < button class='button centerbutton' type='submit'> < b>Direct link to this plot < /b> < /button> < /a> < br>  < /div>".format(short_code)
	#layout = column(text_input, p)
	graph += file_html(p,CDN)
	return graph






def deseq2_plot(ribo_rna_dict,organism,transcriptome,riboseq1,riboseq2,rnaseq1,rnaseq2,background_col,short_code,normalized,filename,no_groups,title_size, axis_label_size, subheading_size,marker_size,ambiguous,gene_list,label,minzscore):

0 Source : timeseries.py
with MIT License
from SolarArbiter

def _single_quality_bar(flag_name, plot_width, x_range, color, source):
    qfig = figure(sizing_mode='stretch_width',
                  plot_height=30,
                  plot_width=plot_width,
                  x_range=x_range,
                  toolbar_location=None,
                  min_border_bottom=0,
                  min_border_top=0,
                  tools='xpan',
                  x_axis_location=None,
                  y_axis_location=None)
    qfig.ygrid.grid_line_color = None
    qfig.line(x='timestamp', y=flag_name,
              line_width=qfig.plot_height,
              source=source, alpha=0.6,
              line_color=color)
    flag_label = Label(x=5, y=0,
                       x_units='screen', y_units='screen',
                       text=flag_name, render_mode='css',
                       border_line_color=None,
                       background_fill_alpha=0,
                       text_font_size='1em',
                       text_font_style='bold')
    qfig.add_layout(flag_label)
    return qfig


def make_quality_bars(source, plot_width, x_range):