I am having a bit of troulbe converting my python optimization script into matlab. I am at the point where I am genuinly considering to pay someone if they can convert it. Please help!
import numpy as np
import math
import time
import gurobipy as gp
from scipy.stats import multivariate_normal as mvn
import scipy.io as sio
import mat73
from gurobipy import GRB
try:
# load adjscent matrix:
data1 = sio.loadmat(r"C:UserschadiDownloadsPath_OPTODs_Time.mat")
data = mat73.loadmat(r"C:UserschadiDownloadsPath_OPTAug_adj0.mat")
adj_mat = data['aug_adj0']
cost_mat = data['aug_adj0'] * 2
# problem parameters
# T = 20 # time span
T = int(data1['ExpTime'].astype(int))
# terminal = 1 # node index for terminal
terminal_list = data1['t0'] - 1
terminal = terminal_list[0][0]
# allow loop at terminal
adj_mat[terminal][terminal] = 1
cost_mat[terminal][terminal] = 0
# start_idx = [4,6,8,10,14,5]
start_idx_list = data1['s'] - 1
start_idx = start_idx_list[0]
n_aircraft = len(start_idx)
n_nodes = len(adj_mat)
nodes = set() #set of nodes
for i in range(n_nodes):
nodes.add(i)
conflict_pairs = []
conflict_nodes = set() # set of conflict free nodes
for i in range(len(conflict_pairs)):
conflict_nodes.add(conflict_pairs[i][0])
conflict_nodes.add(conflict_pairs[i][1])
conflict_free_nodes = nodes.difference(conflict_nodes)
#convert graph to link list representation
link_list = []
link_cost = []
for i in range(n_nodes):
for j in range(n_nodes):
if adj_mat[i][j] > 0:
if i == j and i != terminal:
adj_mat[i][j] = 0;
link_list.append((i,j))
link_cost.append(cost_mat[i][j])
n_links = len(link_list)
n_conflicts = len(conflict_pairs)
n_conf_nodes = len(conflict_nodes)
#create adj-list representation of graph
adj_out_list = {}
adj_in_list = {}
for node in nodes:
out_idx = []
in_idx = []
for j in range(n_links):
if node == link_list[j][0]:
out_idx.append(j)
if node == link_list[j][1]:
in_idx.append(j)
adj_out_list[node] = out_idx
adj_in_list[node] = in_idx
#construct expansion network for one time step
link_exp1_conf = [] #pair are (node_index,conflict_index)
link_exp1_free = [] #pair are (node_index,node_index)
for i in range(len(conflict_pairs)):
link_exp1_conf.append((conflict_pairs[i][0],i))
link_exp1_conf.append((conflict_pairs[i][1],i))
for i in conflict_free_nodes:
link_exp1_free.append((i,i))
n_virtual_conf = len(link_exp1_conf) #number of virtual link for conflict
n_virtual_free = len(link_exp1_free) #number of virtual link for free nodes
exp_cost = [];
for i in range(T):
exp_cost.append(link_cost)
#<!- Down to here, praise ChatGPT ->
#create opt model
m = gp.Model('min_cost_form')
Ub = np.ones((T,n_links))
Ub[:,adj_in_list[terminal]] = n_aircraft # In MATLAB, this is Ub1
#CONTINUOUS
link_flow = m.addMVar((T,n_links),vtype = GRB.INTEGER, lb = np.zeros((T,n_links)), ub = Ub, obj = exp_cost) # j
Ub = np.ones((T,n_nodes))
Ub[:,terminal] = n_aircraft # In MATLAB, this is Ub2
node_flow = m.addMVar((T,n_nodes),vtype = GRB.INTEGER, lb = np.zeros((T,n_nodes)), ub = Ub)
#flow conservation # starting Point Constrain
for node in nodes:
if node in start_idx:
m.addConstr(node_flow[0,node] == 1)
else:
m.addConstr(node_flow[0,node] == 0)
epsilon = 1e-6 # Small positive value
M = 1e4 # Big M value
m.addConstr(link_flow[T-1,adj_in_list[terminal]].sum() == n_aircraft) # Arrival Constraint (is it working??????
for t in range(T): # for t=0:T-1
#final layer for physical_flow
for node in nodes:
if node in conflict_free_nodes:
m.addConstr(node_flow[t,node] == link_flow[t,adj_out_list[node]].sum()) # conservation Contrain
#time step transitition
if t<T-1:
m.addConstr(link_flow[t,adj_in_list[node]].sum() == node_flow[t+1,node]) # route conservation constrain
m.update()
m.optimize()
flow_res = link_flow.getAttr('x')
path_idx = np.transpose((np.nonzero(flow_res)))
path = []
for l in path_idx:
path.append((l[0],link_list[l[1]])) # Double matrix/array with [[item 1, item 2], ...]
print("Runtime:", m.Runtime)
# write result to mat
test_dict = {'result':np.asarray(path, dtype="object")} # Defining temporary variable to save data
# print(test_dict)
sio.savemat('Path_result.mat',mdict = test_dict) # Saving data onto the machine
except gp.GurobiError as e:
print('Error code ' + str(e.errno) + ": " + str(e))
except AttributeError as e:
print('Encountered an attribute error'+ ": " + str(e))
I tried to use what little I know about python and Matlab, but I am new to programming. I have tried these two scripts, the first, I wrote my self, the second is ChatGPT
import gurobi.*;
%% Indexing
% Load adjacent matrix:
data1 = load('C:UserschadiDownloadsPath_OPTODs_Time.mat');
data = load('C:UserschadiDownloadsPath_OPTAug_adj0.mat');
adj_mat = data.aug_adj0;
cost_mat = data.aug_adj0 * 2;
% Problem parameters
T = int32(data1.ExpTime);
terminal_list = data1.t0 - 1;
terminal = terminal_list(1, 1);
% allow loop at terminal
adj_mat(terminal+1, terminal+1) = 1;
cost_mat(terminal+1, terminal+1) = 0;
% start_idx = [4, 6, 8, 10, 14, 5]
start_idx_list = data1.s - 1;
n_aircraft = size(start_idx_list, 2);
n_nodes = length(adj_mat);
% Set of nodes
nodes = 0:n_nodes;
conflict_pairs = [];
conflict_nodes = [];
conflict_free_nodes = nodes;
% Convert graph to link list rep
link_list = []; % Initialize an empty array for link_list
link_cost = []; % Initialize an empty array for link_cost
for i = 1:n_nodes
for j = 1:n_nodes
if adj_mat(i, j) > 0
if i == j && i ~= terminal % Adjusting for MATLAB's 1-based indexing
adj_mat(i, j) = 0;
end
link_list = [link_list; i-1, j-1]; % Append to link_list (adjusting for 0-based indexing)
link_cost = [link_cost; cost_mat(i, j)]; % Append to link_cost
end
end
end
n_links = length(link_list);
n_conflicts = length(conflict_pairs);
n_conf_nodes = length(conflict_nodes);
% Initialize empty containers.Map objects for adj_out_list and adj_in_list
adj_out_list = containers.Map('KeyType', 'double', 'ValueType', 'any');
adj_in_list = containers.Map('KeyType', 'double', 'ValueType', 'any');
% Iterate through each node in the nodes array
for node = nodes
out_idx = []; % Initialize an empty array for outgoing links
in_idx = []; % Initialize an empty array for incoming links
% Iterate through each link in link_list
for j = 1:n_links
if node == link_list(j, 1) % Check for outgoing links
out_idx = [out_idx, j]; % Append the index to out_idx
end
if node == link_list(j, 2) % Check for incoming links
in_idx = [in_idx, j]; % Append the index to in_idx
end
end
% Assign the arrays to the containers.Map objects
adj_out_list(node) = out_idx-1;
adj_in_list(node) = in_idx-1;
end
% construct expansion network for one time step
link_exp1_conf = []; %pair are (node_index,conflict_index)
link_exp1_free = []; %pair are (node_index,node_index)
for i=1:length(conflict_free_nodes)-1
link_exp1_free(i,1)=i-1;
link_exp1_free(i,2)=i-1;
end
n_virtual_conf = length(link_exp1_conf);
n_virtual_free = length(link_exp1_free);
link_exp2_conf = []; %pair are (node_index,conflict_index)
link_exp2_free = []; %pair are (node_index,node_index)
for i=1:length(conflict_free_nodes)-1
link_exp1_free(i,1)=i-1;
link_exp1_free(i,2)=i-1;
end
exp_cost = [];
for i=1:T
exp_cost(:, i) = link_cost; % Each column of exp_cost is equivalent to link_cost
end
%% Gurobi part
% Upper bound
Ub = ones(T, n_links);
Ub1 = Ub; Ub2 = Ub;
Ub1(:, 1) = n_aircraft; Ub1(:,end) = n_aircraft; % Ub1 has both the first and last columns of `n_aircraft`
Ub2(:, end) = n_aircraft; % Ub2 has only the last column of `n_aircraft`
%% Create a first Gurobi model
model = struct();
% Define the variable types for all entries as integer
vtype = repmat('I', T * n_links, 1);
% Define the lower bounds as zeros
lb = zeros(T, n_links);
% Upper bounds are given by the variable Ub
ub = Ub1;
% Objective coefficients are given by exp_cost
obj = exp_cost(:); % Ensure exp_cost is a column vector for Gurobi
x=ones(1,1188);
% Add variables to the model
model.A = sparse(x);
model.obj = obj;
model.modelsense = 'min';
model.vtype = vtype;
model.lb = lb(:); % Flatten to a column vector
model.ub = ub(:); % Flatten to a column vector
% Solve the model
result = gurobi(model);
% Reshape the result to match the original T x n_links dimensions
link_flow = reshape(result.x, T, n_links);
%% create second Gurobi model
% Upper bounds are given by the variable Ub
ub = Ub2;
% Add variables to the model
model.ub = ub(:); % Flatten to a column vector
% Solve the model
result = gurobi(model);
% Reshape the result to match the original T x n_links dimensions
node_flow = reshape(result.x, T, n_links);
% Display the results
% disp('Optimal values of decision variables (node_flow):');
% disp(node_flow);
% disp('Objective function value:');
% disp(result.objval);
%flow conservation # starting Point Constrain
% Define decision variables (node_flow in this case)
% node_flow = optimvar('node_flow', 1, n_nodes, 'Type', 'integer', 'LowerBound', 0, 'UpperBound', 1);
% Add decision variables to the problem
model.Objective = []; % Define objective function if needed
model.DecisionVariables.node_flow = node_flow;
% Loop over nodes and add constraints based on membership in start_idx
for node = 1:n_nodes
if ismember(node, start_idx_list)
model.Constraints.cons(node) = node_flow(node) == 1;
else
model.Constraints.cons(node) = node_flow(node) == 0;
end
end
% Assuming adj_in_list is a containers.Map initialized appropriately
% Assuming adj_in_list is a containers.Map initialized appropriately
epsilon = 1e-6; % Small positive value
M = 1e4; % Big M value
% Ensure adj_in_list is a containers.Map and terminal is a valid key
if isKey(adj_in_list, terminal)
terminal_adj_in_list = adj_in_list(terminal); % Accessing value from containers.Map
terminal_adj_in_list = terminal_adj_in_list + 1;
% Sum of link_flow at time step T for nodes in adj_in_list(terminal)
sum_link_flow = sum(link_flow(T, terminal_adj_in_list)); % Assuming T is correctly defined
else
error('Terminal node not found in adj_in_list.');
end
% Define the constraint
constraint_expr = sum_link_flow == n_aircraft;
constraint_expr = zeros(1, 1188);
% Add the constraint to the optimization model
model.A = [model.A; constraint_expr]; % Adjust based on your solver's method to add constraints
model.rhs = n_aircraft; % Add the RHS value
model.sense = '='; % Define the sense of the constraint
% Assuming T, nodes, conflict_free_nodes, adj_out_list, adj_in_list,
% node_flow, link_flow, link_list, model are defined
% Assuming variables T, n_links, n_nodes, nodes, conflict_free_nodes,
% adj_out_list, adj_in_list, node_flow, link_flow, link_list, model are defined
% Initialize the Gurobi model fields
model.A = sparse([]);
model.rhs = [];
model.sense = '';
% Initialize the constraint matrix dimensions
for t = 0:(T-1) % for t=0:T-1
% final layer for physical_flow
for node = nodes
if ismember(node, conflict_free_nodes)
% conservation Constraint
out_list = adj_out_list(node); % 1-based indexing
Aeq = sparse(1, T * n_links); % Initialize sparse row
for out_idx = out_list
Aeq((t * n_links) + out_idx + 1) = 1; % +1 for 1-based indexing
end
Aeq((t * n_nodes) + node + 1) = -1;
model.A = [model.A; Aeq];
model.rhs = [model.rhs; 0];
model.sense = [model.sense; '='];
end
% time step transition
if t < (T-1)
% route conservation constraint
in_list = adj_in_list(node); % 1-based indexing
Aeq = sparse(1, T * n_links); % Initialize sparse row
for in_idx = in_list
Aeq((t * n_links) + in_idx + 1) = 1; % +1 for 1-based indexing
end
Aeq(((t + 1) * n_nodes) + node + 1) = -1;
model.A = [model.A; Aeq];
model.rhs = [model.rhs; 0];
model.sense = [model.sense; '='];
end
end
end
% Define other model fields (objective, etc.) as required
% Optimize the model
result = gurobi(model);
% Extract the solution
flow_res = result.x;
% Reshape flow_res to a T x n_links matrix
flow_res = reshape(flow_res, [T, n_links]);
% Find non-zero indices
[path_idx_row, path_idx_col] = find(flow_res);
% Initialize the path cell array
path = cell(length(path_idx_row), 2);
for idx = 1:length(path_idx_row)
path{idx, 1} = path_idx_row(idx) - 1; % Convert to 0-based indexing
path{idx, 2} = link_list{path_idx_col(idx)};
end
% Display runtime
disp(['Runtime: ', num2str(result.runtime)]);
% Write result to MAT file
test_dict.result = path;
save('Path_result.mat', '-struct', 'test_dict');
import gurobi.*;
try
% Load adjacent matrix
data1 = load('C:UserschadiDownloadsPath_OPTODs_Time.mat');
data = load('C:UserschadiDownloadsPath_OPTAug_adj0.mat', '-mat');
adj_mat = data.aug_adj0;
cost_mat = data.aug_adj0 * 2;
% Problem parameters
T = double(data1.ExpTime); % Convert to double
terminal_list = double(data1.t0 - 1); % Convert to double
terminal = terminal_list(1);
% Allow loop at terminal
adj_mat(terminal+1, terminal+1) = 1;
cost_mat(terminal+1, terminal+1) = 0;
start_idx_list = double(data1.s - 1); % Convert to double
start_idx = start_idx_list(1, :);
n_aircraft = length(start_idx);
n_nodes = length(adj_mat);
nodes = double(0:n_nodes-1); % Convert to double
conflict_pairs = [];
conflict_nodes = [];
for i = 1:length(conflict_pairs)
conflict_nodes = [conflict_nodes, conflict_pairs(i, :)];
end
conflict_free_nodes = setdiff(nodes, conflict_nodes);
% Convert graph to link list representation
link_list = [];
link_cost = [];
for i = 1:n_nodes
for j = 1:n_nodes
if adj_mat(i, j) > 0
if i == j && i ~= terminal+1
adj_mat(i, j) = 0;
else
link_list = [link_list; [i-1, j-1]];
link_cost = [link_cost; cost_mat(i, j)];
end
end
end
end
n_links = size(link_list, 1);
n_conflicts = size(conflict_pairs, 1);
n_conf_nodes = length(conflict_nodes);
% Create adj-list representation of graph
adj_out_list = containers.Map('KeyType', 'int32', 'ValueType', 'any');
adj_in_list = containers.Map('KeyType', 'int32', 'ValueType', 'any');
for node = nodes
out_idx = find(link_list(:, 1) == node);
in_idx = find(link_list(:, 2) == node);
adj_out_list(node) = out_idx;
adj_in_list(node) = in_idx;
end
% Construct expansion network for one time step
link_exp1_conf = [];
link_exp1_free = [];
for i = 1:size(conflict_pairs, 1)
link_exp1_conf = [link_exp1_conf; [conflict_pairs(i, 1), i-1]];
link_exp1_conf = [link_exp1_conf; [conflict_pairs(i, 2), i-1]];
end
for i = conflict_free_nodes
link_exp1_free = [link_exp1_free; [i, i]];
end
n_virtual_conf = size(link_exp1_conf, 1);
n_virtual_free = size(link_exp1_free, 1);
exp_cost = repmat(link_cost', T, 1);
% Create opt model
model.modelsense = 'min';
Ub = ones(T, n_links);
Ub(:, adj_in_list(terminal)) = n_aircraft;
% Add variables
model.lb = zeros(T * n_links, 1);
model.ub = Ub(:);
model.vtype = repmat('I', T * n_links, 1);
model.obj = exp_cost(:);
Ub2 = ones(T, n_nodes);
Ub2(:, terminal+1) = n_aircraft;
model.lb = [model.lb; zeros(T * n_nodes, 1)];
model.ub = [model.ub; Ub2(:)];
model.vtype = [model.vtype; repmat('I', T * n_nodes, 1)];
model.obj = [model.obj; zeros(T * n_nodes, 1)];
% Initialize A, rhs, and sense fields
model.A = sparse([]);
model.rhs = [];
model.sense = [];
% Flow conservation and starting point constraint
A_start = sparse(n_nodes, T * (n_links + n_nodes));
b_start = zeros(n_nodes, 1);
for node = nodes
if ismember(node, start_idx)
A_start(node+1, T*n_links + node + 1) = 1;
b_start(node+1) = 1;
else
A_start(node+1, T*n_links + node + 1) = 1;
end
end
model.A = [model.A; A_start];
model.rhs = [model.rhs; b_start];
model.sense = [model.sense; repmat('=', n_nodes, 1)];
% Arrival constraint
A_arrival = sparse(1, T * (n_links + n_nodes));
A_arrival(1, (T-1)*n_links + adj_in_list(terminal)) = 1;
model.A = [model.A; A_arrival];
model.rhs = [model.rhs; n_aircraft];
model.sense = [model.sense; '='];
% Conservation and route constraints
for t = 1:T
for node = nodes
if ismember(node, conflict_free_nodes)
A_cons = sparse(1, T * (n_links + n_nodes));
A_cons(1, (t-1)*n_links + adj_out_list(node)) = 1;
A_cons(1, T*n_links + (t-1)*n_nodes + node + 1) = -1;
model.A = [model.A; A_cons];
model.rhs = [model.rhs; 0];
model.sense = [model.sense; '='];
end
if t < T
A_route = sparse(1, T * (n_links + n_nodes));
A_route(1, (t-1)*n_links + adj_in_list(node)) = 1;
A_route(1, T*n_links + t*n_nodes + node + 1) = -1;
model.A = [model.A; A_route];
model.rhs = [model.rhs; 0];
model.sense = [model.sense; '='];
end
end
end
% Optimize model
result = gurobi(model);
% Check if the result contains 'x' field
if isfield(result, 'x')
% Process results
flow_res = reshape(result.x(1:T*n_links), [n_links, T])';
[t_idx, l_idx] = find(flow_res);
path = [t_idx, link_list(l_idx, :)];
disp(['Runtime: ', num2str(result.runtime)]);
% Save results
save('Path_result.mat', 'path');
else
disp('Model is infeasible. No solution found.');
end
catch ME
disp(['Error: ', ME.message]);
end
New contributor
Chadi Harmouche is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.