xyc
2024-10-22 1dad50645c6e61980f15b2be4505f75e7c922ee7
modules/mainPart/src/main/java/com/zt/life/modules/mainPart/taskReliability/service/SimulatAssessService.java
@@ -24,6 +24,7 @@
import com.zt.life.modules.mainPart.taskReliability.dto.TaskPhaseConstraintDto;
import com.zt.life.modules.mainPart.taskReliability.model.*;
import com.zt.life.modules.mainPart.utils.GetStringSpace;
import io.swagger.models.auth.In;
import org.apache.commons.io.IOUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
@@ -43,7 +44,10 @@
import org.springframework.transaction.annotation.Transactional;
import java.io.*;
import java.nio.file.FileAlreadyExistsException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@@ -196,9 +200,9 @@
        double pointNumPerHour = 60.0 / simulatAssess.getSamplPeriod();
        //时序图线
        List<List<TimeDiagramStatusDto>> lineArray = new ArrayList();
        List<TimeDiagramStatusDto> statusDtoList = new ArrayList<>();
        List<TimeDiagramStatusDto> statusDtoListOld = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            List<TimeDiagramStatusDto> statusDtoList = new ArrayList<>();
            x1 = 0;
            groupY = groupHeight * i;
            ProductStatusDto dto = list.get(i);
@@ -228,7 +232,11 @@
                        break;
                }
                x2 = x1 + status.getTimes() * pointNumPerHour + 5;
                statusDtoList.add(new TimeDiagramStatusDto(x1, x2, status2));
                if (i == 0) {
                    statusDtoList.add(new TimeDiagramStatusDto(x1, x2, status2));
                } else {
                    statusDtoListOld.add(new TimeDiagramStatusDto(x1, x2, status2));
                }
                JSONObject lineJson = new JSONObject(templetsStrMap.get(status.getStatus()));
                setlineXy(lineJson, x1, y, x2, y, "");
                JsonUtils2.setJsonValueByPath(lineJson, "data/status".split("/"), status.getStatus());
@@ -239,8 +247,6 @@
                x1 = x2 - 5;
                jsonArray.add(lineJson);
            }
            lineArray.add(statusDtoList);
            JSONObject textJson = new JSONObject(templetsStrMap.get("text"));
            JsonUtils2.setJsonValueByPath(textJson, "id".split("/"), UUIDUtil.generateId().toString());
            JsonUtils2.setJsonValueByPath(textJson, "attrs/label/textWrap/text".split("/"), dto.getName());
