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()
예제 #2
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()
예제 #3
0
#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,
    and and a plant index as a second positional argument
    """
    
    return sum(HoursPerUnit[i,p] * model.WeeklyProd[i] for i in Products) <= HoursAvailable[p]

#This statement is what Pyomo needs to generate one constraint for each plant
model.Capacity = Constraint(Plants, rule = CapacityRule)

#This is an optional code path that allows the script to be run outside of
#pyomo command-line.  For example:  python wyndor.py
if __name__ == '__main__':
   
    #This replicates what the pyomo command-line tools does
    from coopr.opt import SolverFactory
    opt = SolverFactory("glpk")
    instance = model.create()
    results = opt.solve(instance)
    #sends results to stdout
    results.write()
예제 #4
0
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)
예제 #5
0
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)
예제 #6
0
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
if __name__ == '__main__':

    from coopr.opt import SolverFactory
    opt = SolverFactory("glpk")
    instance = model.create()
    results = opt.solve(instance)
    #sends results to stdout
    results.write()

    instance.load(results)  # so we can access variable values by name
    print "Now, we will just write a report (but an ugly one), rather than all results."
    print "we will do it three different ways."