xyc
2024-09-10 0a31d5f715701b1491a471f3187b66331e78cd3b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
package com.zt.life.modules.mainPart.taskReliability.service;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zt.common.constant.Constant;
import com.zt.common.db.query.QueryFilter;
import com.zt.common.service.BaseService;
import com.zt.common.servlet.Result;
import com.zt.common.utils.CacheUtils;
import com.zt.common.utils.CommonUtils;
import com.zt.common.utils.TreeUtils;
import com.zt.common.utils.UUIDUtil;
import com.zt.core.shiro.ImportUtil;
import com.zt.life.modules.mainPart.basicInfo.dao.XhProductModelDao;
import com.zt.life.modules.mainPart.basicInfo.model.ParamData;
import com.zt.life.modules.mainPart.basicInfo.model.ProductImg;
import com.zt.life.modules.mainPart.basicInfo.model.XhProductModel;
import com.zt.life.modules.mainPart.basicInfo.service.ParamDataService;
import com.zt.life.modules.mainPart.sysPictureBase.service.SysPictureBaseService;
import com.zt.life.modules.mainPart.taskReliability.dao.AssessResultDao;
import com.zt.life.modules.mainPart.taskReliability.dao.ReliabilityAssessDao;
import com.zt.life.modules.mainPart.taskReliability.dto.TaskModelCheckResultDto;
import com.zt.life.modules.mainPart.taskReliability.model.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.*;
 
 
/**
 * product_model
 *
 * @author zt generator
 * @since 1.0.0 2024-02-29
 */
@Service
public class ReliabilityAssessService extends BaseService<ReliabilityAssessDao, ReliabilityAssess> {
    private static final Logger logger = LoggerFactory.getLogger(ReliabilityAssessService.class);
    public static final String RELIA_ASSESS_TASK_TYPE_SIMULATION = "assessReq";
 
    @Value("${spring.redis.host}")
    private String redisHost;
    @Value("${spring.redis.port}")
    private String redisPort;
    @Value("${data.reliaSimLib.mainPy}")
    private String reliaSimMain;
    @Value("${data.reliaSimLib.resultHome}")
    private String resultHome;
 
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AssessResultDao assessResultDao;
 
    @Transactional(rollbackFor = Exception.class)
    public Result assess(AssessResult assessResult) {
        Result result = null;
 
        Long assessId = UUIDUtil.generateId();
        assessResult.setId(assessId);
/*
        // 1. 检查参数完整性
        List<TaskModelCheckResultDto> chkResult = taskService.checkTaskModel(simulatAssess.getProductId(),
                simulatAssess.getTaskModelId());
        if (chkResult.size() > 0) {
            result = Result.error("模型不完整,请检查模型定义及参数配置。");
            return result;
        }
 
*/
        // 2. 组装供算法库评定的模型xml
        assembleModelXml(assessResult);
 
        // 3. 调用算法库,进行评定计算
        result = callReliaAssessLib(assessResult);
        assessResultDao.insert(assessResult);
 
        return Result.ok();
    }
 
