Exemple #1
0
def lattice_width(vertices):
    if not vertices:
        return ZZ(-1)

    miny = min(y for x, y in vertices)
    maxy = max(y for x, y in vertices)

    # Interval of Y values
    lattice_width = maxy - miny

    # Try to do better than lattice_width: we propose an affine
    # transformation matrix
    # [ a b 0 ]
    # [ d e f ]
    # [ 0 0 1 ]
    # with the goal of minimizing the interval of Y values.
    compute_width = MixedIntegerLinearProgram(maximization=False, solver="PPL")
    t = compute_width.new_variable(integer=True)
    lw = compute_width.new_variable(integer=True)[0]
    compute_width.set_objective(lw)

    # We want d >= 1 to ensure that the X-axis gets mapped to some
    # line which is not parallel to the original X-axis. If we keep the
    # X-axis parallel, then we get a lattice width equal to lattice_width
    # which does not give new information. If d >= 1, we are also
    # guaranteed that we can make the transformation matrix invertible.
    compute_width.set_min(t[0], 1)
    for x, y in vertices:
        compute_width.add_constraint(0 <= t[0] * x + t[1] * y + t[2] <= lw)

    return min(compute_width.solve(), lattice_width)
Exemple #2
0
 def minimize (self,cows,max_weight,cow_weight,cow_production):
     p = MixedIntegerLinearProgram(maximization=True)
     cow = p.new_variable(binary=True)
     objective_production = [cow_production[l]*cow[l] for l in range(len(cow_production))]
     objective = reduce(operator.add,objective_production)
     p.set_objective(objective)
     constraint_weight = [cow_weight[l]*cow[l] for l in range(len(cow_weight))]
     constraint = reduce(operator.add,constraint_weight)
     p.add_constraint(constraint,max=max_weight)
     return int(p.solve())
Exemple #3
0
class MILP:
  def __init__(self):
    self.milp = MixedIntegerLinearProgram(maximization=False)
    self.var = self.milp.new_variable(integer=True)

  def add_constraint(self, expr):
    self.milp.add_constraint(convert(self, expr.sympy()))

  def set_objective(self, expr):
    self.milp.set_objective(convert(self, expr.sympy()))

  def solve(self):
    self.milp.solve()
    return {k: int(v) for k, v in self.milp.get_values(self.var).iteritems()}
Exemple #4
0
class MILP:
    def __init__(self):
        self.milp = MixedIntegerLinearProgram(maximization=False)
        self.var = self.milp.new_variable(integer=True)

    def add_constraint(self, expr):
        self.milp.add_constraint(convert(self, expr.sympy()))

    def set_objective(self, expr):
        self.milp.set_objective(convert(self, expr.sympy()))

    def solve(self):
        self.milp.solve()
        return {
            k: int(v)
            for k, v in self.milp.get_values(self.var).iteritems()
        }
