Selaa lähdekoodia

dev并入当前分支

louhr 5 vuotta sitten
vanhempi
commit
4b33e00073
63 muutettua tiedostoa jossa 2671 lisäystä ja 781 poistoa
  1. 130 0
      algorithm/src/main/java/org/algorithm/core/FilterRule.java
  2. 282 0
      algorithm/src/main/java/org/algorithm/core/RelationTreeUtils.java
  3. 493 0
      algorithm/src/main/java/org/algorithm/core/RuleCheckMachine.java
  4. 3 4
      algorithm/src/main/java/org/algorithm/core/cnn/AlgorithmCNNExecutor.java
  5. 22 0
      algorithm/src/main/java/org/algorithm/core/cnn/AlgorithmCNNExecutorPacs.java
  6. 1 1
      algorithm/src/main/java/org/algorithm/core/cnn/dataset/RelationExtractionDataSet.java
  7. 32 1
      algorithm/src/main/java/org/algorithm/core/cnn/entity/Lemma.java
  8. 40 13
      algorithm/src/main/java/org/algorithm/core/cnn/model/RelationExtractionEnsembleModel.java
  9. 4 4
      algorithm/src/main/java/org/algorithm/core/cnn/model/RelationExtractionModel.java
  10. 33 0
      algorithm/src/main/java/org/algorithm/factory/RelationExtractionFactory.java
  11. 5 3
      algorithm/src/main/java/org/algorithm/test/ReEnsembleModelTest.java
  12. 15 0
      algorithm/src/main/java/org/algorithm/test/TestRelationTreeUtils.java
  13. 140 0
      algorithm/src/main/java/org/algorithm/test/TestRuleCheckMachine.java
  14. 1 1
      algorithm/src/main/java/org/algorithm/util/MysqlConnector.java
  15. 3 1
      bigdata-web/src/main/java/org/diagbot/bigdata/work/AlgorithmCore.java
  16. 16 26
      bigdata-web/src/main/java/org/diagbot/bigdata/work/BigDataParamsProxy.java
  17. 66 0
      bigdata-web/src/main/java/org/diagbot/bigdata/work/ResultDataProxy.java
  18. 0 6
      common-push/pom.xml
  19. 11 0
      common-push/src/main/java/org/diagbot/common/push/bean/SearchData.java
  20. 83 0
      common-push/src/main/java/org/diagbot/common/push/cache/ApplicationCacheUtil.java
  21. 61 5
      common-push/src/main/java/org/diagbot/common/push/cache/CacheFileManager.java
  22. 95 39
      common-push/src/main/java/org/diagbot/common/push/filter/ClassifyDiag.java
  23. 0 59
      common-push/src/main/java/org/diagbot/common/push/filter/pretreat/PretreatmentLis.java
  24. 0 51
      common-push/src/main/java/org/diagbot/common/push/filter/pretreat/PretreatmentPacs.java
  25. 2 11
      common-push/src/main/java/org/diagbot/common/push/filter/rule/PretreatmentRule.java
  26. 22 0
      common-push/src/main/java/org/diagbot/common/push/util/PushConstants.java
  27. 20 27
      common-push/src/main/java/org/diagbot/common/push/work/ParamsDataProxy.java
  28. 95 0
      common-push/src/main/java/org/diagbot/common/push/work/RelationExtractionUtil.java
  29. 28 317
      graph-web/src/main/java/org/diagbot/graphWeb/work/GraphCalculate.java
  30. 1 1
      graph-web/src/main/java/org/diagbot/graphWeb/work/ScaleCalculate.java
  31. 46 41
      graph/src/main/java/org/diagbot/graph/jdbc/Neo4jAPI.java
  32. 4 3
      graph/src/main/resources/bolt.properties
  33. 1 1
      graphdb/src/main/java/org/diagbot/pub/Ciku.java
  34. 184 0
      graphdb/src/main/java/org/diagbot/repository/BiRepository.java
  35. 11 2
      graphdb/src/main/java/org/diagbot/repository/DiseaseRepository.java
  36. 2 0
      graphdb/src/main/java/org/diagbot/service/KnowledgeService.java
  37. 83 46
      graphdb/src/main/java/org/diagbot/service/impl/KnowledgeServiceImpl.java
  38. 31 0
      graphdb/src/main/java/org/diagbot/vo/domain/BiDetail.java
  39. 11 0
      graphdb/src/main/java/org/diagbot/web/KnowledgeController.java
  40. 2 2
      graphdb/src/main/resources/application.yml
  41. 60 51
      nlp-web/src/main/java/org/diagbot/nlp/controller/FeatureController.java
  42. 7 0
      nlp/src/main/java/org/diagbot/nlp/feature/FeatureAnalyze.java
  43. 31 2
      nlp/src/main/java/org/diagbot/nlp/feature/extract/CaseToken.java
  44. 33 15
      nlp/src/main/java/org/diagbot/nlp/participle/ParticipleUtil.java
  45. 17 0
      nlp/src/main/java/org/diagbot/nlp/rule/analyze/RuleAnalyze.java
  46. 1 1
      common-push/src/main/java/org/diagbot/common/push/bean/PreResult.java
  47. 4 2
      common-push/src/main/java/org/diagbot/common/push/filter/pretreat/Pretreatment.java
  48. 2 2
      common-push/src/main/java/org/diagbot/common/push/filter/pretreat/PretreatmentDiag.java
  49. 86 0
      nlp/src/main/java/org/diagbot/nlp/rule/pretreat/PretreatmentLis.java
  50. 2 2
      common-push/src/main/java/org/diagbot/common/push/filter/pretreat/PretreatmentMakeList.java
  51. 2 4
      common-push/src/main/java/org/diagbot/common/push/filter/pretreat/PretreatmentNormal.java
  52. 2 2
      common-push/src/main/java/org/diagbot/common/push/filter/pretreat/PretreatmentOther.java
  53. 127 0
      nlp/src/main/java/org/diagbot/nlp/rule/pretreat/PretreatmentPacs.java
  54. 2 2
      common-push/src/main/java/org/diagbot/common/push/filter/pretreat/PretreatmentSymptom.java
  55. 2 2
      common-push/src/main/java/org/diagbot/common/push/filter/pretreat/PretreatmentVital.java
  56. 14 0
      nlp/src/main/java/org/diagbot/nlp/util/NlpCache.java
  57. 2 6
      nlp/src/main/java/org/diagbot/nlp/util/NlpUtil.java
  58. 5 2
      nlp/src/main/resources/nlp.properties
  59. 58 23
      push-web/src/main/java/org/diagbot/push/controller/AlgorithmController.java
  60. 2 0
      push-web/src/main/java/org/diagbot/push/controller/CacheFileManagerController.java
  61. 11 0
      push-web/src/main/java/org/diagbot/push/controller/ParticipleController.java
  62. 21 0
      rule/src/main/java/org/diagbot/rule/crisis/CrisisApplication.java
  63. 101 0
      rule/src/main/java/org/diagbot/rule/lis/LisApplication.java

+ 130 - 0
algorithm/src/main/java/org/algorithm/core/FilterRule.java

@@ -0,0 +1,130 @@
+package org.algorithm.core;
+
+import java.util.Map;
+
+/**
+ * 过滤规则
+ *
+ * @Author: bijl
+ * @Date: 2019/9/5 20:21
+ * @Description:
+ */
+public class FilterRule {
+
+    private Integer uuid;
+
+    private String key_1;
+    private String type_1;
+
+    private String key_2;
+    private String type_2;
+
+    private String inside;
+    private String insideType;
+
+    private String despite;
+    private String despiteInside;
+
+    public FilterRule(Map<String, String> aMap) {
+
+        this.key_1 = aMap.get("key_1");
+        this.type_1 = aMap.get("type_1");
+
+        this.key_2 = aMap.get("key_2");
+        this.type_2 = aMap.get("type_2");
+
+        this.inside = aMap.get("inside");
+        this.insideType = aMap.get("inside_type");
+
+        this.despite = aMap.get("despite");
+        this.despiteInside = aMap.get("despite_inside");
+    }
+
+    public Integer getUuid() {
+        return uuid;
+    }
+
+    public void setUuid(Integer uuid) {
+        this.uuid = uuid;
+    }
+
+
+    public String getKey_1() {
+        return key_1;
+    }
+
+    public void setKey_1(String key_1) {
+        this.key_1 = key_1;
+    }
+
+    public String getType_1() {
+        return type_1;
+    }
+
+    public void setType_1(String type_1) {
+        this.type_1 = type_1;
+    }
+
+    public String getKey_2() {
+        return key_2;
+    }
+
+    public void setKey_2(String key_2) {
+        this.key_2 = key_2;
+    }
+
+    public String getType_2() {
+        return type_2;
+    }
+
+    public void setType_2(String type_2) {
+        this.type_2 = type_2;
+    }
+
+    public String getInside() {
+        return inside;
+    }
+
+    public void setInside(String inside) {
+        this.inside = inside;
+    }
+
+    public String getInsideType() {
+        return insideType;
+    }
+
+    public void setInsideType(String insideType) {
+        this.insideType = insideType;
+    }
+
+    public String getDespite() {
+        return despite;
+    }
+
+    public void setDespite(String despite) {
+        this.despite = despite;
+    }
+
+    public String getDespiteInside() {
+        return despiteInside;
+    }
+
+    public void setDespiteInside(String despiteInside) {
+        this.despiteInside = despiteInside;
+    }
+
+    @Override
+    public String toString() {
+        return "FilterRule{" +
+                "uuid=" + uuid +
+                ", key_1='" + key_1 + '\'' +
+                ", type_1='" + type_1 + '\'' +
+                ", key_2='" + key_2 + '\'' +
+                ", type_2='" + type_2 + '\'' +
+                ", inside='" + inside + '\'' +
+                ", insideType='" + insideType + '\'' +
+                ", despite='" + despite + '\'' +
+                ", despiteInside='" + despiteInside + '\'' +
+                '}';
+    }
+}

+ 282 - 0
algorithm/src/main/java/org/algorithm/core/RelationTreeUtils.java

@@ -0,0 +1,282 @@
+package org.algorithm.core;
+
+import org.algorithm.core.cnn.entity.Lemma;
+import org.algorithm.core.cnn.entity.Triad;
+
+import java.util.*;
+
+/**
+ * 关系树工具类
+ *
+ * @Author: bijl
+ * @Date: 2019/9/5 15:16
+ * @Description:
+ */
+public class RelationTreeUtils {
+
+    /**
+     * 同名实体(这里也叫词项)归并
+     * 规则:
+     * 1- 直接替代为位置最前面的一个
+     *
+     * @param triads 实体对列表
+     */
+    public static void sameTextLemmaMerge(List<Triad> triads) {
+
+        Map<String, Lemma> lemmaMap = new HashMap<>();
+        for (Triad triad : triads) {
+            Lemma l1 = triad.getL_1();
+            Lemma l2 = triad.getL_2();
+
+            if (lemmaMap.get(l1.getText()) == null)
+                lemmaMap.put(l1.getText(), l1);
+            else {
+                Lemma l1Pre = lemmaMap.get(l1.getText());
+                if (l1Pre.getStartPosition() > l1.getStartPosition())
+                    triad.setL_1(l1);  // 取靠前的
+            }
+
+            if (lemmaMap.get(l2.getText()) == null)
+                lemmaMap.put(l2.getText(), l2);
+            else {
+                Lemma l2Pre = lemmaMap.get(l2.getText());
+                if (l2Pre.getStartPosition() > l2.getStartPosition())
+                    triad.setL_2(l2);  // 取靠前的
+            }
+        }
+        for (Triad triad : triads) {
+            Lemma l1 = triad.getL_1();
+            Lemma l2 = triad.getL_2();
+            triad.setL_1(lemmaMap.get(l1.getText()));  // 用前面的同名实体(这里也叫词项)替代后面的
+            triad.setL_2(lemmaMap.get(l2.getText()));  // 用前面的同名实体(这里也叫词项)替代后面的
+        }
+    }
+
+    /**
+     * 构建关系树
+     * 基本规则:
+     * 1- 两个有关系的实体,前面的为父节点,后面的为子节点
+     *
+     * @param triads 有关系的三元组列表
+     */
+    public static void buildRelationTree(List<Triad> triads) {
+        for (Triad triad : triads) {
+            Lemma l1 = triad.getL_1();
+            Lemma l2 = triad.getL_2();
+            if (l1.getStartPosition() < l2.getStartPosition()) {  // 在前者为父节点
+                l1.setHaveChildren(true);
+                l2.setParent(l1);
+            } else {
+                l2.setHaveChildren(true);
+                l1.setParent(l2);
+            }
+        }
+    }
+
+    /**
+     * 获取关系树的分枝
+     *
+     * @param triads 有关系,并且设置了父子节点关系的三元组
+     */
+    public static List<List<String>> getRelationTreeBranches(List<Triad> triads) {
+        Map<Lemma, Integer> leafNodeLemmas = new HashMap<>();
+
+        for (Triad triad : triads) {
+            if (!triad.getL_1().isHaveChildren())
+                leafNodeLemmas.putIfAbsent(triad.getL_1(), 1);
+
+            if (!triad.getL_2().isHaveChildren())
+                leafNodeLemmas.putIfAbsent(triad.getL_2(), 1);
+        }
+
+        List<List<String>> branches = new ArrayList<>();
+        for (Lemma lemma : leafNodeLemmas.keySet()) {
+            List<Lemma> aBranch = new ArrayList<>();
+            while (lemma != null) {
+                aBranch.add(lemma);
+                lemma = lemma.getParent();
+            }
+            aBranch.sort(Comparator.naturalOrder());  // 按位置排序
+            branches.addAll(handleBranch(aBranch));
+        }
+
+
+        return branches;
+    }
+
+    /**
+     * 处理分枝,要求组合非阴性词,阴性词必须包含
+     * 操作:
+     * 1- 分离阴性词和非阴性词
+     * 2- 组合非阴性词
+     * 3- 添加阴性词到组合结果中
+     *
+     * @param aBranch
+     * @return
+     */
+    private static List<List<String>> handleBranch(List<Lemma> aBranch) {
+        List<Lemma> nonNegativeLemmas = new ArrayList<>();
+        List<Lemma> negativeLemmas = new ArrayList<>();
+        for (Lemma lemma : aBranch) {
+            if ("反意或虚拟".equals(lemma.getProperty()))
+                negativeLemmas.add(lemma);
+            else
+                nonNegativeLemmas.add(lemma);
+        }
+        List<List<Lemma>> nonNegativeLemmaCombinations = new ArrayList<>();
+        if (nonNegativeLemmas.size() > 0) {
+            for (int i = 1; i <= nonNegativeLemmas.size(); i++) {
+                combinerSelect(nonNegativeLemmas, new ArrayList<>(), nonNegativeLemmaCombinations,
+                        nonNegativeLemmas.size(), i);
+            }
+        }
+        List<List<String>> result = new ArrayList<>();
+        for (List<Lemma> lemmaCombination : nonNegativeLemmaCombinations) {
+            List<String> lemmaNames = new ArrayList<>();
+            lemmaCombination.addAll(negativeLemmas);  // 阴性词加入到组合中
+            lemmaCombination.sort(Comparator.naturalOrder());  // 按位置排序
+            for (Lemma lemma : lemmaCombination)  // 取出名称
+                lemmaNames.add(lemma.getText());
+            if (lemmaNames.size() >= 2)
+                result.add(lemmaNames);
+        }
+
+        return result;
+
+    }
+
+    /**
+     * 从三元组列表到关系树分枝
+     *
+     * @param triads
+     * @return
+     */
+    public static List<List<String>> triadsToRelationTreeBranches(List<Triad> triads) {
+//        sameTextLemmaMerge(triads);
+        buildRelationTree(triads);
+        return getRelationTreeBranches(triads);
+    }
+
+    /**
+     * 组合生成器
+     *
+     * @param data      原始数据
+     * @param workSpace 自定义一个临时空间,用来存储每次符合条件的值
+     * @param k         C(n,k)中的k
+     */
+    private static <E> void combinerSelect(List<E> data, List<E> workSpace, List<List<E>> result, int n, int k) {
+        List<E> copyData;
+        List<E> copyWorkSpace = null;
+
+        if (workSpace.size() == k) {
+//            for (E c : workSpace)
+//                System.out.print(c);
+
+            result.add(new ArrayList<>(workSpace));
+//            System.out.println();
+        }
+
+        for (int i = 0; i < data.size(); i++) {
+            copyData = new ArrayList<E>(data);
+            copyWorkSpace = new ArrayList<E>(workSpace);
+
+            copyWorkSpace.add(copyData.get(i));
+            for (int j = i; j >= 0; j--)
+                copyData.remove(j);
+            combinerSelect(copyData, copyWorkSpace, result, n, k);
+        }
+    }
+
+    /**
+     * 全排列算法
+     *
+     * @param stringList 字符串列表
+     * @return
+     */
+    public static ArrayList<ArrayList<String>> permute(List<String> stringList) {
+        ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();
+        result.add(new ArrayList<String>());
+
+        for (int i = 0; i < stringList.size(); i++) {
+            //list of list in current iteration of the stringList num
+            ArrayList<ArrayList<String>> current = new ArrayList<ArrayList<String>>();
+
+            for (ArrayList<String> l : result) {
+                // # of locations to insert is largest index + 1
+                for (int j = 0; j < l.size() + 1; j++) {
+                    // + add num[i] to different locations
+                    l.add(j, stringList.get(i));
+
+                    ArrayList<String> temp = new ArrayList<String>(l);
+                    current.add(temp);
+
+                    // - remove num[i] add
+                    l.remove(j);
+                }
+            }
+
+            result = new ArrayList<>(current);
+        }
+
+        return result;
+    }
+
+
+    /**
+     * 测试文件
+     */
+    public static void test() {
+
+        List<Triad> triads = new ArrayList<>();
+        String[] arr_1 = {"子宫", "0,1", "部位"};
+        String[] arr_2 = {"内膜", "2,3", "结构"};
+        addTriad(arr_1, arr_2, triads);
+
+        String[] arr_1_1 = {"不", "13,13", "反意或虚拟"};
+        String[] arr_2_1 = {"出血", "10,11", "形容词"};
+        addTriad(arr_1_1, arr_2_1, triads);
+
+        String[] arr_1_2 = {"胸部", "15,16", "部位"};
+        String[] arr_2_2 = {"剧烈", "17,18", "程度"};
+        addTriad(arr_1_2, arr_2_2, triads);
+
+        String[] arr_1_3 = {"疼痛", "17,18", "形容词"};
+        String[] arr_2_3 = {"剧烈", "19,20", "程度"};
+        addTriad(arr_1_3, arr_2_3, triads);
+
+        String[] arr_1_4 = {"内膜", "2,3", "结构"};
+        String[] arr_2_4 = {"出血", "10,11", "形容词"};
+        addTriad(arr_1_4, arr_2_4, triads);
+
+        System.out.println(triads.size());
+        sameTextLemmaMerge(triads);
+        buildRelationTree(triads);
+        List<List<String>> info = getRelationTreeBranches(triads);
+
+        System.out.println(info);
+    }
+
+    /**
+     * 增加三元组
+     */
+    private static void addTriad(String[] lemma_1, String[] lemma_2, List<Triad> triads) {
+        Lemma lemma1 = new Lemma();
+        lemma1.setText(lemma_1[0]);
+        lemma1.setPosition(lemma_1[1]);
+        lemma1.setProperty(lemma_1[2]);
+
+        Lemma lemma2 = new Lemma();
+        lemma2.setText(lemma_2[0]);
+        lemma2.setPosition(lemma_2[1]);
+        lemma2.setProperty(lemma_2[2]);
+
+        Triad triad = new Triad();
+        triad.setL_1(lemma1);
+        triad.setL_2(lemma2);
+
+        triads.add(triad);
+
+    }
+
+
+}

+ 493 - 0
algorithm/src/main/java/org/algorithm/core/RuleCheckMachine.java

