示例#1
0
def writeRandomInputstoCSV(networkName, randomInputManager, delimiter=';'):
    '''
    Function writes random variable data to *.csv  file
    '''
    # TODO: add units
    # evaluate tags
    variablesToSaveTags = []
    variablesToSaveTags.extend(nxml.generalRandomInputsAttributes)
    for listValue in nxml.randomInputsReference.itervalues():
        variablesToSaveTags.extend(listValue)
    variablesToSaveTags.extend(['randomInputType', 'location'])
    # create writer
    randomVariableCSVFile = mFPH.getFilePath('randomVariableCSVFile',
                                             networkName,
                                             'xxx',
                                             'write',
                                             exception='Warning')
    writer = csv.DictWriter(open(randomVariableCSVFile, 'wb'),
                            variablesToSaveTags,
                            delimiter=delimiter)

    firstRow = {key: key for key in variablesToSaveTags}
    writer.writerow(firstRow)

    for randomInput in randomInputManager.randomInputsList:
        rowDict = {}
        for variablesToSaveTag in variablesToSaveTags:
            rowDict[variablesToSaveTag] = randomInput.getVariableValue(
                variablesToSaveTag)
        writer.writerow(rowDict)
示例#2
0
def writeVesselDataToCSV(networkName, vessels, delimiter=';'):
    """
    Functions writes vessel data to *.csv file 
    
    input:
        networkName <string>
        vessels     <dict>    := vessels dict of class vascularNetwork {vesselId : vesselInstance} 
        delimiter   <string>  (default = ';')
    
    """
    tags = []
    for tag in nxml.vesselAttributes:
        tags.append(tag)
    for vesselElement in nxml.vesselElements:
        if vesselElement == 'compliance':
            for specificCompElements in nxml.vesselElementReference[
                    vesselElement].values():
                for tag in specificCompElements:
                    if tag not in tags:
                        tags.append(tag)
        else:
            for tag in nxml.vesselElementReference[vesselElement]:
                tags.append(tag)

    ## openFile and create writer
    vesselCSVFile = mFPH.getFilePath('vesselCSVFile', networkName, 'xxx',
                                     'write')
    writer = ccBC.csv.DictWriter(open(vesselCSVFile, 'wb'),
                                 tags,
                                 delimiter=delimiter)

    # write first row == tags
    firstRow = {}
    for item in tags:
        firstRow[item] = item
    writer.writerow(firstRow)

    # write unit row
    unitRow = {}
    for tag in tags:
        try:
            unitRow[tag] = ''.join(['#', variablesDict[tag]['unitSI']])
        except:
            unitRow[tag] = ''
    unitRow['Id'] = 'unit'

    # write all data
    writer.writerow(unitRow)
    data = []
    for vessel in vessels.itervalues():
        vesselDict = {}
        for tag in tags:
            vesselDict[tag] = vessel.getVariableValue(tag)
        data.append(vesselDict)
    writer.writerows(data)
示例#3
0
def readRandomInputsfromCSV(networkName, randomInputManager, delimiter=';'):
    '''
    Function reads the random variable data from a *.csv file
    all existing rv definitions in the randomInputManager will be erased
    '''

    # prepare randomInputManager
    randomInputManager.deleteAllRandomInputs()

    # create reader
    randomVariableCSVFile = mFPH.getFilePath('randomVariableCSVFile',
                                             networkName,
                                             'xxx',
                                             'read',
                                             exception='Warning')
    reader = csv.DictReader(open(randomVariableCSVFile, 'rb'),
                            delimiter=delimiter)

    # evaluate tags
    variablesToLoadTags = []
    variablesToLoadTags.extend(nxml.generalRandomInputsAttributes)
    for listValue in nxml.randomInputsReference.itervalues():
        variablesToLoadTags.extend(listValue)
    variablesToLoadTags.extend(['randomInputType', 'location'])
    # add random variables
    for row in reader:
        dataDict = {}
        for variable in variablesToLoadTags:
            if variable in row.keys():
                # TODO: add units
                variableUnit = None
                # save converted CSV-value
                dataDict[variable] = mXML.loadVariablesConversion(
                    variable, row[variable], variableUnit)
            else:
                print "WARNING: mCSV.readRandomInputsfromCSV(), no variable {} defined in the csv file but needed to create proper working random input".format(
                    variable)
        randomInputManager.addRandomInput(dataDict)
