Esempio n. 1
0
 def get_medicine_totle_weight(self):
     weight = 0
     neoDb = Neo4jOpt()
     nodes = neoDb.selectNodeElementsFromDB(self.MEDICINETAG)
     for i in range(len(nodes)):
         weight += nodes[i][self.NODEWEIGHT]
     return weight
Esempio n. 2
0
 def store_zhongyaocai_file(self):
     print('开始保存中药材文件')
     neoDb = Neo4jOpt()
     neoDb.graph.data('MATCH (n) DETACH DELETE n')
     with codecs.open('../data/medicine2symptom.txt', 'r',
                      encoding='utf-8') as f:
         for line in f:
             splits = line.split('||')
             medicine = splits[1]
             print medicine
             symptomsList = splits[2].split(',')
             medicineNode = neoDb.selectFirstNodeElementsFromDB(
                 self.MEDICINETAG, properties={self.NODENAME: medicine})
             if (medicineNode == None):
                 medicineNode = neoDb.createNode([self.MEDICINETAG],
                                                 {self.NODENAME: medicine})
             for symptom in symptomsList:
                 symptomNode = neoDb.selectFirstNodeElementsFromDB(
                     self.SYMPTOMTAG, properties={self.NODENAME: symptom})
                 if (symptomNode == None):
                     symptomNode = neoDb.createNode(
                         [self.SYMPTOMTAG], {self.NODENAME: symptom})
                 s2mrel = neoDb.selectFirstRelationshipsFromDB(
                     symptomNode, self.SYMPTOM2MEDICINETAG, medicineNode)
                 if (s2mrel == None):
                     neoDb.createRelationship(self.SYMPTOM2MEDICINETAG,
                                              symptomNode, medicineNode)
Esempio n. 3
0
 def input_multiple_syptomes(self, symptomList, tongueZhi, tongueTai,
                             pulse):
     mysql2Neo = Mysql2Neo4j()
     medicineClassNum = mysql2Neo.get_medicine_class_num()
     symptomClassNum = mysql2Neo.get_syptome_class_num()
     tongueZhiClassNum = mysql2Neo.get_tonguezhi_class_num()
     tongueTaiClassNum = mysql2Neo.get_tonguetai_class_num()
     pulseClassNum = mysql2Neo.get_pulse_class_num()
     medicineTotalWeight = mysql2Neo.get_medicine_totle_weight()
     medicineDicList = []
     neoDb = Neo4jOpt()
     medicinNodes = neoDb.selectNodeElementsFromDB(Mysql2Neo4j.MEDICINETAG)
     for i in range(len(medicinNodes)):
         medicineNode = medicinNodes[i]
         medicineDic = {}
         medicineDic[self.NAME] = medicineNode[Mysql2Neo4j.NODENAME]
         medicineWeight = medicineNode[Mysql2Neo4j.NODEWEIGHT]
         medicnePro = self.myLog((medicineWeight + 1.0) /
                                 (medicineTotalWeight + medicineClassNum))
         symptomOfMedicinePro = 0
         for symptom in symptomList:
             symtpomWeight = self.getSymptome2MedicineWeight(
                 symptom, medicineNode)
             symptomOfMedicinePro = symptomOfMedicinePro + self.myLog(
                 (symtpomWeight + 1.0) / (medicineWeight + symptomClassNum))
         tongueZhiWeight = self.getTongueZhi2MedicineWeight(
             tongueZhi, medicineNode)
         tongueZhiOfMedicinePro = self.myLog(
             (tongueZhiWeight + 1.0) / (medicineWeight + tongueZhiClassNum))
         tongueTaiWeight = self.getTongueTai2MedicineWeight(
             tongueTai, medicineNode)
         tongueTaiOfMedicinePro = self.myLog(
             (tongueTaiWeight + 1.0) / (medicineWeight + tongueTaiClassNum))
         pulseWeight = self.getPulse2MedicineWeight(pulse, medicineNode)
         pulseOfMedicinePro = self.myLog(
             (pulseWeight + 1.0) / (medicineWeight + pulseClassNum))
         totalPro = medicnePro + symptomOfMedicinePro + tongueZhiOfMedicinePro + tongueTaiOfMedicinePro + pulseOfMedicinePro
         # print(medicineNode[Mysql2Neo4j.NODENAME])
         # print("symptomOfMedicinePro"+str(symptomOfMedicinePro))
         # print("tongueZhiOfMedicinePro"+str(tongueZhiOfMedicinePro))
         # print("tongueTaiOfMedicinePro"+str(tongueTaiOfMedicinePro))
         # print("pulseOfMedicinePro"+str(pulseOfMedicinePro))
         # print("medicnePro"+str(medicnePro))
         # print("totalPro"+str(totalPro))
         medicineDic[self.PROBABILITY] = totalPro
         medicineDicList.append(medicineDic)
     # 按照后验概率降序排列
     rankList = sorted(medicineDicList,
                       key=lambda k: k[self.PROBABILITY],
                       reverse=True)
     topMedicineList = []
     topk = 0
     if (len(rankList) < self.TOPK):
         topk = len(rankList)
     else:
         topk = self.TOPK
     for i in range(topk):
         topMedicineList.append(rankList[i])
     lableList = self.chooseLablesNumber(topMedicineList)
     return lableList
