def make_plot(source, title):
    plot = Figure(plot_width=1000, plot_height=600, tools="", toolbar_location=None, y_range=[0,0.5])
    plot.title = title
    
    # Each possible line must be created
    # In the current version of Bokeh, there is no way to hide or show lines interactively, which is
    # why the values had to be set to -1 in the get_dataset function
    plot.line(x='age_group', y='Asian', color="cornflowerblue", 
        source=source, legend="Asian", line_width=2)
    plot.line(x='age_group', y='White', color="green", 
        source=source, legend="White", line_width=2)
    plot.line(x='age_group', y='Black', color="darkviolet", 
        source=source, legend="Black", line_width=2)
    plot.line(x='age_group', y='Hispanic', color="darkgoldenrod", 
        source=source, legend="Hispanic", line_width=2)
    plot.line(x='age_group', y='Male', color="blue", 
        source=source, legend="Male", line_width=2)
    plot.line(x='age_group', y='Female', color="crimson", 
        source=source, legend="Female", line_width=2)
    plot.line(x='age_group', y='Totl', color="grey", 
        source=source, legend="Total", line_width=2)
    
    # fixed attributes
    plot.xaxis.axis_label = 'Age'
    plot.yaxis.axis_label = 'Percent with Science Degrees'
    plot.xaxis.axis_label_text_font_size = "10pt"
    plot.yaxis.axis_label_text_font_size = "10pt"
    plot.legend.label_text_font_size = "7pt"

    return plot
Exemplo n.º 2
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
Exemplo n.º 3
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
Exemplo n.º 4
0
def make_precipitation_plot(source):
    plot = Figure(x_axis_type="datetime",
                  plot_width=1000,
                  plot_height=125,
                  min_border_left=50,
                  min_border_right=50,
                  min_border_top=0,
                  min_border_bottom=0,
                  toolbar_location=None)
    plot.title = None

    plot.quad(top='actual_precipitation',
              bottom=0,
              left='left',
              right='right',
              color=Greens4[1],
              source=source)

    # fixed attributes
    plot.border_fill_color = "whitesmoke"
    plot.yaxis.axis_label = "Precipitation (in)"
    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.x_range = DataRange1d(range_padding=0.0, bounds=None)
    plot.y_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
Exemplo n.º 5
0
def hist_plot(ticker, alias, hsource, df, plot=None, selected_df=None):
    if selected_df is None:
        selected_df = df

    global_hist, global_bins = np.histogram(df[ticker + "_returns"], bins=50)
    hist, bins = np.histogram(selected_df[ticker + "_returns"], bins=50)

    top = hist.max()
    start = global_bins.min()
    end = global_bins.max()
    width = 0.7 * (bins[1] - bins[0])
    hdata = dict(
        width = [width] * len(hist),
        center = (bins[:-1] + bins[1:]) / 2,
        hist2 = hist / 2.0,
        hist = hist
    )
    hsource.data = hdata

    if plot is None:
        plot = Figure(
            plot_width=500, plot_height=200,
            tools="",
            title_text_font_size="10pt",
            x_range=[start, end],
            y_range=[0, top],
        )
        plot.rect('center', 'hist2', 'width', 'hist', source=hsource)

    plot.x_range.start = start
    plot.x_range.end = end
    plot.y_range.start = 0
    plot.y_range.end = top
    plot.title = "%s hist" % alias
    return plot
Exemplo n.º 6
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
Exemplo n.º 7
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
Exemplo n.º 8
0
    def make_plot(source, title):
        print("make plot")
        plot = Figure(x_axis_type="datetime",
                      plot_width=1000,
                      tools="",
                      toolbar_location=None)
        plot.title = title
        colors = Blues4[0:3]

        plot.quad(top='record_max_temp',
                  bottom='record_min_temp',
                  left='left',
                  right='right',
                  color=colors[2],
                  source=source,
                  legend="Record")
        plot.quad(top='average_max_temp',
                  bottom='average_min_temp',
                  left='left',
                  right='right',
                  color=colors[1],
                  source=source,
                  legend="Average")
        plot.quad(top='actual_max_temp',
                  bottom='actual_min_temp',
                  left='left',
                  right='right',
                  color=colors[0],
                  alpha=0.5,
                  line_color="black",
                  source=source,
                  legend="Actual")

        # fixed attributes
        plot.border_fill_color = "whitesmoke"
        plot.xaxis.axis_label = None
        plot.yaxis.axis_label = "Temperature (F)"
        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.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
