or-tools called from SQL Server 2022 not working #3688
-
What version of OR-Tools and what language are you using? I have configured the Python runtime environment in SQL as defined in Microsofts documentation here Other custom Python libraries works correctly in SQL Server e.g. "text-tools" (see install instructions here) However, I don't get any results back from Python when solving the sample MIP problem using or-tools. The problem solves perfectly fine when I run it in Visual Code. What did you expect to see What did you see instead? from ortools.linear_solver.python import model_builder
model = model_builder.ModelBuilder()
print(model) I do see a memory address which I assume means the library might have imported correctly i.e.:? Anything else we should know about your project / environment When I print the content of variable @pythonscript and run it in python manually it works perfectly fine: /* ---- Test OR-Tools Solve */
use MLDemo
--in case the python runtime environment restricts custom libraries like ortools to only work within the database for which it was installed
go
--Example from https://github.com/google/or-tools/blob/stable/ortools/linear_solver/samples/simple_mip_program.py
declare @pythonscript nvarchar(max)
set @pythonscript =N'
#!/usr/bin/env python3
# Copyright 2010-2022 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.
"""Integer programming examples that show how to use the APIs."""
# [START program]
# [START import]
import numpy as np
import pandas as pd
from ortools.linear_solver import pywraplp
# [END import]
def main():
# [START solver]
# Create the mip solver with the SCIP backend.
solver = pywraplp.Solver.CreateSolver('+'''SCIP'''+')
if not solver:
return
# [END solver]
# [START variables]
infinity = solver.infinity()
# x and y are integer non-negative variables.
x = solver.IntVar(0.0, infinity, '+'''x'''+')
y = solver.IntVar(0.0, infinity, '+'''y'''+')
print('+'''Number of variables ='''+', solver.NumVariables())
# [END variables]
# [START constraints]
# x + 7 * y <= 17.5.
solver.Add(x + 7 * y <= 17.5)
# x <= 3.5.
solver.Add(x <= 3.5)
print('+'''Number of constraints ='''+', solver.NumConstraints())
# [END constraints]
# [START objective]
# Maximize x + 10 * y.
solver.Maximize(x + 10 * y)
# [END objective]
# [START solve]
status = solver.Solve()
# [END solve]
# [START print_solution]
if status == pywraplp.Solver.OPTIMAL:
print('+'''Solution:'''+')
print('+'''Objective value ='''+', solver.Objective().Value())
print('+'''x ='''+', x.solution_value())
print('+'''y ='''+', y.solution_value())
else:
print('+'''The problem does not have an optimal solution.'''+')
# [END print_solution]
# [START advanced]
print('+'''\nAdvanced usage:'''+')
print('+'''Problem solved in %f milliseconds'''+' % solver.wall_time())
print('+'''Problem solved in %d iterations'''+' % solver.iterations())
print('+'''Problem solved in %d branch-and-bound nodes'''+' % solver.nodes())
# [END advanced]
# [START SQL Dataframe OutputDataSet]
np_var_names = np.array([])
np_var_values = np.array([])
np_var_names = np.append('+'''x'''+', '+'''y'''+')
np_var_values = np.append(x.solution_value(), y.solution_value())
df = pd.DataFrame(np_var_names, columns =['+'''VariableName'''+'])
df['+'''VariableValue'''+'] = np_var_values.tolist()
OutputDataSet = df
print(OutputDataSet)
# [END SQL Dataframe OutputDataSet]
if __name__ == '+'''__main__'''+':
main()
# [END program]
'
--print @pythonscript
EXEC sp_execute_external_script @language = N'Python'
,@script= @pythonscript
,@input_data_1 = N''
,@output_data_1_name = N'OutputDataSet'
WITH RESULT SETS
( ( [VariableName] VARCHAR(50) NOT NULL,
[VariableValue] float NULL)
) edit: sqlmlutils.SQLPackageManager(connection).install("ortools") sqlmlutils.SQLPackageManager(connection).install("pandas") sqlmlutils.SQLPackageManager(connection).install("numpy") |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments 1 reply
-
Moving to discussions. |
Beta Was this translation helpful? Give feedback.
-
Actually, i do not how what the '+'''Scip'''+' is interpreted by python. Can you check with just 'scip' ? |
Beta Was this translation helpful? Give feedback.
-
This small example proves that the pandas library works fine:
output: |
Beta Was this translation helpful? Give feedback.
-
This T-SQL with double quotes instead of single quotes also solves fine in Python natively i.e. in Visual Code but produces no results when called within SQL Server: /* ---- Test OR-Tools Solve */
use MLDemo
--in case the python runtime environment restricts custom libraries like ortools to only work within the database for which it was installed
go
--Example from https://github.com/google/or-tools/blob/stable/ortools/linear_solver/samples/simple_mip_program.py
declare @pythonscript nvarchar(max)
set @pythonscript =N'
#!/usr/bin/env python3
# Copyright 2010-2022 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.
"""Integer programming examples that show how to use the APIs."""
# [START program]
# [START import]
import numpy as np
import pandas as pd
from ortools.linear_solver import pywraplp
# [END import]
def main():
# [START solver]
# Create the mip solver with the SCIP backend.
solver = pywraplp.Solver.CreateSolver("SCIP")
if not solver:
return
# [END solver]
# [START variables]
infinity = solver.infinity()
# x and y are integer non-negative variables.
x = solver.IntVar(0.0, infinity, "x")
y = solver.IntVar(0.0, infinity, "y")
print("Number of variables =", solver.NumVariables())
# [END variables]
# [START constraints]
# x + 7 * y <= 17.5.
solver.Add(x + 7 * y <= 17.5)
# x <= 3.5.
solver.Add(x <= 3.5)
print("Number of constraints =", solver.NumConstraints())
# [END constraints]
# [START objective]
# Maximize x + 10 * y.
solver.Maximize(x + 10 * y)
# [END objective]
# [START solve]
status = solver.Solve()
# [END solve]
# [START print_solution]
if status == pywraplp.Solver.OPTIMAL:
print("Solution:")
print("Objective value =", solver.Objective().Value())
print("x =", x.solution_value())
print("y =", y.solution_value())
else:
print("The problem does not have an optimal solution.")
# [END print_solution]
# [START advanced]
print("\nAdvanced usage:")
print("Problem solved in %f milliseconds" % solver.wall_time())
print("Problem solved in %d iterations" % solver.iterations())
print("Problem solved in %d branch-and-bound nodes" % solver.nodes())
# [END advanced]
# [START SQL Dataframe OutputDataSet]
np_var_names = np.array([])
np_var_values = np.array([])
np_var_names = np.append("x", "y")
np_var_values = np.append(x.solution_value(), y.solution_value())
df = pd.DataFrame(np_var_names, columns =["VariableName"])
df["VariableValue"] = np_var_values.tolist()
OutputDataSet = df
print(OutputDataSet)
# [END SQL Dataframe OutputDataSet]
if __name__ == "__main__":
main()
# [END program]
'
--print @pythonscript
EXEC sp_execute_external_script @language = N'Python'
,@script= @pythonscript
,@input_data_1 = N''
,@output_data_1_name = N'OutputDataSet'
WITH RESULT SETS
( ( [VariableName] VARCHAR(50) NOT NULL,
[VariableValue] float NULL)
) |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
-
added note for clarity: for earlier versions of SQL e.g. SQL Server 2019: edit: for Python installation instructions in SQL Server 2019 see here for example, run this in elevated cmd prompt to install or-tools using pip in SQL runtime environment: |
Beta Was this translation helpful? Give feedback.
Ok, I managed to get the SQL Server 2022 solve working using a .mps file in the following way:
Herewith the T-SQL: