Esempio n. 1
1
def show(sample_size):
    global session
    global scatter_plot
    global source
    global pie_chart_source
    global line_chart_source
    global slider
    DB.__init__(sample_size)
    min_time = DB.min_time()
    max_time = DB.max_time()
    print min_time
    print min_time
    xs, ys, color, time = DB.get_current()
    xs = [xs[i] for i,v in enumerate(time) if time[i] == min_time]
    ys = [ys[i] for i,v in enumerate(time) if time[i] == min_time]
    color = [color[i] for i,v in enumerate(time) if time[i] == min_time]

    time_dict = Counter(time)
    pie_chart_source = ColumnDataSource(data=ChartMath.compute_color_distribution('x', 'y', 'color', color))
    line_chart_source = ColumnDataSource(data=dict(x=[key for key in time_dict], y=[time_dict[key] for key in time_dict]))
    source = ColumnDataSource(data=dict(x=xs, y=ys, color=color))

    scatter_plot = Figure(plot_height=800,
                          plot_width=1200,
                          title="Plot of Voters",
                          tools="pan, reset, resize, save, wheel_zoom",
                          )

    scatter_plot.circle('x', 'y', color='color', source=source, line_width=0, line_alpha=0.001, fill_alpha=0.5, size=15)
    scatter_plot.patches('x', 'y', source=state_source, fill_alpha=0.1, line_width=3, line_alpha=1)

    scatter_plot.x_range.on_change('end', update_coordinates)
    line_chart = Figure(title="Distribution over Time", plot_width=350, plot_height=350)
    line_chart.line(x='x', y='y', source=line_chart_source)
    pie_chart_plot = Figure(plot_height=350,
                            plot_width=350,
                            title="Voter Distribution",
                            x_range=(-1, 1),
                            y_range=(-1, 1))
    pie_chart_plot.wedge(x=0, y=0, source=pie_chart_source, radius=1, start_angle="x", end_angle="y", color="color")
    slider = Slider(start=min_time, end=max_time, value=min_time, step=1, title="Time")

    slider.on_change('value', update_coordinates)
    h = hplot(scatter_plot, vplot(pie_chart_plot, line_chart))
    vplot(slider, h, width=1600, height=1800)
    session = push_session(curdoc())
    session.show()
    #script = autoload_server(scatter_plot, session_id=session.id)
    session.loop_until_closed()
Esempio n. 2
0
def make_plot(cityData):
    # Hover option to make the plot interactive
    hover = HoverTool(
        tooltips=[
            ("GDD", "$y"),
            ("Date", "@dateStr")            
        ]
    )
    TOOLS = [BoxSelectTool(), hover]
    plot = Figure(x_axis_type="datetime", plot_width=1000, title_text_font_size='12pt', tools=TOOLS)
    plot.title = "Accumulated GDD of cities of Canada"
    colors = Spectral11[0:len(cityData)]    
    index = 0
    for src in cityData: 
        plot.line(x='date', y='GDD',source=cityData[src], color=colors[index], line_width=4, legend=src)
        index = index + 1

    plot.border_fill_color = "whitesmoke"
    plot.xaxis.axis_label = "Months"
    plot.yaxis.axis_label = "Accumulated GDD"
    plot.axis.major_label_text_font_size = "10pt"
    plot.axis.axis_label_text_font_size = "12pt"
    plot.axis.axis_label_text_font_style = "bold"
    plot.grid.grid_line_alpha = 0.3
    plot.grid[0].ticker.desired_num_ticks = 12

    return plot
Esempio n. 3
0
    def __plot_control_chart(self, index):
        plot_args = self.__conf.plot_args[index]
        annotations = self.__conf.annotations[index]
        if not annotations:
            annotations = PlotAnnotationContainer()
        plot = Figure(plot_height=500, plot_width=600,
                      x_range=FactorRange(factors=self.__factors,
                                          name='x_factors'))
        plot.toolbar.logo = None
        plot.title.text = 'Control chart'
        hover_tool = self.__create_tooltips()
        plot.add_tools(hover_tool)
        plot.xaxis.major_label_orientation = pi / 4
        plot.xaxis.major_label_standoff = 10
        if not self.__values['_calc_value'].empty:
            if 'color' not in plot_args:
                plot_args['color'] = 'navy'
            if 'alpha' not in plot_args:
                plot_args['alpha'] = 0.5
            self.__values['s_fac'] = self.__factors
            col_ds = ColumnDataSource(self.__values, name='control_data')
            col_ds.js_on_change('data', CustomJS(code="refresh_maps();"))
            plot.circle('s_fac', '_calc_value', source=col_ds, name='circle',
                        **plot_args)
            plot.line('s_fac', '_calc_value', source=col_ds, name='line',
                      **plot_args)
        min_anno, max_anno = annotations.calc_min_max_annotation(
            self.__values['_calc_value'])
        annotations.plot(plot, self.__values['_calc_value'])

        anno_range = max_anno - min_anno
        if anno_range and not isnan(anno_range):
            plot.y_range.start = min_anno - anno_range
            plot.y_range.end = max_anno + anno_range
        return plot
Esempio n. 4
0
def make_plot(cityData):
    
    hover = HoverTool(
        tooltips=[
            ("GDD", "$y"),
            ("Date", "@dateStr")            
        ]
    )
    TOOLS = [BoxSelectTool(), hover]
    plot = Figure(x_axis_type="datetime", plot_width=1000, tools=TOOLS)
    plot.title = "Accumulated GDD of cities of Canada"
    colors = Spectral11[0:len(cityData)]    
    index = 0
    for src in cityData: 
        plot.line(x='date', y='GDD',source=cityData[src], color=colors[index], line_width=4, legend=src)
        index = index + 1
#    plot.quad(top='max', bottom='min', left='left', right='right', color=colors[2], source=src, legend="Record")

    # fixed attributes
    plot.border_fill_color = "whitesmoke"
    plot.xaxis.axis_label = None
    plot.yaxis.axis_label = "Accumulated GDD"
    plot.axis.major_label_text_font_size = "8pt"
    plot.axis.axis_label_text_font_size = "8pt"
    plot.axis.axis_label_text_font_style = "bold"
    plot.grid.grid_line_alpha = 0.3
    plot.grid[0].ticker.desired_num_ticks = 12

    return plot
Esempio n. 5
0
def performance():
    plot = Figure(x_axis_type="datetime", tools="save", toolbar_location=None, plot_width=1000, plot_height=300)
    l1 = plot.line(x="time", y="power_out", source=source_perfomance, line_color="green", name="local")
    plot.add_tools(HoverTool(renderers=[l1]))
    plot.select(dict(type=HoverTool)).tooltips = [("Date", "@hover_time"), ("Performance", "@power_out")]
    l2 = plot.line(x="time", y="avg_perf", source=source_perfomance, line_color="red", name="global")
    plot.x_range = DataRange1d(range_padding=0.0, bounds=None)
    plot.title = "Plant Performance"
    return plot
Esempio n. 6
0
def plotDayOfWeekTimeline(fileName, initData, bokehPlaceholderId='bokehContent'):    

    source = ColumnDataSource(data=initData)
    selectDOW = Select(title="Days:", value="Monday", options=["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"])
    selectUT = Select(title="User Type:", value="All", options=["All", "Subscriber", "Customer"])
    model = dict(source=source, select_dow = selectDOW, select_ut = selectUT)
    plot = Figure(plot_width=1200, plot_height=400, x_axis_type="datetime")
    plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)
    
    callback = CustomJS(args=model, code="""
          var dayOfWeek = select_dow.get('value')
            var userType = select_ut.get('value')
            var xmlhttp;
            xmlhttp = new XMLHttpRequest();
            
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
                    if(xmlhttp.status == 200){
                        var data = source.get('data');
                        var result = JSON.parse(xmlhttp.responseText);
                        var temp=[];
                        
                        for(var date in result.x) {
                            temp.push(new Date(result.x[date]));
                        }
                        
                        data['x'] = temp;
                        data['y'] = result.y;
                        source.trigger('change');
                    }
                    else if(xmlhttp.status == 400) {
                        alert(400);
                    }
                    else {
                        alert(xmlhttp.status);
                    }
                }
            };
        var params = {dow:dayOfWeek, ut:userType};
        url = "/select?" + jQuery.param( params );
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
        """)
        
    selectDOW.callback = callback
    selectUT.callback = callback
    layout = vform(selectDOW, selectUT, plot)
    script, div = components(layout)
    html = readHtmlFile(fileName)
    html = insertScriptIntoHeader(html, script)
    html = appendElementContent(html, div, "div", "bokehContent")

    return html
    
    
Esempio n. 7
0
def timeplot(data):
	#input data is a DataFrame
	time = pd.DatetimeIndex(data['ltime'])
	#String list to store column names from the third column of the dataframe
	columns = []
	for x in data.columns[1:]:
		columns.append(x)
	#change string to float in the data 
	for x in columns[0:(len(columns)-2)]:
		if (type(data[x][0]) is str):
			for i in range(len(data[x])):
				data[x][i] = float(data[x][i].replace(',',''))
	output_notebook()
	y = data[columns[1]]
	x = time
	p = Figure(x_axis_type = 'datetime', title = "TimeSeries Plotting")
	
	source = ColumnDataSource(data=dict(x=x, y=y, d=data))
	#create a new columndatasoure to pass column name to CustomJS
	source2 = ColumnDataSource(data = dict(columns = columns))

	p.line('x', 'y', source = source)
	p.xaxis.axis_label = "Time"
	p.yaxis.axis_label = "Selected Y"
	callback = CustomJS(args = dict(source = source, columns=source2), code="""
				var data = source.get('data');
				var columns = columns.get('data')['columns'];
				var f = cb_obj.get('value');
				y = data['y'];
				console.log('y');
				console.log(y);
				var d = data['d'];
				//get the index of the chosen column from the widget

				for(i = 0; i<columns.length;i++){
					if(f[0]==columns[i]){
					index = i;
					}
				}
				//make the column transpose since the CustomJS
				//takes dataframe as an array of arrays which is 
				//a row of the DataFrame
				for (i = 0; i < d.length; i++) {
					y[i] = d[i][index+1];
				}
				console.log('y');
				console.log(y.length);
				source.trigger('change');
				""")
	
	select = MultiSelect(title="Y_Option:", value=[columns[0]],
							options=columns, callback=callback)
	layout = vform(select, p)
	show(layout)
Esempio n. 8
0
    def __init__(self, N=200):
        self.document = Document()
        self.params = {'amplitude': 1,
                       'frequency': 1,
                       'phase': 0,
                       'offset': 0
                       }
        self.param_limits = {'amplitude': [-5.0, 5.0, 0.2],
                             'frequency': [0.1, 5.1, 0.1],
                             'phase': [0, 2*np.pi, 2*np.pi/50],
                             'offset': [-5.0, 5.0, 0.1]
                             }
        keys = self.params.keys()
        self.selectors = {n: Select(title="Parameter %i" % (n+1),
                                    value=keys[n],
                                    options=keys)
                          for n in range(2)
                          }
        self.sliders = {n: Slider(value=self.params[keys[n]],
                                  start=self.param_limits[keys[n]][0],
                                  end=self.param_limits[keys[n]][1],
                                  step=self.param_limits[keys[n]][2]
                                  )
                        for n in range(2)
                        }
        selection_layout = VBoxForm(children=[VBoxForm(children=[self.selectors[n],
                                                                 self.sliders[n]
                                                                 ]
                                                        ) for n in range(2)
                                              ]
                                    )
        
        for slider in self.sliders.values():
            slider.on_change('value', self.update_sliders)

        self.selector_values = {}
        for num, selector in self.selectors.items():
            selector.on_change('value', self.update_selectors)
            self.selector_values[num] = selector.value
        self.resetting_selectors = False # keeps from updating plot when we update selection

        self.N = N
        self.source = ColumnDataSource()
        self.update_data()

        plot = Figure(plot_height=400, plot_width=400, title="my sine wave",
                      tools="crosshair,pan,reset,resize,save,wheel_zoom",
                      x_range=[0, 4*np.pi], y_range=[-2.5, 2.5]
                      )
        plot.line('x', 'y', source=self.source, line_width=3, line_alpha=0.6)

        self.document.add_root(HBox(selection_layout, plot))
        self.session = push_session(self.document)
def plot():
    # Set up data
    N = 200
    x = np.linspace(0, 4*np.pi, N)
    y = np.sin(x)
    source = ColumnDataSource(data=dict(x=x, y=y))


    # Set up plots
    plot = Figure(plot_height=400, plot_width=400, title="my sine wave",
                  tools="crosshair,pan,reset,resize,save,wheel_zoom",
                  x_range=[0, 4*np.pi], y_range=[-2.5, 2.5])

    plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)


    # Set up widgets
    text = TextInput(title="title", value='my sine wave')
    offset = Slider(title="offset", value=0.0, start=-5.0, end=5.0, step=0.1)
    amplitude = Slider(title="amplitude", value=1.0, start=-5.0, end=5.0)
    phase = Slider(title="phase", value=0.0, start=0.0, end=2*np.pi)
    freq = Slider(title="frequency", value=1.0, start=0.1, end=5.1)


    # Set up callbacks
    def update_title(attrname, old, new):
        plot.title = text.value

    text.on_change('value', update_title)

    def update_data(attrname, old, new):

        # Get the current slider values
        a = amplitude.value
        b = offset.value
        w = phase.value
        k = freq.value

        # Generate the new curve
        x = np.linspace(0, 4*np.pi, N)
        y = a*np.sin(k*x + w) + b

        source.data = dict(x=x, y=y)

    for w in [offset, amplitude, phase, freq]:
        w.on_change('value', update_data)


    # Set up layouts and add to document
    inputs = VBoxForm(children=[text, offset, amplitude, phase, freq])
    fullformat = HBox(children=[inputs, plot], width=800)

    return fullformat, []
Esempio n. 10
0
def main ():

    logger.debug('version %s starting' % VERSION)

    opt, args = getParms()

    # Find all the exons in all the transcripts for the gene, put them
    # in a list.

    tranList = list()                                      # list of Transcript objects
    exonList = list()                                      # list of Exon objects

    if opt.gtf is not None:
        getGeneFromAnnotation (opt, tranList, exonList)    # lists will be changed
    if opt.matches is not None:
        getGeneFromMatches (opt, tranList, exonList)       # lists will be changed
    if len(exonList) == 0:
        raise RuntimeError ('no exons found for gene %s in annotation or match files' % opt.gene)

    forwardStrand = '-' if opt.flip else '+'
    if exonList[0].strand == forwardStrand:
        exonList.sort(key=lambda x: x.start)               # sort the list by start position
        blocks = assignBlocks (opt, exonList)              # assign each exon to a block
    else:
        exonList.sort(key=lambda x: x.end, reverse=True)   # sort the list by decreasing end position
        blocks = assignBlocksReverse (opt, exonList)       # assign each exon to a block -- backwards

    findRegions (tranList)                       # determine regions occupied by each transcript

    tranNames = orderTranscripts (tranList)

    output_file("transcript.html")
    p = Figure(plot_width=1000, plot_height=750)
    df = groupTran(tranList, exonList, opt.group)
    length = len(tranNames)
    for myExon in exonList:
        exonSize = myExon.end - myExon.start + 1
        adjStart = myExon.adjStart
        for index, row in df.iterrows():
            name = row['name']
            groupColor = 'purple'
            if name in myExon.name:
                groupColor = row['color']
                break
        p.line([adjStart, adjStart+exonSize], [length-(myExon.tran.tranIx+1), length-(myExon.tran.tranIx+1)], line_width=20, line_color=groupColor)

    f_range = FactorRange(factors=tranNames[::-1])
    p.extra_y_ranges = {"Tran": f_range}
    new_axis = CategoricalAxis(y_range_name="Tran")
    p.add_layout(new_axis, 'left')
    show(p)
Esempio n. 11
0
File: gui.py Progetto: YDnepr/asda
def plotPairs(fileName, bokehPlaceholderId='bokehContent'):    

    source = ColumnDataSource(data={'count':[], 'index':[]})
    minCount = TextInput(value="20", title="Minimum number of trips per pair:")
    checkbox_group = CheckboxGroup(labels=["Include trips from a station to itself."])
    ShowButton = Toggle(label="Show", type="success")
    model = dict(source=source, checkbox = checkbox_group, minCount = minCount)
    plot = Figure(title="Accumulative Number Of Trips Over Top Station Pairs", x_axis_label='Top Station Pairs in Decreasing Order', y_axis_label='Accumulative Number of Trips', plot_width=1200, plot_height=400)
    plot.ray(x = [0], y=[90], line_color='red', angle=0.0, name='90%', length = 0, line_width=2)
    plot.ray(x = [0], y=[90], line_color='red', angle=180.0, angle_units = 'deg', length = 0, line_width=2)
    plot.line(x = 'index', y ='count', source=source, line_width=2, line_alpha=0.6)
    
    callback = CustomJS(args=model, code="""
            var selectSelf = checkbox.get('active').length;
            var minCountVal = minCount.get('value');
            var xmlhttp;
            xmlhttp = new XMLHttpRequest();
            
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
                    if(xmlhttp.status == 200){
                        var data = source.get('data');
                        var result = JSON.parse(xmlhttp.responseText);
                        
                        data['count'] = result.count;
                        data['index'] = result.index;
                        source.trigger('change');
                        alert('triggered');
                    }
                    else if(xmlhttp.status == 400) {
                        alert(400);
                    }
                    else {
                        alert(xmlhttp.status);
                    }
                }
            };
        var params = {self:selectSelf, min:minCountVal};
        url = "/pairsdist?" + jQuery.param( params );
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
        """)
        
    ShowButton.callback = callback
    layout = vform(checkbox_group, minCount, ShowButton, plot)
    script, div = components(layout)
    html = readHtmlFile(fileName)
    html = insertScriptIntoHeader(html, script)
    html = appendElementContent(html, div, "div", "bokehContent")

    return html
