Initializing help system before first use

Writing and reading problem matrix files


Type: Programming
Rating: 2 (easy-medium)
Description: The file write_read.py creates a few variables, then builds a problem and saves it to a file before re-reading that file into a new problem. The file getmatrix.py shows how to retrieve the coefficient matrix, objective coefficients, and constraints' right-hand sides for a given problem.
File(s): write_read.py, getmatrix.py


write_read.py
# Create a few variables, then build a problem and save it to a file.
# Re-read that file into a new problem and solve it.
#
# (C) 1983-2025 Fair Isaac Corporation

import xpress as xp

m = xp.problem()

c1 = m.addVariable(name="C1", lb=-xp.infinity, ub=xp.infinity)
c2 = m.addVariable(name="C2", lb=-xp.infinity, ub=200)
c3 = m.addVariable(name="C3", vartype=xp.partiallyinteger, threshold=10)
c4 = m.addVariable(name="C4", vartype=xp.semicontinuous, threshold=3, ub=6)
c5 = m.addVariable(name="C5", vartype=xp.integer)

m.setObjective(c1 + c2)

m.addConstraint(c1**2 + c2**2 <= 6,
                2 * c1 + 3 * c2 + c3 == 2,
                -c3**2 + c4**2 + c5**2 <= 0,
                c4 == 0.316227766016838 * c1,
                c5 == 0.316227766016838 * c2)

m.writeProb("example0", "lp")

m2 = xp.problem()

m2.readProb("example0.lp", "")

m2.optimize()

print("objective value:", m2.attributes.objval)
print("solution:", m2.getSolution())

getmatrix.py
# Example to show how to retrieve the coefficient matrix from a
# problem.
#
# (C) 1983-2025 Fair Isaac Corporation

import xpress as xp
import scipy.sparse

p = xp.problem()

p.readProb('Data/prob1.lp')

# Obtain matrix representation of the coefficient matrix for problem.

beg, ind, coef = p.getRows(0, p.attributes.rows - 1)

# Create a Compressed Sparse Row (CSR) format matrix using the data
# from getRows.

A = scipy.sparse.csr_matrix((coef, ind, beg))

# Convert the CSR matrix to a NumPy array of arrays, so that each row
# is a (non-compressed) array.

M = A.toarray()

print(A)
print(M)

c = p.getObj(0, p.attributes.cols - 1)
b = p.getRHS(0, p.attributes.rows - 1)

print(b)
print(c)

© 2001-2025 Fair Isaac Corporation. All rights reserved. This documentation is the property of Fair Isaac Corporation (“FICO”). Receipt or possession of this documentation does not convey rights to disclose, reproduce, make derivative works, use, or allow others to use it except solely for internal evaluation purposes to determine whether to purchase a license to the software described in this documentation, or as otherwise set forth in a written software license agreement between you and FICO (or a FICO affiliate). Use of this documentation and the software described in it must conform strictly to the foregoing permitted uses, and no other use is permitted.