Ejemplo n.º 1
0
def log_likelihood(theta, model, est_par, data):

    #Update parameters
    par = model.par
    sol = model.sol

    par = updatepar(par, est_par, theta)

    # Solve the model
    model.create_grids()
    model.solve()

    # Predict consumption
    t = data.t
    c_predict = tools.interp_linear_1d(sol.m[t, :], sol.c[t, :], data.m)
    C_predict = c_predict * data.P  #Renormalize

    # Calculate errors
    error = data.logC - np.log(C_predict)

    # Calculate log-likelihood
    log_lik_vec = -0.5 * np.log(2 * np.pi * par.sigma_eta**2)
    log_lik_vec += (-(error**2) / (2 * par.sigma_eta**2))

    return np.mean(log_lik_vec)
Ejemplo n.º 2
0
def sum_squared_diff_moments(theta, model, est_par, data):

    par = model.par
    #Update parameters
    par = updatepar(par, est_par, theta)

    # Solve the model
    model.create_grids()
    model.solve()

    # Simulate the momemnts
    moments = np.nan + np.zeros((data.moments.size, par.moments_numsim))
    for s in range(par.moments_numsim):

        # Simulate
        model.simulate()

        #Calculate moments
        moments[:, s] = calc_moments(par, model.sim)

    # Mean of moments
    moments = np.mean(moments, 1)

    # Objective function
    if hasattr(par, 'weight_mat'):
        weight_mat_inv = np.linalg.inv(par.weight_mat)
    else:
        weight_mat_inv = np.eye(moments.size)  # The identity matrix and I^-1=I

    diff = (moments - data.moments).reshape(moments.size, 1)

    return (diff.T @ weight_mat_inv @ diff).ravel()
Ejemplo n.º 3
0
def generate_vbmap(node_count,
                   replica_count,
                   replica_networks,
                   working_dir='.',
                   use_existing_solution=False):
    if working_dir is None:
        working_dir = '.'
    model = get_vbmap_gen_model()
    params = dict(n=node_count,
                  r=replica_count,
                  prev_connections=make_3d_param_string(replica_networks))
    model.working_dir = working_dir
    model.set_use_existing_solution(use_existing_solution)
    model.solve(params)
    return model
Ejemplo n.º 4
0
def main():
    # file = "instances/f1_l-d_kp_10_269"
    # items, total_weight = parser.read_file(file)
    items, total_weight = parser.read_file("instances/" + sys.argv[1])
    objective_function, m = model.solve(items, total_weight)
    model.print_used_vars(m)
    print("Objective Function: " + str(objective_function))
Ejemplo n.º 5
0
 def res_for(v):
     instance = copy.deepcopy(base_instance)
     instance[param_name] = [v] * param_length
     print(
         f'Running solve with gurobi for param with name {param_name} and value = {v}'
     )
     return model.solve(instance, origin_restricted=False)
def test_oscillation(test_type, ind_var, ind_var_vals, func_form=c.func_form):
    """
        inputs:
            test_type = dependent variable
            ind_var = variable we will be changing
            ind_var_vals = values that we will be testing over
        output:

    """
    kwargs = {
        "days_on":c.days_on,
        "lam_up":c.lam_up,
        "lam_down":c.lam_down,
        "func_form":func_form
    }
    densities = []
    frequencies = []
    max_vals = []
    min_vals = []
    decay_ratio = []
    yy_list = []
    for val in ind_var_vals:
        print(f'{ind_var} = {val}')
        kwargs[ind_var] = val
        tt, yy = model.solve(**kwargs)
        tt = tt[10000:]
        yy = yy[10000:,1]
        max_density, max_frequency = PSD(yy)
        densities.append(max_density)
        frequencies.append(max_frequency)

        min_peak, max_peak, min_index, max_index = calc_min_max(yy)
        min_vals.append(min_peak)
        max_vals.append(max_peak)
        decay_ratio.append(max_peak/min_peak)
        yy_list.append((yy, min_index, max_index))


    return tt, yy_list, [densities, frequencies, max_vals, min_vals, decay_ratio]
Ejemplo n.º 7
0
def get_timeseries(ind_var1, ind_var2, vals1, vals2, func_form=c.func_form, dosing = c.dosing, ind_var3 = None, vals3 = None):
    kwargs = {
        "days_on":c.days_on,
        "lam_up":c.lam_up,
        "lam_down":c.lam_down,
        "func_form":func_form,
        "e_dose":None,
        "p_dose":None,
        "days_missed":c.days_missed,
        "missed_start":c.missed_start
    }
    yy_array = np.zeros((len(vals1)*len(vals2),int(c.num_samples/2)))
    i = 0
    for val1 in vals1:
        j = 0
        for val2 in vals2:
            print(f'{ind_var1} = {val1}')
            print(f'{ind_var2} = {val2}')
            kwargs[ind_var1] = val1
            kwargs[ind_var2] = val2 
            if ind_var3 is not None:
                print('here')
                kwargs[ind_var3] = vals3[j]

            tt, yy = model.solve(**kwargs)

            # Getting the time series after the initial conditions have worn off and only getting LH (y-index 1)
            tt = tt[int(c.num_samples/2):]
            yy = yy[int(c.num_samples/2):,1]
            yy_array[i] = yy
            i += 1
            j+=1
    np.save(f'timeseries/{ind_var1}_{ind_var2}_days_on.npy', yy_array)
    # import module

    shutil.copyfile('config.py',f'configs/{ind_var1}_{ind_var2}_days_on.txt')
Ejemplo n.º 8
0
def main():
    graph, n = parser.read_file('Instances/instance1.txt')
    objective_function, m = model.solve(graph, n)
    model.print_used_vars(m)
    print("Objective Function: " + str(objective_function))
Ejemplo n.º 9
0
def main():
    n, m, c, f = parser.read_file('Instances/instance1.txt')
    objective_function, model_created = model.solve(n, m, c, f)
    model.print_used_vars(model_created)
    print("Objective Function: " + str(objective_function))
Ejemplo n.º 10
0
def main():
    n, p, h, f, d = parser.read_file('Instances/instance1.txt')
    objective_function, m = model.solve(n, p, h, f, d)
    print("Objective Function: " + str(objective_function))
Ejemplo n.º 11
0
def main():
    objective_function, m = model.solve()
    model.print_vars(m)
    print("Objective Function: " + str(objective_function))
Ejemplo n.º 12
0
import model
import config as c
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt

days_on_list = [21, 22, 23, 24, 25, 26, 27, 28]
days_on_list = np.linspace(21, 28, 20)

densities = []
frequencies = []

for days_on in days_on_list:
    tt, yy = model.solve(days_on)
    # plt.plot(tt,yy[1])
    yy = yy[:, 1] - yy[:, 1].mean()
    frequency, power_spectrum = signal.welch(yy)
    arg_max = power_spectrum.argmax()
    max_density = power_spectrum[arg_max]
    max_frequency = frequency[arg_max]
    # plt.plot(tt,yy)
    # plt.show()
    print(max_density)
    print(max_frequency)
    densities.append(max_density)
    frequencies.append(max_frequency)

plt.plot(days_on_list, densities)
plt.ylabel('Max density')
plt.xlabel('Days on')
plt.title('Max Power Spectral Density vs. Days On')
Ejemplo n.º 13
0
def main():
    n = parser.read_file("Instances/instance1.txt")
    objective_function, m = model.solve(n)
    print("Objective Function: " + str(objective_function))