IsolatedLinesFinder.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. package com.shkpr.service.alambizplugin.components.checker;
  2. import com.global.base.log.LogLevelFlag;
  3. import com.global.base.log.LogPrintMgr;
  4. import com.shkpr.service.alambizplugin.commtools.BeanUtil;
  5. import com.shkpr.service.alambizplugin.components.AsyncResultManager;
  6. import com.shkpr.service.alambizplugin.constants.GisSurveySystemCheckKeys;
  7. import com.shkpr.service.alambizplugin.constants.GisSurveySystemCheckResultHead;
  8. import com.shkpr.service.alambizplugin.constants.LogFlagBusiType;
  9. import com.shkpr.service.alambizplugin.dto.GisSurveyLayerApplyLine;
  10. import com.shkpr.service.alambizplugin.dto.GisSurveySystemCheckElement;
  11. import com.shkpr.service.alambizplugin.dto.GisSurveySystemCheckId;
  12. import com.shkpr.service.alambizplugin.dto.GisSurveySystemCheckResultDetail;
  13. import org.springframework.scheduling.annotation.Async;
  14. import org.springframework.scheduling.annotation.AsyncResult;
  15. import org.springframework.stereotype.Component;
  16. import org.springframework.util.concurrent.ListenableFuture;
  17. import java.nio.file.Path;
  18. import java.util.ArrayList;
  19. import java.util.HashMap;
  20. import java.util.List;
  21. import java.util.Map;
  22. import java.util.stream.Collectors;
  23. import java.util.stream.IntStream;
  24. /**
  25. * 孤立线查找
  26. *
  27. * @author 欧阳劲驰
  28. * @since 1.0.0
  29. */
  30. @Component
  31. public class IsolatedLinesFinder {
  32. /**
  33. * log
  34. */
  35. private final String mStrClassName;
  36. private final String mBizType;
  37. private final AsyncResultManager asyncResultManager;
  38. public IsolatedLinesFinder(AsyncResultManager asyncResultManager) {
  39. mStrClassName = "IsolatedLinesFinder";
  40. mBizType = LogFlagBusiType.BUSI_GIS_SURVEY.toStrValue();
  41. this.asyncResultManager = asyncResultManager;
  42. }
  43. /**
  44. * 寻找孤立线
  45. *
  46. * @param lines 线集合
  47. * @return 线分组
  48. */
  49. @Async
  50. public ListenableFuture<GisSurveySystemCheckResultDetail> findIsolatedLines(List<GisSurveyLayerApplyLine> lines
  51. , GisSurveySystemCheckId systemCheckId) throws InterruptedException {
  52. LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_INFO, mBizType, mStrClassName, "开始执行寻找孤立线========>");
  53. long begin = System.currentTimeMillis();
  54. //创建并查集
  55. UnionFind unionFind = new UnionFind();
  56. //分组线
  57. List<List<GisSurveySystemCheckElement>> groupElements = unionFind.groupLines(lines);
  58. return new AsyncResult<>(createResult(groupElements, systemCheckId, begin));
  59. }
  60. /**
  61. * 创建结果
  62. *
  63. * @param data 数据
  64. * @param systemCheckId 系统检查id
  65. * @param begin 开始时间
  66. * @return 结果
  67. */
  68. private GisSurveySystemCheckResultDetail createResult(List<List<GisSurveySystemCheckElement>> data
  69. , GisSurveySystemCheckId systemCheckId, long begin) {
  70. long end = System.currentTimeMillis();
  71. LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_INFO, mBizType, mStrClassName
  72. , String.format(
  73. "结束执行寻找孤立线,用时(毫秒):%d"
  74. , (end - begin)
  75. )
  76. );
  77. //数据大小
  78. final int size = data.size();
  79. //结果flag
  80. final String FLAG = systemCheckId.getFlag();
  81. //写入json和excel结果
  82. Path jsonPath = asyncResultManager.writeJson(data, FLAG, GisSurveySystemCheckKeys.ISOLATED_LINES + ".json");
  83. Path excelPath = asyncResultManager.writeExcel(GisSurveySystemCheckResultHead.ISOLATED_LINES,
  84. buildExcel(data), FLAG, GisSurveySystemCheckKeys.ISOLATED_LINES + ".xlsx");
  85. //构建结果
  86. return new GisSurveySystemCheckResultDetail(true
  87. , FLAG + "/" + jsonPath.getFileName()
  88. , FLAG + "/" + excelPath.getFileName()
  89. , size);
  90. }
  91. /**
  92. * 构建excel数据
  93. *
  94. * @param data 数据
  95. * @return excel数据
  96. */
  97. private List<Map<String, Object>> buildExcel(List<List<GisSurveySystemCheckElement>> data) {
  98. return IntStream.range(0, data.size())
  99. .boxed()
  100. .flatMap(i -> data.get(i).stream().map(element -> {
  101. Map<String, Object> map = new HashMap<>();
  102. map.put(GisSurveySystemCheckResultHead.KEYS.GROUP_NAME, i + 1);
  103. map.put(GisSurveySystemCheckResultHead.KEYS.UP_NO, element.getUpNo());
  104. map.put(GisSurveySystemCheckResultHead.KEYS.DOWN_NO, element.getDownNo());
  105. map.put(GisSurveySystemCheckResultHead.KEYS.CODE, element.getCode());
  106. map.put(GisSurveySystemCheckResultHead.KEYS.UP_NODE, element.getUpNode());
  107. map.put(GisSurveySystemCheckResultHead.KEYS.DOWN_NODE, element.getDownNode());
  108. map.put(GisSurveySystemCheckResultHead.KEYS.NAME, element.getName());
  109. return map;
  110. })).collect(Collectors.toList());
  111. }
  112. /**
  113. * 并查集
  114. */
  115. public static class UnionFind {
  116. //线的子父关系,key:子,value:父(可能为根)
  117. private final Map<String, String> parent = new HashMap<>();
  118. //点根线关系,{线的节点编码}->{根线编码}
  119. private final Map<String, String> pointRoot = new HashMap<>();
  120. //秩,通常树的根节点为1
  121. private final Map<String, Integer> rank = new HashMap<>();
  122. /**
  123. * 线分组
  124. *
  125. * @param lines 线集合
  126. * @return 分组集合
  127. */
  128. public List<List<GisSurveySystemCheckElement>> groupLines(List<GisSurveyLayerApplyLine> lines) throws InterruptedException {
  129. //处理所有线
  130. for (GisSurveyLayerApplyLine line : lines) {
  131. //响应中断
  132. if (Thread.interrupted()) throw new InterruptedException();
  133. //初始化节点
  134. initNode(line.getCode());
  135. //当前code
  136. String currentRoot = line.getCode();
  137. //处理起点,合并当前线与以upNode为终点的根线
  138. if (pointRoot.containsKey(line.getUpNode())) {
  139. String existingRoot = pointRoot.get(line.getUpNode());
  140. currentRoot = unionAndGetRoot(currentRoot, existingRoot);
  141. }
  142. //处理终点,合并当前线与以downNode为终点的根线
  143. if (pointRoot.containsKey(line.getDownNode())) {
  144. String existingRoot = pointRoot.get(line.getDownNode());
  145. currentRoot = unionAndGetRoot(currentRoot, existingRoot);
  146. }
  147. //更新当前节点的根线映射
  148. updateRootMappings(line.getUpNode(), currentRoot);
  149. updateRootMappings(line.getDownNode(), currentRoot);
  150. }
  151. //清理关系表
  152. pointRoot.clear();
  153. //构建分组结果
  154. Map<String, List<GisSurveySystemCheckElement>> groups = new HashMap<>();
  155. for (GisSurveyLayerApplyLine line : lines) {
  156. //响应中断
  157. if (Thread.interrupted()) throw new InterruptedException();
  158. //当前线code
  159. String lineCode = line.getCode();
  160. //根线code
  161. String rootCode = findRoot(lineCode);
  162. //当前线存入根线组
  163. groups.computeIfAbsent(rootCode, k -> new ArrayList<>())
  164. //转为返回元素
  165. .add(BeanUtil.copy(line, GisSurveySystemCheckElement.class));
  166. }
  167. return new ArrayList<>(groups.values());
  168. }
  169. /**
  170. * 更新节点对应的根线映射
  171. *
  172. * @param node 节点
  173. * @param currentRoot 当前节点的根线
  174. */
  175. private void updateRootMappings(String node, String currentRoot) throws InterruptedException {
  176. //获取点根线关系,如存在该关系,则再寻找一次根线,保证多点根一致
  177. String existingRoot = pointRoot.get(node);
  178. if (existingRoot != null) currentRoot = unionAndGetRoot(currentRoot, existingRoot);
  179. //更新点根线关系
  180. pointRoot.put(node, currentRoot);
  181. }
  182. /**
  183. * 初始化节线
  184. *
  185. * @param code 节点code
  186. */
  187. public void initNode(String code) {
  188. parent.computeIfAbsent(code, k -> {
  189. rank.put(k, 0);
  190. return k;
  191. });
  192. }
  193. /**
  194. * 查找根节点
  195. *
  196. * @param code 节点code
  197. * @return 根节点code
  198. */
  199. public String findRoot(String code) throws InterruptedException {
  200. //当前code
  201. String current = code;
  202. //最大迭代深度(该算法时间为常数级,如查找深度到64则为程序异常)
  203. int maxIterationsDepth = 64;
  204. //迭代记录,防止无限递归
  205. int iterations = 0;
  206. while (iterations++ < maxIterationsDepth) {
  207. //响应中断
  208. if (Thread.interrupted()) throw new InterruptedException();
  209. //提取父节点
  210. String parentNode = parent.get(current);
  211. // 找到根节点立即返回
  212. if (parentNode.equals(current)) return current;
  213. //当前节点指向祖父节点,路径减半(已知子父关系,故跳过)
  214. String grandparent = parent.get(parentNode);
  215. parent.put(current, grandparent);
  216. current = grandparent;
  217. }
  218. //递归保险,最终强制验证是否为根节点,否则结束查找
  219. if (parent.get(current).equals(current)) return current;
  220. else throw new IllegalStateException("该code无法查询到根节点: " + code);
  221. }
  222. /**
  223. * 合并并返回根线
  224. *
  225. * @param current 当前线
  226. * @param target 目标线
  227. * @return 根线
  228. */
  229. public String unionAndGetRoot(String current, String target) throws InterruptedException {
  230. //获取两线的根线
  231. String rootCurrent = findRoot(current);
  232. String rootTarget = findRoot(target);
  233. //排除根线相同
  234. if (rootCurrent.equals(rootTarget)) return rootCurrent;
  235. //按秩合并,如 当前线根节点秩 大于 目标线根节点秩,则 目标线根线 为 当前线根线 的下游线
  236. if (rank.get(rootCurrent) > rank.get(rootTarget)) {
  237. parent.put(rootTarget, rootCurrent);
  238. return rootCurrent;
  239. } else {
  240. //否则 当前线根线 为 目标线根线 的下游线
  241. parent.put(rootCurrent, rootTarget);
  242. //如线秩相同,则对根线升秩
  243. if (rank.get(rootCurrent).equals(rank.get(rootTarget))) {
  244. rank.put(rootTarget, rank.get(rootTarget) + 1);
  245. }
  246. return rootTarget;
  247. }
  248. }
  249. }
  250. }