0

我练习使用这个库,Jenetics.io。在他们的手册中,他们有一个例子,旅行推销员。该示例仅显示找到的最小路径,但不显示解决方案的点集或点顺序。如何获得解决方案的点集?

手册.. 第 129 页在此处输入链接描述

运行代码,结果:

[[D@79fc0f2f|[D@37a71e93|[D@4783da3f|[D@6e2c634b|[D@49097b5d|[D@378fd1ac|[D@5e9f23b4|[D@2dda6444|[D@50040f0c] -> 16.46284073991415

我使用的代码:

public class EncotrarRuta implements Problem<ISeq<double[]>,EnumGene<double[]>,Double>{

private final ISeq<double[]> _points;
private ArrayList<Double> puntosX = new ArrayList<>();
private ArrayList<Double> puntosY = new ArrayList<>();


public EncotrarRuta(ArrayList<Double> puntosX, ArrayList<Double> puntosY) {
    this._points = null;
    this.puntosX = puntosX;
    this.puntosY = puntosY;
}


public EncotrarRuta(ISeq<double[]> points) {
    this._points = requireNonNull(points);
}

@Override
public Function<ISeq<double[]>, Double> fitness() {
    return p -> IntStream.range(0, p.length())
        .mapToDouble(i -> {
            final double[] p1 = p.get(i);
            final double[] p2 = p.get((i+1)%p.size());
            return hypot(p1[0]-p2[0],p1[1]-p2[1]);
        }).sum();
}

@Override
public Codec<ISeq<double[]>, EnumGene<double[]>> codec() {
    return Codecs.ofPermutation(_points);
}

public static EncotrarRuta of(ArrayList<Double> puntosX, ArrayList<Double> puntosY){
    final MSeq<double[]> points = MSeq.ofLength(puntosX.size());
    
    for (int i = 0; i < puntosX.size(); i++) {
        points.set(i, new double[]{puntosX.get(i),puntosY.get(i)});
    }

    return new EncotrarRuta(points.asISeq());
}

public void run() {

    EncotrarRuta encotrarRuta = EncotrarRuta.of(puntosX, puntosY);

    Engine<EnumGene<double[]>,Double> engine = Engine
        .builder(encotrarRuta)
        .optimize(Optimize.MINIMUM)
        .maximalPhenotypeAge(11)
        .populationSize(500)
        .alterers(
            new SwapMutator<>(0.2),
            new PartiallyMatchedCrossover<>(0.35))
        .build();

    EvolutionStatistics<Double, ?> statistics = EvolutionStatistics.ofNumber();

    Phenotype<EnumGene<double[]>,Double> best = engine.stream()
        .limit(bySteadyFitness(25))
        .limit(250)
        .peek(statistics)
        .collect(toBestPhenotype());


    System.out.println(best);
   

}

}

4

2 回答 2

0

为了在实际路线中转换最佳 ,您可以使用. 在您的示例中,它将如下所示:PhenotypeCodec

final Phenotype<EnumGene<double[]>, Double> best = ...;
final ISeq<double[]> route = encotrarRuta.codec().decode(best.genotype());

您可以在示例模块中找到另一个 TSP 示例:TravelingSalesman.java。此示例使用JPX库中的真实GPS航点。

于 2021-09-24T07:10:53.243 回答
0

我找到了解决方案,或者我想要获得的东西,

best.genotype().chromosome().iterator().forEachRemaining(i -> {
        for (double ds : i.allele()) {
            System.out.println(ds);
        }
    });

有了它,我得到了解决方案的要点列表

[[D@7cd84586|[D@30dae81|[D@1b2c6ec2|[D@4769b07b|[D@4edde6e5|[D@66a29884|[D@1e80bfe8|[D@70177ecd] -> 12.65685424949238
1.0
1.0
2.0
2.0
3.0
3.0
3.0
1.0
4.0
1.0
6.0
1.0
6.0
3.0
5.0
4.0
于 2021-09-25T00:54:40.690 回答