def do_pyomo_work(profit_rate_windows):

    Products = ['Doors', 'Windows']
    ProfitRate = {'Doors': 300, 'Windows': profit_rate_windows}
    Plants = ['Door Fab', 'Window Fab', 'Assembly']
    HoursAvailable = {'Door Fab': 4, 'Window Fab': 12, 'Assembly': 18}
    HoursPerUnit = {
        ('Doors', 'Door Fab'): 1,
        ('Windows', 'Window Fab'): 2,
        ('Doors', 'Assembly'): 3,
        ('Windows', 'Assembly'): 2,
        ('Windows', 'Door Fab'): 0,
        ('Doors', 'Window Fab'): 0
    }

    #Concrete Model
    model = ConcreteModel()
    #Decision Variables
    model.WeeklyProd = Var(Products, within=NonNegativeReals)

    #Objective
    model.obj = Objective(expr=sum(ProfitRate[i] * model.WeeklyProd[i]
                                   for i in Products),
                          sense=maximize)

    def CapacityRule(model, p):
        """User Defined Capacity Rule
        
        Accepts a pyomo Concrete Model as the first positional argument,
        and a list of Plants as a second positional argument
        """

        return sum(HoursPerUnit[i, p] * model.WeeklyProd[i]
                   for i in Products) <= HoursAvailable[p]

    model.Capacity = Constraint(Plants, rule=CapacityRule)
    opt = SolverFactory("glpk")
    instance = model.create()
    results = opt.solve(instance)
    #results.write()
    return results.Solution()
Esempio n. 2
0
                         Constraint)

# Plant data
Products = ['Doors', 'Windows']
ProfitRate = {'Doors':300, 'Windows':500}
Plants = ['Door Fab', 'Window Fab', 'Assembly']
HoursAvailable = {'Door Fab':4, 'Window Fab':12, 'Assembly':18}
HoursPerUnit = {('Doors', 'Door Fab'):1,
                ('Windows', 'Window Fab'):2,
                ('Doors', 'Assembly'):3,
                ('Windows', 'Assembly'):2,
                ('Windows', 'Door Fab'):0,
                ('Doors', 'Window Fab'):0}
                
# Concrete Model
model = ConcreteModel() # instantiates the data of the problem, such as hours available from the plant
# Decision variables
model.WeeklyProd = Var(Products, within=NonNegativeReals)

# Objective
model.obj = Objective(expr = sum(ProfitRate[i] * model.WeeklyProd[i] for i in Products), 
                      sense=maximize)
                      
def CapacityRule(model, p):
    """User defined capacity rule - 
    Accepts a pyomo Concrete Model as the first positional argument,
    and a plant index as a second positional argument
    """
    return sum(HoursPerUnit[i,p] * model.WeeklyProd[i] for i in Products) <= HoursAvailable[p]
    
# Constraint
Esempio n. 3
0
    def __init__(self,
                 cov,
                 occ,
                 groups_4digit,
                 allele_table,
                 beta,
                 t_max_allele=2,
                 solver="glpk",
                 threads=1,
                 verbosity=0):
        """
        Constructor
        """

        self.__allele_table = allele_table
        self.__beta = float(beta)
        self.__t_max_allele = t_max_allele
        self.__solver = SolverFactory(solver)
        self.__threads = threads
        self.__verbosity = True if verbosity > 0 else False
        self.__changed = True
        self.__ks = 1
        self.__groups_4digit = groups_4digit

        loci_alleles = defaultdict(list)
        for type_4digit, group_alleles in groups_4digit.iteritems():
            #print type_4digit, group_alleles
            loci_alleles[type_4digit.split('*')[0]].extend(group_alleles)

        loci = loci_alleles

        self.__allele_to_4digit = {
            allele: type_4digit
            for type_4digit, group in groups_4digit.iteritems()
            for allele in group
        }
        '''
            generates the basic ILP model
        '''

        model = ConcreteModel()

        #init Sets
        model.LociNames = Set(initialize=loci.keys())
        model.Loci = Set(model.LociNames, initialize=lambda m, l: loci[l])

        L = list(itertools.chain(*loci.values()))
        reconst = {allele_id: 0.01 for allele_id in L if '_' in allele_id}
        R = set([r for (r, _) in cov.keys()])
        model.L = Set(initialize=L)
        model.R = Set(initialize=R)

        #init Params
        model.cov = Param(model.R,
                          model.L,
                          initialize=lambda model, r, a: cov.get((r, a), 0))
        model.reconst = Param(model.L,
                              initialize=lambda model, a: reconst.get(a, 0))

        model.occ = Param(model.R, initialize=occ)
        model.t_allele = Param(initialize=self.__t_max_allele, mutable=True)

        model.beta = Param(
            initialize=self.__beta,
            validate=lambda val, model: 0.0 <= float(self.__beta) <= 0.999,
            mutable=True)
        model.nof_loci = Param(initialize=len(loci))

        #init variables
        model.x = Var(model.L, domain=Binary)
        model.y = Var(model.R, domain=Binary)

        model.re = Var(model.R, bounds=(0.0, None))
        model.hetero = Var(bounds=(0.0, model.nof_loci))

        #init objective
        model.read_cov = Objective(rule=lambda model: sum(
            model.occ[r] * (model.y[r] - model.beta * (model.re[r]))
            for r in model.R) - sum(model.reconst[a] * model.x[a]
                                    for a in model.L),
                                   sense=maximize)

        #init Constraints
        model.max_allel_selection = Constraint(
            model.LociNames,
            rule=lambda model, l: sum(model.x[a] for a in model.Loci[l]
                                      ) <= model.t_allele)
        model.min_allel_selection = Constraint(
            model.LociNames,
            rule=lambda model, l: sum(model.x[a] for a in model.Loci[l]) >= 1)
        model.is_read_cov = Constraint(
            model.R,
            rule=lambda model, r: sum(model.cov[r, a] * model.x[a]
                                      for a in model.L) >= model.y[r])
        model.heterozygot_count = Constraint(
            rule=lambda model: model.hetero >= sum(model.x[a] for a in model.L
                                                   ) - model.nof_loci)

        #regularization constraints
        model.reg1 = Constraint(
            model.R,
            rule=lambda model, r: model.re[r] <= model.nof_loci * model.y[r])
        model.reg2 = Constraint(
            model.R, rule=lambda model, r: model.re[r] <= model.hetero)
        model.reg3 = Constraint(model.R,
                                rule=lambda model, r: model.re[r] >= model.
                                hetero - model.nof_loci * (1 - model.y[r]))

        #generate constraint list for solution enumeration
        model.c = ConstraintList()
        #generate instance
        self.__instance = model.create()
