From a2ee6e0dcdcfd9d1b8011a3cecb4e0fc4f6eeea3 Mon Sep 17 00:00:00 2001 From: dcb <xgybdcb@163.com> Date: 星期五, 06 六月 2025 18:10:32 +0800 Subject: [PATCH] 实时模拟功能实现 --- src/main/java/com/se/nsl/service/ResolveService.java | 190 ++++++++++++++++++++++++++++++++++------------- 1 files changed, 138 insertions(+), 52 deletions(-) diff --git a/src/main/java/com/se/nsl/service/ResolveService.java b/src/main/java/com/se/nsl/service/ResolveService.java index 5edd663..64c27b4 100644 --- a/src/main/java/com/se/nsl/service/ResolveService.java +++ b/src/main/java/com/se/nsl/service/ResolveService.java @@ -4,17 +4,23 @@ import cn.hutool.core.io.FileUtil; import cn.hutool.json.JSONUtil; import com.alibaba.fastjson.JSON; +import com.fasterxml.jackson.databind.ObjectMapper; import com.se.nsl.config.PropertiesConfig; -import com.se.nsl.domain.dto.Zarr2Tif; +import com.se.nsl.domain.dto.*; import com.se.nsl.domain.po.Rainfall; import com.se.nsl.domain.po.Simu; import com.se.nsl.domain.po.SimuData; import com.se.nsl.domain.vo.ConfigVo; +import com.se.nsl.domain.vo.RealTimeInput; +import com.se.nsl.domain.vo.ResultVo; import com.se.nsl.helper.ComHelper; import com.se.nsl.helper.GdalHelper; import com.se.nsl.helper.StringHelper; import com.se.nsl.helper.WebHelper; import com.se.nsl.utils.AreaType; +import com.se.nsl.utils.RainFallUnit; +import com.se.nsl.utils.SimulateType; +import com.se.nsl.utils.TimeFormatUtil; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.gdal.gdal.Band; @@ -36,12 +42,11 @@ import java.math.BigDecimal; import java.math.RoundingMode; import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; +import java.nio.file.*; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.time.Instant; +import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.*; import java.util.concurrent.ExecutorService; @@ -122,7 +127,7 @@ createRainfallFile(simu, data); update(simu, 2, "璋冪敤姹傝В鍣�"); - callUwSolver(data); + callUwSolver(simu, data); update(simu, 3, "璋冪敤Zarr杞琓if"); callZarr2tif(data); @@ -237,30 +242,6 @@ } f.mkdirs(); } - - enum RainFallUnit { - MM_H("mm/h", 60), - MM_15MIN("mm/15min", 15), - MM_5MIN("mm/5min", 5), - MM_MIN("mm/min", 1); - private String unit; - private int c; //绯绘暟 - RainFallUnit(String unit, int c) { - this.unit = unit; - this.c = c; - } - - public static RainFallUnit of(String unit) { - RainFallUnit[] values = values(); - for (RainFallUnit v : values) { - if (v.unit.equals(unit)) { - return v; - } - } - return MM_H; //榛樿鎸夌収mm/h璁$畻 - } - - } public void createRainfallFile(Simu simu, SimuData data) throws Exception { List<Rainfall> rainfalls = data.getRainfalls(); @@ -283,8 +264,8 @@ // int unit = StringUtils.isEmpty(data.getIntensityUnit()) || "mm/h".equals(data.getIntensityUnit()) ? 60 : 5; String iu = data.getIntensityUnit(); RainFallUnit rfUnit = RainFallUnit.of(iu); - data.setIntensityUnit(rfUnit.unit); - int unit = rfUnit.c; + data.setIntensityUnit(rfUnit.getUnit()); + int unit = rfUnit.getC(); int c = rainfalls.size() - 1; for (int i = 0; i < c; i++) { Rainfall r1 = rainfalls.get(i); @@ -325,7 +306,7 @@ /** * 璋冪敤UWSolver */ - public String callUwSolver(SimuData data) throws Exception { + public String callUwSolver(Simu simu, SimuData data) throws Exception { File uwBat = new File(config.getUwSolverBat()); int duration = 3600 * data.getDuration(); // 绉掓暟 @@ -348,7 +329,10 @@ // ConfigVo vo = new ConfigVo(terrainFile, landuseFile, terrainFile, rainfallFile, saveName, duration, config.getSaveFrames()); Integer saveFrameInterval = config.getSaveFrameInterval(); int saveFrames = duration / 60 / saveFrameInterval; - ConfigVo vo = new ConfigVo(terrainFile, landuseFile, terrainFile, rainfallFile, saveName, duration, saveFrames); + Short type = simu.getType(); + SimulateType simulateType = SimulateType.of(type); + String saveMode = simulateType.getSaveMode(); + ConfigVo vo = new ConfigVo(terrainFile, landuseFile, terrainFile, rainfallFile, saveName, duration, saveFrames, saveMode); String configFile = config.getInPath() + File.separator + data.getInPath() + File.separator + data.getInPath() + ".json"; ComHelper.writeJson(configFile, JSON.toJSONString(vo)); @@ -384,12 +368,9 @@ Process process = pb.start(); process.getOutputStream().close(); - //StringBuilder sb = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"))) { String line; while ((line = reader.readLine()) != null) { -// System.out.println(line); - //sb.append(line); log.info(line); } } @@ -402,18 +383,6 @@ return null; } } - - /*private String callZarr2tif(SimuData data) throws Exception { - File uwBat = new File(config.getUwSolverBat()); - String zarrFile = uwBat.getParent() + File.separator + "result.zarr"; - String inPath = config.getInPath() + File.separator + data.getInPath(); - String terrainFile = inPath + File.separator + config.getTerrainFile(); - String waterPath = inPath + File.separator + "depth"; - - String cmd = String.format("%s \"%s\" \"%s\" \"%s\" \"%s\"", config.getZarr2tifBat(), "depth", zarrFile, terrainFile, waterPath); - - return callBat(cmd); - }*/ private String callBat(String cmd) { try { @@ -442,9 +411,6 @@ } private void createNsl(SimuData data) throws Exception { - /*String inPath = config.getInPath() + File.separator + data.getInPath() + File.separator + "depth"; - procTifs(inPath, inPath, data.getStartTime());*/ - testService.test(data); } @@ -472,7 +438,6 @@ public String createRainfallCsv(String csvPath, String mode, double total, double intensity, int hours) { // python 鑴氭湰鍚�.py <鍙傛暟1-csv鏂囦欢鍚�> <鍙傛暟2-闄嶉洦妯″紡:姝f�佸垎甯億骞冲潎鍒嗗竷|娉㈠姩骞冲潎鍒嗗竷|鎸佺画涓婂崌> <鍙傛暟3-闄嶉洦鎬婚噺> <鍙傛暟4-鏈�澶ч洦寮�> <鍙傛暟5-闄嶉洦鏃堕棿(鍒嗛挓)> String cmd = String.format("%s \"%s\" \"%s\" %f %f %d", config.getCreateRainfall(), csvPath, mode, total, intensity, hours * 60); - return callBat(cmd); } @@ -545,4 +510,125 @@ Files.write(Paths.get(dat), list, StandardCharsets.UTF_8); } + + //瀹炴椂妯℃嫙 + public String realTimeSimulate(RealTimeInput input) throws IOException { + long currentTime = System.currentTimeMillis(); + //鏍规嵁鏈嶅姟鎵惧埌鎸囧畾鐨勬枃浠跺す + String serviceName = input.getServiceName(); + File serviceNameDir = new File(config.getInPath(), serviceName); + //鐢熸垚涓�涓柊鐨勯洦閲忔枃浠�,闇�瑕佸師鍏堥洦閲忔枃浠剁殑涓�浜涗俊鎭紝鎵�浠ラ渶瑕佸厛璇诲彇鏃х殑 + String[] values = readTheOldFirstLineRainfallValue(serviceNameDir); + File newDatFile = generateNewRainfallFile(input, values, serviceNameDir, currentTime); + + //鐢熸垚涓�涓柊鐨勭敓鎴恴arr鐨勯厤缃枃浠� + File newConfigFile = generateNewZarrConfigFile(serviceNameDir, serviceName, currentTime, newDatFile); + //鎵ц姹傝В鍣ㄨ繍绠� + String cmd = String.format("%s \"%s\"", config.getUwSolverBat(), newConfigFile); + callBat2(cmd); + + //鐢熸垚涓�涓柊鐨剒arr杞瑃if鐨刯son鏂囦欢 + File newZarr2TifJson = generateNewZarr2TifJson(serviceNameDir, currentTime); + //鎵цzarr杞瑃if + String zarr2TifCmd = String.format("%s \"%s\"", config.getZarr2tifBat(), newZarr2TifJson); + callBat2(zarr2TifCmd); + //杩斿洖鏂扮殑layer.json鍚嶇О + return generateLayerJsonAndPng(serviceName, serviceNameDir, currentTime); + + } + + private String generateLayerJsonAndPng(String serviceName, File serviceNameDir, long currentTime) throws IOException { + ResultDto resultDto = new ResultDto(); + resultDto.setServiceName(serviceName); + File temp = Paths.get(config.getOutPath(), serviceName, "temp").toFile(); + if (!temp.exists()) temp.mkdir(); + resultDto.setTemp(temp.getAbsolutePath()); + resultDto.setOutPath(Paths.get(config.getOutPath(), serviceName).toString()); + File dem = new File(serviceNameDir, "DEM.tif"); + resultDto.setTerrainFile(dem.getAbsolutePath()); + File newDepthDir = new File(serviceNameDir + File.separator + "depth_" + currentTime); + File[] files = newDepthDir.listFiles(); + resultDto.setWaterPath(newDepthDir.getAbsolutePath()); + LayerDto layerDto = new LayerDto(config.getVer(), 4548, config.getSizes()); + String newLayerJsonName = "layer_" + currentTime + ".json"; + layerDto.setName(newLayerJsonName); + testService.processRealTime(resultDto, layerDto); + return newLayerJsonName; + } + +// private static void readDemData(File serviceNameDir, LayerDto layerDto) { +// File dem = new File(serviceNameDir, "DEM.tif"); +// Dataset ds = gdal.Open(dem.getAbsolutePath(), gdalconstConstants.GA_ReadOnly); +// Band band = ds.GetRasterBand(1); +// int width = ds.getRasterXSize(); +// int height = ds.getRasterYSize(); +// float[] buffer = new float[width * height]; +// band.ReadRaster(0, 0, width, height, buffer); +// layerDto.getTerrain().getVals().put(width + "_" + height, buffer); +// } + + private static File generateNewZarr2TifJson(File serviceNameDir, long currentTime) throws IOException { + File srcZarr2TifJson = new File(serviceNameDir, "zarr2tif.json"); + ObjectMapper mapper = new ObjectMapper(); + Zarr2Tif zarr2Tif = mapper.readValue(srcZarr2TifJson, Zarr2Tif.class); + //淇敼zarr2tif瀵硅薄涓殑瀛楁 + String stamp = TimeFormatUtil.formatTime(currentTime, "yyyy-MM-dd HH:mm:ss"); + zarr2Tif.setStart_timestamp(stamp); + String newZarrPath = serviceNameDir + File.separator + "result_" + currentTime + ".zarr"; + zarr2Tif.setZarr_file(newZarrPath); + zarr2Tif.setGeotiff_dir(serviceNameDir + File.separator + "depth_" + currentTime); + File newZarr2TifJson = new File(serviceNameDir, "zarr2tif_" + currentTime + ".json"); + mapper.writeValue(newZarr2TifJson, zarr2Tif); + return newZarr2TifJson; + } + + private File generateNewZarrConfigFile(File serviceNameDir, String serviceName, long currentTime, File newDatFile) throws IOException { + File configFile = new File(serviceNameDir, serviceName + ".json"); + String str = Files.readAllLines(configFile.toPath()).stream().collect(Collectors.joining()); + ConfigVo configVo = JSON.parseObject(str, ConfigVo.class); + configVo.setDuration(300); //鍥哄畾涓�5min + configVo.getRaingage().set(0, newDatFile.getAbsolutePath()); //raingage file + ResultVo result = configVo.getResult(); + result.setSave_interval(60); //60s鐢熸垚涓�甯� + result.setSave_frames(5); //淇濈暀5甯� + String newZarrPath = serviceNameDir + File.separator + "result_" + currentTime + ".zarr"; + result.setSave_name(newZarrPath); + ObjectMapper mapper = new ObjectMapper(); + File newConfigFile = new File(serviceNameDir, currentTime + ".json"); + mapper.writeValue(newConfigFile, configVo); + return newConfigFile; + } + + private File generateNewRainfallFile(RealTimeInput input, String[] values, File serviceNameDir, long currentTime) throws IOException { + String station = values[0]; + double lon = Double.parseDouble(values[1]); + double lat = Double.parseDouble(values[2]); + String title = config.getRainfallTitle(); + List<String> newLines = new ArrayList<>(); + newLines.add(title); + List<RealTimeInput.RealTimeData> data = input.getData(); + for (RealTimeInput.RealTimeData rd : data) { + LocalDateTime dateTime = rd.getDateTime(); + int year = dateTime.getYear(); + int month = dateTime.getMonthValue(); + int day = dateTime.getDayOfMonth(); + int hour = dateTime.getHour(); + int minute = dateTime.getMinute(); + double intensity = rd.getIntensity(); //淇濈暀鎸囧畾浣嶆暟灏忔暟 + String l = String.format("%s %s %s %s %s %s %s %s %s", + station, lon, lat, year, month, day, hour, minute, String.format("%.6f", intensity)); + newLines.add(l); + } + File newDatFile = new File(serviceNameDir, "rainfall_" + currentTime + ".dat"); + if (!newDatFile.exists()) newDatFile.createNewFile(); + Files.write(newDatFile.toPath(), newLines, StandardOpenOption.TRUNCATE_EXISTING); + return newDatFile; + } + + private static String[] readTheOldFirstLineRainfallValue(File serviceNameDir) throws IOException { + File srcRailfallFile = new File(serviceNameDir, "rainfall.dat"); + List<String> lines = Files.readAllLines(srcRailfallFile.toPath()); + String secondLine = lines.get(1); + return secondLine.split(" "); + } } -- Gitblit v1.9.3