예제 #1
0
def stigler_ip():
    """
    Same as stigler_lp, with discrete X
    """

    solver = get_solver("CBC")

    num_items = 2
    X = [solver.IntVar(lb=0, ub=None) for _ in range(num_items)]

    # setting the constraints
    for nutrient, row in enumerate(nutrient_item2content):
        total_nutrient = solver.Sum(
            [x * content for x, content in zip(X, row)])
        requirement = nutrient2requirement[nutrient]
        solver.Add(total_nutrient >= requirement)

    # setting the objective
    price = solver.Dot(X, item2price)
    solver.SetObjective(price, maximize=False)

    # solving and recovering the solution
    solver.Solve(time_limit=10)  # time limit in seconds
    quantities = [solver.solution_value(x) for x in X]
    return quantities
예제 #2
0
def plan(demand,
         policy,
         structure=None,
         t_start=None,
         t_end=None,
         burn_in=None,
         custom_divs=None,
         custom_flows=None,
         legacy=None,
         solver=None):
    if custom_divs is None:
        custom_divs = {}
    if custom_flows is None:
        custom_flows = {}
    if solver is None:
        solver = get_solver("CBC")
        solve_all = True
    elif type(solver) == type(""):
        solver = get_solver(solver)
        solve_all = True
    else:
        solve_all = False
    if structure is None:
        structure = get_structure()
    G = DHNGraph(structure, policy)
    G.T = len(demand)
    G.set_divs(solver, policy["divs"], demand)
    G.set_flows(solver, policy["flows"])
    G.set_speeds(solver)
    G.merge(legacy)
    if burn_in is None:
        if not legacy:
            burn_in = 1
        else:
            burn_in = sum([G_l.T for G_l in legacy])
    G.divergence_constraints(solver, burn_in)
    G.forward_temp_constraint(solver, policy["consumers"], burn_in)
    cost = G.get_objective(solver, policy["plants"], policy["buyers"],
                           policy["sellers"])
    if solve_all:
        solver.SetObjective(cost, maximize=False)
        solver.Solve(time_limit=20)
        print("score: {0:.3f}".format(solver.solution_value(cost)))
        return G.extract_interval(solver, t_start, t_end)
    else:
        return G, cost
예제 #3
0
def test_inverse_cumulative():
    solver = get_solver("CBC")
    densities = [10, 1, 1, 1, 1]
    mass_threshold = 10
    max_mass = 30

    thresholds = inverse_cumulative(solver, densities, mass_threshold,
                                    max_mass)

    solver.Solve(time_limit=10)

    values_solve = [solver.solution_value(thres) for thres in thresholds]
    print(values_solve)
예제 #4
0
def main_mc():
    num_mc = 10  # number of sample scenarios to optimize upon

    np.random.seed(0)
    demand = get_demand_forecast(num_days=10)
    policy = get_policy()

    G_legacy = plan(demand, policy, t_start=48, t_end=66)
    #print("G.T:", get_T(G_legacy))
    idx_legacy = get_T(G_legacy)
    #_, axes_legacy = plt.subplots(nrows=3, sharex=True)
    #present(axes_legacy, G_legacy)

    t0 = time.time()
    solver = get_solver("CBC")
    costs = []
    Gs = []
    planned_hrs = 1
    for _ in range(num_mc):
        demand = get_demand_forecast(num_days=2).iloc[18:]
        dem0, dem_rest = demand.iloc[:planned_hrs], demand.iloc[planned_hrs:]
        G0, _ = plan(solver=solver,
                     demand=dem0,
                     legacy=[G_legacy],
                     burn_in=get_T(G_legacy),
                     policy=policy)
        G, cost = plan(solver=solver,
                       demand=dem_rest,
                       legacy=[G0],
                       burn_in=get_T(G_legacy),
                       policy=policy)
        Gs.append(G)
        costs.append(cost)
    total_cost = solver.Sum(costs)
    solver.SetObjective(total_cost, maximize=False)
    t1 = time.time()
    print("Build time: {0:.3f}".format(t1 - t0))

    solver.Solve(time_limit=200)

    Gs_solved = [G.extract_interval(solver, 0, G.T - 12) for G in Gs]
    costs_solved = [solver.solution_value(cost) for cost in costs]
    present_mc(Gs_solved, costs_solved, idx_legacy, idx_legacy + 1)

    #_, ax_hist = plt.subplots()
    #ax_hist.hist(, bins=50)
    '''
    _, axes = plt.subplots(nrows=3, sharex=True)
    present(axes, Gs_solved[0])
    '''
    plt.show()
예제 #5
0
def test_element_from_one_hot():
    max_value = 10

    solver = get_solver("CBC")
    values = [1, 2, 3, 4, 7]
    indicators = [0, 0, 0, 0, 1]

    H = element_from_one_hot(solver, values, indicators, max_value)

    solver.Solve(time_limit=10)

    H_solve = solver.solution_value(H)

    print(H_solve)
예제 #6
0
def main():
    solver = get_solver("mono")

    x = solver.NumVar(lb=0)
    y = solver.NumVar(lb=0)

    solver.Add(2 * x + y >= 1)
    solver.Add(x + 2 * y >= 1)
    z = x + y

    solver.SetObjective(z, maximize=False)

    solver.Solve(time_limit=10)

    print("x: {0:.3f}".format(solver.solution_value(x)))
    print("y: {0:.3f}".format(solver.solution_value(y)))
    print("z: {0:.3f}".format(solver.solution_value(z)))
예제 #7
0
def stigler_lp():
    """
    Using continuous x
    """

    solver = get_solver("CBC")

    # note that the natural constraint x >= 0 can be set at variable creation
    num_items = 2
    X = [solver.NumVar(lb=0, ub=None) for _ in range(num_items)]

    # setting the constraints
    for nutrient, row in enumerate(nutrient_item2content):
        total_nutrient = solver.Sum(
            [x * content for x, content in zip(X, row)])
        # there is also a shorthand:
        # total_nutrient = solver.Dot(X, row)

        # this is how constraints are added.
        # can be made very much like natural language!
        requirement = nutrient2requirement[nutrient]
        solver.Add(total_nutrient >= requirement)

    # setting the objective
    # note that 'maximize' is a required parameter.
    # I recommend to always explicitly use the keyword,
    # in order to avoid sign errors.
    price = solver.Dot(X, item2price)
    solver.SetObjective(price, maximize=False)

    # solving and recovering the solution
    solver.Solve(time_limit=10)  # time limit in seconds
    # The time limit is useful for larger models, where
    # it is hard to know beforehand whether it will take
    # 30 seconds or 30 minutes to find an optimum.
    #
    # If the time limit is reached before a proven optimal
    # solution has been found, the best known solution is returned.
    # This often actually turns out to be the optimal solution,
    # and the solver has been struggling with proving optimality.

    quantities = [solver.solution_value(x) for x in X]
    return quantities
예제 #8
0
def test_inverse_cumulative_element():
    values = [1, 2, 3, 4, 7]
    max_value = 10

    densities = [10, 1, 1, 1, 1]
    mass_threshold = 10
    max_mass = 30

    solver = get_solver("CBC")

    H, thresholds = inverse_cumulative_element(solver, values, densities,
                                               mass_threshold, max_mass,
                                               max_value)

    solver.Solve(time_limit=10)

    H_solve = solver.solution_value(H)
    print(H_solve)

    thres_solved = [solver.solution_value(thres) for thres in thresholds]
    print(thres_solved)