    private void assembleModelXml(AssessResult assessResult) {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "\n" +
                "<des name=\"General system\" gama=\"0.7\">\n" +
                "  <tasks>\n" +
                "    <task duration=\"1\" model=\"1819282257303678978\"/>\n" +
                "  </tasks>\n" +
                "  <models>\n" +
                "    <model name=\"1819282257303678978\">\n" +
                "      <logic name=\"系统\" type=\"series\" distType=\"ber\" NoE=\"10\" F=\"1\">\n" +
                "        <logic name=\"分系统1\" type=\"series\" distType=\"exp\" ToE=\"68.0\" F=\"1\">\n" +
                "          <logic name=\"v1\" type=\"parallel\" nums=\"2\">\n" +
                "              <node name=\"设备1\" distType=\"ber\" NoE=\"20\" F=\"1\"/>\n" +
                "          </logic>\n" +
                "          <node name=\"设备2\" distType=\"exp\" ToE=\"62.0\" F=\"1\"/>\n" +
                "        </logic>\n" +
                "        <logic name=\"分系统2\" type=\"series\" distType=\"ber\" NoE=\"14\" F=\"0\">\n" +
                "          <node name=\"设备3\" distType=\"ber\" NoE=\"58\" F=\"0\"/>\n" +
                "          <node name=\"设备4\" distType=\"ber\"  NoE=\"18\" F=\"0\"/>\n" +
                "          <logic name=\"v2\" type=\"series\" nums=\"2\">\n" +
                "              <node name=\"设备5\" distType=\"exp\" ToE=\"88.0\" F=\"1\"/>\n" +
                "          </logic>          \n" +
                "          <node name=\"设备6\" distType=\"ber\"  NoE=\"71.52\" F=\"1\"/>\n" +
                "        </logic>\n" +
                "        <logic name=\"分系统3\" type=\"vote\" distType=\"exp\" nums=\"3\" k=\"2\" ToE=\"68.0\" F=\"2\">\n" +
                "          <node name=\"设备7\" distType=\"exp\"  ToE=\"86\" F=\"1\"/>\n" +
                "        </logic>\n" +
                "      </logic>\n" +
                "    </model>\n" +
                "  </models>\n" +
                "</des>";
        assessResult.setXml(xml);
/*
        Long productId = simulatAssess.getProductId();
        XhProductModel product = xhProductModelDao.getById(productId);
        List<XhProductModel> productList = xhProductModelDao.getByShipId(productId);
        List<ParamData> paramDataList = paramDataDao.getDeviceParams(productId);
        Long taskId = simulatAssess.getTaskModelId();
        Task task = taskService.get(taskId);
        List<TaskBinoParam> binoParams = taskBinoParamDao.getBinoParams(taskId);
 
        // 1. 计算各任务阶段的运行时长
        List<TaskPhase> taskPhases = calcTaskPhaseDuration(task);
        // 2. 计算各工况模型的运行时长
        List<TaskPhaseModel> taskPhaseModelAll = new ArrayList<>();
        for (TaskPhase taskPhase : taskPhases) {
            calcTaskPhaseModelDuration(taskPhase, taskPhaseModelAll);
        }
        // 3. 将各工况模型递归拆解为完整的可供算法包仿真计算的模型
        try {
            List<FailureModel> failureModels = new ArrayList<>();
            List<RepairModel> repairModels = new ArrayList<>();
 
            Document document = DocumentHelper.createDocument();
            // 添加root节点
            Element root = document.addElement("des");
            root.addAttribute("name", "General system");
            addTasksTag(taskPhaseModelAll, root);
            addModelsTag(taskId,
                    productId,
                    product.getName(),
                    product.getNamePath(),
                    productList,
                    paramDataList,
                    taskPhaseModelAll,
                    binoParams,
                    root,
                    failureModels, repairModels);
            addFailureModelsTag(failureModels, root);
            addRepairModelsTag(repairModels, root);
            saveSimulatAssessTaskPhaseModel(simulatAssess,
                    task,
                    taskPhases,
                    taskPhaseModelAll);
 
            // 输出格式化xml
            XMLWriter xmlWriter = null;
            try {
                OutputFormat format = OutputFormat.createPrettyPrint();
                format.setEncoding("UTF-8");
                StringWriter writer = new StringWriter();
                xmlWriter = new XMLWriter(writer, format);
                xmlWriter.write(document);
                simulatAssess.setXml(writer.toString());
            } finally {
                if (xmlWriter != null) xmlWriter.close();
            }
            // XML存盘
            insert(simulatAssess);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("组装算法库仿真计算用模型XML失败: " + e.getMessage());
        }
*/
    }
 
