# Tools

MIKE+Py provides access to several MIKE+ data processing tools through the `mikeplus.tools` module. These tools allow you to perform common data manipulation and preparation tasks programmatically.


# <img src="data:image/svg+xml;base64,PHN2ZyBzdHlsZT0iaGVpZ2h0OjFlbTt3aWR0aDoxZW07dmVydGljYWwtYWxpZ246LTAuMTI1ZW07Zm9udC1zaXplOmluaGVyaXQ7b3ZlcmZsb3c6dmlzaWJsZTtwb3NpdGlvbjpyZWxhdGl2ZTsiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld2JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLSBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIGNsYXNzPSJnZC1pY29uIiBhcmlhLWhpZGRlbj0idHJ1ZSI+PHBhdGggZD0ibTE1IDEyLTkuMzczIDkuMzczYTEgMSAwIDAgMS0zLjAwMS0zTDEyIDkiIC8+PHBhdGggZD0ibTE4IDE1IDQtNCIgLz48cGF0aCBkPSJtMjEuNSAxMS41LTEuOTE0LTEuOTE0QTIgMiAwIDAgMSAxOSA4LjE3MnYtLjM0NGEyIDIgMCAwIDAtLjU4Ni0xLjQxNGwtMS42NTctMS42NTdBNiA2IDAgMCAwIDEyLjUxNiAzSDlsMS4yNDMgMS4yNDNBNiA2IDAgMCAxIDEyIDguNDg1VjEwbDIgMmgxLjE3MmEyIDIgMCAwIDEgMS40MTQuNTg2TDE4LjUgMTQuNSIgLz48L3N2Zz4=" class="gd-icon" /> Available Tools

The following tools are available:

