Files
ortools-clone/examples/tests/test_lp_api.py

61 lines
1.4 KiB
Python
Raw Normal View History

2021-12-07 09:13:09 +01:00
#!/usr/bin/env python3
2014-02-19 18:53:31 +00:00
from google.protobuf import text_format
from ortools.linear_solver import pywraplp
from ortools.linear_solver import linear_solver_pb2
2014-02-19 18:53:31 +00:00
import sys
import types
2014-05-22 20:13:16 +00:00
def Sum(arg):
if type(arg) is types.GeneratorType:
arg = [x for x in arg]
2014-05-22 20:13:16 +00:00
sum = 0
for i in arg:
sum += i
2014-05-22 20:13:16 +00:00
print('sum(%s) = %d' % (str(arg), sum))
def test_sum_no_brackets():
Sum(x for x in range(10) if x % 2 == 0)
Sum([x for x in range(10) if x % 2 == 0])
2014-02-19 18:53:31 +00:00
text_model = """
solver_type:CBC_MIXED_INTEGER_PROGRAMMING
model <
maximize:true
variable < lower_bound:1 upper_bound:10 objective_coefficient:2 >
variable < lower_bound:1 upper_bound:10 objective_coefficient:1 >
constraint < lower_bound:-10000 upper_bound:4
2014-06-13 07:27:24 +00:00
var_index:0
var_index:1
coefficient:1
coefficient:2
2014-02-19 18:53:31 +00:00
>
>
"""
2014-05-22 20:13:16 +00:00
2014-02-19 18:53:31 +00:00
def test_proto():
input_proto = linear_solver_pb2.MPModelRequest()
2014-02-19 18:53:31 +00:00
text_format.Merge(text_model, input_proto)
solver = pywraplp.Solver('solveFromProto',
pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)
2015-12-11 14:14:08 +01:00
print(input_proto)
2014-02-19 18:53:31 +00:00
# For now, create the model from the proto by parsing the proto
solver.LoadModelFromProto(input_proto.model)
2014-05-22 20:13:16 +00:00
solver.EnableOutput()
2014-02-19 18:53:31 +00:00
solver.Solve()
# Fill solution
solution = linear_solver_pb2.MPSolutionResponse()
2014-02-19 18:53:31 +00:00
solver.FillSolutionResponseProto(solution)
2015-12-11 14:14:08 +01:00
print(solution)
2014-02-19 18:53:31 +00:00
def main():
test_sum_no_brackets()
2014-07-09 11:17:29 +00:00
# test_proto()
if __name__ == '__main__':
main()