Esempio n. 4
0
 def relationFilter(self):
     neoDb = Neo4jOpt()
     cql = 'MATCH ()-[r:' + self.SYMPTOM2SYMPTOMTAG + ']-() where r.' + self.RELATIONWEIGHT + '<' + str(
         self.SYM2SYMTHRESHOLD) + ' delete r'
     neoDb.graph.data(cql)
     cql = 'MATCH ()-[r:' + self.SYMPTOM2MEDICINETAG + ']-() where r.' + self.RELATIONWEIGHT + '<' + str(
         self.SYM2MEDTHRESHOLD) + ' delete r'
     neoDb.graph.data(cql)
Esempio n. 5
0
 def is_symptom_with_pulse(self, symptom, pulse):
     cql = 'MATCH (s:' + Mysql2Neo4j.SYMPTOMTAG + ')-[r]->(e:' + Mysql2Neo4j.PULSETAG + ") WHERE s.name='"+symptom+"' and e.name='" + pulse + "' return r"
     neoDb = Neo4jOpt()
     result = neoDb.graph.data(cql)
     if len(result)>0:
         print "存在"
     else:
         print "矛盾"
Esempio n. 6
0
 def is_symptom_with_tonguetai(self, symptom, tonguetai):
     cql = 'MATCH (s:' + Mysql2Neo4j.SYMPTOMTAG + ')-[r]->(e:' + Mysql2Neo4j.TONGUETAITAG + ") WHERE s.name='"+symptom+"' and e.name='" + tonguetai + "' return r"
     neoDb = Neo4jOpt()
     result = neoDb.graph.data(cql)
     if len(result)>0:
         print "存在"
     else:
         print "矛盾"
