3
y^                 @   s   d dl mZmZmZmZ d dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlZd dlZd dlZd dlmZ ejeZG dd dZdS )    )absolute_importdivisionprint_functionunicode_literalsN)GraphCycleExceptionc               @   s   e Zd ZdZedd ZdS )Topological_sortu  
    Implementation of Topological Sorting - as per described on wikipedia

    # https://en.wikipedia.org/wiki/Topological_sorting

    L ← Empty list that will contain the sorted elements
    S ← Set of all nodes with no incoming edge
    while S is non-empty do
        remove a node n from S
        add n to tail of L
        for each node m with an edge e from n to m do
            remove edge e from the graph
            if m has no other incoming edges then
                insert m into S
    if graph has edges then
        return error (graph has at least one cycle)
    else
        return L (a topologically sorted order)
    c             C   s"  t jdt|   t }t }x&| D ]}t|j dkr$|j| q$W xlt|dkr|jd}|j| t|j }x:|D ]2}|j	| |j
| t|j dkrz|j| qzW qHW x<| D ]4}t|j dkst|j dkrtd|j  qW d}x&|D ]}|j  |j| |d7 }qW |S )NzNodes to topo sort: r   z#Graph has cycles!  offending node:    )loggerdebugstrlistlenget_prev_nodesappendpopget_next_nodesstash_prev_nodestash_next_noder   toStringrestore_stashed_nodesset_topological_order)Z
nodes_listLSnodeZnode_nZ
n_childrenZn_childidx r   T/broad/hptmp/bhaas/trinityrnaseq/Analysis/SuperTranscripts/pylib/Topological_sort.pytopologically_sort*   s0    






 

z#Topological_sort.topologically_sortN)__name__
__module____qualname____doc__staticmethodr   r   r   r   r   r      s   r   )
__future__r   r   r   r   ossysreloggingargparsecollectionsnumpytimeTNoder   	getLoggerr   r	   r   r   r   r   r   <module>   s   