Esempio n. 12
0
def plotConserved(stats):
    from bokeh.models import HoverTool,ColumnDataSource
    from bokeh.plotting import Figure
    width=500
    height=500
    plot = Figure(title='',title_text_font_size="11pt",
            plot_width=width, plot_height=height,
           x_axis_label='identity',y_axis_label='perc_cons',
           tools="pan, wheel_zoom, resize, hover, reset, save",
           background_fill="#FAFAFA")
    x=stats.index
    for c in stats.columns:
        print x, stats[c]
        plot.line(x,stats[c], line_color='blue',line_width=1.5,legend=c)
    js,html = embedPlot(plot)
    return html
Esempio n. 13
0
def gen_fig(shape, source, tool=''):
	'''function to generate either a circle or line graph'''
	p = Figure(plot_width=500, plot_height=500,\
		title='Selected - Sample by Wave', tools = [tool])
	p.title_text_color = "CadetBlue"
	p.title_text_font = "helvetica"
	p.xaxis.axis_label = "Wave"
	p.xaxis.axis_label_text_font_size = '9pt'
	p.yaxis.axis_label = "Sample Size"
	p.yaxis.axis_label_text_font_size = '9pt'
	if shape == 'circle':
		p.circle('Years', 'SampleSize', source=source,\
			size=10, color="CadetBlue", alpha=0.5)
	elif shape == 'line':
		p.line('Years', 'SampleSize', source=source,\
			line_width=3, color='CadetBlue',line_alpha=0.7)
	return p
Esempio n. 14
0
def make_plot(src, city):
    plot = Figure(x_axis_type="datetime", plot_width=1000, tools="", toolbar_location=None)
    plot.title = city
    colors = Blues4[0:3]
    plot.line(x='date', y='GDD',source=src)
#    plot.quad(top='max', bottom='min', left='left', right='right', color=colors[2], source=src, legend="Record")

    # fixed attributes
    plot.border_fill_color = "whitesmoke"
    plot.xaxis.axis_label = None
    plot.yaxis.axis_label = "Accumulated GDD"
    plot.axis.major_label_text_font_size = "8pt"
    plot.axis.axis_label_text_font_size = "8pt"
    plot.axis.axis_label_text_font_style = "bold"
    plot.grid.grid_line_alpha = 0.3
    plot.grid[0].ticker.desired_num_ticks = 12

    return plot
Esempio n. 15
0
def make_plot(src, city):
    TOOLS = [BoxSelectTool()]
    global plot
    plot = Figure(x_axis_type="datetime", plot_width=1000, title_text_font_size='12pt', tools=TOOLS)
    plot.title = city
    colors = Blues4[0:3]
    plot.line(x='date', y='GDD',source=src, line_width=4)
    
    plot.border_fill_color = "whitesmoke"
    plot.xaxis.axis_label = "Months"
    plot.yaxis.axis_label = "Accumulated GDD"
    plot.axis.major_label_text_font_size = "10pt"
    plot.axis.axis_label_text_font_size = "12pt"
    plot.axis.axis_label_text_font_style = "bold"
    plot.grid.grid_line_alpha = 0.3
    plot.grid[0].ticker.desired_num_ticks = 12

    return plot
Esempio n. 16
0
class ConsoPlot(object):
    def __init__(self):
        self.conso_plot = Figure(
            title="Consommation", toolbar_location="right",
            tools="pan,box_zoom,wheel_zoom,reset", 
            logo=None, min_border=0,
            plot_width=1200, plot_height=250,
            x_axis_type="datetime",
            x_range=(dates.min(), dates.max()),
            y_range=(0., conso_bounds[1]))
        self.sector_renderer = self.conso_plot.line(
            source=conso_source, x="date", y="conso",
            color="navy", alpha=0.7, line_width=1.5)
        self.signal_renderer = self.conso_plot.line(
            source=conso_source, x="date", y="diff",
            color="green", alpha=0.7, line_width=2)
        self.conso_plot.line(source=datetime_source, x="date", y="conso",
                             color="firebrick", line_width=2)
        self.conso_plot.xaxis[0].formatter = DatetimeTickFormatter(
            formats=dict(
                hours=["%d/%m"],
                days=["%d/%m"],
                months=["%d/%m"],
                years=["%d/%m"],
            )
        )
        self.conso_plot.xaxis.axis_label = "Date"
#        self.conso_plot.yaxis.axis_label = "m^3/h"
    
    def get_plot(self):
        return self.conso_plot
        
    def update_title(self, title):
        self.conso_plot.title = title
    
    def set_active(self, active):
        if 0 in active and self.sector_renderer not in self.conso_plot.renderers:
            self.conso_plot.renderers.append(self.sector_renderer)
        elif not 0 in active and self.sector_renderer in self.conso_plot.renderers:
            self.conso_plot.renderers.remove(self.sector_renderer)
        if 1 in active and self.signal_renderer not in self.conso_plot.renderers:
            self.conso_plot.renderers.append(self.signal_renderer)
        elif not 1 in active and self.signal_renderer in self.conso_plot.renderers:
            self.conso_plot.renderers.remove(self.signal_renderer)
    def _replacement_plot(self, source):
        start = self.now - datetime.timedelta(days=self.RECOATING_PERIOD)
        start_timestamp = datetime.datetime(start.year, start.month, start.day, 0, 0, 0, 0).timestamp()
        end_timestamp = datetime.datetime(self.now.year, self.now.month, self.now.day, 0, 0, 0, 0).timestamp()
        x_range = DataRange1d(start=1000 * start_timestamp, end=1000 * end_timestamp)
        y_range = DataRange1d(start=0, end=120)
        plot = Figure(x_axis_type='datetime',
                      x_range=x_range,
                      y_range=y_range,
                      tools=['tap'],
                      toolbar_location=None)

        # required recoated segments
        plot.line(x=[start, self.now],
                  y=[0, 91],
                  legend='required recoated segments',
                  line_width=2,
                  line_color='blue')

        # recoated segments
        plot.line(x='ReplacementDate',
                  y='RecoatingsSinceYearStart',
                  source=source,
                  legend='recoated segments',
                  line_width=2,
                  color='orange')
        plot.circle(x='ReplacementDate',
                    y='RecoatingsSinceYearStart',
                    source=source,
                    legend='recoated segments',
                    size=6,
                    color='orange')

        date_format = '%d %b %Y'
        formats = dict(hours=[date_format], days=[date_format], months=[date_format], years=[date_format])
        plot.xaxis[0].formatter = DatetimeTickFormatter(formats=formats)

        plot.legend.location = 'top_left'

        plot.min_border_top = 20
        plot.min_border_bottom = 30

        return plot
Esempio n. 18
0
def jwst_1d_flux(result_dict, plot=True, output_file= 'flux.html'): 
    """Plot flux rate in e/s
    
    Parameters
    ----------
    result_dict : dict
        Dictionary from pandexo output. If parameter space was run in run_pandexo 
        make sure to restructure the input as a list of dictionaries without they key words 
        that run_pandexo assigns. 
    plot : bool 
        (Optional) True renders plot, Flase does not. Default=True
    output_file : str
        (Optional) Default = 'flux.html'    
    Return
    ------
    x : numpy array
        micron
    y : numpy array
        1D flux rate in electrons/s
        
    See Also
    --------
    jwst_1d_spec, jwst_1d_bkg, jwst_noise, jwst_1d_snr, jwst_2d_det, jwst_2d_sat
    """
    TOOLS = "pan,wheel_zoom,box_zoom,resize,reset,save"
    out = result_dict['PandeiaOutTrans']
    
    # Flux 1d
    x, y = out['1d']['extracted_flux']
    x = x[~np.isnan(y)]
    y = y[~np.isnan(y)]

    plot_flux_1d1 = Figure(tools=TOOLS,
                         x_axis_label='Wavelength [microns]',
                         y_axis_label='Flux (e/s)', title="Out of Transit Flux Rate",
                         plot_width=800, plot_height=300)
    plot_flux_1d1.line(x, y, line_width = 4, alpha = .7)
    
    if plot: 
        outputfile(output_file)
        show(plot_flux_1d1)
    return x,y
Esempio n. 19
0
def jwst_1d_snr(result_dict, plot=True, output_file='snr.html'): 
    """Plot SNR
    
    Parameters
    ----------
    result_dict : dict
        Dictionary from pandexo output. If parameter space was run in run_pandexo 
        make sure to restructure the input as a list of dictionaries without they key words 
        that run_pandexo assigns. 
    plot : bool 
        (Optional) True renders plot, Flase does not. Default=True
    output_file : str
        (Optional) Default = 'snr.html'   
                
    Return
    ------
    x : numpy array
        micron
    y : numpy array
        1D SNR

    See Also
    --------
    jwst_1d_bkg, jwst_noise, jwst_1d_flux, jwst_1d_spec, jwst_2d_det, jwst_2d_sat
    """    
    TOOLS = "pan,wheel_zoom,box_zoom,resize,reset,save"
    # Flux 1d
    x= result_dict['RawData']['wave']
    electrons_out = result_dict['RawData']['electrons_out']
    y = electrons_out/np.sqrt(result_dict['RawData']['var_out'])
    x = x[~np.isnan(y)]
    y = y[~np.isnan(y)]
    plot_snr_1d1 = Figure(tools=TOOLS,
                         x_axis_label='Wavelength (micron)',
                         y_axis_label='SNR', title="SNR Out of Trans",
                         plot_width=800, plot_height=300)
    plot_snr_1d1.line(x, y, line_width = 4, alpha = .7)
    if plot: 
        outputfile(output_file)
        show(plot_snr_1d1)
    return x,y
Esempio n. 20
0
def make_plot(source,AverageTemp,Parcentile_5_Min,Parcentile_5_Max,Parcentile_25_Min,Parcentile_25_Max,MinTemp,MaxTemp,plotDate,cityName):
    plot = Figure(title='Optional Task # 1 : Growing Degree-day for '+cityName, x_axis_type="datetime", plot_width=1000, title_text_font_size='12pt', tools="", toolbar_location=None)
    colors = Blues4[0:3]
    
    plot.circle(MaxTemp,MinTemp, alpha=0.9, color="#66ff33", fill_alpha=0.2, size=10,source=source,legend ='2015')
    plot.quad(top=Parcentile_5_Max, bottom=Parcentile_5_Min, left='left',right='right',
              source=source,color="#e67300", legend="Percentile 5-95")
    plot.quad(top=Parcentile_25_Max, bottom=Parcentile_25_Min,left='left',right='right',
              source=source,color="#66ccff",legend="percentile 25-75")
    plot.line(plotDate,AverageTemp,source=source,line_color='Red', line_width=0.75, legend='AverageTemp')

    plot.border_fill_color = "whitesmoke"
    plot.xaxis.axis_label = "Months"
    plot.yaxis.axis_label = "Temperature (C)"
    plot.axis.major_label_text_font_size = "10pt"
    plot.axis.axis_label_text_font_size = "12pt"
    plot.axis.axis_label_text_font_style = "bold"
    plot.x_range = DataRange1d(range_padding=0.0, bounds=None)
    plot.grid.grid_line_alpha = 0.3
    plot.grid[0].ticker.desired_num_ticks = 12
    return plot
Esempio n. 21
0
def plotnoisecum(noisepkl, fluxscale=1, plot_width=450, plot_height=400):
    """ Merged noise pkl converted to interactive cumulative histogram 

    noisepkl is standard noise pickle file.
    fluxscale is scaling applied by gain calibrator. telcal solutions have fluxscale=1.
    also returns corrected imnoise values if non-unity fluxscale provided
    """

    # noise histogram
    noises = read_noise(noisepkl)
    imnoise = np.sort(fluxscale*noises[4])
    frac = [float(count)/len(imnoise) for count in reversed(range(1, len(imnoise)+1))]
    noiseplot = Figure(plot_width=plot_width, plot_height=plot_height, toolbar_location="above",
                       x_axis_label='Image noise (Jy; cal scaling {0:.3})'.format(fluxscale),
                       y_axis_label='Cumulative fraction', tools='pan, wheel_zoom, reset')
    noiseplot.line(imnoise, frac)

    if fluxscale != 1:
        return noiseplot, imnoise
    else:
        return noiseplot
def make_plot(yscale='linear'):
    # configure the tools
    width_zoom={'dimensions':['width']}
    tools = [tool(**width_zoom) for tool in [BoxZoomTool, WheelZoomTool]]

    hover_pos = HoverTool(
            names=['buy','sell'],
            tooltips=[
              ('Position','@pos'),
              ('Date','@date'),
              ('Price','@price')
            ]
    )
    hover_pos.name = 'Postions'


    tools.extend([PanTool(), hover_pos, ResetTool(), CrosshairTool()])

    # prepare plot
    p = Figure(plot_height=600, plot_width=800, title="Moving Average Positions",
            x_axis_type='datetime', y_axis_type=yscale, tools=tools)

    p.line(x='date', y='price', alpha=0.3, color='Black', line_width=2, source=source, legend='Close', name='price')
    p.line(x='date', y='mav_short', color='DarkBlue', line_width=2, source=source, legend='Short MAV')
    p.line(x='date', y='mav_long', color='FireBrick', line_width=2, source=source, legend='Long MAV')
    p.inverted_triangle(x='x', y='y', color='Crimson', size=20, alpha=0.7, source=sell, legend='Sell', name='sell')
    p.triangle(x='x', y='y', color='ForestGreen', size=20, alpha=0.7, source=buy, legend='Buy', name='buy')

    return p
Esempio n. 23
0
def create_component_spec(result_dict):
    """Generate front end plots of modeling
    
    Function that is responsible for generating the front-end spectra plots.
    
    Parameters
    ----------
    result_dict : dict 
        the dictionary returned from a PandExo run

    Returns
    -------
    tuple
        A tuple containing `(script, div)`, where the `script` is the
        front-end javascript required, and `div` is a dictionary of plot
        objects.
    """  
    num = -1
    color = ["red", "blue", "green", "purple", "black", "yellow", "orange", "pink","cyan","brown"]

    TOOLS = "pan,wheel_zoom,box_zoom,resize,reset,save"
        
    plot1 = Figure(plot_width=800, plot_height=350,  tools=TOOLS, responsive =False,
                                 x_axis_label='Wavelength [um]', x_axis_type="log",
                                 y_axis_label='Alpha Lambda', y_range = [min(result_dict['alpha']), max(result_dict['alpha'])]) 
    plot1.line(result_dict['w'], result_dict['alpha'], alpha = 0.5, line_width = 3)    
    
    plot2 = Figure(plot_width=800, plot_height=350,  tools=TOOLS, responsive =False, y_axis_type="log",
                                 x_axis_label='Wavelength [um]', x_axis_type="log",
                                 y_axis_label='Weighted Cross Section', y_range = [1e-29, 1e-17])
    alpha = result_dict['alpha']
    squig =  result_dict['mols']    
    xsec = result_dict['xsec'] 
    waves = result_dict['w']                       
    for i in squig.keys():  
        if i=="H2":
            num +=1
            plot2.line(waves,squig[i]*xsec[i][alpha> 0.0]*squig["H2"], color = color[num], legend = i)
        elif i=="He":
            num +=1
            plot2.line(waves,squig[i]*xsec[i][alpha> 0.0]*squig["H2"], color = color[num], legend = i)
        else:
            num +=1
            plot2.line(waves,squig[i]*xsec[i][alpha> 0.0], color = color[num], legend = i)            
                             
                          
    result_comp =   components({'plot1':plot1, 
                              'plot2': plot2})
    return result_comp 
Esempio n. 24
0
def make_plots(linesources, pointsources):
    plots = []
    i=0
    for linesource, pointsource in zip(linesources, pointsources):
        fig = Figure(title=None, toolbar_location=None, tools=[],
                   x_axis_type="datetime",
                   width=300, height=70)

        fig.xaxis.visible = False
        if i in [0, 9] :
            fig.xaxis.visible = True
            fig.height = 90
        fig.yaxis.visible = False
        fig.xgrid.visible = True
        fig.ygrid.visible = False
        fig.min_border_left = 10
        fig.min_border_right = 10
        fig.min_border_top = 5
        fig.min_border_bottom = 5
        if not i in [0, 9]:
            fig.xaxis.major_label_text_font_size = "0pt"
        #fig.yaxis.major_label_text_font_size = "0pt"
        fig.xaxis.major_tick_line_color = None
        fig.yaxis.major_tick_line_color = None
        fig.xaxis.minor_tick_line_color = None
        fig.yaxis.minor_tick_line_color = None
        fig.background_fill_color = "whitesmoke"

        fig.line(x='date', y="y", source=linesource)
        fig.circle(x='date', y='y', size=5, source=pointsource)
        fig.text(x='date', y='y', text='text', x_offset=5, y_offset=10, text_font_size='7pt', source=pointsource)

        fig.title.align = 'left'
        fig.title.text_font_style = 'normal'

        plots.append(fig)
        i+=1
    return plots
Esempio n. 25
0
def home():
    
    bokeh_width, bokeh_height = 1000,600
    lat, lon = 46.2437, 6.0251
    api_key = "AIzaSyB4y5u1q0_-4kVQpSMGkH_dxpnzn8PL-dQ"
    print(str(api_key))
    def plot(lat, lng, zoom=10, map_type='roadmap'):
        
        from bokeh.io import show
        from bokeh.plotting import gmap
        from bokeh.models import GMapOptions
        
        gmap_options = GMapOptions(lat=lat, lng=lng, 
                               map_type=map_type, zoom=zoom)
        p = gmap(api_key, gmap_options, title='Pays de Gex', 
                 width=bokeh_width, height=bokeh_height)
        # beware, longitude is on the x axis ;-)
        center = p.circle([lng], [lat], size=10, alpha=0.5, color='red')
        
        return p
    
    p = plot(lat, lon, map_type='roadmap')
    
    #---------------------------------------------------
    from bokeh.io import curdoc
    from bokeh.layouts import column
    from bokeh.models import Button, ColumnDataSource
    from bokeh.plotting import Figure
    
    from bokeh.embed import components
    from bokeh.resources import CDN
    
    from numpy.random import random
    
    xs = []
    ys = []
    points = ColumnDataSource(data={'x_coord':xs, 'y_coord':ys})
    
    plot = Figure(title="Random Lines", x_range=(0, 1), y_range=(0, 1))
    
    plot.line('x_coord', 'y_coord', source=points)
    
    button = Button(label="Click Me!")
    
    def add_random_line():
        """
        Adds a new random point to the line.
        """
        x, y = random(2)
    
        newxs = [*points.data['x_coord'], x]
        newys = [*points.data['y_coord'], y]
    
        points.data = {'x_coord': newxs, 'y_coord': newys}
    
    
    button.on_click(add_random_line)
    
    layout = column(button, plot)
    
    
    curdoc().add_root(layout)
    
    script1, div1, = components(p)
    cdn_js = CDN.js_files[0]
    cdn_css = CDN.css_files
    
    print(script1)
    print('\n============================================')
    print(div1)
    print('\n============================================')
    print(cdn_css)
    print('\n============================================')
    print(cdn_js)
    
    # return render_template("combine.html",script1=script1,div1=div1, cdn_css=cdn_css,cdn_js=cdn_js)
    
    data_val1 = 'Hard Coded value 1'
    data_val2 = 'Hard coded value 2'
    
    templateData = {
        'data1' : data_val1,
        'data2' : data_val2
        }
    
    return render_template("combine.html", **templateData, script1=script1,div1=div1, cdn_css=cdn_css,cdn_js=cdn_js)
