Example #1
0
def main():
    # set graphs directory
    graphPath = str(cur+'/NetworkFiles/')
    
    # create a new window
    window = MyDotWindow()    
    window.connect('destroy',gtk.main_quit)
    window.show()
    
    #create the main graph instance of a graph class
    mainGraph = Graph()
    
    #START THE MAIN LOOP
    menuInput = ""
    subMenuInput = ''
    
    # create vascularNetwork instance
    vascularNetwork = VascularNetwork()
    filename = None
    k = None
    while menuInput != "q":
        menuInput = ""
        print ""
        print '====================================='
        print '#    VascularNetworkCreator_v2.3    #'
        print '====================================='
        print " [a] - add vessel to network"
        print " [d] - delete vessel in network"
        print " [n] - new network"
        print " [b] - set boundary conditions"
        print " [f] - set global fluid properties"
        print " [l] - load network"
        print " [s] - save network"
        print " [u] - update XML form CSV file(s)"
        print " [g] - print network graph"
        print " [p] - print network informations"
        print " [q] - quit"
        print ""
        print '  current network: ', filename
        while  menuInput not in ("l","b","q","a","s","g","f","d","u",'n','p'):
            menuInput = raw_input("what to do? ")
        
        if menuInput == "a": 
            print "Add new vessel"
            
            existing = False
            vesselId = raw_input(" enter the vessel id:  ")
            while True:
                try:
                    vesselId = int(vesselId)
                    if vesselId not in vascularNetwork.vessels:
                        break
                    else:
                        existing = True
                except ValueError:
                    print "TYPE-ERROR: vessel id must be type(int) not type(string)"
                    vesselId = raw_input(" enter non existing id: ")
                if existing == True:
                    print " the vessel id exists already enter a new one"
                    vesselId = raw_input(" enter non existing id: ")
                    existing = False
            
            
            if vascularNetwork.vessels != {}:
                                    
                existing = False
                mother = raw_input(" enter existing mother id:  ")
                while True:
                    try:
                        mother = int(mother)
                        if mother in vascularNetwork.vessels.keys() and vascularNetwork.vessels[mother].rightDaughter == None:
                            break
                        else:
                            existing = True
                    except ValueError:
                        print "TYPE-ERROR: mother id must be type(int) not type(string)"
                        mother = raw_input(" enter existing mother id:  ")
                    if existing == True:
                        if mother not in vascularNetwork.vessels: print " there exists no vessel with this id"
                        else: print "   only bifurcations possible!"
                        mother = raw_input(" enter existing mother id:  ")
                        existing = False
                    
                if vascularNetwork.vessels[mother].leftDaughter == None: vascularNetwork.vessels[mother].leftDaughter = vesselId
                else: vascularNetwork.vessels[mother].rightDaughter = vesselId
                                
            vascularNetwork.addVessel(vesselId)
            print " define vessel compliance!"
            
            
            inputType = '0'
            print "     available compliance types:"
            print ""
            # get all defined boundaryConditions from constants-dict save as bcTypes
            complianceTypes = vesselComplianceElements.keys()
            compTypes = ['default (Hayashi)']
            for compType in complianceTypes: 
                compTypes.append(compType)
            # show all compliance types in the compTypes
            index = 0
            for key in compTypes:
                print "       [",str(index).rjust(2),"]    ",key
                index = index+1
            # get user input and check if it was correct to define the bcType 
            existing = False
            inputType = raw_input ("      choose type ")
            while True:
                # check if right input
                try:
                    inputType = int(inputType)
                    if inputType in np.linspace(0,len(compTypes)-1,len(compTypes)):
                        break
                    else:
                        existing = True
                # if not int but string
                except ValueError:
                    print "      TYPE-ERROR: vessel id must be type(int) not type(string)"
                    inputType = (raw_input ("      choose type "))
                # if int but to low or high
                if existing == True:
                    print "       the type does not exist"
                    inputType = (raw_input ("      choose type "))
                    existing = False
            
            compType = compTypes[int(inputType)] 
            
            if compType != 'default (Hayashi)':
                vesselData = {'complianceType':compType}
                vesselComplianceElements[compType]
                                    
                print ""
                print "      set values for the Compliance: ", compType
                question = True
                for arg in vesselComplianceElements[compType]:
                    if arg != 'complianceType':
                        currValue = raw_input (str("            set value for "+str(arg)+' '))
                        test = True
                        try: float(currValue)
                        except:
                            print '            VALUE or TYPE ERROR, set to None'
                            test = False
                        if test == True: vesselData[arg] = (float(currValue))
                        else: vesselData[arg] = None
                vascularNetwork.updateNetwork({'vesselData':  { vesselId : vesselData}})
            
            mainGraph.update_graph(vascularNetwork, window)
                    
        if menuInput == "d":
            print "Delete a vessel and all its daugthers"
            if vascularNetwork.vessels.keys() != []:
                
                existing = False
                vesselId = raw_input(" enter existing vessel id: ")
                while True:
                    try:
                        vesselId = int(vesselId)
                        if vesselId in vascularNetwork.vessels:
                            break
                        else: 
                            existing = True
                    except ValueError:
                        print "TYPE-ERROR: vessel id must be type(int) not type(string)"
                        vesselId = raw_input(" enter existing vessel id: ")
                    if existing == True:
                        print " the vessel does not exist"
                        vesselId = raw_input(" enter existing vessel id: ")
                        existing = False
                
                #travers the tree starting with the vessel and collect all ids
                toDelete = findAllDaughters(vascularNetwork,vesselId)
                
                toDelete.append(vesselId)
                
                for vesselToDelete in toDelete:
                    vascularNetwork.deleteVessel(vesselToDelete)
                
                # empty the graph to redraw it
                if vascularNetwork.vessels.keys() == []:
                    mainGraph.update_graph(None, window)
                    vascularNetwork = VascularNetwork()
                else:
                    mainGraph.update_graph(vascularNetwork, window)
                
            else:
                print " there are no vessels to delete"
                
        elif menuInput == "n":
            print "new network"
            question = raw_input(" are u sure to delete all current data? [y] - yes: ")
            if question == 'y':
                # delete vascularNetwork
                del vascularNetwork
                # create vascularNetwork instance
                mainGraph.update_graph(None, window)
                vascularNetwork = VascularNetwork()
                    
        elif menuInput == "p":
            vascularNetwork.showVessels()
            vascularNetwork.showNetwork()
                        
        elif menuInput == "g":
            print mainGraph.getGraph()
            
        elif menuInput == "b":
            subMenuInput = ''
            
            while  subMenuInput not in ['1','2','3','4','5','b']:
                if vascularNetwork.getVariableValue('vessels') == {}:
                    print " there are no vessels defined and thus no boundarys available";break
                else:
                    # evaluate boundarys in Network
                    boundarys = []
                    notDefinedBoundarys = []
                    
                    boundarys.extend(vascularNetwork.boundaryVessels)
                    if vascularNetwork.root != None and vascularNetwork.root not in boundarys: 
                        boundarys.append(vascularNetwork.root)
                        
                    boundarysSaved = vascularNetwork.boundaryConditions.keys()
                    
                    # update saved boundary conditions
                    for boundarysCurrent in boundarys:
                        if boundarysCurrent not in boundarysSaved:
                            print " boundary added to vascularNetwork"
                            vascularNetwork.boundaryConditions[boundarysCurrent] = []
                            boundarysSaved.append(boundarysCurrent)
                            
                        if vascularNetwork.boundaryConditions[boundarysCurrent] == []:
                            notDefinedBoundarys.append(boundarysCurrent)
                        
                    nonBoundarys = list(set(boundarys).symmetric_difference(set(boundarysSaved)))
                    for nonBoundary in nonBoundarys:
                        print " boundary removed from vacularNetwork"
                        del(vascularNetwork.boundaryConditions[nonBoundary])
                        if nonBoundary in notDefinedBoundarys: notDefinedBoundarys.remove(nonBoundary)
                        
                    vascularNetwork.evaluateConnections()
                    print ""
                    print "    sub menu: boundary conditions"
                    print ""
                    print "     [1] - show  boundary conditions"
                    print "     [2] - add   boundary condition "
                    print "     [3] - del   boundary condition "
                    print "     [4] - load  boundary conditions from CSV"
                    print "     [5] - write boundary conditions to CSV"
                    print "     [b] - back to the main menu"
                    print ""     
                    subMenuInput = raw_input("     what to do? ") 
                    
                    if subMenuInput == '1':
                        print "     boundary conditions"
                        pprint.pprint(vascularNetwork.boundaryConditions)
                        subMenuInput = ''
                        
                    elif subMenuInput == '2' and vascularNetwork.root != []:
                        
                        print "     add   boundary condition"
                        print ""
                        
                        definedBoundarys = list(set(notDefinedBoundarys).symmetric_difference(set(vascularNetwork.boundaryConditions.keys())))
                        print "     vessels with defined boundary condition:"
                        print "       ",'  '.join(str(i) for i in definedBoundarys)
                        
                        print "     vessels with undefined boundary condition:"
                        print "       ",'  '.join(str(i) for i in notDefinedBoundarys)
                        print ""
                                            
                        existing = False
                        vesselId = raw_input(" enter existing vessel id: ")
                        while True:
                            try:
                                vesselId = int(vesselId)
                                if vesselId in vascularNetwork.vessels:
                                    break
                                else:
                                    existing = True
                            except ValueError:
                                print " TYPE-ERROR: vessel id must be type(int) not type(string)"
                                vesselId = raw_input(" enter existing vessel id: ")
                            if existing == True:
                                print " the vessel does not exist"
                                vesselId = raw_input(" enter existing vessel id: ")
                                existing = False
                                                
                        inputType = '0'
                        print "     add boundary condition type:"
                        print ""
                        # get all defined boundaryConditions from constants-dict save as bcTypes
                        bcTypesAll = bcTagsClassReferences.keys()
                        bcTypes = []
                        for bcType in bcTypesAll: 
                            if "_" is not bcType[0]:
                                bcTypes.append(bcType)
                        bcTypes.sort()
                        # show all boundaryConditions in the bcTypes
                        index = 0
                        for key in bcTypes:
                            print "       [",str(index).rjust(2),"]    ",key
                            index = index+1
                        # get user input and check if it was correct to define the bcType 
                        existing = False
                        inputType = raw_input ("      choose type ")
                        while True:
                            # check if right input
                            try:
                                inputType = int(inputType)
                                if inputType in np.linspace(0,len(bcTypes)-1,len(bcTypes)):
                                    break
                                else:
                                    existing = True
                            # if not int but string
                            except ValueError:
                                print "      TYPE-ERROR: vessel id must be type(int) not type(string)"
                                inputType = (raw_input ("      choose type "))
                            # if int but to low or high
                            if existing == True:
                                print "       the type does not exist"
                                inputType = (raw_input ("      choose type "))
                                existing = False
                        
                        bcType = bcTypes[int(inputType)] 
                        
                        boundaryInstance = eval(bcTagsClassReferences[bcType])()
                        boundaryDataDict = {}
                        boundaryDataDict['name']= bcType
                        
                        print ""
                        print "      set values for the BC condition: ", bcType
                        print "          enter 'b' for the first value to skip this procedure"
                        question = True
                        for arg in bcTags[bcType]:
                            if question == True: 
                                currValue = raw_input (str("            set value for "+str(arg)+' '))
                                if currValue == 'b': question=False
                                test = True
                                try: float(currValue)
                                except:
                                    print '            VALUE or TYPE ERROR, set to None'
                                    test = False
                                if test == True: boundaryDataDict[arg] = (float(currValue))
                                else: boundaryDataDict[arg] = None
                            else: boundaryDataDict[arg] = None
                        if len(vascularNetwork.boundaryConditions.keys()) == 1:
                            print "      set position of the BC condition"
                            position = '2'
                            while position not in ['1','0']:
                                position = raw_input ("          enter '0' for the start or '1' for the end of the vessel ")
                            if position == '1':
                                #bcType = ''.join(['_',bcType])
                                boundaryDataDict['name']= ''.join(['_',bcType])
                        
                        print bcType,boundaryDataDict
                        
                        boundaryInstances = []
                        boundaryInstance.update(boundaryDataDict)
                        boundaryInstances.append(boundaryInstance)
                        
                        if vesselId not in vascularNetwork.boundaryConditions.keys():
                            vascularNetwork.boundaryConditions[vesselId] = boundaryInstances
                        else:
                            vascularNetwork.boundaryConditions[vesselId].extend(boundaryInstances)
                        
                        #if vascularNetwork.getVariableValue('root') != None:
                        mainGraph.update_graph(vascularNetwork, window)
                        subMenuInput = ''
                            
                    
                    elif subMenuInput == '3' and vascularNetwork.root != []:
                        print "     delete boundary condition"
                        print ""
                        pprint.pprint(vascularNetwork.boundaryConditions)
                        
                        vesselId = -1
                        while vesselId not in vascularNetwork.boundaryConditions.keys():
                            vesselId = int(raw_input ("      choose vessel id "))
                        
                        bcs = vascularNetwork.boundaryConditions[vesselId]
                        if bcs != []:                 
                            print ""
                            index = 0
                            for bc in bcs:
                                print "       [",str(index).rjust(2),"]    ",bc.name
                                index = index+1
                            print ""
                            inType = '0'
                            while inType not in np.linspace(0,len(bcs)-1,len(bcs)):
                                inType = int(raw_input ("      choose condition to delete "))
                             
                            print ""
                            print "     boundary condition ",bcs[inType]," removed!"
                            print ""
                            vascularNetwork.boundaryConditions[vesselId].remove(bcs[inType])
                            
                            mainGraph.update_graph(vascularNetwork, window)
                        else:
                            print "     nothing to delete!"
                        subMenuInput = ''
                    
                    elif subMenuInput == '4' and vascularNetwork.root != []:
                        print "     load  boundary conditions from CSV"
                        print ""
                        filename = enterFilename(filename,'')
                        boundaryConditions,boundaryConditionPolyChaos = readBCFromCSV(filename = ''.join([filename,'BC','.csv']))
                        vascularNetwork.update({'boundaryConditions':boundaryConditions,
                                                'boundaryConditionPolyChaos':boundaryConditionPolyChaos})
                        
                        mainGraph.update_graph(vascularNetwork, window)
                                                                
                    elif subMenuInput == '5' and vascularNetwork.root != []:
                        print "     write boundary conditions to CSV"
                        print ""
                        filename = enterFilename(filename,'')
                        boundaryConditions = vascularNetwork.getVariableValue('boundaryConditions')
                        boundaryConditionPolyChaos = deepcopy(vascularNetwork.getVariableValue('boundaryConditionPolyChaos'))
                        writeBCToCSV(boundaryConditions,boundaryConditionPolyChaos,filename = ''.join([filename,'BC','.csv']))         
                        
                    elif subMenuInput == 'b':
                        break
        
        elif menuInput == "f":
            
            subMenuInput = ''
            while  subMenuInput not in ["1","2","b"]:
                print ""
                print "    sub menu: set global fluid properties"
                print ""
                print "     [1] - set all"
                print "     [2] - set individual"
                print "     [b] - back to the main menu"
                print ""
                print "    current fluid properties:"
                for key,value in vascularNetwork.globalFluid.iteritems():
                    print "     {0:20}     {1:10}  {2:10}".format(key,value,variableUnits[key])
                print ""
                subMenuInput = raw_input("    what to do? ")
                
                if subMenuInput == '1':
                    print "     set all fluid properties"
                    
                    for key in vascularNetwork.globalFluid.keys():
                        inputType = "1"
                        typeFalse = False
                        while typeFalse == False:
                            try: 
                                inputType = raw_input("      type value for property: {} with unit {} : ".format(key,variableUnits[key]))
                                inputType = float(inputType)
                                typeFalse = True
                                vascularNetwork.globalFluid[key] = inputType
                            except: pass
                    subMenuInput = ''
                    
                elif subMenuInput == '2':
                    print "     set individual fluid property:"
                    i = 0
                    properties = vascularNetwork.globalFluid.keys()
                    for property_i in properties:
                        print "          [",i,'] - ',property_i
                        i = 1+i
                    inputType = 0
                    while inputType not in [str(i) for i in range(0,len(properties))]:
                        inputType = raw_input("      choose property to set ")
                    
                    inputProperty = ""   
                    inputFalse = False
                    while inputFalse == False:
                        try: 
                            inputProperty = raw_input("      type value for property: {} with unit {} : ".format(properties[int(inputType)],variableUnits[properties[int(inputType)]]))
                            inputProperty = float(inputProperty)
                            vascularNetwork.globalFluid[properties[int(inputType)]] = inputProperty
                            inputFalse = True
                        except: pass
                    subMenuInput = ''
                     
                elif subMenuInput == 'b':
                    break
                
            
        elif menuInput == "l":
            try:
                FILE = open('.recentFilenames.pickle',"rb")
                # store pickle
                recentFilenames = cPickle.load(FILE)
                FILE.close()
            except:
                recentFilenames = []
                
            subMenuInput = ''
            print ""
            print "    sub menu: load data"
            print ""
            print "     [1] - load network from XML"
            print "     [2] - load vessel data from CSV"
            print "     [3] - load vessel data and boundary conditions from CSV"
            print "     [4] - load network from SolutionData"
            print "     [b] - back to the main menu"
            print ""
            while  subMenuInput not in ["1","2","3","b"]:
                subMenuInput = raw_input("what to do? ")
            
                print ""
                print "         resent used networks"
                i = 1
                for name in recentFilenames:
                    print "          [",i,'] - ',name
                    i = 1+i
                print ""
                if subMenuInput == '1':
                    print "     load from XML"
                    
                    filename = enterFilename(filename,'.xml',recentFilenames = recentFilenames)
                    if filename == None:break
                    # delete the old network
                    del vascularNetwork
                    #load the new network
                    vascularNetwork = loadNetworkFromXML(filename= filename)
                    if vascularNetwork == None:
                        mainGraph.update_graph(None, window)
                        vascularNetwork = VascularNetwork()
                        filename = None
                        break
                    mainGraph.update_graph(vascularNetwork, window)
                    filename, value = filename.split(".",1)
                    break
                
                elif subMenuInput == '2':
                    print "     load vessel data from CSV - non existing vessels are added automatically"
                    print ""
                    filename = enterFilename(filename,'.csv',recentFilenames = recentFilenames)
                    if filename == None:break
                    vascularNetwork.updateNetwork(readVesselDataFromCSV(filename=filename))
                    
                    mainGraph.update_graph(vascularNetwork, window)
                    filename, value = filename.split(".",1)
                    break
                
                elif subMenuInput == '3':
                    print "     load vessel data and boundary conditions from CSV"
                    filename = enterFilename(filename,'.csv',recentFilenames = recentFilenames)
                    if filename == None:break
                    vascularNetwork.updateNetwork(readVesselDataFromCSV(filename=filename))
                    mainGraph.update_graph(vascularNetwork, window)
                    
                    
                    filename, value = filename.split(".",1)
                    boundaryConditions,boundaryConditionPolyChaos = readBCFromCSV(filename = ''.join([filename,'BC','.csv']))
                    vascularNetwork.update({'boundaryConditions':boundaryConditions,
                                            'boundaryConditionPolyChaos':boundaryConditionPolyChaos})
                    
                    mainGraph.update_graph(vascularNetwork, window)
                    break
                
                elif subMenuInput == '4':
                    print "     load network from SolutionData"
                    try:
                        networkName,dataSetNumber = chooseSolutionDataCase()
                        vascularNetwork,solData,Description = loadSolutionDataFile(networkName,[dataSetNumber])
                        mainGraph.update_graph(vascularNetwork, window)
                        
                        filename, value = filename.split(".",1)
                    except: " ERROR occured could not open requested network, maybe the class description is out dated"
                    break
                
                elif subMenuInput == 'b':
                    break
            
            if filename != None:    
                if filename not in recentFilenames: recentFilenames.insert(0,filename)
                else: 
                    recentFilenames.remove(filename)
                    recentFilenames.insert(0,filename)
                if len(recentFilenames) > 9: recentFilenames.pop(-1)
                            
                FILE = open('.recentFilenames.pickle',"w")
                # store pickle
                cPickle.dump(recentFilenames, FILE, protocol=2)
                FILE.close()
            
        elif menuInput == "s":
            subMenuInput = ''
            print ""
            print "    sub menu: save data"
            print ""
            print "     [1] - write to XML"
            print "     [2] - write vessel data to CSV"
            print "     [3] - write vessel data and boundary conditions to CSV"
            print "     [4] - write graph to .png and .dot files"
            print "     [b] - back to the main menu"
            print ""
            while subMenuInput not in ["1","2","3","b"]:
                subMenuInput = raw_input("what to do? ")
                     
                if subMenuInput == '1':
                    print "     write to XML"
                    filename = enterFilename(filename,'.xml')
                    if filename == None:break
                    writeNetworkToXML(vascularNetwork,filename = filename)
                    filename, value = filename.split(".",1)
                    break
                    
                elif subMenuInput == '2':
                    print "     write vessel data to CSV"
                    filename = enterFilename(filename,'.csv') 
                    if filename == None:break
                    writeVesselDataToCSV(vessels = vascularNetwork.vessels, filename = filename)
                    filename, value = filename.split(".",1)
                    break
                
                elif subMenuInput == '3':
                    print "     write vessel data and boundary conditions to CSV"
                    filename = enterFilename(filename,'.csv') 
                    if filename == None:break
                    writeVesselDataToCSV(vessels = vascularNetwork.vessels, filename = filename)
                    filename, value = filename.split(".",1)
                    boundaryConditions = vascularNetwork.getVariableValue('boundaryConditions')
                    boundaryConditionPolyChaos = deepcopy(vascularNetwork.getVariableValue('boundaryConditionPolyChaos'))
                    writeBCToCSV(boundaryConditions,boundaryConditionPolyChaos,filename = ''.join([filename,'BC','.csv']))  
                    break
                
                elif subMenuInput == '4':
                    print "     write graph to .png and .dot files"
                    pictureName = str(raw_input("     enter pictureName (only!):"))
                    if pictureName == "":
                        pictureName = 'pydotTest'
                    mainGraph.graph.write(graphPath+filename+'/'+pictureName+'.dot')
                    mainGraph.graph.write_png(graphPath+filename+'/'+pictureName+'.png')
                    break
                    
                if subMenuInput == 'b':
                    break
        
        elif menuInput == "u":
            subMenuInput = ''
            print ""
            print "    sub menu: update XML from CSV"
            print ""
            print "     load from XML"
            
            filename = enterFilename(filename,'.xml')
            if filename == None:break
            # delete the old network
            del vascularNetwork
            #load the new network
            vascularNetwork = loadNetworkFromXML(filename= filename)
            if vascularNetwork == None:
                vascularNetwork = VascularNetwork()
                break
            
            mainGraph.update_graph(vascularNetwork, window)
            
            filename, value = filename.split(".",1)
            
            print "     load vessel data from CSV - non existing vessels are added automatically"
            filenameCSV = ''.join([filename,'.csv'])
            vascularNetwork.updateNetwork(readVesselDataFromCSV(filename=filenameCSV))
            print "     load boundaryData from csv as well? press [u]" 
            subMenuInput = raw_input("yes [u]? ")
            if subMenuInput == 'u':
                boundaryConditions,boundaryConditionPolyChaos = readBCFromCSV(filename = ''.join([filename,'BC','.csv']))
                vascularNetwork.update({'boundaryConditions':boundaryConditions,
                                        'boundaryConditionPolyChaos':boundaryConditionPolyChaos})          
            
            try: mainGraph.update_graph(vascularNetwork, window)
            except:mainGraph.update_graph(None, window)
            
            print "     write to XML"
            filenameXML = ''.join([filename,'.xml'])
            writeNetworkToXML(vascularNetwork,filename = filenameXML)
