Skip to content

Commit 4b4a6fa

Browse files
author
Ledmington
committed
Minor fixes in ga
1 parent 842c854 commit 4b4a6fa

File tree

13 files changed

+172
-230
lines changed

13 files changed

+172
-230
lines changed

examples/src/main/java/com/ledmington/mal/examples/Main.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ public final class Main {
4141
"diet",
4242
Diet::new),
4343
"simulated_annealing",
44-
Map.of("random_strings", com.ledmington.mal.examples.annealing.RandomStrings::new),
44+
Map.of("rosenbrock", com.ledmington.mal.examples.annealing.Rosenbrock::new),
4545
"pattern_search",
4646
Map.of(
4747
"random_strings",

examples/src/main/java/com/ledmington/mal/examples/annealing/RandomStrings.java

Lines changed: 0 additions & 68 deletions
This file was deleted.
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
/*
2+
* minimization-algorithms-library - A collection of minimization algorithms.
3+
* Copyright (C) 2023-2025 Filippo Barbari <filippo.barbari@gmail.com>
4+
*
5+
* This program is free software: you can redistribute it and/or modify
6+
* it under the terms of the GNU General Public License as published by
7+
* the Free Software Foundation, either version 3 of the License, or
8+
* (at your option) any later version.
9+
*
10+
* This program is distributed in the hope that it will be useful,
11+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
12+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13+
* GNU General Public License for more details.
14+
*
15+
* You should have received a copy of the GNU General Public License
16+
* along with this program. If not, see <http://www.gnu.org/licenses/>.
17+
*/
18+
package com.ledmington.mal.examples.annealing;
19+
20+
import java.util.random.RandomGenerator;
21+
import java.util.random.RandomGeneratorFactory;
22+
import java.util.stream.IntStream;
23+
24+
import com.ledmington.mal.annealing.SimulatedAnnealing;
25+
26+
public final class Rosenbrock {
27+
28+
private static final class Solution {
29+
30+
private final double[] x;
31+
32+
Solution(final double[] x) {
33+
this.x = x;
34+
}
35+
36+
public double get(final int idx) {
37+
return x[idx];
38+
}
39+
40+
@Override
41+
public String toString() {
42+
final StringBuilder sb = new StringBuilder();
43+
sb.append('(');
44+
if (x.length > 0) {
45+
sb.append(String.format("%.6f", x[0]));
46+
for (int i = 1; i < x.length; i++) {
47+
sb.append(", ").append(String.format("%.6f", x[i]));
48+
}
49+
}
50+
sb.append(')');
51+
return sb.toString();
52+
}
53+
}
54+
55+
public Rosenbrock() {
56+
final long beginning = System.nanoTime();
57+
58+
final int d = 50;
59+
final double lowerBound = -10.0;
60+
final double upperBound = 10.0;
61+
final RandomGenerator rng = RandomGeneratorFactory.getDefault().create(System.nanoTime());
62+
63+
final SimulatedAnnealing<Solution> sa = new SimulatedAnnealing<>(
64+
10_000,
65+
() -> new Solution(IntStream.range(0, d)
66+
.mapToDouble(x -> rng.nextDouble(lowerBound, upperBound))
67+
.toArray()),
68+
x -> {
69+
// Genrate random hyperpoint inside the unit sphere
70+
final double[] p = new double[d];
71+
for (int i = 0; i < d; i++) {
72+
p[i] = rng.nextGaussian(0.0, 1.0);
73+
}
74+
// Normalize it
75+
double norm = 0.0;
76+
for (int i = 0; i < d; i++) {
77+
norm += p[i] * p[i];
78+
}
79+
norm = Math.sqrt(norm);
80+
for (int i = 0; i < d; i++) {
81+
p[i] /= norm;
82+
}
83+
// Scale it down by a random factor
84+
norm = rng.nextDouble(0.0, 1.0);
85+
for (int i = 0; i < d; i++) {
86+
p[i] *= norm;
87+
}
88+
// Add it to the current vector
89+
final double[] newX = new double[d];
90+
for (int i = 0; i < d; i++) {
91+
newX[i] = Math.clamp(x.get(i) + p[i], lowerBound, upperBound);
92+
}
93+
return new Solution(newX);
94+
},
95+
sol -> {
96+
final double a = 1.0;
97+
final double b = 5.0;
98+
double s = 0.0;
99+
for (int i = 0; i < d - 1; i++) {
100+
final double x = sol.get(i);
101+
final double y = sol.get(i + 1);
102+
final double t1 = a - x;
103+
final double t2 = y - x * x;
104+
s += t1 * t1 + b * t2 * t2;
105+
}
106+
return s;
107+
});
108+
109+
sa.run();
110+
111+
final long end = System.nanoTime();
112+
113+
System.out.printf("Total search time: %.3f seconds%n", (double) (end - beginning) / 1_000_000_000.0);
114+
}
115+
}

examples/src/main/java/com/ledmington/mal/examples/genetic/Diet.java

Lines changed: 2 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,6 @@
2222
import java.util.Map;
2323
import java.util.Objects;
2424
import java.util.Set;
25-
import java.util.concurrent.ExecutorService;
26-
import java.util.concurrent.Executors;
27-
import java.util.concurrent.TimeUnit;
2825
import java.util.function.Supplier;
2926
import java.util.random.RandomGenerator;
3027
import java.util.random.RandomGeneratorFactory;
@@ -249,9 +246,8 @@ public Diet() {
249246
return score;
250247
});
251248