Exemple #5
0
def normalize_vertices(vertices):
    if not vertices:
        return vertices

    lw = lattice_width(vertices)

    # Find all values (d,e,f) of transformation matrices
    # [ a b 0 ]
    # [ d e f ]
    # [ 0 0 1 ]
    # realizing the lattice width.
    compute_width = MixedIntegerLinearProgram(maximization=False, solver="PPL")
    t = compute_width.new_variable(integer=True)

    # There are always 2 choices of sign for (d,e) but we want to pick
    # only one. So we assume d >= 0. We still need to take care of the
    # case d == 0 and e < 0 later.
    compute_width.set_min(t[0], 0)

    for x, y in vertices:
        compute_width.add_constraint(0 <= t[0] * x + t[1] * y + t[2] <= lw)

    # Get list of (a,b,d,e,f) transformation matrices
    if lw:
        transformations = []
        for d, e, f in compute_width.polyhedron().integral_points():
            # Take care of sign of (d,e) when d == 0 and skip
            # trivial solution (d,e) == (0,0).
            if d == 0 and e <= 0:
                continue

            g, a, b = e.xgcd(-d)   # a e - b d = 1
            assert g == 1
            # Two cases: det=1 and det=-1
            transformations += [(a,b,d,e,f), (-a,-b,d,e,f)]
    else:
        # Special case lattice width zero: the "compute_width"
        # polyhedron is a vector line and we want the point on that
        # line with content 1.
        d, e, f = compute_width.polyhedron().lines()[0]
        g = d.gcd(e)
        d, e, f = d/g, e/g, f/g
        g, a, b = e.xgcd(-d)   # a e - b d = 1
        assert g == 1
        transformations = [(a,b,d,e,f)]

    best_llg = None
    candidates = []  # Contains lists of vertices with optimal lattice length
    for a, b, d, e, f in transformations:
        newvertices = [(a * x + b * y, d * x + e * y + f) for x, y in vertices]
        newvertices.sort(key=lambda xy: (xy[1], xy[0]))

        # Assert that the range of Y values is the interval [0,lw]
        assert newvertices[0][1] == 0
        assert newvertices[-1][1] == lw

        # Now move the first vertex to the origin and shear such
        # that all points have positive X-coordinate.
        # Note that this shearing keeps the vertices sorted.
        originx = newvertices[0][0]

        # Now shear by a variable amount. We only need those candidates
        # with minimal lattice length. Remark that lattice length is a
        # convex function of the shear distance.
        if lw:
            maxshear = max((originx - x) / y for x, y in newvertices if y).ceil()
            newvertices = [(x - originx + maxshear * y, y) for x, y in newvertices]
        else:
            # All points have Y-coordinate 0: shearing does nothing
            newvertices = [(x - originx, y) for x, y in newvertices]
        newllg = max(x for x, y in newvertices)
        if best_llg is None or newllg < best_llg:
            # We improved the best length: delete all
            # previous candidates
            candidates = []
            best_llg = newllg
        if newllg == best_llg:
            candidates.append(newvertices)

        if not lw:
            continue

        # Now continue shearing in both directions as long as we do not
        # increase the lattice length.
        for s in [-1, 1]:
            shearvertices = newvertices
            while True:
                originx = min(x + s*y for x, y in shearvertices)
                shearvertices = [(x + s*y - originx, y) for x, y in shearvertices]
                llg = max(x for x, y in shearvertices)
                if llg > newllg:
                    break
                if llg < best_llg:
                    # We improved the best length: delete all
                    # previous candidates
                    candidates = []
                    best_llg = llg
                if llg == best_llg:
                    candidates.append(shearvertices)

    candidates180 = []
    for vertices in candidates:
        # Also consider the polygon rotated over 180 degrees. We need
        # this because we considered only 1 sign for (d,e) in the
        # transformation matrix.
        vertices180 = [(best_llg-x, lw-y) for x, y in vertices[::-1]]
        candidates180.append(vertices180)

    candidates += candidates180

    # Now find the best candidate
    def vertices_key(v):
        k = []
        for x, y in v:
            k += [y, x]
        return k

    return min(candidates, key=vertices_key)