Esempio n. 26
0
        results += item
    return results


source = ColumnDataSource(dict(x=[], y=[], avg=[], longavg=[]))

fig = Figure(x_axis_label='Time',
             y_axis_label='Mhash/s',
             x_axis_type='datetime',
             plot_width=1500,
             plot_height=800)

fig.line(source=source,
         x='x',
         y='y',
         line_width=2,
         alpha=0.85,
         color='red',
         legend='current Hashrate')

fig.line(source=source,
         x='x',
         y='avg',
         line_width=2,
         alpha=0.85,
         color='blue',
         legend='average Hashrate(3HR)')

fig.line(source=source,
         x='x',
         y='longavg',
Esempio n. 27
0
def create_component_spec(result_dict):
    """Generate front end plots of modeling
    
    Function that is responsible for generating the front-end spectra plots.
    
    Parameters
    ----------
    result_dict : dict 
        the dictionary returned from a PandExo run

    Returns
    -------
    tuple
        A tuple containing `(script, div)`, where the `script` is the
        front-end javascript required, and `div` is a dictionary of plot
        objects.
    """
    num = -1
    color = [
        "red", "blue", "green", "purple", "black", "yellow", "orange", "pink",
        "cyan", "brown"
    ]

    TOOLS = "pan,wheel_zoom,box_zoom,resize,reset,save"

    plot1 = Figure(
        plot_width=800,
        plot_height=350,
        tools=TOOLS,
        responsive=False,
        x_axis_label='Wavelength [um]',
        x_axis_type="log",
        y_axis_label='Alpha Lambda',
        y_range=[min(result_dict['alpha']),
                 max(result_dict['alpha'])])
    plot1.line(result_dict['w'], result_dict['alpha'], alpha=0.5, line_width=3)

    plot2 = Figure(plot_width=800,
                   plot_height=350,
                   tools=TOOLS,
                   responsive=False,
                   y_axis_type="log",
                   x_axis_label='Wavelength [um]',
                   x_axis_type="log",
                   y_axis_label='Weighted Cross Section',
                   y_range=[1e-29, 1e-17])
    alpha = result_dict['alpha']
    squig = result_dict['mols']
    xsec = result_dict['xsec']
    waves = result_dict['w']
    for i in squig.keys():
        if i == "H2":
            num += 1
            plot2.line(waves,
                       squig[i] * xsec[i][alpha > 0.0] * squig["H2"],
                       color=color[num],
                       legend=i)
        elif i == "He":
            num += 1
            plot2.line(waves,
                       squig[i] * xsec[i][alpha > 0.0] * squig["H2"],
                       color=color[num],
                       legend=i)
        else:
            num += 1
            plot2.line(waves,
                       squig[i] * xsec[i][alpha > 0.0],
                       color=color[num],
                       legend=i)

    result_comp = components({'plot1': plot1, 'plot2': plot2})
    return result_comp
                                   bounds=(date_calib[0], date_calib[-1])),
                   title=basin + ' Daily Streamflow (CMS)',
                   x_axis_type="datetime",
                   x_axis_label='Date',
                   y_axis_label='Streamflow (CMSD)',
                   y_axis_type="log",
                   plot_width=1300,
                   plot_height=600,
                   lod_factor=20,
                   lod_threshold=50)
    #p.y_range = DataRange1d(bounds=(0,150))

    # add some renderers
    p.line(date_calib,
           discharge,
           legend="Observed - QME",
           line_width=3,
           line_color="black")
    #p.circle(date_calib, discharge, legend="Observed - QME", fill_color="white", size=3)
    p.line(date_calib,
           Q_calib,
           legend="Simulated - SQME",
           line_width=3,
           line_color="red")
    #p.circle(date_calib, Q_calib, legend="Simulated - SQME", fill_color="red", line_color="red", size=3)
    #p.line(x, y2, legend="y=10^x^2", line_color="orange", line_dash="4 4")

    # show the results
    #show(p)
    print 'Saving plot...'
    save(p)
def plot_3DModel_bokeh(filename, map_data_all_slices, map_depth_all_slices, \
                       color_range_all_slices, profile_data_all, boundary_data, \
                       style_parameter):
    '''
    Plot shear velocity maps and velocity profiles using bokeh

    Input:
        filename is the filename of the resulting html file
        map_data_all_slices contains the velocity model parameters saved for map view plots
        map_depth_all_slices is a list of depths
        color_range_all_slices is a list of color ranges
        profile_data_all constains the velocity model parameters saved for profile plots
        boundary_data is a list of boundaries
        style_parameter contains plotting parameters

    Output:
        None
    
    '''
    xlabel_fontsize = style_parameter['xlabel_fontsize']
    #
    colorbar_data_all_left = []
    colorbar_data_all_right = []
    map_view_ndepth = style_parameter['map_view_ndepth']
    ncolor = len(palette)
    colorbar_top = [0.1 for i in range(ncolor)]
    colorbar_bottom = [0 for i in range(ncolor)]
    map_data_all_slices_depth = []
    for idepth in range(map_view_ndepth): 
        color_min = color_range_all_slices[idepth][0]
        color_max = color_range_all_slices[idepth][1]
        color_step = (color_max - color_min)*1./ncolor
        colorbar_left = np.linspace(color_min,color_max-color_step,ncolor)
        colorbar_right = np.linspace(color_min+color_step,color_max,ncolor)
        colorbar_data_all_left.append(colorbar_left)
        colorbar_data_all_right.append(colorbar_right)
        map_depth = map_depth_all_slices[idepth]
        map_data_all_slices_depth.append('Depth: {0:8.0f} km'.format(map_depth))
    #
    palette_r = palette[::-1]
    # data for the colorbar
    colorbar_data_one_slice = {}
    colorbar_data_one_slice['colorbar_left'] = colorbar_data_all_left[style_parameter['map_view_default_index']]
    colorbar_data_one_slice['colorbar_right'] = colorbar_data_all_right[style_parameter['map_view_default_index']]
    colorbar_data_one_slice_bokeh = ColumnDataSource(data=dict(colorbar_top=colorbar_top,colorbar_bottom=colorbar_bottom,\
                                                               colorbar_left=colorbar_data_one_slice['colorbar_left'],\
                                                               colorbar_right=colorbar_data_one_slice['colorbar_right'],\
                                                               palette_r=palette_r))
    colorbar_data_all_slices_bokeh = ColumnDataSource(data=dict(colorbar_data_all_left=colorbar_data_all_left,\
                                                                colorbar_data_all_right=colorbar_data_all_right))
    #
    map_view_label_lon = style_parameter['map_view_depth_label_lon']
    map_view_label_lat = style_parameter['map_view_depth_label_lat']
    map_data_one_slice_depth = map_data_all_slices_depth[style_parameter['map_view_default_index']]
    map_data_one_slice_depth_bokeh = ColumnDataSource(data=dict(lat=[map_view_label_lat], lon=[map_view_label_lon],
                                                           map_depth=[map_data_one_slice_depth]))
    
    #
    map_view_default_index = style_parameter['map_view_default_index']
    map_data_one_slice = map_data_all_slices[map_view_default_index]

    map_data_one_slice_bokeh = ColumnDataSource(data=dict(x=[style_parameter['map_view_image_lon_min']],\
                   y=[style_parameter['map_view_image_lat_min']],dw=[style_parameter['nlon']*style_parameter['dlon']],\
                   dh=[style_parameter['nlat']*style_parameter['dlat']],map_data_one_slice=[map_data_one_slice]))
    map_data_all_slices_bokeh = ColumnDataSource(data=dict(map_data_all_slices=map_data_all_slices,\
                                                           map_data_all_slices_depth=map_data_all_slices_depth))
    # ------------------------------
    nprofile = len(profile_data_all)
    grid_lat_list = []
    grid_lon_list = []
    width_list = []
    height_list = []
    for iprofile in range(nprofile):
        aprofile = profile_data_all[iprofile]
        grid_lat_list.append(aprofile['lat'])
        grid_lon_list.append(aprofile['lon'])
        width_list.append(style_parameter['map_view_grid_width'])
        height_list.append(style_parameter['map_view_grid_height'])
    grid_data_bokeh = ColumnDataSource(data=dict(lon=grid_lon_list,lat=grid_lat_list,\
                                            width=width_list, height=height_list))
    profile_default_index = style_parameter['profile_default_index']
    selected_dot_on_map_bokeh = ColumnDataSource(data=dict(lat=[grid_lat_list[profile_default_index]], \
                                                           lon=[grid_lon_list[profile_default_index]], \
                                                           width=[style_parameter['map_view_grid_width']],\
                                                           height=[style_parameter['map_view_grid_height']],\
                                                           index=[profile_default_index]))
    # ------------------------------
    profile_vs_all = []
    profile_depth_all = []
    profile_ndepth = style_parameter['profile_ndepth']
    profile_lat_label_list = []
    profile_lon_label_list = []
    for iprofile in range(nprofile):
        aprofile = profile_data_all[iprofile]
        vs_raw = aprofile['vs']
        top_raw = aprofile['top']
        profile_lat_label_list.append('Lat: {0:12.1f}'.format(aprofile['lat']))
        profile_lon_label_list.append('Lon: {0:12.1f}'.format(aprofile['lon']))
        vs_plot = []
        depth_plot = []
        for idepth in range(profile_ndepth):
            vs_plot.append(vs_raw[idepth])
            depth_plot.append(top_raw[idepth])
            vs_plot.append(vs_raw[idepth])
            depth_plot.append(top_raw[idepth+1])
        profile_vs_all.append(vs_plot)
        profile_depth_all.append(depth_plot)
    profile_data_all_bokeh = ColumnDataSource(data=dict(profile_vs_all=profile_vs_all, \
                                                        profile_depth_all=profile_depth_all))
    selected_profile_data_bokeh = ColumnDataSource(data=dict(vs=profile_vs_all[profile_default_index],\
                                                             depth=profile_depth_all[profile_default_index]))
    selected_profile_lat_label_bokeh = ColumnDataSource(data=\
                                dict(x=[style_parameter['profile_lat_label_x']], y=[style_parameter['profile_lat_label_y']],\
                                    lat_label=[profile_lat_label_list[profile_default_index]]))
    selected_profile_lon_label_bokeh = ColumnDataSource(data=\
                                dict(x=[style_parameter['profile_lon_label_x']], y=[style_parameter['profile_lon_label_y']],\
                                    lon_label=[profile_lon_label_list[profile_default_index]]))
    all_profile_lat_label_bokeh = ColumnDataSource(data=dict(profile_lat_label_list=profile_lat_label_list))
    all_profile_lon_label_bokeh = ColumnDataSource(data=dict(profile_lon_label_list=profile_lon_label_list))
    #
    button_ndepth = style_parameter['button_ndepth']
    button_data_all_vs = []
    button_data_all_vp = []
    button_data_all_rho = []
    button_data_all_top = []
    for iprofile in range(nprofile):
        aprofile = profile_data_all[iprofile]
        button_data_all_vs.append(aprofile['vs'][:button_ndepth])
        button_data_all_vp.append(aprofile['vp'][:button_ndepth])
        button_data_all_rho.append(aprofile['rho'][:button_ndepth])
        button_data_all_top.append(aprofile['top'][:button_ndepth])
    button_data_all_bokeh = ColumnDataSource(data=dict(button_data_all_vs=button_data_all_vs,\
                                                       button_data_all_vp=button_data_all_vp,\
                                                       button_data_all_rho=button_data_all_rho,\
                                                       button_data_all_top=button_data_all_top))
    # ==============================
    map_view = Figure(plot_width=style_parameter['map_view_plot_width'], plot_height=style_parameter['map_view_plot_height'], \
                      tools=style_parameter['map_view_tools'], title=style_parameter['map_view_title'], \
                      y_range=[style_parameter['map_view_figure_lat_min'], style_parameter['map_view_figure_lat_max']],\
                      x_range=[style_parameter['map_view_figure_lon_min'], style_parameter['map_view_figure_lon_max']])
    #
    map_view.image('map_data_one_slice',x='x',\
                   y='y',dw='dw',\
                   dh='dh',palette=palette_r,\
                   source=map_data_one_slice_bokeh, level='image')

    depth_slider_callback = CustomJS(args=dict(map_data_one_slice_bokeh=map_data_one_slice_bokeh,\
                                               map_data_all_slices_bokeh=map_data_all_slices_bokeh,\
                                               colorbar_data_all_slices_bokeh=colorbar_data_all_slices_bokeh,\
                                               colorbar_data_one_slice_bokeh=colorbar_data_one_slice_bokeh,\
                                               map_data_one_slice_depth_bokeh=map_data_one_slice_depth_bokeh), code="""

        var d_index = Math.round(cb_obj.value)
        
        var map_data_all_slices = map_data_all_slices_bokeh.data
        
        map_data_one_slice_bokeh.data['map_data_one_slice'] = [map_data_all_slices['map_data_all_slices'][d_index]]
        map_data_one_slice_bokeh.change.emit()
        
        var color_data_all_slices = colorbar_data_all_slices_bokeh.data
        colorbar_data_one_slice_bokeh.data['colorbar_left'] = color_data_all_slices['colorbar_data_all_left'][d_index]
        colorbar_data_one_slice_bokeh.data['colorbar_right'] = color_data_all_slices['colorbar_data_all_right'][d_index]
        colorbar_data_one_slice_bokeh.change.emit()
        
        map_data_one_slice_depth_bokeh.data['map_depth'] = [map_data_all_slices['map_data_all_slices_depth'][d_index]]
        map_data_one_slice_depth_bokeh.change.emit()
        
    """) 
    depth_slider = Slider(start=0, end=style_parameter['map_view_ndepth']-1, \
                          value=map_view_default_index, step=1, \
                          width=style_parameter['map_view_plot_width'],\
                          title=style_parameter['depth_slider_title'], height=50, \
                          callback=depth_slider_callback)
    # ------------------------------
    # add boundaries to map view
    # country boundaries
    map_view.multi_line(boundary_data['country']['longitude'],\
                        boundary_data['country']['latitude'],color='black',\
                        line_width=2, level='underlay',nonselection_line_alpha=1.0,\
                        nonselection_line_color='black')
    # marine boundaries
    map_view.multi_line(boundary_data['marine']['longitude'],\
                        boundary_data['marine']['latitude'],color='black',\
                        level='underlay',nonselection_line_alpha=1.0,\
                        nonselection_line_color='black')
    # shoreline boundaries
    map_view.multi_line(boundary_data['shoreline']['longitude'],\
                        boundary_data['shoreline']['latitude'],color='black',\
                        line_width=2, level='underlay',nonselection_line_alpha=1.0,\
                        nonselection_line_color='black')
    # state boundaries
    map_view.multi_line(boundary_data['state']['longitude'],\
                        boundary_data['state']['latitude'],color='black',\
                        level='underlay',nonselection_line_alpha=1.0,\
                        nonselection_line_color='black')
    # ------------------------------
    # add depth label
    map_view.rect(style_parameter['map_view_depth_box_lon'], style_parameter['map_view_depth_box_lat'], \
                  width=style_parameter['map_view_depth_box_width'], height=style_parameter['map_view_depth_box_height'], \
                  width_units='screen',height_units='screen', color='#FFFFFF', line_width=1., line_color='black', level='underlay')
    map_view.text('lon', 'lat', 'map_depth', source=map_data_one_slice_depth_bokeh,\
                  text_font_size=style_parameter['annotating_text_font_size'],text_align='left',level='underlay')
    # ------------------------------
    map_view.rect('lon', 'lat', width='width', \
                  width_units='screen', height='height', \
                  height_units='screen', line_color='gray', line_alpha=0.5, \
                  selection_line_color='gray', selection_line_alpha=0.5, selection_fill_color=None,\
                  nonselection_line_color='gray',nonselection_line_alpha=0.5, nonselection_fill_color=None,\
                  source=grid_data_bokeh, color=None, line_width=1, level='glyph')
    map_view.rect('lon', 'lat',width='width', \
                  width_units='screen', height='height', \
                  height_units='screen', line_color='#00ff00', line_alpha=1.0, \
                  source=selected_dot_on_map_bokeh, fill_color=None, line_width=3.,level='glyph')
    # ------------------------------
    grid_data_bokeh.callback = CustomJS(args=dict(selected_dot_on_map_bokeh=selected_dot_on_map_bokeh, \
                                                  grid_data_bokeh=grid_data_bokeh,\
                                                  profile_data_all_bokeh=profile_data_all_bokeh,\
                                                  selected_profile_data_bokeh=selected_profile_data_bokeh,\
                                                  selected_profile_lat_label_bokeh=selected_profile_lat_label_bokeh,\
                                                  selected_profile_lon_label_bokeh=selected_profile_lon_label_bokeh, \
                                                  all_profile_lat_label_bokeh=all_profile_lat_label_bokeh, \
                                                  all_profile_lon_label_bokeh=all_profile_lon_label_bokeh, \
                                                 ), code="""
        
        var inds = Math.round(cb_obj.selected['1d'].indices)
        
        var grid_data = grid_data_bokeh.data
        selected_dot_on_map_bokeh.data['lat'] = [grid_data['lat'][inds]]
        selected_dot_on_map_bokeh.data['lon'] = [grid_data['lon'][inds]]
        selected_dot_on_map_bokeh.data['index'] = [inds]
        selected_dot_on_map_bokeh.change.emit()
        
        var profile_data_all = profile_data_all_bokeh.data
        selected_profile_data_bokeh.data['vs'] = profile_data_all['profile_vs_all'][inds]
        selected_profile_data_bokeh.data['depth'] = profile_data_all['profile_depth_all'][inds]
        selected_profile_data_bokeh.change.emit()
        
        var all_profile_lat_label = all_profile_lat_label_bokeh.data['profile_lat_label_list']
        var all_profile_lon_label = all_profile_lon_label_bokeh.data['profile_lon_label_list']
        selected_profile_lat_label_bokeh.data['lat_label'] = [all_profile_lat_label[inds]]
        selected_profile_lon_label_bokeh.data['lon_label'] = [all_profile_lon_label[inds]]
        selected_profile_lat_label_bokeh.change.emit()
        selected_profile_lon_label_bokeh.change.emit()
    """)
    # ------------------------------
    # change style
    map_view.title.text_font_size = style_parameter['title_font_size']
    map_view.title.align = 'center'
    map_view.title.text_font_style = 'normal'
    map_view.xaxis.axis_label = style_parameter['map_view_xlabel']
    map_view.xaxis.axis_label_text_font_style = 'normal'
    map_view.xaxis.axis_label_text_font_size = xlabel_fontsize
    map_view.xaxis.major_label_text_font_size = xlabel_fontsize
    map_view.yaxis.axis_label = style_parameter['map_view_ylabel']
    map_view.yaxis.axis_label_text_font_style = 'normal'
    map_view.yaxis.axis_label_text_font_size = xlabel_fontsize
    map_view.yaxis.major_label_text_font_size = xlabel_fontsize
    map_view.xgrid.grid_line_color = None
    map_view.ygrid.grid_line_color = None
    map_view.toolbar.logo = None
    map_view.toolbar_location = 'above'
    map_view.toolbar_sticky = False
    # ==============================
    # plot colorbar
    colorbar_fig = Figure(tools=[], y_range=(0,0.1),plot_width=style_parameter['map_view_plot_width'], \
                      plot_height=style_parameter['colorbar_plot_height'],title=style_parameter['colorbar_title'])
    colorbar_fig.toolbar_location=None
    colorbar_fig.quad(top='colorbar_top',bottom='colorbar_bottom',left='colorbar_left',right='colorbar_right',\
                  color='palette_r',source=colorbar_data_one_slice_bokeh)
    colorbar_fig.yaxis[0].ticker=FixedTicker(ticks=[])
    colorbar_fig.xgrid.grid_line_color = None
    colorbar_fig.ygrid.grid_line_color = None
    colorbar_fig.xaxis.axis_label_text_font_size = xlabel_fontsize
    colorbar_fig.xaxis.major_label_text_font_size = xlabel_fontsize
    colorbar_fig.xaxis[0].formatter = PrintfTickFormatter(format="%5.2f")
    colorbar_fig.title.text_font_size = xlabel_fontsize
    colorbar_fig.title.align = 'center'
    colorbar_fig.title.text_font_style = 'normal'
    # ==============================
    profile_xrange = Range1d(start=style_parameter['profile_plot_xmin'], end=style_parameter['profile_plot_xmax'])
    profile_yrange = Range1d(start=style_parameter['profile_plot_ymax'], end=style_parameter['profile_plot_ymin'])
    profile_fig = Figure(plot_width=style_parameter['profile_plot_width'], plot_height=style_parameter['profile_plot_height'],\
                         x_range=profile_xrange, y_range=profile_yrange, tools=style_parameter['profile_tools'],\
                         title=style_parameter['profile_title'])
    profile_fig.line('vs','depth',source=selected_profile_data_bokeh, line_width=2, line_color='black')
    # ------------------------------
    # add lat, lon
    profile_fig.rect([style_parameter['profile_label_box_x']], [style_parameter['profile_label_box_y']],\
                     width=style_parameter['profile_label_box_width'], height=style_parameter['profile_label_box_height'],\
                     width_units='screen', height_units='screen', color='#FFFFFF', line_width=1., line_color='black',\
                     level='underlay')
    profile_fig.text('x','y','lat_label', source=selected_profile_lat_label_bokeh)
    profile_fig.text('x','y','lon_label', source=selected_profile_lon_label_bokeh)
    # ------------------------------
    # change style
    profile_fig.xaxis.axis_label = style_parameter['profile_xlabel']
    profile_fig.xaxis.axis_label_text_font_style = 'normal'
    profile_fig.xaxis.axis_label_text_font_size = xlabel_fontsize
    profile_fig.xaxis.major_label_text_font_size = xlabel_fontsize
    profile_fig.yaxis.axis_label = style_parameter['profile_ylabel']
    profile_fig.yaxis.axis_label_text_font_style = 'normal'
    profile_fig.yaxis.axis_label_text_font_size = xlabel_fontsize
    profile_fig.yaxis.major_label_text_font_size = xlabel_fontsize
    profile_fig.xgrid.grid_line_dash = [4, 2]
    profile_fig.ygrid.grid_line_dash = [4, 2]
    profile_fig.title.text_font_size = style_parameter['title_font_size']
    profile_fig.title.align = 'center'
    profile_fig.title.text_font_style = 'normal'
    profile_fig.toolbar_location = 'above'
    profile_fig.toolbar_sticky = False
    profile_fig.toolbar.logo = None
    # ==============================
    profile_slider_callback = CustomJS(args=dict(selected_dot_on_map_bokeh=selected_dot_on_map_bokeh,\
                                                 grid_data_bokeh=grid_data_bokeh, \
                                                 profile_data_all_bokeh=profile_data_all_bokeh, \
                                                 selected_profile_data_bokeh=selected_profile_data_bokeh,\
                                                 selected_profile_lat_label_bokeh=selected_profile_lat_label_bokeh,\
                                                 selected_profile_lon_label_bokeh=selected_profile_lon_label_bokeh, \
                                                 all_profile_lat_label_bokeh=all_profile_lat_label_bokeh, \
                                                 all_profile_lon_label_bokeh=all_profile_lon_label_bokeh), code="""
        var p_index = Math.round(cb_obj.value)
        
        var grid_data = grid_data_bokeh.data
        selected_dot_on_map_bokeh.data['lat'] = [grid_data['lat'][p_index]]
        selected_dot_on_map_bokeh.data['lon'] = [grid_data['lon'][p_index]]
        selected_dot_on_map_bokeh.data['index'] = [p_index]
        selected_dot_on_map_bokeh.change.emit()
        
        var profile_data_all = profile_data_all_bokeh.data
        selected_profile_data_bokeh.data['vs'] = profile_data_all['profile_vs_all'][p_index]
        selected_profile_data_bokeh.data['depth'] = profile_data_all['profile_depth_all'][p_index]
        selected_profile_data_bokeh.change.emit()
        
        var all_profile_lat_label = all_profile_lat_label_bokeh.data['profile_lat_label_list']
        var all_profile_lon_label = all_profile_lon_label_bokeh.data['profile_lon_label_list']
        selected_profile_lat_label_bokeh.data['lat_label'] = [all_profile_lat_label[p_index]]
        selected_profile_lon_label_bokeh.data['lon_label'] = [all_profile_lon_label[p_index]]
        selected_profile_lat_label_bokeh.change.emit()
        selected_profile_lon_label_bokeh.change.emit()
        
    """)
    profile_slider = Slider(start=0, end=nprofile-1, value=style_parameter['profile_default_index'], \
                           step=1, title=style_parameter['profile_slider_title'], \
                           width=style_parameter['profile_plot_width'], height=50,\
                           callback=profile_slider_callback)
    profile_slider_callback.args['profile_index'] = profile_slider
    # ==============================
    simple_text_button_callback = CustomJS(args=dict(button_data_all_bokeh=button_data_all_bokeh,\
                                                    selected_dot_on_map_bokeh=selected_dot_on_map_bokeh), \
                                           code="""
        var index = selected_dot_on_map_bokeh.data['index']
        
        var button_data_vs = button_data_all_bokeh.data['button_data_all_vs'][index]
        var button_data_vp = button_data_all_bokeh.data['button_data_all_vp'][index]
        var button_data_rho = button_data_all_bokeh.data['button_data_all_rho'][index]
        var button_data_top = button_data_all_bokeh.data['button_data_all_top'][index]
        
        var csvContent = "data:text;charset=utf-8,"
        var i = 0
        var temp = csvContent
        temp += "# Layer Top (km)      Vs(km/s)    Vp(km/s)    Rho(g/cm^3) \\n"
        while(button_data_vp[i]) {
            temp+=button_data_top[i].toPrecision(6) + "    " + button_data_vs[i].toPrecision(4) + "   " + \
                    button_data_vp[i].toPrecision(4) + "   " + button_data_rho[i].toPrecision(4) + "\\n"
            i = i + 1
        }
        var encodedUri = encodeURI(temp)
        link = document.createElement('a');
        link.setAttribute('href', encodedUri);
        link.setAttribute('download', 'vel_model.txt');
        link.click();
        
    """)

    simple_text_button = Button(label=style_parameter['simple_text_button_label'], button_type='default', width=style_parameter['button_width'],\
                                callback=simple_text_button_callback)
    # ------------------------------
    model96_button_callback = CustomJS(args=dict(button_data_all_bokeh=button_data_all_bokeh,\
                                                    selected_dot_on_map_bokeh=selected_dot_on_map_bokeh), \
                                           code="""
        var index = selected_dot_on_map_bokeh.data['index']
        var lat = selected_dot_on_map_bokeh.data['lat']
        var lon = selected_dot_on_map_bokeh.data['lon']
        
        var button_data_vs = button_data_all_bokeh.data['button_data_all_vs'][index]
        var button_data_vp = button_data_all_bokeh.data['button_data_all_vp'][index]
        var button_data_rho = button_data_all_bokeh.data['button_data_all_rho'][index]
        var button_data_top = button_data_all_bokeh.data['button_data_all_top'][index]
        
        var csvContent = "data:text;charset=utf-8,"
        var i = 0
        var temp = csvContent
        temp +=  "MODEL." + index + " \\n"
        temp +=  "ShearVelocityModel Lat: "+ lat +"  Lon: " + lon + "\\n"
        temp +=  "ISOTROPIC \\n"
        temp +=  "KGS \\n"
        temp +=  "SPHERICAL EARTH \\n"
        temp +=  "1-D \\n"
        temp +=  "CONSTANT VELOCITY \\n"
        temp +=  "LINE08 \\n"
        temp +=  "LINE09 \\n"
        temp +=  "LINE10 \\n"
        temp +=  "LINE11 \\n"
        temp +=  "      H(KM)   VP(KM/S)   VS(KM/S) RHO(GM/CC)     QP         QS       ETAP       ETAS      FREFP      FREFS \\n"
        while(button_data_vp[i+1]) {
            var thickness = button_data_top[i+1] - button_data_top[i]
            temp+="      " +thickness.toPrecision(6) + "    " + button_data_vp[i].toPrecision(4) + "      " + button_data_vs[i].toPrecision(4) \
                 + "      " + button_data_rho[i].toPrecision(4) + "     0.00       0.00       0.00       0.00       1.00       1.00" + "\\n"
            i = i + 1
        }
        var encodedUri = encodeURI(temp)
        link = document.createElement('a');
        link.setAttribute('href', encodedUri);
        link.setAttribute('download', 'vel_model96.txt');
        link.click();
    """)
    model96_button = Button(label=style_parameter['model96_button_label'], button_type='default', width=style_parameter['button_width'],\
                                callback=model96_button_callback)
    # ==============================
    # annotating text
    annotating_fig01 = Div(text=style_parameter['annotating_html01'], \
        width=style_parameter['annotation_plot_width'], height=style_parameter['annotation_plot_height'])
    annotating_fig02 = Div(text=style_parameter['annotating_html02'],\
        width=style_parameter['annotation_plot_width'], height=style_parameter['annotation_plot_height'])
    # ==============================
    output_file(filename,title=style_parameter['html_title'], mode=style_parameter['library_source'])
    left_column = Column(depth_slider, map_view, colorbar_fig, annotating_fig01, width=style_parameter['left_column_width'])
    button_pannel = Row(simple_text_button, model96_button)
    right_column = Column(profile_slider, profile_fig, button_pannel, annotating_fig02, width=style_parameter['right_column_width'])
    layout = Row(left_column, right_column)
    save(layout)
    state = state1
    source.stream(new_data, 200)


