coin-or / pulp

A python Linear Programming API
http://coin-or.github.io/pulp/
Other
2.04k stars 381 forks source link

Raise error on multiplication with NaN #674

Closed hblunck closed 7 months ago

hblunck commented 1 year ago

Describe the new feature

Often times, optimization models are created from data that is handled/manipulated in tools like numpy/pandas. In the data collection and manipulation that preceeds the model building, it might happen that the constant that eventually ends up in the optimization model is NaN. This of course does not result in a valid LP that could reasonably be solved.

However, Pulp currently happily accepts multiplying variables with NaN values.

import pulp
import numpy as np

a = np.nan
x = pulp.LpVariable("x")

print(a*x)

Results in LpAffineExpression instance

nan*x

Such optimization model is often initially accepted by the solver and eventually can lead to errors that are hard to trace back to the original problem.

I would hence suggest, that Pulp raises an error as soon as multiplication with NA (or inf) values is attempted during model creation, thus improving the model development and debugging speed.

Additional info

Please answer these questions before submitting your feature request.

Is your feature request related to an issue? Please include the issue number.

No

Does this feature exist in another product or project? Please provide a link.

No

pchtsp commented 11 months ago

Thanks. I'm curious about how we could try to detect this when numpy is not a dependency of pulp. Maybe we could try to cast the value into a regular python float. If you have a way to check for this, do not hesitate doing a Pull Request

hblunck commented 11 months ago

It appears that the built in math module has a function to check for finite values see here.