FICO
FICO Xpress Optimization Examples Repository
FICO Optimization Community FICO Xpress Optimization Home
Back to examples browserPrevious exampleNext example

Using NumPy and Xpress

Description
An example of printing a matrix of random numbers and a problem formulation that uses the xpress.Dot() operator to formulate constraints simply. Note that the NumPy dot operator is not suitable here as the result is an expression in the Xpress variables.

Further explanation of this example: 'Xpress Python Reference Manual'

NumPy2_python.zip[download all files]

Source Files
By clicking on a file name, a preview is opened at the bottom of this page.
example_numpy1.py[download]
example_numpy2.py[download]





example_numpy1.py

# Example: use numpy to print the product of a matrix by a random vector.
#
# Uses xpress.Dot to on a matrix and a vector. Note that the NumPy dot operator
# works perfectly fine here.
#
# (C) Fair Isaac Corp., 1983-2024

from __future__ import print_function

import numpy as np
import xpress as xp

p = xp.problem()

x = [p.addVariable() for i in range(5)]

p.addConstraint(xp.Sum(x) >= 2)

p.setObjective(xp.Sum(x[i]**2 for i in range(5)))

p.optimize()

A = np.array(range(30)).reshape(6, 5)  # A is a 6x5 matrix
sol = np.array(p.getSolution())  # suppose it's a vector of size 5
columns = A*sol         # not a matrix-vector product!
v = xp.Dot(A, sol)      # this is a matrix-vector product A*sol

print(v)

Back to examples browserPrevious exampleNext example