#if __name__ == '__main__':

# globals - for bokeh plotting
n = 50
model, target_model = build_model(), build_model()
epsilon = 1  # initial exploration rate

av, rewards = deque(maxlen=100), deque(maxlen=100)
replay_buffer = deque(maxlen=1000000)
state = [4, 0, 5]  # initial state: left lane, position, right lane
turn = 0

source = ColumnDataSource(dict(x=[], x_lag=[], l1=[], pos=[], l2=[], av0=[]))

fig = Figure(plot_width=1200, plot_height=400)
fig.line(source=source, x="x", y="l1", line_width=2, alpha=.85, color="red")
fig.line(source=source, x="x", y="l2", line_width=2, alpha=.85, color="red")
fig.line(source=source,
         x="x_lag",
         y="av0",
         line_width=2,
         alpha=.85,
         color="green")

curdoc().add_root(fig)
curdoc().add_periodic_callback(update, 50)
# initialize plot
toolset = "crosshair,pan,reset,wheel_zoom,box_zoom"
# Generate a figure container
plot = Figure(
    plot_height=ode_settings.y_res,
    plot_width=ode_settings.x_res,
    tools=toolset,
    # title=text.value,
    title=ode_settings.title,
    x_range=[ode_settings.min_time, ode_settings.max_time],
    y_range=[ode_settings.min_y, ode_settings.max_y])
# Plot the numerical solution by the x,t values in the source property
plot.line('t_num',
          'x_num',
          source=source_num,
          line_width=2,
          line_alpha=0.6,
          color='black',
          line_dash=[7, 5])
plot.circle('t_num',
            'x_num',
            source=source_num,
            color='red',
            legend_label='numerical solution')
