Back to Or Tools

volsay3

examples/notebook/contrib/volsay3.ipynb

2016-062.9 KB
Original Source
Copyright 2025 Google LLC.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

volsay3

<table align="left"> <td> <a href="https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/contrib/volsay3.ipynb">Run in Google Colab</a> </td> <td> <a href="https://github.com/google/or-tools/blob/main/examples/contrib/volsay3.py">View source on GitHub</a> </td> </table>

First, you must install ortools package in this colab.

python
%pip install ortools

Volsay problem in Google or-tools.

From the OPL model volsay.mod Using arrays.

This model was created by Hakan Kjellerstrand ([email protected]) Also see my other Google CP Solver models: http://www.hakank.org/google_or_tools/

python
from ortools.linear_solver import pywraplp


def main(unused_argv):

  # Create the solver.

  # using GLPK
  # solver = pywraplp.Solver('CoinsGridGLPK',
  #                          pywraplp.Solver.GLPK_LINEAR_PROGRAMMING)

  # Using CLP
  solver = pywraplp.Solver.CreateSolver('CLP')
  if not solver:
    return

  # data
  num_products = 2

  products = ['Gas', 'Chloride']
  components = ['nitrogen', 'hydrogen', 'chlorine']

  demand = [[1, 3, 0], [1, 4, 1]]
  profit = [30, 40]
  stock = [50, 180, 40]

  # declare variables
  production = [
      solver.NumVar(0, 100000, 'production[%i]' % i)
      for i in range(num_products)
  ]

  #
  # constraints
  #
  for c in range(len(components)):
    solver.Add(
        solver.Sum([demand[p][c] * production[p]
                    for p in range(len(products))]) <= stock[c])

  # objective
  # Note: there is no support for solver.ScalProd in the LP/IP interface
  objective = solver.Maximize(
      solver.Sum([production[p] * profit[p] for p in range(num_products)]))

  print('NumConstraints:', solver.NumConstraints())
  print('NumVariables:', solver.NumVariables())
  print()

  #
  # solution and search
  #
  solver.Solve()

  print()
  print('objective = ', solver.Objective().Value())
  for i in range(num_products):
    print(products[i], '=', production[i].SolutionValue(), end=' ')
    print('ReducedCost = ', production[i].ReducedCost())

  print()
  print('walltime  :', solver.WallTime(), 'ms')
  print('iterations:', solver.Iterations())


main('Volsay')