-
Notifications
You must be signed in to change notification settings - Fork 1
/
test.js
133 lines (115 loc) · 4.15 KB
/
test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
const fs = require('fs');
const path = require('path');
const { parse } = require('csv-parse/sync');
class RouteOptimizer {
constructor(cityFile, costMatrixFile) {
this.cityFile = cityFile;
this.costMatrixFile = costMatrixFile;
this.cities = [];
this.costMatrix = [];
}
// Load cities from CSV
loadCities() {
const cityData = fs.readFileSync(this.cityFile, 'utf-8');
const records = parse(cityData, { columns: true, skip_empty_lines: true });
this.cities = records.map(record => ({
id: parseInt(record.City_ID),
name: record.City,
state: record.State,
latitude: parseFloat(record.Latitude),
longitude: parseFloat(record.Longitude)
}));
}
// Generate synthetic cost matrix
generateSyntheticCostMatrix() {
const numCities = this.cities.length;
const maxCost = 500; // Max cost between two cities
this.costMatrix = Array.from({ length: numCities }, () => Array(numCities).fill(0));
for (let i = 0; i < numCities; i++) {
for (let j = i + 1; j < numCities; j++) {
const cost = Math.random() * maxCost + 1; // Random cost
this.costMatrix[i][j] = cost;
this.costMatrix[j][i] = cost; // Symmetric
}
}
// Save cost matrix to file
const matrixContent = this.costMatrix.map(row => row.map(val => val.toFixed(2)).join(',')).join('\n');
fs.writeFileSync(this.costMatrixFile, matrixContent);
console.log(`Synthetic cost matrix saved to ${this.costMatrixFile}`);
}
// Load cost matrix from file
loadCostMatrix() {
const matrixData = fs.readFileSync(this.costMatrixFile, 'utf-8');
this.costMatrix = matrixData.split('\n').map(row => row.split(',').map(parseFloat));
}
// Find all optimal paths
findOptimalPaths() {
const numCities = this.cities.length;
const results = [];
// Floyd-Warshall Algorithm for All-Pairs Shortest Path
const dist = JSON.parse(JSON.stringify(this.costMatrix));
const next = Array.from({ length: numCities }, (_, i) =>
Array.from({ length: numCities }, (_, j) => (i === j ? null : j))
);
for (let k = 0; k < numCities; k++) {
for (let i = 0; i < numCities; i++) {
for (let j = 0; j < numCities; j++) {
if (dist[i][j] > dist[i][k] + dist[k][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
next[i][j] = next[i][k];
}
}
}
}
// Reconstruct paths and store results
for (let i = 0; i < numCities; i++) {
for (let j = i + 1; j < numCities; j++) {
const path = this.reconstructPath(i, j, next);
const pathNames = path.map(index => this.cities[index].name);
const source = this.cities[i].name;
const destination = this.cities[j].name;
const cost = dist[i][j].toFixed(2);
results.push({
source,
destination,
entire_path: pathNames.join(' → '),
minimum_cost: cost
});
}
}
return results;
}
// Reconstruct path using next-hop matrix
reconstructPath(start, end, next) {
if (next[start][end] === null) return [];
const path = [start];
while (start !== end) {
start = next[start][end];
path.push(start);
}
return path;
}
// Save results to CSV
saveResultsToCSV(results, outputFile) {
const header = 'source,destination,entire_path,minimum_cost\n';
const rows = results
.map(row => `${row.source},${row.destination},"${row.entire_path}",${row.minimum_cost}`)
.join('\n');
fs.writeFileSync(outputFile, header + rows);
console.log(`Results saved to ${outputFile}`);
}
// Run the entire process
run(outputFile) {
this.loadCities();
this.generateSyntheticCostMatrix();
this.loadCostMatrix();
const results = this.findOptimalPaths();
this.saveResultsToCSV(results, outputFile);
}
}
// Configuration
const cityFile = path.join(__dirname, 'cities.csv'); // Path to cities file
const costMatrixFile = path.join(__dirname, 'cost_matrix.txt'); // Path to cost matrix file
const outputFile = path.join(__dirname, 'optimal_routes.csv'); // Path to output file
const optimizer = new RouteOptimizer(cityFile, costMatrixFile);
optimizer.run(outputFile);