TSP_inst
Generates TSP instances by sampling nodes from TSPLIB files.
- USAGE:
python -m TSP_inst ./instances
Generates a set of TSP instances, saving original instance data in
./instances (or another specified directory): orig subdirectory
for original instances and QUBO, respectively, for QUBOs.
Instance parameters are specified in main(), which in turn calls the
core generation function, generate_TSP_instances(). This module also
contains a few cross-checks (e.g., alternative MIP models), auxiliary and
visualization code.
Functions
|
Asserts if the solutions to QUBO and 'natural' MIP coincide. |
|
Returns the distance matrix for |
|
Creates an MTZ model from distance matrix |
|
Creates a MIP model (QAP form) from distance matrix D for cross-check. |
|
Draws a grid of instances by (the number part of) IDs. |
|
Draws a grid of instances from |
|
Draws a single TSP instance (weighted graph |
|
Utility to create a QUBO: incorporates constraints in the form "Ax=b". |
|
The core function that generates TSP instances. |
Builds TSP quadratic cost function coefficients from a graph. |
|
Returns the constraints for TSP in the matrix form. |
|
|
Calculates the distance between i and j from node_coords |
|
Checks if |
|
Helper: returns the (linear) vector-index (k) given the matrix-indices (i,t). |
|
Loads an instance by ID and returns matrix D. |
|
The main function specifying instance generation parameters (see the source code). |
|
Calculates the objective given the costs matrix and a tour. |
|
Converts single lat/lon value ( |
|
Creates distance matrices for sub-graphs of given size. |
|
Saves a TSP instance encoded by a distance matrix to a JSON (with metadata). |
|
Wraps |
|
Creates and solves a QAP MIP model for TSP. |
|
Creates and solves a MTZ MIP model for TSP. |
|
Unpacks the tour given the bitstring (assuming QUBO). |
|
Returns the tour given gurobi vars (linear indexing) and the number of nodes. |
|
Returns the tour given gurobi vars (matrix indexing) and the number of nodes. |
- TSP_inst.get_correct_dist(NC, i, j)[source]
Calculates the distance between i and j from node_coords
NC.
- TSP_inst.k(i, t, N)[source]
Helper: returns the (linear) vector-index (k) given the matrix-indices (i,t).
k: (i,t) -> N*t + i
Notes
Both
iandtnumbering is assumed zero-based.Nis the total number of nodes addressed byi.
- TSP_inst.get_QF_coeffs(D)[source]
Builds TSP quadratic cost function coefficients from a graph.
- Parameters:
D – distance matrix, (N x N)
- Returns:
Q– an (N-1)^2 x (N-1)^2 matrix of quadratic coefficients,P– a vector of (N-1)^2 numbers containing linear coefficients.
Note
The resulting form is assumed to be (1/2) x’ Q x + P’ x.
- TSP_inst.encode_constraints(Q, P, A, b, M)[source]
Utility to create a QUBO: incorporates constraints in the form “Ax=b”.
- Parameters:
Q – quadratic coefficients matrix,
P – linear coefficients vector,
A – constraints matrix,
b – constraints RHS vector,
M – big M parameter (multiplicative const) for penalty terms.
- Returns:
Q-prime, P-prime, and Const
Notes
We assume the input problem in the form:
min_x (1/2) x’ Q x + P’ x (1)s.t. Ax = bThe function transforms it to:
min_x (1/2) x’ Qp x + Pp’ x + Const, (2)
where Qp and Pp incorporate penalties (with multiple M) into the objective, so that solutions to (1) and (2) would be the same.
- TSP_inst.get_constraints(D)[source]
Returns the constraints for TSP in the matrix form.
- Parameters:
D – the distance matrix,
- Returns:
Matrix A and vector b, so that the constraints are
Ax = b, assuming x-variables.
- TSP_inst.save_orig_instance(D, inst_id, problem, comment='', directory='./instances/orig/')[source]
Saves a TSP instance encoded by a distance matrix to a JSON (with metadata).
- Parameters:
D – distance matrix,
inst_id (string) – instance ID,
problem – original problem (as loaded by tsplib),
comment – optional comment for the JSON file,
directory – a dir to save files.
- TSP_inst.load_instance_by_ID(ID, directory='./instances/orig/')[source]
Loads an instance by ID and returns matrix D.
- TSP_inst.sample_nodes(Dfull, Ns=[5], K=5)[source]
Creates distance matrices for sub-graphs of given size.
Try to create K unique instances by generating N-node subgraphs from a weighted graph given by distance matrix Dfull.
- Parameters:
Dfull (np.array) – full distance matrix,
N (list) – numbers of nodes to sample (default: one value, 5),
K (int) – number of samples to make per size (default: 5).
Example
>>> seed(2023) >>> t = np.array([[1,2,3],[4,5,6],[7,8,9]]) >>> sample_nodes(t, Ns=2, K=3) [array([[5, 6], [8, 9]]), array([[1, 3], [7, 9]]), array([[1, 2], [4, 5]])]
- TSP_inst.generate_TSP_instances(downloads='./download/', instdir='./instances', Ns=[5, 7, 10], K=1, N_src_inst=15, Ninst_max=1000, N_total=100, seed=2023)[source]
The core function that generates TSP instances.
Creates at least K * len(Ns) and at most
N_totalinstances by sampling from existing TSP instances (looked for indownloadsdirectory) and saves them to directoryinstdir.- Parameters:
downloads (str) – a directory with original instances to sample from
instdir (str) – directory for the generated instances,
Ns (list[int]) – number of nodes to sample
K (int) – number of instances to create per size
N_src_inst (int) – max # of source TSP instances to process.
N_N (int) – max # of source TSP instances to process.
seed (int) – random seed, for reproducibility
- TSP_inst.create_MTZ_TSP_model(D, quiet=False)[source]
Creates an MTZ model from distance matrix
D.Note
All numberings start from one.
- Returns:
A model (
gurobipy.Model),x,u(variables in the form ofdict-s)
- TSP_inst.create_simple_TSP_model(D, quiet=False)[source]
Creates a MIP model (QAP form) from distance matrix D for cross-check.
- Parameters:
D – distance matrix,
- Returns:
model (
gurobipy.Model) and y (adictof variables).
- TSP_inst.unpack_tour_y(y, N)[source]
Returns the tour given gurobi vars (matrix indexing) and the number of nodes.
- Parameters:
y – a
dictof variables returned by Gurobi, keyed by(i, t),N – number of nodes in the graph
- TSP_inst.unpack_tour_QUBO_bitstring(bs, N)[source]
Unpacks the tour given the bitstring (assuming QUBO).
Note
Assumes direct order of bits in the bistring. E.g.,
[n0, n1, n2, ... ].
- TSP_inst.unpack_tour_x(x, N)[source]
Returns the tour given gurobi vars (linear indexing) and the number of nodes.
- Parameters:
x – a
dictof variables returned by Gurobi, keyed by a single numberk(i, t, N-1),N – number of nodes in the graph
- TSP_inst.is_feasible(tour, D)[source]
Checks if
touris feasible (given the distance matrixD).Essentially, checks if the number of nodes is correct, all nodes are visited once, and the last point coincides with the first one.
- TSP_inst.show_feasible(tour, D)[source]
Wraps
is_feasible()into a string, for readability.
- TSP_inst.draw_instance(G, ax=<Axes: >, node_color='blue', node_size=200, with_labels=True)[source]
Draws a single TSP instance (weighted graph
G).
- TSP_inst.draw_inst_grid(selected_files, Ncols=3, directory='./instances-new/QUBO', cross_check=True)[source]
Draws a grid of instances from
selected_files.- Parameters:
selected_files (list) – list of files (*.qubo.json)
Ncols (int) – number of columns in the grid.
directory (str) – directory with QUBO files (*.qubo.json)
- TSP_inst.draw_IDs_grid(sel_IDs, directory='./instances-new/QUBO', Ncols=3, cross_check=True)[source]
Draws a grid of instances by (the number part of) IDs.
- Parameters:
sel_IDs (list[int]) – list of instance IDs (numbers)
directory (str) – directory with QUBO files (*.qubo.json)
Ncols (int) – number of columns in the grid
- Returns:
selected file names.
- TSP_inst.solve_TSP_MIP(instance_file, quiet=True, timeout=None)[source]
Creates and solves a QAP MIP model for TSP.
- TSP_inst.solve_TSP_MTZ(instance_file, quiet=True, timeout=None)[source]
Creates and solves a MTZ MIP model for TSP.