252-
final ExecutorService ex =
253-
Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
254-
final GeneticAlgorithm<Solution> ga = new ParallelGeneticAlgorithm<>(ex, rng);
249+
final GeneticAlgorithm<Solution> ga =
250+
new ParallelGeneticAlgorithm<>(Runtime.getRuntime().availableProcessors());
255251
Set<Solution> g = new HashSet<>();
256252
final Set<Solution> allSolutions = new HashSet<>();
257253

@@ -284,17 +280,5 @@ public Diet() {
284280

285281
System.out.printf("%n%,d solutions evaluated%n", allSolutions.size());
286282
System.out.printf("Total search time: %.3f seconds%n", (double) (end - beginning) / 1_000_000_000.0);
287-
288-
if (!ex.isShutdown()) {
289-
ex.shutdown();
290-
}
291-
while (!ex.isTerminated()) {
292-
try {
293-
if (ex.awaitTermination(1, TimeUnit.SECONDS)) {
294-
break;
295-
}
296-
} catch (final InterruptedException ignored) {
297-
}
298-
}
299283
}
300284
}

examples/src/main/java/com/ledmington/mal/examples/genetic/Knapsack.java

Lines changed: 2 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,6 @@
2222
import java.util.HashSet;
2323
import java.util.Map;
2424
import java.util.Set;
25-
import java.util.concurrent.ExecutorService;
26-
import java.util.concurrent.Executors;
27-
import java.util.concurrent.TimeUnit;
2825
import java.util.function.Supplier;
2926
import java.util.random.RandomGenerator;
3027
import java.util.random.RandomGeneratorFactory;
@@ -175,9 +172,8 @@ public Knapsack() {
175172
return s + validSolutionPrize;
176173
});
177174

178-
final ExecutorService ex =
179-
Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
180-
final GeneticAlgorithm<Solution> ga = new ParallelGeneticAlgorithm<>(ex, rng);
175+
final GeneticAlgorithm<Solution> ga =
176+
new ParallelGeneticAlgorithm<>(Runtime.getRuntime().availableProcessors());
181177
Set<Solution> g = new HashSet<>();
182178
final Set<Solution> allSolutions = new HashSet<>();
183179

@@ -214,17 +210,5 @@ public Knapsack() {
214210

215211
System.out.printf("%n%,d solutions evaluated%n", allSolutions.size());
216212
System.out.printf("Total search time: %.3f seconds%n", (double) (end - beginning) / 1_000_000_000.0);
217-
218-
if (!ex.isShutdown()) {
219-
ex.shutdown();
220-
}
221-
while (!ex.isTerminated()) {
222-
try {
223-
if (ex.awaitTermination(1, TimeUnit.SECONDS)) {
224-
break;
225-
}
226-
} catch (final InterruptedException ignored) {
227-
}
228-
}
229213
}
230214
}

examples/src/main/java/com/ledmington/mal/examples/genetic/NeuralNetwork.java

Lines changed: 2 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,6 @@
1717
*/
1818
package com.ledmington.mal.examples.genetic;
1919

20-
import java.util.concurrent.ExecutorService;
21-
import java.util.concurrent.Executors;
22-
import java.util.concurrent.TimeUnit;
2320
import java.util.random.RandomGenerator;
2421
import java.util.random.RandomGeneratorFactory;
2522