示例#4
0
def writeNetworkToXML(vascularNetwork, dataNumber = "xxx", networkXmlFile = None):
    """
    This function creates an XML file and writes all variable data of a vascularNetwork into it (except solution)
    The forma of the XML and all variable data are defined in constants.py
    """
    networkName = vascularNetwork.getVariableValue('name')

    if networkXmlFile == None:
        networkXmlFile =  mFPH.getFilePath('networkXmlFile', networkName, dataNumber, 'write')

    try:
        root = etree.Element(networkName, id = dataNumber, version = newestNetworkXmlVersion)
    except: #TODO: find out what errors etree.Element raises and fix this except statement.
        print " Error: path / file does not exist"
        return

    ## import current network xml description as nxmlW(rite) to avoid version clash
    from constants import newestNetworkXml as nxmlW

    xmlFile = etree.ElementTree(root)

    for xmlElementName in nxmlW.xmlElements:
        xmlFileElement = etree.SubElement(root, xmlElementName)
        xmlElement = nxmlW.xmlElementsReference[xmlElementName]
                
        if xmlElementName == 'boundaryConditions':
            for vesselId,boundaryConditions in vascularNetwork.boundaryConditions.iteritems():
                subElement = etree.SubElement(xmlFileElement, 'boundaryCondition', vesselId = str(vesselId))
                # loop saved condition instances
                for boundaryCondition in boundaryConditions:
                    boundaryType = boundaryCondition.getVariableValue('name')
                    subsubElement = etree.SubElement(subElement, boundaryType)
                    # loop variables of the instance to be saved in xml
                    for variable in nxmlW.boundaryConditionElements[boundaryType]:
                        variableElement = etree.SubElement(subsubElement, variable)
                        value = boundaryCondition.getVariableValue(variable)
                        value = writeXMLsetUnit(variableElement,variable,value)
                        writeXMLsaveValues(variableElement,variable,value)

        elif xmlElementName == 'vessels':
            for vessel in vascularNetwork.vessels.itervalues():
                attributes = {}
                for attribute in nxmlW.vesselAttributes:
                    attributes[attribute] = str(vessel.getVariableValue(attribute))
                vesselSubElement = etree.SubElement(xmlFileElement,'vessel',attributes)
                for vesselElement in xmlElement:
                    # add vesselElement
                    subElement = etree.SubElement(vesselSubElement, vesselElement)
                    # check if compliance and adjust variables
                    if vesselElement == 'compliance':
                        complianceType = vessel.getVariableValue('complianceType')
                        variables = nxmlW.vesselElementReference[vesselElement][complianceType]
                    else:
                        variables = nxmlW.vesselElementReference[vesselElement]
                    # save variables
                    for variable in variables:
                        subsubElement = etree.SubElement(subElement, variable)
                        variableValues = vessel.getVariableValue(variable)
                        variableValues = writeXMLsetUnit(subsubElement,variable,variableValues)
                        writeXMLsaveValues(subsubElement,variable,variableValues)


        elif xmlElementName == 'communicators':
            for comId,comData in vascularNetwork.communicators.iteritems():
                comType = comData['comType']
                subElement = etree.SubElement(xmlFileElement, comType)
                for variable in nxmlW.communicatorReference[comData['comType']]:
                    subsubElement = etree.SubElement(subElement, variable)
                    value = comData[variable]
                    value = writeXMLsetUnit(subsubElement,variable, value)
                    writeXMLsaveValues(subsubElement,variable,value)

        elif xmlElementName == 'venousPool':
            if vascularNetwork.venousPool is not None:
                venousPoolWrapper = classVenousPool.VenousPoolXMLWrapper()
                venousPoolWrapper.venousPoolContent = vascularNetwork.venousPool
                venousPoolWrapper.writeDataToXmlNode(xmlFileElement)

        elif xmlElementName == 'randomInputManager':
            if vascularNetwork.randomInputManager is not None:
                vascularNetwork.randomInputManager.writeDataToXmlNode(xmlFileElement)
                xmlFileElement.set('class', 'RandomInputManager')
                
        elif xmlElementName == 'measurementRoutine':
            if vascularNetwork.measurementRoutine is not None:
                vascularNetwork.measurementRoutine.writeDataToXmlNode(xmlFileElement)
                xmlFileElement.set('class', 'MeasurementRoutine')
                
        elif xmlElementName == "externalStimuli":
            for stimulusId, stimulus in vascularNetwork.externalStimuli.iteritems():
                stimulusType = stimulus['type']
                # add stimuliElement
                subElement = etree.SubElement(xmlFileElement, 'externalStimulus', Id=str(stimulusId), type=stimulusType)
                variables = nxmlW.xmlElementsReference[xmlElementName][stimulusType]

                for variable in variables:
                    subsubElement = etree.SubElement(subElement, variable)
                    value = stimulus[variable]
                    value = writeXMLsetUnit(subsubElement, variable, value)
                    writeXMLsaveValues(subsubElement, variable, value)
        
        else: # vascularNetwork
            for variable in xmlElement:
                subElement = etree.SubElement(xmlFileElement, variable) # add subElement
                if xmlElementName == 'globalFluid': # get variable values from varscularNetwork
                    variableValues = vascularNetwork.globalFluid[variable]
                else:
                    variableValues = vascularNetwork.getVariableValue(variable)
                variableValues = writeXMLsetUnit(subElement,variable,variableValues)  # check unit

                writeXMLsaveValues(subElement,variable,variableValues)

    xmlFile.write(networkXmlFile,encoding='iso-8859-1',pretty_print = True)
示例#5
0
def loadNetworkFromXML(networkName ,
                       dataNumber = "xxx",
                       exception = 'Error',
                       networkXmlFile = None,
                       pathSolutionDataFilename = None):
    """
    Function loads network from XML-file

    version of XML files supported: 4.0, 4.1, 4.2
    """
    currentVersions = ['4.3']

    # read from file
    if networkName == None:
        print 'ERROR: moduleXML.loadNetworkFromXML() : load XML - no networkName passed'
        return None

    if networkXmlFile == None:
        networkXmlFile = mFPH.getFilePath('networkXmlFile', networkName, dataNumber, 'read', exception = exception)

    # create vascularNetwork instance
    vascularNetwork = cVascNw.VascularNetwork()
    # set name
    vascularNetwork.update({'name': networkName,
                            'dataNumber':dataNumber,
                            'pathSolutionDataFilename': pathSolutionDataFilename})

    try:
        parser = etree.XMLParser(encoding='iso-8859-1')
        tree = etree.parse(''.join([networkXmlFile]), 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()


    if xmlFileVersion == newestNetworkXmlVersion:
        from constants import newestNetworkXml as nxml
    elif xmlFileVersion == '4.0':
        import networkXml040 as nxml
    elif xmlFileVersion == '4.1':
        import networkXml041 as nxml

    if xmlFileVersion != newestNetworkXmlVersion:
        print " WARNING the version of the network xml file you try to load is outdated it may cause some problems!"

    for xmlElementName in nxml.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', '')

                    boundaryInstances = []
                    # loop through possible communicator class types
                    for boundaryType in nxml.xmlElementsReference[xmlElementName]:
                        # find all bcs of this type
                        for bcElements in boundaryConditionElement.findall(''.join(['.//',boundaryType])):
                            boundaryInstance = eval(nxml.bcTagsClassReferences[boundaryType])()
                            boundaryDataDict = {"vesselId":vesselId}
                            boundaryDataDict['name'] = boundaryType
                            # loop through all variables of this type, convert and save values of these
                            for variable in nxml.xmlElementsReference[xmlElementName][boundaryType]:
                                # find normal variables
                                try:
                                    element = bcElements.findall(''.join(['.//',variable]))[0]
                                    # get variable value
                                    try: variableValueStr = element.text
                                    except: loadingErrorMessageValueError(variable, 'boundaryCondition', boundaryType)
                                    # get unit
                                    try: variableUnit = element.attrib['unit']
                                    except: variableUnit = None
                                except: loadingErrorMessageVariableError(variable, 'boundaryCondition', boundaryType)
                                # save converted XML-value
                                boundaryDataDict[variable] = loadVariablesConversion(variable, variableValueStr, variableUnit)

                                # adjust path to boundary condition file
                                if variable == 'filePathName':
                                    ## TODO: fix problem when loading an absolute path
                                    networkDirectory = '/'.join(networkXmlFile.split('/')[0:-1])
                                    # variableValueStr = '/'.join([networkDirectory,variableValueStr])
                                    boundaryDataDict['networkDirectory'] = networkDirectory
                                    boundaryDataDict['filePathName'] = variableValueStr

                            boundaryInstance.update(boundaryDataDict)
                            boundaryInstances.append(boundaryInstance)

                    # apply read data to vascularNetwork
                    if vesselId not in vascularNetwork.boundaryConditions.keys():
                        vascularNetwork.boundaryConditions[vesselId] = boundaryInstances
                    else:
                        vascularNetwork.boundaryConditions[vesselId].extend(boundaryInstances)

            elif xmlElementName == 'vessels':
                for vesselXMLnode in xmlElement.findall(''.join(['.//','vessel'])):
                    vesselData = {}
                    # load vessel attributes
                    for attribute in nxml.vesselAttributes:
                        try: vesselData[attribute] = loadVariablesConversion(attribute, vesselXMLnode.attrib[attribute], '')
                        except:
                            try:    loadingErrorMessageVariableError(attribute, 'vessel', vesselData['Id'])
                            except: loadingErrorMessageVariableError(attribute, 'one vessel', '')

                    for vesselElement in nxml.xmlElementsReference[xmlElementName]:
                        # check if compliance and adjust variables
                        if vesselElement == 'compliance':
                            try: complianceTypeElement = vesselXMLnode.findall(''.join(['.//','complianceType']))[0]
                            except: loadingErrorMessageVariableError('complianceType', 'vessel', vesselData['Id'])
                            complianceType = loadVariablesConversion('complianceType', complianceTypeElement.text, '')
                            variables = nxml.vesselElementReference[vesselElement][complianceType]
                        else:
                            variables = nxml.vesselElementReference[vesselElement]
                        # load variables
                        for variable in variables:
                            try:
                                element = vesselXMLnode.findall(''.join(['.//',variable]))[0]
                                # get variable value
                                try: variableValueStr = element.text
                                except: loadingErrorMessageValueError(variable, 'vessel', vesselData['Id'])
                                # get unit
                                try: variableUnit = element.attrib['unit']
                                except KeyError: variableUnit = None
                            except: loadingErrorMessageVariableError(variable, 'vessel', vesselData['Id'])

                            # save converted XML-value
                            vesselData[variable] = loadVariablesConversion(variable, variableValueStr, variableUnit)


                    vascularNetwork.updateNetwork({'vesselData':{vesselData['Id']:vesselData}})


            elif xmlElementName == 'communicators':
                # loop through possible communicator class types
                for comunicatorType in nxml.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 nxml.xmlElementsReference[xmlElementName][comunicatorType]:
                            try:
                                element = comElements.findall(''.join(['.//',variable]))[0]
                                try: variableValueStr = element.text
                                except: loadingErrorMessageValueError(variable, 'communicator', comunicatorType)
                                # get unit
                                try: variableUnit = element.attrib['unit']
                                except: variableUnit = None
                            except: loadingErrorMessageVariableError(variable, 'communicator', comunicatorType)
                            # get variable value

                            communicatorData[variable] = loadVariablesConversion(variable, variableValueStr, variableUnit)
                            if variable == 'comId': comId = communicatorData[variable]
                        vascularNetwork.updateNetwork({'communicators':{comId:communicatorData}})

            elif xmlElementName == 'externalStimuli':
                for externalStimulusElement in xmlElement.findall(''.join(['.//','externalStimulus'])):
                    try: stimulusId = int(externalStimulusElement.attrib['Id'])
                    except: loadingErrorMessageVariableError('stimulusId', 'one stimulus', '')
                    try: stimulusType = externalStimulusElement.attrib['type']
                    except: loadingErrorMessageVariableError('type', 'one stimulus', '')

                    stimulusData = {'stimulusId':stimulusId}
                    stimulusData['type'] = stimulusType
                    externalStimulusTopLevelElement = externalStimulusElement
                    variables = nxml.externalStimulusElements[stimulusType]
                    for variable in variables:
                        try:
                            element = externalStimulusTopLevelElement.findall(''.join(['.//',variable]))[0]
                            try: variableValueStr = element.text
                            except: loadingErrorMessageValueError(variable, 'externalStimuli', stimulusId)
                            # get unit
                            try: variableUnit = element.attrib['unit']
                            except: variableUnit = None
                        except: loadingErrorMessageVariableError(variable, 'externalStimuli', stimulusId)
                        # get variable value

                        stimulusData[variable] = loadVariablesConversion(variable, variableValueStr, variableUnit)
                        if variable == 'stimulusId': stimulusId = stimulusData[variable]

                    vascularNetwork.updateNetwork({'externalStimuli': {stimulusId:stimulusData}})

            elif xmlElementName == 'globalFluid':

                globalFluidData = {}

                for variable in nxml.xmlElementsReference[xmlElementName]:
                    # find normal variables
                    try:
                        element = xmlElement.findall(''.join(['.//',variable]))[0]
                        # get variable value
                        try: variableValueStr = element.text
                        except: loadingErrorMessageValueError(variable, 'global fluid', '')
                        # get unit
                        try: variableUnit = element.attrib['unit']
                        except: variableUnit = None
                    # save converted XML-value
                    except: loadingErrorMessageVariableError(variable, 'global fluid', '')

                    globalFluidData[variable] = loadVariablesConversion(variable, variableValueStr, variableUnit)

                vascularNetwork.updateNetwork({'globalFluid':globalFluidData}) 

            elif xmlElementName == "venousPool":
                if len(xmlElement) > 0:
                    venousPoolWrapper = classVenousPool.VenousPoolXMLWrapper()
                    venousPoolWrapper.loadDataFromXmlNode(xmlElement)
                    vascularNetwork.venousPool = venousPoolWrapper.venousPoolContent

            elif xmlElementName == 'randomInputManager':
                ## create random vector
                xmlElementChildren = xmlElement.getchildren()
                if len(xmlElementChildren) != 0:
                    randomInputManager = RandomInputManager()
                    vascularNetwork.randomInputManager = randomInputManager
                    vascularNetwork.randomInputManager.loadDataFromXmlNode(xmlElement)

            elif xmlElementName == 'measurementRoutine':
                ## create measurementRoutine
                xmlElementChildren = xmlElement.getchildren()
                if len(xmlElementChildren) != 0:
                    measurmentRoutine = MeasurementRoutine()
                    vascularNetwork.measurementRoutine = measurmentRoutine
                    vascularNetwork.measurementRoutine.loadDataFromXmlNode(xmlElement)
                                

            elif xmlElementName in nxml.vascularNetworkElements: # vascularNetwork
                vascularNetworkData = {}
                for variable in nxml.xmlElementsReference[xmlElementName]:
                    try:
                        element = xmlElement.findall(''.join(['.//',variable]))[0]
                        # get variable value
                        try: variableValueStr = element.text
                        except: loadingErrorMessageValueError(variable, xmlElementName, '')
                        # get
                        try: variableUnit = element.attrib['unit']
                        except: variableUnit = None
                    except: loadingErrorMessageVariableError(variable, xmlElementName, '')

                    # save converted XML-value
                    vascularNetworkData[variable] = loadVariablesConversion(variable, variableValueStr, variableUnit)
                vascularNetwork.update(vascularNetworkData)

    return vascularNetwork
示例#6
0
def readVesselDataFromCSV(networkName, delimiter=';'):
    """
    Functions loads vessel data from *.csv file inclusive polynomial chaos definitions
    
    input:
        networkName 
        delimiter   (default = ';')
    
    return:
            dict := {'vesselData': vesselData} which is used by vascular network to
                    update its vessel data with the function vascularNetwork.updateNetwork(dataDict)
    """

    vesselCSVFile = mFPH.getFilePath('vesselCSVFile',
                                     networkName,
                                     'xxx',
                                     'read',
                                     exception='Warning')

    if vesselCSVFile == None:
        return None

    with open(vesselCSVFile, 'rb') as csvfile:
        dialect = csv.Sniffer().sniff(csvfile.read(1024), delimiters=";,")
        csvfile.seek(0)

        if dialect.delimiter == ',':
            print """\n WARNING: mCSV92 detected delimiter ',': This delimiter might lead to wrong data as
             it is used as well as decimal place separator in some languages! Check the loaded values carefully!"""

        #reader = ccBC.csv.DictReader(csvfile,dialect)
        reader = csv.DictReader(csvfile, delimiter=dialect.delimiter)
        # hash data with in dictionary and separate units
        columUnits = {}
        vesselData = {}

        for row in reader:
            Id = row.pop('Id')
            if Id == 'unit': columUnits = row
            else:
                Id = int(Id)
                vesselData[Id] = row

        variablesToDiscard = []
        for Id, data in vesselData.iteritems():
            #         polyChaos = {}
            for variable, variableValueStr in data.iteritems():
                # check if value is defined
                if variableValueStr not in ['', None]:
                    #find units
                    if '#' in columUnits[variable]:  #  '#' in variable or
                        nothing, variableUnit = columUnits[variable].split(
                            '#', 1)
                    # convert variables to corret unit and type
                    data[variable] = mXML.loadVariablesConversion(
                        variable, variableValueStr, variableUnit)
                else:
                    variablesToDiscard.append(
                        [Id,
                         variable])  # find out variables which have no values
        # remove variables which have no values
        for Id, variableToDiscard in variablesToDiscard:
            del vesselData[Id][variableToDiscard]

        return {'vesselData': vesselData}
示例#7
0
def readBCFromCSV(networkName, delimiter=';'):
    """
    Functions loads boundaryCondition data from \*.csv file inclusive polynomial chaos definitions

    Args:
        networkName (str): The name of the network
        delimiter (str): Delimiter (default = ';')

    Returns:
        VascularNetwork.boundaryConditionDict
            A description of the VascNw.BCD instance returned

        VascularNetwork.boundaryConditionPolyChaos
            A description of the VascNw.BCPC instance returned

    """

    boundaryCSVFile = mFPH.getFilePath('boundaryCSVFile',
                                       networkName,
                                       'xxx',
                                       'read',
                                       exception='Warning')
    reader = ccBC.csv.DictReader(open(boundaryCSVFile, 'rb'),
                                 delimiter=delimiter)

    # hash data with in dictionary and separate units
    columUnits = {}
    boundaryData = []
    for row in reader:
        if row['Id'] == 'unit': columUnits = row
        else: boundaryData.append(row)

    boundaryConditionPolyChaos = {}
    BCconditionData = {}
    for bcData in boundaryData:
        Id = int(bcData['Id'])
        # TODO: read write polynomial chaos variables
        # create class instance
        boundaryType = bcData['boundaryType']
        try:
            boundaryInstance = eval(nxml.bcTagsClassReferences[boundaryType])()
        except:
            'ERROR moduleCSV.readBCFromCSV: boundaryType <<{}>> does not exist'.format(
                boundaryType)
        boundaryDataDict = {'name': boundaryType}
        polyChaos = {}
        for variable, variableValueStr in bcData.iteritems():
            if variable in nxml.boundaryConditionElements[boundaryType]:
                try:
                    variableUnit = columUnits[variable]
                except:
                    variableUnit = None
                # save converted XML-value
                if variable == 'filePathName':
                    path = ''.join([boundaryCSVFile])
                    if path not in variableValueStr:
                        variableValueStr = variableValueStr.join([path, ''])
                print variableValueStr
                if variableValueStr != '':
                    try:
                        boundaryDataDict[
                            variable] = mXML.loadVariablesConversion(
                                variable, variableValueStr, variableUnit)
                    except:
                        pass
            if '-pC' in variable and variableValueStr != '':
                polyChaos['name'] = boundaryType
                variable, number = variable.split('-pC')
                if variable in polyChaos.keys():
                    polyChaos[variable] = ' '.join(
                        [polyChaos[variable], variableValueStr])
                else:
                    polyChaos[variable] = variableValueStr
        # convert polynomial chaos variables to corret unit and type
        if polyChaos != {}:
            for variable, variableValueStr in polyChaos.iteritems():
                try:
                    variableUnit = columUnits[variable].split('#', 1)
                    polyChaos[variable] = mXML.loadVariablesConversion(
                        variable,
                        variableValueStr,
                        variableUnit,
                        polychaos=True)
                except:
                    pass
            if Id not in boundaryConditionPolyChaos.keys():
                boundaryConditionPolyChaos[Id] = [polyChaos]
            else:
                boundaryConditionPolyChaos[Id].append(polyChaos)

        boundaryInstance.update(boundaryDataDict)

        if Id not in BCconditionData.keys():
            BCconditionData[Id] = [boundaryInstance]
        else:
            BCconditionData[Id].append(boundaryInstance)

    return BCconditionData, boundaryConditionPolyChaos
示例#8
0
def writeBCToCSV(networkName,
                 boundaryConditionDict,
                 boundaryConditionPolyChaos,
                 delimiter=';'):
    """
    Functions writes boundaryCondition data to *.csv file 
    
    input:
        networkName <string>
        boundaryConditionDict      <dict>  := boundaryConditionDict dict of class VascularNetwork {vesselId : boundaryConditionInstance} 
        boundaryConditionPolyChaos <dict>  := boundaryConditionPolyChaos dict of class VascularNetwork 
        delimiter   <string>  (default = ';')
    
    """
    # find all polychaos tags
    # TODO: read write polynomial chaos variables
    #     polyChaosTags = {}
    #     for id,bcPolyChaosList in boundaryConditionPolyChaos.iteritems():
    #         for bcPolyChaosDict in bcPolyChaosList:
    #             for variable,interval in bcPolyChaosDict.iteritems():
    #                 if variable != 'name': polyChaosTags[variable] = len(interval)

    # find all tags which are known for all boundary conditions
    tagsBCType1 = ['Id', 'boundaryType']
    tagsBCType2 = []
    for boundaryCondition, elementTags in nxml.boundaryConditionElements.iteritems(
    ):
        # None - bc for tag evaluation
        if 'None' not in boundaryCondition and '_' not in boundaryCondition:
            #check out type of BoundaryCondition:
            bcType = eval(nxml.bcTagsClassReferences[boundaryCondition])(
            ).getVariableValue('type')
            for elementTag in elementTags:
                if bcType == 1:
                    if elementTag not in tagsBCType1:
                        tagsBCType1.append(elementTag)
#                         if elementTag in polyChaosTags.keys():
#                             for count in range(polyChaosTags[elementTag]):
#                                 tagsBCType1.append(''.join([elementTag,'-pC',str(int(count)+1)]))
                elif bcType == 2:
                    if elementTag not in tagsBCType2:
                        tagsBCType2.append(elementTag)
#                         if elementTag in polyChaosTags.keys():
#                             for count in range(polyChaosTags[elementTag]):
#                                 tagsBCType2.append(''.join([elementTag,'-pC',str(int(count)+1)]))

    tagsBCType1.extend(tagsBCType2)
    tags = tagsBCType1

    boundaryCSVFile = mFPH.getFilePath('boundaryCSVFile', networkName, 'xxx',
                                       'write')
    writer = ccBC.csv.DictWriter(open(boundaryCSVFile, 'wb'),
                                 tags,
                                 delimiter=delimiter)

    # write Tag row
    firstRow = {}
    for item in tags:
        firstRow[item] = item
    writer.writerow(firstRow)

    # write unit row
    unitRow = {}
    for tag in tags:
        try:
            if '-pC' in tag:
                tagUnit = tag.split('-pC')[0]
                unitRow[tag] = ''.join(['#', variablesDict[tagUnit]['unitSI']])
            else:
                unitRow[tag] = ''.join(['#', variablesDict[tag]['unitSI']])
        except:
            unitRow[tag] = ''
    unitRow['Id'] = 'unit'
    writer.writerow(unitRow)

    ## fill out data of defined boundary conditions
    for Id, boundaryConditions in boundaryConditionDict.iteritems():
        for boundaryCondition in boundaryConditions:
            boundaryType = boundaryCondition.getVariableValue('name')
            dataRow = {}
            dataRow['Id'] = Id
            dataRow['boundaryType'] = boundaryType
            for variable in nxml.boundaryConditionElements[boundaryType]:
                dataRow[variable] = boundaryCondition.getVariableValue(
                    variable)


#             try:
#                 for bcPolyChaosDict in boundaryConditionPolyChaos[Id]:
#                     bcPolyChaosDict.pop('name')
#                     for variable,interval in bcPolyChaosDict.iteritems():
#                         for count,value in enumerate(interval):
#                             dataRow[''.join([variable,'-pC',str(int(count)+1)])] = value
#             except: pass

            writer.writerow(dataRow)