- **[ImportTool](../reference/tools.ImportTool.md#mikeplus.tools.ImportTool)**: Imports data into your MIKE+ model using an XML configuration file.
- **[TopoRepairTool](../reference/tools.TopoRepairTool.md#mikeplus.tools.TopoRepairTool)**: Detects and repairs common topology issues in your network model.
- **[InterpolationTool](../reference/tools.InterpolationTool.md#mikeplus.tools.InterpolationTool)**: Interpolates and assigns attribute values between model features or from external data sources (e.g., DEMs).
- **[ConnectionRepairTool](../reference/tools.ConnectionRepairTool.md#mikeplus.tools.ConnectionRepairTool)**: Rebuilds connection tables, such as station connections and load point connections.
- **[CreateValvesFromPointsTool](../reference/tools.CreateValvesFromPointsTool.md#mikeplus.tools.CreateValvesFromPointsTool)**: Creates water distribution valves from a point shapefile, snapping each point to a nearby junction or pipe.
- **[DemandConnectionTool](../reference/tools.DemandConnectionTool.md#mikeplus.tools.DemandConnectionTool)**: Connects demand allocations in a water distribution model to junctions or pipes.
- **[DemandAggregationTool](../reference/tools.DemandAggregationTool.md#mikeplus.tools.DemandAggregationTool)**: Aggregates water distribution demand allocations to junction demands or pipe demand coefficients.
- **[CathSlopeLengthProcess](../reference/tools.CathSlopeLengthProcess.md#mikeplus.tools.CathSlopeLengthProcess)**: Calculates catchment slope and length.


# <img src="data:image/svg+xml;base64,PHN2ZyBzdHlsZT0iaGVpZ2h0OjFlbTt3aWR0aDoxZW07dmVydGljYWwtYWxpZ246LTAuMTI1ZW07Zm9udC1zaXplOmluaGVyaXQ7b3ZlcmZsb3c6dmlzaWJsZTtwb3NpdGlvbjpyZWxhdGl2ZTsiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld2JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLSBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIGNsYXNzPSJnZC1pY29uIiBhcmlhLWhpZGRlbj0idHJ1ZSI+PHBhdGggZD0iTTUgNWEyIDIgMCAwIDEgMy4wMDgtMS43MjhsMTEuOTk3IDYuOTk4YTIgMiAwIDAgMSAuMDAzIDMuNDU4bC0xMiA3QTIgMiAwIDAgMSA1IDE5eiIgLz48L3N2Zz4=" class="gd-icon" /> General Usage

To use a tool, first import it from `mikeplus.tools`. Then, create an instance of the tool, passing your opened [Database](../reference/Database.md#mikeplus.Database) object to its constructor. [ImportTool](../reference/tools.ImportTool.md#mikeplus.tools.ImportTool) also takes the path of its XML configuration file, before the database.

``` python
from mikeplus.tools import InterpolationTool
# Assuming 'db' is your opened mikeplus.Database object
interpolation_tool = InterpolationTool(db)
```

Once you have a tool instance, you can call its methods to perform specific actions.


# <img src="data:image/svg+xml;base64,PHN2ZyBzdHlsZT0iaGVpZ2h0OjFlbTt3aWR0aDoxZW07dmVydGljYWwtYWxpZ246LTAuMTI1ZW07Zm9udC1zaXplOmluaGVyaXQ7b3ZlcmZsb3c6dmlzaWJsZTtwb3NpdGlvbjpyZWxhdGl2ZTsiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld2JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLSBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIGNsYXNzPSJnZC1pY29uIiBhcmlhLWhpZGRlbj0idHJ1ZSI+PHBhdGggZD0ibTE2IDE4IDYtNi02LTYiIC8+PHBhdGggZD0ibTggNi02IDYgNiA2IiAvPjwvc3ZnPg==" class="gd-icon" /> Examples

Here are a couple of examples to illustrate how to use these tools.


## Import Tool

The [ImportTool](../reference/tools.ImportTool.md#mikeplus.tools.ImportTool) can import data into your MIKE+ model using an XML configuration file. For instance, to import data from an XML file:

``` python
from mikeplus.tools import ImportTool

import_tool = ImportTool("path/to/your/xml/file.xml", db)
import_tool.run()
```


## InterpolationTool

The [InterpolationTool](../reference/tools.InterpolationTool.md#mikeplus.tools.InterpolationTool) can assign values to features based on proximity or DEM data. For instance, to interpolate the `GroundLevel` for nodes in the `msm_Node` table from a DEM file:

``` python
# interpolation_tool = InterpolationTool(db) # Instantiated as above
tool_parameters = {
    "target_Db_Name": "msm_Node",
    "target_attribute": "GroundLevel",
    "raster_file": "path/to/your/dem.dfs2", # Replace with actual path
    "item_number": 1
}
interpolation_tool.interpolate_from_DEM(**tool_parameters)
```

To interpolate only some elements, pass their MUIDs. `only_null_values=False` overwrites existing values:

``` python
interpolation_tool.interpolate_from_DEM(
    **tool_parameters,
    only_null_values=False,
    muids=["Node_1", "Node_2"],
)
```

Every [InterpolationTool](../reference/tools.InterpolationTool.md#mikeplus.tools.InterpolationTool) method takes `muids`; by default they process all elements of the target table.


## TopoRepairTool

The [TopoRepairTool](../reference/tools.TopoRepairTool.md#mikeplus.tools.TopoRepairTool) helps clean up network topology. Every repair operation of its [run](../reference/Database.md#mikeplus.Database.run) method is enabled by default, so to only delete unlinked nodes and dissolve overlapping nodes, turn the others off:

``` python
from mikeplus.tools import TopoRepairTool

repair_tool = TopoRepairTool(db)
repair_tool.run(
    delete_unLink_node_Link=True,
    dissolve_overlap_node=True,
    correct_link_connection=False,
    search_junction_connection=False,
    create_junction_connection=False,
    split_link_on_tjunction=False,
    add_missing_zones=False,
)
```

[run](../reference/Database.md#mikeplus.Database.run) only repairs CS_MIKE1D and WD_EPANET models; for any other active model it does nothing.


## CreateValvesFromPointsTool

The [CreateValvesFromPointsTool](../reference/tools.CreateValvesFromPointsTool.md#mikeplus.tools.CreateValvesFromPointsTool) adds a valve to a water distribution model for each point in a shapefile. A point near a junction gets a valve at that junction; otherwise the nearest pipe is split at the point. The `*_field` arguments name the shapefile columns to read valve attributes from. The points must be in the model's coordinate system.

``` python
from mikeplus.tools import CreateValvesFromPointsTool

tool = CreateValvesFromPointsTool(db)
messages = tool.run(
    "path/to/valves.shp",
    search_radius=5.0,  # how far to look for a junction or pipe
    valve_length=1.0,
    muid_field="ID",
    type_field="VTYPE",  # 1-6, or PRV, PSV, PBV, FCV, TCV or GPV
    status_field="STATUS",  # 0 regulating, 1 open, 2 closed
)
print(messages[0])  # how many valves were created out of how many points
```

The remaining messages explain each point that was skipped, for example because no pipe was within the search radius.


## DemandConnectionTool

The [DemandConnectionTool](../reference/tools.DemandConnectionTool.md#mikeplus.tools.DemandConnectionTool) does what the MIKE+ connection tool does for demand allocations: it connects each point in `mw_DemAlloc` to a junction or a pipe, sets its `JunctionID` or `PipeID`, and draws the connection line in `mw_DemAllocConn`. To connect every demand allocation to the nearest junction within 50 m:

``` python
from mikeplus.tools import DemandConnectionTool

tool = DemandConnectionTool(db)
tool.run("nearest_junction", max_distance=50.0)
```

The other methods are `"junction_by_nearest_pipe"`, `"junction_by_pipe_id"` and `"nearest_pipe"`. You can limit the run to some demand allocations with `demand_ids`, and the candidate targets with `junction_ids`, `pipe_ids`, `max_diameter` or a SQL [where](../reference/queries.BaseQuery.md#mikeplus.queries.BaseQuery.where) condition:

``` python
tool.run(
    "nearest_pipe",
    demand_ids=["Demand_1", "Demand_2"],
    max_distance=100.0,
    max_diameter=300.0,
)
```

`max_distance` does not apply to `"junction_by_pipe_id"`, `max_diameter` and `pipe_ids` apply only to the pipe-based methods, and `junction_ids` only to `"nearest_junction"`; passing one to a method it does not apply to raises `ValueError`.

After a run, a demand allocation connected to a junction has no `PipeID`, and one connected to a pipe has no `JunctionID`, so switching methods leaves no stale connection behind. A demand allocation for which no target is found loses any connection it had. If MIKE+ fails, the tool raises [mikeplus.DatabaseError](../reference/DatabaseError.md#mikeplus.DatabaseError); demand allocations processed before the failure keep their new connections.


## DemandAggregationTool

The [DemandAggregationTool](../reference/tools.DemandAggregationTool.md#mikeplus.tools.DemandAggregationTool) turns the demand allocations in `mw_DemAlloc` into junction demands in `mw_MDemand`, or into pipe demand coefficients in `mw_Pipe`. Each method aggregates all demand allocations, or only those whose MUIDs you pass.

``` python
from mikeplus.tools import DemandAggregationTool

tool = DemandAggregationTool(db)

# One junction demand per category and pattern, replacing earlier aggregations
tool.aggregate_to_node_demands(reset_existing=True)

# One junction demand per junction, with a fixed category and pattern
tool.aggregate_to_node_demands(keep_categories=False, category="Total", pattern="Daily")

# One junction demand per demand allocation, summing nothing
tool.assign_to_multiple_demands(reset_existing=True)

# Sum two allocations into the pipes' second demand coefficient
tool.aggregate_to_pipe_coefficients(["Alloc_1", "Alloc_2"], coefficient=2)
```

For the junction methods, `reset_existing=True` deletes only the junction demands that earlier aggregations wrote; demands entered any other way are kept. For [aggregate_to_pipe_coefficients](../reference/tools.DemandAggregationTool.md#mikeplus.tools.DemandAggregationTool.aggregate_to_pipe_coefficients), it sets the coefficient to 0 on pipes with no aggregated allocation.

An empty list of MUIDs does nothing, not even the reset. Unknown MUIDs raise a `ValueError`. As in MIKE+, a sum that includes an allocation with a NULL demand is NULL.


## <img src="data:image/svg+xml;base64,PHN2ZyBzdHlsZT0iaGVpZ2h0OjFlbTt3aWR0aDoxZW07dmVydGljYWwtYWxpZ246LTAuMTI1ZW07Zm9udC1zaXplOmluaGVyaXQ7b3ZlcmZsb3c6dmlzaWJsZTtwb3NpdGlvbjpyZWxhdGl2ZTsiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld2JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLSBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIGNsYXNzPSJnZC1pY29uIiBhcmlhLWhpZGRlbj0idHJ1ZSI+PHBhdGggZD0iTTEyIDd2MTQiIC8+PHBhdGggZD0iTTMgMThhMSAxIDAgMCAxLTEtMVY0YTEgMSAwIDAgMSAxLTFoNWE0IDQgMCAwIDEgNCA0IDQgNCAwIDAgMSA0LTRoNWExIDEgMCAwIDEgMSAxdjEzYTEgMSAwIDAgMS0xIDFoLTZhMyAzIDAgMCAwLTMgMyAzIDMgMCAwIDAtMy0zeiIgLz48L3N2Zz4=" class="gd-icon" /> Further Information

For detailed information on all available parameters and methods for each tool, please consult the MIKE+ software documentation or the specific API reference for `mikeplus`.