@@ -180,9 +177,8 @@ public NeuralNetwork() {
180177
}
181178
}
182179

183-
final ExecutorService ex =
184-
Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
185-
final GeneticAlgorithm<Network> ga = new ParallelGeneticAlgorithm<>(ex, rng);
180+
final GeneticAlgorithm<Network> ga =
181+
new ParallelGeneticAlgorithm<>(Runtime.getRuntime().availableProcessors());
186182

187183
ga.setState(GeneticAlgorithmConfig.<Network>builder()
188184
.populationSize(1_000)
@@ -251,17 +247,5 @@ public NeuralNetwork() {
251247
})
252248
.build());
253249
ga.run();
254-
255-
if (!ex.isShutdown()) {
256-
ex.shutdown();
257-
}
258-
while (!ex.isTerminated()) {
259-
try {
260-
if (ex.awaitTermination(1, TimeUnit.SECONDS)) {
261-
break;
262-
}
263-
} catch (final InterruptedException ignored) {
264-
}
265-
}
266250
}
267251
}

examples/src/main/java/com/ledmington/mal/examples/genetic/RandomStrings.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ public RandomStrings() {
3636
final String alphabet =
3737
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .,:;-_@#[]{}()!?='\"+*/";
3838
final String targetString =
39-
"This library for Minimization Algorithms is absolutely fantastic! I cannot wait to try and use it with Java 21 and Gradle 8.11! Now let's write another time just to have longer strings and, therefore, add artificial complexity to the problem.";
39+
"This library for Minimization Algorithms is absolutely fantastic! I cannot wait to try it! Now let's write another time just to have longer strings and, therefore, add artificial complexity to the problem.";
4040
final int targetLength = targetString.length();
4141
final Supplier<Character> randomChar = () -> alphabet.charAt(rng.nextInt(0, alphabet.length()));
4242

examples/src/main/java/com/ledmington/mal/examples/genetic/Tsp.java

Lines changed: 2 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,6 @@
2323
import java.util.Map;
2424
import java.util.Objects;
2525
import java.util.Set;
26-
import java.util.concurrent.ExecutorService;
27-
import java.util.concurrent.Executors;
28-
import java.util.concurrent.TimeUnit;
2926
import java.util.function.Supplier;
3027
import java.util.random.RandomGenerator;
3128
import java.util.random.RandomGeneratorFactory;
@@ -213,9 +210,8 @@ public Tsp() {
213210
return s;
214211
});
215212

216-
final ExecutorService ex =
217-
Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
218-
final GeneticAlgorithm<Solution> ga = new ParallelGeneticAlgorithm<>(ex, rng);
213+
final GeneticAlgorithm<Solution> ga =
214+
new ParallelGeneticAlgorithm<>(Runtime.getRuntime().availableProcessors());
219215
Set<Solution> g = new HashSet<>();
220216
final Set<Solution> allSolutions = new HashSet<>();
221217

@@ -242,17 +238,5 @@ public Tsp() {
242238

243239
System.out.printf("%n%,d solutions evaluated%n", allSolutions.size());
244240
System.out.printf("Total search time: %.3f seconds%n", (double) (end - beginning) / 1_000_000_000.0);
245-
246-
if (!ex.isShutdown()) {
247-
ex.shutdown();
248-
}
249-
while (!ex.isTerminated()) {
250-
try {
251-
if (ex.awaitTermination(1, TimeUnit.SECONDS)) {
252-
break;
253-
}
254-
} catch (final InterruptedException ignored) {
255-
}
256-
}
257241
}
258242
}

examples/src/main/java/com/ledmington/mal/examples/patternsearch/RandomStrings.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ public RandomStrings() {
3232
final String alphabet =
3333
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .,:;-_@#[]{}()!?='\"+*/";
3434
final String targetString =
35-
"This library for Minimization Algorithms is absolutely fantastic! I cannot wait to try and use it with Java 21 and Gradle 8.11! Now let's write another time just to have longer strings and, therefore, add artificial complexity to the problem.";
35+
"This library for Minimization Algorithms is absolutely fantastic! I cannot wait to try it! Now let's write another time just to have longer strings and, therefore, add artificial complexity to the problem.";
3636
final int targetLength = targetString.length();
3737
final Supplier<Character> randomChar = () -> alphabet.charAt(rng.nextInt(0, alphabet.length()));
3838

0 commit comments

Comments
 (0)