Esempio n. 7
0
 def store_symptom2tonguezhi(self, filter=False, filterSet=set([])):
     FileUtil.print_string(u"开始存储症状和舌质的关系...", True)
     mysqlDb = MysqlOpt()
     neoDb = Neo4jOpt()
     treamentMysql = mysqlDb.select('treatment',
                                    'id,symptomIds,tongueZhiId')
     for treamentUnit in treamentMysql:
         syptomeIds = treamentUnit[1].split(",")
         tid = int(treamentUnit[0])
         tongueZhiId = treamentUnit[2]
         if (filter == True and tid not in filterSet):
             continue
         for syptomeId in syptomeIds:
             tongueZhiNodes = neoDb.selectNodeElementsFromDB(
                 self.TONGUEZHITAG,
                 condition=[],
                 properties={self.NODEID: int(tongueZhiId)})
             syptomeNodes = neoDb.selectNodeElementsFromDB(
                 self.SYMPTOMTAG,
                 condition=[],
                 properties={self.NODEID: int(syptomeId)})
             if (len(tongueZhiNodes) > 0 and len(syptomeNodes) > 0):
                 tongueZhiNode = tongueZhiNodes[0]
                 syptomeNode = syptomeNodes[0]
                 # print(tongueZhiNode['name'])
                 # print(syptomeNode['name'])
                 # print("输出症状%s和舌质%s的关系:%d" % (
                 # syptomeNode['name'].encode('utf8'), tongueZhiNode['name'].encode('utf8'), tid))
                 # 如果节点之间已经存在关系了,则权重加1,否则创建关系
                 relations = neoDb.selectRelationshipsFromDB(
                     syptomeNode, self.SYMPTOM2TONGUEZHITAG, tongueZhiNode)
                 if (len(relations) > 0):
                     # print("更新症状%s和舌质%s的关系" % (syptomeNode['name'].encode('utf8'), tongueZhiNode['name'].encode('utf8')))
                     relation = relations[0]
                     tids = relation[self.RELATIONTID]
                     tids.append(tid)
                     ntids = list(set(tids))
                     nweight = len(ntids)
                     neoDb.updateKeyInRelationship(relation,
                                                   properties={
                                                       self.RELATIONTID:
                                                       ntids,
                                                       self.RELATIONWEIGHT:
                                                       nweight
                                                   })
                 else:
                     tids = [tid]
                     weight = 1
                     neoDb.createRelationship(self.SYMPTOM2TONGUEZHITAG,
                                              syptomeNode,
                                              tongueZhiNode,
                                              propertyDic={
                                                  self.RELATIONTID: tids,
                                                  self.RELATIONWEIGHT:
                                                  weight
                                              })
     mysqlDb.close()
Esempio n. 8
0
 def getPulse2MedicineWeight(self, pulse, medicineNode):
     neoDb = Neo4jOpt()
     nodes = neoDb.selectNodeElementsFromDB(
         Mysql2Neo4j.PULSETAG, properties={Mysql2Neo4j.NODENAME: pulse})
     if (len(nodes) == 0):
         return 0
     node = nodes[0]
     relations = neoDb.selectRelationshipsFromDB(
         node, Mysql2Neo4j.PULSE2MEDICINETAG, medicineNode)
     if (len(relations) == 0):
         return 0
     relation = relations[0]
     weight = relation[Mysql2Neo4j.RELATIONWEIGHT]
     return weight
Esempio n. 9
0
 def getTongueTai2MedicineWeight(self, tongueTai, medicineNode):
     neoDb = Neo4jOpt()
     nodes = neoDb.selectNodeElementsFromDB(
         Mysql2Neo4j.TONGUETAITAG,
         properties={Mysql2Neo4j.NODENAME: tongueTai})
     if (len(nodes) == 0):
         return 0
     node = nodes[0]
     relations = neoDb.selectRelationshipsFromDB(
         node, Mysql2Neo4j.TONGUETAI2MEDICINETAG, medicineNode)
     if (len(relations) == 0):
         return 0
     relation = relations[0]
     weight = relation[Mysql2Neo4j.RELATIONWEIGHT]
     return weight
Esempio n. 10
0
 def store_pulse(self, filter=False, filterSet=set([])):
     mysqlDb = MysqlOpt()
     neoDb = Neo4jOpt()
     cql = "MATCH (n:" + self.PULSETAG + ") DETACH DELETE n"
     neoDb.graph.data(cql)
     FileUtil.print_string(u"开始存储脉搏节点...", True)
     mysqlDatas = mysqlDb.select('pulse', 'id,name')
     for unit in mysqlDatas:
         id = unit[0]
         name = unit[1]
         if (filter == True and id not in filterSet):
             continue
         neoDb.createNode([self.PULSETAG], {
             self.NODEID: id,
             self.NODENAME: name
         })
     mysqlDb.close()
Esempio n. 11
0
 def store_medicine_weight(self, filter=False, filterSet=set([])):
     FileUtil.print_string(u"开始存储每个中药节点的出现的次数...", True)
     mysqlDb = MysqlOpt()
     neoDb = Neo4jOpt()
     treamentMysql = mysqlDb.select('treatment', 'id,prescriptionId')
     for treamentUnit in treamentMysql:
         tid = int(treamentUnit[0])
         # print tid
         pid = int(treamentUnit[1])
         if (filter == True and tid not in filterSet):
             continue
         priscriptionMysql = mysqlDb.select('prescription', 'name',
                                            'id = ' + str(pid))
         if (len(priscriptionMysql) > 0):
             medicineIds = priscriptionMysql[0][0].split(",")
         else:
             continue
         # 针对name末尾有逗号的情况进行处理
         lenth = len(medicineIds)
         if (medicineIds[lenth - 1] == ''):
             medicineIds.pop()
         for medicineId in medicineIds:
             # print "mid"+str(medicineId)
             medicineNodes = neoDb.selectNodeElementsFromDB(
                 self.MEDICINETAG,
                 condition=[],
                 properties={self.NODEID: int(medicineId)})
             if (len(medicineNodes) > 0):
                 medicineNode = medicineNodes[0]
                 tids = []
                 for i in medicineNode[self.NODETID]:
                     tids.append(int(i))
                 tids.append(tid)
                 ntids = list(set(tids))
                 nweight = len(ntids)
                 neoDb.updateKeyInNode(medicineNode,
                                       properties={
                                           self.NODETID: ntids,
                                           self.NODEWEIGHT: nweight
                                       })
     mysqlDb.close()
Esempio n. 12
0
 def store_medicine(self, filter=False, filterSet=set([])):
     mysqlDb = MysqlOpt()
     neoDb = Neo4jOpt()
     # 先删除数据库中存在的medicine节点以及和其有关联的关系
     cql = "MATCH (n:" + self.MEDICINETAG + ") DETACH DELETE n"
     neoDb.graph.data(cql)
     FileUtil.print_string(u"开始存储中药节点...", True)
     mysqlDatas = mysqlDb.select('medicine', 'id,name')
     for unit in mysqlDatas:
         id = unit[0]
         name = unit[1]
         if (filter == True and (id not in filterSet)):
             continue
         # print("输出id为%d的药物:%s"%(id,name.encode('utf8')))
         defaultTid = []
         defaultWeight = 0
         neoDb.createNode(
             [self.MEDICINETAG], {
                 self.NODEID: id,
                 self.NODENAME: name,
                 self.NODEWEIGHT: defaultWeight,
                 self.NODETID: defaultTid
             })
     mysqlDb.close()
