Beispiel #1
0
def example_4():
    '''
    Demonstrates the calculation of a synthetic receiver function.
    The trftn96 command must be installed from the CPS library.
    '''

    # Create a simple test model.
    # h    The thickness of the layers
    h = np.array([10.0, 10.0, 10.0, 0.0])
    vs = np.array([3.00, 3.30, 3.50, 4.60])
    vp_vs = 1.74
    rho_vs = 0.77
    model = LayeredModel(
        h,
        vs,
        vp_vs=vp_vs,
        rho_vs=rho_vs,
    )
    # Plot the model.
    plot_model(model, show=False, params=['vp', 'vs', 'rho'])

    # Calculate the receiver function for this model.
    # Try help(LayeredModel.rfn) to see what the parameters are.
    rf_trace = model.rfn(phase='P',
                         rayp=0.05,
                         alpha=1.0,
                         dt=0.1,
                         n=512,
                         delay=5.0,
                         silent=False)

    # Plot the receiver function.
    rf_trace.plot(show=True)
Beispiel #2
0
 def show_possibilities(self, tickers='all', *args, **kwargs):
     do_print = utils.parse_kwargs("do_print", kwargs, True)
     if tickers == 'all':
         tickers = self.tickers
     else:
         tickers = utils.check_ticker_input(tickers_input=tickers,
                                            tickers_avail=self.tickers,
                                            do_print=do_print)
     for ticker in tickers:
         utils.print_issue(None, '=' * 80, do_print=do_print)
         utils.print_issue('INFO', 'Current ticker: {}'.format(ticker), do_print=do_print)
         #check if last value is nan:
         last_value_index = -1
         if not np.isnan(self.data[ticker][last_value_index]):
             utils.print_issue('WARNING', 'Last value of data set is not NaN!')
             input_message = 'Proceed anyways? '
             if not self._get_answer(input_message=input_message):
                 continue
         else:
             last_value_index = -2
         if self.break_values[ticker] is None and generic_value is None:
             utils.print_issue('ERROR', 'No break values computed for this ticker!')
             continue
         deviation = utils.parse_kwargs('deviation', kwargs, error_arg=.0125)
         bottom_value, top_value = self.break_values[ticker]
         middle_value = (top_value - bottom_value)*.5 + bottom_value
         bottom_value *= (1 - deviation)
         top_value *= (1 + deviation)
         test_values = [bottom_value, middle_value, top_value]
         for value in test_values:
             utils.print_issue(None, '-' * 80, do_print=do_print)
             utils.print_issue('INFO', 'Result for value: {}'.format(value),
                               do_print=do_print)
             #create an imag_model:
             test_model = self.copy_model()
             #assign the value to the last entry:
             test_model.data[ticker][-1] = value
             #init model
             test_model._init_model(do_print=False)
             test_model.eval_model(do_print=False)
             p_range = utils.parse_kwargs('plot_range', kwargs, None)
             p_index = utils.parse_kwargs('plot_from_index', kwargs, None)
             p_date = utils.parse_kwargs('plot_from_date', kwargs, None)
             switch_axes = utils.parse_kwargs('switch_axes', kwargs, False)
             return_plot = utils.parse_kwargs("return_plot", kwargs, False)
             save_figures = utils.parse_kwargs("save_figures", kwargs, False)
             fig_name = "{}_imag_value_{:.2f}".format(ticker, value)
             output_folder = utils.parse_kwargs("output_folder", kwargs, None)
             plotting.plot_model(model=test_model,
                                 tickers=ticker,
                                 plot_range=p_range,
                                 plot_from_index=p_index,
                                 plot_from_date=p_date,
                                 plot_break_values=True,
                                 switch_axes=switch_axes,
                                 return_plot=return_plot,
                                 output_folder=output_folder,
                                 save_figures=save_figures,
                                 fig_name=fig_name)
