Commit ae62deba authored by Tong Li's avatar Tong Li

bom

parent 653269ef
...@@ -18,11 +18,10 @@ public class BOMBuildResult { ...@@ -18,11 +18,10 @@ public class BOMBuildResult {
private List<Machine> newMachines; private List<Machine> newMachines;
public BOMBuildResult(List<OrderMaterialRequirement> materialRequirements, List<Order> childOrders,List<Entry> newentrys,List<Machine> newMachines) { public BOMBuildResult(List<OrderMaterialRequirement> materialRequirements, List<Order> childOrders,List<Entry> newentrys) {
this.materialRequirements = materialRequirements; this.materialRequirements = materialRequirements;
this.childOrders = childOrders; this.childOrders = childOrders;
this.newentrys=newentrys; this.newentrys=newentrys;
this.newMachines=newMachines;
} }
public List<OrderMaterialRequirement> getMaterialRequirements() { public List<OrderMaterialRequirement> getMaterialRequirements() {
......
...@@ -3,15 +3,14 @@ package com.aps.entity.Algorithm; ...@@ -3,15 +3,14 @@ package com.aps.entity.Algorithm;
import com.aps.entity.Algorithm.IDAndChildID.GroupResult; import com.aps.entity.Algorithm.IDAndChildID.GroupResult;
import com.aps.entity.basic.Entry; import com.aps.entity.basic.Entry;
import com.aps.entity.basic.Machine; import com.aps.entity.basic.Machine;
import com.aps.entity.basic.Material;
import com.aps.entity.basic.Order; import com.aps.entity.basic.Order;
import lombok.Data; import lombok.Data;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.*;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors; import java.util.stream.Collectors;
...@@ -24,6 +23,8 @@ public class Chromosome { ...@@ -24,6 +23,8 @@ public class Chromosome {
private String ID = UUID.randomUUID().toString(); private String ID = UUID.randomUUID().toString();
private Integer version=0; private Integer version=0;
/// <summary> /// <summary>
...@@ -41,28 +42,44 @@ public class Chromosome { ...@@ -41,28 +42,44 @@ public class Chromosome {
/// </summary> /// </summary>
private String geneStr; private String geneStr;
public void setMachineSelection(List<Integer> val) { public String getGeneStr() {
machineSelection = val; geneStr=getMachineStr()+"_"+getOperationStr();
machineStr = machineSelection.stream() return geneStr;
.map(String::valueOf) // 将每个 Integer 转换为 String }
private Integer gsOrls=0;
public String getMachineStr() {
machineStr= Optional.ofNullable(machineSelection)
.orElse(Collections.emptyList())
.stream()
.map(String::valueOf) // Integer转String
.collect(Collectors.joining(","));
return machineStr;
}
public String getOperationStr() {
operationStr= Optional.ofNullable(operationSequencing)
.orElse(Collections.emptyList())
.stream()
.map(String::valueOf) // Integer转String
.collect(Collectors.joining(",")); .collect(Collectors.joining(","));
geneStr=machineStr+ "_" +operationStr; return operationStr;
} }
/// <summary> /// <summary>
/// 工序排序部分(工件/订单ID) /// 工序排序部分(工件/订单ID)
/// </summary> /// </summary>
private List<Integer> operationSequencing; private List<Integer> operationSequencing;
public void setOperationSequencing(List<Integer> val) {
operationSequencing = val;
operationStr = operationSequencing.stream()
.map(String::valueOf) // 将每个 Integer 转换为 String
.collect(Collectors.joining(","));
geneStr=machineStr+ "_" +operationStr;
}
/// <summary> /// <summary>
/// 工序排序部分(工件/订单ID) /// 工序排序部分(工件/订单ID)
...@@ -74,15 +91,17 @@ public class Chromosome { ...@@ -74,15 +91,17 @@ public class Chromosome {
private List<GlobalOperationInfo> globalOpList; private List<GlobalOperationInfo> globalOpList;
private List<Entry> allOperations; private CopyOnWriteArrayList<Entry> allOperations;
private List<Order> orders; private CopyOnWriteArrayList<Order> orders;
private List<Machine> InitMachines; private List<Machine> InitMachines;
private List<OrderMaterialRequirement> orderMaterials; private List<OrderMaterialRequirement> orderMaterials;
private List<GroupResult> OperatRel; private CopyOnWriteArrayList<GroupResult> OperatRel;
private ObjectiveWeights objectiveWeights; private ObjectiveWeights objectiveWeights;
List<Material> materials;
/* /*
* 最早完工时间(最小化) 最小化总加工时间 最小总换型时间 * 最早完工时间(最小化) 最小化总加工时间 最小总换型时间
*/ */
...@@ -147,7 +166,7 @@ public class Chromosome { ...@@ -147,7 +166,7 @@ public class Chromosome {
private String ScenarioName; private String ScenarioName;
private LocalDateTime BaseTime ; // 当前基准时间 private LocalDateTime BaseTime ; // 当前基准时间
private List<Integer> reOrderids=new ArrayList<>();
// //
// //最大设备利用率 // //最大设备利用率
......
...@@ -38,6 +38,8 @@ public class GAScheduleResult { ...@@ -38,6 +38,8 @@ public class GAScheduleResult {
private int changeOverTime; private int changeOverTime;
private int preTime; private int preTime;
private int seq; //工序顺序 private int seq; //工序顺序
private int bomTime;//物料齐套时间
private List<Integer> TargetFinishedOperationId;
public int getFlowTime() { public int getFlowTime() {
return EndTime - StartTime; return EndTime - StartTime;
......
...@@ -23,7 +23,7 @@ public class OrderMaterialRequirement { ...@@ -23,7 +23,7 @@ public class OrderMaterialRequirement {
private String materialCode; private String materialCode;
private String materialName; private String materialName;
private String materialTypeName; private String materialTypeName;
private String bomId;
/** /**
* 物料类型 * 物料类型
*/ */
...@@ -92,7 +92,35 @@ public class OrderMaterialRequirement { ...@@ -92,7 +92,35 @@ public class OrderMaterialRequirement {
/** /**
* 检验周期 * 检验周期
*/ */
private Long checkLeadTime; private Integer checkLeadTime;
/**
* 采购周期
*/
@TableField(exist = false)
private Integer purchaseTime;
/**
* 单价
*/
@TableField(exist = false)
private BigDecimal price;
@TableField(exist = false) @TableField(exist = false)
private List<OrderMaterialRequirement> replaceMaterial=new ArrayList<>(); private List<OrderMaterialRequirement> replaceMaterial=new ArrayList<>();
@TableField(exist = false)
private double mainQty;
/**
* 物料需求数量
*/
@TableField(exist = false)
private double spentQty;
/**
* 计划数量
*/
@TableField(exist = false)
public double Quantity;
} }
package com.aps.entity; package com.aps.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data; import lombok.Data;
import java.math.BigDecimal; import java.math.BigDecimal;
...@@ -24,7 +25,7 @@ private String storeCode; ...@@ -24,7 +25,7 @@ private String storeCode;
private String storeName; private String storeName;
private double total; private double total;
private Integer measureUnit; private Integer measureUnit;
private BigDecimal totalLock; private double totalLock;
private BigDecimal cost; private BigDecimal cost;
private LocalDateTime productionDate; private LocalDateTime productionDate;
private LocalDateTime expiryDate; private LocalDateTime expiryDate;
...@@ -37,4 +38,16 @@ private String supplierCode; ...@@ -37,4 +38,16 @@ private String supplierCode;
private String supplierName; private String supplierName;
private Short warehousingUnitId; private Short warehousingUnitId;
private String warehousingUnitName; private String warehousingUnitName;
/*已用库存数*/
@TableField(exist = false)
private double usedInventory;
/*可用库存数*/
@TableField(exist = false)
private double availableInventory;
public double getAvailableInventory(){
return total-totalLock-usedInventory;
};
} }
\ No newline at end of file
...@@ -2,6 +2,7 @@ package com.aps.entity.basic; ...@@ -2,6 +2,7 @@ package com.aps.entity.basic;
import com.aps.entity.Algorithm.OperationDependency; import com.aps.entity.Algorithm.OperationDependency;
import com.aps.entity.Algorithm.OrderMaterialRequirement;
import com.aps.entity.RoutingDiscreteParam; import com.aps.entity.RoutingDiscreteParam;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
...@@ -72,7 +73,7 @@ public class Entry { ...@@ -72,7 +73,7 @@ public class Entry {
/** /**
* 基因编号 * 基因编号
*/ */
public Double Quantity; public double Quantity;
/** /**
* 工序顺序 * 工序顺序
*/ */
...@@ -110,7 +111,10 @@ public class Entry { ...@@ -110,7 +111,10 @@ public class Entry {
/** /**
* 所需物料 * 所需物料
*/ */
public List<MaterialRequirement> MaterialRequirements ; // 所需物料 public List<OrderMaterialRequirement> MaterialRequirements ; // 所需物料
/** /**
* 设备资源组 * 设备资源组
*/ */
...@@ -129,7 +133,7 @@ public class Entry { ...@@ -129,7 +133,7 @@ public class Entry {
/// </summary> /// </summary>
public List<Integer> TargetFinishedOperationId; public List<Integer> TargetFinishedOperationId;
private boolean newCreate = false; public boolean newCreate = false;
/// <summary> /// <summary>
/// 半成品最晚完工时间(即成品工序开始时间-1天) /// 半成品最晚完工时间(即成品工序开始时间-1天)
......
package com.aps.service.Algorithm;
/**
* 作者:佟礼
* 时间:2026-01-27
*/
public class DataNode {
int id;
Integer time;
Integer groupId;
int no;
public DataNode(int id, Integer time, int groupId, int no) {
this.id = id;
this.time = time;
this.groupId = groupId;
this.no = no;
}
public int getGroupId() { return groupId; }
public long getTime() { return time; }
public int getNo() { return no; }
@Override
public String toString() {
return String.format("%d\t%d\t%d\t%d", id, time, groupId, no);
}
}
...@@ -14,7 +14,9 @@ import org.springframework.beans.factory.annotation.Autowired; ...@@ -14,7 +14,9 @@ import org.springframework.beans.factory.annotation.Autowired;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.*; import java.util.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.IntStream;
/** /**
* 作者:佟礼 * 作者:佟礼
...@@ -126,7 +128,7 @@ public class GeneticAlgorithm { ...@@ -126,7 +128,7 @@ public class GeneticAlgorithm {
{ {
best.setBaseTime(param.getBaseTime()); best.setBaseTime(param.getBaseTime());
best.setOrderMaterials(orderMaterials); best.setOrderMaterials(orderMaterials);
best.setOperatRel(_entryRel); // best.setOperatRel(_entryRel);
if(best.getInitMachines()==null) if(best.getInitMachines()==null)
{ {
...@@ -266,7 +268,7 @@ public class GeneticAlgorithm { ...@@ -266,7 +268,7 @@ public class GeneticAlgorithm {
FileHelper.writeLogFile("迭代进化-----------结束-------"); FileHelper.writeLogFile("迭代进化-----------结束-------");
best.setBaseTime(param.getBaseTime()); best.setBaseTime(param.getBaseTime());
best.setOrderMaterials(orderMaterials); best.setOrderMaterials(orderMaterials);
best.setOperatRel(_entryRel); // best.setOperatRel(_entryRel);
if(best.getInitMachines()==null) if(best.getInitMachines()==null)
{ {
...@@ -302,6 +304,7 @@ public class GeneticAlgorithm { ...@@ -302,6 +304,7 @@ public class GeneticAlgorithm {
return population; return population;
} }
population = population.stream() population = population.stream()
.filter(chromosome -> chromosome != null && chromosome.getGeneStr() != null)
.collect(Collectors.toMap( .collect(Collectors.toMap(
Chromosome::getGeneStr, // key:去重的字段(GeneStr) Chromosome::getGeneStr, // key:去重的字段(GeneStr)
u -> u, // value:Chromosome对象 u -> u, // value:Chromosome对象
...@@ -371,7 +374,7 @@ return population; ...@@ -371,7 +374,7 @@ return population;
FileHelper.writeLogFile("解码---------------"+population.size() ); FileHelper.writeLogFile("解码---------------"+population.size() );
GeneticDecoder decoder = new GeneticDecoder(_GlobalParam, param.getBaseTime(), machines, orders, materials, machineScheduler,materialRequirementService, sceneId); GeneticDecoder decoder = new GeneticDecoder(_GlobalParam, param.getBaseTime(), machines, orders, materials, machineScheduler,materialRequirementService, sceneId);
boolean ismore=true; boolean ismore=false;
if(ismore) { if(ismore) {
CompletableFuture.allOf(population.stream() CompletableFuture.allOf(population.stream()
.map(chromosome -> CompletableFuture.runAsync(() -> decode(decoder, chromosome, param, allOperations, globalOpList), decodeExecutor)) .map(chromosome -> CompletableFuture.runAsync(() -> decode(decoder, chromosome, param, allOperations, globalOpList), decodeExecutor))
...@@ -380,7 +383,7 @@ return population; ...@@ -380,7 +383,7 @@ return population;
} else { } else {
if (population != null && population.size() > 0) { if (population != null && population.size() > 0) {
population.parallelStream().forEach(chromosome -> { population.forEach(chromosome -> {
decode(decoder, chromosome, param, allOperations, globalOpList); decode(decoder, chromosome, param, allOperations, globalOpList);
}); });
} }
...@@ -401,8 +404,11 @@ return population; ...@@ -401,8 +404,11 @@ return population;
// 假设Machine类有拷贝方法,或使用MapStruct等工具进行映射 // 假设Machine类有拷贝方法,或使用MapStruct等工具进行映射
chromosome.setMachines(ProductionDeepCopyUtil.deepCopyList(machines,Machine.class)); // 简单拷贝,实际可能需要深拷贝 chromosome.setMachines(ProductionDeepCopyUtil.deepCopyList(machines,Machine.class)); // 简单拷贝,实际可能需要深拷贝
chromosome.setOrders(ProductionDeepCopyUtil.deepCopyList(new CopyOnWriteArrayList<>(orders), Order.class) ); // 简单拷贝,实际可能需要深拷贝
chromosome.setOperatRel(ProductionDeepCopyUtil.deepCopyList(new CopyOnWriteArrayList<>(_entryRel), GroupResult.class) ); // 简单拷贝,实际可能需要深拷贝
chromosome.setMaterials(ProductionDeepCopyUtil.deepCopyList(materials,Material.class)); // 简单拷贝,实际可能需要深拷贝
chromosome.setAllOperations(allOperations); // 简单拷贝,实际可能需要深拷贝 chromosome.setAllOperations(ProductionDeepCopyUtil.deepCopyList(new CopyOnWriteArrayList<>(allOperations), Entry.class) ); // 简单拷贝,实际可能需要深拷贝
chromosome.setGlobalOpList(globalOpList); // 简单拷贝,实际可能需要深拷贝 chromosome.setGlobalOpList(globalOpList); // 简单拷贝,实际可能需要深拷贝
//chromosome.setObjectiveWeights(_objectiveWeights); //chromosome.setObjectiveWeights(_objectiveWeights);
chromosome.setBaseTime(param.getBaseTime()); chromosome.setBaseTime(param.getBaseTime());
...@@ -415,4 +421,6 @@ return population; ...@@ -415,4 +421,6 @@ return population;
} }
} }
} }
...@@ -5,8 +5,10 @@ import com.aps.entity.Algorithm.*; ...@@ -5,8 +5,10 @@ import com.aps.entity.Algorithm.*;
import com.aps.entity.basic.Entry; import com.aps.entity.basic.Entry;
import com.aps.entity.basic.GlobalParam; import com.aps.entity.basic.GlobalParam;
import com.aps.entity.basic.MachineOption; import com.aps.entity.basic.MachineOption;
import com.aps.entity.basic.Order;
import java.util.*; import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.IntStream; import java.util.stream.IntStream;
...@@ -132,7 +134,11 @@ public class GeneticOperations { ...@@ -132,7 +134,11 @@ public class GeneticOperations {
// 重载,使用默认锦标赛大小3 // 重载,使用默认锦标赛大小3
public List<Chromosome> tournamentSelection(List<Chromosome> population) { public List<Chromosome> tournamentSelection(List<Chromosome> population) {
return tournamentSelection(population, param.getTournamentSize());
List<Chromosome> populationn= ProductionDeepCopyUtil.deepCopyList(tournamentSelection(population, param.getTournamentSize()),Chromosome.class);
populationn.parallelStream().forEach(t->DelOrder(t));
return populationn;
} }
/** /**
...@@ -414,6 +420,49 @@ public class GeneticOperations { ...@@ -414,6 +420,49 @@ public class GeneticOperations {
return indexWeights.get(CommonCalculator.getOsIndex(indexWeights)); return indexWeights.get(CommonCalculator.getOsIndex(indexWeights));
} }
public void DelOrder(Chromosome chromosome) {
List<Entry> allOperations = chromosome.getAllOperations();
List<GlobalOperationInfo> globalOpList= chromosome.getGlobalOpList();
List<Order> orders = chromosome.getOrders();
List<Integer> OperationSequencing= chromosome.getOperationSequencing();
List<GAScheduleResult> ScheduleResults = chromosome.getResult();
List<Integer> newoorderids= orders.stream()
.filter(t->t.isNewCreate())
.map(Order::getId)
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
if(newoorderids!=null&&newoorderids.size()>0) {
for (Integer id : newoorderids) {
List<Entry> sourceOps = allOperations.stream()
.filter(o -> o.getGroupId()==id)
.sorted(Comparator.comparing(Entry::getSequence))
.collect(Collectors.toList());
for (Entry entry : sourceOps) {
OptionalInt index1 = IntStream.range(0, globalOpList.size())
.filter(h -> entry.getId()==globalOpList.get(h).getOp().getId())
.findFirst();
globalOpList.remove((int)index1.orElse(0));
chromosome.getMachineSelection().remove((int)index1.orElse(0));
}
chromosome.getOperatRel().remove(id-1);
}
allOperations.removeIf(t ->newoorderids.contains(t.getGroupId()));
OperationSequencing.removeIf(t ->newoorderids.contains(t));
AtomicInteger globalOpId = new AtomicInteger(0);
globalOpList.forEach(t-> {
t.setGlobalOpId(globalOpId.getAndIncrement());
});
orders.removeIf(t ->newoorderids.contains(t.getId()));
}
}
} }
...@@ -8,6 +8,7 @@ import com.aps.entity.Algorithm.ScheduleParams; ...@@ -8,6 +8,7 @@ import com.aps.entity.Algorithm.ScheduleParams;
import com.aps.entity.basic.*; import com.aps.entity.basic.*;
import java.util.*; import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.IntStream; import java.util.stream.IntStream;
...@@ -25,6 +26,10 @@ public class Initialization { ...@@ -25,6 +26,10 @@ public class Initialization {
private ObjectiveWeights _objectiveWeights = new ObjectiveWeights(); private ObjectiveWeights _objectiveWeights = new ObjectiveWeights();
public Initialization() {
}
public Initialization(GlobalParam globalParam,List<Entry> allOperations,List<Order> _orders,List<Machine> _machines,ObjectiveWeights objectiveWeights) { public Initialization(GlobalParam globalParam,List<Entry> allOperations,List<Order> _orders,List<Machine> _machines,ObjectiveWeights objectiveWeights) {
Initialization.allOperations = allOperations; Initialization.allOperations = allOperations;
_globalParam= globalParam; _globalParam= globalParam;
...@@ -66,14 +71,17 @@ int populationSize=param.getPopulationSize(); ...@@ -66,14 +71,17 @@ int populationSize=param.getPopulationSize();
Chromosome chromo = new Chromosome(); // 初始化染色体 Chromosome chromo = new Chromosome(); // 初始化染色体
// chromo.setObjectiveWeights(_objectiveWeights); // chromo.setObjectiveWeights(_objectiveWeights);
// chromo.setInitMachines(ProductionDeepCopyUtil.deepCopyList(machines)); // chromo.setInitMachines(ProductionDeepCopyUtil.deepCopyList(machines));
chromo.setOrders(orders); chromo.setOrders(new CopyOnWriteArrayList<>(orders));
// 全局选择(GS):按GlobalOpId顺序生成MachineSelection // 全局选择(GS):按GlobalOpId顺序生成MachineSelection
if (i < gsCount) { if (i < gsCount) {
chromo.setGsOrls(1);
generateGSChromosome(chromo,globalOpList); // 对应 C# GenerateGSChromosome generateGSChromosome(chromo,globalOpList); // 对应 C# GenerateGSChromosome
} else if (i < lsCount) { } else if (i < lsCount) {
chromo.setGsOrls(2);
// 局部选择(LS):按GlobalOpId顺序生成MachineSelection(仅负载计算范围不同) // 局部选择(LS):按GlobalOpId顺序生成MachineSelection(仅负载计算范围不同)
generateLSChromosome(chromo,globalOpList); generateLSChromosome(chromo,globalOpList);
} else { } else {
chromo.setGsOrls(3);
// 随机选择(RS):按GlobalOpId顺序生成MachineSelection(仅机器选择随机) // 随机选择(RS):按GlobalOpId顺序生成MachineSelection(仅机器选择随机)
generateRSChromosome(chromo,globalOpList); generateRSChromosome(chromo,globalOpList);
} }
...@@ -87,6 +95,31 @@ chromo.setOrders(orders); ...@@ -87,6 +95,31 @@ chromo.setOrders(orders);
return population; return population;
} }
public List<Chromosome> generateInitialSFPopulation(Chromosome chromo, List<GlobalOperationInfo> globalOpList) {
List<Chromosome> population = new ArrayList<>();
// 并行循环:对应 Parallel.For(0, PopulationSize, i => { ... })
if (chromo.getGsOrls()==1) {
generateGSChromosome(chromo,globalOpList); // 对应 C# GenerateGSChromosome
} else if (chromo.getGsOrls()==2) {
// 局部选择(LS):按GlobalOpId顺序生成MachineSelection(仅负载计算范围不同)
generateLSChromosome(chromo,globalOpList);
} else {
// 随机选择(RS):按GlobalOpId顺序生成MachineSelection(仅机器选择随机)
generateRSChromosome(chromo,globalOpList);
}
return population;
}
/** /**
* 全局选择(GS)生成染色体(按GlobalOpId顺序生成MachineSelection) * 全局选择(GS)生成染色体(按GlobalOpId顺序生成MachineSelection)
*/ */
...@@ -145,9 +178,17 @@ chromo.setOrders(orders); ...@@ -145,9 +178,17 @@ chromo.setOrders(orders);
osp.clear(); osp.clear();
} }
if(chromosome.getOperationSequencing()!=null&&chromosome.getOperationSequencing().size()>0)
{
chromosome.getOperationSequencing().addAll(os);
chromosome.getMachineSelection().addAll(ms);
}else {
// 步骤2:打乱工序排序部分(OS) // 步骤2:打乱工序排序部分(OS)
chromosome.setOperationSequencing(shuffleWithPriority(os)); chromosome.setOperationSequencing(shuffleWithPriority(os));
chromosome.setMachineSelection(ms); chromosome.setMachineSelection(ms);
}
return chromosome; return chromosome;
} }
...@@ -215,9 +256,15 @@ chromo.setOrders(orders); ...@@ -215,9 +256,15 @@ chromo.setOrders(orders);
os.addAll(osp); os.addAll(osp);
osp.clear(); osp.clear();
} }
if(chromosome.getOperationSequencing()!=null&&chromosome.getOperationSequencing().size()>0)
{
chromosome.getOperationSequencing().addAll(os);
chromosome.getMachineSelection().addAll(ms);
}else {
chromosome.setOperationSequencing(shuffleWithPriority(os)); chromosome.setOperationSequencing(shuffleWithPriority(os));
chromosome.setMachineSelection(ms); chromosome.setMachineSelection(ms);
}
return chromosome; return chromosome;
} }
...@@ -259,9 +306,15 @@ chromo.setOrders(orders); ...@@ -259,9 +306,15 @@ chromo.setOrders(orders);
os.addAll(osp); os.addAll(osp);
osp.clear(); osp.clear();
} }
if(chromosome.getOperationSequencing()!=null&&chromosome.getOperationSequencing().size()>0)
{
chromosome.getOperationSequencing().addAll(os);
chromosome.getMachineSelection().addAll(ms);
}else {
chromosome.setOperationSequencing(shuffleWithPriority(os)); chromosome.setOperationSequencing(shuffleWithPriority(os));
chromosome.setMachineSelection(ms); chromosome.setMachineSelection(ms);
}
return chromosome; return chromosome;
} }
......
...@@ -594,7 +594,7 @@ if(targetOp.getSequence()>1) { ...@@ -594,7 +594,7 @@ if(targetOp.getSequence()>1) {
OperatRels = IdGroupingWithDualSerial.addNode(OperatRels, targetGroupIndex, newId, newParentIds, newChildIds,targetOp.getExecId()); OperatRels = IdGroupingWithDualSerial.addNode(OperatRels, targetGroupIndex, newId, newParentIds, newChildIds,targetOp.getExecId());
} }
} }
chromosome.setOperatRel(OperatRels); chromosome.setOperatRel(new CopyOnWriteArrayList<>(OperatRels) );
//当前组的 //当前组的
groupResult = OperatRels.get(targetGroupIndex); groupResult = OperatRels.get(targetGroupIndex);
...@@ -796,7 +796,7 @@ if(targetOp.getSequence()>1) { ...@@ -796,7 +796,7 @@ if(targetOp.getSequence()>1) {
// 添加新数据 // 添加新数据
OperatRels = IdGroupingWithDualSerial.addNewDataWithIsolatedGroup(OperatRels, newIdList, newChildIdList); OperatRels = IdGroupingWithDualSerial.addNewDataWithIsolatedGroup(OperatRels, newIdList, newChildIdList);
chromosome.setOperatRel(OperatRels); chromosome.setOperatRel(new CopyOnWriteArrayList<>(OperatRels) );
//全局ID //全局ID
int globalOpId = chromosome.getGlobalOpList().stream() int globalOpId = chromosome.getGlobalOpList().stream()
.mapToInt(GlobalOperationInfo::getGlobalOpId) .mapToInt(GlobalOperationInfo::getGlobalOpId)
...@@ -983,7 +983,7 @@ if(targetOp.getSequence()>1) { ...@@ -983,7 +983,7 @@ if(targetOp.getSequence()>1) {
List<GroupResult> OperatRels = chromosome.getOperatRel(); List<GroupResult> OperatRels = chromosome.getOperatRel();
OperatRels = IdGroupingWithDualSerial.deleteNodeByGlobalSerial(OperatRels, opId); OperatRels = IdGroupingWithDualSerial.deleteNodeByGlobalSerial(OperatRels, opId);
chromosome.setOperatRel(OperatRels); chromosome.setOperatRel(new CopyOnWriteArrayList<>(OperatRels) );
Entry targetOp = allOperations.stream() Entry targetOp = allOperations.stream()
.filter(o -> o.getId() == opId) .filter(o -> o.getId() == opId)
.findFirst() .findFirst()
......
package com.aps.service.Algorithm;
import java.util.*;
import java.util.stream.Collectors;
/**
* 作者:佟礼
* 时间:2026-01-27
*/
public class TestSortService {
public void test() {
List<DataNode> list = new ArrayList<>();
// 初始化数据
list.add(new DataNode(1, 18000, 1, 1));
list.add(new DataNode(2, 882000, 1, 2));
list.add(new DataNode(3, 2260078, 2, 1));
list.add(new DataNode(4, 2695678, 2, 2));
list.add(new DataNode(5, 0, 3, 1));
list.add(new DataNode(6, 950400, 3, 2));
list.add(new DataNode(7, 0, 4, 1));
list.add(new DataNode(8, 18000, 4, 2));
list.add(new DataNode(9, 3419998, 5, 1));
list.add(new DataNode(10, 1022646, 5, 2));
// 1. 预处理:计算每个 groupId 对应的最小时间(作为该组的排位基准)
Map<Integer, Long> groupMinTimeMap = list.stream()
.collect(Collectors.groupingBy(
DataNode::getGroupId,
Collectors.mapping(DataNode::getTime, Collectors.minBy(Long::compare))
))
.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().orElse(0L)));
// 2. 执行排序
list.sort((a, b) -> {
// 首先比较所属组的基准时间
long minTimeA = groupMinTimeMap.get(a.getGroupId());
long minTimeB = groupMinTimeMap.get(b.getGroupId());
if (minTimeA != minTimeB) {
return Long.compare(minTimeA, minTimeB);
}
// 如果基准时间相同(比如 group3 和 group4 都是 0),则按 groupId 排序(可选)
if (a.getGroupId() != b.getGroupId()) {
return Integer.compare(a.getGroupId(), b.getGroupId());
}
// 同一组内,按 no 升序
return Integer.compare(a.getNo(), b.getNo());
});
// 输出结果
System.out.println("ID\ttime\tgroupid\tno");
list.forEach(System.out::println);
}
public static List<DataNode> customSort(List<DataNode> dataList) {
// 按groupId分组
Map<Integer, List<DataNode>> groupMap = dataList.stream()
.collect(Collectors.groupingBy(data -> data.groupId));
// 对每个组内的数据按no升序排序
groupMap.values().forEach(group ->
group.sort(Comparator.comparingInt(data -> data.no))
);
// 计算每个组的最小时间(用于组间排序)
Map<Integer, Long> groupMinTime = new HashMap<>();
for (Map.Entry<Integer, List<DataNode>> entry : groupMap.entrySet()) {
long minTime = entry.getValue().stream()
.mapToLong(data -> data.time)
.min()
.orElse(Long.MAX_VALUE);
groupMinTime.put(entry.getKey(), minTime);
}
// 将组按最小时间排序,然后展开
return groupMap.entrySet().stream()
.sorted(Map.Entry.comparingByValue((list1, list2) ->
Long.compare(groupMinTime.get(list1.get(0).groupId),
groupMinTime.get(list2.get(0).groupId))))
.flatMap(entry -> entry.getValue().stream())
.collect(Collectors.toList());
}
// 更简洁的写法
public static List<DataNode> customSort2(List<DataNode> dataList) {
// 按groupId分组并在组内按no排序
Map<Integer, List<DataNode>> groupMap = dataList.stream()
.collect(Collectors.groupingBy(
data -> data.groupId,
Collectors.collectingAndThen(
Collectors.toList(),
list -> {
list.sort(Comparator.comparingInt(d -> d.no));
return list;
}
)
));
// 将组转为列表并按组内最小时间排序
List<List<DataNode>> sortedGroups = new ArrayList<>(groupMap.values());
sortedGroups.sort(Comparator.comparing(
group -> group.stream().mapToLong(d -> d.time).min().orElse(Long.MAX_VALUE)
));
// 展开所有组
return sortedGroups.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
}
public static List<DataNode> sortData(List<DataNode> data) {
// 步骤1: 找出每个groupid的最小time
Map<Integer, Integer> groupMinTime = data.stream()
.collect(Collectors.groupingBy(
item -> item.groupId,
Collectors.mapping(item -> item.time,
Collectors.collectingAndThen(
Collectors.toList(),
list -> list.stream().min(Integer::compareTo).orElse(0)
))
));
// 步骤2: 按照以下规则排序
List<DataNode> sorted = new ArrayList<>(data);
sorted.sort((a, b) -> {
int aMinTime = groupMinTime.get(a.groupId);
int bMinTime = groupMinTime.get(b.groupId);
// 首先按照group的最小time排序
if (aMinTime != bMinTime) {
return Integer.compare(aMinTime, bMinTime);
}
// 如果group最小time相同,按groupid排序
if (a.groupId != b.groupId) {
return Integer.compare(a.groupId, b.groupId);
}
// 同一个group内,按no排序
return Integer.compare(a.no, b.no);
});
return sorted;
}
public void test1() {
// 创建测试数据
List<DataNode> originalData = Arrays.asList(
new DataNode(1, 18000, 1, 1),
new DataNode(2, 882000, 1, 2),
new DataNode(3, 2260078, 2, 1),
new DataNode(4, 2695678, 2, 2),
new DataNode(5, 0, 3, 1),
new DataNode(6, 950400, 3, 2),
new DataNode(7, 0, 4, 1),
new DataNode(8, 18000, 4, 2),
new DataNode(9, 3419998, 5, 1),
new DataNode(10, 1022646, 5, 2)
);
System.out.println("排序前:");
originalData.forEach(System.out::println);
System.out.println("\n排序后:");
List<DataNode> sortedData = sortData(originalData);
sortedData.forEach(System.out::println);
}
}
package com.aps.service.impl; package com.aps.service.impl;
import com.aps.common.exception.SceneGenerationException; import com.aps.common.exception.SceneGenerationException;
import com.aps.common.util.GlobalCacheUtil;
import com.aps.common.util.R; import com.aps.common.util.R;
import com.aps.common.util.SnowFlackIdWorker; import com.aps.common.util.SnowFlackIdWorker;
import com.aps.entity.*; import com.aps.entity.*;
...@@ -27,6 +28,7 @@ import java.time.LocalDate; ...@@ -27,6 +28,7 @@ import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.LocalTime; import java.time.LocalTime;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static org.springframework.beans.BeanUtils.copyProperties; import static org.springframework.beans.BeanUtils.copyProperties;
...@@ -981,7 +983,30 @@ if (connection.getDestoperationid() !=null && connection.getSourceoperationid() ...@@ -981,7 +983,30 @@ if (connection.getDestoperationid() !=null && connection.getSourceoperationid()
return value; return value;
} }
private static final int cachetimeout= 60;
private List<Equiptype1> GetEquipTypes() {
List<Equiptype1> equipTypes=(List<Equiptype1>) GlobalCacheUtil.get("equipType");
if(equipTypes==null)
{
equipTypes = equiptype1Service.lambdaQuery().eq(Equiptype1::getIsdeleted, 0).list();
GlobalCacheUtil.put("equipType",equipTypes, cachetimeout, TimeUnit.MINUTES);
}
return equipTypes;
}
private List<PlanResource> GetPlanResources() {
List<PlanResource> list=(List<PlanResource>) GlobalCacheUtil.get("PlanResource");
if(list==null)
{
list = planResourceService.lambdaQuery()
.eq(PlanResource::getIsdeleted, 0)
.list();
GlobalCacheUtil.put("PlanResource",list, cachetimeout, TimeUnit.MINUTES);
}
return list;
}
/** /**
◦ 设备对照表 ◦ 设备对照表
...@@ -993,11 +1018,9 @@ if (connection.getDestoperationid() !=null && connection.getSourceoperationid() ...@@ -993,11 +1018,9 @@ if (connection.getDestoperationid() !=null && connection.getSourceoperationid()
// log.warn("工艺设备列表为空,跳过设备对照表生成"); // log.warn("工艺设备列表为空,跳过设备对照表生成");
// return null; // return null;
// } // }
List<Equiptype1> equipTypes = equiptype1Service.lambdaQuery().eq(Equiptype1::getIsdeleted, 0).list(); List<Equiptype1> equipTypes = GetEquipTypes();
List<PlanResource> list = planResourceService.lambdaQuery() List<PlanResource> list = GetPlanResources();
.eq(PlanResource::getIsdeleted, 0)
.list();
// 创建ProdEquipment列表 // 创建ProdEquipment列表
List<ProdEquipment> prodEquipments = new java.util.ArrayList<>(); List<ProdEquipment> prodEquipments = new java.util.ArrayList<>();
......
...@@ -31,6 +31,7 @@ import java.time.LocalTime; ...@@ -31,6 +31,7 @@ import java.time.LocalTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit; import java.time.temporal.ChronoUnit;
import java.util.*; import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.IntStream; import java.util.stream.IntStream;
...@@ -168,8 +169,10 @@ public class PlanResultService { ...@@ -168,8 +169,10 @@ public class PlanResultService {
List<GroupResult> entryRel=(List<GroupResult>)list.get(2); List<GroupResult> entryRel=(List<GroupResult>)list.get(2);
Map<Long,Double> machineIds=(Map<Long,Double>)list.get(3); Map<Long,Double> machineIds=(Map<Long,Double>)list.get(3);
Map<Integer,Object> reslte=materialRequirementService.preloadRoutingCache(SceneId,orders,Materials,globalParam.isIsCheckSf());
Map<Integer,Object> reslte=materialRequirementService.preloadRoutingCache(SceneId,param.getBaseTime(), orders,Materials,entrys,globalParam.isIsCheckSf());
List<Long> equipIDs=(List<Long>) reslte.get(1); List<Long> equipIDs=(List<Long>) reslte.get(1);
List<Material> Materials1=(List<Material>) reslte.get(2);
List<Long> machineIds1=machineIds.keySet().stream().collect(Collectors.toList()); List<Long> machineIds1=machineIds.keySet().stream().collect(Collectors.toList());
if(equipIDs!=null&&equipIDs.size()>0) if(equipIDs!=null&&equipIDs.size()>0)
...@@ -197,7 +200,7 @@ public class PlanResultService { ...@@ -197,7 +200,7 @@ public class PlanResultService {
// 5. 执行调度算法 // 5. 执行调度算法
GeneticAlgorithm scheduler =new GeneticAlgorithm(globalParam,machines,orders,Materials,machineScheduler,entryRel,materialRequirementService,_sceneService,SceneId); //new GeneticAlgorithm(products, machines, orders, machineScheduler); GeneticAlgorithm scheduler =new GeneticAlgorithm(globalParam,machines,orders,Materials1,machineScheduler,entryRel,materialRequirementService,_sceneService,SceneId); //new GeneticAlgorithm(products, machines, orders, machineScheduler);
param.initAdaptiveParams(entrys.size()); param.initAdaptiveParams(entrys.size());
double[] customWeights = new double[] { 0.4, 0.1, 0.1, 0.1, 0.3 }; // 延迟时间权重提升到0.5 double[] customWeights = new double[] { 0.4, 0.1, 0.1, 0.1, 0.3 }; // 延迟时间权重提升到0.5
//完工时间、总流程时间、总换型时间、机器负载标准差、延迟时间 //完工时间、总流程时间、总换型时间、机器负载标准差、延迟时间
...@@ -208,7 +211,7 @@ public class PlanResultService { ...@@ -208,7 +211,7 @@ public class PlanResultService {
kpiCalculator.calculatekpi(); kpiCalculator.calculatekpi();
_sceneService.saveChromosomeToFile(chromosome, SceneId); _sceneService.saveChromosomeToFile(chromosome, SceneId);
// WriteScheduleSummary(chromosome); WriteScheduleSummary(chromosome);
return chromosome; return chromosome;
...@@ -760,7 +763,7 @@ public class PlanResultService { ...@@ -760,7 +763,7 @@ public class PlanResultService {
kpiCalculator.calculatekpi(); kpiCalculator.calculatekpi();
chromosomes.setScenarioID(SceneId); chromosomes.setScenarioID(SceneId);
chromosomes.setBaseTime(param.getBaseTime()); chromosomes.setBaseTime(param.getBaseTime());
chromosomes.setOperatRel(entryRel); chromosomes.setOperatRel(new CopyOnWriteArrayList<>(entryRel));
// 保存chromosomes到文件 // 保存chromosomes到文件
_sceneService.saveChromosomeToFile(chromosomes, SceneId); _sceneService.saveChromosomeToFile(chromosomes, SceneId);
...@@ -799,21 +802,30 @@ public class PlanResultService { ...@@ -799,21 +802,30 @@ public class PlanResultService {
for (GAScheduleResult job : sortedJobs) { for (GAScheduleResult job : sortedJobs) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
String TargetFinishedOperationIds="";
if(job.getTargetFinishedOperationId()!=null)
{
TargetFinishedOperationIds= job.getTargetFinishedOperationId().stream()
.map(String::valueOf) // 把每个Integer转成String
.collect(Collectors.joining(","));
}
sb.append(String.format( sb.append(String.format(
"[%d-%d]:[%s-%s] Order %d,OrderID %s, Machine %d, Operation %d, Batch %.1f, processingTime %.1f, 前处理 %d, 后处理 %d, 离散参数 %d", "[%d-%d]:[%s-%s] Order %d,OrderID %s, Machine %d, Operation %d, Batch %.1f, processingTime %.1f, 前处理 %d, 后处理 %d, 离散参数 %d, bomtime %s,TargetOperationId %s",
job.getStartTime(), job.getStartTime(),
job.getEndTime(), job.getEndTime(),
ConvertTime(job.getStartTime()), ConvertTime(job.getStartTime()),
ConvertTime(job.getEndTime()), ConvertTime(job.getEndTime()),
job.getGroupId(), job.getGroupId(),
job.getOrderId(), job.getOrderId(),
job.getMachineId(), job.getMachineId(),
job.getOperationId(), job.getOperationId(),
job.getQuantity(), job.getQuantity(),
job.getProcessingTime(), job.getProcessingTime(),
job.getPreTime(), job.getPreTime(),
job.getTeardownTime(), job.getTeardownTime(),
job.getChangeOverTime() job.getChangeOverTime(),
ConvertTime(job.getBomTime()),
TargetFinishedOperationIds
)); ));
// 追加基因详情 // 追加基因详情
...@@ -1244,6 +1256,8 @@ private GlobalParam InitGlobalParam() ...@@ -1244,6 +1256,8 @@ private GlobalParam InitGlobalParam()
material.setId(m.getId()); material.setId(m.getId());
material.setMaterialType(m.getMaterialType()); material.setMaterialType(m.getMaterialType());
material.setMaterialTypeName(m.getMaterialTypeName()); material.setMaterialTypeName(m.getMaterialTypeName());
material.setCode(m.getCode());
material.setName(m.getName());
material.setCkeckLeadTime(m.getInspectDuration()); material.setCkeckLeadTime(m.getInspectDuration());
material.setPurchaseLeadTime(m.getPurchaseDuration()); material.setPurchaseLeadTime(m.getPurchaseDuration());
......
...@@ -10,8 +10,8 @@ spring: ...@@ -10,8 +10,8 @@ spring:
pathmatch: pathmatch:
matching-strategy: ant_path_matcher # Spring Boot 2.6+ 需要这个配置 matching-strategy: ant_path_matcher # Spring Boot 2.6+ 需要这个配置
redis: redis:
host: 192.168.0.181 host: 39.100.88.40
port: 6380 port: 6379
timeout: 120000 timeout: 120000
database: 10 database: 10
password: redis@228! password: redis@228!
...@@ -55,7 +55,7 @@ spring: ...@@ -55,7 +55,7 @@ spring:
# Oracle数据源 # Oracle数据源
oracle: oracle:
driver-class-name: oracle.jdbc.OracleDriver driver-class-name: oracle.jdbc.OracleDriver
url: jdbc:oracle:thin:@//192.168.0.181:1522/ORCLPDB1 # ORCL为你的Oracle实例名 url: jdbc:oracle:thin:@//39.100.78.207:7002/ORCLPDB1 # ORCL为你的Oracle实例名
username: mes # 替换为你的Oracle用户名 username: mes # 替换为你的Oracle用户名
password: root_mes123456 # 替换为你的Oracle密码 password: root_mes123456 # 替换为你的Oracle密码
# sqlserver: # sqlserver:
......
...@@ -8,6 +8,7 @@ import com.aps.entity.Gantt.ProductGanttVO; ...@@ -8,6 +8,7 @@ import com.aps.entity.Gantt.ProductGanttVO;
import com.aps.entity.basic.Machine; import com.aps.entity.basic.Machine;
import com.aps.entity.basic.MaintenanceWindow; import com.aps.entity.basic.MaintenanceWindow;
import com.aps.service.Algorithm.NSGAIIUtils; import com.aps.service.Algorithm.NSGAIIUtils;
import com.aps.service.Algorithm.TestSortService;
import com.aps.service.plan.PlanResultService; import com.aps.service.plan.PlanResultService;
import com.aps.service.plan.SceneService; import com.aps.service.plan.SceneService;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
...@@ -35,7 +36,8 @@ public class PlanResultServiceTest { ...@@ -35,7 +36,8 @@ public class PlanResultServiceTest {
// Chromosome chromosome= planResultService.moveChromosome("qwerty",3); // Chromosome chromosome= planResultService.moveChromosome("qwerty",3);
// planResultService.execute2("B7881EF032044B9BA4F6007875510B70"); // planResultService.execute2("B7881EF032044B9BA4F6007875510B70");
// NSGAIIUtils nsgaiiUtils=new NSGAIIUtils(); // NSGAIIUtils nsgaiiUtils=new NSGAIIUtils();
// TestSortService sortService=new TestSortService();
// sortService.test1();
// nsgaiiUtils.Test(); // nsgaiiUtils.Test();
planResultService.execute2("83D729F5E0694F25A71614B1991D7457"); planResultService.execute2("83D729F5E0694F25A71614B1991D7457");
// planResultService.execute2("726D4C1A712B4B1393175BD44B775B66"); // planResultService.execute2("726D4C1A712B4B1393175BD44B775B66");
...@@ -43,7 +45,7 @@ public class PlanResultServiceTest { ...@@ -43,7 +45,7 @@ public class PlanResultServiceTest {
// LocalDateTime t= LocalDateTime.of(2026, 02, 14, 1, 25, 52); // LocalDateTime t= LocalDateTime.of(2026, 02, 14, 1, 25, 52);
// List<Integer> opids=new ArrayList<>();//BCA6FA43FFA444D3952CF8F6E1EA291B // List<Integer> opids=new ArrayList<>();//BCA6FA43FFA444D3952CF8F6E1EA291B
// opids.add(7); // opids.add(7);
// planResultService.Move("27065EA0ECD14A81B7FAAFEF52273F93",opids,t,1265l,0); // planResultService.Move("27065EA0ECD14A81B7FAAFEF52273F93",opids,t,1265l,0);
// planResultService.Redecode("27065EA0ECD14A81B7FAAFEF52273F93"); // planResultService.Redecode("27065EA0ECD14A81B7FAAFEF52273F93");
// planResultService.Redecode("CA71321FE55B4437A3900315692F9220"); // planResultService.Redecode("CA71321FE55B4437A3900315692F9220");
// planResultService.Drag("27065EA0ECD14A81B7FAAFEF52273F93",opids,6,false,0l); // planResultService.Drag("27065EA0ECD14A81B7FAAFEF52273F93",opids,6,false,0l);
......
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