Esempio n. 13
0
 def get_public_link_node(self,
                          startNodeTag,
                          relationTag,
                          endNodeTag,
                          endNodeKey,
                          endNodeValue,
                          relationOrderKey='weight',
                          seq='DESC',
                          firstArrow='-',
                          secondArrow='->'):
     if len(endNodeValue) == 1:
         cql = 'MATCH (s1:'+startNodeTag+')'+firstArrow+'[r1:'+relationTag+']'+secondArrow+'(e1:'+endNodeTag+') WHERE e1.'+endNodeKey+'={1} return s1 as '\
               +self.SEARCHVALUEKEY+',r1.'+Mysql2Neo4j.RELATIONWEIGHT+' as '+self.SEARCHWEIGHTKEY+',r1.'+Mysql2Neo4j.RELATIONTID+' as '+self.SEARCHIDSKEY+' order by r1.'+relationOrderKey+' '+seq
         parameters = {"1": endNodeValue[0]}
         # print cql
         # print parameters
         neoDb = Neo4jOpt()
         return neoDb.graph.data(cql, parameters)
     i = 0
     cql = ''
     parameters = {}
     for value in endNodeValue:
         i += 1
         parameters[str(i)] = value
         s = 's' + str(i)
         ssub = 's' + str(i - 1)
         r = 'r' + str(i)
         e = 'e' + str(i)
         match = 'MATCH (' + s + ':' + startNodeTag + ')' + firstArrow + '[' + r + ':' + relationTag + ' ]' + secondArrow + '(' + e + ':' + endNodeTag + ') '
         if (i == 1):
             cql += match
             cql += 'WHERE ' + e + '.' + endNodeKey + '={' + str(
                 i) + '} with ' + s + ',' + r + ' '
         elif (i < len(endNodeValue)):
             cql += match
             cql += 'WHERE ' + e + '.' + endNodeKey + '={' + str(
                 i) + '} and ' + s + '=' + ssub
             rTotal = ''
             flag = False
             for j in range(i):
                 if flag:
                     rTotal += ','
                 else:
                     flag = True
                 rTotal += 'r' + str(j + 1)
             cql += ' with ' + s + ',' + rTotal + ' '
         elif (i == len(endNodeValue)):
             cql += match
             cql += 'WHERE ' + e + '.' + endNodeKey + '={' + str(
                 i) + '} and ' + s + '=' + ssub + ' '
             w = ''
             flag = False
             for j in range(i):
                 if flag:
                     w += '+'
                 else:
                     flag = True
                 w += 'r' + str(j + 1) + '.' + relationOrderKey
             tidReturn = ''
             for j in range(i):
                 tidReturn = ',r' + str(
                     j + 1
                 ) + '.' + Mysql2Neo4j.RELATIONTID + ' as ' + self.SEARCHIDSKEY + str(
                     j + 1) + tidReturn
             cql += 'return ' + s + ' as ' + self.SEARCHVALUEKEY + ',' + w + ' as ' + self.SEARCHWEIGHTKEY + tidReturn + ' order by ' + w + ' ' + seq
     # print cql
     # print parameters
     neoDb = Neo4jOpt()
     return neoDb.graph.data(cql, parameters)
Esempio n. 14
0
 def get_pulse_class_num(self):
     neoDb = Neo4jOpt()
     nodes = neoDb.selectNodeElementsFromDB(self.PULSETAG)
     return len(nodes)
Esempio n. 15
0
 def get_tonguetai_class_num(self):
     neoDb = Neo4jOpt()
     nodes = neoDb.selectNodeElementsFromDB(self.TONGUETAITAG)
     return len(nodes)
Esempio n. 16
0
 def get_syptome_class_num(self):
     neoDb = Neo4jOpt()
     nodes = neoDb.selectNodeElementsFromDB(self.SYMPTOMTAG)
     return len(nodes)
Esempio n. 17
0
 def get_medicine_class_num(self):
     neoDb = Neo4jOpt()
     nodes = neoDb.selectNodeElementsFromDB(self.MEDICINETAG)
     return len(nodes)