Exemplo n.º 9
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
Exemplo n.º 10
0
def make_precipitation_plot(source):
    plot = Figure(x_axis_type="datetime", plot_width=1000, plot_height=125, min_border_left=50, min_border_right=50, min_border_top=0, min_border_bottom=0, toolbar_location=None)
    plot.title = None

    plot.quad(top='actual_precipitation', bottom=0, left='left', right='right', color=Greens4[1], source=source)

    # fixed attributes
    plot.border_fill_color = "whitesmoke"
    plot.yaxis.axis_label = "Precipitation (in)"
    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.x_range = DataRange1d(range_padding=0.0, bounds=None)
    plot.y_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
Exemplo n.º 11
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
Exemplo n.º 12
0
def create_arima_plot(
        df_history: pd.DataFrame,
        model_data: arima.MODEL_DATA
) -> Figure:
    """
    Plot the fitting data for the specified model

    :param df_history:
        The historical data that was fitted by the ARIMA model
    :param model_data:
        The MODEL_DATA instance to plot
    """

    results = model_data.results

    figure = Figure()
    figure.xaxis.axis_label = 'Year'
    figure.yaxis.axis_label = 'Temperature (Celsius)'

    df = df_history.sort_values(by='order')
    order = df['order']
    add_to_arima_plot(
        figure,
        order,
        df['temperature'].values,
        'Data',
        'blue'
    )

    add_to_arima_plot(
        figure,
        order,
        results.fittedvalues,
        'Model',
        'red'
    )

    figure.title = '({p}, {d}, {q}) RMSE: {rmse:0.4f}'.format(
        **model_data._asdict()
    )

    figure.legend.location = 'bottom_left'

    return figure
Exemplo n.º 13
0
Arquivo: main.py Projeto: 0-T-0/bokeh
def make_plot(source, title):
    plot = Figure(x_axis_type="datetime", plot_width=1000, tools="", toolbar_location=None)
    plot.title = title
    colors = Blues4[0:3]

    plot.quad(top='record_max_temp', bottom='record_min_temp', left='left', right='right', color=colors[2], source=source, legend="Record")
    plot.quad(top='average_max_temp', bottom='average_min_temp', left='left', right='right', color=colors[1], source=source, legend="Average")
    plot.quad(top='actual_max_temp', bottom='actual_min_temp', left='left', right='right', color=colors[0], alpha=0.5, line_color="black", source=source, legend="Actual")

    # fixed attributes
    plot.border_fill_color = "whitesmoke"
    plot.xaxis.axis_label = None
    plot.yaxis.axis_label = "Temperature (F)"
    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.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
Exemplo n.º 14
0
def make_plot(source,AverageTemp,Parcentile_5_Min,Parcentile_5_Max,Parcentile_25_Min,Parcentile_25_Max,MinTemp,MaxTemp,plotDate, cityName):
    
    plot = Figure(x_axis_type="datetime", plot_width=1000, tools="", title_text_font_size='12pt', toolbar_location=None)
    plot.title = 'Optional Task # 1 : Growing Degree-day for '+cityName
    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="#000000", 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.5, 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
Exemplo n.º 15
0
#For Red..............
#mean = 658nm
#FWHM = 138nm
#standard_dev = 138/2.355

r_mean = 658.0
r_start = 658.0-138.0
r_end = 658.0+138.0
r_dev = 138.0/2.335

