Модуль NetWorkx - PullRequest
       22

Модуль NetWorkx

0 голосов
/ 12 июля 2019

Я использую модуль NetWorkx, чтобы найти все самые короткие строки между двумя точками графика.как только нет путей между двумя точками, мой сценарий останавливается и не работает для других пар (начальная точка, точка прибытия).

Поэтому я хочу знать, как добавить условие, чтобы примежду двумя точками нет путей, я печатаю следующее сообщение «Между этими двумя точками нет пути» и продолжаю с другими парами

Вот мой код:

import networkx as nx
from collections import defaultdict
dd=defaultdict(set)
P=[]

#File content all couples (starting point, end point) to test
with open("3080_interactions_pour_736.txt","r") as f0:
    for lignes0 in f0:
        lignes0=lignes0.rstrip('\n').split(" ")
        prot1=lignes0[0]
        prot2=lignes0[1]
        couple=prot1,prot2
        P.append(list(couple))
    #print(P)

#File containing all the binary interactions composing my graph
with open("736(int_connues_avec_scores_sup_0).txt","r") as f1:
    for lignes in f1:
        if lignes.startswith('9606'):
            lignes=lignes.rstrip('\n').split(" ")
            proteine1=lignes[2]
            proteine2=lignes[3]
            dd[proteine1].add(proteine2)

#For every couple of my first file, I apply the module of the shortest chains:
for couples in P:
    prot1=couples[0]
    prot2=couples[1]
    Lchaines=([p for p in nx.all_shortest_paths(dd, source=prot1, target=prot2, weight=None)])
    print("")
    print("The first protein in the chain is", prot1)
    print("The last protein in the chain is", prot2)
    print("")
    print("Minimal size chain(s):")
    print("")

    for chaines in Lchaines:

        #To have chains of size 11 maximum
        if len(chaines) <= 11:

            print(' '.join(chaines))
        else :

            print('ERROR - The minimum size of the chains exceeds the limit')
            break
    print("")
    print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")

Вот ошибкаполученное сообщение:

Traceback (most recent call last):

File "C:\Users\loisv\Desktop\pluscourtchemin.py", line 26, in <module>

Lchaines=([p for p in nx.all_shortest_paths(dd, source=prot1, target=prot2, weight=None)])

File "C:\Users\loisv\Desktop\pluscourtchemin.py", line 26, in <listcomp>

Lchaines=([p for p in nx.all_shortest_paths(dd, source=prot1, target=prot2, weight=None)])

File "C:\Users\loisv\AppData\Local\Programs\Python\Python37-32\lib\site-packages\networkx\algorithms\shortest_paths\generic.py", line 481, in all_shortest_paths

'from Source {}'.format(target, source))

networkx.exception.NetworkXNoPath: Target IKBKE cannot be reachedfrom Source LCK

Спасибо за помощь:)

1 Ответ

0 голосов
/ 12 июля 2019

Я не могу проверить это, но если вы получите исключение, вы должны использовать try/except

И вам следует присвоить значение Lchaines (т. Е. Пустой список), потому что исключение может не создать эту переменную иу вас будут ошибки в других местах.

try:
    Lchaines = [p for p in nx.all_shortest_paths(dd, source=prot1, target=prot2, weight=None)]
except networkx.exception.NetworkXNoPath:
    print("No way between these two points")
    Lchaines = []

Или вы можете использовать continue, чтобы пропустить остаток кода в этом цикле

try:
    Lchaines = [p for p in nx.all_shortest_paths(dd, source=prot1, target=prot2, weight=None)]
except networkx.exception.NetworkXNoPath:
    print("No way between these two points")
    continue
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...