Certainly! Below is the MATLAB equivalent of your provided Python script. This translation takes into account MATLAB's 1-based indexing and utilizes MATLAB's built-in functions for file handling, data processing, and parallel computing.
Note:
- Custom Functions: The Python script references two custom functions/modules:
initial_population and initial_routing_phase2. You will need to create equivalent MATLAB functions (initial_population.m and initial_routing_phase2.m) to replicate their functionality.
- Parallel Computing: MATLAB's
parpool is used to leverage multiple cores. Ensure you have the Parallel Computing Toolbox installed.
- File Paths: MATLAB uses
filesep for file separators, which makes the script platform-independent.
- Data Handling: MATLAB uses tables for handling CSV data, similar to pandas in Python.
Here's the complete MATLAB script:
% INITIAL ENCODING GA
% 1. For each particle record:
% a. Route list [[cust1, cust20,...]....[cust7,cust80...]]
% b. Distance list [Dr1, .......Drk]
% c. distance
% d. num_routes
% 2. Record fitness table: distance, num_routes, fitness function value
%% Clear Workspace and Command Window
clear; clc;
%% Add Paths for Custom Functions (Adjust as Needed)
% Make sure to add the directories containing initial_population and initial_routing_phase2
addpath('path_to_initial_pop_generation'); % Replace with your actual path
addpath('path_to_initial_routing_phase2'); % Replace with your actual path
%% Paths
cwd = pwd; % Current working directory
customer_path = fullfile(cwd, 'solomon25_csv', 'customers');
dataInfo_path = fullfile(cwd, 'solomon25_csv', 'data_info');
distanceMatrix_path = fullfile(cwd, 'solomon25_csv', 'distance_matrix');
initial_path = fullfile(cwd, 'initial');
%% Generate Dataset Lists
dataset_list = {};
% Initialize lists
c1_list_datasets = arrayfun(@(x) sprintf('c%d', x), 101:109, 'UniformOutput', false);
r1_list_datasets = arrayfun(@(x) sprintf('r%d', x), 101:112, 'UniformOutput', false);
rc1_list_datasets = arrayfun(@(x) sprintf('rc%d', x), 101:108, 'UniformOutput', false);
c2_list_datasets = arrayfun(@(x) sprintf('c%d', x), 201:208, 'UniformOutput', false);
r2_list_datasets = arrayfun(@(x) sprintf('r%d', x), 201:211, 'UniformOutput', false);
rc2_list_datasets = arrayfun(@(x) sprintf('rc%d', x), 201:208, 'UniformOutput', false);
% Combine all dataset lists
dataset_list = [c1_list_datasets, r1_list_datasets, rc1_list_datasets, ...
c2_list_datasets, r2_list_datasets, rc2_list_datasets];
%% Generate File Lists for DataInfo, Customers, and DistanceMatrix
% Helper function to generate filenames
generate_filenames = @(prefix, range, suffix) arrayfun(@(x) [prefix, num2str(x), suffix], range, 'UniformOutput', false);
% DataInfo Files
c1_list_dataInfo = generate_filenames('c', 101:109, 'dataInfo.csv');
r1_list_dataInfo = generate_filenames('r', 101:112, 'dataInfo.csv');
rc1_list_dataInfo = generate_filenames('rc', 101:108, 'dataInfo.csv');
c2_list_dataInfo = generate_filenames('c', 201:208, 'dataInfo.csv');
r2_list_dataInfo = generate_filenames('r', 201:211, 'dataInfo.csv');
rc2_list_dataInfo = generate_filenames('rc', 201:208, 'dataInfo.csv');
dataInfo_files_list = [c1_list_dataInfo, r1_list_dataInfo, rc1_list_dataInfo, ...
c2_list_dataInfo, r2_list_dataInfo, rc2_list_dataInfo];
% Customers Files
c1_list_customers = generate_filenames('c', 101:109, 'customers.csv');
r1_list_customers = generate_filenames('r', 101:112, 'customers.csv');
rc1_list_customers = generate_filenames('rc', 101:108, 'customers.csv');
c2_list_customers = generate_filenames('c', 201:208, 'customers.csv');
r2_list_customers = generate_filenames('r', 201:211, 'customers.csv');
rc2_list_customers = generate_filenames('rc', 201:208, 'customers.csv');
customers_files_list = [c1_list_customers, r1_list_customers, rc1_list_customers, ...
c2_list_customers, r2_list_customers, rc2_list_customers];
% DistanceMatrix Files
c1_list_distanceMatrix = generate_filenames('c', 101:109, 'distanceMatrix.csv');
r1_list_distanceMatrix = generate_filenames('r', 101:112, 'distanceMatrix.csv');
rc1_list_distanceMatrix = generate_filenames('rc', 101:108, 'distanceMatrix.csv');
c2_list_distanceMatrix = generate_filenames('c', 201:208, 'distanceMatrix.csv');
r2_list_distanceMatrix = generate_filenames('r', 201:211, 'distanceMatrix.csv');
rc2_list_distanceMatrix = generate_filenames('rc', 201:208, 'distanceMatrix.csv');
distanceMatrix_files_list = [c1_list_distanceMatrix, r1_list_distanceMatrix, rc1_list_distanceMatrix, ...
c2_list_distanceMatrix, r2_list_distanceMatrix, rc2_list_distanceMatrix];
% Initial Population Files
c1_list_initialPop = generate_filenames('c', 101:109, 'initialPop.mat'); % Using .mat instead of .npy
r1_list_initialPop = generate_filenames('r', 101:112, 'initialPop.mat');
rc1_list_initialPop = generate_filenames('rc', 101:108, 'initialPop.mat');
c2_list_initialPop = generate_filenames('c', 201:208, 'initialPop.mat');
r2_list_initialPop = generate_filenames('r', 201:211, 'initialPop.mat');
rc2_list_initialPop = generate_filenames('rc', 201:208, 'initialPop.mat');
initialPop_files_list = [c1_list_initialPop, r1_list_initialPop, rc1_list_initialPop, ...
c2_list_initialPop, r2_list_initialPop, rc2_list_initialPop];
% Initial Distance Files
c1_list_initialDistance = generate_filenames('c', 101:109, 'initialDistance.mat');
r1_list_initialDistance = generate_filenames('r', 101:112, 'initialDistance.mat');
rc1_list_initialDistance = generate_filenames('rc', 101:108, 'initialDistance.mat');
c2_list_initialDistance = generate_filenames('c', 201:208, 'initialDistance.mat');
r2_list_initialDistance = generate_filenames('r', 201:211, 'initialDistance.mat');
rc2_list_initialDistance = generate_filenames('rc', 201:208, 'initialDistance.mat');
initialDistance_files_list = [c1_list_initialDistance, r1_list_initialDistance, rc1_list_initialDistance, ...
c2_list_initialDistance, r2_list_initialDistance, rc2_list_initialDistance];
% Initial Results Files
c1_list_initialResults = generate_filenames('c', 101:109, 'initialResults.csv');
r1_list_initialResults = generate_filenames('r', 101:112, 'initialResults.csv');
rc1_list_initialResults = generate_filenames('rc', 101:108, 'initialResults.csv');
c2_list_initialResults = generate_filenames('c', 201:208, 'initialResults.csv');
r2_list_initialResults = generate_filenames('r', 201:211, 'initialResults.csv');
rc2_list_initialResults = generate_filenames('rc', 201:208, 'initialResults.csv');
initialResults_files_list = [c1_list_initialResults, r1_list_initialResults, rc1_list_initialResults, ...
c2_list_initialResults, r2_list_initialResults, rc2_list_initialResults];
%% Experimental Variables
num_experiments = 30;
% Determine the number of available cores and start a parallel pool
num_cores = feature('numcores'); % Number of CPU cores
if isempty(gcp('nocreate'))
parpool('local', num_cores);
end
% Global Variables
N = 300; % Population size
greedy_percent = 0.10; % Percentage to be greedily initialised
random_percent = 0.90; % Percentage to be randomly initialised
alpha = 100;
beta = 0.001;
%% Main Loop Over Each Dataset
for i = 1:length(dataset_list)
dataSet = dataset_list{i};
% Construct file paths
customer_file = fullfile(customer_path, customers_files_list{i});
dataInfo_file = fullfile(dataInfo_path, dataInfo_files_list{i});
distanceMatrix_file = fullfile(distanceMatrix_path, distanceMatrix_files_list{i});
% Read CSV Files
df_customers = readtable(customer_file);
df_distance_matrix = readtable(distanceMatrix_file);
df_dataInfo = readtable(dataInfo_file);
num_customers = height(df_customers);
num_customers_depot = num_customers + 1;
% Assign index starting from 1
df_customers.CustomerIndex = (1:num_customers_depot-1)';
% Determine number of chromosomes
number_random_chromosomes = floor(N * random_percent) - 1;
number_nearest_nn_chromosomes = 1;
number_greedy_chromosomes = N - number_random_chromosomes - 1; % Equivalent to floor(N*greedy_percent)
% Convert to MATLAB arrays
arr_distance_matrix = table2array(df_distance_matrix);
% Greedy radius
dataset_radius = (max(arr_distance_matrix, [], 'all') - min(arr_distance_matrix, [], 'all')) / 2;
% Customer Array: columns [index, demand, service_time, ready_time, due_time, complete_time]
arr_customers = zeros(num_customers, 6);
arr_customers(:,1) = (1:num_customers_depot-1)'; % Customer index
arr_customers(:,2) = df_customers.demand;
arr_customers(:,3) = df_customers.serviceTime;
arr_customers(:,4) = df_customers.readyTime;
arr_customers(:,5) = df_customers.dueTime;
arr_customers(:,6) = df_customers.completeTime;
% Fleet max details
total_time = df_dataInfo.fleet_max_working_time(1);
total_capacity = df_dataInfo.fleet_capacity(1);
all_customers_list = 1:(num_customers_depot-1);
%% Loop Over Each Experiment
for experiment = 1:num_experiments
% Define output directories
experiment_dir = fullfile(initial_path, dataSet, sprintf('experiment%d', experiment));
if ~exist(experiment_dir, 'dir')
mkdir(experiment_dir);
end
% Define output file paths
initial_pop_output_file = fullfile(experiment_dir, initialPop_files_list{i});
initial_pop_distance_output_file = fullfile(experiment_dir, initialDistance_files_list{i});
initial_result_output_file = fullfile(experiment_dir, initialResults_files_list{i});
% Generate random radius
radius = dataset_radius * (0.5 + rand * 0.5); % rand generates [0,1), so 0.5 to 1
% Phase 1: Initial Population Generation
[pop_chromosome_routeList_array, pop_chromosome_distanceList_array, pop_num_routes, pop_total_distance] = ...
initial_population(N, num_cores, number_random_chromosomes, number_greedy_chromosomes, ...
number_nearest_nn_chromosomes, num_customers, arr_customers, arr_distance_matrix, ...
total_capacity, total_time, all_customers_list, radius);
% Phase 2: Initial Routing (Assuming initial_routing_phase2 returns updated populations and results)
[pop_chromosome_routeList_array, pop_chromosome_distanceList_array, arr_pop_results] = ...
initial_routing_phase2(num_cores, N, alpha, beta, pop_chromosome_routeList_array, ...
pop_chromosome_distanceList_array, arr_distance_matrix, arr_customers, ...
total_time, total_capacity);
% Save Initial Population and Distance Arrays
save(initial_pop_output_file, 'pop_chromosome_routeList_array');
save(initial_pop_distance_output_file, 'pop_chromosome_distanceList_array');
% Prepare Initial Results Table
df_initial_results = table(pop_num_routes.', pop_total_distance.', ...
(alpha .* pop_num_routes + beta .* pop_total_distance).', ...
'VariableNames', {'num_vehicles', 'distance', 'fitness'});
% Write Initial Results to CSV
writetable(df_initial_results, initial_result_output_file);
fprintf('Dataset: %s, Experiment: %d completed.\n', dataSet, experiment);
end
fprintf('Completed all experiments for Dataset: %s\n', dataSet);
end
%% Close Parallel Pool
delete(gcp('nocreate'));
Explanation of the MATLAB Script
-
Initialization:
- The script starts by clearing the workspace and command window.
- It then adds paths to the directories containing the custom functions
initial_population and initial_routing_phase2. Make sure to replace 'path_to_initial_pop_generation' and 'path_to_initial_routing_phase2' with the actual paths where these functions are located.
-
Generating Dataset and File Lists:
- MATLAB's
arrayfun and anonymous functions are used to generate lists of dataset names and corresponding filenames, similar to Python's list comprehensions.
- The helper function
generate_filenames is defined to simplify the creation of filenames based on prefixes, numeric ranges, and suffixes.
-
Experimental Variables:
num_experiments is set to 30.
- The number of available CPU cores is determined using
feature('numcores'), and a parallel pool is started using parpool if it's not already running.
- Global variables such as population size (
N), percentages for greedy and random initialization, and coefficients alpha and beta are defined.
-
Main Loop Over Datasets:
- The script iterates over each dataset using a
for loop.
- For each dataset, it constructs the file paths for customers, data information, and distance matrices.
- CSV files are read into MATLAB tables using
readtable.
- Customer data is organized into a numerical array
arr_customers with columns representing different attributes.
- The radius for greedy initialization is calculated based on the distance matrix.
- Fleet constraints (
total_time and total_capacity) are extracted from the dataInfo table.
-
Inner Loop Over Experiments:
- For each experiment, the script creates an output directory if it doesn't exist.
- It then constructs the output file paths for initial populations, distances, and results.
- A random radius is generated within the specified range.
- Phase 1: Calls the
initial_population function to generate the initial population.
Additional Notes
-
Custom Functions Implementation: Ensure that the MATLAB versions of initial_population and initial_routing_phase2 functions are properly implemented. Their signatures should match the way they're called in the script.
-
Data Types and Structures: MATLAB handles data structures differently than Python. Ensure that the data types (especially for routes and distances) are compatible with how you plan to use them in the custom functions.
-
Performance Optimization: MATLAB's parfor can be leveraged within the custom functions to parallelize computations further if needed.
-
Error Handling: Consider adding error checks to handle cases where files might be missing or data might be inconsistent.
-
File Formats: MATLAB uses .mat files for saving variables efficiently. If you need to use .npy specifically, you might need to use a third-party library or MATLAB's support for NumPy files.
Example Implementation for Custom Functions
Below is a skeleton for how you might define the initial_population and initial_routing_phase2 functions in MATLAB. You will need to fill in the actual implementation based on your specific requirements.
% initial_population.m
function [routeList, distanceList, num_routes, total_distance] = initial_population(N, num_cores, num_random, num_greedy, num_nn, num_customers, customers, distance_matrix, capacity, time, all_customers, radius)
% Initialize empty arrays or cell arrays
routeList = cell(N,1);
distanceList = zeros(N,1);
num_routes = zeros(N,1);
total_distance = zeros(N,1);
% Example: Generate random chromosomes
for i = 1:num_random
% Generate random routes (Implement your logic)
routeList{i} = randperm(num_customers);
% Calculate distances and other metrics
distanceList(i) = calculate_total_distance(routeList{i}, distance_matrix);
num_routes(i) = calculate_number_of_routes(routeList{i}, capacity, time); % Implement this function
total_distance(i) = distanceList(i); % Adjust based on your calculations
end
% Similarly implement greedy and nearest neighbor initialization
% ...
end
% initial_routing_phase2.m
function [routeList, distanceList, pop_results] = initial_routing_phase2(num_cores, N, alpha, beta, routeList, distanceList, distance_matrix, customers, total_time, total_capacity)
% Initialize results array
pop_results = zeros(N,3); % [num_vehicles, distance, fitness]
parfor i = 1:N
% Implement your routing logic here
num_vehicles = calculate_number_of_vehicles(routeList{i}, total_capacity); % Implement this
distance = distanceList(i);
fitness = alpha * num_vehicles + beta * distance;
pop_results(i, :) = [num_vehicles, distance, fitness];
end
end
Replace the placeholder functions like calculate_total_distance, calculate_number_of_routes, and calculate_number_of_vehicles with your actual implementation logic.
Conclusion
This MATLAB script mirrors the structure and logic of your original Python script, adapting it to MATLAB's syntax and functionalities. Ensure that all custom functions are properly translated and tested to achieve the desired behavior. If you encounter specific issues during the translation, feel free to ask for further assistance!