Esempio n. 4
0
    def __init__(self, cov, occ, groups_4digit, allele_table, beta, t_max_allele=2, solver="glpk", threads=1,
                 verbosity=0):
        """
        Constructor
        """

        self.__allele_table = allele_table
        self.__beta = float(beta)
        self.__t_max_allele = t_max_allele
        self.__solver = SolverFactory(solver)
        self.__solver.options["threads"] = threads
        self.__verbosity = True if verbosity > 0 else False
        self.__changed = True
        self.__ks = 1
        self.__groups_4digit = groups_4digit

        loci_alleles = defaultdict(list)
        for type_4digit, group_alleles in groups_4digit.iteritems():
            #print type_4digit, group_alleles
            loci_alleles[type_4digit.split('*')[0]].extend(group_alleles)

        loci = loci_alleles

        self.__allele_to_4digit = {allele: type_4digit for type_4digit, group in groups_4digit.iteritems() for allele in
                                   group}

        '''
            generates the basic ILP model
        '''

        model = ConcreteModel()

        #init Sets
        model.LociNames = Set(initialize=loci.keys())
        model.Loci = Set(model.LociNames, initialize=lambda m, l: loci[l])

        L = list(itertools.chain(*loci.values()))
        reconst = {allele_id: 0.01 for allele_id in L if '_' in allele_id}
        R = set([r for (r, _) in cov.keys()])
        model.L = Set(initialize=L)
        model.R = Set(initialize=R)

        #init Params
        model.cov = Param(model.R, model.L, initialize=lambda model, r, a: cov.get((r, a), 0))
        model.reconst = Param(model.L, initialize=lambda model, a: reconst.get(a, 0))

        model.occ = Param(model.R, initialize=occ)
        model.t_allele = Param(initialize=self.__t_max_allele, mutable=True)

        model.beta = Param(initialize=self.__beta,
                           validate=lambda val, model: 0.0 <= float(self.__beta) <= 0.999,
                           mutable=True)
        model.nof_loci = Param(initialize=len(loci))

        #init variables
        model.x = Var(model.L, domain=Binary)
        model.y = Var(model.R, domain=Binary)

        model.re = Var(model.R, bounds=(0.0, None))
        model.hetero = Var(bounds=(0.0, model.nof_loci))

        #init objective
        model.read_cov = Objective(
            rule=lambda model: sum(model.occ[r] * (model.y[r] - model.beta * (model.re[r])) for r in model.R) - sum(
                model.reconst[a] * model.x[a] for a in model.L), sense=maximize)

        #init Constraints
        model.max_allel_selection = Constraint(model.LociNames, rule=lambda model, l: sum(
            model.x[a] for a in model.Loci[l]) <= model.t_allele)
        model.min_allel_selection = Constraint(model.LociNames,
                                               rule=lambda model, l: sum(model.x[a] for a in model.Loci[l]) >= 1)
        model.is_read_cov = Constraint(model.R,
                                       rule=lambda model, r: sum(model.cov[r, a] * model.x[a] for a in model.L) >=
                                                             model.y[r])
        model.heterozygot_count = Constraint(
            rule=lambda model: model.hetero >= sum(model.x[a] for a in model.L) - model.nof_loci)

        #regularization constraints
        model.reg1 = Constraint(model.R, rule=lambda model, r: model.re[r] <= model.nof_loci * model.y[r])
        model.reg2 = Constraint(model.R, rule=lambda model, r: model.re[r] <= model.hetero)
        model.reg3 = Constraint(model.R,
                                rule=lambda model, r: model.re[r] >= model.hetero - model.nof_loci * (1 - model.y[r]))

        #generate constraint list for solution enumeration
        model.c = ConstraintList()
        #generate instance
        self.__instance = model.create()
