Commit 8a7de711 authored by Tong Li's avatar Tong Li

变邻域+模拟退火+禁忌搜索

parent 932c42d2
...@@ -15,7 +15,7 @@ public class ScheduleParams { ...@@ -15,7 +15,7 @@ public class ScheduleParams {
// 基础参数(自适应调整的基准值) // 基础参数(自适应调整的基准值)
private static final int MIN_POPULATION_SIZE = 10; private static final int MIN_POPULATION_SIZE = 10;
private static final int MAX_POPULATION_SIZE = 50; private static final int MAX_POPULATION_SIZE = 20;
private static final int MIN_MAX_ITERATIONS = 50; private static final int MIN_MAX_ITERATIONS = 50;
private static final int MAX_MAX_ITERATIONS = 100; private static final int MAX_MAX_ITERATIONS = 100;
private static final float MIN_CROSSOVER_PROB = 0.6f; private static final float MIN_CROSSOVER_PROB = 0.6f;
...@@ -172,10 +172,14 @@ public class ScheduleParams { ...@@ -172,10 +172,14 @@ public class ScheduleParams {
// 1. 种群大小:50 ~ 500,随工序数线性增加 // 1. 种群大小:50 ~ 500,随工序数线性增加
populationSize = (int) Math.max(MIN_POPULATION_SIZE, populationSize = (int) Math.max(MIN_POPULATION_SIZE,
Math.min(MAX_POPULATION_SIZE, MIN_POPULATION_SIZE + totalOps * populationSizeCoeff)); Math.min(MAX_POPULATION_SIZE, MIN_POPULATION_SIZE + totalOps * populationSizeCoeff));
int maxthead= Runtime.getRuntime().availableProcessors() - 1;
populationSize= populationSize / maxthead*maxthead;
// 确保偶数(方便交叉) // 确保偶数(方便交叉)
if (populationSize % 2 != 0) { // if (populationSize % 2 != 0) {
populationSize += 1; // populationSize += 1;
} // }
// 2. 最大迭代次数:50 ~ 200,随工序数线性减少 // 2. 最大迭代次数:50 ~ 200,随工序数线性减少
maxIterations = (int) Math.max(MIN_MAX_ITERATIONS, maxIterations = (int) Math.max(MIN_MAX_ITERATIONS,
......
...@@ -73,11 +73,11 @@ public class GlobalParam { ...@@ -73,11 +73,11 @@ public class GlobalParam {
public GlobalParam() { public GlobalParam() {
// 初始化默认目标值配置 // 初始化默认目标值配置
//完工时间、总流程时间、总换型时间、机器负载标准差、延迟时间 //完工时间、总流程时间、总换型时间、机器负载标准差、延迟时间
objectiveConfigs.add(new ObjectiveConfig(OBJECTIVE_MAKESPAN, true, 1, 0.6)); objectiveConfigs.add(new ObjectiveConfig(OBJECTIVE_MAKESPAN, true, 1, 0.3));
objectiveConfigs.add(new ObjectiveConfig(OBJECTIVE_FLOW_TIME, false, 2, 0.1)); objectiveConfigs.add(new ObjectiveConfig(OBJECTIVE_FLOW_TIME, true, 2, 0.1));
objectiveConfigs.add(new ObjectiveConfig(OBJECTIVE_SETUP_TIME, true, 2, 0.1)); objectiveConfigs.add(new ObjectiveConfig(OBJECTIVE_SETUP_TIME, true, 2, 0.1));
objectiveConfigs.add(new ObjectiveConfig(OBJECTIVE_MACHINE_LOAD, false, 3, 0.1)); objectiveConfigs.add(new ObjectiveConfig(OBJECTIVE_MACHINE_LOAD, true, 1, 0.1));
objectiveConfigs.add(new ObjectiveConfig(OBJECTIVE_TARDINESS, true, 1, 0.3)); objectiveConfigs.add(new ObjectiveConfig(OBJECTIVE_TARDINESS, true, 1, 0.6));
objectiveConfigs.sort(Comparator.comparing((ObjectiveConfig op) -> op.getLevel())); objectiveConfigs.sort(Comparator.comparing((ObjectiveConfig op) -> op.getLevel()));
} }
......
package com.aps.entity.basic;
/**
* 作者:佟礼
* 时间:2026-04-09
*/
public class KpiTargetConfig {
}
...@@ -425,7 +425,7 @@ public class GeneticAlgorithm { ...@@ -425,7 +425,7 @@ public class GeneticAlgorithm {
// chromosome.setResultOld(new CopyOnWriteArrayList<>()); // chromosome.setResultOld(new CopyOnWriteArrayList<>());
// } // }
decoder.decodeChromosomeWithCache(chromosome); decoder.decodeChromosomeWithCache(chromosome,false);
if (chromosome.getFitness() == 0) { if (chromosome.getFitness() == 0) {
chromosome.setFitness(_fitnessCalculator.calculateFitness(chromosome, _objectiveWeights)); chromosome.setFitness(_fitnessCalculator.calculateFitness(chromosome, _objectiveWeights));
} }
......
...@@ -88,17 +88,17 @@ public class GeneticDecoder { ...@@ -88,17 +88,17 @@ public class GeneticDecoder {
{ {
FileHelper.writeLogFile("解码---------------"+population.size() ); FileHelper.writeLogFile("解码---------------"+population.size() );
boolean ismore=false; boolean ismore=true;
if(ismore) { if(ismore) {
CompletableFuture.allOf(population.stream() CompletableFuture.allOf(population.stream()
.map(chromosome -> CompletableFuture.runAsync(() -> decodeChromosomeWithCache(chromosome), decodeExecutor)) .map(chromosome -> CompletableFuture.runAsync(() -> decodeChromosomeWithCache(chromosome,false), decodeExecutor))
.toArray(CompletableFuture[]::new)) .toArray(CompletableFuture[]::new))
.join(); .join();
} else { } else {
if (population != null && population.size() > 0) { if (population != null && population.size() > 0) {
population.forEach(chromosome -> { population.forEach(chromosome -> {
decodeChromosomeWithCache( chromosome); decodeChromosomeWithCache( chromosome,false);
}); });
} }
} }
...@@ -176,7 +176,7 @@ public class GeneticDecoder { ...@@ -176,7 +176,7 @@ public class GeneticDecoder {
// return chromosome; // return chromosome;
// } // }
public Chromosome decodeChromosomeWithCache(Chromosome chromosome) { public Chromosome decodeChromosomeWithCache(Chromosome chromosome,boolean isParallel) {
String cacheKey = createCacheKey(chromosome); String cacheKey = createCacheKey(chromosome);
// FileHelper.writeLogFile("解码-----------开始-------"+chromosome.getID()+":"+cacheKey ); // FileHelper.writeLogFile("解码-----------开始-------"+chromosome.getID()+":"+cacheKey );
...@@ -214,7 +214,7 @@ public class GeneticDecoder { ...@@ -214,7 +214,7 @@ public class GeneticDecoder {
return chromosome; return chromosome;
} }
// 3. 缓存未命中:执行解码逻辑 // 3. 缓存未命中:执行解码逻辑
decode(chromosome); decode(chromosome,isParallel);
// 4. 将解码结果存入缓存(无锁,ConcurrentHashMap 线程安全) // 4. 将解码结果存入缓存(无锁,ConcurrentHashMap 线程安全)
decodingCache.putIfAbsent(cacheKey, chromosome); decodingCache.putIfAbsent(cacheKey, chromosome);
...@@ -367,12 +367,11 @@ if(finishedOrder==null||finishedOrder.size()==0) ...@@ -367,12 +367,11 @@ if(finishedOrder==null||finishedOrder.size()==0)
orderProcessCounter.put(orderid, scheduledCount); orderProcessCounter.put(orderid, scheduledCount);
} }
public void decode(Chromosome chromosome) { public void decode(Chromosome chromosome,boolean isParallel) {
int operationCount = chromosome.getAllOperations().size();
int cpuCores = Runtime.getRuntime().availableProcessors();
// //
// // 根据工序数量和CPU核心数决定是否使用内部并行 // // 根据工序数量和CPU核心数决定是否使用内部并行
if (operationCount > 5000 && cpuCores > 4) { if (isParallel) {
// 使用设备并行处理 // 使用设备并行处理
// FileHelper.writeLogFile("使用并行处理 _s"); // FileHelper.writeLogFile("使用并行处理 _s");
parallelDecodeByMachine(chromosome); parallelDecodeByMachine(chromosome);
...@@ -392,7 +391,7 @@ if(finishedOrder==null||finishedOrder.size()==0) ...@@ -392,7 +391,7 @@ if(finishedOrder==null||finishedOrder.size()==0)
public void serialDecode(Chromosome chromosome) { public void serialDecode(Chromosome chromosome) {
List<OrderMaterialRequirement> orderMaterials = materialRequirementService.buildMultiLevelRequirementNetwork(chromosome, sceneId, baseTime,_globalParam); // List<OrderMaterialRequirement> orderMaterials = materialRequirementService.buildMultiLevelRequirementNetwork(chromosome, sceneId, baseTime,_globalParam);
chromosome.setScenarioID(sceneId); chromosome.setScenarioID(sceneId);
if(_globalParam.isIsCheckSf()) { if(_globalParam.isIsCheckSf()) {
int isnew= generateGlobalOpList(chromosome); int isnew= generateGlobalOpList(chromosome);
......
...@@ -343,7 +343,7 @@ chromo.setOrders(new CopyOnWriteArrayList<>(orders)); ...@@ -343,7 +343,7 @@ chromo.setOrders(new CopyOnWriteArrayList<>(orders));
/** /**
* 使用构造启发式算法生成初始种群 * 使用构造启发式算法生成初始种群
*/ */
public List<Chromosome> generateHeuristicInitialPopulation(ScheduleParams param, List<GlobalOperationInfo> globalOpList) { public List<Chromosome> generateHeuristicInitialPopulation(ScheduleParams param) {
List<Chromosome> population = new ArrayList<>(); List<Chromosome> population = new ArrayList<>();
int populationSize = param.getPopulationSize(); int populationSize = param.getPopulationSize();
this.baseTime=param.getBaseTime(); this.baseTime=param.getBaseTime();
......
...@@ -1885,7 +1885,7 @@ if(targetOp.getSequence()>1) { ...@@ -1885,7 +1885,7 @@ if(targetOp.getSequence()>1) {
decoder.decode(chromosome); decoder.decode(chromosome,false);
KpiCalculator kpiCalculator=new KpiCalculator(chromosome); KpiCalculator kpiCalculator=new KpiCalculator(chromosome);
kpiCalculator.calculatekpi(); kpiCalculator.calculatekpi();
......
package com.aps.service.Algorithm;
import com.aps.common.util.ProductionDeepCopyUtil;
import com.aps.entity.Algorithm.*;
import com.aps.entity.basic.Entry;
import com.aps.entity.basic.GlobalParam;
import java.util.*;
/**
* 禁忌搜索+模拟退火混合算法
*/
public class TabuSearchWithSA {
private final Random rnd = new Random();
private GlobalParam globalParam;
private List<Entry> allOperations;
private List<GlobalOperationInfo> globalOpList;
private FitnessCalculator fitnessCalculator;
private ObjectiveWeights objectiveWeights;
// 禁忌表
private List<Chromosome> tabuList;
private int tabuListSize = 50;
public TabuSearchWithSA(GlobalParam globalParam, List<Entry> allOperations, List<GlobalOperationInfo> globalOpList, FitnessCalculator fitnessCalculator, ObjectiveWeights objectiveWeights) {
this.globalParam = globalParam;
this.allOperations = allOperations;
this.globalOpList = globalOpList;
this.fitnessCalculator = fitnessCalculator;
this.objectiveWeights = objectiveWeights;
this.tabuList = new ArrayList<>();
}
/**
* 禁忌搜索+模拟退火混合搜索
*/
public Chromosome search(Chromosome chromosome, GeneticDecoder decoder, ScheduleParams param) {
Chromosome current = ProductionDeepCopyUtil.deepCopy(chromosome, Chromosome.class);
Chromosome best = ProductionDeepCopyUtil.deepCopy(chromosome, Chromosome.class);
// 初始化温度
double temperature = 100.0;
double coolingRate = 0.95;
int iterations = 0;
int maxIterations = 1000;
int noImprovementCount = 0;
int maxNoImprovement = 100;
while (iterations < maxIterations && noImprovementCount < maxNoImprovement) {
// 生成邻域解
List<Chromosome> neighbors = generateNeighbors(current);
// 过滤禁忌解
List<Chromosome> validNeighbors = filterTabuSolutions(neighbors);
// 评估所有邻域解
Chromosome bestNeighbor = null;
double bestNeighborFitness = Double.NEGATIVE_INFINITY;
for (Chromosome neighbor : validNeighbors) {
decode(decoder, neighbor, param);
if (neighbor.getFitness() > bestNeighborFitness) {
bestNeighborFitness = neighbor.getFitness();
bestNeighbor = neighbor;
}
}
if (bestNeighbor != null) {
// 计算能量差
decode(decoder, current, param);
double energyDifference = bestNeighbor.getFitness() - current.getFitness();
// 结合模拟退火的概率接受机制
if (energyDifference > 0 || rnd.nextDouble() < Math.exp(energyDifference / temperature)) {
// 更新当前解
current = bestNeighbor;
// 更新禁忌表
addToTabuList(current);
// 更新最优解
if (isBetter(current, best)) {
best = current;
noImprovementCount = 0;
} else {
noImprovementCount++;
}
}
}
// 降温
temperature *= coolingRate;
iterations++;
}
return best;
}
/**
* 生成邻域解
*/
private List<Chromosome> generateNeighbors(Chromosome chromosome) {
List<Chromosome> neighbors = new ArrayList<>();
// 生成多个邻域解
for (int i = 0; i < 10; i++) {
int neighborType = rnd.nextInt(4);
switch (neighborType) {
case 0:
neighbors.add(generateSwapNeighbor(chromosome));
break;
case 1:
neighbors.add(generateReverseNeighbor(chromosome));
break;
case 2:
neighbors.add(generateInsertNeighbor(chromosome));
break;
case 3:
neighbors.add(generateMachineChangeNeighbor(chromosome));
break;
}
}
return neighbors;
}
/**
* 过滤禁忌解
*/
private List<Chromosome> filterTabuSolutions(List<Chromosome> neighbors) {
List<Chromosome> validNeighbors = new ArrayList<>();
for (Chromosome neighbor : neighbors) {
if (!isTabu(neighbor)) {
validNeighbors.add(neighbor);
}
}
// 如果没有有效邻域解,返回所有邻域解
if (validNeighbors.isEmpty()) {
return neighbors;
}
return validNeighbors;
}
/**
* 检查解是否在禁忌表中
*/
private boolean isTabu(Chromosome chromosome) {
for (Chromosome tabuChromosome : tabuList) {
if (chromosome.getGeneStr().equals(tabuChromosome.getGeneStr())) {
return true;
}
}
return false;
}
/**
* 添加解到禁忌表
*/
private void addToTabuList(Chromosome chromosome) {
tabuList.add(chromosome);
if (tabuList.size() > tabuListSize) {
tabuList.remove(0);
}
}
/**
* 生成交换邻域解
*/
private Chromosome generateSwapNeighbor(Chromosome chromosome) {
Chromosome neighbor = ProductionDeepCopyUtil.deepCopy(chromosome, Chromosome.class);
List<Integer> os = neighbor.getOperationSequencing();
if (os.size() >= 2) {
int idx1 = rnd.nextInt(os.size());
int idx2 = rnd.nextInt(os.size());
while (idx2 == idx1) {
idx2 = rnd.nextInt(os.size());
}
Collections.swap(os, idx1, idx2);
neighbor.setOperationSequencing(os);
}
return neighbor;
}
/**
* 生成反转邻域解
*/
private Chromosome generateReverseNeighbor(Chromosome chromosome) {
Chromosome neighbor = ProductionDeepCopyUtil.deepCopy(chromosome, Chromosome.class);
List<Integer> os = neighbor.getOperationSequencing();
if (os.size() >= 2) {
int start = rnd.nextInt(os.size());
int end = rnd.nextInt(os.size());
while (end <= start) {
end = rnd.nextInt(os.size());
}
Collections.reverse(os.subList(start, end + 1));
neighbor.setOperationSequencing(os);
}
return neighbor;
}
/**
* 生成插入邻域解
*/
private Chromosome generateInsertNeighbor(Chromosome chromosome) {
Chromosome neighbor = ProductionDeepCopyUtil.deepCopy(chromosome, Chromosome.class);
List<Integer> os = neighbor.getOperationSequencing();
if (os.size() >= 2) {
int idx1 = rnd.nextInt(os.size());
int idx2 = rnd.nextInt(os.size());
while (idx2 == idx1) {
idx2 = rnd.nextInt(os.size());
}
int value = os.remove(idx1);
os.add(idx2, value);
neighbor.setOperationSequencing(os);
}
return neighbor;
}
/**
* 生成机器选择邻域解
*/
private Chromosome generateMachineChangeNeighbor(Chromosome chromosome) {
Chromosome neighbor = ProductionDeepCopyUtil.deepCopy(chromosome, Chromosome.class);
List<Integer> ms = neighbor.getMachineSelection();
if (!ms.isEmpty()) {
int idx = rnd.nextInt(ms.size());
GlobalOperationInfo globalOp = globalOpList.get(idx);
Entry op = globalOp.getOp();
if (op.getMachineOptions().size() > 1) {
int currentMachineSeq = ms.get(idx);
List<Integer> availableMachines = new ArrayList<>();
for (int i = 1; i <= op.getMachineOptions().size(); i++) {
if (i != currentMachineSeq) {
availableMachines.add(i);
}
}
if (!availableMachines.isEmpty()) {
int newMachineSeq = availableMachines.get(rnd.nextInt(availableMachines.size()));
ms.set(idx, newMachineSeq);
neighbor.setMachineSelection(ms);
}
}
}
return neighbor;
}
/**
* 解码染色体
*/
private void decode(GeneticDecoder decoder, Chromosome chromosome, ScheduleParams param) {
chromosome.setResult(new java.util.concurrent.CopyOnWriteArrayList<>());
decoder.decodeChromosomeWithCache(chromosome);
if (chromosome.getFitness() == 0) {
chromosome.setFitness(fitnessCalculator.calculateFitness(chromosome, objectiveWeights));
}
}
/**
* 比较两个染色体的优劣
*/
private boolean isBetter(Chromosome c1, Chromosome c2) {
return c1.getFitness() > c2.getFitness();
}
}
\ No newline at end of file
...@@ -132,7 +132,7 @@ public class SceneService { ...@@ -132,7 +132,7 @@ public class SceneService {
try { try {
ObjectMapper objectMapper = createObjectMapper(); ObjectMapper objectMapper = createObjectMapper();
SceneChromsome sceneChromsome=(SceneChromsome)redisUtils.get("SceneId."+sceneId); SceneChromsome sceneChromsome=null;//(SceneChromsome)redisUtils.get("SceneId."+sceneId);
if(sceneChromsome==null) if(sceneChromsome==null)
{ {
sceneChromsome=new SceneChromsome(); sceneChromsome=new SceneChromsome();
...@@ -163,7 +163,7 @@ public class SceneService { ...@@ -163,7 +163,7 @@ public class SceneService {
sceneChromsome.getSceneDetails().add(sceneDetail); sceneChromsome.getSceneDetails().add(sceneDetail);
redisUtils.set("SceneId."+sceneId,sceneChromsome); // redisUtils.set("SceneId."+sceneId,sceneChromsome);
File file = getChromosomeFile(sceneId,sceneChromsome.getVersion().toString()); File file = getChromosomeFile(sceneId,sceneChromsome.getVersion().toString());
......
...@@ -39,7 +39,8 @@ public class PlanResultServiceTest { ...@@ -39,7 +39,8 @@ public class PlanResultServiceTest {
// TestSortService sortService=new TestSortService(); // TestSortService sortService=new TestSortService();
// sortService.test1(); // sortService.test1();
// nsgaiiUtils.Test(); // nsgaiiUtils.Test();
planResultService.execute2("0428340BB4F540938F1FB5599F03E8A4");//2000 planResultService.execute2("08B1D87FE1B84ECDBAC2E546DDB6FB81");//2000
// planResultService.execute2("0428340BB4F540938F1FB5599F03E8A4");//2000
// planResultService.execute2("C8B533BD8944405B9A2F8823C575C204");//500 // planResultService.execute2("C8B533BD8944405B9A2F8823C575C204");//500
// planResultService.execute2("EFDD34E4B5BC434BAEAE6A84DFCD4E7B");//20 // planResultService.execute2("EFDD34E4B5BC434BAEAE6A84DFCD4E7B");//20
// planResultService.execute2("00E0C5D3E4AD4F36B56C39395906618D"); // planResultService.execute2("00E0C5D3E4AD4F36B56C39395906618D");
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment