def main():
    """main program"""
    arguments = parse_args()

    # Read mdu file
    mdudir = os.path.dirname(arguments.mdu)
    mduparser = MduParser(defaults=DEFAULTS)
    mduparser.readfp(open(arguments.mdu))
    networkfilename = mduparser.get('geometry', 'NetworkFile')

    # Split up the old network file
    lines = open(os.path.join(mdudir, networkfilename)).readlines()
    records = [line.split() for line in lines]
    breaks = [i for i, record in enumerate(records) if record == ['-1']]
    nodes, definitions, branches = (records[:breaks[0]],
                                    records[breaks[0] + 1:breaks[1]],
                                    records[breaks[1] + 1:])
    # Create tables
    (nodesdf, definitionsdf, branchesdf) = make_tables(nodes, definitions,
                                                       branches)
    # Merge them
    crosssectionsdf = merge_tables(nodesdf, definitionsdf, branchesdf)

    # Some manual changes

    # rectangles all the way down
    definitionsdf["type"] = "rectangle"

    # Add some friction
    frictcoef = mduparser.getfloat('physics', 'FrictCoef')
    fricttype = mduparser.getint('physics', 'FrictType')
    crosssectionsdf['frictiontype'] = fricttype
    crosssectionsdf['frictionvalue'] = frictcoef

    # Write out the definitions
    config = MultiSectionConfigParser()
    for i, definition in definitionsdf.iterrows():
        config.add_section('Definition')
        for key, value in definition.iteritems():
            config.set('Definition', key, str(value))
    with open(os.path.join(mdudir, arguments.definition), 'w') as f:
        config.write(f)

    # and write the crosssections
    config = MultiSectionConfigParser()
    for i, crosssection in crosssectionsdf.sort('id').iterrows():
        config.add_section('CrossSection')
        for key, value in crosssection.iteritems():
            config.set('CrossSection', key, str(value))
    with open(os.path.join(mdudir, arguments.crosssection), 'w') as f:
        config.write(f)

    # and write the network
    lines = []
    for i, node in nodesdf.iterrows():
        lines.append("{id} {type} {x} {y}".format(**node))
    lines.append("-1")
    for i, branch in branchesdf.iterrows():
        if int(branch['type']) == 0:
            lines.append("{id} {type} {from} {to}".format(**branch))
        else:
            lines.append("{id} {type} {from} {to} {npt}".format(**branch))
    with open(arguments.network, 'w') as networkfile:
        networkfile.writelines(line + "\n" for line in lines)

    commentedmdu = MduParserKeepComments()
    commentedmdu.readfp(open(arguments.mdu))
    commentedmdu.set("geometry", "CrossSectionFile", arguments.crosssection)
    commentedmdu.set("geometry", "CrossSectionDefinitionFile",
                     arguments.definition)
    with open(arguments.mdu, 'w') as mdufile:
        comment = "# mdu file changed by {} at {}".format(
            sys.argv[0], datetime.datetime.now())
        mdufile.write(comment + "\n")
        commentedmdu.write(mdufile)