def maxRetPortfolio(riskyRetMtx, riskFreeRetVec, 
                    buyTransFeeMtx, sellTransFeeMtx,
                    allocatedWealth):
    '''
    -假設有T期的資料, 投資在M個risky assets, 以及1個riskfree asset
    -在(T+1)期初結算
    goal: 最大化T+1期期初財產
    
    @param riskyRetMtx, numpy.array, size: M * T+1
    @param riskFreeRetVec, numpy.array, size: T+1
    @param buyTransFeeMtx, numpy.array, size: M * T
    @param sellTransFeeMtx, numpy.array, size: M * T
    @param allocatedWealth, numpy.array, size: (M+1) (最後一個為cash)
    
    @return (buyMtx, sellMtx), numpy.array, each size: M*T
    '''
    assert buyTransFeeMtx.shape == sellTransFeeMtx.shape
    assert riskyRetMtx.shape[1] == riskFreeRetVec.size
   
    M, T =  buyTransFeeMtx.shape

    t1 = time.time()
    #create model
    model = ConcreteModel()
    
    #number of asset and number of periods
    model.symbols = range(M)
    model.T = range(T)
    model.Tp1 = range(T+1)
    model.Mp1 = range(M+1)
    
    #decision variables
    model.buys = Var(model.symbols, model.T, within=NonNegativeReals)
    model.sells = Var(model.symbols, model.T, within=NonNegativeReals)
    model.riskyWealth = Var(model.symbols, model.T, within=NonNegativeReals)
    model.riskFreeWealth = Var(model.T, within=NonNegativeReals)
    
    #objective
    def objective_rule(model):
        wealth =sum( (1. + riskyRetMtx[m, T]) * model.riskyWealth[m, T-1] 
                     for m in xrange(M))
        wealth += (1.+ riskFreeRetVec[T]) * model.riskFreeWealth[T-1] 
        return wealth
        
    model.objective = Objective(rule=objective_rule, sense=maximize)
    
    #constraint
    def riskyWealth_constraint_rule(model, m, t):
        if t>=1:
            preWealth = model.riskyWealth[m, t-1]
        else:
            preWealth = allocatedWealth[m]
       
        return (model.riskyWealth[m, t] == 
                (1. + riskyRetMtx[m,t])*preWealth + 
                model.buys[m,t] - model.sells[m,t])
    
    def riskyFreeWealth_constraint_rule(model, t):
        totalSell = sum((1-sellTransFeeMtx[mdx, t])*model.sells[mdx, t] 
                        for mdx in xrange(M))
        totalBuy = sum((1+buyTransFeeMtx[mdx, t])*model.buys[mdx, t] 
                       for mdx in xrange(M))
        
        if t >=1:
            preWealth = model.riskFreeWealth[t-1]  
        else:
            preWealth = allocatedWealth[-1]
    
        return( model.riskFreeWealth[t] == 
                (1. + riskFreeRetVec[t])*preWealth + 
                totalSell - totalBuy)
        
    
    model.riskyWeathConstraint = Constraint(model.symbols, model.T, 
                                            rule=riskyWealth_constraint_rule)
    model.riskFreeWealthConstraint = Constraint(model.T, 
                                          rule=riskyFreeWealth_constraint_rule)
    
    #optimizer
    opt = SolverFactory('cplex')
#     opt.options["threads"] = 4
    
    instance = model.create()
    results = opt.solve(instance)
    print results
#     instance.load(results)
#     display(instance)
#     instance.load(results)
#     for var in instance.active_components(Var):
#         varobj = getattr(instance, var)
#         for idx in varobj:
#             print varobj[idx], varobj[idx].value
#    
    print "elapsed %.3f secs"%(time.time()-t1)