# Plot the analytical solution by the x_ref,t values in the source property
plot.line('t_ref',
          'x_ref',
          source=source_ref,
          color='green',
          line_width=3,
          line_alpha=0.6,
Esempio n. 32
0
p = Figure(tools="", height=800, width=850)
p.grid.grid_line_color = None
p.axis.visible = False
p.grid.grid_line_color = None
p.axis.visible = False
p.y_range = Range1d(-.25, 1.35)
p.x_range = Range1d(-.15, 1.55)

# plot simplex
left_corner = [0.0, 0.0]
right_corner = [np.sqrt(2), 0.0]
top_corner = [np.sqrt(2) / 2.0, np.sqrt(6) / 2.0]

p.line([left_corner[0], top_corner[0]], [left_corner[1], top_corner[1]],
       color='black',
       line_width=2)
p.line([right_corner[0], top_corner[0]], [right_corner[1], top_corner[1]],
       color='black',
       line_width=2)
p.line([left_corner[0], right_corner[0]], [left_corner[1], right_corner[1]],
       color='black',
       line_width=2)

left_label = Label(x=left_corner[0],
                   y=left_corner[1],
                   text='Pr(0, 0, 1)',
                   render_mode='css',
                   x_offset=-5,
                   y_offset=-30,
                   text_align='center')
Esempio n. 33
0
def hst_spec(result_dict, plot=True, output_file='hstspec.html', model=True):
    """Plot 1d spec with error bars for hst 
    
    Parameters
    ----------
    result_dict : dict 
        Dictionary from pandexo output.
    
    plot : bool 
        (Optional) True renders plot, False does not. Default=True
    model : bool 
        (Optional) Plot model under data. Default=True
    output_file : str
        (Optional) Default = 'hstspec.html'    
    
    Return
    ------
    x : numpy array
        micron
    y : numpy array
        1D spec fp/f* or rp^2/r*^2
    e : numpy array
        1D rms noise
    modelx : numpy array
        micron
    modely : numpy array
        1D spec fp/f* or rp^2/r*^2        
    See Also
    --------
    hst_time
    """
    TOOLS = "pan,wheel_zoom,box_zoom,resize,reset,save"
    #plot planet spectrum
    mwave = result_dict['planet_spec']['model_wave']
    mspec = result_dict['planet_spec']['model_spec']

    binwave = result_dict['planet_spec']['binwave']
    binspec = result_dict['planet_spec']['binspec']

    error = result_dict['planet_spec']['error']
    error = np.zeros(len(binspec)) + error
    xlims = [
        result_dict['planet_spec']['wmin'], result_dict['planet_spec']['wmax']
    ]
    ylims = [
        np.min(binspec) - 2.0 * error[0],
        np.max(binspec) + 2.0 * error[0]
    ]

    plot_spectrum = Figure(
        plot_width=800,
        plot_height=300,
        x_range=xlims,
        y_range=ylims,
        tools=TOOLS,  #responsive=True,
        x_axis_label='Wavelength [microns]',
        y_axis_label='Ratio',
        title="Original Model with Observation")

    y_err = []
    x_err = []
    for px, py, yerr in zip(binwave, binspec, error):
        np.array(x_err.append((px, px)))
        np.array(y_err.append((py - yerr, py + yerr)))
    if model:
        plot_spectrum.line(mwave,
                           mspec,
                           color="black",
                           alpha=0.5,
                           line_width=4)
    plot_spectrum.circle(binwave, binspec, line_width=3, line_alpha=0.6)
    plot_spectrum.multi_line(x_err, y_err)

    if plot:
        outputfile(output_file)
        show(plot_spectrum)

    return binwave, binspec, error, mwave, mspec
Esempio n. 34
0
from bokeh.io import hplot
from bokeh.palettes import Spectral11

import numpy as np


x = np.linspace(-2*np.pi, 2*np.pi, 200)

colour_list = Spectral11 #[(51, 153, 51) ,(153, 51, 51), (51, 51, 153), (153, 51,153 ), (153, 51, 51)]

y = np.sin(x)
w = np.cos(x)

z = np.arcsin(x)
u = np.arccos(x)

v = np.arctan(x)
r = np.tan(x)

list_of_axis = [(y,w), (z, u), (v,r)]

tabs = []
for two in list_of_axis:
    figure_obj = Figure(plot_width = 1000, plot_height = 800, title = "these are waves")
    figure_obj.line(x, two[0], line_width = 2, line_color = colour_list[3])
    figure_obj.line(x, two[1], line_width = 2, line_color = colour_list[1])
    title = "two by two"
    tabs.append(Panel(child=figure_obj, title=title))

curdoc().add_root(Tabs(tabs=tabs))
Esempio n. 35
0
class Layout(BaseApp):
    """Define the Monitor App widgets and the Bokeh document layout.
    """
    # default sizes for widgets
    TINY = 175
    SMALL = 250
    MEDIUM = 500
    LARGE = 1000
    XLARGE = 3000

    def __init__(self):
        super().__init__()

        self.make_input_widgets()
        self.make_header()

        self.make_plot_title()
        self.make_plot()
        self.make_footnote()
        self.make_table()

    def make_input_widgets(self):
        """Define the widgets to select dataset, verification package,
        metrics and period
        """

        self.datasets_widget = Select(title="Dataset:",
                                      value=self.selected_dataset,
                                      options=self.datasets['datasets'])

        self.filters_widget = Select(title="Filter:",
                                     value=self.selected_filter,
                                     options=self.filters)

        self.packages_widget = Select(title="Verification package:",
                                      value=self.selected_package,
                                      options=self.packages['packages'])

        self.metrics_widget = Select(title="Metric:",
                                     value=self.selected_metric,
                                     options=self.metrics['metrics'])

        active = self.periods['periods'].index(self.selected_period)

        self.period_widget = RadioButtonGroup(labels=self.periods['periods'],
                                              active=active)

    def make_header(self):
        """Header area including a title and message text"""

        self.header_widget = Div()
        self.update_header()

    def update_header(self):

        title_text = "<h2>The impact of code changes on" \
                     " Key Performance Metrics</h2>"

        message_text = "<center><p style='color:red;'>{}</p>" \
                       "</center>".format(self.message)

        self.header_widget.text = "{}{}".format(title_text, message_text)

    def make_plot_title(self):
        """Plot title including metric display name and a description
        """
        self.plot_title = Div()
        self.update_plot_title()

    def update_plot_title(self):

        metric_name = self.selected_metric

        display_name = self.metrics_meta[metric_name]['display_name']
        description = self.metrics_meta[metric_name]['description']

        self.plot_title.text = "<p align='center'><strong>" \
                               "{}:</strong> {}</p>".format(display_name,
                                                            description)

    def make_plot(self):
        """Time series plot with a hover and other bokeh tools.
        """
        self.plot = Figure(x_axis_type="datetime",
                           tools="pan, wheel_zoom, xbox_zoom, \
                                  save, reset, tap",
                           active_scroll="wheel_zoom")

        self.plot.x_range.follow = 'end'
        self.plot.x_range.range_padding = 0
        self.plot.xaxis.axis_label = 'Time (UTC)'

        hover = HoverTool(tooltips=[("Time (UTC)", "@date_created"),
                                    ("CI ID", "@ci_id"),
                                    ("Metric measurement", "@formatted_value"),
                                    ("Filter", "@filter_name"),
                                    ("# of packages changed", "@count")])

        self.plot.add_tools(hover)

        self.plot.line(x='time', y='value', color='gray',
                       legend='filter_name', source=self.cds)

        self.plot.circle(x='time', y='value',
                         color='color', legend='filter_name',
                         source=self.cds, fill_color='white',
                         size=12)

        # Legend
        self.plot.background_fill_alpha = 0
        self.plot.legend.location = 'top_right'
        self.plot.legend.click_policy = 'hide'
        self.plot.legend.orientation = 'horizontal'

        # Toolbar
        self.plot.toolbar.logo = None

        self.status = Label(x=350, y=75, x_units='screen', y_units='screen',
                            text="", text_color="lightgray",
                            text_font_size='24pt',
                            text_font_style='normal')

        self.plot.add_layout(self.status)

        self.update_plot()

    def update_plot(self):

        metric_name = self.selected_metric

        display_name = self.metrics_meta[metric_name]['display_name']
        unit = self.metrics_meta[metric_name]['unit']

        if unit:
            self.plot.yaxis[0].axis_label = "{} [{}]".format(display_name,
                                                             unit)
        else:
            self.plot.yaxis[0].axis_label = "{}".format(display_name)

        self.status.text = ""

        self.update_annotations()

        if self.cds.to_df().size < 2:
            self.status.text = "No data to display"

    def update_annotations(self):

        # Remove previous annotations
        for r in self.plot.renderers:
            if r.name == 'annotation':
                r.visible = False

        specs = self.get_specs(self.selected_dataset,
                               self.selected_filter,
                               self.selected_metric)
        names = specs['names']
        thresholds = specs['thresholds']

        for name, threshold in zip(names, thresholds):
            label = Label(name='annotation',
                          x=50,
                          y=threshold,
                          x_units='screen',
                          y_units='data',
                          text=name,
                          text_font_size='8pt',
                          text_color='red')

            span = Span(name='annotation',
                        location=threshold,
                        dimension='width',
                        line_color='red',
                        line_dash='dashed',
                        line_width=0.5)

            self.plot.add_layout(label)
            self.plot.add_layout(span)

    def make_footnote(self):
        """Footnote area to include reference info
        """
        self.footnote = Div()
        self.update_footnote()

    def update_footnote(self):

        metric_name = self.selected_metric

        reference = self.metrics_meta[metric_name]['reference']

        url = reference['url']
        doc = reference['doc']
        page = reference['page']

        self.footnote.text = ""

        if url and doc and page:
            self.footnote.text = "<p align='right'>Ref.: " \
                                 "<a href='{}'>{}</a>, " \
                                 "page {}.</p>".format(url, doc, page)

    def make_table(self):
        """Make a table synched with the plot
        """
        self.table = DataTable(source=self.cds, columns=[],
                               width=Layout.LARGE, height=Layout.TINY,
                               editable=False, selectable=True,
                               fit_columns=False, scroll_to_selection=True)

        self.update_table()

    def update_table(self):

        metric_name = self.selected_metric

        display_name = self.metrics_meta[metric_name]['display_name']
        unit = self.metrics_meta[metric_name]['unit']
        if unit:
            title = "{} [{}]".format(display_name, unit)
        else:
            title = "{}".format(display_name)

        # CI ID
        template = '<a href="<%= ci_url %>" target=_blank ><%= value %></a>'
        ci_url_formatter = HTMLTemplateFormatter(template=template)

        if self.selected_metric == "validate_drp.AM1" or \
           self.selected_metric == "validate_drp.AM2":

            # Drill down app, it uses the job_id to access the data blobs
            app_url = "/dash/AMx?job_id=<%= job_id %>" \
                      "&metric={}&ci_id=<%= ci_id %>" \
                      "&ci_dataset={}".format(self.selected_metric,
                                              self.selected_dataset)

            template = '<a href="{}" ><%= formatted_value %>' \
                       '</a>'.format(app_url)

        else:
            template = "<%= formatted_value %>"

        # https://squash-restful-api-demo.lsst.codes/AMx?job_id=885
        # &metric=validate_drp.AM1

        app_url_formatter = HTMLTemplateFormatter(template=template)

        # Packages
        template = """<% for (x in git_urls) {
                      if (x>0) print(", ");
                      print("<a href=" + git_urls[x] + " target=_blank>"
                      + value[x] + "</a>")
                      }; %>
                   """

        git_url_formatter = HTMLTemplateFormatter(template=template)

        columns = [
            TableColumn(field="date_created", title="Time (UTC)",
                        sortable=True, default_sort='descending',
                        width=Layout.TINY),
            TableColumn(field="ci_id", formatter=ci_url_formatter,
                        title="CI ID", sortable=False,
                        width=Layout.TINY),
            TableColumn(field='value', formatter=app_url_formatter,
                        title=title, sortable=False, width=Layout.TINY),
            # Give room for a large list of package names
            TableColumn(field="package_names", title="Code changes",
                        formatter=git_url_formatter, width=Layout.XLARGE,
                        sortable=False)
        ]

        self.table.columns = columns

    def make_layout(self):
        """App layout
        """
        datasets = widgetbox(self.datasets_widget, width=Layout.TINY)
        filters = widgetbox(self.filters_widget, width=Layout.TINY)
        packages = widgetbox(self.packages_widget, width=Layout.SMALL)
        metrics = widgetbox(self.metrics_widget, width=Layout.SMALL)

        header = widgetbox(self.header_widget, width=Layout.LARGE)
        period = widgetbox(self.period_widget, width=Layout.LARGE)

        plot_title = widgetbox(self.plot_title, width=Layout.LARGE)

        footnote = widgetbox(self.footnote, width=Layout.LARGE)

        layout = column(header,
                        row(datasets, filters, packages, metrics),
                        period, plot_title, self.plot,
                        footnote, self.table)

        self.add_layout(layout)
function1_input = TextInput(value=convolution_settings.function1_input_init, title="my first function:")
function1_input.on_change('value', input_change)
# text input for the second function to be convolved
function2_input = TextInput(value=convolution_settings.function1_input_init, title="my second function:")
function2_input.on_change('value', input_change)

# initialize plot
toolset = "crosshair,pan,reset,resize,save,wheel_zoom"
# Generate a figure container
plot = Figure(plot_height=400, plot_width=400, tools=toolset,
              title="Convolution of two functions",
              x_range=[convolution_settings.x_min_view, convolution_settings.x_max_view],
              y_range=[convolution_settings.y_min_view, convolution_settings.y_max_view])

# Plot the line by the x,y values in the source property
plot.line('x', 'y', source=source_function1, line_width=3, line_alpha=0.6, color='red', legend='function 1')
plot.line('x', 'y', source=source_function2, color='green', line_width=3, line_alpha=0.6, legend='function 2')
plot.line('x', 'y', source=source_result, color='blue', line_width=3, line_alpha=0.6, legend='convolution')
plot.scatter('x', 'y', source=source_xmarker, color='black')
plot.line('x', 'y', source=source_xmarker, color='black', line_width=3)
plot.patch('x', 'y_pos', source=source_overlay, fill_color='blue', fill_alpha=.2)
plot.patch('x', 'y_neg', source=source_overlay, fill_color='red', fill_alpha=.2)

# calculate data
update_data()

# lists all the controls in our app
controls = widgetbox(x_value_input, function_type, function1_input, function2_input, width=400)

# make layout
curdoc().add_root(row(plot, controls, width=800))
Esempio n. 37
0
def plot():

    # FIGURES AND X-AXIS
    fig1 = Figure(title = 'Dive Profile',  plot_width = WIDTH, plot_height = HEIGHT, tools = TOOLS)
    fig2 = Figure(title = 'Dive Controls', plot_width = WIDTH, plot_height = HEIGHT, tools = TOOLS, x_range=fig1.x_range)
    fig3 = Figure(title = 'Attitude',      plot_width = WIDTH, plot_height = HEIGHT, tools = TOOLS, x_range=fig1.x_range)
    figs = gridplot([[fig1],[fig2],[fig3]])

    # Formatting x-axis
    timeticks = DatetimeTickFormatter(formats=dict(seconds =["%b%d %H:%M:%S"],
                                                   minutes =["%b%d %H:%M"],
                                                   hourmin =["%b%d %H:%M"],
                                                   hours =["%b%d %H:%M"],
                                                   days  =["%b%d %H:%M"],
                                                   months=["%b%d %H:%M"],
                                                   years =["%b%d %H:%M %Y"]))
    fig1.xaxis.formatter = timeticks
    fig2.xaxis.formatter = timeticks
    fig3.xaxis.formatter = timeticks

    # removing gridlines
    fig1.xgrid.grid_line_color = None
    fig1.ygrid.grid_line_color = None
    fig2.xgrid.grid_line_color = None
    fig2.ygrid.grid_line_color = None
    fig3.xgrid.grid_line_color = None
    fig3.ygrid.grid_line_color = None

    # INPUT WIDGETS
    collection_list = CONN[DB].collection_names(include_system_collections=False)
    gliders = sorted([platformID for platformID in collection_list if len(platformID)>2])
    gliders = Select(title = 'PlatformID', value = gliders[0], options = gliders)
    prev_glider = Button(label = '<')
    next_glider = Button(label = '>')
    glider_controlbox = HBox(children = [gliders, prev_glider, next_glider], height=80)

    chunkations = Select(title = 'Chunkation', value = 'segment', options = ['segment', '24hr', '30days', '-ALL-'])
    chunk_indicator = TextInput(title = 'index', value = '0')
    prev_chunk = Button(label = '<')
    next_chunk = Button(label = '>')
    chunk_ID   = PreText(height=80)
    chunk_controlbox = HBox(chunkations,
                            HBox(chunk_indicator, width=25),
                            prev_chunk, next_chunk,
                            chunk_ID,
                            height = 80)

    control_box = HBox(glider_controlbox,
                        chunk_controlbox)

    # DATA VARS
    deadby_date = ''
    depth    = ColumnDataSource(dict(x=[],y=[]))
    vert_vel = ColumnDataSource(dict(x=[],y=[]))

    mbpump   = ColumnDataSource(dict(x=[],y=[]))
    battpos  = ColumnDataSource(dict(x=[],y=[]))
    pitch    = ColumnDataSource(dict(x=[],y=[]))

    mfin      = ColumnDataSource(dict(x=[],y=[]))
    cfin      = ColumnDataSource(dict(x=[],y=[]))
    mroll     = ColumnDataSource(dict(x=[],y=[]))
    mheading = ColumnDataSource(dict(x=[],y=[]))
    cheading = ColumnDataSource(dict(x=[],y=[]))

    # AXIS setup
    colors = COLORS[:]

    fig1.y_range.flipped = True
    fig1.yaxis.axis_label = 'm_depth (m)'
    fig1.extra_y_ranges = {'vert_vel': Range1d(start=-50, end=50),
                           'dummy':    Range1d(start=0, end=100)}
    fig1.add_layout(place = 'right',
                    obj = LinearAxis(y_range_name = 'vert_vel',
                                     axis_label   = 'vertical velocity (cm/s)'))
    fig1.add_layout(place = 'left',
                    obj = LinearAxis(y_range_name = 'dummy',
                                     axis_label   = ' '))
    fig1.yaxis[1].visible = False
    fig1.yaxis[1].axis_line_alpha = 0
    fig1.yaxis[1].major_label_text_alpha = 0
    fig1.yaxis[1].major_tick_line_alpha = 0
    fig1.yaxis[1].minor_tick_line_alpha = 0


    fig2.yaxis.axis_label = 'pitch (deg)'
    fig2.y_range.start, fig2.y_range.end = -40,40
    fig2.extra_y_ranges = {'battpos': Range1d(start=-1, end = 1),
                           'bpump':   Range1d(start=-275, end=275)}
    fig2.add_layout(place = 'right',
                    obj = LinearAxis(y_range_name = 'battpos',
                                     axis_label = 'battpos (in)'))
    fig2.add_layout(place = 'left',
                    obj = LinearAxis(y_range_name = 'bpump',
                                     axis_label   = 'bpump (cc)'))
    fig2.yaxis[1].visible = False # necessary for spacing. later gets set to true


    fig3.yaxis.axis_label = 'fin/roll (deg)'
    fig3.y_range.start, fig3.y_range.end = -30, 30
    fig3.extra_y_ranges = {'heading': Range1d(start=0, end=360), #TODO dynamic avg centering
                           'dummy':   Range1d(start=0, end=100)}
    fig3.add_layout(place = 'right',
                    obj = LinearAxis(y_range_name = 'heading',
                                     axis_label   = 'headings (deg)'))
    fig3.add_layout(place = 'left',
                    obj = LinearAxis(y_range_name = 'dummy',
                                     axis_label   = ' '))
    fig3.yaxis[1].visible = False
    fig3.yaxis[1].axis_line_alpha = 0
    fig3.yaxis[1].major_label_text_alpha = 0
    fig3.yaxis[1].major_tick_line_alpha = 0
    fig3.yaxis[1].minor_tick_line_alpha = 0

    # PLOT OBJECTS
    fig1.line(  'x', 'y', source = depth,    legend = 'm_depth',     color = 'red')
    fig1.circle('x', 'y', source = depth,    legend = 'm_depth',     color = 'red')
    fig1.line(  'x', 'y', source = vert_vel, legend = 'vert_vel',    color = 'green',     y_range_name = 'vert_vel')
    fig1.circle('x', 'y', source = vert_vel, legend = 'vert_vel',    color = 'green',     y_range_name = 'vert_vel')
    fig1.renderers.append(Span(location = 0, dimension = 'width',    y_range_name = 'vert_vel',
                               line_color= 'green', line_dash='dashed', line_width=1))

    fig2.line(  'x', 'y', source = pitch,   legend = "m_pitch",    color = 'indigo')
    fig2.circle('x', 'y', source = pitch,   legend = "m_pitch",    color = 'indigo')
    fig2.line(  'x', 'y', source = battpos, legend = 'm_battpos',  color = 'magenta',   y_range_name = 'battpos')
    fig2.circle('x', 'y', source = battpos, legend = 'm_battpos',  color = 'magenta',   y_range_name = 'battpos')
    fig2.line(  'x', 'y', source = mbpump,  legend = "m_'bpump'",  color = 'blue',      y_range_name = 'bpump')
    fig2.circle('x', 'y', source = mbpump,  legend = "m_'bpump'",  color = 'blue',      y_range_name = 'bpump')
    fig2.renderers.append(Span(location = 0, dimension = 'width',
                               line_color= 'black', line_dash='dashed', line_width=1))
    fig3.line(  'x', 'y', source = mfin,       legend = 'm_fin',     color = 'cyan')
    fig3.circle('x', 'y', source = mfin,       legend = 'm_fin',     color = 'cyan')
    fig3.line(  'x', 'y', source = cfin,       legend = 'c_fin',     color = 'orange')
    fig3.circle('x', 'y', source = cfin,       legend = 'c_fin',     color = 'orange')
    fig3.line(  'x', 'y', source = mroll,      legend = 'm_roll',    color = 'magenta')
    fig3.circle('x', 'y', source = mroll,      legend = 'm_roll',    color = 'magenta')
    fig3.line(  'x', 'y', source = mheading,   legend = 'm_heading', color = 'blue',    y_range_name = 'heading')
    fig3.circle('x', 'y', source = mheading,   legend = 'm_heading', color = 'blue',    y_range_name = 'heading')
    fig3.line(  'x', 'y', source = cheading,   legend = 'c_heading', color = 'indigo',  y_range_name = 'heading')
    fig3.circle('x', 'y', source = cheading,   legend = 'c_heading', color = 'indigo',  y_range_name = 'heading')
    fig3.renderers.append(Span(location = 0, dimension = 'width',    y_range_name = 'default',
                               line_color= 'black', line_dash='dashed', line_width=1))

    # CALLBACK FUNCS
    def update_data(attrib,old,new):
        g = gliders.value
        chnk = chunkations.value
        chindex = abs(int(chunk_indicator.value))

        depth.data    = dict(x=[],y=[])
        vert_vel.data = dict(x=[],y=[])
        mbpump.data   = dict(x=[],y=[])
        battpos.data  = dict(x=[],y=[])
        pitch.data    = dict(x=[],y=[])

        mfin.data     = dict(x=[],y=[])
        cfin.data     = dict(x=[],y=[])
        mroll.data    = dict(x=[],y=[])
        mheading.data = dict(x=[],y=[])
        cheading.data = dict(x=[],y=[])


        depth.data,startend   = load_sensor(g, 'm_depth', chnk, chindex)

        if chnk == 'segment':
            xbd = startend[2]
            chunk_ID.text = '{} {} \n{} ({}) \nSTART: {} \nEND:   {}'.format(g, xbd['mission'],
                                                                             xbd['onboard_filename'], xbd['the8x3_filename'],
                                                                             e2ts(xbd['start']), e2ts(xbd['end']))
            if len(set(depth.data['x']))<=1 and attrib == 'chunk':
                if old > new:
                    next_chunk.clicks += 1
                else:
                    prev_chunk.clicks += 1
                return
            elif len(set(depth.data['x']))<=1 and chunk_indicator.value == 0:
                chunk_indicator.value = 1

        elif chnk in ['24hr', '30days']:
            chunk_ID.text = '{} \nSTART: {} \nEND:   {}'.format(g, e2ts(startend[0]), e2ts(startend[1]))
        elif chnk == '-ALL-':
            chunk_ID.text = '{} \nSTART: {} \nEND:   {}'.format(g,e2ts(depth.data['x'][0] /1000),
                                                                  e2ts(depth.data['x'][-1]/1000))


        vert_vel.data  = calc_vert_vel(depth.data)

        mbpump.data,_     = load_sensor(g, 'm_de_oil_vol', chnk, chindex)
        if len(mbpump.data['x']) > 1:
            #for yax in fig2.select('mbpump'):
            #    yax.legend = 'm_de_oil_vol'
            pass
        else:
            mbpump.data,_     = load_sensor(g, 'm_ballast_pumped', chnk, chindex)
            #for yax in fig2.select('mbpump'):
            #    yax.legend = 'm_ballast_pumped'
        battpos.data,_ = load_sensor(g, 'm_battpos',    chnk, chindex)
        pitch.data,_   = load_sensor(g, 'm_pitch',      chnk, chindex)
        pitch.data['y'] = [math.degrees(y) for y in pitch.data['y']]

        mfin.data,_     = load_sensor(g, 'm_fin',     chnk, chindex)
        cfin.data,_     = load_sensor(g, 'c_fin',     chnk, chindex)
        mroll.data,_    = load_sensor(g, 'm_roll',    chnk, chindex)
        mheading.data,_ = load_sensor(g, 'm_heading', chnk, chindex)
        cheading.data,_ = load_sensor(g, 'c_heading', chnk, chindex)
        mfin.data['y']     = [math.degrees(y) for y in mfin.data['y']]
        cfin.data['y']     = [math.degrees(y) for y in cfin.data['y']]
        mheading.data['y'] = [math.degrees(y) for y in mheading.data['y']]
        cheading.data['y'] = [math.degrees(y) for y in cheading.data['y']]
        mroll.data['y']    = [math.degrees(y) for y in mroll.data['y']]

        fig1.yaxis[1].visible = True
        fig2.yaxis[1].visible = True
        fig3.yaxis[1].visible = True


    #GLIDER SELECTS
    def glider_buttons(increment):
        ops = gliders.options
        new_index = ops.index(gliders.value) + increment
        if new_index >= len(ops):
            new_index = 0
        elif new_index < 0:
            new_index = len(ops)-1
        gliders.value = ops[new_index]
        chunkation_update(None, None, None) #reset chunk indicator and clicks
    def next_glider_func():
        glider_buttons(1)
    def prev_glider_func():
        glider_buttons(-1)
    def update_glider(attrib,old,new):
        chunk_indicator.value = '0'
        #update_data(None,None,None)


    gliders.on_change('value', update_glider)
    next_glider.on_click(next_glider_func)
    prev_glider.on_click(prev_glider_func)


        #CHUNK SELECTS
    def chunkation_update(attrib,old,new):
        chunk_indicator.value = '0'
        prev_chunk.clicks = 0
        next_chunk.clicks = 0
        update_data(None,None,None)
        if new == '-ALL-':
            chunk_indicator.value = '-'

    def chunk_func():
        chunkdiff = prev_chunk.clicks - next_chunk.clicks
        if chunkdiff < 0:
            prev_chunk.clicks = 0
            next_chunk.clicks = 0
            chunkdiff = 0
        print (chunkdiff)
        chunk_indicator.value = str(chunkdiff)

    def chunk_indicator_update(attrib,old,new):
        try:
            if abs(int(old)-int(new))>1: #manual update, triggers new non-manual indicator update, ie else clause below
                prev_chunk.clicks = int(new)
                next_chunk.clicks = 0
            else:
                update_data('chunk',int(old),int(new))
            print("UPDATE", old, new)
        except Exception as e:
            print(type(e),e, old, new)

    chunkations.on_change('value', chunkation_update)
    chunk_indicator.on_change('value', chunk_indicator_update)
    next_chunk.on_click(chunk_func)
    prev_chunk.on_click(chunk_func)

    update_data(None,None,None)

    return vplot(control_box, figs)
Esempio n. 38
0
    callback_policy = Enum(SliderCallbackPolicy, default="throttle", help="""
    When the callback is initiated. This parameter can take on only one of three options:
       "continuous": the callback will be executed immediately for each movement of the slider
       "throttle": the callback will be executed at most every ``callback_throttle`` milliseconds.
       "mouseup": the callback will be executed only once when the slider is released.
       The `mouseup` policy is intended for scenarios in which the callback is expensive in time.
    """)


x = [x*0.005 for x in range(2, 198)]
y = x

source = ColumnDataSource(data=dict(x=x, y=y))

plot = Figure(plot_width=400, plot_height=400)
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6, color='#ed5565')