Exemple #2
0
def main():
    """Change mdu file to new version >=2.0 MDU File Format"""
    arguments = parse_args()

    # Read mdu file

    commentedmdu = MduParserKeepComments()
    commentedmdu.readfp(open(arguments.mdu))

    # Check current version:
    try:
        inputversion = commentedmdu.get("model", "FileFormatVersion")
    except ConfigParser.NoOptionError:
        inputversion = "0.0"

    match = re.match(r"""\d+""", inputversion)
    if match is not None:
        inputmajorv = int(match.group())
    else:
        inputmajorv = 0

    outputversion = "2.2"
    outputmajorv = int(float(outputversion))

    if inputmajorv >= outputmajorv:
        logger.info("Input file %s is already recent enough: " +
                    "major version %s >= %s. Exiting.",
                    arguments.mdu, inputmajorv, outputmajorv)
        return

    # Input file is indeed old, now proceed with the actual conversion.
    logger.info("Converting {} -> {}...".format(inputversion, outputversion))

    commentedmdu.set("model", "FileFormatVersion", outputversion)

    # Define the renamings
    changes = collections.OrderedDict([
        (("geometry", "ManholeFile"),
         ("external forcing", "ManholeFile")),
        (("geometry", "FloodIniFile"),
         ("initialization", "FloodIniFile")),
        (("initialization", "WaterLevelFile"),
         ("initialization", "WaterLevelIniFile")),
        (("initialization", "FloodWaterLevel"),
         ("defaults", "FloodWaterLevel")),
        (("initialization", "FloodLevelAbsolute"),
         ("defaults", "FloodLevelAbsolute")),
        (("initialization", "BathymetryIncrement"),
         ("defaults", "BathymetryIncrement")),
        (("initialization", "BathIncAbsolute"),
         ("defaults", "BathIncAbsolute")),
        (("initialization", "InfiltrationRateNew"),
         ("defaults", "InfiltrationRateNew")),
        (("initialization", "Rainfall"),
         ("defaults", "RainfallCloudAmount")),
        (("initialization", "RainfallCloudDiameter"),
         ("defaults", "RainfallCloudDiameter")),
        (("Ground Water", ""),
         ("hydrology", "")),
        (("hydrology", "GroundwaterLevelFile"),
         ("hydrology", "GroundWaterLevelIniFile")),
        (("hydrology", "permeability_x"),
         ("hydrology", "HydraulicConductivity_X")),
        (("hydrology", "permeability_y"),
         ("hydrology", "HydraulicConductivity_Y")),
        (("hydrology", "GroundwaterLevelFile"),
         ("hydrology", "GroundWaterLevelIniFile")),
        (("output", "LogOut"),
         ("display", "RedrawEvery")),
        (("output", "SaveHardCopy"),
         ("display", "SaveHardCopy")),
        (("output", "showGrid"),
         ("display", "showGrid")),
        (("output", "showLinks"),
         ("display", "showLinks")),
        (("output", "Show1DNetwork"),
         ("display", "Show1DNetwork")),
        (("output", "ShowStructures"),
         ("display", "ShowStructures")),
        (("output", "ShowNetworkCRS"),
         ("display", "ShowNetworkCRS")),
        (("output", "ShowNodNumbers"),
         ("display", "ShowNodNumbers")),
        (("output", "Show1DNodNum"),
         ("display", "Show1DNodNum")),
        (("colors", "showInterception"),
         ("display", "showInterception")),
        (("colors", "ShowUZslice"),
         ("display", "ShowUZslice")),
        (("colors", "sliceUZcolor"),
         ("display", "sliceUZcolor")),
        (("colors", "showChanSelect"),
         ("display", "showChanSelect")),
        (("colors", "showChanMinY"),
         ("display", "showChanMinY")),
        (("colors", "showChanMaxY"),
         ("display", "showChanMaxY"))
    ])

    # Perform the renamings
    for (sec1, opt1), (sec2, opt2) in changes.items():
        if opt1 == "" and opt2 == "":
            rename_section(commentedmdu, sec1, sec2)
        else:
            opt_rename(commentedmdu, sec1, sec2, opt1, opt2)

    # Write the new MDU file
    with open(arguments.mdu, 'w') as mdufile:
        comment = "# mdu file changed by {} at {}".format(
            sys.argv[0],
            datetime.datetime.now()
        )
        mdufile.write(comment + "\n")
        commentedmdu.write(mdufile)
def main():
    """main program"""
    arguments = parse_args()

    # Read mdu file
    mdudir = os.path.dirname(arguments.mdu)
    mduparser = MduParser(defaults=DEFAULTS)
    mduparser.readfp(open(arguments.mdu))
    networkfilename = mduparser.get('geometry', 'NetworkFile')

    # Split up the old network file
    lines = open(os.path.join(mdudir, networkfilename)).readlines()
    records = [line.split() for line in lines]
    breaks = [i for i, record in enumerate(records) if record == ['-1']]
    nodes, definitions, branches = (records[:breaks[0]],
                                    records[breaks[0]+1:breaks[1]],
                                    records[breaks[1]+1:])
    # Create tables
    (nodesdf,
     definitionsdf,
     branchesdf) = make_tables(nodes, definitions, branches)
    # Merge them
    crosssectionsdf = merge_tables(nodesdf,
                                   definitionsdf,
                                   branchesdf)

    # Some manual changes

    # rectangles all the way down
    definitionsdf["type"] = "rectangle"

    # Add some friction
    frictcoef = mduparser.getfloat('physics', 'FrictCoef')
    fricttype = mduparser.getint('physics', 'FrictType')
    crosssectionsdf['frictiontype'] = fricttype
    crosssectionsdf['frictionvalue'] = frictcoef

    # Write out the definitions
    config = MultiSectionConfigParser()
    for i, definition in definitionsdf.iterrows():
        config.add_section('Definition')
        for key, value in definition.iteritems():
            config.set('Definition', key, str(value))
    with open(os.path.join(mdudir, arguments.definition), 'w') as f:
        config.write(f)

    # and write the crosssections
    config = MultiSectionConfigParser()
    for i, crosssection in crosssectionsdf.sort('id').iterrows():
        config.add_section('CrossSection')
        for key, value in crosssection.iteritems():
            config.set('CrossSection', key, str(value))
    with open(os.path.join(mdudir, arguments.crosssection), 'w') as f:
        config.write(f)

    # and write the network
    lines = []
    for i, node in nodesdf.iterrows():
        lines.append("{id} {type} {x} {y}".format(**node))
    lines.append("-1")
    for i, branch in branchesdf.iterrows():
        if int(branch['type']) == 0:
            lines.append("{id} {type} {from} {to}".format(**branch))
        else:
            lines.append("{id} {type} {from} {to} {npt}".format(**branch))
    with open(arguments.network, 'w') as networkfile:
        networkfile.writelines(line + "\n" for line in lines)

    commentedmdu = MduParserKeepComments()
    commentedmdu.readfp(open(arguments.mdu))
    commentedmdu.set("geometry",
                     "CrossSectionFile",
                     arguments.crosssection)
    commentedmdu.set("geometry",
                     "CrossSectionDefinitionFile",
                     arguments.definition)
    with open(arguments.mdu, 'w') as mdufile:
        comment = "# mdu file changed by {} at {}".format(
            sys.argv[0],
            datetime.datetime.now()
        )
        mdufile.write(comment + "\n")
        commentedmdu.write(mdufile)
Exemple #4
0
def main():
    """main program"""
    arguments = parse_args()

    # Read mdu file
    # mdudir = os.path.dirname(arguments.mdu)
    # mduparser = MduParser(defaults=DEFAULTS)
    # mduparser.readfp(open(arguments.mdu))
    commentedmdu = MduParserKeepComments()
    commentedmdu.readfp(open(arguments.mdu))

    commentedmdu.set("model", "FileFormatVersion", "2.1")

    # http://docs.python.org/2/library/collections.html#ordereddict-objects
    # changes = collections.OrderedDict([
    #     (("geometry", "ManholeFile"),
    #      ("external forcing", "ManholeFile")),
    #     (("geometry", "FloodIniFile"),
    #      ("initialization", "FloodIniFile")),
    #     (("initialization", "WaterLevelFile"),
    #      ("initialization", "WaterLevelIniFile")),
    #     (("initialization", "FloodWaterLevel"),
    #      ("defaults", "FloodWaterLevel")),
    #     (("initialization", "FloodLevelAbsolute"),
    #      ("defaults", "FloodLevelAbsolute")),
    #     (("initialization", "BathymetryIncrement"),
    #      ("defaults", "BathymetryIncrement")),
    #     (("initialization", "BathIncAbsolute"),
    #      ("defaults", "BathIncAbsolute")),
    #     (("initialization", "InfiltrationRateNew"),
    #      ("defaults", "InfiltrationRateNew")),
    #     (("initialization", "Rainfall"),
    #      ("defaults", "RainfallCloudAmount")),
    #     (("initialization", "RainfallCloudDiameter"),
    #      ("defaults", "RainfallCloudDiameter")),
    #     (("Ground Water", ""),
    #      ("hydrology", "")),
    #     (("hydrology", "GroundwaterLevelFile"),
    #      ("hydrology", "GroundWaterLevelIniFile")),
    #     (("hydrology", "permability_x"),
    #      ("hydrology", "HydraulicConductivity_X")),
    #     (("hydrology", "permability_y"),
    #      ("hydrology", "HydraulicConductivity_Y")),
    #     (("hydrology", "GroundwaterLevelFile"),
    #      ("hydrology", "GroundWaterLevelIniFile")),
    #     (("output", "LogOut"),
    #      ("display", "RedrawEvery")),
    #     (("output", "SaveHardCopy"),
    #      ("display", "SaveHardCopy")),
    #     (("output", "showGrid"),
    #      ("display", "showGrid")),
    #     (("output", "showLinks"),
    #      ("display", "showLinks")),
    #     (("output", "Show1DNetwork"),
    #      ("display", "Show1DNetwork")),
    #     (("output", "ShowStructures"),
    #      ("display", "ShowStructures")),
    #     (("output", "ShowNetworkCRS"),
    #      ("display", "ShowNetworkCRS")),
    #     (("output", "ShowNodNumbers"),
    #      ("display", "ShowNodNumbers")),
    #     (("output", "Show1DNodNum"),
    #      ("display", "Show1DNodNum")),
    #     (("colors", "showInterception"),
    #      ("display", "showInterception")),
    #     (("colors", "ShowUZslice"),
    #      ("display", "ShowUZslice")),
    #     (("colors", "sliceUZcolor"),
    #      ("display", "sliceUZcolor")),
    #     (("colors", "showChanSelect"),
    #      ("display", "showChanSelect")),
    #     (("colors", "showChanMinY"),
    #      ("display", "showChanMinY")),
    #     (("colors", "showChanMaxY"),
    #      ("display", "showChanMaxY"))
    # ])

    # todo: for loop across dict/or list? To be processed in order!
    # foreach
    #    if key1 == "" and key2 == "":
    #       rename_section(commentedmdu, sec1, sec2)
    #    else
    #       opt_rename(commentedmdu, sec1, sec2, key1, key2)
    #        # TODO:  need to catch NoOptionError from config.get??

    with open(arguments.mdu, 'w') as mdufile:
        comment = "# mdu file changed by {} at {}".format(
            sys.argv[0],
            datetime.datetime.now()
        )
        mdufile.write(comment + "\n")
        commentedmdu.write(mdufile)