Esempio n. 18
0
 def createGraph(self, idTrainList, symptomTrainList, medicineTrainList):
     FileUtil.print_string(u"开始创建图谱...", self.LOGFILE, True)
     neoDb = Neo4jOpt()
     neoDb.graph.data('MATCH (n) DETACH DELETE n')
     for i in range(len(idTrainList)):
         print("读取id:" + str(idTrainList[i]))
         tid = idTrainList[i]
         for s in symptomTrainList[i]:
             symptomNode = neoDb.selectFirstNodeElementsFromDB(
                 self.SYMPTOMTAG, properties={self.NODENAME: s})
             if (symptomNode == None):
                 tids = [tid]
                 weight = 1
                 neoDb.createNode(
                     [self.SYMPTOMTAG], {
                         self.NODENAME: s,
                         self.NODETID: tids,
                         self.NODEWEIGHT: weight
                     })
             else:
                 tids = symptomNode[self.NODETID]
                 tids.append(tid)
                 ntids = list(set(tids))
                 nweight = len(ntids)
                 neoDb.updateKeyInNode(symptomNode, {
                     self.NODETID: ntids,
                     self.NODEWEIGHT: nweight
                 })
         for m in medicineTrainList[i]:
             medicineNode = neoDb.selectFirstNodeElementsFromDB(
                 self.MEDICINETAG, properties={self.NODENAME: m})
             if (medicineNode == None):
                 tids = [tid]
                 weight = 1
                 neoDb.createNode(
                     [self.MEDICINETAG], {
                         self.NODENAME: m,
                         self.NODETID: tids,
                         self.NODEWEIGHT: weight
                     })
             else:
                 tids = medicineNode[self.NODETID]
                 tids.append(tid)
                 ntids = list(set(tids))
                 nweight = len(ntids)
                 neoDb.updateKeyInNode(medicineNode, {
                     self.NODETID: ntids,
                     self.NODEWEIGHT: nweight
                 })
         symptoms = symptomTrainList[i]
         for j in range(len(symptoms)):
             s = symptoms[j]
             symptomNode = neoDb.selectFirstNodeElementsFromDB(
                 self.SYMPTOMTAG, properties={self.NODENAME: s})
             # 症状->中药
             for m in medicineTrainList[i]:
                 medicineNode = neoDb.selectFirstNodeElementsFromDB(
                     self.MEDICINETAG, properties={self.NODENAME: m})
                 s2mrel = neoDb.selectFirstRelationshipsFromDB(
                     symptomNode, self.SYMPTOM2MEDICINETAG, medicineNode)
                 if (s2mrel == None):
                     tids = [tid]
                     weight = 1
                     neoDb.createRelationship(self.SYMPTOM2MEDICINETAG,
                                              symptomNode,
                                              medicineNode,
                                              propertyDic={
                                                  self.RELATIONTID: tids,
                                                  self.RELATIONWEIGHT:
                                                  weight
                                              })
                 else:
                     tids = s2mrel[self.RELATIONTID]
                     tids.append(tid)
                     ntids = list(set(tids))
                     nweight = len(ntids)
                     neoDb.updateKeyInRelationship(s2mrel,
                                                   properties={
                                                       self.RELATIONTID:
                                                       ntids,
                                                       self.RELATIONWEIGHT:
                                                       nweight
                                                   })
             if (j == len(symptoms) - 1):
                 continue
             # 症状-症状
             for k in range(j + 1, len(symptoms)):
                 s1 = symptoms[k]
                 if (s == s1):
                     continue
                 symptomNode1 = neoDb.selectFirstNodeElementsFromDB(
                     self.SYMPTOMTAG, properties={self.NODENAME: s1})
                 s2srel = neoDb.selectFirstRelationshipsFromDB(
                     symptomNode,
                     self.SYMPTOM2SYMPTOMTAG,
                     symptomNode1,
                     bidirectional=True)
                 if (s2srel == None):
                     tids = [tid]
                     weight = 1
                     neoDb.createRelationship(self.SYMPTOM2SYMPTOMTAG,
                                              symptomNode,
                                              symptomNode1,
                                              propertyDic={
                                                  self.RELATIONTID: tids,
                                                  self.RELATIONWEIGHT:
                                                  weight
                                              })
                 else:
                     tids = s2srel[self.RELATIONTID]
                     tids.append(tid)
                     ntids = list(set(tids))
                     nweight = len(ntids)
                     neoDb.updateKeyInRelationship(s2srel,
                                                   properties={
                                                       self.RELATIONTID:
                                                       ntids,
                                                       self.RELATIONWEIGHT:
                                                       nweight
                                                   })
     self.relationFilter()