Esempio n. 6
0
def big_m_model():

    with open('Pickled_Data', 'rb') as f:
        rd = pickle.load(f)

    model = ConcreteModel()
    #-----------------------------------------------------------------------------
    #                           DECLARE MODEL PARAMETERS
    #-----------------------------------------------------------------------------

    model.STORES = Set(initialize=rd.STORES)
    model.PRODUCTS = Set(initialize=rd.PRODUCTS)
    model.FASHION = Set(initialize=rd.FASHION)
    model.VENDORS_Q = Set(initialize=rd.VENDORS_Q)
    model.VENDORS_P = Set(initialize=rd.VENDORS_P)
    model.VENDORS = Set(initialize=rd.VENDORS)
    model.TIMES = Set(initialize=rd.TIMES)
    model.PICKING = Set(initialize=rd.PICKING)
    model.PUTAWAY = Set(initialize=rd.PUTAWAY)

    model.SP = model.STORES * model.PRODUCTS
    model.VP = model.VENDORS * model.PRODUCTS
    model.ST = model.STORES * model.TIMES
    model.PT = model.PRODUCTS * model.TIMES
    model.VT = model.VENDORS * model.TIMES
    model.VPT = model.VENDORS * model.PRODUCTS * model.TIMES
    model.SPT = model.STORES * model.PRODUCTS * model.TIMES


    model.OMEGA_Q = Set(initialize=rd.Omega_q, dimen=2)
    model.OMEGA_P = Set(initialize=rd.Omega_p, dimen=2)

    model.T_minus_One = Param(model.TIMES, initialize=rd.T_minus_One)

    def K_init(model, s): return 10000000
    model.K_s = Param(model.STORES, initialize=K_init)

    def L_init(model): return 0
    model.L = Param(initialize=L_init)

    model.Script_Q = Param(initialize=15000)

    model.phi_put = Param(initialize=1.0)
    model.phi_pick = Param(initialize=1.0)
    model.gamma = Param(initialize=0.5)

    model.pt = Param(initialize=1)
    model.tb = Param(initialize=rd.tb)
    model.te = Param(initialize=rd.te)
    model.ty = Param(initialize=rd.ty)

    model.Demand = Param(model.STORES, model.PRODUCTS, model.TIMES, initialize=rd.Demand)

    model.V_p = Param(model.PRODUCTS, initialize=rd.V_p)
    model.V_q = Param(model.FASHION, initialize=rd.V_q)
    model.W_p = Param(model.PRODUCTS, initialize=rd.W_p)
    model.W_q = Param(model.FASHION, initialize=rd.W_q)

    X_ivq = {tup:rd.X_ivq[tup] for tup in model.OMEGA_Q}
    model.X_ivq = Param(model.OMEGA_Q, initialize=X_ivq)
    model.X_osq = Param(model.STORES, model.FASHION, initialize=rd.X_osq)
    model.C_alpha = Param(initialize=rd.C_alpha)
    model.C_beta = Param(initialize=rd.C_beta)

    def C_hp_init(model, p): return .01

    model.C_hp = Param(model.PRODUCTS, initialize=C_hp_init)
    model.C_hq = Param(model.FASHION, initialize=C_hp_init)


    def C_hsp_init(model, s, p): return .05

    model.C_hsp = Param(model.STORES, model.PRODUCTS, initialize=C_hsp_init)
    model.C_hsq = Param(model.STORES, model.FASHION, initialize=C_hsp_init)


    model.C_fv = Param(model.VENDORS, initialize=rd.C_fv)
    model.C_fs = Param(model.STORES, initialize=rd.C_fs)
    model.C_vv = Param(model.VENDORS, initialize=rd.C_vv)
    model.C_vs = Param(model.STORES, initialize=rd.C_vs)


    model.Lambda_put = Param(model.PUTAWAY, initialize=rd.lambda_put)
    model.MHE = Param(model.PUTAWAY, initialize=rd.MHE)
    model.Lambda_pick = Param(model.PICKING, initialize=rd.lambda_pick)
    model.Cth_put = Param(model.PUTAWAY, initialize=rd.C_put)
    model.Cth_pick = Param(model.PICKING, initialize=rd.C_pick)

    #-----------------------------------------------------------------------------
    #                           DECLARE MODEL VARIABLES
    #-----------------------------------------------------------------------------

    model.alpha_put = Var(bounds=(0.0, 500),
                           within=NonNegativeIntegers)

    model.alpha_pick = Var(bounds=(0.0, 500),
                           within=NonNegativeIntegers)

    model.theta_put = Var(model.PUTAWAY, within=Binary)
    model.theta_pick = Var(model.PICKING, within=Binary)

    model.MHE_cost = Var(model.PUTAWAY, within=NonNegativeIntegers)


    model.beta_put = Var(model.TIMES,
                         within=NonNegativeIntegers)

    model.beta_pick = Var(model.TIMES,
                         within=NonNegativeIntegers)

    model.tau_sq = Var(model.STORES, model.FASHION,
                         within=NonNegativeIntegers)

    model.rho_vqt = Var(model.OMEGA_Q, model.TIMES,
                         within=Binary)

    model.rho_sqt = Var(model.STORES, model.FASHION, model.TIMES,
                         within=Binary)

    model.x_vpt = Var(model.OMEGA_P, model.TIMES,
                         within=NonNegativeIntegers)

    model.x_spt = Var(model.STORES, model.PRODUCTS, model.TIMES,
                         within=NonNegativeIntegers)

    model.y_pt = Var(model.PRODUCTS, model.TIMES,
                         within=NonNegativeIntegers)

    model.y_spt = Var(model.STORES, model.PRODUCTS, model.TIMES,
                         within=NonNegativeIntegers)

    model.y_sqt = Var(model.STORES, model.FASHION, model.TIMES,
                         within=NonNegativeIntegers)

    model.z_spt = Var(model.STORES, model.PRODUCTS, model.TIMES,
                         within=NonNegativeIntegers)

    model.z_sqt = Var(model.STORES, model.FASHION, model.TIMES,
                         within=NonNegativeIntegers)

    model.n_vt =  Var(model.VENDORS, model.TIMES,
                         within=NonNegativeIntegers)

    model.n_st =  Var(model.STORES, model.TIMES,
                         within=NonNegativeIntegers)



    def objective_rule(model):
        Workers_Cost = model.Ca * (model.alpha_put + model.alpha_pick) + \
                       model.Cb * sum((model.beta_put[t] + model.beta_pick[t])
                                       for t in model.TIMES)

        MHE_Cost = summation(model.MHE_cost)

        Tech_Cost = summation(model.Cth_put, model.theta_put) + \
                    summation(model.Cth_pick, model.theta_pick)


        Holding_Cost =  sum(model.C_hp[p] * model.y_pt[p,t]
                            for p in model.PRODUCTS for t in model.TIMES)
        Holding_Cost += sum(model.C_hq[q] * model.X_osq[s,q] * model.tau_sq[s,q]
                            for s in model.STORES for q in model.FASHION)
        Holding_Cost += sum(model.C_hsp[s,p] * model.y_spt[s,p,t]
                            for s in model.STORES for p in model.PRODUCTS for t in model.TIMES)
        Holding_Cost += sum(model.C_hsq[s,q] * model.y_sqt[s,q,t]
                            for s in model.STORES for q in model.FASHION for t in model.TIMES)


        Fixed_Shipping_Cost =  sum(model.C_fv[v] * model.n_vt[v,t]
                                  for v in model.VENDORS for t in model.TIMES)
        Fixed_Shipping_Cost += sum(model.C_fs[s] * model.n_st[s,t]
                                  for s in model.STORES for t in model.TIMES)


        Var_Shipping_Cost =  sum(model.C_vv[v] * model.W_p[p] * model.x_vpt[v,p,t]
                                  for v, p in model.OMEGA_P for t in model.TIMES)
        Var_Shipping_Cost += sum(model.C_vv[v] * model.W_q[q] * model.X_ivq[v,q] * model.rho_vqt[v,q,t]
                                  for v, q in model.OMEGA_Q for t in model.TIMES)
        Var_Shipping_Cost += sum(model.C_vs[s] * model.W_p[p] * model.x_spt[s,p,t]
                                  for s in model.STORES for p in model.PRODUCTS for t in model.TIMES)
        Var_Shipping_Cost += sum(model.C_vs[s] * model.W_q[q] * model.X_osq[s,q] * model.rho_sqt[s,q,t]
                                  for s in model.STORES for q in model.FASHION for t in model.TIMES)


        FS_Expr = (Workers_Cost + MHE_Cost + Tech_Cost + Holding_Cost
                                + Fixed_Shipping_Cost + Var_Shipping_Cost)

        return FS_Expr

    model.objective = Objective(sense=minimize)


    def BigM_MHE_LOWER_rule(model, i):
        expr = model.MHE_COST[i]
        expr -= sum(model.MHE[i] * (model.alpha_put + model.beta_put[t])
                    for t in model.TIMES)
        return (-model.M_MHE * (1 - model.theta_put[i]), expr, None)

    model.BigM_MHE_LOWER = Constraint(model.PUTAWAY, model.TIMES)

    def BigM_MHE_UPPER_rule(model, i):
        expr = model.MHE_COST[i]
        expr -= sum(model.MHE[i] * (model.alpha_put + model.beta_put[t])
                    for t in model.TIMES)
        return (None, expr, model.M_MHE * (1 - model.theta_put[i]))

    model.BigM_MHE_UPPER = Constraint(model.PUTAWAY, model.TIMES)

    def ConstraintFour_rule(model, i, t):
        Four_expr1 = sum(model.x_vpt[v,p,t] for v, p in model.OMEGA_P)
        Four_expr1 += sum(model.X_ivq[v,q] * model.rho_vqt[v,q,t] for v, q in model.OMEGA_Q)
        Four_expr2 = model.Lambda_put[i] * (model.alpha_put + model.phi_put * model.beta_put[t])
        return (Four_expr1 - Four_expr2 <= model.BigM * (1 - model.theta_put[i]))

    model.ConstraintFour = Constraint(model.PUTAWAY, model.TIMES)


    def ConstraintFive_rule(model, j, t):
        Five_expr1 = sum(model.x_spt[s,p,t] for s in model.STORES for p in model.PRODUCTS)
        Five_expr1 += sum(model.X_osq[s,q] * model.rho_sqt[s,q,t] for s in model.STORES for q in model.FASHION)
        Five_expr2 = model.Lambda_pick[j]  * (model.alpha_pick + model.phi_pick * model.beta_pick[t])
        return (Five_expr1 - Five_expr2 <= model.BigM * (1 - model.theta_pick[j]))

    model.ConstraintFive = Constraint(model.PICKING, model.TIMES)



    # Constraint Six
    def ConstraintSixPutaway_rule(model, t):
        Six_expr1 = model.beta_put[t]
        Six_expr2 = model.gamma * model.alpha_put
        return (Six_expr1 - Six_expr2 <= 0)

    model.ConstraintSixPutaway = Constraint(model.TIMES)



    def ConstraintSixPicking_rule(model, t):
        Six_expr1 = model.beta_pick[t]
        Six_expr2 = model.gamma * model.alpha_pick
        return (Six_expr1 - Six_expr2 <= 0)

    model.ConstraintSixPicking = Constraint(model.TIMES)



    # Constraint Seven
    def ConstraintSeven_rule(model, v, q, s):
        Seven_expr1 = model.tau_sq[s,q]
        Seven_expr2 =  sum(t * model.rho_sqt[s, q, t] for t in model.TIMES)
        Seven_expr2 -= sum(t * model.rho_vqt[v, q, t] for t in model.TIMES)
        return (Seven_expr1 - Seven_expr2 == 0)

    model.ConstraintSeven = Constraint(model.OMEGA_Q, model.STORES)



    # Constraint Eight
    def ConstraintEight_rule(model, s, q):
        Eight_expr1 = model.tau_sq[s,q]
        return (model.pt - Eight_expr1 <= 0)

    model.ConstraintEight = Constraint(model.STORES, model.FASHION)



    # Constraint Nine
    def ConstraintNine_rule(model, s, q):
        Nine_expr1 = sum(t * model.rho_sqt[s, q, t] for t in model.TIMES)
        Nine_expr2 = model.ty - model.L
        return (Nine_expr1 - Nine_expr2 <= 0)

    model.ConstraintNine = Constraint(model.STORES, model.FASHION)



    # Constraint Ten
    def ConstraintTenVendor_rule(model, v, q):
        Ten_expr1 = sum(model.rho_vqt[v, q, t] for t in model.TIMES if model.tb <= t <= model.te)
        return (Ten_expr1 - 1 == 0)

    model.ConstraintTenVendor = Constraint(model.OMEGA_Q)



    def ConstraintTenStore_rule(model, s, q):
        Ten_expr1 = sum(model.rho_sqt[s, q, t] for t in model.TIMES if model.tb <= t <= model.ty)
        return (Ten_expr1 - 1 == 0)

    model.ConstraintTenStore = Constraint(model.STORES, model.FASHION)

    # Constraint Ten Prime
    def ConstraintTenPrimeVendor_rule(model, v, q, t):
        if not model.tb <= t <= model.ty:
            return model.rho_vqt[v, q, t] == 0
        else:
            return Constraint.Skip

    model.ConstraintTenPrimeVendor = Constraint(model.OMEGA_Q, model.TIMES)

    def ConstraintTenPrimeStore_rule(model, s, q, t):
        if not model.tb <= t <= model.ty:
            return model.rho_sqt[s, q, t] == 0
        else:
            return Constraint.Skip

    model.ConstraintTenPrimeStore = Constraint(model.STORES, model.FASHION, model.TIMES)

    # Constraint Eleven and Twelve
    def ConstraintEleven_rule(model, s, p, t):
        assert model.L == 0

        Eleven_expr1 = model.z_spt[s,p,t]
        Eleven_expr2 = model.x_spt[s,p,t]
        return (Eleven_expr1 - Eleven_expr2 == 0)

    model.ConstraintEleven = Constraint(model.STORES, model.PRODUCTS, model.TIMES)


    # Constraint Thirteen
    def ConstraintThirteen_rule(model, s, q, t):
        assert model.L== 0
        if model.tb <= t <= model.ty:
            Thirteen_expr1 = model.z_sqt[s,q,t]
            Thirteen_expr2 = model.X_osq[s,q] * model.rho_sqt[s,q,t]
            return (Thirteen_expr1 - Thirteen_expr2 == 0)
        else:
            return Constraint.Skip

    model.ConstraintThirteen = Constraint(model.STORES, model.FASHION, model.TIMES)

    # Constraint Fourteen and Fifteen
    def ConstraintFourteen_rule(model, p, t):
        Fourteen_expr1 = sum(model.x_vpt[v, p, t] for v, pee in model.OMEGA_P if pee == p)
        Fourteen_expr1 -= sum(model.x_spt[s, p, t] for s in model.STORES)
        Fourteen_expr2 = model.y_pt[p,t] - model.y_pt[p,model.T_minus_One[t]]
        return (Fourteen_expr1 - Fourteen_expr2 == 0)

    model.ConstraintFourteen = Constraint(model.PRODUCTS, model.TIMES)



    # Constraint Sixteen and Seventeen
    def ConstraintSixteen_rule(model,s,p,t):
        Sixteen_expr1 = model.z_spt[s, p, t]
        Sixteen_expr1 -= model.Demand[s,p,t]
        Sixteen_expr2 = model.y_spt[s,p,t] - model.y_spt[s,p,model.T_minus_One[t]]
        return (Sixteen_expr1 - Sixteen_expr2 == 0)

    model.ConstraintSixteen = Constraint(model.STORES, model.PRODUCTS, model.TIMES)



    # Constraint Eighteen
    def ConstraintEighteen_rule(model,s,q,t):
        if model.tb <= t <= model.ty:
            if t == 1:
                Eighteen_expr1 = model.z_sqt[s, q, t]
                Eighteen_expr2 = model.y_sqt[s,q,t]
                return (Eighteen_expr1 - Eighteen_expr2 == 0)
            else:
                Eighteen_expr1 = model.z_sqt[s, q, t]
                Eighteen_expr2 = model.y_sqt[s,q,t] - model.y_sqt[s,q,model.T_minus_One[t]]
                return (Eighteen_expr1 - Eighteen_expr2 == 0)
        else:
            return Constraint.Skip

    model.ConstraintEighteen = Constraint(model.STORES, model.FASHION, model.TIMES)



    # Constraints Nineteen
    def ConstraintNineteen_rule(model, s, t):
        Nineteen_expr1 =  sum(model.V_p[p] * model.z_spt[s, p, t] for p in model.PRODUCTS)
        Nineteen_expr1 += sum(model.V_q[q] * model.z_sqt[s, q, t] for q in model.FASHION)
        Nineteen_expr2 = model.K_s[s]
        return (Nineteen_expr1 - Nineteen_expr2 <= 0)

    model.ConstraintNineteen = Constraint(model.STORES, model.TIMES)



    # Constraints Twenty
    def ConstraintTwenty_rule(model, v, t):
        if v in model.VENDORS_P:
            Twenty_expr1 =  sum(model.W_p[p] * model.x_vpt[v,p,t] for ve, p in model.OMEGA_P
                                                           if ve == v)
        else:
            Twenty_expr1 = 0

        if v in model.VENDORS_Q:
            Twenty_expr1 += sum(model.W_q[q] * model.X_ivq[v,q] * model.rho_vqt[v,q,t]
                            for ve, q in model.OMEGA_Q if ve == v)

        Twenty_expr2 = model.Script_Q * model.n_vt[v,t]
        return (Twenty_expr1 - Twenty_expr2 <= 0)

    model.ConstraintTwenty = Constraint(model.VENDORS, model.TIMES)


    # Constraints TwentyOne
    def ConstraintTwentyOne_rule(model, s, t):
        TwentyOne_expr1 =  sum(model.W_p[p] * model.x_spt[s,p,t] for p in model.PRODUCTS)
        TwentyOne_expr1 += sum(model.W_q[q] * model.X_osq[s,q] * model.rho_sqt[s,q,t] for q in model.FASHION)
        TwentyOne_expr2 = model.Script_Q * model.n_st[s,t]
        return (TwentyOne_expr1 - TwentyOne_expr2 <= 0)

    model.ConstraintTwentyOne = Constraint(model.STORES, model.TIMES)

    return model