class CnavDataModel():
    '''
    This builds a list of linear constraints for CNAV messging by data subcomponent within messages:
    self.Type10Rate         = #First Ephemeris Messsage 10
    self.Type11Rate         = #Second Ephemeris Message 11
    self.TypeIonoRate       = #Iono/ISC Data on Message 30
    self.TypeRa12Rate       = #Reduced Almanac Data On Message 12
    self.TypeRa31Rate       = #Reduced Almanac Data on Message 31
    self.TypeMaRate         = #Midi Almanac Data on Message 37
    self.TypeEopRate        = #Eop Data on Message 32
    self.TypeUtcRate        = #Utc Data on Message 33
    self.TypeDc34Rate       = #Clock and Ephemeral Differential Correction Data on Message 34
    self.TypeDc13Rate       = #Clock Differential Correction Data on Message 13
    self.TypeDc14Rate       = #Ephemeral Differential Correction Data on Message 14
    self.TypeGgtoRate       = #GGTO Data on Message 35
    '''

    def __init__(self,broadcastInterval, milp, Type10Rate, Type11Rate, TypeCcRate, TypeIonoRate, TypeRa12Rate, TypeRa31Rate, TypeMaRate, TypeEopRate, TypeUtcRate, TypeDc34Rate, TypeDc13Rate, TypeDc14Rate,TypeGgtoRate, Type15, Type36, IsBitOptimization):
        '''
        :param broadcastInterval: Provide Modelling constraints w.r.t. timing
        :param milp: Mixed Integer Linear Programming object
        :param Type10Rate: The rate at which we broadcast message type 10
        :param Type11Rate: The rate at which we broadcast message type 11
        :param TypeCcRate: The rate at which we broadcast clock corrections on message type thirties
        :param TypeIonoRate: The rate at which we broadcast message type 30
        :param TypeRa12Rate: The rate at which we broadcast message type 12
        :param TypeRa31Rate: The rate at which we broadcast message type 31
        :param TypeMaRate: The rate at which we broadcast message type 37
        :param TypeEopRate: The rate at which we broadcast message type 32
        :param TypeUtcRate: The rate at which we broadcast message type 33
        :param TypeDc34Rate: The rate at which we broadcast message type 34
        :param TypeDc13Rate: The rate at which we broadcast message type 13
        :param TypeDc14Rate: The rate at which we broadcast message type 14
        :param TypeGgtoRate: The rate at which we broadcast message type 35
        :param Type15      : Do you want to maximize objective with type 15
        :param Type36      : Do you want to maximize objective with type 36
        :param IsBitOptimization: Do you want to maximize by bit optimization?  if not then maximize by message count
        :remark:  If the rates are 0, we assume that we do not broadcast that message.
        '''
        self.broadcastInterval = broadcastInterval
        #check if MixedIntegerLinearProgram
        # if type(milp) is type(MixedIntegerLinearProgram):
        #     self.milp = milp
        # else:
        self.milp = MixedIntegerLinearProgram()
        #create messaging variable
        self.msg = self.milp.new_variable(integer=True, nonnegative=True)
        #determine worst broadcasting interval requirement
        self.totalBroadcastInterval = self.DetermineTotalBroadcastIntervalTime(broadcastInterval, Type10Rate,
                                                                               Type11Rate, TypeCcRate, TypeIonoRate, TypeRa12Rate,
                                                                               TypeRa31Rate, TypeMaRate, TypeEopRate,
                                                                               TypeUtcRate, TypeDc34Rate, TypeDc13Rate,
                                                                               TypeDc14Rate, TypeGgtoRate)
        #check if OptimizationGoal
        self.IsBitOptimization = IsBitOptimization
        #set types
        self.type10Rate = Type10Rate
        self.type11Rate = Type11Rate
        self.typeCcRate = TypeCcRate
        self.typeIonoRate = TypeIonoRate
        self.typeRa12Rate = TypeRa12Rate
        self.typeRa31Rate = TypeRa31Rate
        self.typeMaRate = TypeMaRate
        self.typeEopRate = TypeEopRate
        self.typeUtcRate = TypeUtcRate
        self.typeDc34Rate = TypeDc34Rate
        self.typeDc13Rate = TypeDc13Rate
        self.typeDc14Rate = TypeDc14Rate
        self.typeGgtoRate = TypeGgtoRate
        self.type15 = Type15
        self.type36 = Type36
        #build linear constraints if called for it.
        if self.type10Rate:
            self.BuildType10()
        if self.type11Rate:
            self.BuildType11()
        if self.typeCcRate:
            self.BuildTypeCc()
        if self.typeIonoRate:
            self.BuildTypeIono()
        if self.typeRa12Rate or self.typeRa31Rate:
            self.BuildRaType()
        if self.typeMaRate:
            self.BuildMaType()
        if self.typeEopRate:
            self.BuildEopRate()
        if self.typeUtcRate:
            self.BuildUtcRate()
        if self.typeDc34Rate or self.typeDc13Rate or self.typeDc14Rate:
            self.BuildDcRate()
        if self.typeGgtoRate:
            self.BuildGgtoRate()
        self.BuildTotalMessagesConstraint()
        self.BuildOptimizationGoal()

    def BuildTotalMessagesConstraint(self):
        self.milp.add_constraint(self.msg[10]+self.msg[11]+self.msg[12]+self.msg[13]+self.msg[14]+self.msg[15]+self.msg[30]+self.msg[31]+self.msg[32]+self.msg[33]+self.msg[34]+self.msg[35]+self.msg[36]+self.msg[37]==self.totalBroadcastInterval)

    def DetermineTotalBroadcastIntervalTime(self,broadcastInterval, Type10Rate, Type11Rate, TypeCcRate, TypeIonoRate, TypeRa12Rate, TypeRa31Rate, TypeMaRate, TypeEopRate, TypeUtcRate, TypeDc34Rate, TypeDc13Rate, TypeDc14Rate, TypeGgtoRate):
        '''
        :param broadcastInterval: An object that inherits MessageBroadcastIntervals
        :param Type10Rate: The rate at which we broadcast message type 10
        :param Type11Rate: The rate at which we broadcast message type 11
        :param TypeIonoRate: The rate at which we broadcast message type 30
        :param TypeRa12Rate: The rate at which we broadcast message type 12
        :param TypeRa31Rate: The rate at which we broadcast message type 31
        :param TypeMaRate: The rate at which we broadcast message type 37
        :param TypeEopRate: The rate at which we broadcast message type 32
        :param TypeUtcRate: The rate at which we broadcast message type 33
        :param TypeDc34Rate: The rate at which we broadcast message type 34
        :param TypeDc13Rate: The rate at which we broadcast message type 13
        :param TypeDc14Rate: The rate at which we broadcast message type 14
        :param TypeGgtoRate: The rate at which we broadcast message type 35
        :return: The number of messages needed within a super frame
        '''
        interval = 0
        if Type10Rate > 0 or Type11Rate > 0 or TypeCcRate > 0:
            interval = 4
        if TypeIonoRate > 0 or TypeGgtoRate > 0 or TypeUtcRate > 0:
            interval = 24
        if TypeRa31Rate > 0 or TypeRa12Rate > 0:
            interval = 100
        if TypeEopRate > 0 or TypeDc34Rate > 0 or TypeDc13Rate > 0 or TypeDc14Rate > 0:
            interval = 150
        if TypeMaRate:
            interval = 600
        return interval
    
    def BuildType10(self):
        '''
        Builds the linear constraints for message type 10
        :return:
        '''
        self.milp.add_constraint(self.msg[10] >= self.totalBroadcastInterval/4)

    def BuildType11(self):
        '''
        
        :return:
        '''
        self.milp.add_constraint(self.msg[11] >= self.totalBroadcastInterval/4)
    def BuildTypeCc(self):
        '''
        
        :return:
        '''
        self.milp.add_constraint(self.msg[30]+self.msg[31]+self.msg[32]+self.msg[33]+self.msg[34]+self.msg[35]+self.msg[36]+self.msg[37] >= self.totalBroadcastInterval/4)
    def BuildTypeIono(self):
        '''
        
        :return:
        '''
        self.milp.add_constraint(self.msg[30] >= self.totalBroadcastInterval/25)
    def BuildRaType(self):
        '''
        type 12 has 7
        type 31 has 4
        Reduced Almanac


        The almanac parameters are provided in any one of message types 31, 37, and 12. Message type 37 provides Midi almanac parameters and the reduced almanac parameters are provided in either message type 31 or type 12. The SV shall broadcast both message types 31 (and/or 12) and 37. However, the reduced almanac parameters (i.e. message types 31 and/or 12) for the complete set of SVs in the constellation will be broadcast by a SV using shorter duration of time compared to the broadcast of the complete set of Midi almanac parameters (i.e. message type 37). The parameters are defined below, followed by material pertinent to the use of the data.

        :return:
        '''
        if self.typeRa12Rate and self.typeRa31Rate:
            self.milp.add_constraint(7*self.msg[12]+4*self.msg[31]>=self.broadcastInterval.SvCount*6)
        if self.typeRa12Rate and not self.typeRa31Rate:
            self.milp.add_constraint(7*self.msg[12]>=self.broadcastInterval.SvCount*6)
        if self.typeRa31Rate and not self.typeRa12Rate:
            self.milp.add_constraint(4*self.msg[31]>=self.broadcastInterval.SvCount*6)
    def BuildMaType(self):
        '''
        Midi Almanac

        The almanac parameters are provided in any one of message types 31, 37, and 12. Message type 37 provides Midi almanac parameters and the reduced almanac parameters are provided in either message type 31 or type 12. The SV shall broadcast both message types 31 (and/or 12) and 37. However, the reduced almanac parameters (i.e. message types 31 and/or 12) for the complete set of SVs in the constellation will be broadcast by a SV using shorter duration of time compared to the broadcast of the complete set of Midi almanac parameters (i.e. message type 37). The parameters are defined below, followed by material pertinent to the use of the data.

        :return:
        '''
        self.milp.add_constraint(self.msg[37]>=self.broadcastInterval.SvCount)
    def BuildEopRate(self):
        '''
        
        :return:
        '''
        self.milp.add_constraint(self.msg[32] >= 4)
    def BuildUtcRate(self):
        '''
        
        :return:
        '''
        self.milp.add_constraint(self.msg[33] >= self.totalBroadcastInterval/25)
    def BuildDcRate(self):
        '''
        Message type 34 provides SV clock correction parameters (ref. Section 30.3.3.2) and also, shall contain DC parameters that apply to the clock and ephemeris data transmitted by another SV. One message type 34, Figure 30-7, shall contain 34 bits of clock differential correction (CDC) parameters and 92 bits of ephemeris differential correction (EDC) parameters for one SV other than the transmitting SV. Bit 150 of message type 34 shall be a DC Data Type indicator that indicates the data type for which the DC parameters apply. Zero (0) signifies that the corrections apply to CNAV data, Dc(t), and one (1) signifies that the corrections apply to NAV data, D(t).
Message types 13 and 14 together also provide DC parameters. Message type 13, Figure 30-12, shall contain CDC parameters applicable to 6 SVs and message type 14, Figure 30-13, shall contain EDC parameters applicable to 2 SVs. There shall be a DC Data Type indicator preceding each CDC or EDC packet. The content of an individual data packet is depicted in Figure 30-16. The number of bits, scale factors (LSB), the range, and the units of all fields in the DC packet are given in Table 30-X.
        :return:
        '''
        if self.typeDc14Rate and self.typeDc13Rate and self.typeDc34Rate:
            self.milp.add_constraint(2*self.msg[14]+self.msg[34]>=(self.broadcastInterval.SvCount - 1)*4)
            self.milp.add_constraint(6*self.msg[13]+self.msg[34]>=(self.broadcastInterval.SvCount - 1)*4)
        if self.typeDc14Rate and self.typeDc13Rate and not self.typeDc34Rate:
            self.milp.add_constraint(2*self.msg[14]>=(self.broadcastInterval.SvCount - 1)*4)
            self.milp.add_constraint(6*self.msg[13]>=(self.broadcastInterval.SvCount - 1)*4)
        if self.typeDc14Rate and not self.typeDc13Rate and self.typeDc34Rate:
            self.milp.add_constraint(2*self.msg[14]+self.msg[34]>=(self.broadcastInterval.SvCount - 1)*4)
        if self.typeDc14Rate and not self.typeDc13Rate and not self.typeDc34Rate:
            self.milp.add_constraint(2*self.msg[14]>=(self.broadcastInterval.SvCount - 1)*4)
        if not self.typeDc14Rate and self.typeDc13Rate and self.typeDc34Rate:
            self.milp.add_constraint(6*self.msg[13]+self.msg[34]>=(self.broadcastInterval.SvCount - 1)*4)
        if not self.typeDc14Rate and self.typeDc13Rate and not self.typeDc34Rate:
            self.milp.add_constraint(6*self.msg[13]>=(self.broadcastInterval.SvCount - 1)*4)
        if not self.typeDc14Rate and not self.typeDc13Rate and self.typeDc34Rate:
            self.milp.add_constraint(self.msg[34]>=(self.broadcastInterval.SvCount - 1)*4)
        if not self.typeDc14Rate and not self.typeDc13Rate and not self.typeDc34Rate:
            return
    def BuildGgtoRate(self):
        '''
        
        :return:
        '''
        self.milp.add_constraint(self.msg[35] >= self.totalBroadcastInterval/25)
    def BuildOptimizationGoal(self):
        '''

        :return:
        '''
        if self.type15 and self.type36 and self.IsBitOptimization:
            self.milp.set_objective(149*self.msg[36] + 238*self.msg[15])
        if self.type15 and self.type36 and not self.IsBitOptimization:
            self.milp.set_objective(self.msg[36] + self.msg[15])
        if self.type15 and not self.type36 and self.IsBitOptimization:
            self.milp.set_objective(238*self.msg[15])
        if self.type15 and not self.type36 and not self.IsBitOptimization:
            self.milp.set_objective(self.msg[15])
        if not self.type15 and self.type36 and self.IsBitOptimization:
            self.milp.set_objective(149*self.msg[36])
        if not self.type15 and self.type36 and not self.IsBitOptimization:
            self.milp.set_objective(self.msg[36])
        if not self.type15 and not self.type36 and self.IsBitOptimization:
            raise Exception('Optimization Execption: need to specify an optimization goal')
        if not self.type15 and not self.type36 and not self.IsBitOptimization:
            raise Exception('Optimization Execption: need to specify an optimization goal')

    def Solve(self):
        print "solving..."
        self.milp.show()
        self.milp.solve()
        print "solved!"

    def GetResults(self):
        for msg in sorted(self.milp.get_values(self.msg)):
            print 'Message %s = %s' % (msg,int(round(self.milp.get_values(self.msg)[msg])))
 def __init__(self,broadcastInterval, milp, Type10Rate, Type11Rate, TypeCcRate, TypeIonoRate, TypeRa12Rate, TypeRa31Rate, TypeMaRate, TypeEopRate, TypeUtcRate, TypeDc34Rate, TypeDc13Rate, TypeDc14Rate,TypeGgtoRate, Type15, Type36, IsBitOptimization):
     '''
     :param broadcastInterval: Provide Modelling constraints w.r.t. timing
     :param milp: Mixed Integer Linear Programming object
     :param Type10Rate: The rate at which we broadcast message type 10
     :param Type11Rate: The rate at which we broadcast message type 11
     :param TypeCcRate: The rate at which we broadcast clock corrections on message type thirties
     :param TypeIonoRate: The rate at which we broadcast message type 30
     :param TypeRa12Rate: The rate at which we broadcast message type 12
     :param TypeRa31Rate: The rate at which we broadcast message type 31
     :param TypeMaRate: The rate at which we broadcast message type 37
     :param TypeEopRate: The rate at which we broadcast message type 32
     :param TypeUtcRate: The rate at which we broadcast message type 33
     :param TypeDc34Rate: The rate at which we broadcast message type 34
     :param TypeDc13Rate: The rate at which we broadcast message type 13
     :param TypeDc14Rate: The rate at which we broadcast message type 14
     :param TypeGgtoRate: The rate at which we broadcast message type 35
     :param Type15      : Do you want to maximize objective with type 15
     :param Type36      : Do you want to maximize objective with type 36
     :param IsBitOptimization: Do you want to maximize by bit optimization?  if not then maximize by message count
     :remark:  If the rates are 0, we assume that we do not broadcast that message.
     '''
     self.broadcastInterval = broadcastInterval
     #check if MixedIntegerLinearProgram
     # if type(milp) is type(MixedIntegerLinearProgram):
     #     self.milp = milp
     # else:
     self.milp = MixedIntegerLinearProgram()
     #create messaging variable
     self.msg = self.milp.new_variable(integer=True, nonnegative=True)
     #determine worst broadcasting interval requirement
     self.totalBroadcastInterval = self.DetermineTotalBroadcastIntervalTime(broadcastInterval, Type10Rate,
                                                                            Type11Rate, TypeCcRate, TypeIonoRate, TypeRa12Rate,
                                                                            TypeRa31Rate, TypeMaRate, TypeEopRate,
                                                                            TypeUtcRate, TypeDc34Rate, TypeDc13Rate,
                                                                            TypeDc14Rate, TypeGgtoRate)
     #check if OptimizationGoal
     self.IsBitOptimization = IsBitOptimization
     #set types
     self.type10Rate = Type10Rate
     self.type11Rate = Type11Rate
     self.typeCcRate = TypeCcRate
     self.typeIonoRate = TypeIonoRate
     self.typeRa12Rate = TypeRa12Rate
     self.typeRa31Rate = TypeRa31Rate
     self.typeMaRate = TypeMaRate
     self.typeEopRate = TypeEopRate
     self.typeUtcRate = TypeUtcRate
     self.typeDc34Rate = TypeDc34Rate
     self.typeDc13Rate = TypeDc13Rate
     self.typeDc14Rate = TypeDc14Rate
     self.typeGgtoRate = TypeGgtoRate
     self.type15 = Type15
     self.type36 = Type36
     #build linear constraints if called for it.
     if self.type10Rate:
         self.BuildType10()
     if self.type11Rate:
         self.BuildType11()
     if self.typeCcRate:
         self.BuildTypeCc()
     if self.typeIonoRate:
         self.BuildTypeIono()
     if self.typeRa12Rate or self.typeRa31Rate:
         self.BuildRaType()
     if self.typeMaRate:
         self.BuildMaType()
     if self.typeEopRate:
         self.BuildEopRate()
     if self.typeUtcRate:
         self.BuildUtcRate()
     if self.typeDc34Rate or self.typeDc13Rate or self.typeDc14Rate:
         self.BuildDcRate()
     if self.typeGgtoRate:
         self.BuildGgtoRate()
     self.BuildTotalMessagesConstraint()
     self.BuildOptimizationGoal()