r_x = np.linspace(r_start,r_end,1000)
r_y = bb_filter_my(r_mean,r_dev,r_x)
'''

p3 = Figure(plot_width = 500,plot_height = 500)
p3.title = "Plot at 5500K"
p3.yaxis.axis_label = "Flux"
p3.xaxis.axis_label = "Wavelength (nm)"
p3.patch(ux_pass,uz_pass,line_width = 2, line_alpha = 0.1, color = (62,6,148), legend = "Ultraviolet(U)")
p3.patch(bx_pass,bz_pass,line_width = 2, line_alpha = 0.1, color = "blue", legend = "Blue(B)")
p3.patch(vx_pass,vz_pass,line_width = 2, line_alpha = 0.1, color = "violet", legend = "Violet(V)")
p3.patch(rx_pass,rz_pass,line_width = 2, line_alpha = 0.1, color = "red", legend = "Red(R)")



#.....................................FluxVsWavelength Implementation.........................................................

x = np.linspace(50,3000,500)
#print x
y = bb_flux(x,temp)
#print y 
Exemplo n.º 16
0
def tab_learning():

    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    session = tf.Session(config=config)

    select_data = Select(title="Data:", value="", options=[])
    select_model = Select(title="Model script:", value="", options=[])

    data_descriptor = Paragraph(text=""" Data descriptor """, width=250, height=250)
    model_descriptor = Paragraph(text=""" Model descriptor """, width=250, height=250)

    select_grid = gridplot([[select_data, select_model], [data_descriptor, model_descriptor]])

    problem_type = RadioGroup(labels=["Classification", "Regression"], active=0)

    def problem_handler(new):
        if(new == 0):
            select_data.options = glob.glob('./np/Classification/*.npy')
            select_model.options = list(filter(lambda x: 'model_' in x, dir(classification)))

        elif(new == 1):
            select_data.options = glob.glob('./np/Regression/*.npy')
            select_model.options = list(filter(lambda x: 'model_' in x, dir(regression)))

    problem_type.on_click(problem_handler)

    learning_rate = TextInput(value="0.01", title="Learning rate")
    epoch_size = Slider(start=2, end=200, value=5, step=1, title="Epoch")
    batch_size = Slider(start=16, end=256, value=64, step=1, title="Batch")
    model_insert = TextInput(value="model", title="Model name")
    opeimizer = Select(title="Optimizer:", value="", options=["SGD", "ADAM", "RMS"])

    hyper_param = gridplot([[learning_rate], [epoch_size], [batch_size], [opeimizer], [model_insert]])

    xs = [[1], [1]]
    ys = [[1], [1]]
    label = [['Train loss'], ['Validation loss']]
    color = [['blue'], ['green']]
    total_loss_src = ColumnDataSource(data=dict(xs=xs, ys=ys, label=label, color=color))
    plot2 = Figure(plot_width=500, plot_height=300)
    plot2.multi_line('xs', 'ys', color='color', source=total_loss_src, line_width=3, line_alpha=0.6)
    TOOLTIPS = [("loss type", "@label"), ("loss value", "$y")]
    plot2.add_tools(HoverTool(tooltips=TOOLTIPS))
    t = Title()
    t.text = 'Loss'
    plot2.title = t

    acc_src = ColumnDataSource(data=dict(x=[1], y=[1], label=['R^2 score']))
    plot_acc = Figure(plot_width=500, plot_height=300, title="Accuracy")
    plot_acc.line('x', 'y', source=acc_src, line_width=3, line_alpha=0.7, color='red')
    TOOLTIPS = [("Type ", "@label"), ("Accuracy value", "$y")]
    plot_acc.add_tools(HoverTool(tooltips=TOOLTIPS))
    acc_list = []

    notifier = Paragraph(text=""" Notification """, width=200, height=100)

    def learning_handler():
        print("Start learning")
        del acc_list[:]

        tf.reset_default_graph()
        K.clear_session()

        data = np.load(select_data.value)
        data = data.item()

        print("data load complete")

        time_window = data.get('x').shape[-2]
        model_name = model_insert.value
        model_name = '(' + str(time_window) + ')' + model_name

        if (problem_type.active == 0):
            sub_path = 'Classification/'
        elif (problem_type.active == 1):
            sub_path = 'Regression/'

        model_save_dir = './model/' + sub_path + model_name + '/'
        if not os.path.exists(model_save_dir):
            os.makedirs(model_save_dir)

        x_shape = list(data.get('x').shape)
        print("Optimizer: " + str(opeimizer.value))

        print(select_model.value)

        if (problem_type.active == 0):
            target_model = getattr(classification, select_model.value)
            model = target_model(x_shape[-3], x_shape[-2], float(learning_rate.value), str(opeimizer.value),
                                 data.get('y').shape[-1])
        elif (problem_type.active == 1):
            target_model = getattr(regression, select_model.value)
            model = target_model(x_shape[-3], x_shape[-2], float(learning_rate.value), str(opeimizer.value),
                                 data.get('y').shape[-1])

        notifier.text = """ get model """

        training_epochs = int(epoch_size.value)
        batch = int(batch_size.value)
        loss_train = []
        loss_val = []

        train_ratio = 0.8
        train_x = data.get('x')
        train_y = data.get('y')
        length = train_x.shape[0]

        print(train_x.shape)

        data_descriptor.text = "Data shape: " + str(train_x.shape)
        # model_descriptor.text = "Model layer: " + str(model.model.summary())

        val_x = train_x[int(length * train_ratio):]
        if(val_x.shape[-1] == 1 and not 'cnn' in select_model.value):
            val_x = np.squeeze(val_x, -1)
        val_y = train_y[int(length * train_ratio):]

        train_x = train_x[:int(length * train_ratio)]
        if (train_x.shape[-1] == 1 and not 'cnn' in select_model.value):
            train_x = np.squeeze(train_x, -1)
        train_y = train_y[:int(length * train_ratio)]

        print(train_x.shape)

        if('model_dl' in select_model.value):
            for epoch in range(training_epochs):
                notifier.text = """ learning -- epoch: """ + str(epoch)

                hist = model.fit(train_x,
                                 train_y,
                                 epochs=1,
                                 batch_size=batch,
                                 validation_data=(val_x, val_y),
                                 verbose=1)

                print("%d epoch's cost:  %f" % (epoch, hist.history['loss'][0]))
                loss_train.append(hist.history['loss'][0])
                loss_val.append(hist.history['val_loss'][0])

                xs_temp = []
                xs_temp.append([i for i in range(epoch + 1)])
                xs_temp.append([i for i in range(epoch + 1)])

                ys_temp = []
                ys_temp.append(loss_train)
                ys_temp.append(loss_val)

                total_loss_src.data['xs'] = xs_temp
                total_loss_src.data['ys'] = ys_temp

                if (problem_type.active == 0):
                    r2 = hist.history['val_acc'][0]
                    label_str = 'Class accuracy'
                elif (problem_type.active == 1):
                    pred_y = model.predict(val_x)
                    r2 = r2_score(val_y, pred_y)
                    label_str = 'R^2 score'

                print("%d epoch's acc:  %f" % (epoch, r2))
                acc_list.append(np.max([r2, 0]))

                acc_src.data['x'] = [i for i in range(epoch+1)]
                acc_src.data['y'] = acc_list
                acc_src.data['label'] = [label_str for _ in range(epoch + 1)]

                print(acc_src.data)

            notifier.text = """ learning complete """
            model.save(model_save_dir + model_name + '.h5')
            notifier.text = """ model save complete """

            K.clear_session()

        elif('model_ml' in select_model.value):
            notifier.text = """ Machine learning model """

            if(train_x.shape[-2] != 1):
                notifier.text = """ Data include more then one time-frame. \n\n Data will automatically be flatten"""

            train_x = train_x.reshape([train_x.shape[0], -1])
            val_x = val_x.reshape([val_x.shape[0], -1])

            ##### shit
            if (problem_type.active == 0):
                train_y = np.argmax(train_y, axis=-1).astype(float)

            print(train_x.shape)
            print(train_y.shape)

            model.fit(train_x, train_y)
            notifier.text = """ Training done """
            pred_y = model.predict(val_x)

            print(pred_y)

            pickle.dump(model, open(model_save_dir + model_name + '.sav', 'wb'))
            notifier.text = """ Machine learning model saved """


    button_learning = Button(label="Run model")
    button_learning.on_click(learning_handler)

    learning_grid = gridplot(
        [[problem_type],
         [select_grid, hyper_param, button_learning, notifier],
         [plot2, plot_acc]])

    tab = Panel(child=learning_grid, title='Learning')

    return tab
Exemplo n.º 17
0
response_plus_noise = ColumnDataSource(data=dict(x=contrast,y=contrast**alpha + offset + (np.random.random(contrast.shape)-0.5)/CNR))
baseline = ColumnDataSource(data=dict(x=contrast,y=offset*np.ones(contrast.shape)))
baseline_plus_noise = ColumnDataSource(data=dict(x=contrast,y=offset+(np.random.random(contrast.shape)-0.5)/CNR))

# sim some data
data = np.zeros([nRep,3])
for iRep in range(nRep):
    stim = offset + np.array([0.08,0.16,0.32])**alpha + (np.random.random((1,3))-0.5)/CNR
    fonly = offset + (np.random.random()-0.5)/CNR
    data[iRep,:] = stim - fonly

p1.line('x','y',source=baseline, line_dash=[8,8], color = 'green')
p1.line('x','y',source=baseline_plus_noise, alpha=0.6, color='green')
p1.line('x','y',source=response, alpha=0.6, color='black')
p1.line('x','y',source=response_plus_noise, alpha=0.6, color='black')
p1.title = 'CNR = %2.1f' %CNR

p2.line([0,1], [0,0], line_dash=[8,8], color = 'green')
data_all = []
data_eb = []

for iC,c in enumerate([0.08,0.16,0.32]):
    data_all.append(ColumnDataSource(data=dict(x=c*np.ones([nRep]),y=data[:,iC])))
    p2.circle('x', 'y', source=data_all[iC], color='red', fill_alpha=0.3, line_alpha=0.3)
data_means = ColumnDataSource(data=dict(x=np.array([0.08,0.16,0.32]),y=np.mean(data,axis=0)))
p2.line('x', 'y', source=data_means, color='red')
for iC,c in enumerate([0.08,0.16,0.32]):
    data_eb.append(ColumnDataSource(data=dict(x=[c,c],y=np.mean(data[:,iC]) + np.std(data[:,iC])/np.sqrt(nRep)*np.array([-1,1]))))    
    p2.line('x', 'y', source=data_eb[iC], color='red')

curdoc().add_root(hplot(vplot(CNRslider,offsetSlider,nREPslider,alphaSlider,redrawButton),p1,p2)) #vform, from bokeh.io also works in there
Exemplo n.º 18
0
def temp(request):
	month = request.GET['month']
	cnx = DB.connect(host='ec500-nasa.csmyiysxb7lc.us-east-1.rds.amazonaws.com',user='******',passwd='nasaenvironment',db='environment')
	cur = cnx.cursor()

	#cur.execute("SELECT VERSION()")
	#data = cur.fetchone()
	#print "Database Version:%s" % data
	sql = "SELECT * FROM environment.Temp_Deviation_Monthly WHERE Month=%s" %month
	year =[]
	month=[]
	USCRN =[]
	CLIMDIV =[]
	CMBUSHCN =[]
	try:
		cur.execute(sql)
		data=cur.fetchall()

		for row in data:
			year.append(row[0])
			month.append(row[1])
			USCRN.append(row[2])
			CLIMDIV.append(row[3])  
			CMBUSHCN.append(row[4])    	
	
	except:
		print "Error: unable to fecth data"
		
	plot = Figure(x_range=[1895,2016], y_range=[-10,8], plot_width=1000, tools="", toolbar_location=None)
	plot.title = "Plot of temprature of month %s from 1895-2015" % month[0]
	colors = Blues4[0:3]
	plot.border_fill_color = "whitesmoke"
	plot.xaxis.axis_label = "Year"
	plot.yaxis.axis_label = "Temperature (F)"
	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.x_range = DataRange1d(range_padding=0.0, bounds=None)
	plot.grid.grid_line_alpha = 0.3
	plot.grid[0].ticker.desired_num_ticks = 12
	plot.line(year, USCRN, color='#A6CEE3', legend='AAPL')
	plot.line(year, CLIMDIV, color='#B2DF8A', legend='GOOG')
	plot.line(year, CMBUSHCN, color='#33A02C', legend='IBM')
	

	#fig=plt.figure(figsize=(16,12))
	#plt.xlabel('Year')
	#plt.ylabel('Temprature')
	#plt.style.use('ggplot')
	#plt.plot(year,USCRN,'ro-')
	#plt.plot(year,CLIMDIV,'go-')
	#plt.plot(year,CMBUSHCN,'bo-')
	#plt.axis([1895,2016,-10,8])
	#plt.title('Plot of temprature of month %s from 1895-2015' %month[0])
	#os.remove(os.getcwd() + '\Temprature.png')
	#plt.savefig(os.path.join(BASE_DIR, 'static\img\Temprature.png'),dpi=80)
	#plt.savefig(os.path.join(BASE_DIR, 'static\img\Temprature2.png'),dpi=80)
	#fig.clf()
	#plt.close(fig)
	#img=open(os.getcwd() + '\Temprature.png',"rb")
	#response = django.http.HttpResponse(content_type="image/png")
	#plt.savefig(response, format="png")
	#img=open("Temprature.png", "rb")
	#img.save(response, "PNG")
    #img.close()
	#image_bytes = requests.get(os.path.join(BASE_DIR, 'static\img\Temprature.png').content
	#image_bytes.save(response,"PNG")#lambda x: x.startswith('Temprature')
	#f = open(os.path.join(BASE_DIR, 'static\img\Temprature.png'),"rb")
	#img = f.read()
	#f.close()
	cur.close()
	cnx.close()	
	script,div=components(plot)
	return render(request, "temp.html",{"this_script": script, "this_div": div})
Exemplo n.º 19
0
def temp(request):
    month = request.GET['month']
    cnx = DB.connect(
        host='ec500-nasa.csmyiysxb7lc.us-east-1.rds.amazonaws.com',
        user='******',
        passwd='nasaenvironment',
        db='environment')
    cur = cnx.cursor()

    #cur.execute("SELECT VERSION()")
    #data = cur.fetchone()
    #print "Database Version:%s" % data
    sql = "SELECT * FROM environment.Temp_Deviation_Monthly WHERE Month=%s" % month
    year = []
    month = []
    USCRN = []
    CLIMDIV = []
    CMBUSHCN = []
    try:
        cur.execute(sql)
        data = cur.fetchall()

        for row in data:
            year.append(row[0])
            month.append(row[1])
            USCRN.append(row[2])
            CLIMDIV.append(row[3])
            CMBUSHCN.append(row[4])

    except:
        print "Error: unable to fecth data"

    plot = Figure(x_range=[1895, 2016],
                  y_range=[-10, 8],
                  plot_width=1000,
                  tools="",
                  toolbar_location=None)
    plot.title = "Plot of temprature of month %s from 1895-2015" % month[0]
    colors = Blues4[0:3]
    plot.border_fill_color = "whitesmoke"
    plot.xaxis.axis_label = "Year"
    plot.yaxis.axis_label = "Temperature (F)"
    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.x_range = DataRange1d(range_padding=0.0, bounds=None)
    plot.grid.grid_line_alpha = 0.3
    plot.grid[0].ticker.desired_num_ticks = 12
    plot.line(year, USCRN, color='#A6CEE3', legend='AAPL')
    plot.line(year, CLIMDIV, color='#B2DF8A', legend='GOOG')
    plot.line(year, CMBUSHCN, color='#33A02C', legend='IBM')

    #fig=plt.figure(figsize=(16,12))
    #plt.xlabel('Year')
    #plt.ylabel('Temprature')
    #plt.style.use('ggplot')
    #plt.plot(year,USCRN,'ro-')
    #plt.plot(year,CLIMDIV,'go-')
    #plt.plot(year,CMBUSHCN,'bo-')
    #plt.axis([1895,2016,-10,8])
    #plt.title('Plot of temprature of month %s from 1895-2015' %month[0])
    #os.remove(os.getcwd() + '\Temprature.png')
    #plt.savefig(os.path.join(BASE_DIR, 'static\img\Temprature.png'),dpi=80)
    #plt.savefig(os.path.join(BASE_DIR, 'static\img\Temprature2.png'),dpi=80)
    #fig.clf()
    #plt.close(fig)
    #img=open(os.getcwd() + '\Temprature.png',"rb")
    #response = django.http.HttpResponse(content_type="image/png")
    #plt.savefig(response, format="png")
    #img=open("Temprature.png", "rb")
    #img.save(response, "PNG")
    #img.close()
    #image_bytes = requests.get(os.path.join(BASE_DIR, 'static\img\Temprature.png').content
    #image_bytes.save(response,"PNG")#lambda x: x.startswith('Temprature')
    #f = open(os.path.join(BASE_DIR, 'static\img\Temprature.png'),"rb")
    #img = f.read()
    #f.close()
    cur.close()
    cnx.close()
    script, div = components(plot)
    return render(request, "temp.html", {
        "this_script": script,
        "this_div": div
    })
Exemplo n.º 20
0
#For Red..............
#mean = 658nm
#FWHM = 138nm
#standard_dev = 138/2.355

r_mean = 658.0
r_start = 658.0-138.0
r_end = 658.0+138.0
r_dev = 138.0/2.335

r_x = np.linspace(r_start,r_end,1000)
r_y = bb_filter_my(r_mean,r_dev,r_x)
'''

p3 = Figure(plot_width=500, plot_height=500)
p3.title = "Plot at 5500K"
p3.yaxis.axis_label = "Flux"
p3.xaxis.axis_label = "Wavelength (nm)"
p3.patch(ux_pass,
         uz_pass,
         line_width=2,
         line_alpha=0.1,
         color=(62, 6, 148),
         legend="Ultraviolet(U)")
p3.patch(bx_pass,
         bz_pass,
         line_width=2,
         line_alpha=0.1,
         color="blue",
         legend="Blue(B)")
p3.patch(vx_pass,