Esempio n. 7
0
#Explicit importing makes it more clear what a user needs to define
#versus what is included within the pyomo library
from coopr.pyomo import (ConcreteModel, Objective, Var, NonNegativeIntegers, maximize, Constraint)

Products = ['Doors', 'Windows', 'Tables']
ProfitRate = {'Doors':0.300, 'Windows':0.500, 'Tables':0.430}
Plants = ['Door Fab', 'Window Fab', 'Assembly']
HoursAvailable = {'Door Fab':4, 'Window Fab':4, 'Assembly':3}
HoursPerUnit = {('Doors','Door Fab'):0.21, ('Windows', 'Window Fab'):0.52,
                ('Doors','Assembly'):0.23, ('Windows', 'Assembly'):0.32,
                ('Windows', 'Door Fab'):0.30,('Doors', 'Window Fab'):0.20,
                ('Tables','Door Fab'):0.29, ('Tables','Window Fab'):0.34,
                ('Tables', 'Assembly'):0.41}

#Concrete Model
model = ConcreteModel()

#Decision Variables
model.WeeklyProd = Var(Products, within=NonNegativeIntegers)

#Objective
model.obj = Objective(expr=
            sum(ProfitRate[i] * model.WeeklyProd[i] for i in Products),
            sense = maximize)