Esempio n. 19
0
 def store_tonguezhi2medicine(self, filter=False, filterSet=set([])):
     FileUtil.print_string(u"开始存储舌质和中药的关系...", True)
     mysqlDb = MysqlOpt()
     neoDb = Neo4jOpt()
     treamentMysql = mysqlDb.select('treatment',
                                    'id,tongueZhiId,prescriptionId')
     for treamentUnit in treamentMysql:
         tongueZhiId = treamentUnit[1]
         tid = int(treamentUnit[0])
         if (filter == True and tid not in filterSet):
             continue
         priscriptionMysql = mysqlDb.select('prescription', 'name',
                                            'id = ' + str(treamentUnit[2]))
         if (len(priscriptionMysql) > 0):
             medicineIds = priscriptionMysql[0][0].split(",")
         else:
             continue
         # 针对name末尾有逗号的情况进行处理
         lenth = len(medicineIds)
         if (medicineIds[lenth - 1] == ''):
             medicineIds.pop()
         for medicineId in medicineIds:
             medicineNodes = neoDb.selectNodeElementsFromDB(
                 self.MEDICINETAG,
                 condition=[],
                 properties={self.NODEID: int(medicineId)})
             tongueZhiNodes = neoDb.selectNodeElementsFromDB(
                 self.TONGUEZHITAG,
                 condition=[],
                 properties={self.NODEID: int(tongueZhiId)})
             if (len(medicineNodes) > 0 and len(tongueZhiNodes) > 0):
                 medicineNode = medicineNodes[0]
                 tongueZhiNode = tongueZhiNodes[0]
                 # print(medicineNode['name'])
                 # print(tongueZhiNode['name'])
                 # print("输出舌质%s和药物%s的关系:%d"%(tongueZhiNode['name'].encode('utf8'),medicineNode['name'].encode('utf8'),tid))
                 # 如果节点之间已经存在关系了,则权重加1,否则创建关系
                 relations = neoDb.selectRelationshipsFromDB(
                     tongueZhiNode, self.TONGUEZHI2MEDICINETAG,
                     medicineNode)
                 if (len(relations) > 0):
                     # print("更新舌质%s和药物%s的关系" % (tongueZhiNode['name'].encode('utf8'), medicineNode['name'].encode('utf8')))
                     relation = relations[0]
                     tids = relation[self.RELATIONTID]
                     tids.append(tid)
                     ntids = list(set(tids))
                     nweight = len(ntids)
                     neoDb.updateKeyInRelationship(relation,
                                                   properties={
                                                       self.RELATIONTID:
                                                       ntids,
                                                       self.RELATIONWEIGHT:
                                                       nweight
                                                   })
                 else:
                     tids = [tid]
                     weight = 1
                     neoDb.createRelationship(self.TONGUEZHI2MEDICINETAG,
                                              tongueZhiNode,
                                              medicineNode,
                                              propertyDic={
                                                  self.RELATIONTID: tids,
                                                  self.RELATIONWEIGHT:
                                                  weight
                                              })
     mysqlDb.close()