Beispiel #3
0
def example_3():
    '''
    Demonstrates the calculation of sensitivity kernels using the srfker96 command in CPS (see also example 4, where sensitivity kernels are calculated using sregn96 command).
    This example requires CPS to be installed.
    '''

    # Use a pre-defined LayeredModel as the underlying structure.
    base = grand_helmberger_lm()

    # Create a model.
    h = np.array([20.0, 20.0, 40.0, 10.0, 10.0, 0.0])
    vs = np.array([3.70, 3.70, 3.70, 4.60, 4.60, 4.60])
    vp_vs = 1.74
    rho_vs = 0.77
    model = LayeredModel(
        h,
        vs,
        vp_vs=vp_vs,
        rho_vs=rho_vs,
    )  #base    = base)

    # Resample the model with finer layers.
    # Although this slows down the calculation the eigenfunctions are only output at the layer boundaries, so it is necessary to have many layers to get a clear picture of the eigenfunctions.
    model = model.resample()

    # Plot the model.
    plot_model(model, show=False, params=['vp', 'vs', 'rho'])

    # Define the periods at which the sensitivity kernels will be calculated.
    periods = np.array(
        [20.0, 25.0, 30.0, 40.0, 50.0, 60.0, 70.0, 85.0, 100.0, 120.0, 140.0])

    # Calculate the sensitivity of the phase speed (c) of the fundamental mode (0) to the shear wave speed (b).
    dv = 'c'
    iv = 'b'
    sensitivity = model.sensitivity(periods,
                                    mode=0,
                                    dv='c',
                                    iv='b',
                                    spherical=False)

    # Plot sensitivity kernels.
    plot_kernels_srfker96(model,
                          periods,
                          sensitivity=sensitivity,
                          dv=dv,
                          iv=iv,
                          smoothing=True,
                          fill_between=False,
                          colours=None,
                          show=True)
Beispiel #4
0
def example_5():
    '''
    Demonstrates the calculation of the Earth response function.
    This example requires respknt to be installed.
    '''

    # Load a pre-defined layered model from <models.py>.
    # This model will be used as a 'base' to extend the model we define.
    # In this case we choose the shield model of Grand and Helmberger (1984).
    base = grand_helmberger_lm()

    # Create a simple test model.
    # h    The thickness of the layers
    h = np.array([10.0, 10.0, 10.0, 0.0])
    vs = np.array([3.00, 3.30, 3.50, 4.60])
    vp_vs = 1.74
    rho_vs = 0.77
    model = LayeredModel(
        h,
        vs,
        vp_vs=vp_vs,
        rho_vs=rho_vs,
    )
    # Plot the model.
    plot_model(model, show=False, params=['vp', 'vs', 'rho'])

    # Create a synthetic seismogram by calculating the Earth response function and convolving it with the source-time function <./data/st.sac>.
    t_synth, synth, synth_trace = model.earth_response(
        phase='p',
        component='z',
        ray_param=0.05,
        dt=0.01,
        Dt=45.0,
        src_time_file='data/st.sac',
        clip=False,
        silent=False)

    # Plot the synthetic seismogram.
    synth_trace.plot(show=True)
Beispiel #5
0
def example_1():
    '''
    Demonstrates creation of LayeredModel and calculation of dispersion.
    This example requires CPS to be installed.
    '''

    # Create a layered model with increasing Vs with depth and constant Vp/Vs and rho/Vs ratios.
    h = np.array([20.0, 20.0, 40.0, 10.0, 10.0, 0.0])
    vs = np.array([3.70, 3.70, 3.70, 4.60, 4.60, 5.00])
    vp_vs = 1.74
    rho_vs = 0.77
    model = LayeredModel(h, vs, vp_vs=vp_vs, rho_vs=rho_vs)

    # Plot the model.
    plot_model(model, show=False, params=['vp', 'vs', 'rho'])

    # Calculate fundamental-model Rayleigh wave dispersion for phase speed and group speed at 100 different periods.
    period_min = 30.0  # seconds
    period_max = 100.0
    n_periods = 100
    periods = np.linspace(period_min, period_max, num=n_periods)
    #
    period_list, c_list, u_list = model.dispersion(periods,
                                                   silent=False,
                                                   n_modes=1,
                                                   rayleigh=True,
                                                   spherical=False,
                                                   eigenfuncs=False,
                                                   kernels=False)

    # Plot the dispersion curves.
    plot_dispersion(period_list,
                    c=c_list,
                    u=u_list,
                    show=True,
                    x_label='Frequency / Hz',
                    y_label='Phase and group speed / km s$^{-1}$')
