install gurobi
Step 1: Download gurobi ( http://www.gurobi.com ), you need to register an account
The second step, apply for license registration
If it can pass through the campus network, it will be generated directly.
If not, please send an email to apply through the website http://www.gurobi.cn/NewsView1.Asp?id=4
Third, an application code will be sent by email, follow the steps below
Fourth, configure environment variables
GRB_LICENSE_FILE=gurobi.lic path
Step 5: Install Gurobi into the python library, first enter the installation directory, and then run setup.py in the command prompt
Enter python setup.py install in the command prompt window to install.
Sixth, test code
m = Model("min example")
m.modelSense = GRB.MINIMIZE
objFcnCoeffs = [3, 5, 6, 9]
xVars = []
for i in range(4):
xVars.append(m.addVar(vtype=GRB.INTEGER, obj=objFcnCoeffs[i], name="Open%d" % i))
# Update model to integrate new variables
m.update()
# Constraints
m.addConstr(-2 * xVars[0] + 6 * xVars[1] - 3 * xVars[2] + 4 * xVars[3] >= 2, "Con1")
m.addConstr(-5 * xVars[0] + 3 * xVars[1] + xVars[2] + 3 * xVars[3] >= -2, "Con2")
m.addConstr(5 * xVars[0] - xVars[1] + 4 * xVars[2] - 2 * xVars[3] >= 3, "Con3")
# Attempt to set an initial feasible solution (in this case to an optimal solution)
startValues = [1, 1, 0, 0]
for i in range(4):
xVars[i].start = startValues[i]
# Solve model
m.optimize()
# Print solution
print('\
TOTAL COSTS: %g' % m.objVal)
for i in range(4):
print('\
xVar[%s] = %g' % i, xVars[i])
Pycharm configuration syntax prompt
The compiler can run gurobi, but pycharm doesn't recognize gurobi, gives a red line, and can't type hint.
Just install the gurobipy-stubs module (enter the project environment first, in the case of conda, it is the name of the conda activate environment)
pip install gurobipy-stubs
References: https://blog.csdn.net/qq_57867839/article/details/126844519