for i in Products:
    print model.WeeklyProd[i]

def CapacityRule(model, p):
    """User Defined Capacity Rule
    
    Accepts a pyomo Concrete Model as the first positional argument,
Esempio n. 8
0
from coopr.pyomo import (ConcreteModel, Objective, Var, NonNegativeReals,
                              maximize, Constraint)



Activities = ['ActivityOne', 'ActivityTwo'] #Products in other models
UnitProfit = {'ActivityOne':2, 'ActivityTwo':5} #Also called ProfitRate
Resources = ['ResourceOne', 'ResourceTwo']
ResourcesAvailable = {'ResourceOne':10, 'ResourceTwo':12}
ResourcesPerUnit = {('ActivityOne', 'ResourceOne'):1,
                    ('ActivityTwo', 'ResourceOne'):2,
                    ('ActivityOne', 'ResourceTwo'):1,
                    ('ActivityTwo', 'ResourceTwo'):3}

#Concrete Model
model = ConcreteModel()
#Decision Variables
model.Prod = Var(Activities, within=NonNegativeReals)

#Objective
model.obj = Objective(expr=
            sum(UnitProfit[i] * model.Prod[i] for i in Activities),
            sense = maximize)

def ActivityRule(model, r):
    return sum(ResourcesPerUnit[i,r] * model.Prod[i] for i in Activities) <= ResourcesAvailable[r]

model.Utilization = Constraint(Resources, rule = ActivityRule)

#This is an optional code path that allows the script to be run outside of
#pyomo command-line. For example: python wyndor.py
def maxRetPortfolio(riskyRetMtx, riskFreeRetVec, buyTransFeeMtx,
                    sellTransFeeMtx, allocatedWealth):
    '''
    -假設有T期的資料, 投資在M個risky assets, 以及1個riskfree asset
    -在(T+1)期初結算
    goal: 最大化T+1期期初財產
    
    @param riskyRetMtx, numpy.array, size: M * T+1
    @param riskFreeRetVec, numpy.array, size: T+1
    @param buyTransFeeMtx, numpy.array, size: M * T
    @param sellTransFeeMtx, numpy.array, size: M * T
    @param allocatedWealth, numpy.array, size: (M+1) (最後一個為cash)
    
    @return (buyMtx, sellMtx), numpy.array, each size: M*T
    '''
    assert buyTransFeeMtx.shape == sellTransFeeMtx.shape
    assert riskyRetMtx.shape[1] == riskFreeRetVec.size

    M, T = buyTransFeeMtx.shape

    t1 = time.time()
    #create model
    model = ConcreteModel()

    #number of asset and number of periods
    model.symbols = range(M)
    model.T = range(T)
    model.Tp1 = range(T + 1)
    model.Mp1 = range(M + 1)

    #decision variables
    model.buys = Var(model.symbols, model.T, within=NonNegativeReals)
    model.sells = Var(model.symbols, model.T, within=NonNegativeReals)
    model.riskyWealth = Var(model.symbols, model.T, within=NonNegativeReals)
    model.riskFreeWealth = Var(model.T, within=NonNegativeReals)

    #objective
    def objective_rule(model):
        wealth = sum((1. + riskyRetMtx[m, T]) * model.riskyWealth[m, T - 1]
                     for m in xrange(M))
        wealth += (1. + riskFreeRetVec[T]) * model.riskFreeWealth[T - 1]
        return wealth

    model.objective = Objective(rule=objective_rule, sense=maximize)

    #constraint
    def riskyWealth_constraint_rule(model, m, t):
        if t >= 1:
            preWealth = model.riskyWealth[m, t - 1]
        else:
            preWealth = allocatedWealth[m]

        return (model.riskyWealth[m,
                                  t] == (1. + riskyRetMtx[m, t]) * preWealth +
                model.buys[m, t] - model.sells[m, t])

    def riskyFreeWealth_constraint_rule(model, t):
        totalSell = sum((1 - sellTransFeeMtx[mdx, t]) * model.sells[mdx, t]
                        for mdx in xrange(M))
        totalBuy = sum((1 + buyTransFeeMtx[mdx, t]) * model.buys[mdx, t]
                       for mdx in xrange(M))

        if t >= 1:
            preWealth = model.riskFreeWealth[t - 1]
        else:
            preWealth = allocatedWealth[-1]

        return (
            model.riskFreeWealth[t] == (1. + riskFreeRetVec[t]) * preWealth +
            totalSell - totalBuy)

    model.riskyWeathConstraint = Constraint(model.symbols,
                                            model.T,
                                            rule=riskyWealth_constraint_rule)
    model.riskFreeWealthConstraint = Constraint(
        model.T, rule=riskyFreeWealth_constraint_rule)

    #optimizer
    opt = SolverFactory('cplex')
    #     opt.options["threads"] = 4

    instance = model.create()
    results = opt.solve(instance)
    print results
    #     instance.load(results)
    #     display(instance)
    #     instance.load(results)
    #     for var in instance.active_components(Var):
    #         varobj = getattr(instance, var)
    #         for idx in varobj:
    #             print varobj[idx], varobj[idx].value
    #
    print "elapsed %.3f secs" % (time.time() - t1)
Esempio n. 10
0
Plants = ['Barley', 'Wheat', 'Rice', 'Maize']                   # Plants' area
SellingPrice = {'Barley':300, 'Wheat':200, 'Rice':250, 'Maize':380}     # selling price per km2
Resource = ['fertilizer', 'pesticide']                          # fertilizer and pesticide are constraints
Resource_available = {'fertilizer':1260, 'pesticide':780}       # amount of fertilizer and pesticide available
Resource_required = {('Barley', 'fertilizer'):4,
                     ('Wheat', 'fertilizer'):12,
                    ('Rice', 'fertilizer'):18,
                    ('Maize', 'fertilizer'):19,
                    ('Barley', 'pesticide'):5,
                    ('Wheat', 'pesticide'):4,
                    ('Rice', 'pesticide'):3,
                    ('Maize', 'pesticide'):6}

                
# Concrete Model instantiates the data of the problem
model = ConcreteModel()

# Decision variables - varying the combination of plant area
model.SeasonProd = Var(Plants, within=NonNegativeReals)

# Objective - to maximize profit
# meaning: for each product, calculate the profit rate * production, sum all these at the end
model.obj = Objective(expr = sum(SellingPrice[i] * model.SeasonProd[i] for i in Plants), 
                      sense=maximize)

# Constraint - uses a Capacity Rule and Land Area function
# meaning: for each plant, the resource used should not exceed the total resource available
def CapacityRule(model, p):
    """User defined capacity rule - 
    Accepts a pyomo ConcreteModel as the first positional argument,
    and a plant index as a second positional argument"""
def maxRetMultiStagePortfolio(riskyRetMtx, riskFreeRetVec, buyTransFeeMtx,
                              sellTransFeeMtx, allocatedWealth, symbols,
                              transDates):
    '''
    -假設資料共T期, 投資在M個risky assets, 以及1個riskfree asset
    -求出每個risky asset每一期應該要買進以及賣出的金額
    -最後一期結算不投資
    
    @param riskyRetMtx, numpy.array, size: M * T+1
    @param riskFreeRetVec, numpy.array, size: T+1
    @param buyTransFeeMtx, numpy.array, size: M * T
    @param sellTransFeeMtx, numpy.array, size: M * T
    @param allocatedWealth, numpy.array, size: (M+1) (最後一個為cash)
    
    @return (buyMtx, sellMtx), numpy.array, each size: M*T
    '''

    assert buyTransFeeMtx.shape == sellTransFeeMtx.shape
    assert riskyRetMtx.shape[1] == riskFreeRetVec.size

    M, T = buyTransFeeMtx.shape

    t1 = time.time()

    #create model
    model = ConcreteModel()

    #number of asset and number of periods
    model.symbols = range(M)
    model.T = range(T)

    #decision variables
    model.buys = Var(model.symbols, model.T, within=NonNegativeReals)
    model.sells = Var(model.symbols, model.T, within=NonNegativeReals)
    model.riskyWealth = Var(model.symbols, model.T, within=NonNegativeReals)
    model.riskFreeWealth = Var(model.T, within=NonNegativeReals)

    #objective
    def objective_rule(model):
        wealth = sum((1. + riskyRetMtx[m, T]) * model.riskyWealth[m, T - 1]
                     for m in xrange(M))
        wealth += (1. + riskFreeRetVec[T]) * model.riskFreeWealth[T - 1]
        return wealth

    model.objective = Objective(sense=maximize)

    #constraint
    def riskyWeathConstraint_rule(model, m, t):
        if t >= 1:
            preWealth = model.riskyWealth[m, t - 1]
        else:
            preWealth = allocatedWealth[m]

        return (model.riskyWealth[m,
                                  t] == (1. + riskyRetMtx[m, t]) * preWealth +
                model.buys[m, t] - model.sells[m, t])

    def riskFreeWealthConstraint_rule(model, t):
        totalSell = sum((1 - sellTransFeeMtx[mdx, t]) * model.sells[mdx, t]
                        for mdx in xrange(M))
        totalBuy = sum((1 + buyTransFeeMtx[mdx, t]) * model.buys[mdx, t]
                       for mdx in xrange(M))

        if t >= 1:
            preWealth = model.riskFreeWealth[t - 1]
        else:
            preWealth = allocatedWealth[-1]

        return (
            model.riskFreeWealth[t] == (1. + riskFreeRetVec[t]) * preWealth +
            totalSell - totalBuy)

    model.riskyWeathConstraint = Constraint(model.symbols, model.T)
    model.riskFreeWealthConstraint = Constraint(model.T)

    #optimizer
    opt = SolverFactory('cplex')

    instance = model.create()
    results = opt.solve(instance)
    print type(results)
    print results

    #load decision variable
    instance.load(results)
    display(instance)
    #     instance.load(results)
    #     for var in instance.active_components(Var):
    #         varobj = getattr(instance, var)
    #         for idx in varobj:
    #             print varobj[idx], varobj[idx].value
    #
    #     print type(results)
    #load objective value
    finalWealth = results.Solution.Objective.__default_objective__['value']

    print "finalWealth:", finalWealth
    print "ret: %.3f %%" % ((finalWealth / 1e5 - 1) * 100)
    print "elapsed %.3f secs" % (time.time() - t1)
Esempio n. 12
0
from coopr.pyomo import (ConcreteModel, Objective, Var, NonNegativeReals,
                         maximize, Constraint)

Activities = ['ActivityOne', 'ActivityTwo']  #Products in other models
UnitProfit = {'ActivityOne': 2, 'ActivityTwo': 5}  #Also called ProfitRate
Resources = ['ResourceOne', 'ResourceTwo']
ResourcesAvailable = {'ResourceOne': 10, 'ResourceTwo': 12}
ResourcesPerUnit = {
    ('ActivityOne', 'ResourceOne'): 1,
    ('ActivityTwo', 'ResourceOne'): 2,
    ('ActivityOne', 'ResourceTwo'): 1,
    ('ActivityTwo', 'ResourceTwo'): 3
}

#Concrete Model
model = ConcreteModel()
#Decision Variables
model.Prod = Var(Activities, within=NonNegativeReals)

#Objective
model.obj = Objective(expr=sum(UnitProfit[i] * model.Prod[i]
                               for i in Activities),
                      sense=maximize)


def ActivityRule(model, r):
    return sum(ResourcesPerUnit[i, r] * model.Prod[i]
               for i in Activities) <= ResourcesAvailable[r]


model.Utilization = Constraint(Resources, rule=ActivityRule)