@@ -324,67 +330,73 @@
            curPointHour += periodHour;
        }
        List<TimeDiagramStatusDto> statusDtoListNew = new ArrayList<>();
        while (statusDtoListOld.size() > 0) {
            statusDtoListOld.stream().sorted(Comparator.comparing(TimeDiagramStatusDto::getX1)).collect(Collectors.toList());
            TimeDiagramStatusDto nextStatusDto = statusDtoListOld.get(0);
            if (statusDtoListNew.size() == 0) {
                statusDtoListNew.add(nextStatusDto);
            } else {
                TimeDiagramStatusDto currentStatusDto = statusDtoListNew.get(statusDtoListNew.size() - 1);
                if (nextStatusDto.getStatus() < currentStatusDto.getStatus()) {
                    if (nextStatusDto.getX1() == currentStatusDto.getX1() && nextStatusDto.getX2() == currentStatusDto.getX2()) {
                        currentStatusDto.setStatus(nextStatusDto.getStatus());
                    } else if (nextStatusDto.getX1() == currentStatusDto.getX1() && nextStatusDto.getX2() < currentStatusDto.getX2()) {
                        statusDtoListOld.add(new TimeDiagramStatusDto(nextStatusDto.getX2(), currentStatusDto.getX2(), currentStatusDto.getStatus()));
                        currentStatusDto.setStatus(nextStatusDto.getStatus());
                        currentStatusDto.setX2(nextStatusDto.getX2());
                    } else if (nextStatusDto.getX1() == currentStatusDto.getX1() && nextStatusDto.getX2() > currentStatusDto.getX2()) {
                        currentStatusDto.setStatus(nextStatusDto.getStatus());
                        currentStatusDto.setX2(nextStatusDto.getX2());
                    } else if (nextStatusDto.getX1() > currentStatusDto.getX1() && nextStatusDto.getX2() >= currentStatusDto.getX2()) {
                        currentStatusDto.setX2(nextStatusDto.getX1());
                        statusDtoListNew.add(new TimeDiagramStatusDto(nextStatusDto.getX1(), nextStatusDto.getX2(), nextStatusDto.getStatus()));
                    } else if (nextStatusDto.getX1() > currentStatusDto.getX1() && nextStatusDto.getX2() < currentStatusDto.getX2()) {
                        currentStatusDto.setX2(nextStatusDto.getX1());
                        statusDtoListNew.add(new TimeDiagramStatusDto(nextStatusDto.getX1(), nextStatusDto.getX2(), nextStatusDto.getStatus()));
                        statusDtoListOld.add(new TimeDiagramStatusDto(nextStatusDto.getX2(), currentStatusDto.getX2(), currentStatusDto.getStatus()));
                    }
                } else {
                    if (nextStatusDto.getX2() > currentStatusDto.getX2()) {
                        statusDtoListOld.add(new TimeDiagramStatusDto(currentStatusDto.getX2(), nextStatusDto.getX2(), nextStatusDto.getStatus()));
                    }
                }
            }
            statusDtoListOld.remove(0);
        }
        timeDiagramDto.setTotalWidth(x2);
        double pointRate = timeDiagramDto.getTotalWidth() / timeDiagramDto.getSmallWidth();
        List<TimeDiagramStatusDto> subStatusDtoList = new ArrayList<>();
        int lastStatus = 5;
        boolean isFirst = true;
        x1 = 0;
        for (double i = 0; i < timeDiagramDto.getSmallWidth(); i = i + timeDiagramDto.getMinPointNum()) {
            int netStatus = 5;
            for (int j = 1; j < list.size(); j++) {
                if (i >= 448) {
                    System.out.println(111);
                }
                int tmpStatus = getPointStatus(lineArray.get(j), i * pointRate, (i + timeDiagramDto.getMinPointNum()) * pointRate - 1);
                if (tmpStatus < netStatus) {
                    netStatus = tmpStatus;
                }
            }
            if (!isFirst) {
                if (lastStatus != netStatus) {
                    subStatusDtoList.add(new TimeDiagramStatusDto(x1, x2, lastStatus));
                    lastStatus = netStatus;
                    x1 = i;
                }
            } else {
                lastStatus = netStatus;
                isFirst = false;
            }
            x2 = i + timeDiagramDto.getMinPointNum() - 1;
        }
        subStatusDtoList.add(new TimeDiagramStatusDto(x1, x2, lastStatus));
        List<List<TimeDiagramStatusDto>> lineArray = new ArrayList();
        lineArray.add(statusDtoList);
        lineArray.add(statusDtoListNew);
        List<TimeDiagramStatusDto> parentStatusDtoList = new ArrayList<>();
        lastStatus = 5;
        isFirst = true;
        x1 = 0;
        for (double i = 0; i < timeDiagramDto.getSmallWidth(); i = i + timeDiagramDto.getMinPointNum()) {
            if (i >= 448) {
                System.out.println(111);
            }
            int netStatus = getPointStatus(lineArray.get(0), i * pointRate, (i + timeDiagramDto.getMinPointNum()) * pointRate - 1);
            if (!isFirst) {
                if (lastStatus != netStatus) {
                    parentStatusDtoList.add(new TimeDiagramStatusDto(x1, x2, lastStatus));
        List<List<TimeDiagramStatusDto>> smallStatusDtoList = new ArrayList<>();
        for (int j = 0; j < lineArray.size(); j++) {
            List<TimeDiagramStatusDto> tmpStatusDtoList = new ArrayList<>();
            int lastStatus = 5;
            Boolean isFirst = true;
            x1 = 0;
            for (double i = 0; i < timeDiagramDto.getSmallWidth(); i = i + timeDiagramDto.getMinPointNum()) {
                int netStatus = getPointStatus(lineArray.get(j), i * pointRate, (i + timeDiagramDto.getMinPointNum()) * pointRate - 1);
                if (!isFirst) {
                    if (lastStatus != netStatus) {
                        tmpStatusDtoList.add(new TimeDiagramStatusDto(x1, x2, lastStatus));
                        lastStatus = netStatus;
                        x1 = i;
                    }
                } else {
                    lastStatus = netStatus;
                    x1 = i;
                    isFirst = false;
                }
            } else {
                lastStatus = netStatus;
                isFirst = false;
                x2 = i + timeDiagramDto.getMinPointNum() - 1;
            }
            x2 = i + timeDiagramDto.getMinPointNum() - 1;
            tmpStatusDtoList.add(new TimeDiagramStatusDto(x1, x2, lastStatus));
            smallStatusDtoList.add(tmpStatusDtoList);
        }
        parentStatusDtoList.add(new TimeDiagramStatusDto(x1, x2, lastStatus));
        JSONObject jsonObject2 = new JSONObject(modelStr2);
        JSONArray jsonArray2 = jsonObject2.getJSONArray("cells");
        List<List<TimeDiagramStatusDto>> smallStatusDtoList = new ArrayList<>();
        smallStatusDtoList.add(parentStatusDtoList);
        smallStatusDtoList.add(subStatusDtoList);
        y = 10;
        for (int i = 0; i < smallStatusDtoList.size(); i++) {
            for (TimeDiagramStatusDto status : smallStatusDtoList.get(i)) {
@@ -606,17 +618,20 @@
    }
    @Transactional(rollbackFor = Exception.class)
    public Result simulate(SimulatAssess simulatAssess) {
        Result result = null;
    public List<TaskModelCheckResultDto> simulateChecK(SimulatAssess simulatAssess) {
        List<TaskModelCheckResultDto> result = null;
        // 1. 检查模型完整性
        List<TaskModelCheckResultDto> chkResult = taskService.checkTaskModel(simulatAssess.getProductId(),
                simulatAssess.getTaskModelId());
        if (chkResult.size() > 0) {
            result = Result.error("模型不完整,请检查模型定义及参数配置。");
//            result = Result.ok(chkResult);
            return result;
            return chkResult;
        }
        return result;
    }
    @Transactional(rollbackFor = Exception.class)
    public Boolean simulate(SimulatAssess simulatAssess) {
        Boolean result = false;
        // 2. 组装供算法库仿真的模型xml
        assembleModelXml(simulatAssess);
@@ -626,12 +641,16 @@
        return result;
    }
    private Result callReliaSimLib(SimulatAssess simulatAssess) {
        Result result = null;
    private Boolean callReliaSimLib(SimulatAssess simulatAssess) {
        Boolean result = false;
        InputStream is = null;
        BufferedReader br = null;
        try {
            setParamToRedis(simulatAssess);
            try {
                setParamToRedis(simulatAssess);
            } catch (Exception e) {
                throw new RenException("访问Redis失败。请检查Redis是否已启动。");
            }
            Process process = null;
            String command = "python " + reliaSimMain;
@@ -643,7 +662,7 @@
            } else if (System.getProperty("os.name").toLowerCase().indexOf("linux") > -1) {
                process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", command});
            } else {
                throw new Exception("暂不支持该操作系统,进行启动算法库计算!");
                throw new RenException("暂不支持该操作系统,进行启动算法库计算!");
            }
            is = process.getInputStream();
            // 以命令行方式调用算法库时,接口约定返回的结果是utf-8编码
@@ -654,17 +673,17 @@
            if (line != null) {
                ReliaSimLibResult rtn = com.alibaba.fastjson.JSONObject.parseObject(line, ReliaSimLibResult.class);
                if ("0".equals(rtn.getCode())) {
                    logger.info("启动算法库成功。");
                    result = Result.ok();
                    logger.info("启动可靠性仿真评估算法库成功。");
                    result = true;
                } else {
                    String errorMsg = rtn.getErrorMsg();
                    throw new RuntimeException("启动算法库失败: errorMsg=" + errorMsg);
                    throw new RenException("启动可靠性仿真评估算法库失败: errorMsg=" + errorMsg);
                }
            }
        } catch (Exception e) {
            logger.error("启动算法库仿真时发生Exception:", e);
        } catch (IOException e) {
            logger.error("启动可靠性仿真评估算法库仿真时发生Exception:", e);
            e.printStackTrace();
            result = Result.error(e.getMessage());
            throw new RenException("启动可靠性仿真评估算法库失败: errorMsg=" + e.getMessage());
        } finally {
            if (is != null) {
                try {
@@ -717,6 +736,9 @@
        List<ParamData> paramDataList = paramDataDao.getDeviceParams(productId);
        Long taskId = simulatAssess.getTaskModelId();
        Task task = taskService.get(taskId);
        if (simulatAssess.getTaskDuration() != null) {
            task.setTaskDuration(simulatAssess.getTaskDuration());
        }
        List<TaskBinoParam> binoParams = taskBinoParamDao.getBinoParams(taskId);
        // 1. 计算各任务阶段的运行时长
@@ -769,7 +791,7 @@
            insert(simulatAssess);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("组装算法库仿真计算用模型XML失败: " + e.getMessage());
            throw new RenException("组装算法库仿真计算用模型XML失败: " + e.getMessage());
        }
    }
@@ -1005,9 +1027,10 @@
                        failureModels, repairModels);
            } else if ("5".equals(product.getProductType())) {
                // 设备
                Integer deviceNo = node.getDeviceNo();
                Element nodeTag = parent.addElement("node");
                nodeTag.addAttribute("name", dataId.toString());
                nodeTag.addAttribute("real_name", product.getName());
                nodeTag.addAttribute("name", deviceNo == 0 ? dataId.toString() : dataId.toString()+"-"+deviceNo);
                nodeTag.addAttribute("real_name", deviceNo == 0 ? product.getName() : product.getName()+"-"+deviceNo);
                nodeTag.addAttribute("name_path", product.getNamePath());
                nodeTag.addAttribute("type", "node");
@@ -1109,7 +1132,8 @@
                break;
            case 3:
                // 二项分布
                if (taskBinoParam.getSimulatTimes().intValue() == taskBinoParam.getSuccessTimes().intValue()) {
                if ((taskBinoParam.getSimulatTimes() == null && taskBinoParam.getSuccessTimes() == null) ||
                        (taskBinoParam.getSimulatTimes().intValue() == taskBinoParam.getSuccessTimes().intValue())) {
                    // 相等则为成败型
                    failureModel.setType(FailureModel.TYPE_FIX);
                    failureModel.setParam1(taskBinoParam.getSuccessRate());
@@ -1244,43 +1268,55 @@
        }
    }
    public SchemeComparDto SchemeCompar(String[] taskList, Long showProductId) {
        SchemeComparDto dto = new SchemeComparDto();
    public SimulatResult SchemeCompar(String[] taskList, Long showProductId, Integer samplPeriod, Integer simulatFrequency) {
        SimulatResult simulatResult = new SimulatResult();
        List<Long> idList = new ArrayList<>();
        List<TaskModelCheckResultDto> result = null;
/*        SchemeComparDto dto = new SchemeComparDto();
        List<SimulaDataDto> dataDtoList = new ArrayList<>();
        List<SchemeComparCurve> curveList = new ArrayList<>();
        List<Double> xData = new ArrayList<>();
        SimulatAssess simulatAssess;
        SimulaDataDto data;
        SimulaDataDto data;*/
        List<SimulatAssess> simulatAssessList = new ArrayList<>();
        Task task;
        double maxTaskDuration = 0.0;
        for (String taskId : taskList) {
            Long taskModelId = Long.parseLong(taskId);
            task = taskService.get(taskModelId);
            simulatAssess = this.getByTaskId(taskModelId);
            SimulaDataDto resultData;
            if (showProductId != null) {
                simulatAssess.setProductId(showProductId);
                resultData = this.getResultXML(simulatAssess);
            } else {
                resultData = this.getResultXML(simulatAssess);
            task = taskService.get(Long.parseLong(taskId));
            if (task.getTaskDuration() > maxTaskDuration) {
                maxTaskDuration = task.getTaskDuration();
            }
            data = resultData;
            data.setName(task.getTaskName());
            dataDtoList.add(data);
            xData = resultData.getCurveParam().getXData();
            SimulatAssess simulatAssess = new SimulatAssess();
            Long id = UUIDUtil.generateId();
            simulatAssess.setId(id);
            simulatAssess.setName("");
            simulatAssess.setProductId(showProductId);
            simulatAssess.setSamplPeriod(samplPeriod);
            simulatAssess.setSimulatFrequency(simulatFrequency);
            simulatAssess.setTaskDuration(maxTaskDuration);
            simulatAssess.setTaskModelId(Long.parseLong(taskId));
            SchemeComparCurve curve = new SchemeComparCurve();
            curve.setName(task.getTaskName());
            curve.setSmooth(true);
            curve.setType("line");
            curve.setData(resultData.getCurveParam().getYData());
            curveList.add(curve);
            simulatAssessList.add(simulatAssess);
            result = simulateChecK(simulatAssess);
            if (result!=null){
                simulatResult.setType("errorList");
                simulatResult.setErrList(result);
                return simulatResult;
            }
            idList.add(id);
        }
        dto.setXDataList(xData);
        dto.setDataList(dataDtoList);
        dto.setCurveList(curveList);
        return dto;
        for (SimulatAssess simulatAssess : simulatAssessList) {
            simulatAssess.setTaskDuration(maxTaskDuration);
            this.simulate(simulatAssess);
        }
        simulatResult.setType("idList");
        simulatResult.setIdList(idList);
        return simulatResult;
    }
    public SimulaDataDto getResultXML(SimulatAssess simulatAssess) {
@@ -1367,4 +1403,134 @@
        }
        return data;
    }
    public String verify(Long taskId) {
        StringBuilder result = new StringBuilder();
        Task task = taskService.get(taskId);
        double taskTime = task.getTaskDuration();
        List<OperatConditModel> list = baseDao.getModel(taskId);
        List<Double> reliabiyList = new ArrayList<>();
        String modelStr2 = "";
        for (OperatConditModel model : list) {
            if (model.getProductId().equals(task.getProductId())) {
                modelStr2 = model.getContent();
                continue;
            }
            List<verifyDto> listNodes = baseDao.getNode(model.getModelId());
            for (verifyDto node : listNodes) {
                //lmd,reliabiy,failRate
                double lmd = 1 / node.getMtbf();
                double reliabiy = Math.exp(-1 * lmd * taskTime);
                double failRate = 1 - reliabiy;
                node.setLmd(lmd);
                node.setReliabiy(reliabiy);
                node.setFailRate(failRate);
            }
            int total = listNodes.size();
            String modelStr = model.getContent();
            //找到表决数量
            if (modelStr.contains("switch")) {
                double a = 0;
                double lmd = listNodes.get(0).getLmd();
                result.append("\n").append(total).append("个相同设备旁联,3选1,MTTBCF是").append(listNodes.get(0).getMtbf()).append("\n");
                for (int i = 0; i <= total - 1; i++) {
                    double ijc = getjc(i);
                    double b = Math.pow(taskTime * lmd, i) * Math.exp(-1 * lmd * taskTime) / ijc;
                    a = a + b;
                    result.append("有").append(i + 1).append("个设备好的的概率为").append(b).append("\n");
                }
                result.append("整个旁联系统的可靠度为").append(new Formatter().format("%.4f", a)).append("\n");
                reliabiyList.add(a);
            } else if (modelStr.contains("parallel")) {
                double a = 1;
                result.append("\n并联设备有").append(total).append("个\n");
                for (int i = 0; i < listNodes.size(); i++) {
                    a = a * listNodes.get(i).getFailRate();
                    result.append("第").append(i + 1).append("个设备的MTBCF为").append(listNodes.get(i).getMtbf()).append(",").append(i + 1).append("个设备并联的失效率为").append(a).append("\n");
                }
                double reliabiy = 1 - a;
                result.append("整个并联系统的失效率为").append(a).append("整个并联系统的可靠度为").append(new Formatter().format("%.4f", reliabiy)).append("\n");
                reliabiyList.add(reliabiy);
            } else if (modelStr.contains("vote")) {
                Integer voteNum = baseDao.getVoteNum(model.getModelId());
                if (voteNum != null) {
                    result.append("\n").append(total).append("个相同设备表决,MTBCF为").append(listNodes.get(0).getMtbf()).append("表决数量为").append(voteNum).append("个\n");
                    double a = 0;
                    double zjc = getjc(total);
                    double reliabiy = listNodes.get(0).getReliabiy();
                    for (int i = voteNum; i <= total; i++) {
                        double ijc = getjc(i);
                        double nijc = getjc(total - i);
                        double b = (zjc / (ijc * nijc)) * Math.pow(reliabiy, i) * Math.pow(1 - reliabiy, total - i);
                        a = a + b;
                        result.append("有").append(i).append("个设备是好的概率为").append(b).append("\n");
                    }
                    result.append("整个表决系统的可靠度为").append(new Formatter().format("%.4f", a)).append("\n");
                    reliabiyList.add(a);
                }
            }
        }
        double totalReliabiy = 1;
        if (modelStr2.contains("parallel")) {
            for (Double reliabiy : reliabiyList) {
                totalReliabiy = totalReliabiy * (1 - reliabiy);
            }
            totalReliabiy = 1 - totalReliabiy;
        } else {
            for (Double reliabiy : reliabiyList) {
                totalReliabiy = totalReliabiy * reliabiy;
            }
        }
        result.append("\n整个总体系统的可靠度为").append(totalReliabiy).append("\n");
        return String.valueOf(result);
    }
    Double getjc(int a) {
        double result = 1.0;
        for (int i = a; i > 0; i--)
            result = result * i;
        return result;
    }
    public SchemeComparDto getEcharts(String[] taskList, Long showProductId) {
        SchemeComparDto dto = new SchemeComparDto();
        List<SimulaDataDto> dataDtoList = new ArrayList<>();
        List<SchemeComparCurve> curveList = new ArrayList<>();
        List<Double> xData = new ArrayList<>();
        SimulatAssess simulatAssess;
        SimulaDataDto data;
        Task task;
        for (String taskId : taskList) {
            Long taskModelId = Long.parseLong(taskId);
            task = taskService.get(taskModelId);
            simulatAssess = this.getByTaskId(taskModelId);
            simulatAssess.setDataType("fz");
            SimulaDataDto resultData;
            if (showProductId != null) {
                simulatAssess.setProductId(showProductId);
                resultData = this.getResultXML(simulatAssess);
            } else {
                resultData = this.getResultXML(simulatAssess);
            }
            data = resultData;
            data.setName(task.getTaskName());
            dataDtoList.add(data);
            xData = resultData.getCurveParam().getXData();
            SchemeComparCurve curve = new SchemeComparCurve();
            curve.setName(task.getTaskName());
            curve.setSmooth(true);
            curve.setType("line");
            curve.setData(resultData.getCurveParam().getYData());
            curveList.add(curve);
        }
        dto.setXDataList(xData);
        dto.setDataList(dataDtoList);
        dto.setCurveList(curveList);
        return dto;
    }
}