@@ -0,0 +1,493 @@
+package org.algorithm.core;
+
+import org.algorithm.core.cnn.entity.Lemma;
+import org.algorithm.core.cnn.entity.Triad;
+import org.algorithm.util.MysqlConnector;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.*;
+
+/**
+ * 规则检查机器
+ *
+ * @Author: bijl
+ * @Date: 2019/9/6 10:32
+ * @Description:
+ */
+public class RuleCheckMachine {
+    private final List<FilterRule> filterRules = new ArrayList<>();
+    private Map<String, Map<String, Set<Integer>>> key_1_map = null;
+    private Map<String, Map<String, Set<Integer>>> key_2_map = null;
+    private Map<String, String> punctuations = new HashMap<>();
+    private Map<String, Set<Integer>> despiteMap = null;  // 实体名:[规则uuid列表]
+    private Map<String, Set<Integer>> despiteInsideMap = null; // 实体名:[规则uuid列表]
+    private Map<String, Map<String, Set<Integer>>> insideMap = null;
+
+
+    public RuleCheckMachine() {
+        this.loadRules();
+        this.makeKey1Map();
+        this.makeKey2Map();
+        this.makeInsideMap();
+        this.makeDespiteMap();
+        this.makeDespiteInsideMap();
+    }
+
+
+    /**
+     * 加载规则
+     */
+    public void loadRules() {
+        /**
+         * 连接数据库
+         */
+        String url = "jdbc:mysql://192.168.2.235/test_case?user=root&password=diagbot@20180822";
+        MysqlConnector connector = new MysqlConnector(url);
+        String querySql =
+                "SELECT rr.key_1, rr.type_1, rr.key_2, rr.type_2, rr.inside, rr.inside_type, " +
+                        "rr.despite, rr.despite_inside " +
+                        "FROM relation_neg_rules AS rr " +
+                        "WHERE rr.`status` = 1";
+
+        ResultSet rs = connector.query(querySql);
+        Integer uuid = 0;
+        try {
+            while (rs.next()) {
+                String key_1 = rs.getString("key_1");
+                String type_1 = rs.getString("type_1");
+
+                String key_2 = rs.getString("key_2");
+                String type_2 = rs.getString("type_2");
+
+                String inside = rs.getString("inside");
+                String inside_type = rs.getString("inside_type");
+
+                String despite = rs.getString("despite");
+                String despite_inside = rs.getString("despite_inside");
+
+                String[] despiteSplit = despite.split(",");
+                String[] despiteInsideSplit = despite_inside.split(",");
+                for (int j = 0; j < despiteSplit.length; j++) {
+                    for (int k = 0; k < despiteInsideSplit.length; k++) {
+                        Map<String, String> variableMap = new HashMap<>();
+                        variableMap.put("key_1", key_1);
+                        variableMap.put("type_1", type_1);
+
+                        variableMap.put("key_2", key_2);
+                        variableMap.put("type_2", type_2);
+
+                        variableMap.put("inside", inside);
+                        variableMap.put("inside_type", inside_type);
+
+                        variableMap.put("despite", despiteSplit[j]);
+                        variableMap.put("despite_inside", despiteInsideSplit[k]);
+
+                        FilterRule filterRule = new FilterRule(variableMap);
+                        filterRule.setUuid(uuid);
+                        this.filterRules.add(filterRule);
+
+//                            System.out.println(filterRule);
+
+                        uuid += 1;
+                    }
+                }
+
+            }
+
+        } catch (SQLException e) {
+            e.printStackTrace();
+            throw new RuntimeException("加载规则字典失败");
+        } finally {
+            connector.close();
+        }
+    }
+
+    /**
+     * 制作实体1相关信息字典
+     */
+    private void makeKey1Map() {
+        Map<String, Map<String, Set<Integer>>> key_1_map_ = new HashMap<>();
+        Map<String, Set<Integer>> emptyMap = new HashMap<>();
+        Map<String, Set<Integer>> typeMap = new HashMap<>();
+        Map<String, Set<Integer>> wordMap = new HashMap<>();
+        key_1_map_.put("", emptyMap);
+        key_1_map_.put("type", typeMap);
+        key_1_map_.put("word", wordMap);
+
+        for (FilterRule rule : this.filterRules) {
+            String key_1 = rule.getKey_1();
+            String type_1 = rule.getType_1();
+            Integer uuid = rule.getUuid();
+
+            this.inputMaps(key_1, type_1, uuid, emptyMap, typeMap, wordMap, null);
+        }
+        this.key_1_map = key_1_map_;
+    }
+
+
+    /**
+     * 制作实体2相关信息字典
+     */
+    private void makeKey2Map() {
+        Map<String, Map<String, Set<Integer>>> key_2_map_ = new HashMap<>();
+        Map<String, Set<Integer>> emptyMap = new HashMap<>();
+        Map<String, Set<Integer>> typeMap = new HashMap<>();
+        Map<String, Set<Integer>> wordMap = new HashMap<>();
+        key_2_map_.put("", emptyMap);
+        key_2_map_.put("type", typeMap);
+        key_2_map_.put("word", wordMap);
+
+        for (FilterRule rule : this.filterRules) {
+            String key_2 = rule.getKey_2();
+            String type_2 = rule.getType_2();
+            Integer uuid = rule.getUuid();
+
+            this.inputMaps(key_2, type_2, uuid, emptyMap, typeMap, wordMap, null);
+        }
+        this.key_2_map = key_2_map_;
+    }
+
+    /**
+     * 制作内部实体相关信息字典
+     */
+    private void makeInsideMap() {
+        Map<String, Map<String, Set<Integer>>> insideMap_ = new HashMap<>();
+        Map<String, Set<Integer>> punctuationMap = new HashMap<>();
+        Map<String, Set<Integer>> typeMap = new HashMap<>();
+        Map<String, Set<Integer>> typePunctuationMap = new HashMap<>();
+        Map<String, Set<Integer>> wordMap = new HashMap<>();
+        insideMap_.put("punc", punctuationMap);
+        insideMap_.put("type", typeMap);
+        insideMap_.put("typePunctuation", typePunctuationMap);
+        insideMap_.put("word", wordMap);
+
+        for (FilterRule rule : this.filterRules) {
+            String inside = rule.getInside();
+            String insideType = rule.getInsideType();
+            Integer uuid = rule.getUuid();
+            if (insideType.equals("punc"))
+                this.punctuations.put(inside, inside);
+
+            if (",".equals(inside.substring(0, 1)))
+                this.inputMaps(inside, insideType, uuid, null, typePunctuationMap, wordMap, punctuationMap);
+            else
+                this.inputMaps(inside, insideType, uuid, null, typeMap, wordMap, punctuationMap);
+        }
+        this.insideMap = insideMap_;
+    }
+
+    /**
+     * maps输入
+     *
+     * @param key
+     * @param type
+     * @param uuid
+     * @param emptyMap
+     * @param typeMap
+     * @param wordMap
+     */
+    private void inputMaps(String key, String type, Integer uuid, Map<String, Set<Integer>> emptyMap,
+                           Map<String, Set<Integer>> typeMap, Map<String, Set<Integer>> wordMap,
+                           Map<String, Set<Integer>> punctuationMap) {
+
+        if ("".equals(type)) {
+            if (emptyMap.get(key) == null)
+                emptyMap.put(key, new HashSet<>());
+            emptyMap.get(key).add(uuid);
+        } else if ("type".equals(type)) {
+            if (typeMap.get(key) == null)
+                typeMap.put(key, new HashSet<>());
+            typeMap.get(key).add(uuid);
+        } else if ("word".equals(type)) {
+            if (wordMap.get(key) == null)
+                wordMap.put(key, new HashSet<>());
+            wordMap.get(key).add(uuid);
+        } else if ("punc".equals(type)) {
+            if (punctuationMap.get(key) == null)
+                punctuationMap.put(key, new HashSet<>());
+            punctuationMap.get(key).add(uuid);
+        } else {
+            throw new RuntimeException("出现了位置新type");
+        }
+
+    }
+
+
+    /**
+     * 制作例外字典
+     */
+    private void makeDespiteMap() {
+        Map<String, Set<Integer>> despiteMap = new HashMap<>();
+        for (FilterRule rule : this.filterRules) {
+            String despite = rule.getDespite();
+            if (!despite.equals("")) {  // 空白不收录
+                if (despiteMap.get(despite) == null) {
+                    despiteMap.put(despite, new HashSet<>());
+                }
+                despiteMap.get(despite).add(rule.getUuid());  //
+            }
+        }
+        this.despiteMap = despiteMap;
+    }
+
+
+    /**
+     * 制作例外_内部字典
+     */
+    private void makeDespiteInsideMap() {
+        Map<String, Set<Integer>> despiteInsideMap = new HashMap<>();
+        for (FilterRule rule : this.filterRules) {
+            String despiteInside = rule.getDespiteInside();
+            if (!despiteInside.equals("")) {  // 空白不收录
+                if (despiteInsideMap.get(despiteInside) == null) {
+                    despiteInsideMap.put(despiteInside, new HashSet<>());
+                }
+                despiteInsideMap.get(despiteInside).add(rule.getUuid());  //
+            }
+        }
+        this.despiteInsideMap = despiteInsideMap;
+    }
+
+    /**
+     * 名称—类别—开始位置类
+     */
+    class NameTypeStartPosition implements Comparable<NameTypeStartPosition> {
+        private String name;
+        private String type;
+        private int startPosition;
+
+        public NameTypeStartPosition(String name, String type, int startPosition) {
+            this.name = name;
+            this.type = type;
+            this.startPosition = startPosition;
+        }
+
+        @Override
+        public int compareTo(NameTypeStartPosition o) {
+            return this.startPosition - o.getStartPosition();
+        }
+
+        public String getName() {
+            return name;
+        }
+
+        public void setName(String name) {
+            this.name = name;
+        }
+
+        public String getType() {
+            return type;
+        }
+
+        public void setType(String type) {
+            this.type = type;
+        }
+
+        public int getStartPosition() {
+            return startPosition;
+        }
+
+        public void setStartPosition(int startPosition) {
+            this.startPosition = startPosition;
+        }
+
+        @Override
+        public String toString() {
+            return "NameTypeStartPosition{" +
+                    "name='" + name + '\'' +
+                    ", type='" + type + '\'' +
+                    ", startPosition=" + startPosition +
+                    '}';
+        }
+
+    }
+
+    /**
+     * 获取已排序的(名称,类别,开始位置)对象
+     *
+     * @param triads
+     * @return
+     */
+    public List<NameTypeStartPosition> getSortedNameTypeByPosition(List<Triad> triads) {
+        List<NameTypeStartPosition> nameTypeStartPositions = new ArrayList<>();
+        for (Triad triad : triads) {
+            Lemma l1 = triad.getL_1();
+            Lemma l2 = triad.getL_2();
+            nameTypeStartPositions.add(
+                    new NameTypeStartPosition(l1.getText(), l1.getProperty(), l1.getStartPosition()));
+            nameTypeStartPositions.add(
+                    new NameTypeStartPosition(l2.getText(), l2.getProperty(), l2.getStartPosition()));
+        }
+        nameTypeStartPositions.sort(Comparator.naturalOrder());
+
+        return nameTypeStartPositions;
+    }
+
+    /**
+     * 是否移除
+     *
+     * @param nameTypeStartPositions
+     * @param startIndex
+     * @param endIndex
+     * @return
+     */
+    public boolean isRemove(List<NameTypeStartPosition> nameTypeStartPositions, int startIndex, int endIndex,
+                            String sentence) {
+        Set<Integer> remainUuids = new HashSet<>();  // 剩余规则的uuid
+        for (FilterRule rule : this.filterRules)
+            remainUuids.add(rule.getUuid());
+
+        // 过滤实体名称触发例外条件情况
+        String entity_1_name = nameTypeStartPositions.get(startIndex).getName();
+        String entity_1_type = nameTypeStartPositions.get(startIndex).getType();
+
+        String entity_2_name = nameTypeStartPositions.get(endIndex).getType();
+        String entity_2_type = nameTypeStartPositions.get(endIndex).getType();
+
+        Set<Integer> set = null;
+        set = this.despiteMap.get(entity_1_name);  // 过滤有实体1名为例外情况(即,不成立)的规则(的uuid)
+        this.removeAll(remainUuids, set);
+
+        set = this.despiteMap.get(entity_2_name);  // 过滤有实体2名为例外情况(即,不成立)的规则(的uuid)
+        this.removeAll(remainUuids, set);
+
+        // 过滤中间实体的名称触发例外条件情况
+        for (int i = startIndex; i <= endIndex; i++) {
+            NameTypeStartPosition nameTypeStartPosition = nameTypeStartPositions.get(i);
+            set = this.despiteInsideMap.get(nameTypeStartPosition.getName());
+            this.removeAll(remainUuids, set);
+        }
+
+        // 三板斧过滤
+        // 实体1,过滤
+        set = new HashSet<>();
+        this.addAll(set, this.key_1_map.get("").get(""));
+        // 满足,形如("形容词", "type") 过滤条件的规则
+        this.addAll(set, this.key_1_map.get("type").get(entity_1_type));
+        // 满足,形如("胸痛", "word") 过滤条件的规则
+        this.addAll(set, this.key_1_map.get("word").get(entity_1_name));
+        this.retainAll(remainUuids, set);  // 求交集,同事满足实体1相关的过滤条件,且不不满足例外情况
+        if (remainUuids.size() == 0)
+            return false;
+
+        // 实体2,过滤
+        set = new HashSet<>();
+        this.addAll(set, this.key_2_map.get("").get(""));
+        // 满足,形如("形容词", "type") 过滤条件的规则
+        this.addAll(set, this.key_2_map.get("type").get(entity_2_type));
+        // 满足,形如("胸痛", "word") 过滤条件的规则
+        this.addAll(set, this.key_2_map.get("word").get(entity_2_name));
+        this.retainAll(remainUuids, set);  // 求交集,同事满足实体1相关的过滤条件,且不不满足例外情况
+        if (remainUuids.size() == 0)
+            return false;
+
+        // 中间实体过滤
+        set = new HashSet<>();
+        for (int i = startIndex; i <= endIndex; i++) {
+            NameTypeStartPosition nameTypeStartPosition = nameTypeStartPositions.get(i);
+            // 中间实体满足,形如("胸痛", "word") 过滤条件的规则
+            this.addAll(set, this.insideMap.get("word").get(nameTypeStartPosition.getName()));
+            // 中间实体满足,形如(";", "punc") 过滤条件的规则
+            this.addAll(set, this.insideMap.get("type").get(nameTypeStartPosition.getType()));  // 没有逗号的
+        }
+
+        int entity_1_start = nameTypeStartPositions.get(startIndex).getStartPosition();
+        int entity_2_start = nameTypeStartPositions.get(endIndex).getStartPosition();
+
+        // 标点过滤
+        String aPunc = null;
+        for (int i=entity_1_start; i<entity_2_start;i++){
+            aPunc = sentence.substring(i, i+1);
+            if (this.punctuations.get(aPunc) != null)
+                this.addAll(set, this.insideMap.get("punc").get(aPunc));
+        }
+
+        // 中文和英文逗号+属性 过滤
+        String[] commas = {",", ","};
+        int commaIndex = 0;
+        String commaPadType = null;  // 逗号拼接上类型
+        for (String comma: commas) {
+            commaIndex = sentence.indexOf(comma, entity_1_start + 1);  // 逗号位置
+            while (commaIndex > -1 && commaIndex < entity_2_start) {
+                commaIndex = sentence.indexOf(comma, commaIndex + 1);  // 下一个逗号
+                for (int i = startIndex; i <= endIndex; i++) {  // 每个逗号与后面的所有实体都匹配一次
+                    NameTypeStartPosition nameTypeStartPosition = nameTypeStartPositions.get(i);
+                    if (nameTypeStartPosition.getStartPosition() > commaIndex) {
+                        commaPadType = "," + nameTypeStartPosition.getType();
+                        this.addAll(set, this.insideMap.get("typePunctuation").get(commaPadType));
+                    }
+
+                }
+            }
+
+        }
+
+        this.retainAll(remainUuids, set);  // 求交集,同事中间实体相关的过滤条件,且不不满足例外情况
+
+//        for (FilterRule rule: this.filterRules) {
+//            if (remainUuids.contains(rule.getUuid()))
+//                System.out.println(rule);
+//
+//        }
+
+        return remainUuids.size() > 0;  // 还有规则满足,则过滤
+
+    }
+
+    /**
+     * 求差集,避免null和空集
+     *
+     * @param basicSet
+     * @param set
+     */
+    private void removeAll(Set<Integer> basicSet, Set<Integer> set) {
+        if (set != null && set.size() > 0)
+            basicSet.removeAll(set);
+    }
+
+    /**
+     * 求交集,避免null和空集
+     *
+     * @param basicSet
+     * @param set
+     */
+    private void addAll(Set<Integer> basicSet, Set<Integer> set) {
+        if (set != null && set.size() > 0)
+            basicSet.addAll(set);
+    }
+
+    /**
+     * 求并集,避免null和空集
+     *
+     * @param basicSet
+     * @param set
+     */
+    private void retainAll(Set<Integer> basicSet, Set<Integer> set) {
+        if (set != null && set.size() > 0)
+            basicSet.retainAll(set);
+    }
+
+    /**
+     * 检查并移除
+     *
+     * @param sentence 句子
+     * @param triads 三元组列表
+     */
+    public void checkAndRemove(String sentence, List<Triad> triads) {
+        List<NameTypeStartPosition> nameTypeStartPositions = this.getSortedNameTypeByPosition(triads);
+        Map<Integer, Integer> startPositionToIndexMap = new HashMap<>();
+        for (int i = 0; i < nameTypeStartPositions.size(); i++)
+            startPositionToIndexMap.put(nameTypeStartPositions.get(i).getStartPosition(), i);
+
+        Iterator<Triad> it = triads.iterator();
+        while (it.hasNext()) {  // 遍历三元组,移除满足过滤规则的
+            Triad triad = it.next();
+            int startIndex = startPositionToIndexMap.get(triad.getL_1().getStartPosition());
+            int endIndex = startPositionToIndexMap.get(triad.getL_2().getStartPosition());
+            if (isRemove(nameTypeStartPositions, startIndex, endIndex, sentence)) {
+                it.remove();
+            }
+        }
+    }
+}

+ 3 - 4
algorithm/src/main/java/org/algorithm/core/cnn/AlgorithmCNNExecutor.java

@@ -1,13 +1,12 @@
 package org.algorithm.core.cnn;
 
-import org.algorithm.core.cnn.entity.Lemma;
 import org.algorithm.core.cnn.entity.Triad;
 
 import java.util.List;
 
 /**
  * @ClassName org.algorithm.core.cnn.model.AlgorithmCNNExecutor
- * @Description TODO
+ * @Description
  * @Author fyeman
  * @Date 2019/1/17/017 19:18
  * @Version 1.0
@@ -16,8 +15,8 @@ public abstract class AlgorithmCNNExecutor {
     /**
      *
      * @param content 输入句子
-     * @param triads 实体列表
-     * @return
+     * @param triads 实体列表(三元组列表)
+     * @return  [[有关系的一系列词]]
      */
     public abstract List<Triad> execute(String content, List<Triad> triads);
 }

+ 22 - 0
algorithm/src/main/java/org/algorithm/core/cnn/AlgorithmCNNExecutorPacs.java

@@ -0,0 +1,22 @@
+package org.algorithm.core.cnn;
+
+import org.algorithm.core.cnn.entity.Triad;
+
+import java.util.List;
+
+/**
+ * @ClassName org.algorithm.core.cnn.model.AlgorithmCNNExecutor
+ * @Description
+ * @Author fyeman
+ * @Date 2019/1/17/017 19:18
+ * @Version 1.0
+ **/
+public abstract class AlgorithmCNNExecutorPacs {
+    /**
+     *
+     * @param content 输入句子
+     * @param triads 实体列表(三元组列表)
+     * @return  [[有关系的一系列词]]
+     */
+    public abstract List<List<String>>  execute(String content, List<Triad> triads);
+}

+ 1 - 1
algorithm/src/main/java/org/algorithm/core/cnn/dataset/RelationExtractionDataSet.java

@@ -17,7 +17,7 @@ import com.alibaba.fastjson.JSONObject;
 public class RelationExtractionDataSet {
 
     private Map<String, Integer> char2id = new HashMap<>();
-    public final int MAX_LEN = 512;
+    public final int MAX_LEN = 256;
 
 
     public RelationExtractionDataSet(String dir) {

+ 32 - 1
algorithm/src/main/java/org/algorithm/core/cnn/entity/Lemma.java

@@ -10,12 +10,38 @@ import java.util.List;
  * @Date 2019/1/17/017 19:15
  * @Version 1.0
  **/
-public class Lemma {
+public class Lemma implements Comparable<Lemma> {
     private String text;
     private String position;
     private int len;
     private String property;
 
+    private Lemma parent;
+
+    private boolean haveChildren = false;
+
+    public boolean isHaveChildren() {
+        return haveChildren;
+    }
+
+    public void setHaveChildren(boolean haveChildren) {
+        this.haveChildren = haveChildren;
+    }
+
+    public Lemma getParent() {
+        return parent;
+    }
+
+    public void setParent(Lemma parent) {
+        this.parent = parent;
+    }
+
+    public int getStartPosition() {
+        String[] pos = this.position.split(",");
+        return Integer.parseInt(pos[0]);
+    }
+
+
     private List<Lemma> relationLemmas = new ArrayList<>();
 
     public String getText() {
@@ -64,4 +90,9 @@ public class Lemma {
         }
         relationLemmas.add(l);
     }
+
+    @Override
+    public int compareTo(Lemma o) {
+        return this.getStartPosition() - o.getStartPosition();
+    }
 }

+ 40 - 13
algorithm/src/main/java/org/algorithm/core/cnn/model/RelationExtractionEnsembleModel.java

@@ -1,6 +1,8 @@
 package org.algorithm.core.cnn.model;
 
-import org.algorithm.core.cnn.AlgorithmCNNExecutor;
+import org.algorithm.core.RelationTreeUtils;
+import org.algorithm.core.RuleCheckMachine;
+import org.algorithm.core.cnn.AlgorithmCNNExecutorPacs;
 import org.algorithm.core.cnn.dataset.RelationExtractionDataSet;
 import org.algorithm.core.cnn.entity.Triad;
 import org.diagbot.pub.utils.PropertiesUtil;
@@ -21,7 +23,7 @@ import java.util.concurrent.*;
  * @Date: 2019/1/22 10:21
  * @Description: 集成模型
  */
-public class RelationExtractionEnsembleModel extends AlgorithmCNNExecutor {
+public class RelationExtractionEnsembleModel extends AlgorithmCNNExecutorPacs {
     private final String X_PLACEHOLDER = "X";
     private final String PREDICTION = "prediction/prediction";
     private final int NUM_LABEL = 1;
@@ -30,8 +32,10 @@ public class RelationExtractionEnsembleModel extends AlgorithmCNNExecutor {
     private RelationExtractionDataSet dataSet;
     private RelationExtractionSubModel[] subModels = new RelationExtractionSubModel[2];
     private ExecutorService executorService = Executors.newCachedThreadPool();
+    private final RuleCheckMachine ruleCheckMachine = new RuleCheckMachine();
 
     public RelationExtractionEnsembleModel() {
+        // 解析路径
         PropertiesUtil prop = new PropertiesUtil("/algorithm.properties");
 
         String modelsPath = prop.getProperty("basicPath");  // 模型基本路径
@@ -39,18 +43,20 @@ public class RelationExtractionEnsembleModel extends AlgorithmCNNExecutor {
         dataSetPath = dataSetPath + File.separator + "char2id.json";
         String exportDir = modelsPath.replace("model_version_replacement", "ensemble_model_2");
 
+        // 加载数据集和初始化集成模型
         this.dataSet = new RelationExtractionDataSet(dataSetPath);
         this.init(exportDir);
 
+        // 添加子模型系数,并加载子模型cnn_1d_low
         Map<String, Tensor<Float>> cnn_1d_low_map = new HashMap<>();
-        cnn_1d_low_map.put("keep_prob",Tensor.create(1.0f, Float.class));
+        cnn_1d_low_map.put("keep_prob", Tensor.create(1.0f, Float.class));
         subModels[0] = new RelationExtractionSubModel("cnn_1d_low", cnn_1d_low_map);
-//        subModels[1] = new RelationExtractionSubModel("cnn_1d_lstm_low");
 
+        // 添加子模型系数,并加载子模型lstm_low_api
         Map<String, Tensor<Float>> lstm_low_api_map = new HashMap<>();
-        lstm_low_api_map.put("input_keep_prob",Tensor.create(1.0f, Float.class));
-        lstm_low_api_map.put("output_keep_prob",Tensor.create(1.0f, Float.class));
-        lstm_low_api_map.put("state_keep_prob",Tensor.create(1.0f, Float.class));
+        lstm_low_api_map.put("input_keep_prob", Tensor.create(1.0f, Float.class));
+        lstm_low_api_map.put("output_keep_prob", Tensor.create(1.0f, Float.class));
+        lstm_low_api_map.put("state_keep_prob", Tensor.create(1.0f, Float.class));
         subModels[1] = new RelationExtractionSubModel("lstm_low_api", lstm_low_api_map);
     }
 
@@ -92,12 +98,24 @@ public class RelationExtractionEnsembleModel extends AlgorithmCNNExecutor {
         return inputValues;
     }
 
+
+    /**
+     * 数据预处理,包括过滤,等操作
+     * @param content
+     * @param triads
+     */
+    private void preProcess(String content, List<Triad> triads){
+        if (!(content.length() > this.dataSet.MAX_LEN) && triads.size() > 0) // 句子长度不超过MAX_LEN,有三元组
+            this.ruleCheckMachine.checkAndRemove(content, triads);
+    }
+
     @Override
-    public List<Triad> execute(String content, List<Triad> triads) {
-        // 句子长度不超过MAX_LEN,有三元组
-        if (content.length() > this.dataSet.MAX_LEN || triads.size() < 1) {
-            return new ArrayList<>();
-        }
+    public List<List<String>> execute(String content, List<Triad> triads) {
+        // 预处理
+        this.preProcess(content, triads);
+        if (content.length() > this.dataSet.MAX_LEN || triads.size() < 1)  // 句子长度不超过MAX_LEN,有三元组
+            return null;
+
         int[][] inputValues = this.convertData(content, triads);  // shape = [3, batchSize * this.subModels.length]
         int batchSize = triads.size();
 
@@ -159,7 +177,16 @@ public class RelationExtractionEnsembleModel extends AlgorithmCNNExecutor {
         for (Triad triad : deleteTriads)
             triads.remove(triad);
 
-        return triads;
+        return this.triadsToRelationTreeBranches(triads);
+    }
+
+    /**
+     * 从三元组列表到关系树分枝
+     * @param triads
+     * @return
+     */
+    public List<List<String>> triadsToRelationTreeBranches(List<Triad> triads) {
+        return RelationTreeUtils.triadsToRelationTreeBranches(triads);
     }
 
 

+ 4 - 4
algorithm/src/main/java/org/algorithm/core/cnn/model/RelationExtractionModel.java

@@ -4,7 +4,7 @@ import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
 import com.alibaba.fastjson.TypeReference;
-import org.algorithm.core.cnn.AlgorithmCNNExecutor;
+import org.algorithm.core.cnn.AlgorithmCNNExecutorPacs;
 import org.algorithm.core.cnn.dataset.RelationExtractionDataSet;
 import org.algorithm.core.cnn.entity.LemmaInfo;
 import org.algorithm.core.cnn.entity.Triad;
@@ -21,7 +21,7 @@ import java.util.List;
  * @Date: 2019/1/22 10:21
  * @Decription:
  */
-public class RelationExtractionModel extends AlgorithmCNNExecutor {
+public class RelationExtractionModel extends AlgorithmCNNExecutorPacs {
 //    self.X = tf.placeholder(tf.int32, shape=[None, self.max_length], name='X')
 //    self.pos1 = tf.placeholder(tf.int32, shape=[None, self.max_length], name='pos1')
 //    self.pos2 = tf.placeholder(tf.int32, shape=[None, self.max_length], name='pos2')
@@ -54,7 +54,7 @@ public class RelationExtractionModel extends AlgorithmCNNExecutor {
     }
 
     @Override
-    public List<Triad> execute(String content, List<Triad> triads) {
+    public List<List<String>> execute(String content, List<Triad> triads) {
 //        List<Lemma[]> combinations = new ArrayList<>();
 //        // 组合
 //        for(int i=0; i < lemmas.size() - 1; i++){  // 两两组合成实体对
@@ -83,7 +83,7 @@ public class RelationExtractionModel extends AlgorithmCNNExecutor {
 //            }
 //
 //        }
-        return triads;
+        return null;
     }
 
     /**

+ 33 - 0
algorithm/src/main/java/org/algorithm/factory/RelationExtractionFactory.java

@@ -0,0 +1,33 @@
+package org.algorithm.factory;
+
+import org.algorithm.core.cnn.AlgorithmCNNExecutorPacs;
+import org.algorithm.core.cnn.model.RelationExtractionEnsembleModel;
+
+/**
+ * @Description:
+ * @Author: HUJING
+ * @Date: 2019/9/10 15:25
+ */
+public class RelationExtractionFactory {
+    private static RelationExtractionEnsembleModel relationExtractionEnsembleModelInstance = null;
+
+    public static AlgorithmCNNExecutorPacs getInstance() {
+        try {
+            relationExtractionEnsembleModelInstance = (RelationExtractionEnsembleModel) create(relationExtractionEnsembleModelInstance, RelationExtractionEnsembleModel.class);
+        } catch (InstantiationException inst) {
+            inst.printStackTrace();
+        } catch (IllegalAccessException ille) {
+            ille.printStackTrace();
+        }
+        return relationExtractionEnsembleModelInstance;
+    }
+
+    private static Object create(Object obj, Class cls) throws InstantiationException, IllegalAccessException {
+        if (obj == null) {
+            synchronized (cls) {
+                obj = cls.newInstance();
+            }
+        }
+        return obj;
+    }
+}

+ 5 - 3
algorithm/src/main/java/org/algorithm/test/ReEnsembleModelTest.java

@@ -18,7 +18,7 @@ public class ReEnsembleModelTest {
 
     public static void main(String[] args) {
         RelationExtractionEnsembleModel ensembleModel = new RelationExtractionEnsembleModel();
-
+        List<List<String>> result = new ArrayList<>();
         List<Triad> triads = new ArrayList<>();
         Triad triad_1 = new Triad();
         Lemma l_1 = new Lemma();
@@ -36,9 +36,11 @@ public class ReEnsembleModelTest {
 
         long start = System.nanoTime();
         for (int i=0; i<200; i++)  // 重复100次
-            triads = ensembleModel.execute("患者剧烈胸痛头痛失眠不安", triads);
+        {
+            result = ensembleModel.execute("患者剧烈胸痛头痛失眠不安", triads);
+        }
         long elapsedTime = System.nanoTime() - start;
-        System.out.println(triads.size());
+        System.out.println(result.size());
         System.out.println(elapsedTime);
     }
 }

+ 15 - 0
algorithm/src/main/java/org/algorithm/test/TestRelationTreeUtils.java

@@ -0,0 +1,15 @@
+package org.algorithm.test;
+
+import org.algorithm.core.RelationTreeUtils;
+
+/**
+ * @Author: bijl
+ * @Date: 2019/9/5 17:07
+ * @Description:
+ */
+public class TestRelationTreeUtils {
+
+    public static void main(String[] args) {
+        RelationTreeUtils.test();
+    }
+}

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 140 - 0
algorithm/src/main/java/org/algorithm/test/TestRuleCheckMachine.java


+ 1 - 1
algorithm/src/main/java/org/algorithm/util/MysqlConnector.java

@@ -45,7 +45,7 @@ public class MysqlConnector {
     
     /**
      * 执行sql语句
-     * @param sql
+     * @param sqls
      */
     public void executeBatch(List<String> sqls) {
         Statement stmt = null;

+ 3 - 1
bigdata-web/src/main/java/org/diagbot/bigdata/work/AlgorithmCore.java

@@ -25,6 +25,7 @@ import java.util.*;
  **/
 public class AlgorithmCore {
     Logger logger = LoggerFactory.getLogger(AlgorithmCore.class);
+
     public ResponseData algorithm(HttpServletRequest request, SearchData searchData, ResponseData responseData) throws Exception {
         //录入文本处理,包括提取特征、推送类型转换等
         BigDataParamsProxy paramsDataProxy = new BigDataParamsProxy();
@@ -50,7 +51,8 @@ public class AlgorithmCore {
             AlgorithmExecutor executor = AlgorithmFactory.getInstance(classifies[i]);
             Map<String, Float> featuresMap = null;
             if (executor != null) {
-                featuresMap = executor.execute(bigDataSearchData.getInputs());;
+                featuresMap = executor.execute(bigDataSearchData.getInputs());
+                ;
             }
             List<Map.Entry<String, Float>> featuresOrderList = null;
             if (featuresMap == null) {

+ 16 - 26
bigdata-web/src/main/java/org/diagbot/bigdata/work/BigDataParamsProxy.java

@@ -8,9 +8,6 @@ import org.diagbot.nlp.feature.FeatureType;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import java.util.ArrayList;
-import java.util.List;
-
 /**
  * @ClassName org.diagbot.bigdata.work.ParamsDataProxy
  * @Description TODO
@@ -25,6 +22,7 @@ public class BigDataParamsProxy {
         ParamsDataProxy paramsDataProxy = new ParamsDataProxy();
         paramsDataProxy.createSearchData(searchData);
     }
+
     /**
      * featureType转算法模型类型
      *
@@ -33,7 +31,7 @@ public class BigDataParamsProxy {
      * @param searchData
      */
     public AlgorithmClassify[] createAlgorithmClassify(String sysCode, String[] featureTypes, SearchData searchData) {
-        List<AlgorithmClassify> algorithmClassifies = new ArrayList<>();
+        AlgorithmClassify[] classifies = new AlgorithmClassify[featureTypes.length];
         //下了诊断且其他信息全为空 反推标识
         boolean reverse = !StringUtils.isEmpty(searchData.getDiag()) && StringUtils.isEmpty(searchData.getSymptom());
         for (int i = 0; i < featureTypes.length; i++) {
@@ -42,64 +40,56 @@ public class BigDataParamsProxy {
                 switch (FeatureType.parse(featureTypes[i])) {
                     case SYMPTOM:
                         if (reverse) {
-                            algorithmClassifies.add(AlgorithmClassify.NEURAL_DIAG_SYMPTOM);
+                            classifies[i] = AlgorithmClassify.NEURAL_DIAG_SYMPTOM;
                         } else {
-                            algorithmClassifies.add(AlgorithmClassify.NEURAL_SYMPTOM);
+                            classifies[i] = AlgorithmClassify.NEURAL_SYMPTOM;
                         }
                         break;
                     case DIAG:
                         if (reverse) {
-                            algorithmClassifies.add(null);
+                            classifies[i] = null;
                         } else {
-                            algorithmClassifies.add(AlgorithmClassify.NEURAL_DIAG);
+                            classifies[i] = AlgorithmClassify.NEURAL_DIAG;
                         }
                         break;
                     case VITAL:
                         if (reverse) {
-                            algorithmClassifies.add(AlgorithmClassify.NEURAL_DIAG_VITAL);
-
+                            classifies[i] = AlgorithmClassify.NEURAL_DIAG_VITAL;
                         } else {
-                            algorithmClassifies.add(AlgorithmClassify.NEURAL_VITAL);
-
+                            classifies[i] = AlgorithmClassify.NEURAL_VITAL;
                         }
                         break;
                     case LIS:
                         if (reverse) {
-                            algorithmClassifies.add(AlgorithmClassify.NEURAL_DIAG_LIS);
-
+                            classifies[i] = AlgorithmClassify.NEURAL_DIAG_LIS;
                         } else {
-                            algorithmClassifies.add(AlgorithmClassify.NEURAL_LIS);
+                            classifies[i] = AlgorithmClassify.NEURAL_LIS;
                         }
                         break;
                     case PACS:
                         if (reverse) {
-                            algorithmClassifies.add(AlgorithmClassify.NEURAL_DIAG_PACS);
+                            classifies[i] = AlgorithmClassify.NEURAL_DIAG_PACS;
                         } else {
-                            algorithmClassifies.add(AlgorithmClassify.NEURAL_PACS);
+                            classifies[i] = AlgorithmClassify.NEURAL_PACS;
                         }
                         break;
                     case TREAT:
                         if (reverse) {
-                            algorithmClassifies.add(AlgorithmClassify.NEURAL_DIAG_TREAT);
-
+                            classifies[i] = AlgorithmClassify.NEURAL_DIAG_TREAT;
                         } else {
-                            algorithmClassifies.add(AlgorithmClassify.NEURAL_TREAT);
-
+                            classifies[i] = AlgorithmClassify.NEURAL_TREAT;
                         }
                         break;
                     case HISTORY:
                         if (reverse) {
-                            algorithmClassifies.add(AlgorithmClassify.NEURAL_DIAG_HISTORY);
-
+                            classifies[i] = AlgorithmClassify.NEURAL_DIAG_HISTORY;
                         } else {
-                            algorithmClassifies.add(AlgorithmClassify.NEURAL_HISTORY);
+                            classifies[i] = AlgorithmClassify.NEURAL_HISTORY;
                         }
                         break;
                 }
             }
         }
-        AlgorithmClassify[] classifies = new AlgorithmClassify[algorithmClassifies.size()];
-        algorithmClassifies.toArray(classifies);
         return classifies;
     }
 }

+ 66 - 0
bigdata-web/src/main/java/org/diagbot/bigdata/work/ResultDataProxy.java

@@ -1,8 +1,11 @@
 package org.diagbot.bigdata.work;
 
+import com.alibaba.fastjson.JSON;
 import org.apache.commons.lang3.StringUtils;
 import org.diagbot.common.push.bean.FeatureRate;
+import org.diagbot.common.push.bean.ResponseData;
 import org.diagbot.common.push.bean.ResultMappingFilter;
+import org.diagbot.common.push.bean.SearchData;
 import org.diagbot.common.push.cache.ApplicationCacheUtil;
 import org.diagbot.nlp.feature.FeatureType;
 import org.diagbot.nlp.util.Constants;
@@ -139,4 +142,67 @@ public class ResultDataProxy {
         }
         return result;
     }
+
+    /**
+     * 化验辅检体征,年龄性别过滤
+     *
+     * @param responseData
+     * @param searchData
+     * @return
+     */
+    public ResponseData resultSexAgeFilter(HttpServletRequest request, ResponseData responseData, SearchData searchData) {
+        if (responseData.getLabs().size() > 0) {//化验
+            responseData.setLabs(sexFilter(request, responseData.getLabs(), searchData, Constants.feature_type_lis));
+        }
+        if (responseData.getPacs().size() > 0) {//辅检
+            responseData.setPacs(sexFilter(request, responseData.getPacs(), searchData, Constants.feature_type_pacs));
+        }
+        if (responseData.getVitals().size() > 0) {//查体
+            responseData.setVitals(sexFilter(request, responseData.getVitals(), searchData, Constants.feature_type_vital));
+        }
+        return responseData;
+    }
+
+    public List<FeatureRate> sexFilter(HttpServletRequest request, List<FeatureRate> featureList, SearchData searchData, String featureType) {
+        List<FeatureRate> featureRates = new ArrayList<>(10);//用来存放传入的数据结果
+        List<FeatureRate> featureRateList = new ArrayList<>(10);//用来存放返回结果
+        Map<String, Map<String, ResultMappingFilter>> resultMappingFilterMap = ApplicationCacheUtil.getDoc_result_mapping_lpvSex_filter_map();
+        boolean isFirst = false;
+        for (int i = 0; i < featureList.size(); i++) {
+            FeatureRate entity = JSON.parseObject(JSON.toJSONString(featureList.get(i)), FeatureRate.class);
+            featureRates.add(entity);
+        }
+        for (FeatureRate featureRate : featureRates) {
+            isFirst = false;
+            //性别年龄过滤
+            Map<String, ResultMappingFilter> filterMap = resultMappingFilterMap.get(featureType);
+            if (filterMap != null) {
+                ResultMappingFilter filter = filterMap.get(featureRate.getFeatureName());
+                if (filter != null) {
+                    if (filter.getSex() != null && !StringUtils.isEmpty(searchData.getSex())
+                            && !filter.getSex().equals(searchData.getSex())) {      //性别过滤
+                        isFirst = true;
+                    } else {
+                        isFirst = false;
+                    }
+                    //年龄过滤
+                    if (filter.getAgeStart() > -1 && searchData.getAge() != 0 && searchData.getAge() < filter.getAgeEnd()) {
+                        isFirst = true;
+                    } else {
+                        isFirst = false;
+                    }
+                    if (filter.getAgeEnd() > -1 && searchData.getAge() != 0 && searchData.getAge() > filter.getAgeStart()) {
+                        isFirst = true;
+                    } else {
+                        isFirst = false;
+                    }
+                }
+                if (isFirst) {
+                    featureRateList.add(featureRate);
+                }
+            }
+        }
+        return featureRateList;
+    }
+
 }

+ 0 - 6
common-push/pom.xml

@@ -28,12 +28,6 @@
             <artifactId>nlp</artifactId>
             <version>1.0.0</version>
         </dependency>
-
-        <dependency>
-            <groupId>org.diagbot</groupId>
-            <artifactId>common-service</artifactId>
-            <version>1.0.0</version>
-        </dependency>
     </dependencies>
 
     <build>

+ 11 - 0
common-push/src/main/java/org/diagbot/common/push/bean/SearchData.java

@@ -1,5 +1,7 @@
 package org.diagbot.common.push.bean;
 
+import org.diagbot.nlp.rule.module.PreResult;
+
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
@@ -31,6 +33,7 @@ public class SearchData {
     protected String lis = "";
     protected String pacs = "";
     protected String diag = "";
+    private String diseaseName;
     protected String past = "";
     protected String other = "";
     //当前开单lis项目
@@ -311,4 +314,12 @@ public class SearchData {
     public void setRules(Map<String, List<Rule>> rules) {
         this.rules = rules;
     }
+
+    public String getDiseaseName() {
+        return diseaseName;
+    }
+
+    public void setDiseaseName(String diseaseName) {
+        this.diseaseName = diseaseName;
+    }
 }

+ 83 - 0
common-push/src/main/java/org/diagbot/common/push/cache/ApplicationCacheUtil.java

@@ -9,8 +9,10 @@ import org.diagbot.nlp.util.NlpCache;
 
 import java.util.ArrayList;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 
 public class ApplicationCacheUtil {
 
@@ -20,10 +22,14 @@ public class ApplicationCacheUtil {
     public static Map<String, String> doc_result_mapping_diag_map = null;
     //特征性别 年龄过滤等
     public static Map<String, Map<String, ResultMappingFilter>> doc_result_mapping_filter_map = null;
+    //化验辅检体征 性别 年龄过滤等
+    public static Map<String, Map<String, ResultMappingFilter>> doc_result_mapping_lpvSex_filter_map = null;
     // 规则
     public static Map<String, List<Rule>> kl_rule_filter_map = null;
     //危险值提醒
     public static Map<String, RuleApp> kl_rule_app_filter_map = null;
+    //pacs关系抽取过滤
+    public static Map<String, Map<String, String>> kl_diagnose_detail_filter_map = null;
 
     public static Map<String, Map<String, String>> getStandard_info_synonym_map() {
         if (standard_info_synonym_map == null) {
@@ -45,6 +51,13 @@ public class ApplicationCacheUtil {
         return doc_result_mapping_diag_map;
     }
 
+    public static Map<String, Map<String, ResultMappingFilter>> getDoc_result_mapping_lpvSex_filter_map() {
+        if (doc_result_mapping_lpvSex_filter_map == null) {
+            createDoc_result_mapping_lpvSex_filter_map();
+        }
+        return doc_result_mapping_lpvSex_filter_map;
+    }
+
     public static Map<String, Map<String, ResultMappingFilter>> getDoc_result_mapping_filter_map() {
         if (doc_result_mapping_filter_map == null) {
             createDoc_result_mapping_filter_map();
@@ -87,6 +100,46 @@ public class ApplicationCacheUtil {
         return doc_result_mapping_filter_map;
     }
 
+    /**
+     * 化验辅检体征年龄性别过滤
+     *
+     * @return
+     */
+    public static Map<String, Map<String, ResultMappingFilter>> createDoc_result_mapping_lpvSex_filter_map() {
+        Configuration configuration = new DefaultConfig();
+        List<String> fileContents = configuration.readFileContents("bigdata_lpv_sex_age_filter.dict");
+        String[] line_string;
+        List<ResultMappingFilter> resultMappingFilters = new ArrayList<>();
+        try {
+            for (int i = 0; i < fileContents.size(); i++) {
+                line_string = org.apache.commons.lang3.StringUtils.split(fileContents.get(i), "\\|");
+                if (line_string.length == 5) {
+                    ResultMappingFilter resultMappingFilter = new ResultMappingFilter();
+                    resultMappingFilter.setFeatureName(line_string[0]);
+                    resultMappingFilter.setFeatureType(line_string[1]);
+                    resultMappingFilter.setSex(line_string[2]);
+                    resultMappingFilter.setAgeStart(Integer.parseInt(line_string[3]));
+                    resultMappingFilter.setAgeEnd(Integer.parseInt(line_string[4]));
+                    resultMappingFilters.add(resultMappingFilter);
+                }
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+        doc_result_mapping_lpvSex_filter_map = new HashMap<>();
+        Map<String, ResultMappingFilter> filterMap = null;
+        for (ResultMappingFilter resultMappingFilter : resultMappingFilters) {
+            filterMap = doc_result_mapping_lpvSex_filter_map.get(resultMappingFilter.getFeatureType());
+            if (filterMap == null) {
+                filterMap = new HashMap<>();
+            }
+            filterMap.put(resultMappingFilter.getFeatureName(), resultMappingFilter);
+            doc_result_mapping_lpvSex_filter_map.put(resultMappingFilter.getFeatureType(), filterMap);
+        }
+        return doc_result_mapping_lpvSex_filter_map;
+    }
+
 
     public static Map<String, List<Rule>> getKl_rule_filter_map() {
         if (kl_rule_filter_map == null) {
@@ -154,4 +207,34 @@ public class ApplicationCacheUtil {
             }
         }
     }
+
+    public static Map<String, Map<String, String>> getKl_diagnose_detail_filter_map() {
+        if (kl_diagnose_detail_filter_map == null) {
+            create_kl_diagnose_detail_filter_map();
+        }
+        return kl_diagnose_detail_filter_map;
+    }
+
+
+    public static void create_kl_diagnose_detail_filter_map() {
+        kl_diagnose_detail_filter_map = new HashMap<>();
+        Map<String, String> diagnoseDetailRelationMap = new HashMap<>();
+        Set<String> diagnoseDetailRelation = new HashSet<>();
+        Configuration configuration = new DefaultConfig();
+        List<String> fileContents = configuration.readFileContents("bigdata_diagnose_detail_filter.dict");
+        for (String line : fileContents) {
+            String[] content = line.split("\\|", -1);
+            String[] relations = content[1].split("、");
+            for (String relation : relations) {
+                if (diagnoseDetailRelation.add(relation)) {
+                    if (kl_diagnose_detail_filter_map.get(content[0]) == null) {
+                        diagnoseDetailRelationMap.put(relation, relation);
+                        kl_diagnose_detail_filter_map.put(content[0], diagnoseDetailRelationMap);
+                    } else {
+                        kl_diagnose_detail_filter_map.get(content[0]).put(relation, relation);
+                    }
+                }
+            }
+        }
+    }
 }

+ 61 - 5
common-push/src/main/java/org/diagbot/common/push/cache/CacheFileManager.java

@@ -22,9 +22,9 @@ import java.util.*;
 public class CacheFileManager {
     Logger logger = LoggerFactory.getLogger(CacheFileManager.class);
 
-    private String user = "root";
-    private String password = "lantone";
-    private String url = "jdbc:mysql://192.168.2.122:3306/med?useUnicode=true&characterEncoding=UTF-8";
+    private String user = "teamdata";
+    private String password = "jiO2rfnYhg";
+    private String url = "jdbc:mysql://192.168.2.121:3306/med?useUnicode=true&characterEncoding=UTF-8";
 
     private String path = "";
 
@@ -164,6 +164,18 @@ public class CacheFileManager {
 
             fw = new FileWriter(path + "classify.dict");
             fw.close();
+
+            sql = "select name, type from kl_library_info_pacs order by name";
+            st = conn.createStatement();
+            rs = st.executeQuery(sql);
+            fw = new FileWriter(path + "pacs-tc.dict");
+            while (rs.next()) {
+                r1 = rs.getString(1);
+                r2 = rs.getString(2);
+                fw.write(encrypDES.encrytor(r1 + "|9|"+ r2 + "|" + r1));
+                fw.write("\n");
+            }
+            fw.close();
         } catch (IOException ioe) {
             ioe.printStackTrace();
         } catch (SQLException sqle) {
@@ -237,7 +249,7 @@ public class CacheFileManager {
             }
             fw.close();
             //疾病科室信息
-            sql = "SELECT k1.lib_name diag_name, k2.lib_name dept_name FROM kl_concept_common kcc, kl_concept k1, kl_concept k2 " +
+            sql = "SELECT k1.lib_name diag_name, k2.lib_name dept_name FROM kl_disease kcc, kl_concept k1, kl_concept k2 " +
                     "where kcc.concept_id = k1.id and kcc.dept_id = k2.id " +
                     "and k1.lib_type = 18 and kcc.dept_id  is not null";
             st = conn.createStatement();
@@ -281,7 +293,7 @@ public class CacheFileManager {
         try {
             EncrypDES encrypDES = new EncrypDES();
             //疾病科室
-            String sql = "SELECT k1.lib_name diag_name, k2.lib_name dept_name FROM kl_concept_common kcc, kl_concept k1, kl_concept k2 " +
+            String sql = "SELECT k1.lib_name diag_name, k2.lib_name dept_name FROM kl_disease kcc, kl_concept k1, kl_concept k2 " +
                     "where kcc.concept_id = k1.id and kcc.dept_id = k2.id " +
                     "and k1.lib_type = 18 and kcc.dept_id  is not null";
             st = conn.createStatement();
@@ -386,6 +398,50 @@ public class CacheFileManager {
                 fw.write("\n");
             }
             fw.close();
+
+            sql = "SELECT type,relation FROM `kl_diagnose_detail` WHERE type = 4 AND LENGTH(relation) > 0 GROUP BY relation";
+            st = conn.createStatement();
+            rs = st.executeQuery(sql);
+            fw = new FileWriter(path + "bigdata_diagnose_detail_filter.dict");
+            while (rs.next()) {
+                r1 = String.valueOf(rs.getInt(1));
+                r2 = rs.getString(2);
+                fw.write(encrypDES.encrytor(r1+ "|" + r2));
+                fw.write("\n");
+            }
+            fw.close();
+
+            //化验辅检体征性别年龄
+            sql = "SELECT k1.lib_name, k1.lib_type, kcc.sex_type, kcc.min_age, kcc.max_age " +
+                    "FROM kl_concept_common kcc, kl_concept k1 " +
+                    "where kcc.concept_id = k1.id " +
+                    "and k1.lib_type in (1, 18,12,16,33,35)";
+            st = conn.createStatement();
+            rs = st.executeQuery(sql);
+            fw = new FileWriter(path + "bigdata_lpv_sex_age_filter.dict");//化验辅检体征相关文件
+            while (rs.next()) {
+                r1 = rs.getString(1);
+                r2 = rs.getString(2);
+                r3 = rs.getString(3);
+                r4 = rs.getString(4);
+                r5 = rs.getString(5);
+                if ("18".equals(r2)) {//诊断
+                    r2 = "2";
+                }
+                if ("12".equals(r2)) {//化验
+                    r2 = "4";
+                }
+                if ("16".equals(r2)) {//辅检
+                    r2 = "5";
+                }
+                if ("33".equals(r2) | "35".equals(r2)) {//体征
+                    r2 = "3";
+                }
+                fw.write(encrypDES.encrytor(r1 + "|" + r2 + "|" + r3 + "|" + r4 + "|" + r5));
+                fw.write("\n");
+            }
+            fw.close();
+
         } catch (IOException ioe) {
             ioe.printStackTrace();
         } catch (SQLException sqle) {

+ 95 - 39
common-push/src/main/java/org/diagbot/common/push/filter/ClassifyDiag.java

@@ -5,6 +5,7 @@ import org.apache.commons.lang3.StringUtils;
 import org.diagbot.common.push.bean.FeatureRate;
 import org.diagbot.common.push.bean.ResponseData;
 import org.diagbot.common.push.cache.CacheUtil;
+import org.diagbot.nlp.relation.module.Lis;
 
 import java.text.DecimalFormat;
 import java.util.*;
@@ -21,34 +22,6 @@ public class ClassifyDiag {
     //每个诊断所在的级别缓存
     Map<String, Integer> diagClassifyJiCache = CacheUtil.getDiagClassifyJiCache();
 
-   /* public static void main(String[] args) {
-
-        List<String> disList = new LinkedList<>();
-        String[] disArray = {"急性胰腺炎","冠心病","急性冠状动脉综合征","急性非ST段抬高型心肌梗死","急性ST段抬高型心肌梗死"
-        ,"三度房室传导阻滞","心力衰竭","急性心力衰竭"};
-         disList = Arrays.asList(disArray);
-        System.out.println("输入的诊断"+disList);
-        List<FeatureRate> inintFeature = new ArrayList<>();
-        Double inintNumber = 0.95;
-        String rate = "";
-        for (String dis:disList) {
-            FeatureRate featureRate = new FeatureRate();
-            featureRate.setFeatureName(dis);
-            inintNumber = inintNumber - 0.1;
-            rate = String.valueOf(inintNumber);
-            featureRate.setRate(rate);
-            inintFeature.add(featureRate);
-        }
-
-        ClassifyDiag classifyDiag = new ClassifyDiag();
-        List<FeatureRate> classify = classifyDiag.diagClassify(inintFeature);
-        System.out.println("hao hai you");
-        for (FeatureRate d:classify) {
-            System.out.println(d.getFeatureName()+"\t"+d.getRate()+"\t"+d.getExtraProperty());
-        }
-
-    }*/
-
     /**
      * 根据诊断依据规则过滤诊断
      * @param graphResponseData 把过滤的诊断包装在这个对象里
@@ -81,6 +54,7 @@ public class ClassifyDiag {
     public List<FeatureRate> diagClassify(List<FeatureRate> updateFeatures){
         List<FeatureRate> finalDiagList = new LinkedList<>();//最终返回
         List<String> highDiagList = new LinkedList<>();//警惕集合
+        List<String> diffDiagList = new LinkedList<>();//鉴别诊断集合
         List<String> queDiagList = new LinkedList<>();//确诊集合
         List<String> bigDiagList = new LinkedList<>();//可能诊断集合
         if(updateFeatures != null && updateFeatures.size()>0){
@@ -89,13 +63,11 @@ public class ClassifyDiag {
                 String desc = featureRate.getDesc();
                 Map<String,Object> d = new HashMap<>();
                 if(desc != null){
-                    JSONObject jsonObject = JSONObject.parseObject(desc);
-                    d = jsonObject;
-                    if(d.keySet().size() == 1 && "警惕".equals(d.keySet().toArray()[0])){
-                        highDiagList.add(featureName);
-                    }else {
-                        queDiagList.add(featureName);
-                    }
+                   if(desc.contains("确诊") || desc.contains("拟诊")){
+                       queDiagList.add(featureName);
+                   }else {
+                       highDiagList.add(featureName);
+                   }
                 }else {
                     bigDiagList.add(featureName);
                 }
@@ -107,7 +79,18 @@ public class ClassifyDiag {
                 FeatureRate featureRate = updateFeatures.get(j);
                 String featureName = featureRate.getFeatureName();
                 int i = highDiagList.indexOf(featureName);
-                if(i >= 0){
+                if(i >= 0 && featureRate.getDesc() != null){
+                    finalDiagList.add(featureRate);
+                }
+            }
+        }
+        //再把鉴别诊断加进去
+        if(diffDiagList.size()>0){
+            for(int j =0;j<updateFeatures.size();j++){
+                FeatureRate featureRate = updateFeatures.get(j);
+                String featureName = featureRate.getFeatureName();
+                int i = diffDiagList.indexOf(featureName);
+                if(i >= 0 && featureRate.getDesc() != null){
                     finalDiagList.add(featureRate);
                 }
             }
@@ -121,12 +104,16 @@ public class ClassifyDiag {
         System.out.println("图谱归一前数据 :"+queDiagList);
         if(queDiagList != null && queDiagList.size()>0){
             //图谱归一 ,图谱sign =0,大数据sign = 1
-            queSet = this.diagProcess(queDiagList,0);
+            List<String> que = this.processQue(updateFeatures, queDiagList);
+            queSet = this.diagProcess(que,0);
             System.out.println("图谱归一后的数据    :"+queSet);
             if(queSet != null && queSet.size()>0){
                 for (String queDis:queSet) {
                     if(queDiagList.indexOf(queDis)>=0){ //可以找到,就取出来,用原来的
                         FeatureRate feature = this.getFeature(updateFeatures, queDis);
+//                        if(feature.getDesc().contains("拟诊")){
+                            feature.setDesc(feature.getDesc());
+//                        }
                         feature.setExtraProperty(diagDepartCache.get(queDis));
                         finalDiagList.add(feature);
                     }else {
@@ -186,6 +173,8 @@ public class ClassifyDiag {
                             bigDataIDiagList.add(featureName);
                         }else if("Ⅱ".equals(s)){
                             bigDataIIDiagList.add(featureName);
+                        }else {
+                            bigDataIDiagList.add(featureName);
                         }
                     }else {
                         bigDataIDiagList.add(featureName);
@@ -193,13 +182,23 @@ public class ClassifyDiag {
                 }
             }
         }
-        finalDiagList.addAll(neoDiagList);
+//        finalDiagList.addAll(neoDiagList);
         finalDiagList.addAll(bigDataIDiagList);
         finalDiagList.addAll(bigDataIIDiagList);
+        if(neoDiagList !=null && neoDiagList.size()>0){
+            for (String diag:neoDiagList) {
+                for (FeatureRate feature:updateFeatureRates) {
+                    if(diag.equals(feature.getFeatureName())&& "neo4j".equals(feature.getSource())){
+                        finalDiagFeature.add(feature);
+                        break;
+                    }
+                }
+            }
+        }
         if(finalDiagList != null && finalDiagList.size()>0){
             for (String diag:finalDiagList){
                 for (FeatureRate f:updateFeatureRates) {
-                    if(diag.equals(f.getFeatureName())){
+                    if(diag.equals(f.getFeatureName())&& f.getSource()==null){
                         finalDiagFeature.add(f);
                         break;
                     }
@@ -527,5 +526,62 @@ public class ClassifyDiag {
         }
         return arrayList;
     }
+    //归一有确诊的诊断
+    public  List<String> processQue(List<FeatureRate> updateFeatures,List<String>queList){
+        List<String> finallyQue = new LinkedList<>();
+        List<String> que = new ArrayList<>();
+        List<String> ni = new ArrayList<>();
+        for (String qd:queList) {
+            for (FeatureRate f:updateFeatures) {
+                if("neo4j".equals(f.getSource()) && qd.equals(f.getFeatureName())){
+                    if(f.getDesc().contains("确诊")){
+                        que.add(qd);
+                    }else if(f.getDesc().contains("拟诊")) {
+                        ni.add(qd);
+                    }
+                }
+            }
+        }
+        if(que != null && que.size()>0){
+            for (String q:que) {
+                Set<String> classifySet = new HashSet<>();
+                String s = diagClassifyCache.get(q);
+                if(StringUtils.isNotEmpty(s)){
+                    classifySet.add(s);
+                    List<Object> key = this.getKey(diagClassifyCache, s);
+                    if(key != null && key.size()>0){
+                        for (Object o:key) {
+                            classifySet.add(o.toString());
+                            List<Object> key1 = this.getKey(diagClassifyCache, o.toString());
+                            if(key1 != null && key1.size()>0){
+                                for (Object f:key1
+                                     ) {
+                                    classifySet.add(f.toString());
+                                }
+                            }
+                        }
+                    }
+                }
+                List<Object> key = this.getKey(diagClassifyCache, q);
+                if(key != null && key.size()>0){
+                    for (Object o:key) {
+                        classifySet.add(o.toString());
+                    }
+                }
+                if(classifySet != null && classifySet.size()>0){
+                    for (String sq:classifySet
+                         ) {
+                        if(ni.indexOf(sq) >= 0){
+                            ni.remove(sq);
+                        }
+                    }
+                }
+            }
+        }
+        finallyQue.addAll(que);
+        finallyQue.addAll(ni);
+        return finallyQue;
+
+    }
 
 }

+ 0 - 59
common-push/src/main/java/org/diagbot/common/push/filter/pretreat/PretreatmentLis.java

@@ -1,59 +0,0 @@
-package org.diagbot.common.push.filter.pretreat;
-
-import org.diagbot.common.push.bean.PreResult;
-import org.diagbot.nlp.participle.word.Lexeme;
-import org.diagbot.nlp.participle.word.LexemePath;
-import org.diagbot.nlp.util.NegativeEnum;
-import org.diagbot.nlp.util.NlpUtil;
-
-import java.lang.reflect.Array;
-import java.util.List;
-
-public class PretreatmentLis extends Pretreatment {
-    private String join_symbols = ";:;:";
-
-    public List<PreResult> analyze(String content) throws java.io.IOException{
-        return super.analyzeDefault(content);
-    }
-
-    public PreResult createPreResult(LexemePath<Lexeme> lexemes, Lexeme lexeme, int index) {
-        PreResult result = new PreResult();
-        double value = findNumberValue(lexemes, lexeme, index);
-        if (value == -1) return null;
-        //继续往前找化验明细项
-        if (cursor > 0) cursor--;
-        Lexeme leftLexeme = lexemes.get(cursor);
-        if (join_symbols.contains(leftLexeme.getText())) {
-            if (cursor > 0) {
-                cursor--;
-                leftLexeme = lexemes.get(cursor);
-            } else {
-                return null;
-            }
-        }
-        if (NlpUtil.isFeature(leftLexeme.getProperty(), new NegativeEnum[]{NegativeEnum.LIS_NAME})) {
-            result.setDetailName(NlpUtil.concept(leftLexeme, NegativeEnum.LIS_NAME));
-        } else if (NlpUtil.isFeature(leftLexeme.getProperty(), new NegativeEnum[]{NegativeEnum.PUB_NAME})) {
-            result.setUniqueName(NlpUtil.concept(leftLexeme, NegativeEnum.PUB_NAME));
-        } else {
-            return null;
-        }
-        //查找化验套餐
-        int position = cursor - 1;
-        while (position > -1) {
-            leftLexeme = lexemes.get(position);
-            if (NlpUtil.isFeature(leftLexeme.getProperty(), new NegativeEnum[]{NegativeEnum.LIS_TYPE})) {
-                result.setName(NlpUtil.concept(leftLexeme, NegativeEnum.LIS_TYPE));
-                break;
-            }
-            position--;
-        }
-        result.setValue(String.valueOf(value));
-        result.setUnits(lexeme.getText());
-        return result;
-    }
-
-    public String findBodyValue(LexemePath<Lexeme> lexemes, Lexeme lexeme, int index) {
-        return null;
-    }
-}

+ 0 - 51
common-push/src/main/java/org/diagbot/common/push/filter/pretreat/PretreatmentPacs.java

@@ -1,51 +0,0 @@
-package org.diagbot.common.push.filter.pretreat;
-
-import org.diagbot.common.push.bean.PreResult;
-import org.diagbot.nlp.participle.ParticipleUtil;
-import org.diagbot.nlp.participle.word.Lexeme;
-import org.diagbot.nlp.participle.word.LexemePath;
-import org.diagbot.nlp.util.NegativeEnum;
-import org.diagbot.nlp.util.NlpUtil;
-
-import java.util.List;
-
-public class PretreatmentPacs extends Pretreatment {
-    protected NegativeEnum[] nees_pacs_result = new NegativeEnum[]{NegativeEnum.PACS_RESULT};
-    protected NegativeEnum[] nees_pacs_name = new NegativeEnum[]{NegativeEnum.PACS_NAME};
-    public List<PreResult> analyze(String content) throws java.io.IOException{
-        List<PreResult> preResultList = super.analyzeDefault(content);
-        //pacs除了数值型需要转, 还需要对部分检查结果提取,以便做危机警示
-        LexemePath<Lexeme> lexemes = ParticipleUtil.participle(content);
-
-        Lexeme leftLexeme;
-        for (int i = 0; i < lexemes.size(); i++) {
-            Lexeme l = lexemes.get(i);
-            if (NlpUtil.isFeature(l.getProperty(), nees_pacs_result) && i > 0) {
-                int c = i - 1;
-                while (c > -1) {
-                    leftLexeme = lexemes.get(c);
-                    if (NlpUtil.isFeature(leftLexeme.getProperty(), nees_pacs_name)) {
-                        PreResult result = new PreResult();
-                        result.setValue(NlpUtil.concept(l, NegativeEnum.PACS_RESULT));
-                        result.setDetailName(NlpUtil.concept(leftLexeme, NegativeEnum.PACS_NAME));
-                        result.setUniqueName(NlpUtil.concept(leftLexeme, NegativeEnum.PACS_NAME));
-                        preResultList.add(result);
-                        break;
-                    }
-                    c--;
-                }
-
-            }
-        }
-
-        return preResultList;
-    }
-
-    public PreResult createPreResult(LexemePath<Lexeme> lexemes, Lexeme lexeme, int index) {
-        return super.createDefaultPreResult(lexemes, lexeme, index);
-    }
-
-    public String findBodyValue(LexemePath<Lexeme> lexemes, Lexeme lexeme, int index) {
-        return null;
-    }
-}

+ 2 - 11
common-push/src/main/java/org/diagbot/common/push/filter/rule/PretreatmentRule.java

@@ -1,13 +1,11 @@
 package org.diagbot.common.push.filter.rule;
 
 
-import org.diagbot.common.push.bean.PreResult;
-import org.diagbot.common.push.bean.ResponseData;
 import org.diagbot.common.push.bean.Rule;
 import org.diagbot.common.push.bean.SearchData;
 import org.diagbot.common.push.cache.ApplicationCacheUtil;
-import org.diagbot.common.push.filter.pretreat.*;
-import org.diagbot.pub.Constants;
+import org.diagbot.nlp.rule.module.PreResult;
+import org.diagbot.nlp.rule.pretreat.*;
 import org.springframework.util.StringUtils;
 
 import java.io.IOException;
@@ -63,13 +61,6 @@ public class PretreatmentRule {
         return add2PreResultList(preResultList, content, ruleType, searchData);
     }
 
-    public static void main(String[] args) throws IOException {
-        PretreatmentRule pretreatmentRule = new PretreatmentRule();
-        SearchData searchData = new SearchData();
-        searchData.setSymptom("钠(Na)110mmol/L");
-        pretreatmentRule.rule(searchData);
-    }
-
     private String add2PreResultList(List<PreResult> preResultList, String content, String ruleType, SearchData searchData) throws java.io.IOException {
         Map<String, List<Rule>> kl_rule_filter_map = ApplicationCacheUtil.getKl_rule_filter_map();
         //符合条件的规则

+ 22 - 0
common-push/src/main/java/org/diagbot/common/push/util/PushConstants.java

@@ -1,5 +1,8 @@
 package org.diagbot.common.push.util;
 
+import java.util.HashMap;
+import java.util.Map;
+
 /**
  * @ClassName org.diagbot.bigdata.util.BigDataConstants
  * @Description TODO
@@ -38,4 +41,23 @@ public class PushConstants {
     public final static String result_mapping_vital = "resultMappingVitalMap";          //推送体征结果名称映射
     public final static String result_mapping_diag = "resultMappingDiagMap";          //推送疾病科室名称映射
     public final static String result_mapping_filter = "resultMappingFilterMap";          //推送结果年龄 性别过滤
+
+    //关系抽取property_id对应property_name
+    public final static Map<String,String> featureTypeMap = new HashMap<String,String>(){{
+        put("80","辅检其他");
+        put("9","单位");
+        put("2","时间");
+        put("3","部位");
+        put("7","反意或虚拟");
+        put("16","辅检项目");
+        put("17","辅检结果");
+        put("81","属性");
+        put("82","方位");
+        put("83","形容词");
+        put("84","局部结构");
+        put("85","属性值");
+        put("86","表现");
+        put("28","字母与数值");
+        put("87","正常表现");
+    }};
 }

+ 20 - 27
common-push/src/main/java/org/diagbot/common/push/work/ParamsDataProxy.java

@@ -1,7 +1,15 @@
 package org.diagbot.common.push.work;
 
+import com.alibaba.fastjson.JSON;
+import org.algorithm.core.cnn.AlgorithmCNNExecutor;
+import org.algorithm.core.cnn.AlgorithmCNNExecutorPacs;
+import org.algorithm.factory.RelationExtractionFactory;
 import org.apache.commons.lang3.StringUtils;
+import org.diagbot.common.push.bean.FeatureRate;
+import org.diagbot.common.push.bean.ResponseData;
+import org.diagbot.common.push.bean.ResultMappingFilter;
 import org.diagbot.common.push.bean.SearchData;
+import org.diagbot.common.push.cache.ApplicationCacheUtil;
 import org.diagbot.common.push.util.PushConstants;
 import org.diagbot.nlp.feature.FeatureAnalyze;
 import org.diagbot.nlp.feature.FeatureType;
@@ -12,7 +20,6 @@ import org.slf4j.LoggerFactory;
 
 import javax.servlet.http.HttpServletRequest;
 import java.util.*;
-import java.util.regex.Pattern;
 
 /**
  * @ClassName org.diagbot.bigdata.work.ParamsDataProxy
@@ -23,25 +30,6 @@ import java.util.regex.Pattern;
  **/
 public class ParamsDataProxy {
     Logger logger = LoggerFactory.getLogger(ParamsDataProxy.class);
-    //标准词只处理的词性
-    public static NegativeEnum[] negativeEnums = new NegativeEnum[] { NegativeEnum.VITAL_INDEX, NegativeEnum.SYMPTOM
-            , NegativeEnum.DIGITS, NegativeEnum.EVENT_TIME, NegativeEnum.UNIT, NegativeEnum.DIAG_STAND
-            , NegativeEnum.OTHER};
-    //标准词处理的三元组
-    public static NegativeEnum[][] negativeEnumTriple = {
-            { NegativeEnum.VITAL_INDEX, NegativeEnum.DIGITS, NegativeEnum.UNIT },
-            { NegativeEnum.VITAL_INDEX, NegativeEnum.DIGITS, NegativeEnum.EVENT_TIME },
-            { NegativeEnum.SYMPTOM, NegativeEnum.DIGITS, NegativeEnum.UNIT },
-            { NegativeEnum.SYMPTOM, NegativeEnum.DIGITS, NegativeEnum.EVENT_TIME },
-            { NegativeEnum.DIAG_STAND, NegativeEnum.DIGITS, NegativeEnum.UNIT },
-            { NegativeEnum.DIAG_STAND, NegativeEnum.DIGITS, NegativeEnum.EVENT_TIME },
-            { NegativeEnum.DIAG_STAND, NegativeEnum.DIGITS, NegativeEnum.OTHER }
-    };
-    //标准词处理的二元组
-    public static NegativeEnum[][] negativeEnumTwoTuple = {
-            { NegativeEnum.VITAL_INDEX, NegativeEnum.DIGITS },
-            { NegativeEnum.SYMPTOM, NegativeEnum.DIGITS }
-    };
 
     public void createNormalInfo(SearchData searchData) throws Exception {
         //计算年龄区间
@@ -138,11 +126,16 @@ public class ParamsDataProxy {
             featuresList = fa.start(searchData.getDiag(), FeatureType.DIAG);
             paramFeatureInit(searchData, featuresList);
         }
-
-        //主诉、现病史、体征文本信息一并传入模型
-        Map<String, String> featureMap = new HashMap<>();
-        featureMap.put("sentence", searchData.getSymptom());
-        searchData.getInputs().put("sentence", featureMap);
+        if (!StringUtils.isEmpty(searchData.getPacs())) {
+            //关系抽取模型
+            AlgorithmCNNExecutorPacs algorithmCNNExecutor = RelationExtractionFactory.getInstance();
+            RelationExtractionUtil re = new RelationExtractionUtil();
+            //Pacs原始分词结果
+            List<List<String>> execute = algorithmCNNExecutor.execute(searchData.getPacs(), re.createTriad(searchData));
+            if (execute != null && execute.size() > 0) {
+                re.addToSearchDataInputs(execute, searchData);
+            }
+        }
     }
 
     /**
@@ -253,10 +246,10 @@ public class ParamsDataProxy {
                 map.put("concept", String.valueOf(featureMap.get("concept")));
                 if (Constants.default_negative.equals(featureMap.get("negative"))) {
                     if (map.get("featureType").equals(Constants.feature_type_time)) {
-                        searchData.getInputs().put("时间", map);
+//                        searchData.getInputs().put("时间", map);
                     } else {
                         if (searchData.getInputs().get(map.get("feature_name")) == null) {
-                            if (i < 5) {
+                            if (i < 8) {
                                 searchData.getInputs().put(map.get("feature_name"), map);
                             }
                             searchData.getGraphInputs().put(map.get("feature_name"), map);

+ 95 - 0
common-push/src/main/java/org/diagbot/common/push/work/RelationExtractionUtil.java

@@ -0,0 +1,95 @@
+package org.diagbot.common.push.work;
+
+import org.algorithm.core.cnn.entity.Lemma;
+import org.algorithm.core.cnn.entity.Triad;
+import org.diagbot.common.push.bean.SearchData;
+import org.diagbot.common.push.cache.ApplicationCacheUtil;
+import org.diagbot.common.push.util.PushConstants;
+import org.diagbot.nlp.participle.ParticipleUtil;
+import org.diagbot.nlp.participle.word.Lexeme;
+import org.diagbot.nlp.participle.word.LexemePath;
+import org.diagbot.nlp.util.Constants;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @Description:
+ * @Author: HUJING
+ * @Date: 2019/9/9 17:30
+ */
+public class RelationExtractionUtil {
+    public List<Triad> createTriad(SearchData searchData) throws IOException {
+        List<Triad> triads = new ArrayList<>();
+        String[] pacsSplits = searchData.getPacs().trim().split("。|\n");
+        List<Lemma> lemmaList = new ArrayList<>();
+        Lemma lemma = null;
+        for (String pacsSplit : pacsSplits) {
+            LexemePath<Lexeme> pacsLexemes = ParticipleUtil.participlePacs(pacsSplit);
+            for (int i = 0; i < pacsLexemes.size(); i++) {
+                //跳过非医学词
+                if (Constants.word_property_other.equals(pacsLexemes.get(i).getProperty())) {
+                    continue;
+                }
+                lemma = new Lemma();
+                lemma.setText(pacsLexemes.get(i).getText());
+                lemma.setPosition(String.valueOf(pacsLexemes.get(i).getOffset()) + "," + (Integer.valueOf(pacsLexemes.get(i).getOffset() + pacsLexemes.get(i).getLength()) - 1));
+                lemma.setProperty(PushConstants.featureTypeMap.get(pacsLexemes.get(i).getProperty()));
+                lemmaList.add(lemma);
+            }
+        }
+        for (int i = 0; i < lemmaList.size() - 1; i++) {
+            for (int j = i + 1; j < lemmaList.size(); j++) {
+                Triad triad = new Triad();
+                triad.setL_1(lemmaList.get(i));
+                triad.setL_2(lemmaList.get(j));
+                triads.add(triad);
+            }
+        }
+        return triads;
+    }
+
+    public void addToSearchDataInputs(List<List<String>> relationExtractionContents, SearchData searchData) throws Exception {
+        StringBuffer sb = null;
+        for (List<String> contents : relationExtractionContents) {
+            sb = new StringBuffer();
+            for (String content : contents) {
+                sb.append(content);
+            }
+            if (isExist(sb.toString())) {
+                Map<String, String> map = new HashMap<>();
+                map.put("featureType", Constants.feature_type_pacs);
+                map.put("featureName", sb.toString());
+                map.put("property", Constants.word_property_PACS_Result);
+                map.put("concept", sb.toString());
+                //全是有
+                map.put("negative", Constants.default_negative);
+                if (searchData.getInputs().get(map.get("featureName")) == null) {
+                    searchData.getInputs().put(map.get("featureName"), map);
+                }
+                if (searchData.getGraphInputs().get(map.get("featureName")) == null) {
+                    searchData.getGraphInputs().put(map.get("featureName"), map);
+                }
+            }
+        }
+    }
+
+    /**
+     * 关系抽取输出的content是否在已有诊断依据中存在
+     * @param content
+     * @return
+     */
+    public boolean isExist(String content){
+        Map<String, Map<String, String>> kl_diagnose_detail_filter_map = ApplicationCacheUtil.getKl_diagnose_detail_filter_map();
+        if (kl_diagnose_detail_filter_map.get("4") != null){
+            if (kl_diagnose_detail_filter_map.get("4").containsKey(content)){
+                return true;
+            }
+        }
+        return false;
+    }
+
+}

+ 28 - 317
graph-web/src/main/java/org/diagbot/graphWeb/work/GraphCalculate.java

@@ -5,7 +5,6 @@ import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
 import org.apache.commons.lang3.StringUtils;
 import org.diagbot.common.push.bean.FeatureRate;
-import org.diagbot.common.push.bean.PreResult;
 import org.diagbot.common.push.bean.ResponseData;
 import org.diagbot.common.push.bean.SearchData;
 import org.diagbot.common.push.bean.neo4j.Filnlly;
@@ -19,7 +18,7 @@ import org.diagbot.graph.jdbc.Neo4jAPI;
 import javax.servlet.http.HttpServletRequest;
 import java.util.*;
 
-import org.diagbot.graphWeb.util.MapValueComparator;
+import org.diagbot.nlp.rule.module.PreResult;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -39,15 +38,14 @@ public class GraphCalculate {
 
         long starttime = System.currentTimeMillis();
         System.out.println("Start at: " + starttime);
-
         ResponseData responseData = new ResponseData();
 //        ParamsDataProxy paramsDataProxy = new ParamsDataProxy();
 //        paramsDataProxy.createSearchData(request, searchData);
         List<String> inputList = new ArrayList<>();
         int age = searchData.getAge();
         String sex = searchData.getSex();
+        String diseaseName = searchData.getDiseaseName();
         logger.info("前端传来的年龄为 :"+age+" 前端传来的性别为 :"+sex);
-
         Map<String, Map<String, String>> sexAgeCache = CacheUtil.getSexAgeCache();
         Map<String, Map<String, String>> inputs = searchData.getGraphInputs();
         Set<String> ss = new HashSet<>();
@@ -61,9 +59,9 @@ public class GraphCalculate {
                 }
             }
         }
+
         logger.info("从分词系统接收到的词 :" + ss);
         System.out.println("Participle takes: " + (System.currentTimeMillis()-starttime)/1000d + 's');
-
         List<String> featureTypeList = Arrays.asList(searchData.getFeatureTypes());
         logger.info("featureTypeList : " + featureTypeList);
         inputList.addAll(ss);
@@ -73,39 +71,38 @@ public class GraphCalculate {
         logger.info("图谱开始推送诊断!!!!!!!!!!!");
         String webDiag = searchData.getDiag();
         logger.info("页面诊断为 :"+webDiag);
+        String[] webDiagList = webDiag.split(",|,|、|;|:|;");
         //计算诊断
-        Map<String, Map<String,String>> condition =null;
+        Map<String, Object> condition =null;
         Map<String, Map<String, String>> excludelist = null;
         if(featureTypeList.contains("2")){
             condition = neo4jAPI.getNewCondition((String[]) inputList.toArray(new String[inputList.size()]),webDiag );
-
             // 查找需要排除的诊断
             excludelist = neo4jAPI.getExcludeDiag(inputList);
             responseData.setExcludeDiag(Arrays.asList(excludelist.keySet().stream().toArray(String[]::new)));
         }
-
         List<FeatureRate> featureRates = new ArrayList<>();
         if(condition != null){
-            for (Map.Entry<String, Map<String,String>> d : condition.entrySet()) {
-                String dis = d.getKey();
-                Map<String, String> sexAgeMap = sexAgeCache.get(dis);
-                if(sexAgeMap != null){
-                    String sexType = sexAgeMap.get("sexType");
-                    Integer min_age = Integer.parseInt(sexAgeMap.get("min_age"));
-                    Integer max_age = Integer.parseInt(sexAgeMap.get("max_age"));
-
-                    if(("1".equals(sexType) &&sex.equals(sexType)) || ("2".equals(sexType) &&sex.equals(sexType)) || "3".equals(sexType)){
-                        if(min_age <age && age<=max_age){
-                            FeatureRate featureRate = new FeatureRate();
-                            featureRate.setFeatureName(dis);
-                            Map<String, String> value = d.getValue();
-                            String s = JSON.toJSONString(value);
-                            featureRate.setDesc(s);
-//                            featureRate.setRate("neo4j");
-                            featureRate.setSource("neo4j");
-                            featureRates.add(featureRate);
+            Map<String, Map<String,String>> allCondition = (Map<String, Map<String,String>>)condition.get("全部诊断");
+            if(allCondition != null && allCondition.size()>0){
+                for (Map.Entry<String, Map<String,String>> d : allCondition.entrySet()) {
+                    String dis = d.getKey();
+                    Map<String, String> sexAgeMap = sexAgeCache.get(dis);
+                    if(sexAgeMap != null){
+                        String sexType = sexAgeMap.get("sexType");
+                        Integer min_age = Integer.parseInt(sexAgeMap.get("min_age"));
+                        Integer max_age = Integer.parseInt(sexAgeMap.get("max_age"));
+                        if(("1".equals(sexType) &&sex.equals(sexType)) || ("2".equals(sexType) &&sex.equals(sexType)) || "3".equals(sexType)){
+                            if(min_age <age && age<=max_age){
+                                FeatureRate featureRate = new FeatureRate();
+                                featureRate.setFeatureName(dis);
+                                Map<String, String> value = d.getValue();
+                                String s = JSON.toJSONString(value);
+                                featureRate.setDesc(s);
+                                featureRate.setSource("neo4j");
+                                featureRates.add(featureRate);
+                            }
                         }
-
                     }
                 }
             }
@@ -132,33 +129,28 @@ public class GraphCalculate {
             }
         }
         logger.info("页面导入的所有化验项为 :" +lisSet);
-
         //走治疗
-        if (webDiag !=null && webDiag.trim() != null && webDiag.trim() != "" && featureTypeList.contains("6")) {
+        if (StringUtils.isNotEmpty(diseaseName) && featureTypeList.contains("6")) {
             // 查找页面诊断里是否有不良反应
-            String[] webDiagList = webDiag.split(",|,|、|;|:|;");
-            Map<String, List<String>> disUE = neo4jAPI.getDisUE(webDiagList, diseaseType);
+            Map<String, List<String>> disUE = neo4jAPI.getDisUE(diseaseName, diseaseType);
             //根据页面输入内容推出的不良反应集合
             Set<String> ue = neo4jAPI.getUe((String[]) inputList.toArray(new String[inputList.size()]));
             //走平常诊断治疗
-            Map<String, Filnlly> mulDiseaseTreat = neo4jAPI.getMulDiseaseTreat_2(webDiag, diseaseType, diseaseSet,disUE,ue,String.join(",", inputList));
+            Map<String, Filnlly> mulDiseaseTreat = neo4jAPI.getMulDiseaseTreat_2(diseaseName,webDiag, diseaseType, diseaseSet,disUE,ue,String.join(",", inputList));
             responseData.setTreat(mulDiseaseTreat);
         }
         //管理评估(慢病才有)
         if (featureTypeList.contains("11") && diseaseType == 1 && diseaseType != null) {
             logger.info("featureTypeList 包含11,走管理评估!!!");
             if(webDiag != null){
-                String[] webDiagsplits = webDiag.split(",|,|、|;|:|;");
-                MangementEvaluation mangementEvaluation = neo4jAPI.pushMe(webDiagsplits,lis_Result);
+                MangementEvaluation mangementEvaluation = neo4jAPI.pushMe(webDiagList,lis_Result);
                 Map<String, JSONObject> mangementEvaluation1 = mangementEvaluation.getMangementEvaluation();
                 responseData.setManagementEvaluation(mangementEvaluation1);
             }
         }
-        String pacsOrder = searchData.getPacsOrder();
         //指标推送
         if (featureTypeList.contains("22") ) {
             List<MedicalIndication> idns =new ArrayList<>();
-//            List<MedicalIndication> pacsMi = getPacsMi(pacsOrder, inputList,webDiag);
             Set<String> newindSet = new HashSet<>();
             Set<String> newindSet1 = new HashSet<>();
             //查找指标
@@ -172,8 +164,6 @@ public class GraphCalculate {
                     }
                 }
             }
-
-
             Map<String, String> indLiang =null;
             if(newindSet1 != null && newindSet1.size()>0){
                 indLiang =neo4jAPI.getIndLiang(newindSet1);
@@ -199,297 +189,18 @@ public class GraphCalculate {
                     if(indLiang != null){
                         jsonObject.put("name",indLiang.get(ind)); 
                     }
-                    
                     medicalIndicationDetail.setContent(jsonObject);
                     ds.add(medicalIndicationDetail);
                     medicalIndication.setDetails(ds);
                     idns.add(medicalIndication);
-
                 }
             }
             responseData.setMedicalIndications(idns);
-
         }
-
         //诊断推送
         responseData.setDis(featureRates);
         responseData.setInputs(searchData.getInputs());
-
         System.out.println("Total takes: " + (System.currentTimeMillis()-starttime)/1000d + 's');
         return responseData;
     }
-    public List<MedicalIndication> getPacsMi(String pacsOrder,List<String> inputList,String webDiag){
-        if(StringUtils.isNotEmpty(webDiag)){
-            String[] webDiagsplits = webDiag.split(",|,|、|;|:|;");
-            for (String wd:webDiagsplits
-                 ) {
-                inputList.add(wd);
-            }
-        }
-
-        List<MedicalIndication> pacsMi = new ArrayList<>();
-        Map<String, String> newInd = neo4jAPI.getNewInd((String[]) inputList.toArray(new String[inputList.size()]));
-        if(StringUtils.isNotEmpty(pacsOrder)){
-            String[] pacsOrders = pacsOrder.split(",|,");
-            for (String pacs:pacsOrders) {
-                if(newInd.containsKey(pacs)){
-                    String causes = newInd.get(pacs);
-                    MedicalIndication m = new MedicalIndication();
-                    List<MedicalIndicationDetail> mds = new ArrayList<>();
-                    MedicalIndicationDetail medicalIndicationDetail = new MedicalIndicationDetail();
-                    medicalIndicationDetail.setType(4);
-                    JSONObject jsonObject = new JSONObject();
-                    jsonObject.put("name", causes);
-                    jsonObject.put("controlType",2);
-                    medicalIndicationDetail.setContent(jsonObject);
-                    mds.add(medicalIndicationDetail);
-                    m.setName("不建议做:"+pacs);
-                    m.setDetails(mds);
-                    pacsMi.add(m);
-                }
-            }
-        }
-        return pacsMi;
-    }
-//    诊断过滤
-    public void filterDis(List<FeatureRate> graphFeatureRates,String sex,Integer age) throws Exception {
-        if(neo4jAPI == null){
-            neo4jAPI = new Neo4jAPI(DriverManager.newDrive());
-        }
-        List<String> disList = new ArrayList<>();
-        if(graphFeatureRates != null && graphFeatureRates.size()>0){
-            for (FeatureRate f:graphFeatureRates) {
-                disList.add("\""+f.getFeatureName()+"\"");
-            }
-        }
-//        第一步先过滤性别和年龄
-        Set<String> filterSexAgeList = neo4jAPI.filterDisFromSexAge(disList,sex,age);
-
-
-    }
-    /**
-     * 返回LIS,PACS
-     *
-     * @param searchData
-     */
-    public ResponseData getLisPacs(HttpServletRequest request, SearchData searchData) throws Exception {
-        ResponseData responseData = new ResponseData();
-        Neo4jAPI neo4jAPI = new Neo4jAPI(DriverManager.newDrive());
-        String webDiag = searchData.getDiag();
-        List<String> webDiagList = Arrays.asList(webDiag.split(",|,|、"));
-        List<FeatureRate> bigdataDiagFeature = searchData.getPushDiags();
-        List<String> bigdataDiagList = new LinkedList<>();
-        if (bigdataDiagFeature.size() > 0) {
-            for (FeatureRate fe : bigdataDiagFeature) {
-                if ("neo4j".equals(fe.getRate())) {
-                    bigdataDiagList.add(fe.getFeatureName());
-                    logger.info("图谱推出的诊断为: " + fe.getFeatureName());
-                } else {
-                    bigdataDiagList.add(fe.getFeatureName());
-                    logger.info("大数据推出的诊断为: " + fe.getFeatureName());
-                }
-            }
-        }
-        for (String web : webDiagList) {
-            for (int i = 0; i < bigdataDiagList.size(); i++) {
-                if (bigdataDiagList.get(i).equals(web)) {
-                    bigdataDiagList.remove(bigdataDiagList.get(i));
-                }
-            }
-        }
-        logger.info("界面诊断为: " + webDiagList);
-        logger.info("推出的诊断合并为: " + bigdataDiagList);
-        Map<String, Set<String>> weblisPacs1 = null;
-        Map<String, Set<String>> biglisPacs1 = null;
-        if (webDiagList != null && webDiagList.size() > 0) {
-            weblisPacs1 = neo4jAPI.getLisPacs(webDiagList);//界面诊断推出的LIS,PACS
-        }
-        if (bigdataDiagList != null && bigdataDiagList.size() > 0) {
-            biglisPacs1 = neo4jAPI.getLisPacs(bigdataDiagList);//大数据推得诊断
-        }
-        Set<String> lis = null;
-        Set<String> pacs = null;
-        //如果界面有诊断
-        if (weblisPacs1 != null && weblisPacs1.values().size() > 0) {
-            lis = weblisPacs1.get("LIS");
-            pacs = weblisPacs1.get("PACS");
-            logger.info("界面有诊断的情况下,界面诊断推出的lis为: " + lis);
-            logger.info("界面有诊断的情况下,界面诊断推出的pacs为: " + pacs);
-            if (biglisPacs1 != null && biglisPacs1.values().size() > 0) {
-                Set<String> bl = biglisPacs1.get("LIS");
-                Set<String> bp = biglisPacs1.get("PACS");
-                logger.info("界面有诊断的情况下,推出诊断的lis为: " + bl);
-                logger.info("界面有诊断的情况下,推出诊断的pacs为: " + bp);
-                lis.addAll(bl);
-                pacs.addAll(bp);
-            }
-        } else {
-            lis = biglisPacs1.get("LIS");
-            pacs = biglisPacs1.get("PACS");
-            logger.info("界面无诊断的情况下,推出诊断的lis为: " + lis);
-            logger.info("界面无诊断的情况下,推出诊断的lis为: " + pacs);
-        }
-        logger.info("推出的合并lis为: " + lis);
-        logger.info("推出的合并pacs为: " + pacs);
-        ArrayList<FeatureRate> lisFeature = new ArrayList<>();
-        ArrayList<FeatureRate> pacsFeature = new ArrayList<>();
-        for (String l : lis) {
-            FeatureRate featureRate = new FeatureRate();
-            featureRate.setFeatureName(l);
-            lisFeature.add(featureRate);
-        }
-        for (String p : pacs) {
-            FeatureRate featureRate = new FeatureRate();
-            featureRate.setFeatureName(p);
-            pacsFeature.add(featureRate);
-        }
-        responseData.setLabs(lisFeature);
-        responseData.setPacs(pacsFeature);
-        return responseData;
-    }
-
-
-    /**
-     * 对化验和检查的结果进行排序
-     *
-     * @param set
-     * @return List<FeatureRate>
-     */
-    public Set<String> processResult(Set<String> set) {
-        Set<String> frlist = new LinkedHashSet<>();
-        Map<String, String> sortval = new HashMap<>();
-        Map<String, String> items = new HashMap<>();
-        String name;
-        try {
-            if (set != null && set.size() > 0) {
-                for (String item : set) {
-                    if (sortval.get(item) == null) {
-                        sortval.put(item, "1");
-                    } else {
-                        sortval.put(item, String.valueOf(Integer.parseInt(sortval.get(item)) + 1));
-                    }
-                }
-                sortval = sortMapByValue(sortval);
-                for (String key : sortval.keySet()) {
-                    frlist.add(items.get(key));
-                }
-            }
-        } catch (Exception ex) {
-            ex.printStackTrace();
-        } finally {
-            return frlist;
-        }
-    }
-
-
-    /**
-     * 使用 Map按value进行排序
-     *
-     * @param oriMap
-     * @return
-     */
-    public static Map<String, String> sortMapByValue(Map<String, String> oriMap) {
-        if (oriMap == null || oriMap.isEmpty()) {
-            return null;
-        }
-        Map<String, String> sortedMap = new LinkedHashMap<String, String>();
-        List<Map.Entry<String, String>> entryList = new ArrayList<Map.Entry<String, String>>(
-                oriMap.entrySet());
-        Collections.sort(entryList, new MapValueComparator());
-        Iterator<Map.Entry<String, String>> iter = entryList.iterator();
-        Map.Entry<String, String> tmpEntry = null;
-        while (iter.hasNext()) {
-            tmpEntry = iter.next();
-            sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
-        }
-        return sortedMap;
-    }
-
-
-    public Map<String, Object> scaleCalcMethod(MedicalIndicationDetail medicalIndicationDetail) throws Exception {
-        Map<String, Object> scaleCalcResult = new HashMap<>();
-        Integer type = medicalIndicationDetail.getType();
-        if (type == 2) {
-            JSONObject content = medicalIndicationDetail.getContent();
-            JSONArray contentDetails = content.getJSONArray("details");
-            if ("肾小球滤过率".equals(content.get("name"))) {
-                int age = 0;
-                double scr = 0.00;
-                float k = 0.0f;
-                double a = 0.00;
-                double denger = 0.00;
-                for (int i = 0; i < contentDetails.size(); i++) {
-                    JSONObject detailSub = contentDetails.getJSONObject(i);
-                    if ("年龄".equals(detailSub.getString("name"))) {
-                        if ("".equals(detailSub.getString("value"))) {
-                            //如果拿到的年龄为空,
-                            break;
-                        } else {
-                            age = Integer.parseInt(detailSub.getString("value"));
-                        }
-                    } else if ("血肌酐".equals(detailSub.getString("name"))) {
-                        if ("".equals(detailSub.getString("value"))) {
-                            //如果给的value是空,给的2.2621是假数据
-                            break;
-                        } else {
-                            if ("umol/L".equals(detailSub.getString("value"))) {
-                                scr = Double.valueOf(detailSub.getString("value")) / 88.41;
-                            } else {
-                                scr = Double.valueOf(detailSub.getString("value"));
-                            }
-                        }
-                    } else if ("性别".equals(detailSub.getString("name"))) {
-                        JSONArray genderDetails = detailSub.getJSONArray("details");
-                        for (int j = 0; j < genderDetails.size(); j++) {
-                            JSONObject genderDetail = genderDetails.getJSONObject(j);
-                            //返回的数据结构性别暂时是写死(默认女性)
-                            if (genderDetail.getInteger("state") == 1) {
-                                if ("男".equals(genderDetail.getString("detailName"))) {
-                                    k = 0.9f;
-                                    denger = Double.parseDouble(genderDetail.getString("value"));
-                                    if (scr <= 0.90) {
-                                        a = -0.411;
-                                    } else {
-                                        a = -1.209;
-                                    }
-                                } else if ("女".equals(genderDetail.getString("detailName"))) {
-                                    k = 0.7f;
-                                    denger = Double.parseDouble(genderDetail.getString("value"));
-                                    if (scr <= 0.70) {
-                                        a = -0.329;
-                                    } else {
-                                        a = -1.209;
-                                    }
-                                }
-                            }
-                        }
-                    }
-                }
-                double eGFR3 = 141 * Math.pow((scr / k), a) * Math.pow(0.993, age) * denger;
-                String unit = "ml/min•1.73m2";
-                String text = null;
-                if (eGFR3 <= 0) {
-                    text = "指标值缺少";
-                } else if (eGFR3 > 0 && eGFR3 < 15) {
-                    text = "肾功能衰竭";
-                } else if (eGFR3 >= 15 && eGFR3 <= 29) {
-                    text = "重度下降";
-                } else if (eGFR3 > 29 && eGFR3 < 60) {
-                    text = "中度下降";
-                } else if (eGFR3 >= 60 && eGFR3 <= 89) {
-                    text = "轻度下降";
-                } else if (eGFR3 > 89) {
-                    text = "正常或肾损伤代偿期";
-                }
-
-                scaleCalcResult.put("text", text);
-                scaleCalcResult.put("unit", unit);
-                scaleCalcResult.put("value", eGFR3);
-                System.out.println("text:" + text + "\tunit:" + unit + "\tvalue:" + eGFR3);
-            }
-        }
-
-
-        return scaleCalcResult;
-    }
 }

+ 1 - 1
graph-web/src/main/java/org/diagbot/graphWeb/work/ScaleCalculate.java

@@ -109,7 +109,7 @@ public class ScaleCalculate {
 
                 groupLists.add(groupResults);
             }
-            String text = null;
+            String text = "";
             Map<String, Object> calculate = (Map<String, Object>) data.get("calculate");
             List<Map<String, Object>> rangeList = (List<Map<String, Object>>) calculate.get("range");
             for (Map<String, Object> range : rangeList) {

+ 46 - 41
graph/src/main/java/org/diagbot/graph/jdbc/Neo4jAPI.java

@@ -789,7 +789,8 @@ public class Neo4jAPI {
      * @param webDiag
      * @return
      */
-    public Map<String, Map<String, String>> getNewCondition(String[] keys, String webDiag) {
+    public Map<String, Object> getNewCondition(String[] keys, String webDiag) {
+        Map<String, Object> conditionMap = new HashMap<>();
         Map<String, Map<String, String>> diseaseCondition = new LinkedHashMap<>();
         Map<String, Map<String, String>> diseaseCondition1 = new LinkedHashMap<>(16, 0.75f, true);
         Map<String,Map<String,String>> neoPushMap = new HashMap<>();
@@ -842,17 +843,15 @@ public class Neo4jAPI {
                 Record record = result.next();
                 String quezhenName = record.get("name").toString().replace("\"", "");
                 String conditionType = record.get("relationType").toString().replace("\"", "");
-                /*if("拟诊".equals(conditionType) || "确诊".equals(conditionType)){
-                    que = "确诊";
-                }else {
-                    que = conditionType;
-                }*/
                 que = conditionType;
                 Map<String, String> queMap = neoPushMap.get(quezhenName);
                 if(queMap != null && queMap.size()>0){
+                    if("拟诊".equals(que) &&queMap.keySet().contains("确诊") ){
+                        continue;
+                    }
                     if(queMap.keySet().contains("拟诊") && "确诊".equals(que) ){
                         queMap.remove("拟诊");
-                        queMap.put("确诊","");
+                        queMap.put(que,"");
                         neoPushMap.put(quezhenName,queMap);
                     }else if(que.equals("警惕")){
                         queMap.put("警惕","");
@@ -869,14 +868,7 @@ public class Neo4jAPI {
                     newMap.put(que,"");
                     neoPushMap.put(quezhenName,newMap);
                 }
-               /* if(queMap != null){
-                    queMap.put(que, "");
-                    neoPushMap.put(quezhenName,queMap);
-                }else {
-                    Map<String,String> newMap = new HashMap<>();
-                    newMap.put(que,"");
-                    neoPushMap.put(quezhenName,newMap);
-                }*/
+
             }
             Map<String,Map<String,String>> queHighMap = new HashMap<>();
             Map<String,Map<String,String>> highMap = new HashMap<>();
@@ -885,15 +877,7 @@ public class Neo4jAPI {
                 String dis = l.getKey();
                 Set<String> typeSet = l.getValue().keySet();
                 Map<String,String> con = new HashMap<>();
-                /*if(typeSet.size() == 2 && typeSet.contains("确诊") && typeSet.contains("警惕")){
-                    queHighMap.put(dis,new HashMap<>());
-                }
-                if(typeSet.size() == 1 && typeSet.contains("确诊")){
-                    quezhenMap.put(dis,new HashMap<>());
-                }
-                if(typeSet.size() == 1 && typeSet.contains("警惕")){
-                    highMap.put(dis,new HashMap<>());
-                }*/
+
                 if(typeSet.size() == 2){
                     for (String type:typeSet) {
                         con.put(type,"");
@@ -919,7 +903,6 @@ public class Neo4jAPI {
                     Map<String,String> k = new HashMap<>();
                     k.put("确诊","");
                     k.put("警惕","");
-//                    diseaseCondition.put(dis,k);
                     diseaseCondition.put(dis,queHighMap.get(dis));
                 }
                 if(quezhenMap != null && quezhenMap.size()>0){
@@ -927,7 +910,6 @@ public class Neo4jAPI {
                     for (String dis:queDis) {
                         Map<String,String> k = new HashMap<>();
                         k.put("确诊","");
-//                        diseaseCondition.put(dis,k);
                         diseaseCondition.put(dis,quezhenMap.get(dis));
                     }
                 }
@@ -937,7 +919,6 @@ public class Neo4jAPI {
                     for (String dis:queDis) {
                         Map<String,String> k = new HashMap<>();
                         k.put("确诊","");
-//                        diseaseCondition.put(dis,k);
                         diseaseCondition.put(dis,quezhenMap.get(dis));
                     }
                 }
@@ -946,7 +927,6 @@ public class Neo4jAPI {
                     for (String dis:highSet) {
                         Map<String,String> k = new HashMap<>();
                         k.put("警惕","");
-//                        diseaseCondition.put(dis,k);
                         diseaseCondition.put(dis,highMap.get(dis));
                     }
                 }
@@ -975,6 +955,28 @@ public class Neo4jAPI {
                         }
                     }
                 }
+                //查找是否有页面急诊
+                List<String> webDiagList = new ArrayList<>();
+               /* for (String wd:webDiagSplits) {
+                    webDiagList.add("\'"+wd+"\'");
+                }*/
+                webDiagList.add("\'"+webDiagSplits[0]+"\'");
+                query =propertiesUtil.getProperty("searchEmergency").replace("disList",webDiagList.toString());
+                result = session.run(query);
+                while (result.hasNext()) {
+                    Record record = result.next();
+                    String emDis = record.get("emDis").toString();
+                    int em = record.get("em").asInt();//急诊
+                    Map<String, String> stringStringMap = neoPushMap.get(emDis.replace("\"", ""));
+                    if( stringStringMap == null ){
+                        stringStringMap = new HashMap<>();
+                    }
+                    if(em == 1){
+                        stringStringMap.put("页面急诊", "");
+                        diseaseCondition.put(emDis.replace("\"", ""), stringStringMap);
+                    }
+
+                }
             }
             List<String> newDis = new ArrayList<>();
             //判断急诊
@@ -998,12 +1000,13 @@ public class Neo4jAPI {
                 }
                     diseaseCondition.put(emDis.replace("\"", ""), stringStringMap);
             }
-
+           /* Set<String> queset = new LinkedHashSet<>();
             Set<String> ll = new LinkedHashSet<>();
             Set<String> kk = new LinkedHashSet<>();
             for (Map.Entry<String,Map<String,String>> l:diseaseCondition.entrySet()) {
                 if(l.getValue().keySet().contains("确诊")){
                     ll.add(l.getKey());
+                    queset.add(l.getKey());
                 }else {
                     kk.add(l.getKey());
                 }
@@ -1018,14 +1021,15 @@ public class Neo4jAPI {
                         break;
                     }
                 }
-
                 diseaseCondition1.put(dis,stringStringMap);
             }
+            conditionMap.put("确诊",queset);*/
+            conditionMap.put("全部诊断",diseaseCondition);
         } catch (Exception e) {
             e.printStackTrace();
         } finally {
             CloseSession(session);
-            return diseaseCondition1;
+            return conditionMap;
         }
     }
 
@@ -1347,14 +1351,15 @@ public class Neo4jAPI {
     /**
      * 获取每个慢病对应的不良反应
      *
-     * @param webDiagArray
+     * @param
      * @param diseaseType
      * @return
      */
-    public Map<String, List<String>> getDisUE(String[] webDiagArray, Integer diseaseType) {
+    public Map<String, List<String>> getDisUE(String disName, Integer diseaseType) {
         Session session = null;
         Map<String, List<String>> disUE = new HashMap<>();
         List<String> webDiagList = new ArrayList<>();
+        String[] webDiagArray = disName.split(",");
         if (diseaseType != null && 1 == diseaseType) {
             for (String dis : webDiagArray) {
                 if (!"".equals(dis)) {
@@ -1396,7 +1401,7 @@ public class Neo4jAPI {
      * @param filds   //     * @param sign 标志,2是平常诊断的治疗,0是复诊诊断的治疗,1是急诊
      * @return
      */
-    public Map<String, Filnlly> getMulDiseaseTreat_2(String disease, Integer diseaseType, Set<String> disSet, Map<String, List<String>> disUE, Set<String> ueSet, String filds) {
+    public Map<String, Filnlly> getMulDiseaseTreat_2(String disName,String disease, Integer diseaseType, Set<String> disSet, Map<String, List<String>> disUE, Set<String> ueSet, String filds) {
         Map<String, Filnlly> diagTreat = new HashMap<>();
         Session session = null;
         NumberFormat nf = NumberFormat.getPercentInstance();
@@ -1409,7 +1414,7 @@ public class Neo4jAPI {
             diseaseList.add(diseaseArray[i]);
         }
         Map<String, ArrayList> diseFilds = new HashMap<>();
-        for (int i = 0; i < diseaseList.size(); i++) {
+//        for (int i = 0; i < diseaseList.size(); i++) {
             String[] fildsArray = filds.split(",");
             ArrayList<String> fildsList = new ArrayList<>();//其他条件数组
             for (String fild : fildsArray) {
@@ -1424,14 +1429,14 @@ public class Neo4jAPI {
             for (String h : ueSet) {
                 fildsList.add("\'" + h + "\'");
             }
-            for (int j = 0; j < diseaseList.size(); j++) {
+           /* for (int j = 0; j < diseaseList.size(); j++) {
                 if (i != j) {
                     fildsList.add("\'" + diseaseList.get(j) + "\'");
                 }
-            }
+            }*/
 
-            diseFilds.put(diseaseList.get(i), fildsList);
-        }
+            diseFilds.put(disName, fildsList);
+//        }
         try {
             session = driver.session(AccessMode.WRITE);
             Integer integer = session.writeTransaction(new TransactionWork<Integer>() {
@@ -2873,8 +2878,8 @@ public class Neo4jAPI {
         Map<String, Map<String, String>> diaglist = new HashMap<>();
         try{
             session = driver.session(AccessMode.READ);
-            String query = "unwind " + infostr + " as lis " +
-                    "match (ex)-[q:排除依据]-(c)-[r:排除]->(d:Disease) where ex.name = lis return d";
+
+            String query = propertiesUtil.getProperty("excludeDiag").replace("infostr",infostr);
             System.out.println(query);
             StatementResult dlist = session.run(query);
 

+ 4 - 3
graph/src/main/resources/bolt.properties

@@ -5,9 +5,9 @@ pass_235 = diagbot@20180822
 
 # neo4j bolt credentials
 #\u7EBF\u4E0A\u4F7F\u7528
-bolt.uri=bolt://192.168.2.123
+bolt.uri=bolt://192.168.2.233
 bolt.user=neo4j
-bolt.passwd=root
+bolt.passwd=123456
 
 
 #\u6D4B\u8BD5\u4F7F\u7528
@@ -71,7 +71,8 @@ searchDis=match (n:Condition)-[r:\u786E\u8BCA|:\u62DF\u8BCA|:\u8B66\u60D5]->(m:D
 where n.name in startList\n \
 with distinct m,r\n \
 return m.name as name, labels(m)[0] as label,type(r) as relationType;
-
+#\u6392\u9664\u8BCA\u65AD
+excludeDiag=match (ex)-[q:\u6392\u9664\u4F9D\u636E]-(c)-[r:\u6392\u9664]->(d:Disease) where ex.name in infostr return d
 #\u6CBB\u7597\u5904\u7406
 #\u67E5\u627E\u8BCA\u65AD\u5BF9\u5E94\u7684\u7C7B\u548C\u836F,\u4EE5\u53CA\u4ED6\u4EEC\u7684\u6392\u5E8F
 searchDrugsMedic=match (d:Disease{name:diseaseName})-[r0:\u63A8\u8350]->(m:Drugs)-[:\u5305\u542B]->(n:Medicine),(d:Disease)-[r1:\u63A8\u8350]->(n)\n \

+ 1 - 1
graphdb/src/main/java/org/diagbot/pub/Ciku.java

@@ -2,7 +2,7 @@ package org.diagbot.pub;
 
 public enum Ciku {
     SYMPTOM("1","1,70"),VITAL_RESULT("2","35,70"),BIGlIS("3","12"),SUBLIS("subLis","13")
-    ,RESULTLIS("resultLis","14,70"),PACS("4","16"),RESULTPACS("resultPacs","17,70"),DISEASE("5","18")
+    ,RESULTLIS("resultLis","14"),PACS("4","16"),RESULTPACS("resultPacs","17"),DISEASE("5","18")
     ,HISTORY("6","18,70"),CAUSE("7","5,70"),PROGNOSIS("8","70"),OTHER("9","70");
     private String name;
     private String label;

+ 184 - 0
graphdb/src/main/java/org/diagbot/repository/BiRepository.java

@@ -0,0 +1,184 @@
+package org.diagbot.repository;
+
+import org.diagbot.entity.node.Disease;
+import org.springframework.data.neo4j.annotation.Query;
+import org.springframework.data.neo4j.repository.Neo4jRepository;
+
+import java.util.List;
+import java.util.Map;
+
+public interface BiRepository extends Neo4jRepository<Disease, Long> {
+    List<Disease> findByNameContaining(String token);
+    //查找图谱中诊断依据数量
+    @Query("match(d:Disease)<-[r:确诊|:拟诊]-(c:Condition) return count(distinct d.name) as discount")
+    Long diagnoseCount();
+    //查找图谱中的儿科疾病数量
+    @Query("MATCH (n:Disease)<-[r:确诊|:拟诊]-(c:Condition) where n.maxAge < 200 and n.minAge =0 RETURN count(distinct n.name) as child")
+    Long childCount();
+    //图谱中有内容的量表数量
+    @Query("MATCH (n:Scale) RETURN count(distinct n.name) as scaleCount")
+    Long scaleCount();
+
+
+    // find High Risk Disease
+    @Query("MATCH (d:Disease) WHERE d.name in {0} RETURN d.name as name, d.high_risk as risk")
+    List<Map<String, Object>> findHighRiskDisease(List<String> diseaselist);
+
+    //get high risk
+    @Query("match(d:Disease) where d.name in {0} return d.name as name, d.high_risk as risk")
+    List<Map<String, Object>> getHighRisk(List diagList);
+
+
+    //删除诊断依据
+    //删除关系1
+    @Query("match(d:Disease)<-[r:拟诊|:确诊|:警惕]-(c:Condition)<-[r1]-(k:Condition)<-[r2]-(h:Condition) where d.disId={0} detach delete c,k,h")
+    void deleteRelation1(Long disId);
+    //删除关系2
+    @Query("match(d:Disease)<-[r:拟诊|:确诊|:警惕]-(c:Condition)<-[r1]-(k:Condition) where d.disId={0} detach delete c,k")
+    void deleteRelation2(Long disId);
+    //删除关系3
+    @Query("match(d:Disease)<-[r:拟诊|:确诊|:警惕]-(c:Condition) where d.disId={0} detach delete r")
+    void deleteRelation3(Long disId);
+    //删除排除关系4
+    @Query("match(d:Disease)<-[r:排除]-(l) where d.disId={0} detach delete l")
+    void deleteRelation4(Long disId);
+    //删除排除关系5
+    @Query("match(d:Disease)-[r:表现]->(j)-[r1:属于]->(k) where d.disId={0} detach delete r")
+    void deleteRelation5(Long disId);
+    //删除排除关系6
+    @Query("match(d:Disease)-[r:表现]->(j) where d.disId={0} detach delete r")
+    void deleteRelation6(Long disId);
+    //删除排除关系7
+    @Query("match(d:Disease)-[r:推荐]->(j:LIS) where d.disId={0} detach delete r")
+    void deleteRelation7(Long disId);
+    //删除排除关系8
+    @Query("match(d:Disease)-[r:推荐]->(j:PACS) where d.disId={0} detach delete r")
+    void deleteRelation8(Long disId);
+    //删除排除关系9
+    @Query("match(d:Disease)-[r:鉴别诊断]->(b) where d.disId={0} detach delete r")
+    void deleteRelation9(Long disId);
+    //删除排除关系10
+    @Query("match(c:Condition) where c.name={0} detach delete c")
+    void deleteRelation10(String conditionName);
+    //删除诊断
+    @Query("match(c:Disease) where c.disId={0} detach delete c")
+    void deleteRelation11(Long disId);
+    //更新图谱
+    //存储疾病
+    @Query("merge(d:Disease{name:{0},disId:{1},emergency:{2}})")
+    void mergeDis(String name, Long disId, Integer emergency);
+    //存储确诊,拟诊,警惕
+    @Query( "merge(c:Condition{name:{0},path:{1}})")
+    void mergeCondition(String disName, Integer path);
+    @Query("match(c:Condition{name:{0}}),(d:Disease{disId:{1}})" +
+            " merge(c)-[:确诊]->(d)")
+    void mergeQueNiHigh(String conditionName, Long disId);
+    @Query("match(c:Condition{name:{0}}),(d:Disease{disId:{1}})" +
+            " merge(c)-[:拟诊]->(d)")
+    void mergeNiHigh(String conditionName, Long disId);
+    @Query("match(c:Condition{name:{0}}),(d:Disease{disId:{1}})" +
+            " merge(c)-[:警惕]->(d)")
+    void mergeHigh(String conditionName, Long disId);
+    //任几的condition
+    @Query("merge(c:Condition{name:{0},path:{1},relation:{2}})")
+    void mergeRenCondition(String conditionName, Integer path, String relation);
+    @Query("match(c:Condition{name:{0}}),(s:Condition{name:{1}}) merge(c)-[r:诊断依据]->(s)")
+    void mergeRenCondition(String c1, String c2);
+    //具体code Condition
+    @Query("merge(c:Condition{name:{0},path:1,relation:'任一'})")
+    void mergeNUMCondition(String disName);
+    @Query("match(c:Condition{name:{0}}),(s:Condition{name:{1}}) merge(c)-[r:诊断依据]->(s)")
+    void mergeNUMCondition(String c1, String c2);
+    //开始添加所有的词语
+    //添加症状标准词
+    @Query("merge(d:Symptom{name:{0}})")
+    void mergeStandardSymptom(String name);
+    //疾病表现症状标准词
+    @Query("match(d:Disease{disId:{0}}),(s:Symptom{name:{1}}) merge(d)-[r:表现]->(s)")
+    void mergeRelationStandard(Long disId, String name);
+    //属于症状标准词
+    @Query("match(d:Condition{name:{0}}),(s:Symptom{name:{1}}) merge(d)<-[r:属于]-(s)")
+    void mergeRelationStandardshuyu(String conditionName, String name);
+    //添加体征标准词
+    @Query("merge(d:Vital{name:{0}})")
+    void mergeStandardVital(String name);
+    //疾病表现体征标准词
+    @Query("match(d:Disease{disId:{0}}),(s:Vital{name:{1}}) merge(d)-[r:表现]->(s)")
+    void mergeRelationStandardVital(Long disId, String name);
+    //属于体征标准词
+    @Query("match(d:Condition{name:{0}}),(s:Vital{name:{1}}) merge(d)<-[r:属于]-(s)")
+    void mergeRelationStandardVitalshuyu(String conditionName, String name);
+    //添加病史标准词
+    @Query("merge(d:History{name:{0}})")
+    void mergeStandardHistory(String name);
+    //疾病表现病史标准词
+    @Query("match(d:Disease{disId:{0}}),(s:History{name:{1}}) merge(d)-[r:表现]->(s)")
+    void mergeRelationStandardHistory(Long disId, String name);
+    //属于病史标准词
+    @Query("match(d:Condition{name:{0}}),(s:History{name:{1}}) merge(d)<-[r:属于]-(s)")
+    void mergeRelationStandardHistoryshuyu(String conditionName, String name);
+    //添加诱因标准词
+    @Query("merge(d:Cause{name:{0}})")
+    void mergeStandardCause(String name);
+    //疾病表现诱因标准词
+    @Query("match(d:Disease{disId:{0}}),(s:Cause{name:{1}}) merge(d)-[r:表现]->(s)")
+    void mergeRelationStandardCause(Long disId, String name);
+    //属于诱因标准词
+    @Query("match(d:Condition{name:{0}}),(s:Cause{name:{1}}) merge(d)<-[r:属于]-(s)")
+    void mergeRelationStandardCauseshuyu(String conditionName, String name);
+    //添加病程标准词
+    @Query("merge(d:Prognosis{name:{0}})")
+    void mergeStandardPrognosis(String name);
+    //疾病表现病程标准词
+    @Query("match(d:Disease{disId:{0}}),(s:Prognosis{name:{1}}) merge(d)-[r:表现]->(s)")
+    void mergeRelationStandardPrognosis(Long disId, String name);
+    //属于病程标准词
+    @Query("match(d:Condition{name:{0}}),(s:Prognosis{name:{1}}) merge(d)<-[r:属于]-(s)")
+    void mergeRelationStandardPrognosisshuyu(String conditionName, String name);
+    //添加其他标准词
+    @Query("merge(d:Other{name:{0}})")
+    void mergeStandardOther(String name);
+    //疾病表现其他标准词
+    @Query("match(d:Disease{disId:{0}}),(s:Other{name:{1}}) merge(d)-[r:表现]->(s)")
+    void mergeRelationStandardOther(Long disId, String name);
+    //属于其他标准词
+    @Query("match(d:Condition{name:{0}}),(s:Other{name:{1}}) merge(d)<-[r:属于]-(s)")
+    void mergeRelationStandardOthershuyu(String conditionName, String name);
+    //添加鉴别诊断
+    @Query("merge(d:DifferentDis{name:{0}})")
+    void mergeDifferentDis(String disName);
+    //疾病和鉴别诊断创建关系
+    @Query("match(d:Disease{disId:{0}}),(s:DifferentDis{name:{1}}) merge(d)-[r:鉴别诊断]->(s)")
+    void mergeRelationDifferentDis(Long disId, String name);
+    //创建公表名
+    @Query("merge(l:LIS{name:{0}})")
+    void mergePublicLIS(String lisName);
+    //疾病和鉴别诊断创建关系
+    @Query("match(d:Disease{disId:{0}}),(s:LIS{name:{1}}) merge(d)-[r:推荐]->(s)")
+    void mergeRelationLIS(Long disId, String name);
+    //创建化验结果节点
+    @Query("merge(l:LISResult{name:{0}})")
+    void mergeLISRESULT(String name);
+    //公表名和化验结果创建关系
+    @Query("match(d:LIS{name:{0}}),(s:LISResult{name:{1}}) merge(d)-[r:结果]->(s)")
+    void mergeRelationPublicLIS(String publicLis, String lisResult);
+    //化验结果和对应的codeCondition创建关系
+    @Query("match(d:Condition{name:{0}}),(s:LISResult{name:{1}}) merge(d)<-[r:诊断依据]-(s)")
+    void mergeRelationCondiLisRes(String codeCondition, String lisRes);
+    //创建辅检项目
+    @Query("merge(p:PACS{name:{0}})")
+    void mergePacs(String pacsName);
+    //疾病推荐辅检
+    @Query("match(d:Disease{disId:{0}}),(s:PACS{name:{1}}) merge(d)-[r:推荐]->(s)")
+    void mergeRelationDis2Pacs(Long disId, String name);
+    //创建辅检结果节点
+    @Query("merge(p:PACSResult{name:{0}})")
+    void mergePacsResult(String name);
+    //创建辅检和辅检结果的关系
+    @Query("match(d:PACS{name:{0}}),(s:PACSResult{name:{1}}) merge(d)-[r:结果]->(s)")
+    void mergeRelationPacsResult(String pacs, String pacsResult);
+    //辅检结果和对应的codeCondition创建关系
+    @Query("match(d:Condition{name:{0}}),(s:PACSResult{name:{1}}) merge(d)<-[r:诊断依据]-(s)")
+    void mergeRelationCondiPacsRes(String codeCondition, String pacsRes);
+}
+

+ 11 - 2
graphdb/src/main/java/org/diagbot/repository/DiseaseRepository.java

@@ -140,12 +140,18 @@ public interface DiseaseRepository extends Neo4jRepository<Disease, Long> {
     //疾病和鉴别诊断创建关系
     @Query("match(d:Disease{disId:{0}}),(s:DifferentDis{name:{1}}) merge(d)-[r:鉴别诊断]->(s)")
     void mergeRelationDifferentDis(Long disId,String name);
-    //创建公表名
+    //创建化验大项
     @Query("merge(l:LIS{name:{0}})")
     void mergePublicLIS(String lisName);
-    //疾病和鉴别诊断创建关系
+    //疾病和化验大项创建关系
     @Query("match(d:Disease{disId:{0}}),(s:LIS{name:{1}}) merge(d)-[r:推荐]->(s)")
     void mergeRelationLIS(Long disId,String name);
+    //创建化验公表项
+    @Query("merge(l:PublicLIS{name:{0}})")
+    void mergePublicLIS_1(String lisName);
+    //疾病和化验公表项创建关系
+    @Query("match(d:Disease{disId:{0}}),(s:PublicLIS{name:{1}}) merge(d)-[r:推荐]->(s)")
+    void mergeRelationLIS_1(Long disId,String name);
     //创建化验结果节点
     @Query("merge(l:LISResult{name:{0}})")
     void mergeLISRESULT(String name);
@@ -155,6 +161,9 @@ public interface DiseaseRepository extends Neo4jRepository<Disease, Long> {
     //化验结果和对应的codeCondition创建关系
     @Query("match(d:Condition{name:{0}}),(s:LISResult{name:{1}}) merge(d)<-[r:诊断依据]-(s)")
     void mergeRelationCondiLisRes(String codeCondition,String lisRes);
+    //公表名和化验结果创建关系
+    @Query("match(d:LIS{name:{0}}),(s:PublicLIS{name:{1}}) merge(d)-[r:化验公表]->(s)")
+    void mergeRelationPublicAndLIS(String lis,String publicLis);
     //创建辅检项目
     @Query("merge(p:PACS{name:{0}})")
     void mergePacs(String pacsName);

+ 2 - 0
graphdb/src/main/java/org/diagbot/service/KnowledgeService.java

@@ -58,5 +58,7 @@ public interface KnowledgeService {
     RespDTO deleteNeoDisease(NeoParamVO singleDisease);
     //批量插入
     RespDTO<Boolean> batchInsertDis();
+    //图谱bi统计
+    List<BiDetail> neoBi();
 
 }

+ 83 - 46
graphdb/src/main/java/org/diagbot/service/impl/KnowledgeServiceImpl.java

@@ -28,10 +28,7 @@ import org.springframework.data.domain.Sort;
 import org.springframework.stereotype.Service;
 
 import java.math.RoundingMode;
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
+import java.sql.*;
 import java.text.NumberFormat;
 import java.util.*;
 
@@ -53,11 +50,12 @@ public class    KnowledgeServiceImpl implements KnowledgeService {
     private ScaleRepository scaleRepository;
     @Autowired
     private KnowledgeMapper knowledgeMapper;
-
+    @Autowired
+    private BiRepository biRepository;
     private List<BaseNode> baseNodes;
-    private String user = "root";
-    private String password = "lantone";
-    private String url = "jdbc:mysql://192.168.2.241:3306/med?useUnicode=true&characterEncoding=UTF-8";
+    private String user = "teamdata";
+    private String password = "jiO2rfnYhg";
+    private String url = "jdbc:mysql://192.168.2.121:3306/med?useUnicode=true&characterEncoding=UTF-8";
     private Pageable pageable;
     /**
      * 处理症状节点相关的申请
@@ -399,7 +397,7 @@ public class    KnowledgeServiceImpl implements KnowledgeService {
         List<String> bigdataDiagList = new LinkedList<>();//大数据诊断
         if (bigdataDiagFeature.size() > 0) {
             for (FeatureRate fe : bigdataDiagFeature) {
-                if ("neo4j".equals(fe.getSource()) && fe.getDesc().contains("确诊")) {
+                if ("neo4j".equals(fe.getSource()) && (fe.getDesc().contains("确诊") || fe.getDesc().contains("拟诊"))) {
                     neo4jDiagList.add(fe.getFeatureName());
                 } else if (fe.getDesc() == null) {
                     bigdataDiagList.add(fe.getFeatureName());
@@ -1443,7 +1441,7 @@ public class    KnowledgeServiceImpl implements KnowledgeService {
         if(StringUtils.isNotEmpty(disName)){
             diseaseRepository.mergeDis(disName,disId,0);
         }else {
-            respDTO = RespDTO.onError("在数据库中没有找到"+disId+"对应的疾病!!");
+            respDTO = RespDTO.onError("在数据库中没有找到这个疾病!!");
         }
 
         //获取每个诊断依据的全部数据
@@ -1465,8 +1463,8 @@ public class    KnowledgeServiceImpl implements KnowledgeService {
         Statement st = null;
         ResultSet rs = null;
         try {
-            String type, code ,standard,relation,result,formula,name;
-            String sql = "SELECT diagnose_id,dis_name,`type`,`code`,standard,relation,result,formula FROM `kl_diagnose_detail` where diagnose_id = "+disId+"  and is_deleted = 'N'";
+            String type, code ,standard,relation,unique_name,result,formula,name;
+            String sql = "SELECT diagnose_id,dis_name,`type`,`code`,standard,relation,unique_name,result,formula FROM `kl_diagnose_detail` where diagnose_id = "+disId+"  and is_deleted = 'N'";
             st = connection.createStatement();
             rs = st.executeQuery(sql);
             while (rs.next()){
@@ -1475,6 +1473,7 @@ public class    KnowledgeServiceImpl implements KnowledgeService {
                 code = rs.getString("code");
                 standard = rs.getString("standard");
                 relation = rs.getString("relation");
+                unique_name = rs.getString("unique_name");
                 result = rs.getString("result");
                 formula = rs.getString("formula");
                 name = Type.getName(Integer.parseInt(type));
@@ -1483,6 +1482,7 @@ public class    KnowledgeServiceImpl implements KnowledgeService {
                 content.put("code",code);
                 content.put("standard",standard);
                 content.put("relation",relation);
+                content.put("unique_name",unique_name);
                 content.put("result",result);
                 content.put("formula",formula);
                 contentList.add(content);
@@ -1706,6 +1706,15 @@ public class    KnowledgeServiceImpl implements KnowledgeService {
                 }else if(ni.contains("任七")){
                     path = 7;
                     rel = "任七";
+                }else if(ni.contains("任八")){
+                    path = 8;
+                    rel = "任八";
+                }else if(ni.contains("任九")){
+                    path = 9;
+                    rel = "任九";
+                }else if(ni.contains("任十")){
+                    path = 10;
+                    rel = "任十";
                 }else {
                     path = 1;
                     rel = "任一";
@@ -1790,6 +1799,7 @@ public class    KnowledgeServiceImpl implements KnowledgeService {
             String typeName = row.get("typeName");//类型对应的中文名
             String standard = row.get("standard");//标准词
             String relation = row.get("relation");//关联词
+            String unique_name = row.get("unique_name");//公表项
             String result = row.get("result");//结果
             if(StringUtils.isNotEmpty(type)){
                 String[] split =null;
@@ -1958,48 +1968,35 @@ public class    KnowledgeServiceImpl implements KnowledgeService {
                     }
                 } else if("3".equals(type)){ //处理化验
                     String lis = "";
-                    //查找化验大项的标准词
-                    standWord = searchStandWord(standard,type,ciKu);
-                    if(StringUtils.isNotEmpty(standWord)){
-                        if(StringUtils.isNotEmpty(relation) && standard.equals(relation)){
-                            lis = standWord;
-                        }else if(StringUtils.isNotEmpty(standard) && StringUtils.isEmpty(relation)){
-                            lis = standWord;
-                        }else if(StringUtils.isNotEmpty(standard)&& StringUtils.isNotEmpty(relation)&&!standard.equals(relation)){
-                            type = "subLis";
-                            if(StringUtils.isNotEmpty(searchStandWord(relation,type,ciKu))){
-                                //查找化验小项的标准词
-                                lis = standWord+"--"+searchStandWord(relation,type,ciKu);
-                            }
-
-                        }
-                    }
-
-                    //创建公表名
+                    if(StringUtils.isNotEmpty(unique_name)){
+                        //创建化验公表项
+                        diseaseRepository.mergePublicLIS_1(unique_name);
+                        //疾病和化验公表项创建推荐关系
+                        diseaseRepository.mergeRelationLIS_1(disId,unique_name);
+                        lis =standard;
+                    //创建大项名
                     diseaseRepository.mergePublicLIS(lis);
-                    //疾病推荐化验公表
+                    //疾病推荐化验大项名
                     diseaseRepository.mergeRelationLIS(disId,lis);
                     //处理化验结果
-                    if(StringUtils.isNotEmpty(result)){
+                    if(StringUtils.isNotEmpty(result) && StringUtils.isNotEmpty(unique_name)){
                         lisResultSplit = result.split("、");
                         if(lisResultSplit != null && lisResultSplit.length>0){
-                            //化验结果找标准词
                             for (String lisRs:lisResultSplit) {
                                 if(StringUtils.isNotEmpty(lisRs)){
-                                    lisResult = searchStandWord(lisRs,"resultLis",ciKu);
-                                    if(StringUtils.isNotEmpty(lisResult)){
-                                        //创建化验结果节点
-                                        diseaseRepository.mergeLISRESULT(lisResult);
-                                        //公表名和化验结果创建关系
-                                        diseaseRepository.mergeRelationPublicLIS(lis,lisResult);
-                                        //化验结果和对应的codeCondition创建关系
-                                        diseaseRepository.mergeRelationCondiLisRes(disName+code,lisResult);
-                                    }
-
+                                    //创建化验结果节点
+                                    diseaseRepository.mergeLISRESULT(lisRs);
+                                    //大项和化验结果创建关系
+                                    diseaseRepository.mergeRelationPublicLIS(lis,lisRs);
+                                    //化验结果和对应的codeCondition创建关系
+                                    diseaseRepository.mergeRelationCondiLisRes(disName+code,lisRs);
+                                    //化验大项和化验公表项创建关系
+//                                    diseaseRepository.mergeRelationPublicAndLIS(lis,unique_name);
                                 }
                             }
                         }
                     }
+                    }
                 }else if("4".equals(type)){ //辅检
                     //查找辅检的标准词
                     standWord = searchStandWord(standard,type,ciKu);
@@ -2076,7 +2073,7 @@ public class    KnowledgeServiceImpl implements KnowledgeService {
             connect.close();
             respDTO = RespDTO.onSuc(true);
         }else {
-            respDTO = RespDTO.onError(disId +" 删除失败!!!");
+            respDTO = RespDTO.onError(" 删除失败!!!");
         }
         } catch (SQLException e) {
             e.printStackTrace();
@@ -2124,6 +2121,7 @@ public class    KnowledgeServiceImpl implements KnowledgeService {
             if(disList != null && disList.size()>0){
                 for (Long disId:disList) {
                    respDTO = this.updateNeo(respDTO, disId, connect, ciKu);
+                   this.updateDate(connect,disId);
 
                 }
             }
@@ -2134,8 +2132,46 @@ public class    KnowledgeServiceImpl implements KnowledgeService {
 
         return respDTO;
     }
-    public void updateDate(Connection connection,Long disId){
-        String sql = "UPDATE `kl_diagnose` set neo_update='1970-01-01 12:00:00' where id="+disId+";";
+
+    @Override
+    public List<BiDetail> neoBi() {
+        List<BiDetail> biDetailList = new ArrayList<>();
+        Long disCount = biRepository.diagnoseCount();
+        Long childCount = biRepository.childCount();
+        Long scaleCount = biRepository.scaleCount();
+        BiDetail dis = new BiDetail();
+        dis.setModuleName("疾病");
+        dis.setItemName("图谱推送的疾病");
+        dis.setCount(disCount);
+        BiDetail child = new BiDetail();
+        child.setModuleName("疾病");
+        child.setItemName("图谱推送的儿科疾病");
+        child.setCount(childCount);
+        BiDetail scale = new BiDetail();
+        scale.setModuleName("量表");
+        scale.setItemName("量表总数");
+        scale.setCount(scaleCount);
+        biDetailList.add(dis);
+        biDetailList.add(child);
+        biDetailList.add(scale);
+        return biDetailList;
+    }
+
+    public void updateDate(Connection connection,Long disId) throws SQLException {
+        String sql = "UPDATE `kl_diagnose` set neo_update='1970-01-01 12:00:00' where id=?";
+        PreparedStatement preparedStatement =null;
+        try {
+            connection.setAutoCommit(false);
+            preparedStatement = connection.prepareStatement(sql);
+            preparedStatement.setLong(1,disId);
+            int i = preparedStatement.executeUpdate();
+            connection.commit();
+        } catch (SQLException e) {
+            connection.rollback();
+            e.printStackTrace();
+        }finally {
+            preparedStatement.close();
+        }
     }
     public List<Long> getDisList(Connection connection){
         List<Long> disIds = new ArrayList<>();
@@ -2214,6 +2250,7 @@ public class    KnowledgeServiceImpl implements KnowledgeService {
     }
 
 
+
     public Pageable getPageable(PageVo pageVo) {
         if (pageVo.getSize() > 0) {
             if (pageVo.getSort_key() != null && pageVo.getSort_direct() != null) {

+ 31 - 0
graphdb/src/main/java/org/diagbot/vo/domain/BiDetail.java

@@ -0,0 +1,31 @@
+package org.diagbot.vo.domain;
+
+public class BiDetail {
+    private String moduleName;
+    private String itemName;
+    private Long count;
+
+    public String getModuleName() {
+        return moduleName;
+    }
+
+    public void setModuleName(String moduleName) {
+        this.moduleName = moduleName;
+    }
+
+    public String getItemName() {
+        return itemName;
+    }
+
+    public void setItemName(String itemName) {
+        this.itemName = itemName;
+    }
+
+    public Long getCount() {
+        return count;
+    }
+
+    public void setCount(Long count) {
+        this.count = count;
+    }
+}

+ 11 - 0
graphdb/src/main/java/org/diagbot/web/KnowledgeController.java

@@ -14,6 +14,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 
 import javax.validation.Valid;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
@@ -211,4 +212,14 @@ public class KnowledgeController {
         RespDTO respDTO = knowledgeService.batchInsertDis();
         return respDTO;
     }
+
+    /**
+     * 图谱的bi指标统计
+     * @return
+     */
+    @RequestMapping("/neoStatistics")
+    public List<BiDetail> biCount(){
+        List<BiDetail> biCount = knowledgeService.neoBi();
+        return biCount;
+    }
 }

+ 2 - 2
graphdb/src/main/resources/application.yml

@@ -6,14 +6,14 @@ spring:
     active: local
   data:
     neo4j:
-      uri: bolt://192.168.2.123:7687
+      uri: bolt://192.168.2.233:7687
       username: neo4j
       password: root
 
 # 驱动配置信息
   datasource:
     driver-class-name: org.neo4j.jdbc.Driver
-    url: jdbc:neo4j:http://192.168.2.123:7474
+    url: jdbc:neo4j:http://192.168.2.233:7474
     username: neo4j
     password: root
     #定义初始连接数

+ 60 - 51
nlp-web/src/main/java/org/diagbot/nlp/controller/FeatureController.java

@@ -28,13 +28,18 @@ import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.ResponseBody;
 
 import javax.servlet.http.HttpServletRequest;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
 
 @Controller
 @RequestMapping("/feature")
 public class FeatureController extends BaseController<Feature, FeatureWrapper, Long> {
     private String[] negative_words = Constants.negative_words;
-
+    //体征提取范围
+    private String featureNum;
     private Map<String, String> propelSymptom = null;
     private Map<String, String> propelDiag = null;
     private Map<String, String> propelVital= null;
@@ -146,60 +151,64 @@ public class FeatureController extends BaseController<Feature, FeatureWrapper, L
             Map<String, String> propel = null;
             List<Map<String, Object>> data = new ArrayList<>();
 
+           /* PropertiesUtil propertiesUtil = new PropertiesUtil("nlp.properties");
+            featureNum = propertiesUtil.getProperty("push.feature.num");*/
             FeatureAnalyze sa = new FeatureAnalyze();
             for (String featureType : featureTypes.split(",")) {
-                for (Info info : docInfos) {
-                    switch (FeatureType.parse(featureType)) {
-                        case SYMPTOM:
-                            content = info.getPresent();
-                            propel = propelSymptom;
-                            break;
-                        case TIME:
-                            content = info.getPresent();
-                            propel = propelSymptom;
-                            break;
-                        case FEATURE:
-                            content = info.getPresent();
-                            propel = propelSymptom;
-                            break;
-                        case VITAL:
-                            content = info.getVital();
-                            propel = propelVital;
-                            break;
-                        case PACS:
-                            content = info.getPacs();
-                            propel = propelPacs;
-                            break;
-                        case LIS:
-                            content = info.getLis();
-                            propel = propelLis;
-                            break;
-                        case DIAG:
-                            content = info.getDiag();
-                            propel = propelDiag;
-                            break;
-                    }
-                    featureList = sa.start(content, FeatureType.parse(featureType));
-
-                    if (featureList == null) {
-                        continue;
-                    }
-                    for (int i = 0; i < featureList.size(); i++) {
-                        featureMap = featureList.get(i);
-                        featureMap.put("rdn", info.getRdn());
-                        featureMap.put("age", StringUtils.isEmpty(info.getAge())?"0":info.getAge());
-                        featureMap.put("sex", info.getSex());
-                        featureMap.put("resource_type", info.getResourceType());
-
-                        if (propel.get(featureMap.get("feature_name")) == null) {
-                            featureMap.put("is_push", "0");
-                        } else {
-                            featureMap.put("is_push", "1");
+                for (String feature : featureNum.split(",")) {
+                    /*sa.setFeatureNum(feature);*/
+                    for (Info info : docInfos) {
+                        switch (FeatureType.parse(featureType)) {
+                            case SYMPTOM:
+                                content = info.getPresent();
+                                propel = propelSymptom;
+                                break;
+                            case TIME:
+                                content = info.getPresent();
+                                propel = propelSymptom;
+                                break;
+                            case FEATURE:
+                                content = info.getPresent();
+                                propel = propelSymptom;
+                                break;
+                            case VITAL:
+                                content = info.getVital();
+                                propel = propelVital;
+                                break;
+                            case PACS:
+                                content = info.getPacs();
+                                propel = propelPacs;
+                                break;
+                            case LIS:
+                                content = info.getLis();
+                                propel = propelLis;
+                                break;
+                            case DIAG:
+                                content = info.getDiag();
+                                propel = propelDiag;
+                                break;
+                        }
+                        featureList = sa.start(content, FeatureType.parse(featureType));
+                        if (featureList == null) {
+                            continue;
+                        }
+                        for (int i = 0; i < featureList.size(); i++) {
+                            featureMap = featureList.get(i);
+                            featureMap.put("rdn", info.getRdn() + "_" + feature);
+                            featureMap.put("age", StringUtils.isEmpty(info.getAge()) ? "0" : info.getAge());
+                            featureMap.put("sex", info.getSex());
+                            featureMap.put("resource_type", info.getResourceType());
+                            if (propel.get(featureMap.get("feature_name")) == null) {
+                                featureMap.put("is_push", "0");
+                            } else {
+                                featureMap.put("is_push", "1");
+                            }
+                            data.add(featureMap);
                         }
-                        data.add(featureMap);
-                    }
 
+                    }
                 }
+
             }
 
             MysqlJdbc jdbc = new MysqlJdbc(env.getProperty("spring.datasource.username"),

+ 7 - 0
nlp/src/main/java/org/diagbot/nlp/feature/FeatureAnalyze.java

@@ -18,6 +18,7 @@ import java.util.Map;
 
 public class FeatureAnalyze {
     private LexemePath<Lexeme> lexemePath = null;
+/*    private String featureNum = "";//特征提取范围*/
 
     Logger logger = LoggerFactory.getLogger(FeatureAnalyze.class);
 
@@ -61,6 +62,7 @@ public class FeatureAnalyze {
 //        }
 //        logger.info("分词文本结果:" + lexeme_text);
         lexemePath = replaceLexeme(lexemePath);
+        /*caseToken.getFeatureSize(featureNum);*/
         return caseToken.analyze(lexemePath);
     }
 
@@ -98,4 +100,9 @@ public class FeatureAnalyze {
         }
         return lexemePath;
     }
+
+  /*  public String setFeatureNum(String featureNum){
+        this.featureNum = featureNum;
+        return featureNum;
+    }*/
 }

+ 31 - 2
nlp/src/main/java/org/diagbot/nlp/feature/extract/CaseToken.java

@@ -6,8 +6,10 @@ import org.diagbot.nlp.util.Constants;
 import org.diagbot.nlp.util.NegativeEnum;
 import org.diagbot.nlp.util.NlpUtil;
 
-import java.util.*;
-
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
 public abstract class CaseToken {
     protected static String[] ignore_symbol = new String[]{"、", "."};
     protected static String[] stop_symbol = new String[]{"。", ";", "?", ";", "?", "“", "”", "\r", "\n", "[", "]", "{", "}"};
@@ -20,6 +22,7 @@ public abstract class CaseToken {
     protected Lexeme leftFeatureLexeme = null;
     protected Lexeme rightFeatureLexeme = null;
     protected int sn = 0;
+/*    protected String featureSize = "";*/
 
     static {
         Arrays.sort(ignore_symbol);
@@ -100,6 +103,29 @@ public abstract class CaseToken {
             }
         }
         if (!hasFeature) {
+ /*           if (StringUtils.isNotEmpty(featureSize)) {
+                if(featureSize.equals("all")){//featureSize为all时提取所有特征
+                    Map<String, Object> fMap = new HashMap<>(10);
+                    fMap.put("feature_name", lexeme.getText());
+                    fMap.put("feature_type", featureType);
+                    fMap.put("negative", key);
+                    fMap.put("sn", String.valueOf(sn++));
+                    fMap.put("property", lexeme.getProperty());
+                    fMap.put("concept", lexeme.getConcept());
+                    featuresList.add(fMap);
+                }else {
+                    if (sn < Integer.parseInt(featureSize)){
+                        Map<String, Object> fMap = new HashMap<>(10);
+                        fMap.put("feature_name", lexeme.getText());
+                        fMap.put("feature_type", featureType);
+                        fMap.put("negative", key);
+                        fMap.put("sn", String.valueOf(sn++));
+                        fMap.put("property", lexeme.getProperty());
+                        fMap.put("concept", lexeme.getConcept());
+                        featuresList.add(fMap);
+                    }
+                }
+            }*/
             Map<String, Object> fMap = new HashMap<>(10);
             fMap.put("feature_name", lexeme.getText());
             fMap.put("feature_type", featureType);
@@ -110,5 +136,8 @@ public abstract class CaseToken {
             featuresList.add(fMap);
         }
     }
+  /*  public void getFeatureSize(String fetureSize){
+        this.featureSize = fetureSize;
+    }*/
 }
 

+ 33 - 15
nlp/src/main/java/org/diagbot/nlp/participle/ParticipleUtil.java

@@ -23,20 +23,7 @@ public class ParticipleUtil {
         LexemePath<Lexeme> lexemes = participle(content);
         if (isCombineUnit) {
             ParticipleUtil util = new ParticipleUtil();
-            lexemes = util.combineValidate(lexemes);
-            lexemes = util.joinTime(lexemes);
-
-            String year_pattern = "([1-2][0-9]{3}|[0-9]{2})";
-            String mouth_day_pattern = "([0-9]{2}|[0-9])";
-            String join_pattern = "([-/.]?)";
-            String pattern_string = year_pattern + join_pattern + mouth_day_pattern + join_pattern + mouth_day_pattern;
-            for (Lexeme l : lexemes) {
-                if (l.getProperty().equals(Constants.word_property_number)) {
-                    if (Pattern.matches(pattern_string,l.getText())) {
-                        l.setProperty(Constants.word_property_time);
-                    }
-                }
-            }
+            lexemes = util.combine(util, lexemes);
         }
         return lexemes;
     }
@@ -48,6 +35,19 @@ public class ParticipleUtil {
         return participle(content, NlpCache.segment_cache);
     }
 
+    public static LexemePath<Lexeme> participlePacs(String content) throws IOException {
+        if (NlpCache.segment_cache_pacs == null) {
+            NlpCache.createSegmentCachePacs();
+        }
+        ParticipleToken token = new ParticipleToken();
+        token.start(new StringReader(content), NlpCache.segment_cache_pacs);
+        LexemePath<Lexeme> lexemePath = token.getLexemePath();
+        ParticipleUtil util = new ParticipleUtil();
+        lexemePath = util.combine(util, lexemePath);
+        token.end();
+        return lexemePath;
+    }
+
     public static LexemePath<Lexeme> participle(String content, String path) throws IOException {
         Configuration configuration = new DefaultConfig();
         NlpCache.segment_cache = configuration.loadMainDict(path);
@@ -65,6 +65,24 @@ public class ParticipleUtil {
         return lexemePath;
     }
 
+    private LexemePath<Lexeme> combine(ParticipleUtil util, LexemePath<Lexeme> lexemes) {
+        lexemes = util.combineValidate(lexemes);
+        lexemes = util.joinTime(lexemes);
+
+        String year_pattern = "([1-2][0-9]{3}|[0-9]{2})";
+        String mouth_day_pattern = "([0-9]{2}|[0-9])";
+        String join_pattern = "([-/.]?)";
+        String pattern_string = year_pattern + join_pattern + mouth_day_pattern + join_pattern + mouth_day_pattern;
+        for (Lexeme l : lexemes) {
+            if (l.getProperty().equals(Constants.word_property_number)) {
+                if (Pattern.matches(pattern_string,l.getText())) {
+                    l.setProperty(Constants.word_property_time);
+                }
+            }
+        }
+        return lexemes;
+    }
+
     public static String participleAndHighlight(String content) throws IOException {
         LexemePath<Lexeme> lexemePath = participle(content, false);
         String separator = "&nbsp;*&nbsp;";
@@ -110,7 +128,7 @@ public class ParticipleUtil {
         System.out.println(Pattern.matches(pattern_string,"12.434"));
         try {
             ParticipleUtil util = new ParticipleUtil();
-            String content = "2017-01,9毫克7斤重量015年6月23日出现";
+            String content = "5天2017-01,9毫克7斤重量015年6月23日出现";
             LexemePath<Lexeme> lexemes = util.participle(content);
 
             lexemes = util.combineValidate(lexemes);

+ 17 - 0
nlp/src/main/java/org/diagbot/nlp/rule/analyze/RuleAnalyze.java

@@ -0,0 +1,17 @@
+package org.diagbot.nlp.rule.analyze;
+
+import org.diagbot.nlp.rule.module.PreResult;
+import org.diagbot.nlp.rule.pretreat.Pretreatment;
+import org.diagbot.nlp.rule.pretreat.PretreatmentLis;
+
+import java.util.List;
+
+/**
+ * Created by louhr on 2019/9/25.
+ */
+public class RuleAnalyze {
+    public List<PreResult> lisConvert(String content) throws java.io.IOException {
+        Pretreatment pretreatment = new PretreatmentLis();
+        return pretreatment.analyze(content);
+    }
+}

+ 1 - 1
common-push/src/main/java/org/diagbot/common/push/bean/PreResult.java

@@ -1,4 +1,4 @@
-package org.diagbot.common.push.bean;
+package org.diagbot.nlp.rule.module;
 
 /**
  * Created by louhr on 2019/8/31.

+ 4 - 2
common-push/src/main/java/org/diagbot/common/push/filter/pretreat/Pretreatment.java

@@ -1,9 +1,9 @@
-package org.diagbot.common.push.filter.pretreat;
+package org.diagbot.nlp.rule.pretreat;
 
-import org.diagbot.common.push.bean.PreResult;
 import org.diagbot.nlp.participle.ParticipleUtil;
 import org.diagbot.nlp.participle.word.Lexeme;
 import org.diagbot.nlp.participle.word.LexemePath;
+import org.diagbot.nlp.rule.module.PreResult;
 import org.diagbot.nlp.util.NegativeEnum;
 import org.diagbot.nlp.util.NlpUtil;
 import org.springframework.util.StringUtils;
@@ -80,4 +80,6 @@ public abstract class Pretreatment {
         }
         return -1;
     }
+
+
 }

+ 2 - 2
common-push/src/main/java/org/diagbot/common/push/filter/pretreat/PretreatmentDiag.java

@@ -1,9 +1,9 @@
-package org.diagbot.common.push.filter.pretreat;
+package org.diagbot.nlp.rule.pretreat;
 
-import org.diagbot.common.push.bean.PreResult;
 import org.diagbot.nlp.participle.ParticipleUtil;
 import org.diagbot.nlp.participle.word.Lexeme;
 import org.diagbot.nlp.participle.word.LexemePath;
+import org.diagbot.nlp.rule.module.PreResult;
 import org.diagbot.nlp.util.NegativeEnum;
 import org.diagbot.nlp.util.NlpUtil;
 

+ 86 - 0
nlp/src/main/java/org/diagbot/nlp/rule/pretreat/PretreatmentLis.java

@@ -0,0 +1,86 @@
+package org.diagbot.nlp.rule.pretreat;
+
+import org.diagbot.nlp.participle.ParticipleUtil;
+import org.diagbot.nlp.participle.word.Lexeme;
+import org.diagbot.nlp.participle.word.LexemePath;
+import org.diagbot.nlp.rule.module.PreResult;
+import org.diagbot.nlp.util.NegativeEnum;
+import org.diagbot.nlp.util.NlpUtil;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class PretreatmentLis extends Pretreatment {
+    private String join_symbols = ";:;:";
+    protected NegativeEnum[] lis_result = new NegativeEnum[]{NegativeEnum.LIS_RESULT};
+    protected NegativeEnum[] lis_name = new NegativeEnum[]{NegativeEnum.LIS_NAME};
+    protected NegativeEnum[] lis_type = new NegativeEnum[]{NegativeEnum.LIS_TYPE};
+
+    public List<PreResult> analyze(String content) throws java.io.IOException {
+        List<PreResult> preResults = new ArrayList<>();
+        LexemePath<Lexeme> lexemes = ParticipleUtil.participle(content);
+        for (int i = 0; i < lexemes.size(); i++) {
+            Lexeme l = lexemes.get(i);
+            if (NlpUtil.isFeature(l.getProperty(), lis_name)) {
+                cursor = i;
+                PreResult result = new PreResult();
+                result.setDetailName(NlpUtil.concept(l, NegativeEnum.LIS_NAME));
+                result = createPreResult(lexemes, result, i);
+                if (result != null) {
+                    preResults.add(result);
+                }
+            }
+        }
+        return preResults;
+    }
+
+    public PreResult createPreResult(LexemePath<Lexeme> lexemes, Lexeme lexeme, int index) {
+        return null;
+    }
+
+    public PreResult createPreResult(LexemePath<Lexeme> lexemes, PreResult result, int index) {
+        Lexeme leftLexeme;
+        //往前查找化验套餐
+        int position = index - 1;
+        while (position > -1) {
+            leftLexeme = lexemes.get(position);
+            if (NlpUtil.isFeature(leftLexeme.getProperty(), lis_type)) {
+                result.setName(NlpUtil.concept(leftLexeme, NegativeEnum.LIS_TYPE));
+                break;
+            }
+            position--;
+        }
+        //往后查找化验结果
+        int max_find_step = 10;
+        if (index ==  lexemes.size() - 1) return null;
+        position = index++;
+        Lexeme rightLexeme;
+        while (position < (index + max_find_step) &&  position < lexemes.size()) {
+            rightLexeme = lexemes.get(position);
+            //遇上数字查找是否有单位
+            if (NlpUtil.isNumberString(rightLexeme)) {
+                result.setValue(rightLexeme.getText());
+                //继续找单位
+                int offset = 1;
+                while (offset < max_find_step && position + offset < lexemes.size()) {
+                    rightLexeme = lexemes.get(position + offset);
+                    if (NlpUtil.isFeature(rightLexeme.getProperty(), nees_time_and_unit)) {
+                        result.setUnits(rightLexeme.getText());
+                        break;
+                    }
+                    offset++;
+                }
+                break;
+            } else if (NlpUtil.isFeature(rightLexeme.getProperty(), lis_result)) {  //化验结果
+                result.setValue(rightLexeme.getText());
+                break;
+            }
+            position++;
+        }
+        return result;
+    }
+
+    public String findBodyValue(LexemePath<Lexeme> lexemes, Lexeme lexeme, int index) {
+        return null;
+    }
+}

+ 2 - 2
common-push/src/main/java/org/diagbot/common/push/filter/pretreat/PretreatmentMakeList.java

@@ -1,9 +1,9 @@
-package org.diagbot.common.push.filter.pretreat;
+package org.diagbot.nlp.rule.pretreat;
 
-import org.diagbot.common.push.bean.PreResult;
 import org.diagbot.nlp.participle.ParticipleUtil;
 import org.diagbot.nlp.participle.word.Lexeme;
 import org.diagbot.nlp.participle.word.LexemePath;
+import org.diagbot.nlp.rule.module.PreResult;
 import org.diagbot.nlp.util.NegativeEnum;
 import org.diagbot.nlp.util.NlpUtil;
 

+ 2 - 4
common-push/src/main/java/org/diagbot/common/push/filter/pretreat/PretreatmentNormal.java

@@ -1,11 +1,9 @@
-package org.diagbot.common.push.filter.pretreat;
+package org.diagbot.nlp.rule.pretreat;
 
-import org.diagbot.common.push.bean.PreResult;
 import org.diagbot.nlp.participle.ParticipleUtil;
 import org.diagbot.nlp.participle.word.Lexeme;
 import org.diagbot.nlp.participle.word.LexemePath;
-import org.diagbot.nlp.util.NegativeEnum;
-import org.diagbot.nlp.util.NlpUtil;
+import org.diagbot.nlp.rule.module.PreResult;
 
 import java.util.List;
 

+ 2 - 2
common-push/src/main/java/org/diagbot/common/push/filter/pretreat/PretreatmentOther.java

@@ -1,9 +1,9 @@
-package org.diagbot.common.push.filter.pretreat;
+package org.diagbot.nlp.rule.pretreat;
 
-import org.diagbot.common.push.bean.PreResult;
 import org.diagbot.nlp.participle.ParticipleUtil;
 import org.diagbot.nlp.participle.word.Lexeme;
 import org.diagbot.nlp.participle.word.LexemePath;
+import org.diagbot.nlp.rule.module.PreResult;
 import org.diagbot.nlp.util.NegativeEnum;
 import org.diagbot.nlp.util.NlpUtil;
 

+ 127 - 0
nlp/src/main/java/org/diagbot/nlp/rule/pretreat/PretreatmentPacs.java

@@ -0,0 +1,127 @@
+package org.diagbot.nlp.rule.pretreat;
+
+import org.diagbot.nlp.participle.ParticipleUtil;
+import org.diagbot.nlp.participle.word.Lexeme;
+import org.diagbot.nlp.participle.word.LexemePath;
+import org.diagbot.nlp.rule.module.PreResult;
+import org.diagbot.nlp.util.NegativeEnum;
+import org.diagbot.nlp.util.NlpUtil;
+
+import java.util.List;
+
+public class PretreatmentPacs extends Pretreatment {
+    protected NegativeEnum[] nees_pacs_result = new NegativeEnum[] { NegativeEnum.PACS_RESULT };
+    protected NegativeEnum[] nees_pacs_name = new NegativeEnum[] { NegativeEnum.PACS_NAME };
+    private String join_symbols = ";:;:";
+
+    public List<PreResult> analyze(String content) throws java.io.IOException {
+        List<PreResult> preResultList = super.analyzeDefault(content);
+        //pacs除了数值型需要转, 还需要对部分检查结果提取,以便做危机警示
+        LexemePath<Lexeme> lexemes = ParticipleUtil.participle(content);
+
+        Lexeme leftLexeme;
+        for (int i = 0; i < lexemes.size(); i++) {
+            Lexeme l = lexemes.get(i);
+            if (NlpUtil.isFeature(l.getProperty(), nees_pacs_result) && i > 0) {
+                int c = i - 1;
+                while (c > -1) {
+                    leftLexeme = lexemes.get(c);
+                    if (NlpUtil.isFeature(leftLexeme.getProperty(), nees_pacs_name)) {
+                        PreResult result = new PreResult();
+                        result.setValue(NlpUtil.concept(l, NegativeEnum.PACS_RESULT));
+                        result.setDetailName(NlpUtil.concept(leftLexeme, NegativeEnum.PACS_NAME));
+                        result.setUniqueName(NlpUtil.concept(leftLexeme, NegativeEnum.PACS_NAME));
+                        preResultList.add(result);
+                        break;
+                    }
+                    c--;
+                }
+            } else if (NlpUtil.isFeature(l.getProperty(), nees_time_and_unit) && i > 0) {
+                PreResult result = data2Object(lexemes, l, i, l.getProperty());
+                if (result != null) {
+                    preResultList.add(result);
+                }
+            }
+        }
+        return preResultList;
+    }
+
+    public PreResult createPreResult(LexemePath<Lexeme> lexemes, Lexeme lexeme, int index) {
+        double value = findNumberValue(lexemes, lexeme, index);
+        if (value == -1) {
+            return null;
+        }
+//        //继续往前找本体
+//        String text = findBodyValue(lexemes, lexeme, index);
+//        if (StringUtils.isEmpty(text)) {
+//            return null;
+//        }
+        PreResult result = new PreResult();
+        result.setValue(String.valueOf(value));
+        result.setUnits(lexeme.getText());
+        return getPreResultPub(lexemes, result);
+    }
+
+    public String findBodyValue(LexemePath<Lexeme> lexemes, Lexeme lexeme, int index) {
+        return null;
+    }
+
+    public PreResult getPreResultPub(LexemePath<Lexeme> lexemes, PreResult result) {
+        //继续往前找辅检明细项
+        if (cursor > 0) {
+            cursor--;
+        }
+        Lexeme leftLexeme = lexemes.get(cursor);
+        if (join_symbols.contains(leftLexeme.getText())) {
+            if (cursor > 0) {
+                cursor--;
+                leftLexeme = lexemes.get(cursor);
+            } else {
+                return null;
+            }
+        }
+        if (NlpUtil.isFeature(leftLexeme.getProperty(), new NegativeEnum[] { NegativeEnum.PACS_NAME })) {
+            result.setDetailName(NlpUtil.concept(leftLexeme, NegativeEnum.PACS_NAME));
+        } else if (NlpUtil.isFeature(leftLexeme.getProperty(), new NegativeEnum[] { NegativeEnum.PACS_NAME })) {
+            result.setUniqueName(NlpUtil.concept(leftLexeme, NegativeEnum.PACS_NAME));
+        } else {
+            return null;
+        }
+        return result;
+    }
+
+    protected double findNumberValue(LexemePath<Lexeme> lexemes, Lexeme lexeme, int index) {
+        if (index < 1) {
+            return -1;
+        }
+        cursor = index - 1;
+        Lexeme leftLexeme = lexemes.get(cursor);
+        if (isNumberString(leftLexeme)) {
+            String[] numbersSplit = leftLexeme.getText().split("\\*");
+            try {
+                if (numbersSplit.length == 2) {
+                    return Double.valueOf(numbersSplit[0]) * Double.valueOf(numbersSplit[1]);
+                } else if (numbersSplit.length == 3) {
+                    return Double.valueOf(numbersSplit[0]) * Double.valueOf(numbersSplit[1])
+                            * Double.valueOf(numbersSplit[2]);
+                } else {
+                    return -1;
+                }
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        }
+        return -1;
+    }
+
+    public static boolean isNumberString(Lexeme l) {
+        if (l == null) {
+            return false;
+        }
+        if (NlpUtil.isFeature(l.getProperty(), new NegativeEnum[] { NegativeEnum.DIGITS })
+                && l.getText().indexOf("*") != -1) {
+            return true;
+        }
+        return false;
+    }
+}

+ 2 - 2
common-push/src/main/java/org/diagbot/common/push/filter/pretreat/PretreatmentSymptom.java

@@ -1,9 +1,9 @@
-package org.diagbot.common.push.filter.pretreat;
+package org.diagbot.nlp.rule.pretreat;
 
-import org.diagbot.common.push.bean.PreResult;
 import org.diagbot.nlp.participle.ParticipleUtil;
 import org.diagbot.nlp.participle.word.Lexeme;
 import org.diagbot.nlp.participle.word.LexemePath;
+import org.diagbot.nlp.rule.module.PreResult;
 import org.diagbot.nlp.util.NegativeEnum;
 import org.diagbot.nlp.util.NlpUtil;
 

+ 2 - 2
common-push/src/main/java/org/diagbot/common/push/filter/pretreat/PretreatmentVital.java

@@ -1,9 +1,9 @@
-package org.diagbot.common.push.filter.pretreat;
+package org.diagbot.nlp.rule.pretreat;
 
-import org.diagbot.common.push.bean.PreResult;
 import org.diagbot.nlp.participle.ParticipleUtil;
 import org.diagbot.nlp.participle.word.Lexeme;
 import org.diagbot.nlp.participle.word.LexemePath;
+import org.diagbot.nlp.rule.module.PreResult;
 import org.diagbot.nlp.util.NegativeEnum;
 import org.diagbot.nlp.util.NlpUtil;
 

+ 14 - 0
nlp/src/main/java/org/diagbot/nlp/util/NlpCache.java

@@ -16,6 +16,8 @@ import java.util.*;
 public class NlpCache {
     //词典库
     public static Segment segment_cache = null;
+    //词典库
+    public static Segment segment_cache_pacs = null;
     //推送字典
     public static Map<String, String> standard_info_push_map = null;
     //词库同义词定义
@@ -34,6 +36,11 @@ public class NlpCache {
         segment_cache = configuration.loadMainDict( "tc.dict");
     }
 
+    public static void createSegmentCachePacs() {
+        Configuration configuration = new DefaultConfig();
+        segment_cache_pacs = configuration.loadMainDict("pacs-tc.dict");
+    }
+
     public static void createPushCache() {
         Configuration configuration = new DefaultConfig();
         standard_info_push_map = configuration.loadMapDict( "push-tc.dict");
@@ -120,6 +127,13 @@ public class NlpCache {
         return segment_cache;
     }
 
+    public static Segment getSegment_cache_pacs() {
+        if (segment_cache_pacs == null) {
+            createSegmentCachePacs();
+        }
+        return segment_cache_pacs;
+    }
+
     public static Map<String, String> getStandard_info_push_map() {
         if (standard_info_push_map == null) {
             createPushCache();

+ 2 - 6
nlp/src/main/java/org/diagbot/nlp/util/NlpUtil.java

@@ -3,6 +3,7 @@ package org.diagbot.nlp.util;
 import org.diagbot.nlp.participle.word.Lexeme;
 
 import java.util.*;
+import java.util.regex.Pattern;
 
 /**
  * @Auther: fyeman
@@ -39,12 +40,7 @@ public class NlpUtil {
         if (NlpUtil.isFeature(l.getProperty(), new NegativeEnum[]{NegativeEnum.NUMBER_QUANTIFIER})) {
             return true;
         }
-        for (char c : l.getText().toCharArray()) {
-            if (c >= '0' && c <= '9') {
-                return true;
-            }
-        }
-        return false;
+        return Pattern.matches("^[-\\+]?\\d+(\\.\\d+)?",l.getText());
     }
 
     public static double numberText2value(Lexeme l) {

+ 5 - 2
nlp/src/main/resources/nlp.properties

@@ -1,3 +1,6 @@
 #数据文件存放路径
-#cache.file.dir=/opt/diagbot-push/cache_file/
-cache.file.dir=d:\\cache_file\\
+cache.file.dir=/opt/diagbot-push/cache_file/
+#cache.file.dir=e:\\cache_file\\
+
+#特征提取范围(不限制范围时配置:all)
+#push.feature.num=all

+ 58 - 23
push-web/src/main/java/org/diagbot/push/controller/AlgorithmController.java

@@ -3,17 +3,24 @@ package org.diagbot.push.controller;
 import com.alibaba.fastjson.JSONObject;
 import org.apache.commons.lang3.StringUtils;
 import org.diagbot.bigdata.work.AlgorithmCore;
+import org.diagbot.bigdata.work.ResultDataProxy;
 import org.diagbot.common.push.bean.CrisisDetail;
 import org.diagbot.common.push.bean.FeatureRate;
 import org.diagbot.common.push.bean.ResponseData;
 import org.diagbot.common.push.bean.SearchData;
-import org.diagbot.common.push.bean.neo4j.*;
+import org.diagbot.common.push.bean.neo4j.Drugs;
+import org.diagbot.common.push.bean.neo4j.Filnlly;
+import org.diagbot.common.push.bean.neo4j.MedicalIndication;
+import org.diagbot.common.push.bean.neo4j.MedicalIndicationDetail;
+import org.diagbot.common.push.bean.neo4j.Medicition;
 import org.diagbot.common.push.cache.CacheUtil;
 import org.diagbot.common.push.filter.ClassifyDiag;
 import org.diagbot.common.push.filter.rule.PretreatmentRule;
 import org.diagbot.common.push.work.ParamsDataProxy;
 import org.diagbot.graphWeb.work.GraphCalculate;
 import org.diagbot.graphWeb.work.LisPacsCalculate;
+import org.diagbot.nlp.rule.pretreat.Pretreatment;
+import org.diagbot.nlp.rule.pretreat.PretreatmentLis;
 import org.diagbot.nlp.util.Constants;
 import org.diagbot.nlp.util.NlpCache;
 import org.diagbot.pub.api.Response;
@@ -22,6 +29,7 @@ import org.diagbot.pub.utils.PropertiesUtil;
 import org.diagbot.pub.utils.http.HttpApi;
 import org.diagbot.pub.web.BaseController;
 import org.diagbot.rule.crisis.CrisisApplication;
+import org.diagbot.rule.lis.LisApplication;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.stereotype.Controller;
@@ -49,7 +57,7 @@ public class AlgorithmController extends BaseController {
         listView = "/pages/algorithm/list.html";
     }
 
-    @RequestMapping({"/index"})
+    @RequestMapping({ "/index" })
     public String index() {
         return listView;
     }
@@ -72,7 +80,7 @@ public class AlgorithmController extends BaseController {
         Response<ResponseData> response = new Response<>();
 
         MysqlJdbc nlpJdbc = new MysqlJdbc("root", "diagbot@20180822", "jdbc:mysql://192.168.2.235:3306/med-s?useUnicode=true&characterEncoding=UTF-8");
-        List<Map<String, String>> data = nlpJdbc.query("doc_info_validate", new String[]{"pk_dcpv", "present", "diag", "sex", "age"}, "");
+        List<Map<String, String>> data = nlpJdbc.query("doc_info_validate", new String[] { "pk_dcpv", "present", "diag", "sex", "age" }, "");
 
         Map<String, String> diags = NlpCache.getStandard_info_synonym_map().get(Constants.word_property_diagnose);
 
@@ -122,6 +130,14 @@ public class AlgorithmController extends BaseController {
     public Response<ResponseData> combine(HttpServletRequest request, SearchData searchData) throws Exception {
         ResponseData responseData = new ResponseData();
         logger.info("开始推送服务......");
+        LisApplication lisApplication = new LisApplication();
+        if ((searchData.getLisArr() == null || searchData.getLisArr().size() == 0)
+                && StringUtils.isNotEmpty(searchData.getLis())) {
+            Pretreatment pretreatment = new PretreatmentLis();
+            searchData.setLisArr(pretreatment.analyze(searchData.getLis()));
+        }
+        lisApplication.lisConvertToInputs(searchData.getLisArr(),searchData);
+
         Response<ResponseData> response = new Response();
         //一些基本信息预处理 如年龄 性别
         ParamsDataProxy paramsDataProxy = new ParamsDataProxy();
@@ -141,19 +157,31 @@ public class AlgorithmController extends BaseController {
         ResponseData graphResponseData = graphCalculate.calculate(request, searchData);
         if (graphResponseData.getDis().size() > 0) {
             List<FeatureRate> disFeatureRates = new ArrayList<>();
-            boolean isFind = false;
+            /*boolean isFind = false;
             for (int i = 0; i < bigDataResponseData.getDis().size(); i++) {
                 FeatureRate bigdata_fr = bigDataResponseData.getDis().get(i);
                 isFind = false;
                 for (FeatureRate graph_fr : graphResponseData.getDis()) {
-                    if (bigdata_fr.getFeatureName().equals(graph_fr.getFeatureName())) {
+                    if (graph_fr.getDesc().contains("拟诊")|| graph_fr.getDesc().contains("确诊") && bigdata_fr.getFeatureName().equals(graph_fr.getFeatureName())) {
                         isFind = true;
                     }
                 }
                 if (!isFind) {
                     disFeatureRates.add(bigdata_fr);
                 }
+            }*/
+            List<FeatureRate> bigdis = bigDataResponseData.getDis();
+            List<FeatureRate> graphdis = graphResponseData.getDis();
+            for (FeatureRate bg:graphdis) {
+                Iterator<FeatureRate> iterator = bigdis.iterator();
+                while (iterator.hasNext()){
+                    FeatureRate gd = iterator.next();
+                    if(gd.getFeatureName().equals(bg.getFeatureName()) &&(bg.getDesc().contains("确诊")|| bg.getDesc().contains("拟诊"))){
+                        iterator.remove();
+                    }
+                }
             }
+            disFeatureRates = bigdis;
             List<FeatureRate> graphFeatureRates = graphResponseData.getDis();
             graphFeatureRates.addAll(disFeatureRates);
             bigDataResponseData.setDis(graphFeatureRates);
@@ -170,11 +198,13 @@ public class AlgorithmController extends BaseController {
         Map<String, List<CrisisDetail>> crisisDetails = responseData.getCrisisDetails();
         List<MedicalIndication> crisisDetailsList = this.getCrisisDetails(crisisDetails);
         List<MedicalIndication> medicalIndications = graphResponseData.getMedicalIndications();
-        if (medicalIndications == null) medicalIndications = new ArrayList<>();
+        if (medicalIndications == null) {
+            medicalIndications = new ArrayList<>();
+        }
         medicalIndications.addAll(crisisDetailsList);
         if (medicalIndications != null && medicalIndications.size() > 0) {
             logger.info("指标推送!!!!!!!!!");
-//           bigDataResponseData.getMedicalIndications().addAll(medicalIndications);
+            //           bigDataResponseData.getMedicalIndications().addAll(medicalIndications);
             bigDataResponseData.setMedicalIndications(medicalIndications);
         }
 
@@ -191,11 +221,11 @@ public class AlgorithmController extends BaseController {
         Map<String, String> vitalCache = CacheUtil.getVitalCache();
         List<String> featureList = Arrays.asList(searchData.getFeatureTypes());
         List<FeatureRate> vitals = graphResponseData.getVitals();
-        if(featureList.contains(Constants.feature_type_vital_index) && this.getVital(vitalCache,vitals).size() > 0){
-            bigDataResponseData.setVitals(this.getVital(vitalCache,vitals));
+        if (featureList.contains(Constants.feature_type_vital_index) && this.getVital(vitalCache, vitals).size() > 0) {
+            bigDataResponseData.setVitals(this.getVital(vitalCache, vitals));
 
         }
-        if(featureList.contains(Constants.feature_type_vital) && vitals.size() > 0){
+        if (featureList.contains(Constants.feature_type_vital) && vitals.size() > 0) {
             bigDataResponseData.setVitals(vitals);
         }
 
@@ -205,29 +235,33 @@ public class AlgorithmController extends BaseController {
         List<FeatureRate> classify = classifyDiag.diagClassify(upfes);
         List<FeatureRate> featureRates = classifyDiag.sortDiag(classify);
         bigDataResponseData.setDis(featureRates);
+        //返回结果化验、辅检、体征、进行性别年龄过滤
+        ResultDataProxy resultDataProxy = new ResultDataProxy();
+        resultDataProxy.resultSexAgeFilter(request, bigDataResponseData, searchData);
         response.setData(bigDataResponseData);
         return response;
     }
 
     /**
      * 包装输出的危急值
+     *
      * @param crisisDetails
      * @return
      */
-    public List<MedicalIndication> getCrisisDetails(Map<String, List<CrisisDetail>> crisisDetails){
+    public List<MedicalIndication> getCrisisDetails(Map<String, List<CrisisDetail>> crisisDetails) {
         List<MedicalIndication> crisisDetailList = new ArrayList<>();
-        for(Map.Entry<String, List<CrisisDetail>> entry : crisisDetails.entrySet()) {
-            for (CrisisDetail crisisDetail:entry.getValue()) {
+        for (Map.Entry<String, List<CrisisDetail>> entry : crisisDetails.entrySet()) {
+            for (CrisisDetail crisisDetail : entry.getValue()) {
                 String originText = crisisDetail.getOriginText();//文本输入的数据
                 String remindText = crisisDetail.getRemindText();//危机警示指标
                 String standardText = crisisDetail.getStandardText();//评判标准
-                if(StringUtils.isNotEmpty(remindText)){
+                if (StringUtils.isNotEmpty(remindText)) {
                     MedicalIndication medicalIndication = new MedicalIndication();
                     List<MedicalIndicationDetail> crisisMid = new ArrayList<>();
                     MedicalIndicationDetail medicalIndicationDetail = new MedicalIndicationDetail();
                     JSONObject jsonObject = new JSONObject();
-                    jsonObject.put("controlType",2);
-                    jsonObject.put("name",standardText);
+                    jsonObject.put("controlType", 2);
+                    jsonObject.put("name", standardText);
                     medicalIndicationDetail.setType(4);
                     medicalIndicationDetail.setContent(jsonObject);
                     crisisMid.add(medicalIndicationDetail);
@@ -240,26 +274,27 @@ public class AlgorithmController extends BaseController {
         return crisisDetailList;
     }
 
-    public List<FeatureRate> getVital(Map<String, String> vitalCache,List<FeatureRate> vitals){
+    public List<FeatureRate> getVital(Map<String, String> vitalCache, List<FeatureRate> vitals) {
         Set<String> vitalSet = new LinkedHashSet<>();
         List<FeatureRate> vitalList = new ArrayList<>();
-        if(vitals != null){
-            for (FeatureRate f:vitals) {
+        if (vitals != null) {
+            for (FeatureRate f : vitals) {
                 String s = vitalCache.get(f.getFeatureName());
-                if(StringUtils.isNotEmpty(s)){
+                if (StringUtils.isNotEmpty(s)) {
                     vitalSet.add(s);
                 }
             }
         }
-        if(vitalSet != null){
-            for (String vi:vitalSet) {
-                FeatureRate featureRate= new FeatureRate();
+        if (vitalSet != null) {
+            for (String vi : vitalSet) {
+                FeatureRate featureRate = new FeatureRate();
                 featureRate.setFeatureName(vi);
                 vitalList.add(featureRate);
             }
         }
         return vitalList;
     }
+
     public Response<ResponseData> algorithm(HttpServletRequest request, SearchData searchData) throws Exception {
         Response<ResponseData> response = new Response();
 

+ 2 - 0
push-web/src/main/java/org/diagbot/push/controller/CacheFileManagerController.java

@@ -32,6 +32,7 @@ public class CacheFileManagerController extends BaseController {
         NlpCache.createClassifyCache();
         NlpCache.createChronicCache();
         NlpCache.createSynonymCache();
+        NlpCache.createSegmentCachePacs();
         //更新图谱缓存
         CacheUtil.createDiagSortCache();
         CacheUtil.createSexAgeCache();
@@ -44,6 +45,7 @@ public class CacheFileManagerController extends BaseController {
         ApplicationCacheUtil.createDoc_result_mapping_filter_map();
         ApplicationCacheUtil.create_kl_rule_filter_map();
         ApplicationCacheUtil.create_kl_rule_app_filter_map();
+        ApplicationCacheUtil.create_kl_diagnose_detail_filter_map();
         return response;
     }
 }

+ 11 - 0
push-web/src/main/java/org/diagbot/push/controller/ParticipleController.java

@@ -20,6 +20,17 @@ public class ParticipleController extends BaseController {
         return listView;
     }
 
+    @ResponseBody
+    @RequestMapping("/split_pacs")
+    public Response split(String content) throws IOException {
+        Response response = new Response();
+        long start = System.currentTimeMillis();
+        response.setData(ParticipleUtil.participlePacs(content));
+        long end = System.currentTimeMillis();
+        System.out.println("总耗时:........." + (end - start));
+        return response;
+    }
+
     @ResponseBody
     @RequestMapping("/split_and_highlight")
     public Response splitAndHighlight(String content) throws IOException {

+ 21 - 0
rule/src/main/java/org/diagbot/rule/crisis/CrisisApplication.java

@@ -77,4 +77,25 @@ public class CrisisApplication {
         }
         return crisisMap;
     }
+
+    private String mergeStandardText(Rule rule) {
+        //标准值最优先匹配
+        StringBuffer sb = new StringBuffer();
+        if (org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getEq_value())) {
+            sb.append(rule.getPub_name()).append(rule.getEq_operator()).append(rule.getEq_value());
+        } else if (org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getMax_value()) && org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getMin_value())) {
+            sb.append(rule.getPub_name()).append(rule.getMin_operator()).append(rule.getMin_value())
+                    .append(rule.getMin_unit()).append(";")
+                    .append(rule.getPub_name()).append(rule.getMax_operator()).append(rule.getMax_value())
+                    .append(rule.getMax_unit());
+        } else if (org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getMin_value())) {
+            sb.append(rule.getPub_name()).append(rule.getMin_operator()).append(rule.getMin_value())
+                    .append(rule.getMin_unit());
+        } else if (org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getMax_value())) {
+            sb.append(rule.getPub_name()).append(rule.getMax_operator()).append(rule.getMax_value())
+                    .append(rule.getMax_unit());
+        }
+        return sb.toString();
+    }
+
 }

+ 101 - 0
rule/src/main/java/org/diagbot/rule/lis/LisApplication.java

@@ -0,0 +1,101 @@
+package org.diagbot.rule.lis;
+
+import org.diagbot.common.push.bean.SearchData;
+import org.diagbot.nlp.rule.module.PreResult;
+import org.diagbot.nlp.util.Constants;
+import org.springframework.util.StringUtils;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Pattern;
+
+/**
+ * @Description:
+ * @Author: HUJING
+ * @Date: 2019/9/25 13:33
+ */
+public class LisApplication {
+    private static String up = "升高";
+    private static String down = "降低";
+    private static String normal = "正常";
+
+    public void lisConvertToInputs(List<PreResult> preResultList, SearchData searchData) {
+        if (preResultList == null || preResultList.size() == 0) {
+            return;
+        }
+        String covertValue = "";
+        for (PreResult result : preResultList) {
+            if (!StringUtils.isEmpty(result.getUniqueName())) {
+                //value是数值类型则进行转换
+                if (!StringUtils.isEmpty(result.getValue()) && isNumber(result.getValue())) {
+                    if (!StringUtils.isEmpty(result.getMaxValue()) && !StringUtils.isEmpty(result.getMinValue())
+                            && isNormal(result.getValue(), result.getMaxValue(), result.getMinValue())) {
+                        covertValue = result.getUniqueName() + normal;
+                    } else if (!StringUtils.isEmpty(result.getMaxValue())
+                            && compareMax(result.getValue(), result.getMaxValue())) {
+                        covertValue = result.getUniqueName() + up;
+                    } else if (!StringUtils.isEmpty(result.getMinValue())
+                            && compareMin(result.getValue(), result.getMinValue())) {
+                        covertValue = result.getUniqueName() + down;
+                    }
+                } else if (!StringUtils.isEmpty(result.getOtherValue())) {
+                    //otherValue是文本类型则直接与UniqueName拼接
+                    covertValue = result.getUniqueName() + result.getOtherValue();
+                }
+
+                Map<String, String> map = new HashMap<>();
+                map.put("featureType", Constants.feature_type_lis);
+                map.put("featureName", covertValue);
+                map.put("property", Constants.word_property_LIS_Result);
+                map.put("concept", covertValue);
+                //全是有
+                map.put("negative", Constants.default_negative);
+                if (searchData.getInputs().get(map.get("featureName")) == null) {
+                    searchData.getInputs().put(map.get("featureName"), map);
+                }
+                if (searchData.getGraphInputs().get(map.get("featureName")) == null) {
+                    searchData.getGraphInputs().put(map.get("featureName"), map);
+                }
+            }
+        }
+    }
+
+
+    private boolean isNormal(String value, String maxValue, String minValue) {
+        try {
+            return Double.valueOf(value) < Double.valueOf(maxValue) && Double.valueOf(value) > Double.valueOf(minValue);
+        } catch (Exception e) {
+        }
+        return false;
+    }
+
+    private boolean compareMin(String value, String minValue) {
+        try {
+            return Double.valueOf(value) < Double.valueOf(minValue);
+        } catch (Exception e) {
+        }
+        return false;
+    }
+
+    private boolean compareMax(String value, String maxValue) {
+        try {
+            return Double.valueOf(value) > Double.valueOf(maxValue);
+        } catch (Exception e) {
+        }
+        return false;
+    }
+
+    /**
+     * 只要是整数或者是小数就是true
+     * @param value
+     * @return
+     */
+    public static boolean isNumber(String value) {
+        if (StringUtils.isEmpty(value)) {
+            return false;
+        }
+        return Pattern.matches("^[-\\+]?\\d+(\\.\\d+)?",value);
+    }
+}