callback_single = CustomJS(args=dict(source=source), code="""
        var data = source.data;
        var f = cb_obj.value
        x = data['x']
        y = data['y']
        for (i = 0; i < x.length; i++) {
            y[i] = Math.pow(x[i], f)
        }
        source.change.emit();
    """)


callback_ion = CustomJS(args=dict(source=source), code="""
        var data = source.data;
Esempio n. 39
0
params = sliders.keys()
Slider_instances = []

for n, param in enumerate(params):

    # create a global Slider instance for each parameter:
    exec('param{0}'.format(n) + " = Slider(" + sliders[param] + ")")

    Slider_instances.append(eval('param{0}'.format(n)))  # add Slider to list
    # get the first value for all parameters:
    exec(param + " = " + 'param{0}.value'.format(n))

# generate the first curve:
exec(new_plot_info[0])  #  execute y = f(x, params)
source = ColumnDataSource(data=dict(x=x, y=y))
plot.line('x', 'y', source=source, line_width=5, color='navy', line_alpha=0.6)

# Set up callbacks


def update_data(attrname, old, new):

    # Get the current slider values

    for n, param in enumerate(params):
        # get all parameter values:
        exec(param + " = " + 'param{0}.value'.format(n))

    # Generate the new curve:
    exec(new_plot_info[0])  #  execute y = f(x, params)
Esempio n. 40
0
def jwst_1d_spec(result_dict,
                 model=True,
                 title='Model + Data + Error Bars',
                 output_file='data.html',
                 legend=False,
                 R=False,
                 num_tran=False,
                 plot_width=800,
                 plot_height=400,
                 x_range=[1, 10]):
    """Plots 1d simulated spectrum and rebin or rescale for more transits
    
    Plots 1d data points with model in the background (if wanted). Designed to read in exact 
    output of run_pandexo. 
    
    Parameters 
    ----------
    result_dict : dict or list of dict
        Dictionary from pandexo output. If parameter space was run in run_pandexo 
        make sure to restructure the input as a list of dictionaries without they key words 
        that run_pandexo assigns. 
    model : bool 
        (Optional) True is default. True plots model, False does not plot model     
    title : str
        (Optional) Title of plot. Default is "Model + Data + Error Bars".  
    output_file : str 
        (Optional) name of html file for you bokeh plot. After bokeh plot is rendered you will 
        have the option to save as png. 
    legend : bool 
        (Optional) Default is False. True, plots legend. 
    R : float 
        (Optional) Rebin data from native instrument resolution to specified resolution. Dafult is False, 
        no binning. 
    num_tran : float
        (Optional) Scales data by number of transits to improve error by sqrt(`num_trans`)
    plot_width : int 
        (Optional) Sets the width of the plot. Default = 800
    plot_height : int 
        (Optional) Sets the height of the plot. Default = 400 
    x_range : list of int
        (Optional) Sets x range of plot. Default = [1,10]

    Returns
    -------
    x,y,e : list of arrays 
        Returns wave axis, spectrum and associated error in list format. x[0] will be correspond 
        to the first dictionary input, x[1] to the second, etc. 
        
    Examples
    --------
    
    >>> jwst_1d_spec(result_dict, num_tran = 3, R = 35) #for a single plot 
    
    If you wanted to save each of the axis that were being plotted: 
    
    >>> x,y,e = jwst_1d_data([result_dict1, result_dict2], model=False, num_tran = 5, R = 100) #for multiple 
    
    See Also
    --------
    jwst_noise, jwst_1d_bkg, jwst_1d_flux, jwst_1d_snr, jwst_2d_det, jwst_2d_sat

    """
    outx = []
    outy = []
    oute = []
    TOOLS = "pan,wheel_zoom,box_zoom,resize,reset,save"
    outputfile(output_file)
    colors = [
        'black', 'blue', 'red', 'orange', 'yellow', 'purple', 'pink', 'cyan',
        'grey', 'brown'
    ]
    #make sure its iterable
    if type(result_dict) != list:
        result_dict = [result_dict]

    if type(legend) != bool:
        legend_keys = legend
        legend = True
        if type(legend_keys) != list:
            legend_keys = [legend_keys]

    i = 0
    for dict in result_dict:
        ntran_old = dict['timing']['Number of Transits']
        #remove any nans
        y = dict['FinalSpectrum']['spectrum_w_rand']
        x = dict['FinalSpectrum']['wave'][~np.isnan(y)]
        err = dict['FinalSpectrum']['error_w_floor'][~np.isnan(y)]
        y = y[~np.isnan(y)]

        if (R == False) & (num_tran == False):
            x = x
            y = y
        elif (R != False) & (num_tran != False):
            new_wave = bin_wave_to_R(x, R)
            out = uniform_tophat_sum(
                new_wave, x,
                dict['RawData']['electrons_out'] * num_tran / ntran_old)
            inn = uniform_tophat_sum(
                new_wave, x,
                dict['RawData']['electrons_in'] * num_tran / ntran_old)
            vout = uniform_tophat_sum(
                new_wave, x, dict['RawData']['var_out'] * num_tran / ntran_old)
            vin = uniform_tophat_sum(
                new_wave, x, dict['RawData']['var_in'] * num_tran / ntran_old)
            if dict['input']['Primary/Secondary'] == 'fp/f*':
                fac = -1.0
            else:
                fac = 1.0
            rand_noise = np.sqrt(
                (vin + vout)) * (np.random.randn(len(new_wave)))
            sim_spec = fac * (out - inn + rand_noise) / out
            x = new_wave
            y = sim_spec
            err = np.sqrt(vout + vin) / out
        elif (R == False) & (num_tran != False):
            out = dict['RawData']['electrons_out'] * num_tran / ntran_old
            inn = dict['RawData']['electrons_in'] * num_tran / ntran_old
            vout = dict['RawData']['var_out'] * num_tran / ntran_old
            vin = dict['RawData']['var_in'] * num_tran / ntran_old
            if dict['input']['Primary/Secondary'] == 'fp/f*':
                fac = -1.0
            else:
                fac = 1.0
            rand_noise = np.sqrt((vin + vout)) * (np.random.randn(len(x)))
            sim_spec = fac * (out - inn + rand_noise) / out
            x = x
            y = sim_spec
            err = np.sqrt(vout + vin) / out
        elif (R != False) & (num_tran == False):
            new_wave = bin_wave_to_R(x, R)
            out = uniform_tophat_sum(new_wave, x,
                                     dict['RawData']['electrons_out'])
            inn = uniform_tophat_sum(new_wave, x,
                                     dict['RawData']['electrons_in'])
            vout = uniform_tophat_sum(new_wave, x, dict['RawData']['var_out'])
            vin = uniform_tophat_sum(new_wave, x, dict['RawData']['var_in'])
            if dict['input']['Primary/Secondary'] == 'fp/f*':
                fac = -1.0
            else:
                fac = 1.0
            rand_noise = np.sqrt(
                (vin + vout)) * (np.random.randn(len(new_wave)))
            sim_spec = fac * (out - inn + rand_noise) / out
            x = new_wave
            y = sim_spec
            err = np.sqrt(vout + vin) / out
        else:
            print(
                "Something went wrong. Cannot enter both resolution and ask to bin to new wave"
            )
            return

        #create error bars for Bokeh's multi_line
        y_err = []
        x_err = []
        for px, py, yerr in zip(x, y, err):
            np.array(x_err.append((px, px)))
            np.array(y_err.append((py - yerr, py + yerr)))
        #initialize Figure
        if i == 0:
            #Define units for x and y axis
            y_axis_label = dict['input']['Primary/Secondary']

            if y_axis_label == 'fp/f*': p = -1.0
            else: y_axis_label = '(' + y_axis_label + ')^2'

            if dict['input']['Calculation Type'] == 'phase_spec':
                x_axis_label = 'Time (secs)'
                x_range = [min(x), max(x)]
            else:
                x_axis_label = 'Wavelength [microns]'

            ylims = [
                min(dict['OriginalInput']['model_spec']) -
                0.1 * min(dict['OriginalInput']['model_spec']),
                0.1 * max(dict['OriginalInput']['model_spec']) +
                max(dict['OriginalInput']['model_spec'])
            ]
            xlims = [min(x), max(x)]

            fig1d = Figure(x_range=x_range,
                           y_range=ylims,
                           plot_width=plot_width,
                           plot_height=plot_height,
                           title=title,
                           x_axis_label=x_axis_label,
                           y_axis_label=y_axis_label,
                           tools=TOOLS,
                           background_fill_color='white')

        #plot model, data, and errors
        if model:
            mxx = dict['OriginalInput']['model_wave']
            myy = dict['OriginalInput']['model_spec']

            my = uniform_tophat_mean(x, mxx, myy)
            fig1d.line(x, my, color='black', alpha=0.2, line_width=4)
        if legend:
            fig1d.circle(x, y, color=colors[i], legend=legend_keys[i])
        else:
            fig1d.circle(x, y, color=colors[i])
        outx += [x]
        outy += [y]
        oute += [err]
        fig1d.multi_line(x_err, y_err, color=colors[i])
        i += 1
    show(fig1d)
    return outx, outy, oute
Esempio n. 41
0
from bokeh.driving import count

BUFSIZE = 200
MA12, MA26, EMA12, EMA26 = '12-tick Moving Avg', '26-tick Moving Avg', '12-tick EMA', '26-tick EMA'

source = ColumnDataSource(dict(
    time=[], average=[], low=[], high=[], open=[], close=[],
    ma=[], macd=[], macd9=[], macdh=[], color=[]
))

p = Figure(plot_width=1200, plot_height=600, toolbar_location="left")
p.x_range.follow = "end"
p.x_range.follow_interval = 100
p.background_fill_color = "#eeeeee"

p.line(x='time', y='average', alpha=0.2, line_width=3, color='navy', source=source)
p.line(x='time', y='ma', alpha=0.8, line_width=2, color='orange', source=source)
p.segment(x0='time', y0='low', x1='time', y1='high', source=source, color='black', line_width=2)
p.segment(x0='time', y0='open', x1='time', y1='close', line_width=8, color='color', source=source)

p2 = Figure(plot_width=1200, plot_height=250, toolbar_location="left", tools="pan", x_range=p.x_range)

p2.line(x='time', y='macd', color='red', source=source)
p2.line(x='time', y='macd9', color='blue', source=source)
p2.segment(x0='time', y0=0, x1='time', y1='macdh', line_width=6, color='black', alpha=0.5, source=source)

mean = Slider(title="mean", value=0, start=-0.01, end=0.01, step=0.001)
stddev = Slider(title="stddev", value=0.04, start=0.01, end=0.1, step=0.01)
mavg = Select(value=MA12, options=[MA12, MA26, EMA12, EMA26])

curdoc().add_root(VBox(HBox(mean, stddev, mavg), VBox(p, p2)))
Esempio n. 42
0
def hst_time(result_dict, plot=True, output_file='hsttime.html', model=True):
    """Plot earliest and latest start times for hst observation
    
    Parameters
    ----------
    result_dict : dict 
        Dictionary from pandexo output.
    
    plot : bool 
        (Optional) True renders plot, False does not. Default=True
    model : bool 
        (Optional) Plot model under data. Default=True
    output_file : str
        (Optional) Default = 'hsttime.html'    
    
    Return
    ------
    obsphase1 : numpy array
        earliest start time
    obstr1 : numpy array
        white light curve
    obsphase2 : numpy array
        latest start time
    obstr2 : numpy array
        white light curve
    rms : numpy array
        1D rms noise

    See Also
    --------
    hst_spec
    """
    TOOLS = "pan,wheel_zoom,box_zoom,resize,reset,save"
    #earliest and latest start times
    obsphase1 = result_dict['calc_start_window']['obsphase1']
    obstr1 = result_dict['calc_start_window']['obstr1']
    rms = result_dict['calc_start_window']['light_curve_rms']
    obsphase2 = result_dict['calc_start_window']['obsphase2']
    obstr2 = result_dict['calc_start_window']['obstr2']
    phase1 = result_dict['calc_start_window']['phase1']
    phase2 = result_dict['calc_start_window']['phase2']
    trmodel1 = result_dict['calc_start_window']['trmodel1']
    trmodel2 = result_dict['calc_start_window']['trmodel2']

    if isinstance(rms, float):
        rms = np.zeros(len(obsphase1)) + rms
    y_err1 = []
    x_err1 = []
    for px, py, yerr in zip(obsphase1, obstr1, rms):
        np.array(x_err1.append((px, px)))
        np.array(y_err1.append((py - yerr, py + yerr)))

    y_err2 = []
    x_err2 = []
    for px, py, yerr in zip(obsphase2, obstr2, rms):
        np.array(x_err2.append((px, px)))
        np.array(y_err2.append((py - yerr, py + yerr)))

    early = Figure(
        plot_width=400,
        plot_height=300,
        tools=TOOLS,  #responsive=True,
        x_axis_label='Orbital Phase',
        y_axis_label='Flux',
        title="Earliest Start Time")

    if model:
        early.line(phase1, trmodel1, color='black', alpha=0.5, line_width=4)
    early.circle(obsphase1, obstr1, line_width=3, line_alpha=0.6)
    early.multi_line(x_err1, y_err1)

    late = Figure(
        plot_width=400,
        plot_height=300,
        tools=TOOLS,  #responsive=True,
        x_axis_label='Orbital Phase',
        y_axis_label='Flux',
        title="Latest Start Time")
    if model:
        late.line(phase2, trmodel2, color='black', alpha=0.5, line_width=3)
    late.circle(obsphase2, obstr2, line_width=3, line_alpha=0.6)
    late.multi_line(x_err2, y_err2)

    start_time = row(early, late)

    if plot:
        outputfile(output_file)
        show(start_time)

    return obsphase1, obstr1, obsphase2, obstr2, rms
# initialize plot
toolset = "crosshair,pan,reset,save,wheel_zoom"
# Generate a figure container
plot = Figure(plot_height=400,
              plot_width=400,
              tools=toolset,
              title="Arc length parametrization",
              x_range=[arc_settings.x_min_view, arc_settings.x_max_view],
              y_range=[arc_settings.y_min_view, arc_settings.y_max_view])

# Plot the line by the x,y values in the source property
plot.line('x',
          'y',
          source=source_curve,
          line_width=3,
          line_alpha=1,
          color='black',
          legend_label='curve')
# quiver related to normal length parametrization
quiver = 2 * [None]
quiver[0] = my_bokeh_utils.Quiver(plot,
                                  fix_at_middle=False,
                                  line_width=2,
                                  color='blue')
plot.scatter('x',
             'y',
             source=source_point_normal,
             color='blue',
             legend_label='original parametrization')
# quiver related to arc length parametrization
    def construct_total_pnl_figure(self, x, y, t):
        str_total_pnl = "Total Pnl " + POUND_SYMBOL
        # workaround to format date in the hover tool at the moment bokeh does not supported in the tool tips
        time = [e.strftime('%d %b %Y') for e in x]
        source_total_pnl = ColumnDataSource(data=dict(x=x, y=y, time=time))

        tooltips_total_pnl = [
                ("Date", "@time"),
                ("Total Pnl", "@y{0.00}"),
            ]

        tooltips_capital = [
                ("Date", "@time"),
                ("Capital", "@y{0.00}"),
            ]

        # create a new pnl plot
        p2 = Figure(x_axis_type="datetime", title="Total Pnl/Capital Allocated " + POUND_SYMBOL,
                    toolbar_location="above", tools=['box_zoom, box_select, crosshair, resize, reset, save,  wheel_zoom'])
        # add renderers
        r1 = p2.circle(x, y, size=8, color='black', alpha=0.2, legend=str_total_pnl, source=source_total_pnl)
        r11 = p2.line(x, y, color='navy', legend=str_total_pnl, source=source_total_pnl)

        # add renderers to the HoverTool instead of to the figure so we can have different tooltips for each glyph
        p2.add_tools(HoverTool(renderers=[r1, r11], tooltips=tooltips_total_pnl))

        max_total_pnl = max(y)
        min_total_pnl = min(y)

        # offset to adjust the plot so the max and min ranges are visible
        offset = (max(abs(max_total_pnl), abs(min_total_pnl))) * 0.10
        p2.y_range = Range1d(min_total_pnl - offset, max_total_pnl + offset)

        # NEW: customize by setting attributes
        # p2.title = "Total Pnl/Capital Allocated " + POUND_SYMBOL
        p2.legend.location = "top_left"
        p2.grid.grid_line_alpha = 0
        p2.xaxis.axis_label = 'Date'
        p2.yaxis.axis_label = str_total_pnl
        p2.ygrid.band_fill_color = "olive"
        p2.ygrid.band_fill_alpha = 0.1
        p2.xaxis.formatter = DatetimeTickFormatter(formats={'days': ['%d %b'], 'months': ['%b %Y']})
        # formatter without exponential notation
        p2.yaxis.formatter = PrintfTickFormatter(format="%.0f")

        # secondary axis
        max_capital = max(t)
        min_capital = min(t)
        # offset to adjust the plot so the max and min ranges are visible
        offset = (max(abs(max_capital), abs(min_capital))) * 0.10
        p2.extra_y_ranges = {"capital": Range1d(start=min_capital - offset, end=max_capital + offset)}

        # formatter without exponential notation
        formatter = PrintfTickFormatter()
        formatter.format = "%.0f"

        # formatter=NumeralTickFormatter(format="0,0"))
        p2.add_layout(LinearAxis(y_range_name="capital", axis_label="Capital allocated " + POUND_SYMBOL,
                                 formatter=formatter), 'right')

        # create plot for capital series
        source_capital = ColumnDataSource(data=dict(x=x, t=t, time=time))
        r2 = p2.square(x, t, size=8, color='green', alpha=0.2, legend="Capital " + POUND_SYMBOL, y_range_name="capital",
                  source=source_capital)
        r22 = p2.line(x, t, color='green', legend="Capital " + POUND_SYMBOL, y_range_name="capital", source=source_capital)

        # add renderers to the HoverTool instead of to the figure so we can have different tooltips for each glyph
        p2.add_tools(HoverTool(renderers=[r2, r22], tooltips=tooltips_capital))

        return p2
Esempio n. 45
0
def plot_cumulative_line(p: Figure, source: ColumnDataSource) -> GlyphRenderer:
    # Plot cumulative line.
    cumulative_line = p.line(**CUMULATIVE_LINE_KWARGS, source=source)
    line_hover = HoverTool(**LINE_HOVER_KWARGS)
    p.add_tools(line_hover)
    return cumulative_line
Esempio n. 46
0
# Set up data
N = 200
x = [-1.]
y = [0.]
source = ColumnDataSource(data=dict(x=x, y=y))


# Set up plot
plot = Figure(plot_height=500, plot_width=500, title="ball sliding along semicircle, angle=0",
              tools="crosshair,pan,reset,resize,save,wheel_zoom",
              x_range=[-1.1, 1.1], y_range=[-1.1, 1.1])

plot.circle('x', 'y', source=source, size=10, color='navy', line_alpha=0.6)

theta_line = np.linspace(0, pi, 101)
plot.line(-np.cos(theta_line), -np.sin(theta_line), line_width=2)



# Set up widgets
titlevalue = 'ball sliding along semicircle, angle='
mu = Slider(title="mu", value=0.0, start=0, end=1, step=0.1)
tau = Slider(title="tau", value=0.0, start=0, end=10.0, step=0.1)
print mu.value

# Set up callbacks

def update_data(attrname, old, new):

    # Get the current slider values
    mu_v = mu.value
# remove grid from plot
plot.grid[0].grid_line_alpha = 0.0
plot.grid[1].grid_line_alpha = 0.0

# Plot the direction field
quiver = my_bokeh_utils.Quiver(plot)
# Plot initial values
plot.scatter('x0',
             'y0',
             source=source_initialvalue,
             color='black',
             legend_label='(x0,y0)')
# Plot streamline
plot.line('x',
          'y',
          source=source_streamline,
          color='black',
          legend_label='streamline')
# Plot critical points and lines
plot.scatter('x',
             'y',
             source=source_critical_pts,
             color='red',
             legend_label='critical pts')
plot.multi_line('x_ls',
                'y_ls',
                source=source_critical_lines,
                color='red',
                legend_label='critical lines')

# initialize controls
Esempio n. 48
0
    def create_mcmc_fit_figures(self, run_fitting_button):
        initial_fit_data_source = ColumnDataSource({
            'Folded time (days)': [],
            'Relative flux': [],
            'Fit': [],
            'Fit time': [],
            'Time (BTJD)': self.times
        })
        self_ = self
        initial_fit_figure = Figure(x_axis_label='Folded time (days)',
                                    y_axis_label='Relative flux',
                                    title=f'Initial fit {self.title}')
        parameters_table_data_source = ColumnDataSource(pd.DataFrame())
        parameters_table_columns = [
            TableColumn(field=column, title=column)
            for column in ['parameter', 'mean', 'sd', 'r_hat']
        ]
        parameters_table = DataTable(source=parameters_table_data_source,
                                     columns=parameters_table_columns,
                                     editable=True)

        def run_fitting():
            with pm.Model() as model:
                # Stellar parameters
                mean = pm.Normal("mean", mu=0.0, sigma=10.0 * 1e-3)
                u = xo.distributions.QuadLimbDark("u")
                star_params = [mean, u]

                # Gaussian process noise model
                sigma = pm.InverseGamma("sigma",
                                        alpha=3.0,
                                        beta=2 *
                                        np.median(self_.relative_flux_errors))
                log_Sw4 = pm.Normal("log_Sw4", mu=0.0, sigma=10.0)
                log_w0 = pm.Normal("log_w0",
                                   mu=np.log(2 * np.pi / 10.0),
                                   sigma=10.0)
                kernel = xo.gp.terms.SHOTerm(log_Sw4=log_Sw4,
                                             log_w0=log_w0,
                                             Q=1.0 / 3)
                noise_params = [sigma, log_Sw4, log_w0]

                # Planet parameters
                log_ror = pm.Normal("log_ror",
                                    mu=0.5 * np.log(self_.depth),
                                    sigma=10.0 * 1e-3)
                ror = pm.Deterministic("ror", tt.exp(log_ror))
                depth = pm.Deterministic("depth", tt.square(ror))

                # Orbital parameters
                log_period = pm.Normal("log_period",
                                       mu=np.log(self_.period),
                                       sigma=1.0)
                t0 = pm.Normal("t0", mu=self_.transit_epoch, sigma=1.0)
                log_dur = pm.Normal("log_dur", mu=np.log(0.1), sigma=10.0)
                b = xo.distributions.ImpactParameter("b", ror=ror)

                period = pm.Deterministic("period", tt.exp(log_period))
                dur = pm.Deterministic("dur", tt.exp(log_dur))

                # Set up the orbit
                orbit = xo.orbits.KeplerianOrbit(period=period,
                                                 duration=dur,
                                                 t0=t0,
                                                 b=b,
                                                 r_star=self.star_radius)

                # We're going to track the implied density for reasons that will become clear later
                pm.Deterministic("rho_circ", orbit.rho_star)

                # Set up the mean transit model
                star = xo.LimbDarkLightCurve(u)

                def lc_model(t):
                    return mean + tt.sum(star.get_light_curve(
                        orbit=orbit, r=ror * self.star_radius, t=t),
                                         axis=-1)

                # Finally the GP observation model
                gp = xo.gp.GP(kernel,
                              self_.times,
                              (self_.relative_flux_errors**2) + (sigma**2),
                              mean=lc_model)
                gp.marginal("obs", observed=self_.relative_fluxes)

                # Double check that everything looks good - we shouldn't see any NaNs!
                print(model.check_test_point())

                # Optimize the model
                map_soln = model.test_point
                map_soln = xo.optimize(map_soln, [sigma])
                map_soln = xo.optimize(map_soln, [log_ror, b, log_dur])
                map_soln = xo.optimize(map_soln, noise_params)
                map_soln = xo.optimize(map_soln, star_params)
                map_soln = xo.optimize(map_soln)

            with model:
                gp_pred, lc_pred = xo.eval_in_model(
                    [gp.predict(), lc_model(self_.times)], map_soln)

            x_fold = (self_.times - map_soln["t0"] + 0.5 * map_soln["period"]
                      ) % map_soln["period"] - 0.5 * map_soln["period"]
            inds = np.argsort(x_fold)
            initial_fit_data_source.data['Folded time (days)'] = x_fold
            initial_fit_data_source.data[
                'Relative flux'] = self_.relative_fluxes - gp_pred - map_soln[
                    "mean"]
            initial_fit_data_source.data[
                'Fit'] = lc_pred[inds] - map_soln["mean"]
            initial_fit_data_source.data['Fit time'] = x_fold[
                inds]  # TODO: This is terrible, you should be able to line them up *afterward* to not make a duplicate time column

            with model:
                trace = pm.sample(
                    tune=2000,
                    draws=2000,
                    start=map_soln,
                    chains=4,
                    step=xo.get_dense_nuts_step(target_accept=0.9),
                )

            trace_summary = pm.summary(
                trace, round_to='none'
            )  # Not a typo. PyMC3 wants 'none' as a string here.
            epoch = round(
                trace_summary['mean']['t0'],
                3)  # Round the epoch differently, as BTJD needs more digits.
            trace_summary['mean'] = self_.round_series_to_significant_figures(
                trace_summary['mean'], 5)
            trace_summary['mean']['t0'] = epoch
            parameters_table_data_source.data = trace_summary
            parameters_table_data_source.data[
                'parameter'] = trace_summary.index
            with pd.option_context('display.max_columns', None,
                                   'display.max_rows', None):
                print(trace_summary)
                print(f'Star radius: {self.star_radius}')
            # TODO: This should not happen automatically. Only after a button click.
            # scopes = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
            # credentials = Credentials.from_service_account_file(
            #     'ramjet/analysis/google_spreadsheet_credentials.json', scopes=scopes)
            # gc = gspread.authorize(credentials)
            # sh = gc.open('Ramjet transit candidates shared for vetting')
            # worksheet = sh.get_worksheet(0)
            # # Find first empty row.
            # empty_row_index = 1
            # for row_index in itertools.count(start=1):
            #     row_values = worksheet.row_values(row_index)
            #     if len(row_values) == 0:
            #         empty_row_index = row_index
            #         break
            # worksheet.update_cell(empty_row_index, 1, self_.tic_id)
            # worksheet.update_cell(empty_row_index, 2, str(self_.sectors).replace('[', '').replace(']', '')),
            # worksheet.update_cell(empty_row_index, 3, trace_summary['mean']['t0'])
            # worksheet.update_cell(empty_row_index, 4, trace_summary['mean']['period'])
            # worksheet.update_cell(empty_row_index, 5, trace_summary['mean']['depth'])
            # worksheet.update_cell(empty_row_index, 6, trace_summary['mean']['dur'])
            # worksheet.update_cell(empty_row_index, 7, self_.star_radius)
            # worksheet.update_cell(empty_row_index, 8, trace_summary['mean']['ror'] * self_.star_radius)

        run_fitting_button.on_click(run_fitting)
        self.plot_light_curve_source(initial_fit_figure,
                                     initial_fit_data_source,
                                     time_column_name='Folded time (days)')
        initial_fit_figure.line('Fit time',
                                'Fit',
                                source=initial_fit_data_source,
                                color='black',
                                line_width=3)
        initial_fit_figure.sizing_mode = 'stretch_width'

        return initial_fit_figure, parameters_table
    return [source1, source2, source3]


source = init_source()
oSource = list(source)

# dessin
p = Figure(plot_width=400, plot_height=400)

# Axes
p.y_range = Range1d(start=0, end=100)
p.x_range = Range1d(start=0, end=50)

# dessin
for i in range(3):
    p.line(x='x', y='y', line_width=2, line_color=color[i], source=source[i])

# création du bouton
bt = Button(label="Lance", button_type="success")

# fonction de callback
callback = CustomJS(args=dict(source=source, p=p, anim=anim),
                    code="""
    
    var x = new Array(source.length)
    var y = new Array(source.length)
    var c = new Array(source.length)        // coefficient de la droite
    var odata = new Array(source.length)    // sert à faire un reset des données
        
    function init(){
        for (var i = 0; i<source.length; i++){
Esempio n. 50
0
def distance(p1, p2):
    return ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)**0.5


p = Figure(plot_width=500,
           plot_height=300,
           y_range=(-2, 2),
           x_range=(0, 2 * math.pi),
           min_border_top=10,
           min_border_left=40)
p.toolbar.active_drag = None

# A 'curvy' function that we can use to see how good the splines approximate it
x = np.linspace(0, 2 * math.pi, num=100)
source_function = ColumnDataSource(data=dict(x=x, y=np.sin(x)))
p.line(x='x', y='y', source=source_function, color="blue", line_width=1)

# A few datapoints to get us started
source_datapoints = ColumnDataSource(
    data=dict(x=[0, 0.5 * math.pi, 1 * math.pi, 1.5 * math.pi, 2 * math.pi],
              y=[
                  0,
                  np.sin(0.5 * math.pi),
                  np.sin(1 * math.pi),
                  np.sin(1.5 * math.pi),
                  np.sin(2 * math.pi)
              ]))
p.circle(x='x',
         y='y',
         size=CIRCLE_RADIUS,
         source=source_datapoints,
Esempio n. 51
0
def create_component_hst(result_dict):
    """Generate front end plots HST
    
    Function that is responsible for generating the front-end spectra plots for HST.
    
    Parameters
    ----------
    result_dict : dict 
        The dictionary returned from a PandExo (HST) run

    Returns
    -------
    tuple
        A tuple containing `(script, div)`, where the `script` is the
        front-end javascript required, and `div` is a dictionary of plot
        objects.
    """
    TOOLS = "pan,wheel_zoom,box_zoom,resize,reset,save"

    #plot planet spectrum
    mwave = result_dict['planet_spec']['model_wave']
    mspec = result_dict['planet_spec']['model_spec']

    binwave = result_dict['planet_spec']['binwave']
    binspec = result_dict['planet_spec']['binspec']

    error = result_dict['planet_spec']['error']
    error = np.zeros(len(binspec)) + error
    xlims = [
        result_dict['planet_spec']['wmin'], result_dict['planet_spec']['wmax']
    ]
    ylims = [
        np.min(binspec) - 2.0 * error[0],
        np.max(binspec) + 2.0 * error[0]
    ]

    plot_spectrum = Figure(
        plot_width=800,
        plot_height=300,
        x_range=xlims,
        y_range=ylims,
        tools=TOOLS,  #responsive=True,
        x_axis_label='Wavelength [microns]',
        y_axis_label='(Rp/R*)^2',
        title="Original Model with Observation")

    y_err = []
    x_err = []
    for px, py, yerr in zip(binwave, binspec, error):
        np.array(x_err.append((px, px)))
        np.array(y_err.append((py - yerr, py + yerr)))

    plot_spectrum.line(mwave, mspec, color="black", alpha=0.5, line_width=4)
    plot_spectrum.circle(binwave, binspec, line_width=3, line_alpha=0.6)
    plot_spectrum.multi_line(x_err, y_err)

    #earliest and latest start times
    obsphase1 = result_dict['calc_start_window']['obsphase1']
    obstr1 = result_dict['calc_start_window']['obstr1']
    rms = result_dict['calc_start_window']['light_curve_rms']
    obsphase2 = result_dict['calc_start_window']['obsphase2']
    obstr2 = result_dict['calc_start_window']['obstr2']
    phase1 = result_dict['calc_start_window']['phase1']
    phase2 = result_dict['calc_start_window']['phase2']
    trmodel1 = result_dict['calc_start_window']['trmodel1']
    trmodel2 = result_dict['calc_start_window']['trmodel2']

    if isinstance(rms, float):
        rms = np.zeros(len(obsphase1)) + rms
    y_err1 = []
    x_err1 = []
    for px, py, yerr in zip(obsphase1, obstr1, rms):
        np.array(x_err1.append((px, px)))
        np.array(y_err1.append((py - yerr, py + yerr)))

    y_err2 = []
    x_err2 = []
    for px, py, yerr in zip(obsphase2, obstr2, rms):
        np.array(x_err2.append((px, px)))
        np.array(y_err2.append((py - yerr, py + yerr)))

    early = Figure(
        plot_width=400,
        plot_height=300,
        tools=TOOLS,  #responsive=True,
        x_axis_label='Orbital Phase',
        y_axis_label='Flux',
        title="Earliest Start Time")

    early.line(phase1, trmodel1, color='black', alpha=0.5, line_width=4)
    early.circle(obsphase1, obstr1, line_width=3, line_alpha=0.6)
    early.multi_line(x_err1, y_err1)

    late = Figure(
        plot_width=400,
        plot_height=300,
        tools=TOOLS,  #responsive=True,
        x_axis_label='Orbital Phase',
        y_axis_label='Flux',
        title="Latest Start Time")
    late.line(phase2, trmodel2, color='black', alpha=0.5, line_width=3)
    late.circle(obsphase2, obstr2, line_width=3, line_alpha=0.6)
    late.multi_line(x_err2, y_err2)

    start_time = row(early, late)

    result_comp = components({
        'plot_spectrum': plot_spectrum,
        'start_time': start_time
    })

    return result_comp
              plot_width=750,
              plot_height=650)
#Plot properties:
plot.axis.visible = False
plot.grid.visible = False
plot.toolbar.logo = None
plot.outline_line_width = 1
plot.outline_line_alpha = 0.3
plot.outline_line_color = "Black"
plot.title.text_color = "black"
plot.title.text_font_style = "bold"
plot.title.align = "center"
#########

#Plot of frames
plot.line(x='x', y='y', source=orig.pts, color="grey",
          line_width=3)  #Original stationary frame
plot.line(x='x', y='y', source=MBD.f1.pts, color=MBD.f1color,
          line_width=5)  #Frame 1
plot.line(x='x', y='y', source=MBD.f2.pts, color=MBD.f2color,
          line_width=5)  #Frame 2
plot.line(x='x', y='y', source=t_line, color="Black",
          line_width=5)  #Black line under frame righthandside

###Dashed Lines:

#dashed line that follows the deformations:
plot.line(x='x1',
          y='y1',
          source=MBD.f1.wdline,
          color="Black",
          line_width=2,
Esempio n. 53
0
        <div>
            <div>
                <span style="font-size: 15px; font-weight: bold; color: #696">Mass = @mass  Msun</span>
            </div>
            <div>
                <span style="font-size: 15px; font-weight: bold; color: #696">Vmax = </span>
                <span style="font-size: 15px; font-weight: bold; color: #696;">@vmax km / s</span>
            </div>
        </div>
        """)
plot1.add_tools(hover)

# this is a grey square grid for convenience at reading coordinates
for xx in np.arange(17) * 10. - 80:
    print(xx)
    plot1.line([xx, xx], [-50, 50], line_width=1, line_color='grey')
    plot1.line([-75, 75], [xx, xx], line_width=1, line_color='grey')

# set up the cluster vmax vs. mass plot
plot2 = Figure(plot_height=400,
               plot_width=450,
               tools="pan,reset,wheel_zoom,hover,save",
               outline_line_color='black',
               x_range=[2, 7],
               y_range=[80, 1500],
               y_axis_type='log',
               toolbar_location='right',
               title=' Outflow Properties')
plot2.background_fill_color = "beige"
plot2.title.text_font_size = '14pt'
plot2.title.align = 'center'
                y[gsubs],
                'y_hidden': [1e18] * y[gsubs].size,
                'ymag':
                -2.5 * np.log10(y[gsubs] / 3631.0)
            })

            if x.size == 1:
                glyph = plot.circle(x='x',
                                    y='y',
                                    source=source,
                                    color=colors[instrument],
                                    size=7)
            else:
                glyph = plot.line(x='x',
                                  y='y',
                                  line_alpha=0.7,
                                  source=source,
                                  line_width=3,
                                  color=colors[instrument])

            # Store a reference to every data source
            sources[(label + config).replace(" ", "")] = glyph.data_source

# http://bokeh.pydata.org/en/1.1.0/docs/user_guide/interaction/callbacks.html#userguide-interaction-jscallbacks
scode = """
        var active_labels = [];
        for (let i = 0; i < this.active.length; i++) {
            active_labels.push(this.labels[this.active[i]].toLowerCase());
            }

        // the last two arguments are Bokeh-related, and have no data
        for (let i = 0; i < arguments.length - 2; i++) {
Esempio n. 55
0
class CreateApp():

    def __init__(self, plot_info):


        N = 200
        colors = ['red', 'green', 'indigo', 'orange', 'blue', 'grey', 'purple']
        possible_inputs = ['x_axis_label', 'xrange', 'yrange', 'sliderDict', 'title', 'number_of_graphs']

        y = None
        if ".py" in plot_info[0]:
            print "handling .pyfile"
            compute = None
            exec("from " + plot_info[0][0:-3] + " import compute")
            arg_names = inspect.getargspec(compute).args
            argString = ""
            for n, arg in enumerate(arg_names):
                argString = argString + arg
                if n != len(arg_names) - 1:
                    argString = argString + ", "
            computeString = "y = compute(" + argString + ")"
            self.computeString = computeString
            self.compute = compute

        self.curve = plot_info[0]
        x_axis_label = None
        y_axis_label = None
        xrange = (0, 10)
        yrange = (0, 10)
        sliderDict = None
        title = None
        number_of_graphs = None
        legend = None
        reverseAxes = False

        self.source = []
        self.sliderList = []


        for n in range(1,len(plot_info)):
            # Update inputs
            exec(plot_info[n].strip())

        if reverseAxes:
            self.x = np.linspace(yrange[0], yrange[1], N)
        else:
            self.x = np.linspace(xrange[0], xrange[1], N)

        self.reverseAxes = reverseAxes
        if sliderDict != None:
            self.parameters = sliderDict.keys()

            for n, param in enumerate(self.parameters):
                exec("sliderInstance = Slider(" + sliderDict[param] + ")") # Todo: Fix so exec is not needed
                exec("self.sliderList.append(sliderInstance)") # Todo: Fix so exec is not needed

                # get first value of param
                exec(param + " = "  + 'self.sliderList[n].value') # Todo: Fix so exec is not needed

        # Set up plot
        self.plot = Figure(plot_height=400, plot_width=400, title=title,
                      tools="crosshair,pan,reset,resize,save,wheel_zoom",
                      x_range=xrange, y_range=yrange)
        self.plot.xaxis.axis_label = x_axis_label
        self.plot.yaxis.axis_label = y_axis_label
        # generate the first curve:
        x = self.x
        if ".py" in plot_info[0]:
            exec(computeString)
        else:
            exec(plot_info[0]) #  execute y = f(x, params)

        if type(y) is list:
            if legend == None:
                legend = [legend]*len(y)
            for n in range(len(y)):

                if self.reverseAxes:
                    x_plot = y[n]
                    y_plot = self.x
                else:
                    x_plot = self.x
                    y_plot = y[n]
                self.source.append(ColumnDataSource(data=dict(x=x_plot, y=y_plot)))
                self.plot.line('x', 'y', source=self.source[n], line_width=3, line_color=colors[n], legend=legend[n])
        else:
            if self.reverseAxes:
                x_plot = y
                y_plot = self.x
            else:
                x_plot = self.x
                y_plot = y
            self.source.append(ColumnDataSource(data=dict(x=x_plot, y=y_plot)))
            self.plot.line('x', 'y', source=self.source[0], line_width=3, legend=legend)



    def update_data(self, attrname, old, new):

        # Get the current slider values

        y = None
        x = self.x
        for n, param in enumerate(self.parameters):
            exec(param + " = "  + 'self.sliderList[n].value')
        # generate the new curve:

        if ".py" in self.curve:
            compute = self.compute
            exec(self.computeString) #  execute y = compute(x, params)
        else:
            exec(self.curve) #  execute y = f(x, params)

        if type(y) is list:
            for n in range(len(y)):
                if self.reverseAxes:
                    x_plot = y[n]
                    y_plot = self.x
                else:
                    x_plot = self.x
                    y_plot = y[n]
                self.source[n].data = dict(x=x_plot, y=y_plot)
        else:
            if self.reverseAxes:
                x_plot = y
                y_plot = x
            else:
                x_plot = x
                y_plot = y
            self.source[0].data = dict(x=x_plot, y=y_plot)
Esempio n. 56
0
        return Z

p = Figure(tools="", height=800, width=850)
p.grid.grid_line_color = None
p.axis.visible = False
p.grid.grid_line_color = None
p.axis.visible = False
p.y_range = Range1d(-.25, 1.35)
p.x_range = Range1d(-.15, 1.55)

# plot simplex
left_corner = [0.0, 0.0]
right_corner = [np.sqrt(2), 0.0]
top_corner = [np.sqrt(2)/2.0, np.sqrt(6)/2.0]

p.line([left_corner[0], top_corner[0]], [left_corner[1], top_corner[1]], color='black', line_width=2)
p.line([right_corner[0], top_corner[0]], [right_corner[1], top_corner[1]], color='black', line_width=2)
p.line([left_corner[0], right_corner[0]], [left_corner[1], right_corner[1]], color='black', line_width=2)

left_label = Label(x=left_corner[0], y=left_corner[1],
                        text='Pr(0, 0, 1)', render_mode='css',
                        x_offset=-5, y_offset=-30, text_align='center')
right_label = Label(x=right_corner[0], y=right_corner[1],
                        text='Pr(1, 0, 0)', render_mode='css',
                        x_offset=5, y_offset=-30, text_align='center')
top_label = Label(x=top_corner[0], y=top_corner[1],
                        text='Pr(0, 1, 0)', render_mode='css',
                        x_offset=0, y_offset=20, text_align='center')
p.add_layout(left_label)
p.add_layout(right_label)
p.add_layout(top_label)
Esempio n. 57
0
File: main.py Progetto: 0-T-0/bokeh
from bokeh.driving import count

BUFSIZE = 200
MA12, MA26, EMA12, EMA26 = '12-tick Moving Avg', '26-tick Moving Avg', '12-tick EMA', '26-tick EMA'

source = ColumnDataSource(dict(
    time=[], average=[], low=[], high=[], open=[], close=[],
    ma=[], macd=[], macd9=[], macdh=[], color=[]
))

p = Figure(plot_height=600, tools="xpan,xwheel_zoom,xbox_zoom,reset", x_axis_type=None)
p.x_range.follow = "end"
p.x_range.follow_interval = 100
p.x_range.range_padding = 0

p.line(x='time', y='average', alpha=0.2, line_width=3, color='navy', source=source)
p.line(x='time', y='ma', alpha=0.8, line_width=2, color='orange', source=source)
p.segment(x0='time', y0='low', x1='time', y1='high', line_width=2, color='black', source=source)
p.segment(x0='time', y0='open', x1='time', y1='close', line_width=8, color='color', source=source)

p2 = Figure(plot_height=250, x_range=p.x_range, tools="xpan,xwheel_zoom,xbox_zoom,reset")
p2.line(x='time', y='macd', color='red', source=source)
p2.line(x='time', y='macd9', color='blue', source=source)
p2.segment(x0='time', y0=0, x1='time', y1='macdh', line_width=6, color='black', alpha=0.5, source=source)

mean = Slider(title="mean", value=0, start=-0.01, end=0.01, step=0.001)
stddev = Slider(title="stddev", value=0.04, start=0.01, end=0.1, step=0.01)
mavg = Select(value=MA12, options=[MA12, MA26, EMA12, EMA26])

curdoc().add_root(VBox(HBox(mean, stddev, mavg, width=800), GridPlot(children=[[p], [p2]])))
Esempio n. 58
0
x_rejected = [] #initial data (list)
y_rejected = []
x_nonrejected = [] #initial data (list)
y_nonrejected = []
x_original = []
y_fitted = []

sourcenon = ColumnDataSource(data=dict(x_nonrejected=x_nonrejected, y_nonrejected=y_nonrejected)) #ColumnDataSource is the object where the data of the graph is stored.
sourcerej = ColumnDataSource(data=dict(x_rejected=x_rejected, y_rejected=y_rejected)) #ColumnDataSource is the object where the data of the graph is stored.
sourceall = ColumnDataSource(data=dict(x_original=x_original, y_fitted=y_fitted)) #ColumnDataSource is the object where the data of the graph is stored.

plot = Figure(plot_width=600, plot_height=600)
#plotting code
plot.circle('x_nonrejected', 'y_nonrejected', source=sourcenon, size=5, color="navy", alpha=0.5, legend="nonrejected data")# nonrejected
plot.circle('x_rejected', 'y_rejected', source=sourcerej, size=5, color="red", alpha=0.5, legend="rejected data")# rejected
plot.line('x_original', 'y_fitted', source=sourceall, color="green", line_width=2, legend="fitted model")

#plot.circle('x', 'y', source=source, line_width=3, line_alpha=0.6) #plotting by name

#defines the callback to be used:
callback = CustomJS(args=dict(sourcenon=sourcenon, sourcerej=sourcerej, sourceall=sourceall, p=plot), code="""
    console.log('Plot Generating...');

    p.reset.emit();

    var datanon = sourcenon.data;
    var datarej = sourcerej.data;
    var dataall = sourceall.data;

    var x_rejected = datarej['x_rejected']
    var y_rejected = datarej['y_rejected']
Esempio n. 59
0
            sl = len(spectrumscaled[i])
            data = dict(
                x0 = spectrumwave[i],
                y0 = spectrumscaled[i],
                yorig = spectrumflux[i],
                fluxunit = [label_format(catalog[entry]['spectra'][i]['fluxunit'])]*sl,
                x = spectrumwave[i],
                y = [y_offsets[i] + j for j in spectrumscaled[i]],
                src = [catalog[entry]['spectra'][i]['source']]*sl
            )
            if 'redshift' in catalog[entry]:
                data['xrest'] = [x/(1.0 + z) for x in spectrumwave[i]]
            if 'timeunit' in spectrum and 'time' in spectrum:
                data['epoch'] = [catalog[entry]['spectra'][i]['time'] for j in spectrumscaled[i]]
            sources.append(ColumnDataSource(data))
            p2.line('x', 'y', source=sources[i], color=mycolors[i % len(mycolors)], line_width=2)

        if 'redshift' in catalog[entry]:
            minredw = minsw/(1.0 + z)
            maxredw = maxsw/(1.0 + z)
            p2.extra_x_ranges = {"other wavelength": Range1d(start=minredw, end=maxredw)}
            p2.add_layout(LinearAxis(axis_label ="Restframe Wavelength (Å)", x_range_name="other wavelength"), 'above')

        sdicts = dict(zip(['s'+str(x) for x in range(len(sources))], sources))
        callback = CustomJS(args=sdicts, code="""
            var yoffs = [""" + ','.join([str(x) for x in y_offsets]) + """];
            for (s = 0; s < """ + str(len(sources)) + """; s++) {
                var data = eval('s'+s).get('data');
                var redshift = """ + str(z if 'redshift' in catalog[entry] else 0.) + """;
                if (!('binsize' in data)) {
                    data['binsize'] = 1.0
from bokeh.layouts import column
from bokeh.models import CustomJS, ColumnDataSource, Slider
from bokeh.plotting import Figure, output_file, show

output_file("callback.html")

x = [x * 0.005 for x in range(0, 200)]
y = x

source = ColumnDataSource(data=dict(x=x, y=y))

plot = Figure(plot_width=400, plot_height=400)
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)


def callback(source=source, window=None):
    data = source.get('data')
    f = cb_obj.get('value')
    x, y = data['x'], data['y']
    for i in range(len(x)):
        y[i] = window.Math.pow(x[i], f)
    source.trigger('change')


slider = Slider(start=0.1,
                end=4,
                value=1,
                step=.1,
                title="power",
                callback=CustomJS.from_py_func(callback))