Beispiel #6
0
    N = 1  # tilpasning for plottefunksjonen
    I **= 2
    _, C1 = sp.get_data_spiral_2d(I)
    C = np.reshape(C1, I)
    print("C: ", np.shape(C))
    return algoritme(N,
                     grad=gradient,
                     y0=x,
                     C=C,
                     K=K,
                     sigma=sigma,
                     h=h,
                     Wk=Wk,
                     bk=bk,
                     w=w,
                     mu=mu,
                     C1=C1,
                     I=I)[5]


def last_function(x, w=w, mu=mu, I=I):
    return eta(np.transpose(x) @ w + mu * np.ones(I**2))  # x = siste Y_K)


#Fungerer best for mange iterasjoner:
Y_K, Wk, bk, w, mu, arr_z = algoritme(60000, gradient, y0, C, K, sigma, h, Wk,
                                      bk, w, mu)
plot_progression(Y_K, np.transpose(C1))
plot_model(forward_function, y0, np.transpose(C1), I)
plot_separation(last_function, Y_K[-1, :, :], C1, I)
Beispiel #7
0
def main(args):
    """Main function."""
    
    tickers = args["tickers"]
    start_date_delta = args["startDateDelta"]
    plot_date_delta = args["plotDateDelta"]
    day_hour = args["dayHour"]
    entry_money = _get_as_str(args["entryMoney"], str, 0)
    #set plotting:
    save_figures = args["saveFigures"]
    if save_figures:
        return_plot = False
    else:
        return_plot = True
    #prepare output_folder:
    todays_date = pd.Timestamp.today()
    output_folder = _get_as_str(args["outputFolder"], str)
    if output_folder is not None:
        if output_folder == "auto":
            output_folder = "OUTPUT/{}".format(todays_date.strftime("%Y_%m_%d"))
        create_folder(output_folder)
    else:
        return_plot = True
        
    #set log file:
    log_file = args["writeLogFile"]
    if log_file:
        if output_folder is not None:
            log_file = "{}/log.txt".format(output_folder)
        else:
            log_file = "log.txt"
        logging.basicConfig(filename=log_file, level=logging.INFO)
        logger = logging.getLogger()
        sys.stderr.write = logger.error
        sys.stdout.write = logger.info
    else:
        #TODO: decide what happens here:
        pass
    do_print = True    
    #main function starts here:
    #specify dates:
    start_date = todays_date - pd.Timedelta("{} days".format(start_date_delta))
    filter_date = start_date.floor(freq="D").replace(hour=day_hour)
    #get data:
    model = MODEL(tickers=tickers)
    model.get_data(start=start_date, interval="60m")
    #filter by datetime:
    date_range = utils.create_date_range(start_date=filter_date)
    model.apply_date_filter(date_range, force_apply=True, do_print=do_print)
    #eval model:
    model.eval_model(tickers=tickers, entry_money=entry_money, do_print=do_print)
    #plotting:
    plot_date = todays_date - pd.Timedelta("{} days".format(plot_date_delta))
    plot_start = str(plot_date.date())
    plotting.plot_model(model, tickers=tickers,
                        plot_from_date=plot_start,
                        return_plot=return_plot,
                        save_figures=save_figures,
                        output_folder=output_folder,
                        do_print=do_print)
    #imag_model:
    imag_model = model.copy_model()
    imag_model.append_timedelta(timedelta=1, do_print=do_print)
    #compute break values:
    imag_model.comp_break_values(tickers="all", 
                                 parallel_computing=True, 
                                 do_print=do_print)
    #init model:
    imag_model._init_model(do_print=do_print)
    #show possibilities:
    imag_model.show_possibilities(plot_from_date=plot_start, 
                                  switch_axes=False, 
                                  return_plot=return_plot,
                                  save_figures=save_figures,
                                  output_folder=output_folder,
                                  do_print=do_print)
    #calulate statistics:
    fstats_pct_chg.calc_probs(model=imag_model, 
                              tickers="all", 
                              auto_update_tolerances=True,
                              return_plot=return_plot,
                              save_figures=save_figures,
                              output_folder=output_folder)
    #disable logger here:
    sys.stdout = sys.__stdout__
    sys.stderr = sys.__stderr__