Exemple #8
0
 def __init__(self):
     self.milp = MixedIntegerLinearProgram(maximization=False)
     self.var = self.milp.new_variable(integer=True)
Exemple #9
0
 def __init__(self):
   self.milp = MixedIntegerLinearProgram(maximization=False)
   self.var = self.milp.new_variable(integer=True)
Exemple #10
0
def ricci_gen(g, problem):
    # relevant_verts will have unique items starting with source, then target,
    # then the neighbors of source and target.
    # Use an OrderedDict to get uniques but preserve order.
    relevant_verts = OrderedDict.fromkeys(
        [problem.src, problem.tgt] +
        list(g.neighbor_iterator(problem.src)) +
        list(g.neighbor_iterator(problem.tgt))).keys()
    N = len(relevant_verts)
    D = matrix(ZZ, N, N)
    for i in range(N):
        for j in range(i, N):
            dist = g.distance(relevant_verts[i], relevant_verts[j])
            D[i, j] = dist
            D[j, i] = dist

    # We multiply through by problem.denom, so this checks for unit mass:
    assert(problem.denom == sum(problem.m_src[z] for z in relevant_verts))
    assert(problem.denom == sum(problem.m_tgt[z] for z in relevant_verts))

    # Set up linear program.
    p = MixedIntegerLinearProgram()
    # Note that here and in what follows, i and j are used as the vertices that
    # correspond to relevant_verts[i] and relevant_verts[j].
    # a[i,j] is the (unknown) amount of mass that goes from i to j.
    # It is constrained to be nonnegative, which are the only inequalities for
    # our LP.
    a = p.new_variable(nonnegative=True)
    # Maximize the negative of the mass transport.
    p.set_objective(
        -p.sum(D[i, j]*a[i, j] for i in range(N) for j in range(N)))
    # The equality constraints simply state that the mass starts in the places
    # it has diffused to from source...
    for i in range(N):
        p.add_constraint(
            p.sum(a[i, j] for j in range(N)) ==
            problem.m_src[relevant_verts[i]])
    # and finishes in the places it has diffused to from target.
    for j in range(N):
        p.add_constraint(
            p.sum(a[i, j] for i in range(N)) ==
            problem.m_tgt[relevant_verts[j]])

    W1 = -QQ(p.solve())/problem.denom

    dist_src_tgt = D[0, 1]  # By def'n of relevant_verts.
    kappa = 1 - W1/dist_src_tgt
    return Result(
        coupling={
            (relevant_verts[i], relevant_verts[j]): QQ(v/problem.denom)
            for ((i, j), v) in p.get_values(a).items() if v > 0},
        dist=dist_src_tgt,
        W1=W1,
        kappa=kappa,
        ric=kappa)
Exemple #11
0
#!/Users/syrus/Downloads/sage-4.7/sage -python
from sage.all import MixedIntegerLinearProgram
p = MixedIntegerLinearProgram(maximization=True)
x = p.new_variable(binary=True)
#for i in range(7):
	#p.set_binary(x[i+1])
weight = '340,355,223,243,130,240,260,155,302,130'.split(',')
production = '45,50,34,39,29,40,30,52,31'.split(',')
cows= len(production)
#objective = 0
#for l in range(len(production)):
#	objective = objective+int(production[l])*x[l+1]
import operator
objective = reduce(operator.add,[int(production[l])*x[l+1] for l in range(cows)])
p.set_objective(objective)

constraint = 0
for l in range(len(weight)):
	constraint = constraint +int(weight[l])*x[l+1]

p.add_constraint(constraint,max=2000)

#p.show()
print int(p.solve())