├── .gitignore
├── .idea
├── .gitignore
├── vcs.xml
├── misc.xml
├── inspectionProfiles
│ └── profiles_settings.xml
├── modules.xml
└── cplexrunonwml.iml
├── model.tar.gz
├── README.md
├── log.txt
├── solution.json
├── diet.lp
├── cplexrunonwml.py
├── cplexrunonwmlv2.py
└── LICENSE
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | log.txt
3 | model.tar.gz
4 |
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /workspace.xml
3 |
--------------------------------------------------------------------------------
/model.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IBMDecisionOptimization/cplexrunonwml/master/model.tar.gz
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # cplexrunonwml
2 |
3 | This is a sample python code to run CPLEX models (.lp, .mps, etc) on WML.
4 |
5 | The v2 versions is to be used with WML v2 instances.
6 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/cplexrunonwml.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/log.txt:
--------------------------------------------------------------------------------
1 | [2020-09-17T09:17:04Z, INFO] CPLEX version 12100000
2 |
3 | [2020-09-17T09:17:04Z, WARNING] Changed parameter CPX_PARAM_THREADS from 0 to 1
4 |
5 | [2020-09-17T09:17:04Z, INFO] Param[1,067] = 1
6 |
7 | [2020-09-17T09:17:04Z, INFO] Param[1,130] = UTF-8
8 |
9 | [2020-09-17T09:17:04Z, INFO] Param[1,132] = -1
10 |
11 | [2020-09-17T09:17:04Z, INFO] Version identifier: 12.10.0.0 | 2020-01-09 | 0d94640
12 |
13 | [2020-09-17T09:17:04Z, INFO] CPXPARAM_Threads 1
14 |
15 | [2020-09-17T09:17:04Z, INFO] CPXPARAM_Output_CloneLog -1
16 |
17 | [2020-09-17T09:17:04Z, INFO] CPXPARAM_Read_APIEncoding "UTF-8"
18 |
19 | [2020-09-17T09:17:04Z, INFO] Tried aggregator 1 time.
20 |
21 | [2020-09-17T09:17:04Z, INFO] LP Presolve eliminated 0 rows and 1 columns.
22 |
23 | [2020-09-17T09:17:04Z, INFO] Reduced LP has 7 rows, 15 columns, and 63 nonzeros.
24 |
25 | [2020-09-17T09:17:04Z, INFO] Presolve time = 0.00 sec. (0.01 ticks)
26 |
27 | [2020-09-17T09:17:04Z, INFO] Initializing dual steep norms . . .
28 |
29 | [2020-09-17T09:17:04Z, INFO]
30 |
31 | [2020-09-17T09:17:04Z, INFO] Iteration log . . .
32 |
33 | [2020-09-17T09:17:04Z, INFO] Iteration: 1 Dual objective = 1.860884
34 |
35 | [2020-09-17T09:17:04Z, INFO] There are no bound infeasibilities.
36 |
37 | [2020-09-17T09:17:04Z, INFO] There are no reduced-cost infeasibilities.
38 |
39 | [2020-09-17T09:17:04Z, INFO] Max. unscaled (scaled) Ax-b resid. = 1.13687e-13 (4.44089e-16)
40 |
41 | [2020-09-17T09:17:04Z, INFO] Max. unscaled (scaled) c-B'pi resid. = 1.17961e-16 (1.17961e-16)
42 |
43 | [2020-09-17T09:17:04Z, INFO] Max. unscaled (scaled) |x| = 41481.6 (10.1273)
44 |
45 | [2020-09-17T09:17:04Z, INFO] Max. unscaled (scaled) |pi| = 0.0266733 (0.321274)
46 |
47 | [2020-09-17T09:17:04Z, INFO] Max. unscaled (scaled) |red-cost| = 0.486119 (4.71716)
48 |
49 | [2020-09-17T09:17:04Z, INFO] Condition number of scaled basis = 4.5e+00
50 |
51 | [2020-09-17T09:17:04Z, INFO] optimal (1)
52 |
53 |
--------------------------------------------------------------------------------
/solution.json:
--------------------------------------------------------------------------------
1 | {"CPLEXSolution":{"version":"1.2","header":{"primalFeasible":true,"solutionTypeValue":1,"solutionMethodString":"dual","writeLevel":1,"objectiveValue":"2.6904091716962637","solutionTypeString":"basic","problemName":"diet.lp","solutionStatusString":"optimal","solutionStatusValue":1,"simplexIterations":3,"dualFeasible":true },"quality":{"maxPi":"0.026673346086024577","maxRedCost":"0.48611933803276086","epRHS":"9.9999999999999995e-07","maxDualResidual":"1.1796119636642288e-16","maxX":"41481.567457514182","maxPrimalResidual":"1.1368683772161603e-13","maxPrimalInfeas":"0","maxSlack":"0","kappa":"4.5217531406433773","epOpt":"9.9999999999999995e-07","maxDualInfeas":"0" },"linearConstraints":[{"dual":"0.0012549782286529975","slack":"0","name":"c1","index":0,"status":"LL" },{"dual":"0.0002625434401323112","slack":"0","name":"c2","index":1,"status":"LL" },{"dual":"-0","slack":"0","name":"c3","index":2,"status":"LL" },{"dual":"-0","slack":"0","name":"c4","index":3,"status":"LL" },{"dual":"0.026673346086024577","slack":"0","name":"c5","index":4,"status":"LL" },{"dual":"-0","slack":"0","name":"c6","index":5,"status":"LL" },{"dual":"-0","slack":"0","name":"c7","index":6,"status":"LL" } ],"variables":[{"reducedCost":"0.48611933803276086","name":"Roasted_Chicken","index":0,"value":"0","status":"LL" },{"reducedCost":"0","name":"Spaghetti_W__Sauce","index":1,"value":"2.1551724137931036","status":"BS" },{"reducedCost":"0.19865110785149795","name":"Tomato,Red,Ripe,Raw","index":2,"value":"0","status":"LL" },{"reducedCost":"0.036606720300071643","name":"Apple,Raw,W_Skin","index":3,"value":"0","status":"LL" },{"reducedCost":"0.29482251183368496","name":"Grapes","index":4,"value":"0","status":"LL" },{"reducedCost":"-0.069641568986619426","name":"Chocolate_Chip_Cookies","index":5,"value":"10","status":"UL" },{"reducedCost":"0","name":"Lowfat_Milk","index":6,"value":"1.8311671008899097","status":"BS" },{"reducedCost":"0.08547181116023489","name":"Raisin_Brn","index":7,"value":"0","status":"LL" },{"reducedCost":"0","name":"Hotdog","index":8,"value":"0.92969759913859251","status":"BS" },{"reducedCost":"0.0012549782286529975","name":"Rgc1","index":9,"value":"-500","status":"LL" },{"reducedCost":"0.0002625434401323112","name":"Rgc2","index":10,"value":"-800","status":"LL" },{"reducedCost":"0","name":"Rgc3","index":11,"value":"-18.721682260168105","status":"BS" },{"reducedCost":"0","name":"Rgc4","index":12,"value":"-41481.567457514182","status":"BS" },{"reducedCost":"0.026673346086024577","name":"Rgc5","index":13,"value":"-75","status":"LL" },{"reducedCost":"0","name":"Rgc6","index":14,"value":"-43.194236410955455","status":"BS" },{"reducedCost":"0","name":"Rgc7","index":15,"value":"-48.82627765864693","status":"BS" } ] }}
--------------------------------------------------------------------------------
/diet.lp:
--------------------------------------------------------------------------------
1 | \ This file has been generated by DOcplex
2 | \ ENCODING=ISO-8859-1
3 | \Problem name: diet
4 |
5 | Minimize
6 | obj: 0.840000000000 Roasted_Chicken + 0.780000000000 Spaghetti_W__Sauce
7 | + 0.270000000000 Tomato,Red,Ripe,Raw + 0.240000000000 Apple,Raw,W_Skin
8 | + 0.320000000000 Grapes + 0.030000000000 Chocolate_Chip_Cookies
9 | + 0.230000000000 Lowfat_Milk + 0.340000000000 Raisin_Brn
10 | + 0.310000000000 Hotdog
11 | Subject To
12 | c1: 277.400000000000 Roasted_Chicken + 358.200000000000 Spaghetti_W__Sauce
13 | + 25.800000000000 Tomato,Red,Ripe,Raw + 81.400000000000 Apple,Raw,W_Skin
14 | + 15.100000000000 Grapes + 78.100000000000 Chocolate_Chip_Cookies
15 | + 121.200000000000 Lowfat_Milk + 115.100000000000 Raisin_Brn
16 | + 242.100000000000 Hotdog- Rgc1 = 2500
17 | c2: 21.900000000000 Roasted_Chicken + 80.200000000000 Spaghetti_W__Sauce
18 | + 6.200000000000 Tomato,Red,Ripe,Raw + 9.700000000000 Apple,Raw,W_Skin
19 | + 3.400000000000 Grapes + 6.200000000000 Chocolate_Chip_Cookies
20 | + 296.700000000000 Lowfat_Milk + 12.900000000000 Raisin_Brn
21 | + 23.500000000000 Hotdog- Rgc2 = 1600
22 | c3: 1.800000000000 Roasted_Chicken + 2.300000000000 Spaghetti_W__Sauce
23 | + 0.600000000000 Tomato,Red,Ripe,Raw + 0.200000000000 Apple,Raw,W_Skin
24 | + 0.100000000000 Grapes + 0.400000000000 Chocolate_Chip_Cookies
25 | + 0.100000000000 Lowfat_Milk + 16.800000000000 Raisin_Brn
26 | + 2.300000000000 Hotdog- Rgc3 = 30
27 | c4: 77.400000000000 Roasted_Chicken + 3055.200000000000 Spaghetti_W__Sauce
28 | + 766.300000000000 Tomato,Red,Ripe,Raw + 73.100000000000 Apple,Raw,W_Skin
29 | + 24 Grapes + 101.800000000000 Chocolate_Chip_Cookies
30 | + 500.200000000000 Lowfat_Milk + 1250.200000000000 Raisin_Brn- Rgc4 = 50000
31 | c5: 11.600000000000 Spaghetti_W__Sauce + 1.400000000000 Tomato,Red,Ripe,Raw
32 | + 3.700000000000 Apple,Raw,W_Skin + 0.200000000000 Grapes + 4 Raisin_Brn-
33 | Rgc5 = 100
34 | c6: 58.300000000000 Spaghetti_W__Sauce + 5.700000000000 Tomato,Red,Ripe,Raw
35 | + 21 Apple,Raw,W_Skin + 4.100000000000 Grapes
36 | + 9.300000000000 Chocolate_Chip_Cookies + 11.700000000000 Lowfat_Milk
37 | + 27.900000000000 Raisin_Brn + 18 Hotdog- Rgc6 = 300
38 | c7: 42.200000000000 Roasted_Chicken + 8.200000000000 Spaghetti_W__Sauce
39 | + Tomato,Red,Ripe,Raw + 0.300000000000 Apple,Raw,W_Skin
40 | + 0.200000000000 Grapes + 0.900000000000 Chocolate_Chip_Cookies
41 | + 8.100000000000 Lowfat_Milk + 4 Raisin_Brn + 10.400000000000 Hotdog- Rgc7
42 | = 100
43 |
44 | Bounds
45 | Roasted_Chicken <= 10
46 | Spaghetti_W__Sauce <= 10
47 | Tomato,Red,Ripe,Raw <= 10
48 | Apple,Raw,W_Skin <= 10
49 | Grapes <= 10
50 | Chocolate_Chip_Cookies <= 10
51 | Lowfat_Milk <= 10
52 | Raisin_Brn <= 10
53 | Hotdog <= 10
54 | -500 <= Rgc1 <= 0
55 | -800 <= Rgc2 <= 0
56 | -20 <= Rgc3 <= 0
57 | -45000 <= Rgc4 <= 0
58 | -75 <= Rgc5 <= 0
59 | -300 <= Rgc6 <= 0
60 | -50 <= Rgc7 <= 0
61 | End
62 |
--------------------------------------------------------------------------------
/cplexrunonwml.py:
--------------------------------------------------------------------------------
1 | import sys, getopt
2 |
3 | try:
4 | sys.modules['sklearn.externals.joblib'] = __import__('joblib')
5 | from watson_machine_learning_client import WatsonMachineLearningAPIClient
6 | except ImportError:
7 | from watson_machine_learning_client import WatsonMachineLearningAPIClient
8 |
9 |
10 | # THIS IS THE USER CREDENTIALS
11 | wml_credentials = {
12 | "apikey": "xxxxxxxxxxxxxxxxxxxxxxxxx",
13 | "instance_id": "xxxxxxxxxxxxxxxxxxxxxxxxx",
14 | "url": "https://us-south.ml.cloud.ibm.com",
15 | }
16 | # END OF THE USER CREDENTIALS
17 |
18 | def main(argv):
19 | cplex_file = "diet.lp"
20 | try:
21 | opts, args = getopt.getopt(argv,"hf:",["ffile="])
22 | except getopt.GetoptError:
23 | print('cplexrunonwml.py -f ')
24 | sys.exit(2)
25 | for opt, arg in opts:
26 | if opt == '-h':
27 | print('cplexrunonwml.py -f ')
28 | sys.exit()
29 | elif opt in ("-f", "--ffile"):
30 | cplex_file = arg
31 | print('CPLEX file is', cplex_file)
32 |
33 | basename = cplex_file.split('.')[0]
34 | model_name = basename + "_model"
35 | deployment_name = basename + "_deployment"
36 |
37 | print("Creating WML Client")
38 | client = WatsonMachineLearningAPIClient(wml_credentials)
39 |
40 | print("Getting deployment")
41 | deployments = client.deployments.get_details()
42 |
43 | deployment_uid = None
44 | for res in deployments['resources']:
45 | if res['entity']['name'] == deployment_name:
46 | deployment_uid = res['metadata']['guid']
47 | print("Found deployment", deployment_uid)
48 | break
49 |
50 | if deployment_uid == None:
51 | print("Creating model")
52 | import tarfile
53 |
54 |
55 | def reset(tarinfo):
56 | tarinfo.uid = tarinfo.gid = 0
57 | tarinfo.uname = tarinfo.gname = "root"
58 | return tarinfo
59 |
60 |
61 | tar = tarfile.open("model.tar.gz", "w:gz")
62 | tar.add(cplex_file, arcname=cplex_file, filter=reset)
63 | tar.close()
64 |
65 | print("Storing model")
66 | model_metadata = {
67 | client.repository.ModelMetaNames.NAME: model_name,
68 | client.repository.ModelMetaNames.DESCRIPTION: model_name,
69 | client.repository.ModelMetaNames.TYPE: "do-cplex_12.10",
70 | client.repository.ModelMetaNames.RUNTIME_UID: "do_12.10"
71 | }
72 |
73 | model_details = client.repository.store_model(model='./model.tar.gz', meta_props=model_metadata)
74 |
75 | model_uid = client.repository.get_model_uid(model_details)
76 |
77 | print(model_uid)
78 |
79 | print("Creating deployment")
80 | deployment_props = {
81 | client.deployments.ConfigurationMetaNames.NAME: deployment_name,
82 | client.deployments.ConfigurationMetaNames.DESCRIPTION: deployment_name,
83 | client.deployments.ConfigurationMetaNames.BATCH: {},
84 | client.deployments.ConfigurationMetaNames.COMPUTE: {'name': 'S', 'nodes': 1}
85 | }
86 |
87 | deployment_details = client.deployments.create(model_uid, meta_props=deployment_props)
88 |
89 | deployment_uid = client.deployments.get_uid(deployment_details)
90 |
91 | print('deployment_id:', deployment_uid)
92 |
93 | print("Creating job")
94 | import pandas as pd
95 |
96 | with open(cplex_file, 'r') as file:
97 | model = file.read();
98 | import base64
99 |
100 | model = model.encode("UTF-8")
101 | model = base64.b64encode(model)
102 | model = model.decode("UTF-8")
103 | df_model = pd.DataFrame(columns=['___TEXT___'], data=[[model]])
104 | solve_payload = {
105 | client.deployments.DecisionOptimizationMetaNames.SOLVE_PARAMETERS: {
106 | 'oaas.logAttachmentName': 'log.txt',
107 | 'oaas.logTailEnabled': 'true',
108 | 'oaas.includeInputData': 'false',
109 | 'oaas.resultsFormat': 'JSON'
110 | },
111 | client.deployments.DecisionOptimizationMetaNames.INPUT_DATA: [
112 | {
113 | "id": cplex_file,
114 | "values": df_model
115 | }
116 | ],
117 | client.deployments.DecisionOptimizationMetaNames.OUTPUT_DATA: [
118 | {
119 | "id": ".*\.json"
120 | },
121 | {
122 | "id": ".*\.txt"
123 | }
124 | ]
125 | }
126 |
127 | job_details = client.deployments.create_job(deployment_uid, solve_payload)
128 | job_uid = client.deployments.get_job_uid(job_details)
129 |
130 | print('job_id', job_uid)
131 |
132 | from time import sleep
133 |
134 | while job_details['entity']['decision_optimization']['status']['state'] not in ['completed', 'failed', 'canceled']:
135 | print(job_details['entity']['decision_optimization']['status']['state'] + '...')
136 | sleep(5)
137 | job_details = client.deployments.get_job_details(job_uid)
138 |
139 | print(job_details['entity']['decision_optimization']['status']['state'])
140 |
141 | for output_data in job_details['entity']['decision_optimization']['output_data']:
142 | if output_data['id'].endswith('csv'):
143 | print('Solution table:' + output_data['id'])
144 | solution = pd.DataFrame(output_data['values'],
145 | columns=output_data['fields'])
146 | solution.head()
147 | else:
148 | print(output_data['id'])
149 | output = output_data['values'][0][0]
150 | output = output.encode("UTF-8")
151 | output = base64.b64decode(output)
152 | output = output.decode("UTF-8")
153 | print(output)
154 | with open(output_data['id'], 'wt') as file:
155 | file.write(output)
156 |
157 | # print ("Deleting deployment")
158 | # client.deployments.delete(deployment_uid)
159 |
160 |
161 | if __name__ == '__main__':
162 | main(sys.argv[1:])
163 |
--------------------------------------------------------------------------------
/cplexrunonwmlv2.py:
--------------------------------------------------------------------------------
1 | import sys, getopt
2 |
3 | try:
4 | sys.modules['sklearn.externals.joblib'] = __import__('joblib')
5 | from ibm_watson_machine_learning import APIClient
6 | except ImportError:
7 | from ibm_watson_machine_learning import APIClient
8 |
9 |
10 | # THIS IS THE USER CREDENTIALS
11 | wml_credentials = {
12 | "apikey": "xxxxxxxxxxxxxxxxxxxxxxxxx",
13 | "url": "https://us-south.ml.cloud.ibm.com"
14 | }
15 |
16 |
17 | import base64
18 | def getfileasdata(filename):
19 | with open(filename, 'r') as file:
20 | data = file.read();
21 |
22 | data = data.encode("UTF-8")
23 | data = base64.b64encode(data)
24 | data = data.decode("UTF-8")
25 |
26 | return data
27 |
28 | def main(argv):
29 | cplex_file = "diet.lp"
30 | try:
31 | opts, args = getopt.getopt(argv,"hf:",["ffile="])
32 | except getopt.GetoptError:
33 | print('cplexrunonwml.py -f ')
34 | sys.exit(2)
35 | for opt, arg in opts:
36 | if opt == '-h':
37 | print('cplexrunonwml.py -f ')
38 | sys.exit()
39 | elif opt in ("-f", "--ffile"):
40 | cplex_file = arg
41 | print('CPLEX file is', cplex_file)
42 |
43 | basename = cplex_file.split('.')[0]
44 | model_name = basename + "_model"
45 | deployment_name = basename + "_deployment"
46 | space_name = basename + "_space"
47 |
48 | print("Creating WML Client")
49 | client = APIClient(wml_credentials)
50 |
51 |
52 | def guid_from_space_name(client, name):
53 | space = client.spaces.get_details()
54 | for item in space['resources']:
55 | if item['entity']["name"] == name:
56 | return item['metadata']['id']
57 | return None
58 |
59 | space_id = guid_from_space_name(client, space_name)
60 |
61 | if space_id == None:
62 | print("Creating space")
63 | cos_resource_crn = 'xxxxxxxxxxxxxxxxxxxxxxxxx'
64 | instance_crn = 'xxxxxxxxxxxxxxxxxxxxxxxxx'
65 |
66 | metadata = {
67 | client.spaces.ConfigurationMetaNames.NAME: space_name,
68 | client.spaces.ConfigurationMetaNames.DESCRIPTION: space_name + ' description',
69 | client.spaces.ConfigurationMetaNames.STORAGE: {
70 | "type": "bmcos_object_storage",
71 | "resource_crn": cos_resource_crn
72 | },
73 | client.spaces.ConfigurationMetaNames.COMPUTE: {
74 | "name": "existing_instance_id",
75 | "crn": instance_crn
76 | }
77 | }
78 | space = client.spaces.store(meta_props=metadata)
79 | space_id = client.spaces.get_id(space)
80 |
81 | print("space_id:", space_id)
82 |
83 | client.set.default_space(space_id)
84 |
85 | print("Getting deployment")
86 | deployments = client.deployments.get_details()
87 |
88 | deployment_uid = None
89 | for res in deployments['resources']:
90 | if res['entity']['name'] == deployment_name:
91 | deployment_uid = res['metadata']['id']
92 | print("Found deployment", deployment_uid)
93 | break
94 |
95 | if deployment_uid == None:
96 | print("Creating model")
97 | import tarfile
98 |
99 |
100 | def reset(tarinfo):
101 | tarinfo.uid = tarinfo.gid = 0
102 | tarinfo.uname = tarinfo.gname = "root"
103 | return tarinfo
104 |
105 |
106 | tar = tarfile.open("model.tar.gz", "w:gz")
107 | tar.add(cplex_file, arcname=cplex_file, filter=reset)
108 | tar.close()
109 |
110 | print("Storing model")
111 | model_metadata = {
112 | client.repository.ModelMetaNames.NAME: model_name,
113 | client.repository.ModelMetaNames.DESCRIPTION: model_name,
114 | client.repository.ModelMetaNames.TYPE: "do-cplex_12.10",
115 | client.repository.ModelMetaNames.SOFTWARE_SPEC_UID: client.software_specifications.get_uid_by_name(
116 | "do_12.10")
117 | }
118 |
119 | model_details = client.repository.store_model(model='./model.tar.gz', meta_props=model_metadata)
120 |
121 | model_uid = client.repository.get_model_uid(model_details)
122 |
123 | print(model_uid)
124 |
125 | print("Creating deployment")
126 | deployment_props = {
127 | client.deployments.ConfigurationMetaNames.NAME: deployment_name,
128 | client.deployments.ConfigurationMetaNames.DESCRIPTION: deployment_name,
129 | client.deployments.ConfigurationMetaNames.BATCH: {},
130 | client.deployments.ConfigurationMetaNames.HARDWARE_SPEC: {'name': 'S', 'nodes': 1}
131 | }
132 |
133 | deployment_details = client.deployments.create(model_uid, meta_props=deployment_props)
134 |
135 | deployment_uid = client.deployments.get_uid(deployment_details)
136 |
137 | print('deployment_id:', deployment_uid)
138 |
139 | print("Creating job")
140 | import pandas as pd
141 |
142 | solve_payload = {
143 | client.deployments.DecisionOptimizationMetaNames.SOLVE_PARAMETERS: {
144 | 'oaas.logAttachmentName': 'log.txt',
145 | 'oaas.logTailEnabled': 'true',
146 | 'oaas.includeInputData': 'false',
147 | 'oaas.resultsFormat': 'JSON'
148 | },
149 | client.deployments.DecisionOptimizationMetaNames.INPUT_DATA: [
150 | {
151 | "id": cplex_file,
152 | "content": getfileasdata(cplex_file)
153 | }
154 | ],
155 | client.deployments.DecisionOptimizationMetaNames.OUTPUT_DATA: [
156 | {
157 | "id": ".*\.json"
158 | },
159 | {
160 | "id": ".*\.txt"
161 | }
162 | ]
163 | }
164 |
165 | job_details = client.deployments.create_job(deployment_uid, solve_payload)
166 | job_uid = client.deployments.get_job_uid(job_details)
167 |
168 | print('job_id', job_uid)
169 |
170 | from time import sleep
171 |
172 | while job_details['entity']['decision_optimization']['status']['state'] not in ['completed', 'failed', 'canceled']:
173 | print(job_details['entity']['decision_optimization']['status']['state'] + '...')
174 | sleep(5)
175 | job_details = client.deployments.get_job_details(job_uid)
176 |
177 | print(job_details['entity']['decision_optimization']['status']['state'])
178 |
179 | for output_data in job_details['entity']['decision_optimization']['output_data']:
180 | if output_data['id'].endswith('csv'):
181 | print('Solution table:' + output_data['id'])
182 | solution = pd.DataFrame(output_data['values'],
183 | columns=output_data['fields'])
184 | solution.head()
185 | else:
186 | print(output_data['id'])
187 | if "values" in output_data:
188 | output = output_data['values'][0][0]
189 | else:
190 | if "content" in output_data:
191 | output = output_data['content']
192 | output = output.encode("UTF-8")
193 | output = base64.b64decode(output)
194 | output = output.decode("UTF-8")
195 | print(output)
196 | with open(output_data['id'], 'wt') as file:
197 | file.write(output)
198 |
199 | # print ("Deleting deployment")
200 | # client.deployments.delete(deployment_uid)
201 |
202 |
203 | if __name__ == '__main__':
204 | main(sys.argv[1:])
205 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------