def case_worksheet_9():
    """
    Experiment
    number	Date and time	Duration
    [hours]	Product created [g], per unit sugar used
    1	06 May 2019 09:36	24.0	23
    2	06 May 2019 09:37	48.0	64
    3	06 May 2019 09:38	36.0	51
    4	06 May 2019 09:38	36.0	54
    5	06 May 2019 09:40	60.0	71
    6	20 May 2019 10:33	75.0	79
    7	20 May 2019 10:40	90.0	81
    8	20 May 2019 10:44	95.0	82
    9	20 May 2019 10:45	105.0	67
    """
    d1 = c(24,
           48,
           center=36,
           range=(24, 48),
           coded=False,
           units='hours',
           name='Duration')
    D1 = d1.to_coded()
    y1 = c(23, 64, name="Production", units="g/unit sugar")
    expt1 = gather(D=D1, y=y1, title="Starting off")
    model1 = lm("y ~ D", data=expt1)
    summary(model1)
    p = plot_model(model1, "D", "y", xlim=(-2, 5), color="blue")

    d2 = d1.extend([36, 36])
    D2 = d2.to_coded()
    y2 = y1.extend([51, 54])
    expt2 = gather(D=D2, y=y2, title="Added 2 center points")

    # Model 2: y = intercept + D
    model2 = lm("y ~ D", data=expt2)
    summary(model2)
    p = plot_model(model2, "D", "y", fig=p, xlim=(-2, 5), color="darkgreen")

    # Model 2B: y = intercept + D + D^2
    model2B = lm("y ~ D + I(D**2)", data=expt2)
    summary(model2B)
    p = plot_model(model2B, "D", "y", fig=p, xlim=(-2, 5), color="red")

    # Try a new point at +2:
    d3 = d2.extend([60])
    D3 = d3.to_coded()
    predict(model2B, D=D3)  # predicts ___

    # Actual y = 71. Therefore, our model isn't so good. Improve it:
    y3 = y2.extend([71])
    expt3 = gather(D=D3, y=y3, title="Extend out to +2 (coded)")
    model3 = lm("y ~ D + I(D**2)", data=expt3, name='Quadratic model')
    summary(model3)

    # Plot it again: purple
    p = plot_model(model3, "D", "y", fig=p, xlim=(-2, 5), color="purple")

    #------------
    # Normally at this point I would reset the frame of reference;
    # keep our range the same (24 hours)
    # -1: 36 hours [prior coded "0" now becomes "-1]
    #  0: 48 hours [prior coded "+1" now becomes "0"]
    # +1: 60 hours [prior coded "+2" now becomes "+1"]

    # At this point I will also switch the model type back to real-world units.
    # For 2 reasons: there is only 1 variable that is interesting (duration), so
    # coded units don't matter; secondly the model types we will use cannot be
    # built when the coded x-value is negative.
    d4 = c(24, 48, 36, 36, 60, coded=False, units='hours', name='Duration')
    y4 = c(23, 64, 51, 54, 71, name="Production", units="g/unit sugar")
    """
    Experiment
    number	Date and time	Duration
    [hours]	Product created [g], per unit sugar used
    1	06 May 2019 09:36	24.0	23
    2	06 May 2019 09:37	48.0	64
    3	06 May 2019 09:38	36.0	51
    4	06 May 2019 09:38	36.0	54
    5	06 May 2019 09:40	60.0	71
    6	20 May 2019 10:33	75.0	79
    7	20 May 2019 10:40	90.0	81
    8	20 May 2019 10:44	95.0	82
    9	20 May 2019 10:45	105.0	67
    """

    # Rebuild the model, and start the plots again. Try different model type
    expt4 = gather(d=d4, y=y4, title="Switch over to real-world units")
    model4 = lm("y ~ d + I(d**2)", data=expt4)
    summary(model4)
    p = plot_model(model4, "d", "y", xlim=(20, 105), color="purple")

    # Let's see how well this model fits. If we run an experiment at 75 hours,
    # we should notice a drop-off. But, predict it first:
    d5 = d4.extend([75])
    print(predict(model4, d=d5))

    # Expect a predicted value of 57 in the output. # Actual result: 79.
    # Bad prediction.

    # Let's try a different model structure: y = intercept + 1/d
    y5 = y4.extend([79])
    expt5 = gather(d=d5, y=y5, title="Hyperbolic model")
    model5 = lm("y ~ I(1/d)", data=expt5)
    summary(model5)
    p = plot_model(model5, "d", "y", fig=p, xlim=(20, 105), color="darkgreen")

    # -------
    # Let's try at around 90 hours. Expect an outcome of around 83 units.
    d6 = d5.extend([90])
    print(predict(model5, d=d6))

    # Got a value of 81 instead. Stabilized?
    y6 = y5.extend([81])
    expt6 = gather(d=d6, y=y6, title="Hyperbolic model with point at d=90 hrs")
    # Rebuild the model with the new data point, keeping model structure: y=1/d
    model6 = lm("y ~  I(1/d)", data=expt6)
    summary(model6)
    p = plot_model(model6, "d", "y", fig=p, xlim=(20, 105), color="blue")

    # Try adding few more points:
    # Point 8. Try 95 hours. Seems to sqrt.  Predict 83.5; actual: 82
    # Point 9: Try 105 hour to see decline.  Predict 85.4; actual: 67
    # Massive difference: something is different in the system here?

    ## Build a model with all values now
    d7 = d6.extend([95, 105])
    print(predict(model6, d=d7))

    y7 = y6.extend([82, 67])
    expt7 = gather(d=d7, y=y7, title="Hyperbolic model all 9 points")
    model7 = lm("y ~  I(1/d)", data=expt7)
    summary(model7)
    p = plot_model(model7, "d", "y", fig=p, xlim=(20, 110), color="red")

    # The current model structure does not allow for decrease/stabilization.
    # Rebuild it with a different structure
    # Model 7:  y = 1/d               SE = 6.181
    # Model 8:  y = d + 1/sqrt(d)     SE = 4.596
    # Model 9:  y = d + 1/log(d)      SE = 4.648
    # Model 10: y = d + d^2           SE = 4.321

    model8 = lm("y ~ d + I(1/np.sqrt(d))", data=expt7, name="With sqrt term")
    summary(model8)
    p = plot_model(model8, "d", "y", fig=p, xlim=(20, 110), color="orange")

    model9 = lm("y ~ d + I(1/np.log(d))", data=expt7, name="With log term")
    summary(model9)
    p = plot_model(model9, "d", "y", fig=p, xlim=(20, 110), color="brown")

    model10 = lm("y ~ d + I(d**2)", data=expt7, name="With quadratic term")
    summary(model10)
    p = plot_model(model10, "d", "y", fig=p, xlim=(20, 110), color="darkcyan")
Beispiel #9
0
pars_opt = {scan_pars[_i]: scan_range[scan_pars[_i]][min_idx[_i]] for _i in range(len(scan_pars))}
print('\nBest parameters:')
for par in pars_opt:
    print('%s: %s' % (par, np.round(pars_opt[par], digits[par])))

# Create plot to show fit quality
cases, confirmed, dead, active = run_model(pars_opt, days.size)
fit_quality(days, confirmed_data, confirmed, dead_data, dead)
plt.savefig('img/fit_model%s.png' % identifier, bbox_inches='tight')
plt.close("all")


pred_len = 120 if (('R0-1' in scan_pars) or ('R0-lo-A' in scan_pars)) else 3
cases, confirmed, dead, active = run_model(pars_opt, days.size + pred_len)

fig, axs = plot_model(days_data, confirmed_data, confirmed, dead_data, dead, cases=cases, active=active, cut_data=False)
plt.tight_layout()
plt.savefig('img/predict_model_%s.png' % identifier, bbox_inches='tight')
plt.close()


if ('R0-lo-A' in scan_pars):
    days_pred = add_days(days_data, len(cases)-len(days_data))
    _R0 = logistic_function(np.arange(len(days_pred)), pars_opt.get('R0-0', defaults['R0-0']), pars_opt.get('R0-lo-A'),
                            pars_opt.get('R0-lo-B'), pars_opt.get('R0-lo-C'))
    plt.plot(days_pred, _R0, color='k')
    plt.xlabel("Time")
    plt.ylabel("R(0)")
    plt.grid(True)
    plt.savefig('img/reproduction_rate_%s.png' % identifier, bbox_inches='tight')
    plt.close()