def loadNetworkFromXML(filename = None, update = None, networkPath = str(cur+"/../NetworkFiles/")):
    '''
    Function laods network from XML-file
    
    version of XML files supported: 4.0
    '''
    currentVersions = ['4.0']
    
    # read from file
    if filename == None:
        print 'ERROR: moduleXML.loadNetworkFromXML() : load XML - no filename passed'
        return None
    
    if '.xml' not in filename:
        filename = ''.join([filename,'.xml'])  
      
    networkDirectory = filename.split('.')[0]
    if not os.path.exists(str(networkPath+networkDirectory)):
        print 'ERROR: moduleXML.loadNetworkFromXML(): directory and file does not exists'
        return None
    
    # create vascularNetwork instance
    vascularNetwork = VascularNetwork()
    # set name
    vascularNetwork.name = (filename.split('.'))[0]
    
    try:
        parser = etree.XMLParser(encoding='iso-8859-1')
        tree = etree.parse(''.join([networkPath,networkDirectory,'/',filename]), parser)
    except (etree.ParseError, ImportError) as e:
        if isinstance(e, etree.ParseError):
            print " ERROR moduleXML.loadNetworkFromXML() on line {} {}: ".format(e.position[0], e)
            exit()
      
    # create root
    root = tree.getroot()
    xmlFileVersion = root.attrib['version']
    if xmlFileVersion not in currentVersions:
        print "ERROR moduleXML.loadNetworkFromXML(): XML file is outdated file-version {} " \
        "current supported version {}, could not parse file! system exit".format(root.attrib['version'],currentVersions); exit()
    
    for xmlElementName in xmlElements:
        for xmlElement in root.findall(''.join([".//",xmlElementName])):
                      
            if xmlElementName == 'boundaryConditions':
                # loop through all boundaryCondition
                for boundaryConditionElement in xmlElement.findall(''.join(['.//','boundaryCondition'])):
                    try: vesselId = int(boundaryConditionElement.attrib['vesselId'])
                    except: loadingErrorMessageVariableError('vesselId', 'one boundaryCondition', '', variablesDict['vesselId'])
                       
                    boundaryInstances = []
                    boundaryIntervals = []
                    # loop through possible communicator class types
                    for boundaryType in xmlElementsReference[xmlElementName]:
                        # find all bcs of this type
                        for bcElements in boundaryConditionElement.findall(''.join(['.//',boundaryType])):
                            boundaryInstance = eval(bcTagsClassReferences[boundaryType])()
                            boundaryDataDict = {}
                            boundaryDataDict['name'] = boundaryType
                            boundaryIntervalDataDict = {}
                            # loop through all variables of this type, convert and save values of these
                            for variable in xmlElementsReference[xmlElementName][boundaryType]: 
                                # find normal variables
                                try: element = bcElements.findall(''.join(['.//',variable]))[0]
                                except: loadingErrorMessageVariableError(variable, 'boundaryCondition', boundaryType, variablesDict[variable])
                                # get variable value                        
                                try: variableValueStr = element.text
                                except: loadingErrorMessageValueError(variable, 'boundaryCondition', boundaryType, variablesDict[variable])
                                # get unit
                                try: variableUnit = element.attrib['unit']
                                except: variableUnit = None 
                                # save converted XML-value
                                boundaryDataDict[variable] = loadVariablesConversion(variable, variableValueStr, variableUnit)
                                # find polynomial chaos variable
                                try:                                                       
                                    # find polychaos variables
                                    element = bcElements.findall(''.join(['.//',variable,'-polyChaos']))[0]
                                    # get variable value                        
                                    try: variableValueStr = element.text
                                    except: loadingErrorMessageValueError(variable, 'boundaryCondition', boundaryType, variablesDict[variable])
                                    # get unit
                                    try: variableUnit = element.attrib['unit']
                                    except: variableUnit = None 
                                    # save converted XML-value                      
                                    boundaryIntervalDataDict[variable] = loadVariablesConversion(variable, variableValueStr, variableUnit, polychaos = True)
                                    boundaryIntervalDataDict['name'] = boundaryType  
                                except: pass
                                # adjust path to boundary condition file
                                if variable == 'filePathName':
                                    path = ''.join([networkDirectory,'/'])
                                    if path not in variableValueStr:  variableValueStr = variableValueStr.join([path,''])
                                    boundaryDataDict['filePathName'] = variableValueStr
                                    
                            boundaryInstance.update(boundaryDataDict)
                            boundaryInstances.append(boundaryInstance)             
                            if boundaryIntervalDataDict != {}:
                                boundaryIntervals.append(boundaryIntervalDataDict)
                                
                    # apply read data to vascularNetwork
                    if vesselId not in vascularNetwork.boundaryConditions.keys():
                        vascularNetwork.boundaryConditions[vesselId] = boundaryInstances
                    else:
                        vascularNetwork.boundaryConditions[vesselId].extend(boundaryInstances)
                    if boundaryIntervals != []: 
                        vascularNetwork.boundaryConditionPolyChaos[vesselId] = boundaryIntervals
                        
            elif xmlElementName == 'vessels':
                for vesselXMLnode in xmlElement.findall(''.join(['.//','vessel'])):
                    vesselData = {}
                    vesselPolychaosData = {}
                    # load vessel attributes
                    for attribute in vesselAttributes:
                        try: vesselData[attribute] = loadVariablesConversion(attribute, vesselXMLnode.attrib[attribute], '')
                        except: 
                            try:    loadingErrorMessageVariableError(attribute, 'vessel', vesselData['Id'], variablesDict[attribute])
                            except: loadingErrorMessageVariableError(attribute, 'one vessel', '', variablesDict[attribute])
                        
                        
                    for vesselElement in xmlElementsReference[xmlElementName]: 
                        # check if compliance and adjust variables
                        if vesselElement == 'compliance':
                            try: complianceTypeElement = vesselXMLnode.findall(''.join(['.//','complianceType']))[0]
                            except: loadingErrorMessageVariableError('complianceType', 'vessel', vesselData['Id'], variablesDict['complianceType'])
                            complianceType = loadVariablesConversion('complianceType', complianceTypeElement.text, '')
                            variables = vesselElementReference[vesselElement][complianceType]
                        else:
                            variables = vesselElementReference[vesselElement]
                        # load variables
                        for variable in variables:
                            try: element = vesselXMLnode.findall(''.join(['.//',variable]))[0]
                            except: loadingErrorMessageVariableError(variable, 'vessel', vesselData['Id'], variablesDict[variable])
                            # get variable value                        
                            try: variableValueStr = element.text
                            except: loadingErrorMessageValueError(variable, 'vessel', vesselData['Id'], variablesDict[variable])
                            # get unit 
                            try: variableUnit = element.attrib['unit']
                            except: variableUnit = None 
                            # save converted XML-value
                            vesselData[variable] = loadVariablesConversion(variable, variableValueStr, variableUnit)
                            # find polynomial chaos variable
                            try:                        
                                # find polychaos variables
                                element = vesselXMLnode.findall(''.join(['.//',variable,'-polyChaos']))[0]
                                # get variable value                        
                                try: variableValueStr = element.text
                                except: loadingErrorMessageValueError(variable, 'vessel', vesselData['Id'], variablesDict[variable])
                                # get unit
                                try: variableUnit = element.attrib['unit']
                                except: variableUnit = None 
                                # save converted XML-value                      
                                vesselPolychaosData[variable] = loadVariablesConversion(variable, variableValueStr, variableUnit, polychaos = True)
                            except: pass
                        vesselData['polyChaos'] = vesselPolychaosData
                    vascularNetwork.updateNetwork({'vesselData':{vesselData['Id']:vesselData}})
            
            elif xmlElementName == 'communicators':
                # loop through possible communicator class types
                for comunicatorType in xmlElementsReference[xmlElementName]:
                    # find all communicator of this type
                    for comElements in xmlElement.findall(''.join(['.//',comunicatorType])):
                        # loop through all variables of this type, convert and save values of these
                        communicatorData = {}
                        for variable in xmlElementsReference[xmlElementName][comunicatorType]: 
                            try: element = comElements.findall(''.join(['.//',variable]))[0]
                            except: loadingErrorMessageVariableError(variable, 'communicator', comunicatorType, variablesDict[variable])
                            # get variable value                        
                            try: variableValueStr = element.text
                            except: loadingErrorMessageValueError(variable, 'communicator', comunicatorType, variablesDict[variable])
                            # get unit
                            try: variableUnit = element.attrib['unit']
                            except: variableUnit = None 
                            communicatorData[variable] = loadVariablesConversion(variable, variableValueStr, variableUnit)
                            if variable == 'comId': comId = communicatorData[variable]
                        vascularNetwork.updateNetwork({'communicators':{comId:communicatorData}})
            
            elif xmlElementName == 'globalFluid':
                    
                globalFluidData = {}
                globalFluidPolychaosData = {}
                
                for variable in xmlElementsReference[xmlElementName]: 
                    # find normal variables
                    try: element = xmlElement.findall(''.join(['.//',variable]))[0]
                    except: loadingErrorMessageVariableError(variable, 'global fluid', '',  variablesDict[variable])
                    # get variable value                        
                    try: variableValueStr = element.text
                    except: loadingErrorMessageValueError(variable, 'global fluid', '',  variablesDict[variable])
                    # get unit
                    try: variableUnit = element.attrib['unit']
                    except: variableUnit = None 
                    # save converted XML-value
                    globalFluidData[variable] = loadVariablesConversion(variable, variableValueStr, variableUnit) 
                    
                    # find polynomial chaos variable
                    try:                        
                        # find polychaos variables
                        element = xmlElement.findall(''.join(['.//',variable,'-polyChaos']))[0]
                        # get variable value                        
                        try: variableValueStr = element.text
                        except: loadingErrorMessageValueError(variable, 'global fluid', '', variablesDict[variable])
                        # get unit
                        try: variableUnit = element.attrib['unit']
                        except: variableUnit = None 
                        # save converted XML-value                      
                        globalFluidPolychaosData[variable] = loadVariablesConversion(variable, variableValueStr, variableUnit, polychaos = True)
                    except: pass
                vascularNetwork.updateNetwork({'globalFluid':globalFluidData,'globalFluidPolyChaos':globalFluidPolychaosData})
                    
            elif xmlElementName in vascularNetworkElements: # vascularNetwork
                vascularNetworkData = {}
                for variable in xmlElementsReference[xmlElementName]: 
                    try: element = xmlElement.findall(''.join(['.//',variable]))[0]
                    except: loadingErrorMessageVariableError(variable, xmlElementName, '', variablesDict[variable])
                    # get variable value                        
                    try: variableValueStr = element.text
                    except: loadingErrorMessageValueError(variable, xmlElementName, '', variablesDict[variable])
                    # get 
                    try: variableUnit = element.attrib['unit']
                    except: variableUnit = None 
                    # save converted XML-value
                    vascularNetworkData[variable] = loadVariablesConversion(variable, variableValueStr, variableUnit)
                vascularNetwork.update(vascularNetworkData)
        
    return vascularNetwork
def main():
    # set graphs directory
    graphPath = str(cur+'/../vascular1Dflow_v0.2/NetworkFiles/')
    
    # create a new window
    window = MyDotWindow()    
    window.connect('destroy',gtk.main_quit)
    window.show()
    
    #create the main graph instance of a graph class
    mainGraph = Graph()
    
    #START THE MAIN LOOP
    menuInput = ""
    subMenuInput = ''
    
    # create vascularNetwork instance
    vascularNetwork = VascularNetwork()
    filename = None
    networkTopologyMode = True
    networkTopologyModes = {0: 'node Description', 1:'mother-daugther Description'}
    k = None
    while menuInput != "q":
        menuInput = ""
        print ""
        print "vnc 2.1 - menu"
        print ""
        print " [a] - add vessel to network"
        print " [d] - delete vessel in network"
        print " [n] - new network"
        print " [b] - set boundary conditions"
        print " [l] - load network"
        print " [s] - save network"
        print " [u] - update XML form CSV file"
        print " [g] - print network graph"
        print " [f] - print network informations"
        print " [m] - change network topology mode; current: ", networkTopologyModes[networkTopologyMode]
        print " [q] - quit"
        print ""
        print '  current network: ', filename
        while  menuInput not in ("l","b","q","a","s","g","f","d","u",'n','m'): #(menuInput != "l") and (menuInput != "b") and (menuInput != "q") and (menuInput != "a") and (menuInput != "s") and (menuInput != "g") and (menuInput != "d") and (menuInput != "f"):
            menuInput = raw_input("what to do? ")
        
        if menuInput == "a": 
            print "Add new vessel"
            
            existing = False
            vesselID = raw_input(" enter the vessel id:  ")
            while True:
                try:
                     vesselID = int(vesselID)
                     if vesselID not in vascularNetwork.vessels:
                         break
                     else:
                         existing = True
                except ValueError:
                    print "TYPE-ERROR: vessel id must be type(int) not type(string)"
                    vesselID = raw_input(" enter non existing id: ")
                if existing == True:
                    print " the vessel id exists already enter a new one"
                    vesselID = raw_input(" enter non existing id: ")
                    existing = False
            
            
            if not networkTopologyMode:
                # define start node ony bifurctaion are allowed
                startNode = int(raw_input(" enter starting node:  "))
                while bifTest(vascularNetwork.vessels, startNode) == False:
                    print "   only bifurcations possible!"
                    startNode = int(raw_input(" enter starting node:  "))
                # define end node
                endNode = int(raw_input (" enter ending node:    "))
                # create vessel obj and save them in vessels-dict
                
                dataDict = {'end': endNode, 'start': startNode}
                vascularNetwork.addVessel(vesselID, dataDict)
                
            else:
                if vascularNetwork.vessels != {}:
#                    mother = int(raw_input(" enter existing mother id:  "))
#                    while mother not in vascularNetwork.vessels or (mother in vascularNetwork.vessels and vascularNetwork.vessels[mother].rightDaughter != None):
#                        if mother not in vascularNetwork.vessels: print " there exists no vessel with this ID"
#                        else: print "   only bifurcations possible!"
#                        mother = int(raw_input(" enter existing mother id: "))
                        
                    existing = False
                    mother = raw_input(" enter existing mother id:  ")
                    while True:
                        try:
                             mother = int(mother)
                             if mother in vascularNetwork.vessels and vascularNetwork.vessels[mother].rightDaughter == None:
                                 break
                             else:
                                 existing = True
                        except ValueError:
                            print "TYPE-ERROR: mother id must be type(int) not type(string)"
                            mother = raw_input(" enter existing mother id:  ")
                        if existing == True:
                            if mother not in vascularNetwork.vessels: print " there exists no vessel with this id"
                            else: print "   only bifurcations possible!"
                            mother = raw_input(" enter existing mother id:  ")
                            existing = False
                        
                    if vascularNetwork.vessels[mother].leftDaughter == None: vascularNetwork.vessels[mother].leftDaughter = vesselID
                    else: vascularNetwork.vessels[mother].rightDaughter = vesselID
                    vascularNetwork.vessels[mother].end = None
                
                vascularNetwork.addVessel(vesselID)
            mainGraph.update_graph(vascularNetwork, window)
                    
        if menuInput == "d":
            print "Delete a vessel and all its daugthers"
            if vascularNetwork.vessels.keys() != []:
                
#                vesselID = int(raw_input(" enter the vessel id: "))
#                while (vesselID in vascularNetwork.vessels) == False:
#                    print " the vessel does not exist"
#                    vesselID = int(raw_input(" enter existing vessel id: "))
                
                existing = False
                vesselID = raw_input(" enter existing vessel id: ")
                while True:
                    try:
                         vesselID = int(vesselID)
                         if vesselID in vascularNetwork.vessels:
                             break
                         else:
                             existing = True
                    except ValueError:
                        print "TYPE-ERROR: vessel id must be type(int) not type(string)"
                        vesselID = raw_input(" enter existing vessel id: ")
                    if existing == True:
                        print " the vessel does not exist"
                        vesselID = raw_input(" enter existing vessel id: ")
                        existing = False
                
                #travers the tree starting with the vessel and collect all ids
                toDelete = findAllDaughters(vascularNetwork,vesselID)
                
                toDelete.append(vesselID)
                for vesselToDelete in toDelete:
                    vascularNetwork.deleteVessel(vesselToDelete)
                    
                # empty the graph to redraw it
                mainGraph.update_graph(vascularNetwork, window)
                
            else:
                print " there are no vessels to delete"
                
        elif menuInput == "n":
            print "new network"
            question = raw_input(" are u sure to delete all current data? [n] - yes: ")
            if question == 'n':
                # delet vascularNetwork
                del vascularNetwork
                # create vascularNetwork instance
                vascularNetwork = VascularNetwork()
                mainGraph.update_graph(vascularNetwork, window)
            
        elif menuInput == "m":
            networkTopologyMode = not networkTopologyMode
        
        elif menuInput == "f":
            vascularNetwork.showVessels()
            vascularNetwork.showNetwork()
            vascularNetwork.calculateNetworkResistance()
            
            
        elif menuInput == "g":
            print mainGraph.getGraph()
            
        elif menuInput == "b":
            subMenuInput = ''
            
            print 'create/load/save/delete/show BoundaryCondistions, not implemented yet'
#           
#            while  subMenuInput not in ['1','2','3','4','5','b']:         
#                # evaluate boundarys in Network
#                boundarys = []
#                notDefinedBoundarys = []
#                
#                boundarys.extend(vascularNetwork.ends)
#                if vascularNetwork.root != [] and vascularNetwork.root[0] not in boundarys: 
#                    boundarys.extend(vascularNetwork.root)
#                    
#                boundarysSaved = vascularNetwork.boundaryConditions.keys()
#                
#                # update saved boundary conditions
#                for boundarysCurrent in boundarys:
#                    if boundarysCurrent not in boundarysSaved:
#                        print " boundary added to vascularNetwork"
#                        vascularNetwork.boundaryConditions[boundarysCurrent] = {}
#                        boundarysSaved.append(boundarysCurrent)
#                        
#                    if vascularNetwork.boundaryConditions[boundarysCurrent] == {}:
#                        notDefinedBoundarys.append(boundarysCurrent)
#                    
#                nonBoundarys = list(set(boundarys).symmetric_difference(set(boundarysSaved)))
#                for nonBoundary in nonBoundarys:
#                    print " boundary removed from vacularNetwork"
#                    del(vascularNetwork.boundaryConditions[nonBoundary])
#                    if nonBoundary in notDefinedBoundarys: notDefinedBoundarys.remove(nonBoundary)
#                    
#                vascularNetwork.evaluateConnections()
#                print ""
#                print "    sub menu: boundary conditions"
#                print ""
#                print "     [1] - show  boundary conditions"
#                print "     [2] - add   boundary condition "
#                print "     [3] - del   boundary condition "
#                print "     [4] - load  boundary conditions from CSV"
#                print "     [5] - write boundary conditions to CSV"
#                print "     [b] - back to the main menu"
#                print ""     
#                subMenuInput = raw_input("     what to do? ") 
#                
#                if subMenuInput == '1':
#                    print "     boundary conditions"
#                    pprint.pprint(vascularNetwork.boundaryConditions)
#                    subMenuInput = ''
#                    
#                elif subMenuInput == '2' and vascularNetwork.root != []:
#                    
#                    print "     add   boundary condition"
#                    print ""
#                    
#                    definedBoundarys = list(set(notDefinedBoundarys).symmetric_difference(set(vascularNetwork.boundaryConditions.keys())))
#                    print "     vessels with defined boundary condition:"
#                    print "       ",'  '.join(str(i) for i in definedBoundarys)
#                    
#                    print "     vessels with undefined boundary condition:"
#                    print "       ",'  '.join(str(i) for i in notDefinedBoundarys)
#                    print ""
#                                        
#                    existing = False
#                    vesselID = raw_input(" enter existing vessel id: ")
#                    while True:
#                        try:
#                             vesselID = int(vesselID)
#                             if vesselID in vascularNetwork.vessels:
#                                 break
#                             else:
#                                 existing = True
#                        except ValueError:
#                            print " TYPE-ERROR: vessel id must be type(int) not type(string)"
#                            vesselID = raw_input(" enter existing vessel id: ")
#                        if existing == True:
#                            print " the vessel does not exist"
#                            vesselID = raw_input(" enter existing vessel id: ")
#                            existing = False
#                    
#                    
#                    inType = '0'
#                    print "     add boundary condition type"
#                    print ""
#                    print "      'Qa'   'Q2a'   'Qm'   'Q2m'   'Pa'    'P2a'   'Pm'   'P2m'   'Ue' "
#                    print "       [1]    [2]    [3]     [4]     [5]     [6]     [7]    [8]     [9]"
#                    print ""
#                    print "      'Rt'    'R'    'WK2'  'WK3'   'QPhy'  'Lnet'  'Fou'   'D'    'PhyQ' "
#                    print "      [10]    [11]   [12]    [13]    [14]    [15]    [16]   [17]    [18]"
#                    print ""
#                    
#                    types = ['Qa','Q2a','Qm','Q2m','Pa','P2a','Pm','P2m','Ue','Rt','R','WK2','WK3','QPhy','Lnet','Fou','D','PhyQ']
#                    
#                    existing = False
#                    inType = raw_input ("      choose type ")
#                    while True:
#                        try:
#                             inType = int(inType)
#                             if inType in np.linspace(1,18,18):
#                                 break
#                             else:
#                                 existing = True
#                        except ValueError:
#                            print "      TYPE-ERROR: vessel id must be type(int) not type(string)"
#                            inType = (raw_input ("      choose type "))
#                        if existing == True:
#                            print "       the type does not exist"
#                            inType = (raw_input ("      choose type "))
#                            existing = False
#                    
#                    
#                    type = types[int(inType)-1]
#                     
#                    bcTags = {'Rt':['Rt'],
#                              'R':['Rc'],
#                              'WK2':['Rc','C'],
#                              'WK3':['Rc','C','R1','RT'],
#                              'QPhy':['Q0_a','Npulse','freq','Tpulse','Tspace'],
#                              'Qa':['Q0_a','Npulse','freq'],
#                              'Q2a':['Q0_a','Npulse','freq','Tpulse'],
#                              'Qm':['Q0_m','Tmean','Traise'],
#                              'Q2m':['Q0_m','Tmean','Traise'],
#                              'Ue':['Upeak','C','Traise'],
#                              'Pa':['P0_a','Npulse','freq'],
#                              'P2a':['P0_a','Npulse','freq','Tpulse'],
#                              'Pm':['P0_m','Tmean','Traise'],
#                              'P2m':['P0_m','Tmean','Traise'],
#                              'Fou':['P0_m','Tmean','Traise','scale','Npulse','Tpulse'],
#                              'D':[''],
#                              'PhyQ':[''],
#                              'Lnet':['Z','C']}
#                    
#                    
#                    bcList = []
#                    print "      set values for the BC condition"
#                    print "          enter 'b' for the first value to skip this procedure"
#                    question = True
#                    for arg in bcTags[type]:
#                        if question == True: 
#                            currValue = raw_input (str("            set value for "+str(arg)+' '))
#                            if currValue == 'b': question=False
#                            test = True
#                            try: float(currValue)
#                            except:
#                                print '            VALUE or TYPE ERROR, set to None'
#                                test = False
#                            if test == True: bcList.append(float(currValue))
#                            else: bcList.append(None)
#                        else: bcList.append(None)
#                    if len(vascularNetwork.boundaryConditions.keys()) == 1:
#                        print "      set position of the BC condition"
#                        position = '2'
#                        while position not in ['1','0']:
#                            position = raw_input ("          enter '0' for the start or '1' for the end of the vessel ")
#                        if position == '1':
#                            type = ''.join(['_',type])
#                    
#                    vascularNetwork.boundaryConditions[vesselID].update({type : bcList})
#                    mainGraph.update_graph(vascularNetwork, window)
#                    subMenuInput = ''
#                        
#                elif subMenuInput == '3' and vascularNetwork.root != []:
#                    print "     delete boundary condition"
#                    print ""
#                    pprint.pprint(vascularNetwork.boundaryConditions)
#                    
#                    vesselID = -1
#                    while vesselID not in vascularNetwork.boundaryConditions.keys():
#                        vesselID = int(raw_input ("      choose vessel id "))
#                    
#                    bcs = vascularNetwork.boundaryConditions[vesselID].keys()
#                    if bcs != []:                 
#                        print ""
#                        print '        ','  '.join(str(' '+i+' ') for i in bcs)
#                        print '        ','   '.join(str('['+str(int(i))+']') for i in np.linspace(1,len(bcs),len(bcs)))
#                        print ""
#                        inType = '0'
#                        while inType not in np.linspace(1,len(bcs),len(bcs)):
#                            inType = int(raw_input ("      choose condition to delete "))
#                            
#                        vascularNetwork.boundaryConditions[vesselID].pop(bcs[inType-1])
#                        print ""
#                        print "     boundary condition ",bcs[inType-1]," removed!"
#                        print ""
#                        mainGraph.update_graph(vascularNetwork, window)
#                    else:
#                        print "     nothing to delete!"
#                    subMenuInput = ''
#                
#                elif subMenuInput == '4' and vascularNetwork.root != []:
#                    
#                    print "     load  boundary conditions from CSV"
#                    print ""
#                    filename = enterFilename(filename,'')
#                    vascularNetwork.boundaryConditions = readBCFromCSV(filename = ''.join([filename,'BC','.csv']))
#                    mainGraph.update_graph(vascularNetwork, window)
#                                                           
#                elif subMenuInput == '5' and vascularNetwork.root != []:
#                    print "     write boundary conditions to CSV"
#                    print ""
#                    filename = enterFilename(filename,'')
#                    writeBCToCSV(vascularNetwork.boundaryConditions,filename = ''.join([filename,'BC','.csv']))
#                                                         
#                    
#                elif subMenuInput == 'b':
#                    break
            
        elif menuInput == "l":
            try:
                FILE = open('recentFilenames.pickle',"rb")
                # store pickle
                recentFilenames = cPickle.load(FILE)
                FILE.close()
            except:
                recentFilenames = []
                
            subMenuInput = ''
            print ""
            print "    sub menu: load data"
            print ""
            print "     [1] - load network from XML"
            print "     [2] - load vessel data from CSV"
            print "     [3] - load vessel data and boundary conditions from CSV"
            print "     [b] - back to the main menu"
            print ""
            while  subMenuInput not in ["1","2","3","b"]:
                subMenuInput = raw_input("what to do? ")
            
                print ""
                print "         resent used networks"
                i = 1
                for name in recentFilenames:
                    print "          [",i,'] - ',name
                    i = 1+i
                print ""
                if subMenuInput == '1':
                    print "     load from XML"
                    
                    filename = enterFilename(filename,'.xml',recentFilenames = recentFilenames)
                    if filename == None:break
                    # delete the old network
                    del vascularNetwork
                    #load the new network
                    vascularNetwork = loadNetworkFromXML(filename= filename)
                    if vascularNetwork == None:
                        vascularNetwork = VascularNetwork()
                        mainGraph.update_graph(vascularNetwork, window)
                        filename = None
                        break
                    
                    mainGraph.update_graph(vascularNetwork, window)
                    filename, value = filename.split(".",1)
                    break
                
                elif subMenuInput == '2':
                    print "     load vessel data from CSV - non existing vessels are added automatically"
                    print ""
                    filename = enterFilename(filename,'.csv',recentFilenames = recentFilenames)
                    if filename == None:break
                    vascularNetwork.updateNetwork(readVesselDataFromCSV(filename=filename))
                    
                    mainGraph.update_graph(vascularNetwork, window)
                    filename, value = filename.split(".",1)
                    break
                
                elif subMenuInput == '3':
                    print "     load vessel data and boundary conditions from CSV"
                    filename = enterFilename(filename,'.csv',recentFilenames = recentFilenames)
                    if filename == None:break
                    vascularNetwork.updateNetwork(readVesselDataFromCSV(filename=filename))
                    mainGraph.update_graph(vascularNetwork, window)
                    filename, value = filename.split(".",1)
                    
                    vascularNetwork.boundaryConditions = readBCFromCSV(filename = ''.join([filename,'BC','.csv']))
                    mainGraph.update_graph(vascularNetwork, window)
                    break
                
                elif subMenuInput == 'b':
                    break
            
            if filename != None:    
                if filename not in recentFilenames: recentFilenames.insert(0,filename)
                else: 
                    recentFilenames.remove(filename)
                    recentFilenames.insert(0,filename)
                if len(recentFilenames) > 5: recentFilenames.pop(-1)
                            
                FILE = open('recentFilenames.pickle',"w")
                # store pickle
                cPickle.dump(recentFilenames, FILE, protocol=2)
                FILE.close()
            
        elif menuInput == "s":
            subMenuInput = ''
            print ""
            print "    sub menu: save data"
            print ""
            print "     [1] - write to XML"
            print "     [2] - write vessel data to CSV"
            print "     [3] - write vessel data and boundary conditions to CSV"
            print "     [4] - write graph to .png and .dot files"
            print "     [b] - back to the main menu"
            print ""
            while subMenuInput not in ["1","2","3","b"]:
                subMenuInput = raw_input("what to do? ")
                     
                if subMenuInput == '1':
                    print "     write to XML"
                    filename = enterFilename(filename,'.xml')
                    if filename == None:break
                    writeNetworkToXML(vascularNetwork,filename = filename)
                    filename, value = filename.split(".",1)
                    break
                    
                elif subMenuInput == '2':
                    print "     write vessel data to CSV"
                    filename = enterFilename(filename,'.csv') 
                    if filename == None:break
                    writeVesselDataToCSV(vessels = vascularNetwork.vessels, filename = filename)
                    filename, value = filename.split(".",1)
                    break
                
                elif subMenuInput == '3':
                    print "     write vessel data and boundary conditions to CSV"
                    filename = enterFilename(filename,'.csv') 
                    if filename == None:break
                    writeVesselDataToCSV(vessels = vascularNetwork.vessels, filename = filename)
                    filename, value = filename.split(".",1)
                    writeBCToCSV(vascularNetwork.boundaryConditions,filename = ''.join([filename,'BC','.csv']))
                    break
                
                elif subMenuInput == '4':
                    print "     write graph to .png and .dot files"
                    pictureName = str(raw_input("     enter pictureName (only!):"))
                    if pictureName == "":
                        pictureName = 'pydotTest'
                    mainGraph.graph.write(graphPath+filename+'/'+pictureName+'.dot')
                    mainGraph.graph.write_png(graphPath+filename+'/'+pictureName+'.png')
                    break
                    
                if subMenuInput == 'b':
                    break
        
        elif menuInput == "u":
            subMenuInput = ''
            print ""
            print "    sub menu: update XML from CSV"
            print ""
            print "     load from XML"
            
            filename = enterFilename(filename,'.xml')
            if filename == None:break
            # delete the old network
            del vascularNetwork
            #load the new network
            vascularNetwork = loadNetworkFromXML(filename= filename)
            if vascularNetwork == None:
                vascularNetwork = VascularNetwork()
                break
            
            mainGraph.update_graph(vascularNetwork, window)
            
            filename, value = filename.split(".",1)
            
            print "     load vessel data from CSV - non existing vessels are added automatically"
            filenameCSV = ''.join([filename,'.csv'])
            vascularNetwork.updateNetwork(readVesselDataFromCSV(filename=filenameCSV))
            
            mainGraph.update_graph(vascularNetwork, window)
            
            print "     write to XML"
            filenameXML = ''.join([filename,'.xml'])
            writeNetworkToXML(vascularNetwork,filename = filenameXML)
