场景文件保存读取

parent 05e4217f
package com.aps.controller; package com.aps.controller;
import com.aps.common.util.R; import com.aps.common.util.R;
import com.aps.entity.Algorithm.Chromosome;
import com.aps.service.LanuchService; import com.aps.service.LanuchService;
import com.aps.service.plan.PlanResultService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
...@@ -16,6 +19,8 @@ public class LanuchController { ...@@ -16,6 +19,8 @@ public class LanuchController {
@Autowired @Autowired
private LanuchService lanuchService; private LanuchService lanuchService;
@Autowired
private PlanResultService planResultService;
/** /**
* 启动工单 * 启动工单
* *
...@@ -33,4 +38,15 @@ public class LanuchController { ...@@ -33,4 +38,15 @@ public class LanuchController {
return lanuchService.lanuch(sceneName, username); return lanuchService.lanuch(sceneName, username);
} }
@GetMapping("/schedule")
public Chromosome schedule(@RequestParam String sceneID) {
// 调用 PlanResultService 获取 ScheduleChromosome 列表
Chromosome scheduleChromosomes = planResultService.schedule(sceneID);
// 提取所有场景ID
return scheduleChromosomes;
}
} }
\ No newline at end of file
...@@ -5,6 +5,7 @@ import com.aps.entity.basic.Machine; ...@@ -5,6 +5,7 @@ import com.aps.entity.basic.Machine;
import com.aps.entity.basic.Order; import com.aps.entity.basic.Order;
import lombok.Data; import lombok.Data;
import java.time.LocalDateTime;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.stream.Collectors; import java.util.stream.Collectors;
...@@ -97,4 +98,8 @@ public class Chromosome { ...@@ -97,4 +98,8 @@ public class Chromosome {
private double DelayTime; private double DelayTime;
private String ScenarioID;
private String ScenarioName;
private LocalDateTime BaseTime ; // 当前基准时间
} }
...@@ -20,7 +20,7 @@ public class TaskVO { ...@@ -20,7 +20,7 @@ public class TaskVO {
private Integer id; private Integer id;
@Schema(description = "计划ID") @Schema(description = "计划ID")
private Integer planId; private String planId;
@Schema(description = "产品类型") @Schema(description = "产品类型")
private Integer productType; private Integer productType;
...@@ -29,10 +29,10 @@ public class TaskVO { ...@@ -29,10 +29,10 @@ public class TaskVO {
private String productName; private String productName;
@Schema(description = "产品ID") @Schema(description = "产品ID")
private Integer productId; private String productId;
@Schema(description = "数量") @Schema(description = "数量")
private Integer quantity; private double quantity;
@Schema(description = "开始时间") @Schema(description = "开始时间")
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
...@@ -101,7 +101,7 @@ public class TaskVO { ...@@ -101,7 +101,7 @@ public class TaskVO {
@Schema(description = "工序名称") @Schema(description = "工序名称")
private String seqName; private String seqName;
private int processingTime; // 绝对处理时间(分钟) private double processingTime; // 绝对处理时间(分钟)
private int absolutePreparationTime; // 新增:绝对准备时间 private int absolutePreparationTime; // 新增:绝对准备时间
......
...@@ -59,7 +59,8 @@ public class PlanResultService { ...@@ -59,7 +59,8 @@ public class PlanResultService {
@Autowired @Autowired
private PlanResourceService _PlanResourceService; private PlanResourceService _PlanResourceService;
@Autowired
private SceneService _sceneService;
@Autowired @Autowired
private ProdOrderProcessService _prodOrderProcessService; private ProdOrderProcessService _prodOrderProcessService;
...@@ -294,6 +295,69 @@ public class PlanResultService { ...@@ -294,6 +295,69 @@ public class PlanResultService {
} }
public Chromosome schedule(String SceneId) {
try {
ScheduleParams param = new ScheduleParams();
param.setBaseTime(LocalDateTime.of(2025, 11, 1, 0, 0, 0));
param.setPopulationSize(50);
param.setMaxIterations(100);
// 1. 读取数据
// List<Machine> machines = loadData("machines.json", Machine.class);
// List<Product> products = loadData("products.json", Product.class);
// List<Order> orders = loadData("orders.json", Order.class);
List<ProdEquipment> ProdEquipments= _prodEquipmentService.lambdaQuery()
.eq(ProdEquipment::getSceneId,SceneId)
.list();
List<ProdLaunchOrder> ProdLaunchOrders= _prodLaunchOrderService.lambdaQuery()
.eq(ProdLaunchOrder::getSceneId,SceneId)
.list();
// 3. 创建调度服务
MachineSchedulerService machineScheduler = new MachineSchedulerService(
param.getBaseTime());
List<Machine> machines= InitCalendarToAllMachines(SceneId, ProdEquipments,machineScheduler);
// 3. 构建订单-工序数据
List<Order> orders=new ArrayList<>();
for (ProdLaunchOrder lo : ProdLaunchOrders) {
Order order=new Order();
order.setOrderId(lo.getOrderId());
order.setMaterialId(lo.getMaterialId());
order.setDueDate(lo.getEndDate());
order.setQuantity(lo.getQuantity());
orders.add(order);
}
List<Entry> entrys= InitEntrys(SceneId,ProdEquipments,ProdLaunchOrders);
GlobalParam globalParam=new GlobalParam();
// 5. 执行调度算法
GeneticAlgorithm scheduler =new GeneticAlgorithm(globalParam,machines,orders,null,machineScheduler); //new GeneticAlgorithm(products, machines, orders, machineScheduler);
Chromosome chromosomes =scheduler.Run(param,entrys);
chromosomes.setScenarioID(SceneId);
chromosomes.setBaseTime(param.getBaseTime());
// 保存chromosomes到文件
_sceneService.saveChromosomeToFile(chromosomes, SceneId);
// Chromosomes.forEach(this::WriteScheduleSummary);
return chromosomes;
} catch (Exception e) {
throw new RuntimeException("调度执行失败", e);
}
}
public void WriteScheduleSummary(Chromosome schedule) { public void WriteScheduleSummary(Chromosome schedule) {
// 写入日志 // 写入日志
FileHelper.writeLogFile(String.format("\n=== Schedule Summary === %f", schedule.getFitness())); FileHelper.writeLogFile(String.format("\n=== Schedule Summary === %f", schedule.getFitness()));
......
package com.aps.service.plan;
import com.aps.entity.Algorithm.Chromosome;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
/**
* SceneService.java
*
* @author jdt
* @description 场景保存修改
* @since 2025-12-01
*/
@Service
public class SceneService {
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(SceneService.class);
// 统一配置 ObjectMapper
private ObjectMapper createObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
// 忽略未知属性,防止反序列化时出错
objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return objectMapper;
}
/**
* 获取文件存储目录
*/
private File getResultDirectory() {
File resultDir = new File("result");
if (!resultDir.exists()) {
boolean created = resultDir.mkdirs();
if (!created) {
logger.warn("无法创建结果目录: {}", resultDir.getAbsolutePath());
throw new RuntimeException("无法创建结果目录: " + resultDir.getAbsolutePath());
}
}
return resultDir;
}
/**
* 获取文件路径
*/
private File getChromosomeFile(String sceneId) {
File resultDir = getResultDirectory();
String fileName = "chromosome_result_" + sceneId + ".json";
return new File(resultDir, fileName);
}
/**
* 从文件中读取Chromosome对象
*/
public Chromosome loadChromosomeFromFile(String sceneId) {
if (sceneId == null || sceneId.trim().isEmpty()) {
logger.warn("场景ID不能为空");
return null;
}
try {
ObjectMapper objectMapper = createObjectMapper();
File file = getChromosomeFile(sceneId);
if (!file.exists()) {
logger.warn("染色体文件不存在: {}", file.getAbsolutePath());
return null;
}
if (file.length() == 0) {
logger.warn("染色体文件为空: {}", file.getAbsolutePath());
return null;
}
logger.info("正在从文件加载染色体: {}", file.getAbsolutePath());
Chromosome chromosome = objectMapper.readValue(file, Chromosome.class);
logger.info("染色体加载成功,场景ID: {}", sceneId);
return chromosome;
} catch (Exception e) {
// 正确的错误日志写法
logger.error("加载染色体文件失败,场景ID: " + sceneId, e);
throw new RuntimeException("加载染色体文件失败: " + e.getMessage(), e);
}
}
/**
* 将染色体结果保存到JSON文件
*/
public boolean saveChromosomeToFile(Chromosome chromosome, String sceneId) {
if (chromosome == null) {
logger.warn("染色体对象不能为空");
return false;
}
if (sceneId == null || sceneId.trim().isEmpty()) {
logger.warn("场景ID不能为空");
return false;
}
try {
ObjectMapper objectMapper = createObjectMapper();
File file = getChromosomeFile(sceneId);
File tempFile = new File(file.getParentFile(), file.getName() + ".tmp");
objectMapper.writeValue(tempFile, chromosome);
if (tempFile.length() == 0) {
logger.error("写入的临时文件为空: {}", tempFile.getAbsolutePath());
Files.deleteIfExists(tempFile.toPath());
return false;
}
// 验证文件内容
try {
Chromosome verifyChromosome = objectMapper.readValue(tempFile, Chromosome.class);
if (verifyChromosome == null) {
throw new IOException("验证读取失败");
}
} catch (Exception e) {
logger.error("验证染色体文件内容失败,文件: {}", tempFile.getAbsolutePath(), e);
Files.deleteIfExists(tempFile.toPath());
return false;
}
// 替换原文件
if (file.exists()) {
Files.deleteIfExists(file.toPath());
}
Files.move(tempFile.toPath(), file.toPath());
logger.info("染色体保存成功,场景ID: {}, 文件: {}", sceneId, file.getAbsolutePath());
return true;
} catch (Exception e) {
logger.error("保存染色体文件失败,场景ID: " + sceneId, e);
return false;
}
}
/**
* 检查染色体文件是否存在
*/
public boolean chromosomeFileExists(String sceneId) {
if (sceneId == null || sceneId.trim().isEmpty()) {
return false;
}
File file = getChromosomeFile(sceneId);
return file.exists() && file.length() > 0;
}
/**
* 删除染色体文件
*/
public boolean deleteChromosomeFile(String sceneId) {
try {
File file = getChromosomeFile(sceneId);
if (file.exists()) {
boolean deleted = Files.deleteIfExists(file.toPath());
if (deleted) {
logger.info("删除染色体文件成功: {}", file.getAbsolutePath());
}
return deleted;
}
return true;
} catch (Exception e) {
logger.error("删除染色体文件失败,场景ID: " + sceneId, e);
return false;
}
}
}
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