Page MenuHomec4science

gurobi.py
No OneTemporary

File Metadata

Created
Tue, Apr 30, 13:49

gurobi.py

# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np
import gurobipy as gp
from gurobipy import GRB
#This function places the molecule M optimally within the target T.
def OptimalPlacement(M,T):
try:
#Dimemsion of the Molecule and Target
m = len(M)
n = len(T)
print("Sizes of Matrices to match: ", m, n, print("\n"))
# Create a new model
Z = gp.Model("QP")
#Create Variables
x = Z.addVars(m, n, name='X', vtype=GRB.BINARY)
Z.addConstrs(x.sum(i, '*') == 1 for i in range(m))
Z.addConstrs(x.sum('*',j) <= 1 for j in range(n))
# Set objective by building a long expression
expr = 2*x[1,1] * x[1,2]
expr.clear()
for i in range(m):
for j in range(m):
for k in range(n):
for l in range(n):
expr.add(x[i,k] * x[j,l], (T[k,l]-M[i,j])**2)
Z.setObjective(expr, GRB.MINIMIZE)
# Optimize model
print("\n----------------\n Optimisation... \n----------------\n")
Z.optimize()
print("\n------------------\n Best match... \n------------------\n")
matched_target = []
for v in Z.getVars():
if v.x == 1:
i,j = v.varName.split("[")[-1].split("]")[0].split(",")
j = int(j)
matched_target.append(j)
print("Indices of the target:")
print(matched_target)
# print("\n------------------\n Best match... \n------------------\n")
# Z.printAttr('X')
# print(Z.getObjective() )
return matched_target
except gp.GurobiError as e:
print('Error code ' + str(e.errno) + ': ' + str(e))
except AttributeError:
print('Encountered an attribute error')
if __name__ == "__main__":
data = np.load("data.npz", allow_pickle=True)
# temporarily commented out the line below
OptimalPlacement(data['database_CMs'][2],data['target_CMs'][0])
# L = [2,8,7,1,4,9,10]
# T = data['target_CMs'][0][L][:,L]
# print("\n T = ", T)
# T = T - data['database_CMs'][2]
# print ("\n Error: ", np.sum(T ** 2))
#print("\n Molecule:", data['database_CMs'][2])
#print("\n Target:",data['target_CMs'][0])

Event Timeline