Example #4
0
def loadNetworkFromXML(filename=None,
                       update=None,
                       networkPath=str(cur + "/../NetworkFiles/")):

    # read from file
    if filename == None:
        filename = "oldNetwork1.xml"

    networkDirectory = filename.split('.')[0]
    if not os.path.exists(str(networkPath + networkDirectory)):
        print 'Error: file not in the correct directory'
        return

    # create vascularNetwork instance
    if update == None:
        vascularNetwork = VascularNetwork()
        # set name
        vascularNetwork.name = (filename.split('.'))[0]
    else:
        netBC = {}
        netFluid = {}
        netSimCon = {}
        netSolver = {}
        networkDataDict = {
            'boundaryConditions': netBC,
            'globalFluid': netFluid,
            'simulationContext': netSimCon,
            'networkSolver': netSolver
        }
        vesselDataDict = {}

    # load the data!
    try:
        parser = etree.XMLParser(encoding='iso-8859-1')
        tree = etree.parse(networkPath + networkDirectory + '/' + filename,
                           parser)
    except:
        print " Error: path / file does not exist or error in file"
        if update == None:
            return
        else:
            return {
                'networkData': networkDataDict,
                'vesselData': vesselDataDict
            }

    # create root
    root = tree.getroot()

    #SimulationContext
    for simContext in root.findall(".//simulationContext"):
        for data in simContext:
            if data.tag == 'CFL':
                if data.text != 'None' and data.text != None:
                    if update == None:
                        vascularNetwork.simulationContext['CFL'] = float(
                            eval(data.text))
                    else:
                        netSimCon['CFL'] = float(eval(data.text))
            if data.tag == 'totalTime':
                if data.text != 'None' and data.text != None:
                    if update == None:
                        vascularNetwork.simulationContext[
                            'totalTime'] = unitConversionToSI(
                                unitsDict, float(data.text),
                                data.attrib['unit'])
                    else:
                        netSimCon['totalTime'] = unitConversionToSI(
                            unitsDict, float(data.text), data.attrib['unit'])

            if data.tag == 'EqSystem' or data.tag == 'NumScheme':
                if data.text != 'None' and data.text != None:
                    if update == None:
                        vascularNetwork.networkSolver[data.tag] = str(
                            data.text)
                    else:
                        netSolver[data.tag] = str(data.text)
            if data.tag == 'CharSystem':
                if data.text != 'None' and data.text != None:
                    try:
                        charsys = int(data.text)
                    except:
                        raise TypeError(
                            'Value of %s in simulationContext not convertable to int'
                            % data.tag)
                    if update == None:
                        vascularNetwork.networkSolver[data.tag] = charsys
                    else:
                        netSolver[data.tag] = charsys

    #load boundary Conditions
    for bcs in root.findall(".//boundaryConditions/boundaryCondition"):
        bcDict = bcs.attrib
        if 'vessel_id' in bcDict:
            try:
                vessel_id = int(bcDict['vessel_id'])
            except:
                raise TypeError(
                    'vessel_id %s in boundaryCondition not convertable to int'
                    % bcDict['vessel_id'])
            typeData2 = {}

            boundaryInstances = []
            boundaryIntervals = []

            for data in bcs:

                if data.tag in bcTags.keys():
                    boundaryInstance = eval(bcTagsClassReferences[data.tag])()
                    boundaryDataDict = {}
                    boundaryDataDict['name'] = data.tag
                    boundaryIntervalDataDict = {}

                    bcItems = bcTags[data.tag]

                    for bcItem in bcItems:
                        # find scalar Data
                        for value in data.findall(str(".//" + bcItem)):
                            try:
                                floatValue = float(eval(value.text))
                            except:
                                raise TypeError(
                                    'Value %s in boundaryCondition not convertable to float'
                                    % value.text)
                            boundaryDataDict[bcItem] = unitConversionToSI(
                                unitsDict, floatValue, value.attrib['unit'])
                        # find interval Data for polychaos
                        for value in data.findall(".//" + bcItem +
                                                  "-interval"):
                            if value.text != 'None' and value.text != None:
                                interval = []
                                try:
                                    for number in map(float,
                                                      value.text.split(' ')):
                                        interval.append(
                                            unitConversionToSI(
                                                unitsDict, float(number),
                                                value.attrib['unit']))
                                except:
                                    raise TypeError(
                                        'Value %s in boundaryCondition Interval not convertable to float'
                                        % value.text)

                                boundaryIntervalDataDict[bcItem] = interval
                                boundaryIntervalDataDict['name'] = data.tag

                    # exception for reflection coefficient because the value can stand rigth begind the
                    if data.tag in ['Rt', '_Rt']:
                        if type(data.text) != type(None):
                            if '.' in data.text:
                                try:
                                    floatValue = float(eval(data.text))
                                except:
                                    raise TypeError(
                                        'Value %s in boundaryCondition not convertable to float'
                                        % data.text)

                                # compatibility old xml-version Rt no unit-tag new version <Rt unit=''>..
                                Rtunit = ''
                                if 'unit' in data.attrib:
                                    Rtunit = data.attrib['unit']

                                boundaryDataDict[bcItem] = unitConversionToSI(
                                    unitsDict, floatValue, Rtunit)

                    #check if enough parameters are given:
                    if len(boundaryDataDict) != len(bcItems) + 1:
                        print len(boundaryDataDict)
                        raise TypeError(
                            str('boundaryCondition not sufficient defined; check if these attributes are given '
                                + str(bcItems)))

                    # set du-matrix correct for type 1
                    if data.tag in bcDuMatrix.keys():
                        boundaryDataDict['duMatrix'] = bcDuMatrix[data.tag]
                    # update boundarz condition
                    boundaryInstance.update(boundaryDataDict)
                    boundaryInstances.append(boundaryInstance)

                    boundaryIntervals.append(boundaryIntervalDataDict)

            if update == None:
                vascularNetwork.boundaryConditions[
                    vessel_id] = boundaryInstances

                if boundaryIntervalDataDict != {}:
                    vascularNetwork.boundaryConditionIntervals[
                        vessel_id] = boundaryIntervals

            else:
                netBC[vessel_id] = boundaryInstances

    #load global Fluid properties
    for my in root.findall(".//globalFluid/my"):
        if str(my.text) != 'None':
            # find units and convert if needed to SI
            if update == None:
                vascularNetwork.globalFluid['my'] = unitConversionToSI(
                    unitsDict, float(eval(my.text)), my.attrib['unit'])
            else:
                netFluid['my'] = unitConversionToSI(unitsDict,
                                                    float(eval(my.text)),
                                                    my.attrib['unit'])
    for rho in root.findall(".//globalFluid/rho"):
        if str(rho.text) != 'None':
            # find units and convert if needed to SI
            if update == None:
                vascularNetwork.globalFluid['rho'] = unitConversionToSI(
                    unitsDict, float(eval(rho.text)), rho.attrib['unit'])
            else:
                netFluid['rho'] = unitConversionToSI(unitsDict,
                                                     float(eval(rho.text)),
                                                     rho.attrib['unit'])
    for gamma in root.findall(".//globalFluid/gamma"):
        if str(gamma.text) != 'None':
            if update == None:
                vascularNetwork.globalFluid['gamma'] = float(eval(gamma.text))
            else:
                netFluid['gamma'] = float(eval(gamma.text))
    for dlt in root.findall(".//globalFluid/dlt"):
        if str(dlt.text) != 'None':
            if update == None:
                vascularNetwork.globalFluid['dlt'] = float(eval(dlt.text))
            else:
                netFluid['dlt'] = float(eval(dlt.text))
        elif str(gamma.text) != 'None':
            if update == None:
                vascularNetwork.globalFluid['dlt'] = (float(eval(
                    gamma.text)) + 2.) / (float(eval(gamma.text)) + 1.)
            else:
                netFluid['dlt'] = (float(eval(gamma.text)) +
                                   2.0) / (float(eval(gamma.text)) + 1.)

    for pref in root.findall(".//globalFluid/pref"):
        if str(pref.text) != 'None':
            if update == None:
                vascularNetwork.globalFluid['pref'] = unitConversionToSI(
                    unitsDict, float(eval(pref.text)), pref.attrib['unit'])
            else:
                netFluid['pref'] = unitConversionToSI(unitsDict,
                                                      float(eval(pref.text)),
                                                      pref.attrib['unit'])

    # find vessel data
    for vessel_i in root.findall(".//vessel"):

        vesselXMLDict = vessel_i.attrib

        vesselID = None
        vesselData = {
            'name': None,
            'start': None,
            'end': None,
            'leftDaughter': None,
            'rightDaughter': None,
            'angleToMother': None,
            'geom': None,
            'length': None,
            'lengthInterval': None,
            'radiusA': None,
            'radiusAInterval': None,
            'radiusB': None,
            'radiusBInterval': None,
            'N': None,
            'comp': None,
            'Pfunc': None,
            'Ps': None,
            'As': None,
            'wallThickness': None,
            'wallThicknessInterval': None,
            'youngModulus': None,
            'youngModulusInterval': None,
            'beta': None,
            'betaInterval': None,
            'my': None,
            'rho': None,
            'gamma': None,
            'dlt': None,
            'pref': None
        }

        if 'id' in vesselXMLDict and str(vesselXMLDict['id']) != 'None':
            vesselID = int(vesselXMLDict['id'])
        if 'start_node' in vesselXMLDict and str(
                vesselXMLDict['start_node']) != 'None':
            vesselData['start'] = int(vesselXMLDict['start_node'])
        if 'end_node' in vesselXMLDict and str(
                vesselXMLDict['end_node']) != 'None':
            vesselData['end'] = int(vesselXMLDict['end_node'])
        if 'name' in vesselXMLDict and str(vesselXMLDict['name']) != 'None':
            vesselData['name'] = str(vesselXMLDict['name'])
        if 'leftDaughter' in vesselXMLDict and str(
                vesselXMLDict['leftDaughter']) != 'None':
            vesselData['leftDaughter'] = int(vesselXMLDict['leftDaughter'])
        if 'rightDaughter' in vesselXMLDict and str(
                vesselXMLDict['rightDaughter']) != 'None':
            vesselData['rightDaughter'] = int(vesselXMLDict['rightDaughter'])
        if 'angleToMother' in vesselXMLDict and str(
                vesselXMLDict['angleToMother']) != 'None':
            vesselData['angleToMother'] = float(vesselXMLDict['angleToMother'])
        ## old variable names // only version compatibility delete this for next version 0.3
        if 'leftDaugther' in vesselXMLDict and str(
                vesselXMLDict['leftDaugther']) != 'None':
            vesselData['leftDaughter'] = int(vesselXMLDict['leftDaugther'])
        if 'rightDaugther' in vesselXMLDict and str(
                vesselXMLDict['rightDaugther']) != 'None':
            vesselData['rightDaughter'] = int(vesselXMLDict['rightDaugther'])

        # find grid properties
        for grid in vessel_i.findall(".//grid"):
            for data in grid:
                if data.tag == 'geom':
                    if data.text != 'None' and data.text != None:
                        vesselData['geom'] = str(data.text)

                if data.tag == 'length' or data.tag == 'radiusA' or data.tag == 'radiusB' or data.tag == 'N':
                    for value in data.findall(".//scalar"):
                        if value.text != 'None' and value.text != None:
                            vesselData[data.tag] = unitConversionToSI(
                                unitsDict, float(eval(value.text)),
                                value.attrib['unit'])
                    for value in data.findall(".//interval"):
                        if value.text != 'None' and value.text != None:
                            interval = []
                            for number in map(float, value.text.split(' ')):
                                interval.append(
                                    unitConversionToSI(unitsDict,
                                                       float(number),
                                                       value.attrib['unit']))
                            vesselData[data.tag + 'Interval'] = interval

        # find Solid properties
        for solid in vessel_i.findall(".//solid"):
            for data in solid:

                if data.tag == 'comp':
                    if data.text != 'None' and data.text != None:
                        vesselData['comp'] = str(data.text)
                if data.tag == 'Pfunc':
                    if data.text != 'None' and data.text != None:
                        if data.text == 'True': data.text = '1'
                        if data.text == 'False': data.text = '0'
                        vesselData['Pfunc'] = bool(int(data.text))
                if data.tag == 'Ps' or data.tag == 'As':
                    if data.text != 'None' and data.text != None:
                        vesselData[data.tag] = unitConversionToSI(
                            unitsDict, float(eval(data.text)),
                            data.attrib['unit'])

                if data.tag == 'beta' or data.tag == 'wallThickness' or data.tag == 'youngModulus':
                    for value in data.findall(".//scalar"):
                        if value.text != 'None' and value.text != None:
                            vesselData[data.tag] = unitConversionToSI(
                                unitsDict, float(eval(value.text)),
                                value.attrib['unit'])
                    for value in data.findall(".//interval"):
                        if value.text != 'None' and value.text != None:
                            interval = []
                            for number in map(float, value.text.split(' ')):
                                interval.append(
                                    unitConversionToSI(unitsDict,
                                                       float(number),
                                                       value.attrib['unit']))
                            vesselData[data.tag + 'Interval'] = interval

        # find fluid properties
        for fluid in vessel_i.findall(".//fluid"):
            for data in fluid:
                if data.tag == 'my' or data.tag == 'rho' or data.tag == 'pref' or data.tag == 'gamma' or data.tag == 'dlt':
                    if data.text != 'None' and data.text != None:
                        vesselData[data.tag] = unitConversionToSI(
                            unitsDict, float(eval(data.text)),
                            data.attrib['unit'])

        # pre check if vessels data given is consitent:
        # warning if not
        if vesselData['comp'] == 'Exponential':
            if (vesselData['beta'] or vesselData['Ps']
                    or vesselData['As']) == None:
                print "WARNING: not all specifications for %s are met!" % vesselData[
                    'comp']
        elif vesselData['comp'] == 'Laplace':
            if (vesselData['wallThickness'] or vesselData['youngModulus']
                    or vesselData['Ps'] or vesselData['As']) == None:
                print "WARNING: not all specifications for %s are met!" % vesselData[
                    'comp']

        # calculate area out of radius
        if vesselData['geom'] == 'Uni':
            if vesselData['radiusA'] != None and vesselData['As'] == None:
                vesselData['As'] = vesselData['radiusA']**2 * pi
            if vesselData['radiusA'] == None and vesselData['As'] != None:
                data['radiusA'] = sqrt(data['As'] / pi)
        if vesselData['geom'] == 'Cone':
            if vesselData['radiusA'] != None and vesselData[
                    'radiusB'] != None and vesselData['As'] == None:
                vesselData['As'] = (vesselData['radiusA']**2 +
                                    vesselData['radiusB']**2) / 2.0 * pi

        if vesselData['dlt'] == None and vesselData['gamma'] != None:
            vesselData['dlt'] = (vesselData['gamma'] +
                                 2.) / (vesselData['gamma'] + 1.)

        # add vessel to the network
        if update == None:
            vascularNetwork.addVessel(Id=vesselID, dataDict=vesselData)
        else:
            vesselDataDict[vesselID] = vesselData

    if update == None:
        print " ... loaded successfully"
        return vascularNetwork
    else:
        return {'networkData': networkDataDict, 'vesselData': vesselDataDict}