Esempio n. 20
0
 def predict_medicine(self, syptomList):
     neoDb = Neo4jOpt()
     # 生成以给定症状为中心形成的广度子图:中心症状的权值各自传播给子节点后,再把各个子图叠加起来
     symptomeWeightDic = {}
     for s in syptomList:
         initWeight = 1
         symptomNode = neoDb.selectFirstNodeElementsFromDB(
             self.SYMPTOMTAG, properties={self.NODENAME: s})
         if (symptomNode == None):
             continue
         # 如果只有一层
         if (self.BFSLAYER < 2):
             if (symptomeWeightDic.get(s) == None):
                 symptomeWeightDic[s] = initWeight
             else:
                 symptomeWeightDic[s] += initWeight
             continue
         bfsLayerDic = {}
         bfsLayerDic[1] = {s: initWeight}
         symptomVisitDic = {}
         symptomVisitDic[s] = True
         #获取特定层次的广度图
         for currentLayerNum in range(1, self.BFSLAYER):
             nextLayerNum = currentLayerNum + 1
             bfsLayerDic[nextLayerNum] = {}
             # 获取每一层节点的子节点,并赋权重
             for (parentName,
                  parentWeight) in bfsLayerDic[currentLayerNum].items():
                 symptomNode = neoDb.selectFirstNodeElementsFromDB(
                     self.SYMPTOMTAG,
                     properties={self.NODENAME: parentName})
                 rels = neoDb.selectRelationshipsFromDB(
                     symptomNode,
                     self.SYMPTOM2SYMPTOMTAG,
                     bidirectional=True)
                 for rel in rels:
                     childName = rel.start_node()[
                         self.NODENAME] if rel.end_node()[
                             self.NODENAME] == parentName else rel.end_node(
                             )[self.NODENAME]
                     if (symptomVisitDic.get(childName) != None):
                         continue
                     childWeight = round(
                         rel[self.RELATIONWEIGHT] * 1.0 * parentWeight /
                         symptomNode[self.NODEWEIGHT], self.POINTACCURACY)
                     # 考虑到同一层的不同父节点可以赋权值给同一个子节点
                     if (bfsLayerDic[nextLayerNum].get(childName) == None):
                         bfsLayerDic[nextLayerNum][childName] = childWeight
                     else:
                         bfsLayerDic[nextLayerNum][childName] += childWeight
             for nextLayerElementName in bfsLayerDic[nextLayerNum]:
                 symptomVisitDic[nextLayerElementName] = True
         for i in bfsLayerDic:
             for j in bfsLayerDic[i]:
                 if (symptomeWeightDic.get(j) == None):
                     symptomeWeightDic[j] = bfsLayerDic[i][j]
                 else:
                     symptomeWeightDic[j] += bfsLayerDic[i][j]
     for i in symptomeWeightDic:
         print u"症状:" + i + str(symptomeWeightDic[i])
 #   计算每一种和子图症状相连的中药的权值
     medicineWeightDic = {}
     for i in symptomeWeightDic:
         syptomeName = i
         syptomeWeight = symptomeWeightDic[i]
         symptomNode = neoDb.selectFirstNodeElementsFromDB(
             self.SYMPTOMTAG, properties={self.NODENAME: syptomeName})
         rels = neoDb.selectRelationshipsFromDB(symptomNode,
                                                self.SYMPTOM2MEDICINETAG)
         for rel in rels:
             medicineName = rel.end_node()[self.NODENAME].strip()
             medicineWeight = round(
                 rel[self.RELATIONWEIGHT] * syptomeWeight * 1.0 /
                 symptomNode[self.NODEWEIGHT], self.POINTACCURACY)
             if (medicineWeightDic.get(medicineName) == None):
                 medicineWeightDic[medicineName] = medicineWeight
             else:
                 medicineWeightDic[medicineName] += medicineWeight
     # 转成排序好的列表,[0]是中药名,[1]是权值
     medicineWeightSortedList = sorted(medicineWeightDic.iteritems(),
                                       key=lambda d: d[1],
                                       reverse=True)
     topMedicineList = []
     if (len(medicineWeightSortedList) > self.TOPK):
         topMedicineList = [
             medicineWeightSortedList[i] for i in range(self.TOPK)
         ]
     else:
         topMedicineList = [
             medicineWeightSortedList[i]
             for i in range(len(medicineWeightSortedList))
         ]
     for i in topMedicineList:
         print u"中药" + i[0] + str(i[1])
     if (len(topMedicineList) == 0):
         return []
     preMedicineList = self.chooseTopLables(topMedicineList)
     for i in preMedicineList:
         print i
     return preMedicineList