    private Result callReliaAssessLib(AssessResult assessResult) {
        Result result = null;
        InputStream is = null;
        BufferedReader br = null;
        try {
            setParamToRedis(assessResult);
 
            Process process = null;
            String command = "python " + reliaSimMain;
            command += " -ip " + redisHost + " -port " + redisPort;
            command += " -taskType " + RELIA_ASSESS_TASK_TYPE_SIMULATION + " -taskId " + assessResult.getId().toString();
            logger.info("cmd命令为:" + command);
            if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1) {
                process = Runtime.getRuntime().exec(new String[]{"cmd", "/c", command});
            } else if (System.getProperty("os.name").toLowerCase().indexOf("linux") > -1) {
                process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", command});
            } else {
                throw new Exception("暂不支持该操作系统,进行启动算法库计算!");
            }
            is = process.getInputStream();
            // 以命令行方式调用算法库时,接口约定返回的结果是utf-8编码
            br = new BufferedReader(new InputStreamReader(is, "utf-8"));
            String line = br.readLine();
            logger.info("算法库返回结果:" + line);
            int exitCode = process.waitFor(); // 同步方式,等待算法库计算完毕
            if (line != null) {
                ReliaSimLibResult rtn = com.alibaba.fastjson.JSONObject.parseObject(line, ReliaSimLibResult.class);
                if ("0".equals(rtn.getCode())) {
                    logger.info("启动算法库成功。");
                    result = Result.ok();
                } else {
                    String errorMsg = rtn.getErrorMsg();
                    throw new RuntimeException("启动算法库失败: errorMsg=" + errorMsg);
                }
            }
        } catch (Exception e) {
            logger.error("启动可靠性评定算法库时发生Exception:", e);
            e.printStackTrace();
            result = Result.error(e.getMessage());
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (br != null) {
                try {
                    br.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
 
        return result;
    }
 
    private void setParamToRedis(AssessResult assessResult) {
        String key = assessResult.getId().toString() + RELIA_ASSESS_TASK_TYPE_SIMULATION;
        logger.info("redis key:" + key);
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        jsonObject.put("xmlfile", assessResult.getXml());
        jsonObject.put("confidence_level", assessResult.getConfidence());
        jsonObject.put("result_home", resultHome);
        redisTemplate.opsForValue().set(key, jsonObject.toJSONString());
    }
 
    public void deleteAssessInfoInRedis(Long simId) {
        redisTemplate.delete(simId.toString() + RELIA_ASSESS_TASK_TYPE_SIMULATION);
    }
 
 
    public List<Map<String, Object>> importProductExcel(MultipartFile mutFile, String progressId, Long shipId, Long itemId) {
        Date beginDate = new Date();
        List<Map<String, Object>> list = new ArrayList<>();//存储所有的导入状态
        Map<String, Object> map;//存储每一行的状态
        Integer sum = 0; // 总共的条数
        Integer suc = 0; // 成功的条数
        Integer err = 0; // 失败的条数
        int row1 = 0;
        Map<String, Object> errMap = new HashMap<>();
 
        try {
            // 获取导入文件的后缀名
            String fileName = mutFile.getOriginalFilename();
            Workbook workbook = null;
            //解决excel版本问题
            if (fileName != null && fileName.endsWith(".xls")) {
                workbook = new HSSFWorkbook(mutFile.getInputStream());
            } else if (fileName != null && fileName.endsWith(".xlsx")) {
                workbook = new XSSFWorkbook(mutFile.getInputStream());
            }
            assert workbook != null; //断言如果[boolean表达式]为true,则程序继续执行。 如果为false,则程序抛出AssertionError,并终止执行。
            int sheets = workbook.getNumberOfSheets();
 
            Map<String, XhProductModel> modelMap = new HashMap<>();
            List<XhProductModel> prductList = baseDao.getProductPath(shipId);
 
            for (XhProductModel product : prductList) {
                if (StringUtils.isNotBlank(product.getNamePath())) {
                    modelMap.put(product.getNamePath(), product);
                }
            }
 
            String shipPath = "";
            String xtPath = "";
            String fxtPath = "";
            String sbPath = "";
            String path = "";
            for (int i = 0; i < sheets; i++) {
                Sheet sheet = workbook.getSheetAt(i);
                int num = sheet.getLastRowNum(); // 一共有多少行
                String sheetName = sheet.getSheetName(); //获取当前sheet名称
                for (int j = 1; j <= num; j++) {
                    CacheUtils.put(progressId, "speed", CommonUtils.getPercent(j, num));
                    CacheUtils.put(progressId, "msg", "共" + num + "行,已完成第" + j + "行");
 
                    row1 = j;
                    String pattern = "yyyy-MM-dd";
                    Row row = sheet.getRow(row1);
                   // String sort = ImportUtil.getCellValue(row, 0, pattern); //序号
 
                    String name = ImportUtil.getCellValue(row, 1, pattern); //节点名称
                    String type = ImportUtil.getCellValue(row, 2, pattern);//节点类型
                    String runNum = ImportUtil.getCellValue(row, 3, pattern); //运行时长
                    String runTime = ImportUtil.getCellValue(row, 4, pattern); //运行次数
                    String failNum = ImportUtil.getCellValue(row, 5, pattern); //失败次数
 
                    if (StringUtils.isBlank(name) || StringUtils.isBlank(type))
                        continue;
 
                    Long productId = null;
                    if (type.equals("总体")) {
                        path = shipPath = name;
                        xtPath = "";
                        fxtPath = "";
                        sbPath = "";
                        productId = shipId;
                    }else {
                        if (type.equals("系统")) {
                            if (StringUtils.isNotBlank(shipPath)) {
                                path = xtPath = name;
                                fxtPath = "";
                                sbPath = "";
                            } else {
                                continue;
                            }
                        }
                        if (type.equals("分系统")) {
                            if (StringUtils.isNotBlank(xtPath)) {
                                path = fxtPath = xtPath + "," + name;
                                sbPath = "";
                            } else {
                                continue;
                            }
                        }
                        if (type.equals("设备")) {
                            if ((StringUtils.isNotBlank(xtPath) || StringUtils.isNotBlank(fxtPath))) {
                                path = sbPath = StringUtils.isNotBlank(fxtPath) ? fxtPath + "," + name : xtPath + "," + name;
                            } else {
                                continue;
                            }
                        }
                        if (modelMap.get(path) != null) {
                            productId = modelMap.get(path).getId();
                        }
                    }
 
 
 
                    ReliabilityAssess assess = new ReliabilityAssess();
                    assess.setFailNum(Integer.valueOf(failNum));
                    if (StringUtils.isNotBlank(runNum)){
                        assess.setRunNum(Integer.valueOf(runNum));
                    }
                    if (StringUtils.isNotBlank(runTime)){
                        assess.setRunTimes(Double.valueOf(runTime));
                    }
                    assess.setItemId(itemId);
                    assess.setProductId(productId);
                    this.insert(assess);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ImportUtil.updateErrMap(errMap, "导入异常" + e.getMessage(), "", row1);
            //err++;
        }
 
        Date nowDate = new Date();
        String msg = "产品模型导入时间:" + CommonUtils.getDatePoor(nowDate, beginDate) + "\r\n";
        System.out.println(msg);
        suc = sum - err;
        map = new HashMap<>();
        map.put("sum", sum + ""); // 所有导入的条数
        map.put("suc", suc + ""); // 成功的条数
        map.put("err", err + ""); // 失败的条数
        list.add(map);
        list.add(errMap);
        return list;
    }
 
    public List<AssessItem> getAssessDataList(Long productId) {
        return baseDao.getAssessDataList(productId);
    }
}