├── .gitattributes
├── src
└── rtctools_channel_flow
│ ├── modelica
│ └── Deltares
│ │ ├── ChannelFlow
│ │ ├── Salt
│ │ │ ├── package.order
│ │ │ ├── package.mo
│ │ │ └── Elements
│ │ │ │ ├── package.mo
│ │ │ │ ├── package.order
│ │ │ │ ├── QMForcing.mo
│ │ │ │ ├── SaltyLinearReservoir.mo
│ │ │ │ ├── SaltyLinearReservoirBnd.mo
│ │ │ │ ├── SaltyPartialReservoirBnd.mo
│ │ │ │ ├── SaltyPartialReservoir.mo
│ │ │ │ ├── SaltyPartialStorage.mo
│ │ │ │ ├── NodeSalty.mo
│ │ │ │ └── SubstanceControlledStructure.mo
│ │ ├── Media
│ │ │ ├── package.order
│ │ │ ├── package.mo
│ │ │ ├── FreshWater.mo
│ │ │ └── SalineWater.mo
│ │ ├── Hydraulic
│ │ │ ├── Storage
│ │ │ │ ├── package.order
│ │ │ │ ├── Internal
│ │ │ │ │ ├── package.order
│ │ │ │ │ ├── package.mo
│ │ │ │ │ └── PartialStorage.mo
│ │ │ │ ├── package.mo
│ │ │ │ └── Linear.mo
│ │ │ ├── BoundaryConditions
│ │ │ │ ├── package.order
│ │ │ │ ├── package.mo
│ │ │ │ ├── Level.mo
│ │ │ │ └── Discharge.mo
│ │ │ ├── Reservoir
│ │ │ │ ├── package.order
│ │ │ │ ├── package.mo
│ │ │ │ ├── Internal
│ │ │ │ │ ├── package.order
│ │ │ │ │ ├── package.mo
│ │ │ │ │ ├── PartialReservoir.mo
│ │ │ │ │ ├── PartialHomotopicVolume.mo
│ │ │ │ │ └── PartialHomotopicPower.mo
│ │ │ │ ├── HomotopicPower.mo
│ │ │ │ ├── HomotopicVolume.mo
│ │ │ │ └── Linear.mo
│ │ │ ├── Branches
│ │ │ │ ├── Internal
│ │ │ │ │ ├── package.order
│ │ │ │ │ ├── package.mo
│ │ │ │ │ ├── BottomFrictionCoefficient.mo
│ │ │ │ │ └── PartialHomotopic.mo
│ │ │ │ ├── package.mo
│ │ │ │ ├── package.order
│ │ │ │ ├── Linear.mo
│ │ │ │ ├── HomotopicLinear.mo
│ │ │ │ ├── HomotopicTrapezoidal.mo
│ │ │ │ └── LinearisedSV.mo
│ │ │ ├── Structures
│ │ │ │ ├── package.order
│ │ │ │ ├── package.mo
│ │ │ │ ├── Pump.mo
│ │ │ │ ├── PumpUserEquationdH.mo
│ │ │ │ └── DischargeControlledStructure.mo
│ │ │ ├── package.mo
│ │ │ └── package.order
│ │ ├── Interfaces
│ │ │ ├── Adaptors
│ │ │ │ ├── package.order
│ │ │ │ ├── package.mo
│ │ │ │ ├── HQToQOut.mo
│ │ │ │ └── QInToHQ.mo
│ │ │ ├── package.order
│ │ │ ├── package.mo
│ │ │ ├── QInPort.mo
│ │ │ ├── QOutPort.mo
│ │ │ ├── HQPort.mo
│ │ │ └── HQCMPort.mo
│ │ ├── SimpleRouting
│ │ │ ├── Nodes
│ │ │ │ ├── Internal
│ │ │ │ │ ├── package.order
│ │ │ │ │ ├── package.mo
│ │ │ │ │ └── PartialNode.mo
│ │ │ │ ├── package.order
│ │ │ │ ├── package.mo
│ │ │ │ ├── NodeHQPort.mo
│ │ │ │ └── Node.mo
│ │ │ ├── Storage
│ │ │ │ ├── package.order
│ │ │ │ ├── package.mo
│ │ │ │ ├── QSI.mo
│ │ │ │ ├── QSO.mo
│ │ │ │ └── Storage.mo
│ │ │ ├── BoundaryConditions
│ │ │ │ ├── package.order
│ │ │ │ ├── package.mo
│ │ │ │ ├── Terminal.mo
│ │ │ │ └── Inflow.mo
│ │ │ ├── Reservoir
│ │ │ │ ├── package.order
│ │ │ │ ├── package.mo
│ │ │ │ ├── Reservoir_turbine_out.mo
│ │ │ │ ├── Reservoir.mo
│ │ │ │ └── Reservoir_multi_io.mo
│ │ │ ├── Structures
│ │ │ │ ├── package.order
│ │ │ │ ├── package.mo
│ │ │ │ ├── Pump.mo
│ │ │ │ ├── DischargeControlledStructure.mo
│ │ │ │ └── RunOfRiverHydropowerComplexFixedHead.mo
│ │ │ ├── package.order
│ │ │ ├── Branches
│ │ │ │ ├── package.order
│ │ │ │ ├── package.mo
│ │ │ │ ├── Internal
│ │ │ │ │ ├── KNAlpha.mo
│ │ │ │ │ ├── package.mo
│ │ │ │ │ ├── KNNonlinearityParameter.mo
│ │ │ │ │ ├── MuskingumWeightingFactor.mo
│ │ │ │ │ ├── KNNonlinearityParameterNumerator.mo
│ │ │ │ │ ├── KNNonlinearityParameterDenominator.mo
│ │ │ │ │ ├── package.order
│ │ │ │ │ ├── PartialKNNonlinear.mo
│ │ │ │ │ └── PartialMuskingum.mo
│ │ │ │ ├── Muskingum.mo
│ │ │ │ ├── Delay.mo
│ │ │ │ ├── EmptyBranch.mo
│ │ │ │ ├── Steady.mo
│ │ │ │ ├── Integrator.mo
│ │ │ │ ├── KNNonlinear.mo
│ │ │ │ └── LagAndK.mo
│ │ │ └── package.mo
│ │ ├── package.mo
│ │ ├── Internal
│ │ │ ├── Functions
│ │ │ │ ├── package.order
│ │ │ │ ├── package.mo
│ │ │ │ ├── SmoothSwitch.mo
│ │ │ │ ├── SmoothAbs.mo
│ │ │ │ ├── SmoothMax.mo
│ │ │ │ └── SmoothMin.mo
│ │ │ ├── package.mo
│ │ │ ├── package.order
│ │ │ ├── QSI.mo
│ │ │ ├── QSO.mo
│ │ │ ├── Volume.mo
│ │ │ ├── QForcing.mo
│ │ │ ├── HQOnePort.mo
│ │ │ ├── QLateral.mo
│ │ │ ├── QSISO.mo
│ │ │ ├── Reservoir.mo
│ │ │ └── HQTwoPort.mo
│ │ └── package.order
│ │ ├── Constants.mo
│ │ └── package.mo
│ ├── __init__.py
│ ├── calculate_parameters.py
│ ├── channel_flow_parameter_setting.py
│ └── _version.py
├── .gitignore
├── AUTHORS
├── MANIFEST.in
├── README
├── .pre-commit-config.yaml
├── setup.cfg
├── .gitlab-ci.yml
├── .github
└── workflows
│ └── ci.yml
├── setup.py
├── COPYING.LESSER
└── COPYING
/.gitattributes:
--------------------------------------------------------------------------------
1 | src/rtctools_channel_flow/_version.py export-subst
2 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Salt/package.order:
--------------------------------------------------------------------------------
1 | Elements
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # pycache files
2 | __pycache__
3 |
4 | # Distribution & Packaging
5 | *.eggs
6 | *.egg-info
7 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Media/package.order:
--------------------------------------------------------------------------------
1 | FreshWater
2 | SalineWater
3 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Storage/package.order:
--------------------------------------------------------------------------------
1 | Internal
2 | Linear
3 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Storage/Internal/package.order:
--------------------------------------------------------------------------------
1 | PartialStorage
2 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Interfaces/Adaptors/package.order:
--------------------------------------------------------------------------------
1 | HQToQOut
2 | QInToHQ
3 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Nodes/Internal/package.order:
--------------------------------------------------------------------------------
1 | PartialNode
2 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Storage/package.order:
--------------------------------------------------------------------------------
1 | QSI
2 | QSO
3 | Storage
4 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/BoundaryConditions/package.order:
--------------------------------------------------------------------------------
1 | Level
2 | Discharge
3 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/BoundaryConditions/package.order:
--------------------------------------------------------------------------------
1 | Inflow
2 | Terminal
3 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Nodes/package.order:
--------------------------------------------------------------------------------
1 | Internal
2 | Node
3 | NodeHQPort
4 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares;
2 |
3 | package ChannelFlow
4 | end ChannelFlow;
--------------------------------------------------------------------------------
/AUTHORS:
--------------------------------------------------------------------------------
1 | Matthijs den Toom (Deltares)
2 | Jorn Baayen (KISTERS, formerly Deltares)
3 | Jesse VanderWees (KISTERS, formerly Deltares)
4 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Media/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow;
2 |
3 | package Media
4 | end Media;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Salt/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow;
2 |
3 | package Salt
4 | end Salt;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Interfaces/package.order:
--------------------------------------------------------------------------------
1 | HQPort
2 | QInPort
3 | QOutPort
4 | Adaptors
5 | HQCMPort
6 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Reservoir/package.order:
--------------------------------------------------------------------------------
1 | Internal
2 | Linear
3 | HomotopicVolume
4 | HomotopicPower
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Internal/Functions/package.order:
--------------------------------------------------------------------------------
1 | SmoothMax
2 | SmoothMin
3 | SmoothAbs
4 | SmoothSwitch
5 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/package.order:
--------------------------------------------------------------------------------
1 | Media
2 | Interfaces
3 | Internal
4 | SimpleRouting
5 | Hydraulic
6 | Salt
7 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Branches/Internal/package.order:
--------------------------------------------------------------------------------
1 | BottomFrictionCoefficient
2 | PartialHomotopic
3 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Structures/package.order:
--------------------------------------------------------------------------------
1 | DischargeControlledStructure
2 | Pump
3 | PumpUserEquationdH
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow;
2 |
3 | package Hydraulic
4 | end Hydraulic;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Reservoir/package.order:
--------------------------------------------------------------------------------
1 | Reservoir
2 | Reservoir_turbine_out
3 | Reservoir_multi_io
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | recursive-include src/rtctools_channel_flow/modelica/Deltares *
2 | include versioneer.py
3 | include src/rtctools_channel_flow/_version.py
4 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/package.order:
--------------------------------------------------------------------------------
1 | Branches
2 | Storage
3 | BoundaryConditions
4 | Structures
5 | Reservoir
6 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Salt/Elements/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Salt;
2 |
3 | package Elements
4 | end Elements;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/__init__.py:
--------------------------------------------------------------------------------
1 | # Get version.
2 | from ._version import get_versions
3 |
4 | __version__ = get_versions()["version"]
5 | del get_versions
6 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Branches/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic;
2 |
3 | package Branches
4 | end Branches;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Storage/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic;
2 |
3 | package Storage
4 | end Storage;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Internal/Functions/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Internal;
2 |
3 | package Functions
4 | end Functions;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Reservoir/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic;
2 |
3 | package Reservoir
4 | end Reservoir;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Storage/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting;
2 |
3 | package Storage
4 | end Storage;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Structures/package.order:
--------------------------------------------------------------------------------
1 | DischargeControlledStructure
2 | Pump
3 | RunOfRiverHydropowerComplexFixedHead
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/package.order:
--------------------------------------------------------------------------------
1 | BoundaryConditions
2 | Branches
3 | Nodes
4 | Reservoir
5 | Storage
6 | Structures
7 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Branches/package.order:
--------------------------------------------------------------------------------
1 | Internal
2 | Linear
3 | LinearisedSV
4 | HomotopicLinear
5 | HomotopicTrapezoidal
6 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Reservoir/Internal/package.order:
--------------------------------------------------------------------------------
1 | PartialReservoir
2 | PartialHomotopicPower
3 | PartialHomotopicVolume
4 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Structures/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic;
2 |
3 | package Structures
4 | end Structures;
5 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Reservoir/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting;
2 |
3 | package Reservoir
4 | end Reservoir;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Reservoir/Internal/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic.Reservoir;
2 |
3 | package Internal
4 | end Internal;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Structures/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting;
2 |
3 | package Structures
4 | end Structures;
5 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Branches/Internal/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic.Branches;
2 |
3 | package Internal
4 | end Internal;
5 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/BoundaryConditions/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic;
2 |
3 | package BoundaryConditions
4 | end BoundaryConditions;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Branches/package.order:
--------------------------------------------------------------------------------
1 | Internal
2 | Delay
3 | EmptyBranch
4 | Integrator
5 | KNNonlinear
6 | Muskingum
7 | Steady
8 | LagAndK
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Interfaces/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow;
2 |
3 | package Interfaces
4 | extends Modelica.Icons.InterfacesPackage;
5 | end Interfaces;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Internal/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow;
2 |
3 | package Internal "Partial models"
4 | extends Modelica.Icons.Package;
5 | end Internal;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Media/FreshWater.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Media;
2 |
3 | record FreshWater
4 | constant Integer n_substances = 0;
5 | end FreshWater;
6 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Media/SalineWater.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Media;
2 |
3 | record SalineWater
4 | constant Integer n_substances = 1;
5 | end SalineWater;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Nodes/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting;
2 |
3 | package Nodes "Nodes for simple routing models"
4 | end Nodes;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Branches/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting;
2 |
3 | package Branches "Branches for simple routing models"
4 | end Branches;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Branches/Linear.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic.Branches;
2 |
3 | model Linear
4 | extends HomotopicLinear(theta = 0.0);
5 | end Linear;
6 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Interfaces/Adaptors/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Interfaces;
2 |
3 | package Adaptors "Adaptors"
4 | extends Modelica.Icons.Package;
5 | end Adaptors;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Internal/package.order:
--------------------------------------------------------------------------------
1 | Functions
2 | HQOnePort
3 | HQTwoPort
4 | QSI
5 | QSO
6 | QSISO
7 | QForcing
8 | QLateral
9 | Reservoir
10 | Volume
11 |
--------------------------------------------------------------------------------
/README:
--------------------------------------------------------------------------------
1 | This is the ChannelFlow library for RTC-Tools 2.0. It contains both simple as well as hydraulic routing models.
2 |
3 | Visit the RTC-Tools website at:
4 |
5 | https://www.deltares.nl/en/software/rtc-tools/
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Branches/Internal/KNAlpha.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Branches.Internal;
2 |
3 | type KNAlpha = Real(final unit = "1", min = 0, max = 500);
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Storage/Internal/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic.Storage;
2 |
3 | package Internal
4 | extends Modelica.Icons.InternalPackage;
5 | end Internal;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Nodes/Internal/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Nodes;
2 |
3 | package Internal
4 | extends Modelica.Icons.InternalPackage;
5 | end Internal;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Structures/Pump.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Structures;
2 |
3 | block Pump "Pump"
4 | extends DischargeControlledStructure;
5 | end Pump;
6 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Branches/Internal/BottomFrictionCoefficient.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic.Branches.Internal;
2 |
3 | type BottomFrictionCoefficient = Real(final unit = "m^0.5/s");
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Branches/Internal/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Branches;
2 |
3 | package Internal
4 | extends Modelica.Icons.InternalPackage;
5 | end Internal;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Reservoir/HomotopicPower.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic.Reservoir;
2 |
3 | model HomotopicPower
4 | extends Internal.PartialHomotopicPower;
5 | end HomotopicPower;
6 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Reservoir/HomotopicVolume.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic.Reservoir;
2 |
3 | model HomotopicVolume
4 | extends Internal.PartialHomotopicVolume;
5 | end HomotopicVolume;
6 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/BoundaryConditions/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting;
2 |
3 | package BoundaryConditions "Boundary conditions for simple routing models"
4 | end BoundaryConditions;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/package.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow;
2 |
3 | package SimpleRouting "Simple routing components based on QInPort and QOutPort, i.e. without potential variable"
4 | end SimpleRouting;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Branches/Internal/KNNonlinearityParameter.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Branches.Internal;
2 |
3 | type KNNonlinearityParameter = Real(final unit = "1", min = 0, max = 10);
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Branches/Internal/MuskingumWeightingFactor.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Branches.Internal;
2 |
3 | type MuskingumWeightingFactor = Real(final unit = "1", min = 0, max = 0.5);
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Branches/Internal/KNNonlinearityParameterNumerator.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Branches.Internal;
2 |
3 | type KNNonlinearityParameterNumerator = Real(final unit = "1", min = 0, max = 100);
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Branches/Internal/KNNonlinearityParameterDenominator.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Branches.Internal;
2 |
3 | type KNNonlinearityParameterDenominator = Real(final unit = "1", min = 0, max = 100);
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Salt/Elements/package.order:
--------------------------------------------------------------------------------
1 | SubstanceControlledStructure
2 | SaltyPartialStorage
3 | SaltyPartialReservoirBnd
4 | SaltyPartialReservoir
5 | SaltyLinearReservoirBnd
6 | SaltyLinearReservoir
7 | QMForcing
8 | NodeSalty
9 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Branches/Internal/package.order:
--------------------------------------------------------------------------------
1 | PartialMuskingum
2 | MuskingumWeightingFactor
3 | PartialKNNonlinear
4 | KNAlpha
5 | KNNonlinearityParameter
6 | KNNonlinearityParameterDenominator
7 | KNNonlinearityParameterNumerator
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Internal/Functions/SmoothSwitch.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Internal.Functions;
2 |
3 | function SmoothSwitch
4 | input Real x;
5 | output Real y;
6 | protected
7 | Real k = 50;
8 | algorithm
9 | y := if x < -1 then 0 elseif x > 1 then 1 else 0 + (1 - 0) / (1 + exp(-k * x));
10 | end SmoothSwitch;
11 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | exclude: |
2 | (?x)^(
3 | src/rtctools/_version\.py|
4 | src/rtctools/data/interpolation/__init__\.py|
5 | versioneer.py
6 | )$
7 | repos:
8 | - repo: https://github.com/astral-sh/ruff-pre-commit
9 | rev: v0.9.4
10 | hooks:
11 | - id: ruff
12 | args: [--fix, --exit-non-zero-on-fix]
13 | - id: ruff-format
14 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Internal/QSI.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Internal;
2 |
3 | partial block QSI
4 | Deltares.ChannelFlow.Interfaces.QInPort QIn annotation(Placement(visible = true, transformation(origin = {-80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0), iconTransformation(origin = {-80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0)));
5 | end QSI;
6 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Internal/QSO.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Internal;
2 |
3 | partial block QSO
4 | Deltares.ChannelFlow.Interfaces.QOutPort QOut annotation(Placement(visible = true, transformation(origin = {80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0), iconTransformation(origin = {80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0)));
5 | end QSO;
6 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Internal/Volume.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Internal;
2 |
3 | partial class Volume
4 | Modelica.Units.SI.Volume V(min = 0, nominal = 1e6);
5 | annotation(Icon(coordinateSystem(initialScale = 0.1, grid = {10, 10}), graphics = {Rectangle(fillColor = {255, 0, 0}, fillPattern = FillPattern.Solid, extent = {{-50, 50}, {50, -50}})}));
6 | end Volume;
7 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Branches/Muskingum.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Branches;
2 |
3 | block Muskingum "Muskingum routing"
4 | extends Internal.PartialMuskingum(K_internal=K, x_internal=x);
5 | parameter Modelica.Units.SI.Time K = 1.E4 "Storage constant";
6 | parameter Internal.MuskingumWeightingFactor x = 0.2 "Weighting factor";
7 | end Muskingum;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Internal/Functions/SmoothAbs.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Internal.Functions;
2 |
3 | function SmoothAbs "Smooth Approximation of an Abs() Function"
4 | input Real a;
5 | // A small value to ensure smoothness
6 | input Real eps = Deltares.Constants.eps;
7 | output Real smooth_abs;
8 | algorithm
9 | smooth_abs := sqrt(a ^ 2 + eps);
10 | end SmoothAbs;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Internal/Functions/SmoothMax.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Internal.Functions;
2 |
3 | function SmoothMax "Smooth Approximation of a Max() Function"
4 | input Real a;
5 | input Real b;
6 | // A small value to ensure smoothness
7 | input Real eps = Deltares.Constants.eps;
8 | output Real smooth_max;
9 | algorithm
10 | smooth_max := sqrt((a - b) ^ 2 + eps) / 2 + (a + b) / 2;
11 | end SmoothMax;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Internal/Functions/SmoothMin.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Internal.Functions;
2 |
3 | function SmoothMin "Smooth Approximation of a Min() Function"
4 | input Real a;
5 | input Real b;
6 | // A small value to ensure smoothness
7 | input Real eps = Deltares.Constants.eps;
8 | output Real smooth_min;
9 | algorithm
10 | smooth_min := -1.0 * SmoothMax(a=-1.0 * a, b=-1.0 * b, eps=eps);
11 | end SmoothMin;
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [metadata]
2 | license_file = COPYING.LESSER
3 |
4 | # See the docstring in versioneer.py for instructions. Note that you must
5 | # re-run 'versioneer.py setup' after changing this section, and commit the
6 | # resulting files.
7 |
8 | [versioneer]
9 | VCS = git
10 | style = pep440
11 | versionfile_source = src/rtctools_channel_flow/_version.py
12 | versionfile_build = rtctools_channel_flow/_version.py
13 | tag_prefix =
14 | parentdir_prefix = rtctools_channel_flow-
15 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Internal/QForcing.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Internal;
2 |
3 | partial class QForcing
4 | parameter Integer n_QForcing(min = 0) = 0;
5 | input Modelica.Units.SI.VolumeFlowRate QForcing[n_QForcing];
6 | annotation(Icon(graphics = {Line(origin = {-40, 0}, points = {{-20, 100}, {0, 60}, {20, 100}}), Text(extent = {{-90, 100}, {-50, 80}}, textString = "%n_QForcing")}, coordinateSystem(initialScale = 0.1)));
7 | end QForcing;
8 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Internal/HQOnePort.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Internal;
2 |
3 | partial model HQOnePort "Partial model of one port"
4 | replaceable package medium = Deltares.ChannelFlow.Media.FreshWater;
5 | Deltares.ChannelFlow.Interfaces.HQCMPort HQ(redeclare package medium = medium) annotation(Placement(visible = true, transformation(origin = {0, -80}, extent = {{-20, -20}, {20, 20}}, rotation = 0), iconTransformation(origin = {0, -80}, extent = {{-20, -20}, {20, 20}}, rotation = 0)));
6 | end HQOnePort;
7 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Storage/QSI.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Storage;
2 |
3 | block QSI
4 | import SI = Modelica.Units.SI;
5 | extends Deltares.ChannelFlow.Internal.QSI(QIn.Q(nominal=Q_nominal));
6 | extends Deltares.ChannelFlow.Internal.QForcing(QForcing(each nominal=Q_nominal));
7 | extends Deltares.ChannelFlow.Internal.Volume;
8 | parameter SI.VolumeFlowRate Q_nominal = 1.0;
9 | equation
10 | // Mass balance
11 | der(V) / Q_nominal = (QIn.Q + sum(QForcing)) / Q_nominal;
12 | end QSI;
13 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Interfaces/QInPort.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Interfaces;
2 |
3 | connector QInPort "Connector with potential water level (H) and flow discharge (Q)"
4 | input Modelica.Units.SI.VolumeFlowRate Q "Volume flow";
5 | annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Polygon(visible = true, fillColor = {0, 255, 0}, fillPattern = FillPattern.Solid, points = {{-100, 100}, {-100, -100}, {100, 0}, {-100, 100}})}));
6 | end QInPort;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Reservoir/Linear.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic.Reservoir;
2 |
3 | model Linear
4 | import SI = Modelica.Units.SI;
5 | extends Internal.PartialReservoir(H(min = H_b));
6 | // Parameters
7 | parameter SI.Area A;
8 | // Bed level
9 | parameter SI.Position H_b;
10 | equation
11 | // Volume - forebay relation
12 | V = A * (H - H_b);
13 | annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10})));
14 | end Linear;
15 |
--------------------------------------------------------------------------------
/.gitlab-ci.yml:
--------------------------------------------------------------------------------
1 | image: python:3.6
2 |
3 | stages:
4 | - build
5 | - deploy
6 |
7 | # build
8 | build:
9 | stage: build
10 | script:
11 | - python setup.py sdist bdist_wheel
12 | artifacts:
13 | paths:
14 | - dist/
15 | expire_in: 1 week
16 |
17 | # deploy
18 | deploy:
19 | stage: deploy
20 | dependencies:
21 | - build
22 | script:
23 | - pip install twine
24 | - twine upload -u $PYPI_USER -p $PYPI_PASSWORD dist/*
25 | only:
26 | - tags
27 | except:
28 | # Do not deploy tags that do not start with 1.
29 | - /^(?!1\.).*$
30 |
31 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Interfaces/QOutPort.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Interfaces;
2 |
3 | connector QOutPort "Connector with potential water level (H) and flow discharge (Q)"
4 | output Modelica.Units.SI.VolumeFlowRate Q "Volume flow";
5 | annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Polygon(visible = true, origin = {-0.28, 0}, fillColor = {0, 85, 0}, fillPattern = FillPattern.Solid, points = {{-100, 100}, {100, 0}, {-100, -100}, {-100, 100}})}));
6 | end QOutPort;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Branches/Delay.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Branches;
2 |
3 | block Delay
4 | import SI = Modelica.Units.SI;
5 | extends Deltares.ChannelFlow.Internal.QSISO(QIn.Q(nominal=Q_nominal), QOut.Q(nominal=Q_nominal));
6 | parameter SI.Duration duration = 0.0;
7 | parameter SI.VolumeFlowRate Q_nominal = 1.0;
8 | equation
9 | QOut.Q / Q_nominal = delay(QIn.Q, duration) / Q_nominal;
10 | annotation(Icon(graphics = {Text(extent = {{-25, 25}, {25, -25}}, textString = "τ")}, coordinateSystem(initialScale = 0.1)));
11 | end Delay;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Internal/QLateral.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Internal;
2 |
3 | partial class QLateral
4 | parameter Integer n_QLateral(min = 0) = 0;
5 | Deltares.ChannelFlow.Interfaces.QInPort QLateral[n_QLateral] annotation(Placement(visible = true, transformation(origin = {40, 80}, extent = {{20, -20}, {-20, 20}}, rotation = 90), iconTransformation(origin = {40, 80}, extent = {{20, -20}, {-20, 20}}, rotation = 90)));
6 | annotation(Icon(graphics = {Text(extent = {{50, 100}, {90, 80}}, textString = "%n_QLateral")}, coordinateSystem(initialScale = 0.1)));
7 | end QLateral;
8 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Branches/EmptyBranch.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Branches;
2 |
3 | model EmptyBranch "Branch whose delays can be modified within the python src"
4 | import SI = Modelica.Units.SI;
5 | extends Deltares.ChannelFlow.Internal.QSISO(QIn.Q(nominal=Q_nominal), QOut.Q(nominal=Q_nominal));
6 | // Nominal values for scaling
7 | parameter SI.VolumeFlowRate Q_nominal = 1.0;
8 | equation
9 | annotation(Icon(coordinateSystem( initialScale = 0.1, grid = {10, 10}), graphics = {Line(points = {{-50, 0}, {50, 0}})}));
10 | end EmptyBranch;
11 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Salt/Elements/QMForcing.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Salt.Elements;
2 |
3 | class QMForcing
4 | import SI = Modelica.Units.SI;
5 | parameter Integer n_QForcing(min = 0) = 0;
6 | replaceable package medium = Deltares.ChannelFlow.Media.FreshWater;
7 | input SI.VolumeFlowRate QForcing[n_QForcing];
8 | input SI.MassFlowRate MForcing[n_QForcing];
9 | annotation(Icon(graphics = {Line(origin = {-40, 0}, points = {{-20, 100}, {0, 60}, {20, 100}}), Text(extent = {{-90, 100}, {-50, 80}}, textString = "%n_QForcing")}, coordinateSystem(initialScale = 0.1)));
10 | end QMForcing;
11 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Internal/QSISO.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Internal;
2 |
3 | partial block QSISO "Partial block for single input single output"
4 | Deltares.ChannelFlow.Interfaces.QInPort QIn annotation(Placement(visible = true, transformation(origin = {-80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0), iconTransformation(origin = {-80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0)));
5 | Deltares.ChannelFlow.Interfaces.QOutPort QOut annotation(Placement(visible = true, transformation(origin = {80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0), iconTransformation(origin = {80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0)));
6 | end QSISO;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Structures/Pump.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic.Structures;
2 |
3 | model Pump "Pump"
4 | extends DischargeControlledStructure;
5 | // Note: dH is a helper state which is determined via the head_option parameter
6 | // If dH cannot be calculated directly from the upstream and downstream heads
7 | // use the PumpDynamicHead model instead
8 | parameter Integer head_option = 0;
9 | Modelica.Units.SI.Distance dH;
10 |
11 | equation
12 | if head_option == -1 then
13 | dH = HQUp.H;
14 | elseif head_option == 1 then
15 | dH = HQDown.H;
16 | else
17 | dH = HQDown.H - HQUp.H;
18 | end if;
19 | end Pump;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Storage/QSO.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Storage;
2 |
3 | block QSO
4 | import SI = Modelica.Units.SI;
5 | extends Deltares.ChannelFlow.Internal.QSO(QOut.Q(nominal=Q_nominal));
6 | extends Deltares.ChannelFlow.Internal.QForcing(QForcing(each nominal=Q_nominal));
7 | extends Deltares.ChannelFlow.Internal.Volume;
8 | // Inputs
9 | input SI.VolumeFlowRate QOut_control(nominal=Q_nominal);
10 | parameter SI.VolumeFlowRate Q_nominal = 1.0;
11 | equation
12 | // Mass balance
13 | der(V) / Q_nominal = (-QOut.Q + sum(QForcing)) / Q_nominal;
14 | // Outflow equals release
15 | QOut.Q / Q_nominal = QOut_control / Q_nominal;
16 | end QSO;
17 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/Constants.mo:
--------------------------------------------------------------------------------
1 | within Deltares;
2 |
3 | package Constants
4 | "Library of mathematical constants and constants of nature"
5 |
6 | // Mathematical constants
7 | final constant Real pi=3.14159265358979;
8 | final constant Real D2R=0.01745329251994329577 "Degree to Radian";
9 | final constant Real R2D=57.2957795130823208768 "Radian to Degree";
10 |
11 | // Constants of nature
12 | // (name, value, description from http://physics.nist.gov/cuu/Constants/index.html, data from 2014)
13 | final constant Modelica.Units.SI.Acceleration g_n=9.80665;
14 |
15 | // Numerical tuning constants
16 | constant Real eps=1e-12 "Small number used to guard against singularities";
17 | end Constants;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Interfaces/HQPort.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Interfaces;
2 |
3 | connector HQPort "Connector with potential water level (H) and flow discharge (Q)"
4 | Modelica.Units.SI.Position H "Level above datum";
5 | flow Modelica.Units.SI.VolumeFlowRate Q "Volume flow (positive inwards)";
6 | annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Ellipse(visible = true, lineColor = {0, 0, 255}, fillColor = {255, 255, 255}, extent = {{-100, -100}, {100, 100}}), Ellipse(visible = true, lineColor = {0, 0, 255}, fillColor = {0, 0, 255}, fillPattern = FillPattern.Solid, extent = {{-50, -50}, {50, 50}})}));
7 | end HQPort;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/BoundaryConditions/Terminal.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.BoundaryConditions;
2 |
3 | block Terminal
4 | import SI = Modelica.Units.SI;
5 | extends Deltares.ChannelFlow.Internal.QSI(QIn.Q(nominal=Q_nominal));
6 | // Outputs
7 | output SI.VolumeFlowRate Q(nominal=Q_nominal);
8 |
9 | parameter SI.VolumeFlowRate Q_nominal = 1.0;
10 | equation
11 | Q / Q_nominal = QIn.Q / Q_nominal;
12 | annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Rectangle(visible = true, fillColor = {255, 0, 255}, fillPattern = FillPattern.Solid, extent = {{-50, -30}, {50, 30}})}));
13 | end Terminal;
14 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Branches/Steady.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Branches;
2 |
3 | block Steady
4 | import SI = Modelica.Units.SI;
5 | extends Deltares.ChannelFlow.Internal.QSISO(QIn.Q(nominal=Q_nominal), QOut.Q(nominal=Q_nominal));
6 | extends Deltares.ChannelFlow.Internal.QForcing(QForcing(each nominal=Q_nominal));
7 | extends Deltares.ChannelFlow.Internal.QLateral(QLateral.Q(each nominal=Q_nominal));
8 | parameter SI.VolumeFlowRate Q_nominal = 1.0;
9 | equation
10 | QOut.Q / Q_nominal = (QIn.Q + sum(QForcing) + sum(QLateral.Q)) / Q_nominal;
11 | annotation(Icon(coordinateSystem( initialScale = 0.1, grid = {10, 10}), graphics = {Line(points = {{-50, 0}, {50, 0}})}));
12 | end Steady;
13 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Salt/Elements/SaltyLinearReservoir.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Salt.Elements;
2 |
3 | model SaltyLinearReservoir
4 | /*
5 | This block is designed to be used together with the "salt_simulation_mixin" to calculate dispersive and advective transport
6 | between salty reservoir elements, do not user in optimization.
7 | */
8 | import SI = Modelica.Units.SI;
9 | extends SaltyPartialReservoir(H(min = H_b));
10 |
11 | parameter SI.Area A;
12 | parameter SI.Position H_b; // Bed level
13 |
14 | equation
15 |
16 | V = A * (H - H_b);
17 | annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10})));
18 | end SaltyLinearReservoir;
19 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Storage/Linear.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic.Storage;
2 |
3 | model Linear "Storage with linear level-storage relation"
4 | /*
5 | Note: The default medium is FreshWater.
6 | To use a different medium, decalre the choice in your model file, for example
7 | replaceable package MyMedium = Deltares.ChannelFlow.Media.SalineWater;
8 | Pass this as an argument to the Linear block (redeclare package medium=MyMedium)
9 | */
10 | extends Internal.PartialStorage(HQ.H(min = H_b), V_nominal = 1 * A, V(nominal = A));
11 | // Surface area
12 | parameter Modelica.Units.SI.Area A;
13 | // Bed level
14 | parameter Modelica.Units.SI.Position H_b;
15 | equation
16 | V / V_nominal = A * (HQ.H - H_b) / V_nominal;
17 | end Linear;
18 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Salt/Elements/SaltyLinearReservoirBnd.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Salt.Elements;
2 |
3 | model SaltyLinearReservoirBnd
4 | /*
5 | This block is designed to be used together with the "salt_simulation_mixin" to calculate dispersive and advective transport
6 | between salty reservoir elements, do not use in optimization.
7 | */
8 | import SI = Modelica.Units.SI;
9 | extends SaltyPartialReservoirBnd(H(min = H_b));
10 |
11 | parameter SI.Area A;
12 | parameter SI.Position H_b; // Bed level
13 |
14 | equation
15 |
16 | V = A * (H - H_b);
17 | annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10})));
18 | end SaltyLinearReservoirBnd;
19 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/BoundaryConditions/Inflow.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.BoundaryConditions;
2 |
3 | block Inflow
4 | import SI = Modelica.Units.SI;
5 | extends Deltares.ChannelFlow.Internal.QSO(QOut.Q(nominal=Q_nominal));
6 | // Inputs
7 | input SI.VolumeFlowRate Q(nominal=Q_nominal);
8 |
9 | parameter SI.VolumeFlowRate Q_nominal = 1.0;
10 | equation
11 | QOut.Q / Q_nominal = Q / Q_nominal;
12 | annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Polygon(visible = true, fillColor = {255, 0, 255}, fillPattern = FillPattern.Solid, points = {{0, 50}, {-15, 15}, {-50, 0}, {-15, -15}, {0, -50}, {15, -15}, {50, 0}, {15, 15}})}));
13 | end Inflow;
14 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Structures/PumpUserEquationdH.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic.Structures;
2 |
3 | model PumpUserEquationdH "PumpUserEquationdH"
4 | extends DischargeControlledStructure;
5 | Modelica.Units.SI.Position HW;
6 | // Note: This block introduces a new state (HW).
7 | // This must be set via an equation. The choice of equation is up to the user.
8 | // Note: This block can be extended to support other head options
9 | parameter Integer head_option = 2;
10 | // The default head option of 2 aligns with the notation used in hydraulic structures
11 | Modelica.Units.SI.Distance dH;
12 |
13 | equation
14 | if head_option == 2 then
15 | dH = HQDown.H - HW;
16 | else
17 | dH = HQDown.H - HQUp.H;
18 | end if;
19 | end PumpUserEquationdH;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Interfaces/HQCMPort.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Interfaces;
2 |
3 | connector HQCMPort
4 | extends HQPort;
5 | replaceable package medium = Deltares.ChannelFlow.Media.FreshWater;
6 | flow Modelica.Units.SI.MassFlowRate M[medium.n_substances](each nominal = 10);
7 | Modelica.Units.SI.Density C[medium.n_substances](each min = 0, each nominal = 1);
8 | annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Ellipse(visible = true, lineColor = {0, 0, 255}, fillColor = {255, 255, 255}, extent = {{-100, -100}, {100, 100}}), Ellipse(visible = true, lineColor = {0, 0, 255}, fillColor = {0, 0, 255}, fillPattern = FillPattern.Solid, extent = {{-50, -50}, {50, 50}})}));
9 | end HQCMPort;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Branches/Integrator.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Branches;
2 |
3 | block Integrator
4 | import SI = Modelica.Units.SI;
5 | extends Deltares.ChannelFlow.Internal.QSISO(QIn.Q(nominal=Q_nominal), QOut.Q(nominal=Q_nominal));
6 | extends Deltares.ChannelFlow.Internal.QForcing(QForcing(each nominal = Q_nominal));
7 | extends Deltares.ChannelFlow.Internal.QLateral(QLateral.Q(each nominal=Q_nominal));
8 | extends Deltares.ChannelFlow.Internal.Volume;
9 | // Inputs
10 | input SI.VolumeFlowRate QOut_control(nominal=Q_nominal);
11 | parameter SI.VolumeFlowRate Q_nominal = 1.0;
12 | equation
13 | // Mass balance
14 | der(V) / Q_nominal = (QIn.Q - QOut.Q + sum(QForcing) + sum(QLateral.Q)) / Q_nominal;
15 |
16 | // Outflow equals release
17 | QOut.Q / Q_nominal = QOut_control / Q_nominal;
18 | end Integrator;
19 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Branches/KNNonlinear.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Branches;
2 |
3 | block KNNonlinear "K-N non-inear routing"
4 | import SI = Modelica.Units.SI;
5 | extends Internal.PartialKNNonlinear(k_internal_num=k_num, k_internal_den=k_den, alpha_internal=alpha, L_internal=L);
6 | parameter Internal.KNNonlinearityParameterNumerator k_num "Nonlinearity parameter numerator";
7 | parameter Internal.KNNonlinearityParameterDenominator k_den "Nonlinearity parameter denominator";
8 | parameter Internal.KNAlpha alpha "Routing parameter";
9 | parameter SI.Position L;
10 | annotation(Icon(coordinateSystem( initialScale = 0.1, grid = {10, 10}), graphics = {Rectangle( extent={{-10,10},{10,-10}}, lineColor={0,0,255}, fillColor={85,170,255}, fillPattern=FillPattern.Solid), Line(points = {{-50, 0}, {50, 0}})}));
11 | end KNNonlinear;
12 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Reservoir/Reservoir_turbine_out.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Reservoir;
2 |
3 | block Reservoir_turbine_out
4 | import SI = Modelica.Units.SI;
5 | extends Deltares.ChannelFlow.Internal.QSISO(QIn.Q(nominal=Q_nominal), QOut.Q(nominal=Q_nominal));
6 | extends Deltares.ChannelFlow.Internal.QForcing(QForcing(each nominal=Q_nominal));
7 | extends Deltares.ChannelFlow.Internal.QLateral(QLateral.Q(each nominal=Q_nominal));
8 | extends Deltares.ChannelFlow.Internal.Reservoir(Q_turbine(nominal=Q_nominal), Q_spill(nominal=Q_nominal));
9 | parameter SI.VolumeFlowRate Q_nominal = 1.0;
10 | equation
11 | // Mass balance
12 | der(V) / Q_nominal = (QIn.Q - QOut.Q + sum(QForcing) + sum(QLateral.Q) - Q_spill) / Q_nominal;
13 | // Outflow is only from the turbine
14 | QOut.Q = Q_turbine;
15 | end Reservoir_turbine_out;
16 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Reservoir/Reservoir.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Reservoir;
2 |
3 | block Reservoir
4 | import SI = Modelica.Units.SI;
5 | extends Deltares.ChannelFlow.Internal.QSISO(QIn.Q(nominal=Q_nominal), QOut.Q(nominal=Q_nominal));
6 | extends Deltares.ChannelFlow.Internal.QForcing(QForcing(each nominal=Q_nominal));
7 | extends Deltares.ChannelFlow.Internal.QLateral(QLateral.Q(each nominal=Q_nominal));
8 | extends Deltares.ChannelFlow.Internal.Reservoir(Q_turbine(nominal=Q_nominal), Q_spill(nominal=Q_nominal));
9 | parameter SI.VolumeFlowRate Q_nominal = 1.0;
10 | equation
11 | // Mass balance
12 | der(V) / Q_nominal = (QIn.Q - QOut.Q + sum(QForcing) + sum(QLateral.Q)) / Q_nominal;
13 | // Split outflow between turbine and spill flow
14 | QOut.Q / Q_nominal = (Q_turbine + Q_spill) / Q_nominal;
15 | end Reservoir;
16 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Interfaces/Adaptors/HQToQOut.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Interfaces.Adaptors;
2 |
3 | model HQToQOut "Model with HQPort to model with QinPort"
4 | HQPort HQ annotation(Placement(visible = true, transformation(origin = {-80, -0}, extent = {{-20, -20}, {20, 20}}, rotation = 0), iconTransformation(origin = {-80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0)));
5 | QOutPort QOut annotation(Placement(visible = true, transformation(origin = {80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0), iconTransformation(origin = {80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0)));
6 | input Modelica.Units.SI.Position H "Level above datum";
7 | equation
8 | QOut.Q = HQ.Q;
9 | H = HQ.H;
10 | annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Line(visible = true, points = {{-50, 0}, {50, 0}})}));
11 | end HQToQOut;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Interfaces/Adaptors/QInToHQ.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Interfaces.Adaptors;
2 |
3 | model QInToHQ "Model with QOutPort to model with HQPort"
4 | QInPort QIn annotation(Placement(visible = true, transformation(origin = {-80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0), iconTransformation(origin = {-80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0)));
5 | HQPort HQ annotation(Placement(visible = true, transformation(origin = {80, -0}, extent = {{-20, -20}, {20, 20}}, rotation = 0), iconTransformation(origin = {80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0)));
6 | output Modelica.Units.SI.Position H "Level above datum";
7 | equation
8 | HQ.Q + QIn.Q = 0;
9 | H = HQ.H;
10 | annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Line(visible = true, points = {{-50, 0}, {50, 0}})}));
11 | end QInToHQ;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Salt/Elements/SaltyPartialReservoirBnd.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Salt.Elements;
2 |
3 | partial model SaltyPartialReservoirBnd
4 | import SI = Modelica.Units.SI;
5 | extends Deltares.ChannelFlow.Internal.HQTwoPort;
6 | extends Deltares.ChannelFlow.Internal.QForcing;
7 | extends Deltares.ChannelFlow.Internal.QLateral;
8 | extends Deltares.ChannelFlow.Internal.Reservoir;
9 | // States
10 | SI.Position H;
11 | SI.Concentration C(nominal = 0.001);
12 |
13 | parameter Real theta = 1.0;
14 | parameter SI.VolumeFlowRate Q_nominal = 1.0;
15 | parameter SI.Concentration C_nominal = 1.0;
16 | parameter SI.Volume V_nominal;
17 |
18 | equation
19 | // Water level
20 | H = HQUp.H;
21 | H = HQDown.H;
22 |
23 | C = HQUp.C[1];
24 | C = HQDown.C[1];
25 |
26 | // Mass balance
27 | der(V) = 0;
28 | der(V * C) = 0;
29 |
30 |
31 | end SaltyPartialReservoirBnd;
32 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Salt/Elements/SaltyPartialReservoir.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Salt.Elements;
2 |
3 | partial model SaltyPartialReservoir
4 | import SI = Modelica.Units.SI;
5 | extends Deltares.ChannelFlow.Internal.HQTwoPort;
6 | extends QMForcing;
7 | extends Deltares.ChannelFlow.Internal.QLateral;
8 | extends Deltares.ChannelFlow.Internal.Reservoir;
9 | // States
10 | SI.Position H;
11 | SI.Concentration C(nominal = 0.001);
12 |
13 | parameter Real theta = 1.0;
14 | parameter SI.VolumeFlowRate Q_nominal = 1.0;
15 | parameter SI.Concentration C_nominal = 1.0;
16 | parameter SI.Volume V_nominal;
17 |
18 | equation
19 | // Water level
20 | H = HQUp.H;
21 | H = HQDown.H;
22 |
23 | C = HQUp.C[1];
24 | C = HQDown.C[1];
25 |
26 | // Mass balance
27 | der(V) = HQUp.Q + HQDown.Q + sum(QForcing) + sum(QLateral.Q);
28 | der(V * C) = HQUp.M[1] + HQDown.M[1] + sum(MForcing);
29 |
30 | end SaltyPartialReservoir;
31 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Storage/Storage.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Storage;
2 |
3 | block Storage "DEPRECATED, use Branches.Integrator instead"
4 | import SI = Modelica.Units.SI;
5 | extends Deltares.ChannelFlow.Internal.QSISO(QIn.Q(nominal=Q_nominal), QOut.Q(nominal=Q_nominal));
6 | extends Deltares.ChannelFlow.Internal.QForcing(QForcing(each nominal = Q_nominal));
7 | // Inputs
8 | input SI.VolumeFlowRate Q_release(nominal=Q_nominal);
9 | // States
10 | SI.Volume V(min=0, nominal = 1e6);
11 |
12 | parameter SI.VolumeFlowRate Q_nominal = 1.0;
13 | equation
14 | // Mass balance
15 | der(V) / Q_nominal = (QIn.Q - QOut.Q + sum(QForcing)) / Q_nominal;
16 | // Outflow equals release
17 | QOut.Q / Q_nominal = Q_release / Q_nominal;
18 | annotation(Icon(coordinateSystem(initialScale = 0.1, grid = {10, 10}), graphics = {Rectangle(fillColor = {255, 0, 0}, fillPattern = FillPattern.Solid, extent = {{-50, 50}, {50, -50}})}));
19 | end Storage;
20 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/BoundaryConditions/Level.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic.BoundaryConditions;
2 |
3 | model Level "Defines absolute water level"
4 | /*
5 | Note: The default medium is FreshWater.
6 | To use a different medium, decalre the choice in your model file, for example
7 | replaceable package MyMedium = Deltares.ChannelFlow.Media.SalineWater;
8 | Pass this as an argument to the Level block (redeclare package medium=MyMedium)
9 | */
10 | extends Deltares.ChannelFlow.Internal.HQOnePort;
11 | input Modelica.Units.SI.Position H;
12 | input Modelica.Units.SI.Density C[medium.n_substances];
13 | equation
14 | HQ.H = H;
15 | HQ.C = C;
16 | annotation(__Wolfram(itemFlippingEnabled = true), Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Rectangle(visible = true, fillColor = {255, 0, 255}, fillPattern = FillPattern.Solid, extent = {{-50, -50}, {50, 50}})}));
17 | end Level;
18 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Reservoir/Internal/PartialReservoir.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic.Reservoir.Internal;
2 |
3 | partial model PartialReservoir
4 | // partial reservoir model for the Hydraulic library: volumes, flows and water levels.
5 | // The water balance equation is specified here, and the discharge is split into turbine flow and spill flow.
6 | extends Deltares.ChannelFlow.Internal.HQTwoPort;
7 | extends Deltares.ChannelFlow.Internal.QForcing;
8 | extends Deltares.ChannelFlow.Internal.QLateral;
9 | extends Deltares.ChannelFlow.Internal.Reservoir;
10 | // States
11 | Modelica.Units.SI.Position H;
12 | // Parameters
13 | parameter Real Q_nominal=1.0;
14 | equation
15 | // Water level
16 | H = HQUp.H;
17 | // Mass balance
18 | der(V) / Q_nominal = (HQUp.Q + HQDown.Q + sum(QForcing) + sum(QLateral.Q)) / Q_nominal;
19 | // Split outflow between turbine and spill flow
20 | HQDown.Q + Q_turbine + Q_spill = 0.0;
21 | end PartialReservoir;
22 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Internal/Reservoir.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Internal;
2 |
3 | partial class Reservoir
4 | // a base class for any reservoir lake: 1) volumes and flows only or 2) volumes, flows and water levels
5 | // no equations for the water balance specified.
6 | // turbine flow is the portion of the reservoir release that is guided through the power hose.
7 | // spill flow accounts for flow throgh bottom outlet and flow through the spillway
8 | import SI = Modelica.Units.SI;
9 | // Inputs
10 | input SI.VolumeFlowRate Q_turbine;
11 | input SI.VolumeFlowRate Q_spill;
12 | // States
13 | SI.Volume V(min = 0, nominal = 1e6);
14 | equation
15 | annotation(Icon(coordinateSystem( initialScale = 0.1, grid = {10, 10}), graphics = {Polygon(fillColor = {0, 255, 255}, fillPattern = FillPattern.Solid, points = {{40, 50}, {-45, 0}, {40, -50}, {40, 50}, {40, 50}}), Text(origin = {0, -80}, extent = {{-70, 20}, {70, -20}}, textString = "%name", fontName = "MS Shell Dlg 2")}));
16 | end Reservoir;
17 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Salt/Elements/SaltyPartialStorage.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Salt.Elements;
2 |
3 | partial model SaltyPartialStorage
4 | /*
5 | This block is designed to be used together with the "salt_simulation_mixin" to calculate dispersive and advective transport
6 | between salty reservoir elements, do not user in optimization.
7 | */
8 | import SI = Modelica.Units.SI;
9 | extends Deltares.ChannelFlow.Internal.HQOnePort(HQ.Q(each nominal = Q_nominal), HQ.M(each nominal =Q_nominal * C_nominal));
10 | extends Deltares.ChannelFlow.Internal.QForcing(QForcing(each nominal = Q_nominal));
11 | extends Deltares.ChannelFlow.Internal.Volume;
12 |
13 | parameter SI.Volume V_nominal;
14 | parameter SI.Concentration C_nominal = 1e-3;
15 | parameter SI.VolumeFlowRate Q_nominal = 1.0;
16 |
17 | equation
18 |
19 | der(V) / Q_nominal = (HQ.Q + sum(QForcing)) / Q_nominal;
20 | HQ.M / (Q_nominal * C_nominal) = der(V * HQ.C) / (Q_nominal * C_nominal);
21 |
22 | end SaltyPartialStorage;
23 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Structures/DischargeControlledStructure.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Structures;
2 |
3 | block DischargeControlledStructure "DischargeControlledStructure"
4 | import SI = Modelica.Units.SI;
5 | extends Deltares.ChannelFlow.Internal.QSISO(QIn.Q(nominal=Q_nominal), QOut.Q(nominal=Q_nominal));
6 | // Inputs
7 | input SI.VolumeFlowRate Q;
8 | parameter SI.VolumeFlowRate Q_nominal = 1.0;
9 | equation
10 | QIn.Q / Q_nominal = QOut.Q / Q_nominal;
11 | QIn.Q / Q_nominal = Q / Q_nominal;
12 | annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Polygon(visible = true, origin = {0, -16.667}, fillColor = {255, 128, 0}, fillPattern = FillPattern.Solid, lineThickness = 0.25, points = {{0, 66.667}, {-50, -33.333}, {50, -33.333}})}), Diagram(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10})));
13 | end DischargeControlledStructure;
14 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Structures/RunOfRiverHydropowerComplexFixedHead.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Structures;
2 |
3 | block RunOfRiverHydropowerComplexFixedHead "Node for a simple complex of a run-of-river hydropower plant and a weir. Head difference for power production is constant."
4 | import SI = Modelica.Units.SI;
5 | extends Deltares.ChannelFlow.Internal.QSISO(QIn.Q(nominal=Q_nominal), QOut.Q(nominal=Q_nominal));
6 | parameter SI.VolumeFlowRate Q_nominal = 1.0;
7 | // Head difference
8 | parameter SI.Position dH;
9 | // Turbine efficiency
10 | parameter Real nu;
11 | // Water density
12 | parameter SI.Density ro;
13 | // Turbine flow
14 | output SI.VolumeFlowRate Q_turbine(min=0);
15 | // Spill flow
16 | output SI.VolumeFlowRate Q_spill(min=0);
17 | // Power production
18 | output SI.Power P;
19 | equation
20 | QOut.Q / Q_nominal = (Q_turbine + Q_spill) / Q_nominal;
21 | QOut.Q / Q_nominal = QIn.Q / Q_nominal;
22 | P / (nu * ro * Deltares.Constants.g_n * dH * Q_nominal) = Q_turbine / Q_nominal;
23 | end RunOfRiverHydropowerComplexFixedHead;
24 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Salt/Elements/NodeSalty.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Salt.Elements;
2 |
3 | model NodeSalty
4 | /*
5 | This block is designed to be used together with the "salt_simulation_mixin" to calculate dispersive and advective transport
6 | between salty reservoir elements, do not use in optimization.
7 | */
8 | extends Deltares.ChannelFlow.Internal.HQTwoPort;
9 | extends QMForcing;
10 |
11 | equation
12 |
13 | HQUp.Q + HQDown.Q + sum(QForcing) = 0;
14 | HQUp.M[1] + HQDown.M[1] + sum(MForcing) = 0; //Mass balance, can be used for one substance, like salt.
15 |
16 | HQDown.H = HQUp.H;
17 | HQUp.C = HQDown.C;
18 |
19 | annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Polygon(visible = true, fillColor = {255, 170, 0}, fillPattern = FillPattern.Solid, points = {{0, 50}, {-30, 40}, {30, -40}, {0, -50}, {-30, -40}, {30, 40}}), Polygon(visible = true, fillColor = {255, 0, 0}, fillPattern = FillPattern.Solid, points = {{-50, 0}, {-40, 30}, {-30, 40}, {30, -40}, {40, -30}, {50, 0}, {40, 30}, {30, 40}, {-30, -40}, {-40, -30}})}));
20 | end NodeSalty;
21 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Nodes/NodeHQPort.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Nodes;
2 |
3 | block NodeHQPort "Block with multiple inflows and multiple outflows, where allocation is based on explicitly specified outflows, including a port for a reservoir"
4 | import SI = Modelica.Units.SI;
5 | extends Internal.PartialNode;
6 | extends Deltares.ChannelFlow.Internal.HQOnePort;
7 | input SI.VolumeFlowRate QOut_control[nout](each nominal=Q_nominal);
8 | output SI.Position H;
9 | equation
10 | QInSum = sum(QIn.Q);
11 | QOutSum = sum(QOut_control);
12 | for i in 1:nout loop
13 | QOut[i].Q = QOut_control[i];
14 | end for;
15 | HQ.Q + QInSum - QOutSum = 0.;
16 | HQ.H = H;
17 | annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Polygon(visible = true, fillColor = {255, 170, 0}, fillPattern = FillPattern.Solid, points = {{0, 50}, {-30, 40}, {30, -40}, {0, -50}, {-30, -40}, {30, 40}}), Polygon(visible = true, fillColor = {255, 0, 0}, fillPattern = FillPattern.Solid, points = {{-50, 0}, {-40, 30}, {-30, 40}, {30, -40}, {40, -30}, {50, 0}, {40, 30}, {30, 40}, {-30, -40}, {-40, -30}})}));
18 | end NodeHQPort;
19 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Branches/LagAndK.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Branches;
2 |
3 | block LagAndK
4 | import SI = Modelica.Units.SI;
5 | extends Deltares.ChannelFlow.Internal.QSISO(QIn.Q(nominal=Q_nominal), QOut.Q(nominal=Q_nominal));
6 | parameter Modelica.Units.SI.Time Lag_parameter = 3600;
7 | parameter Modelica.Units.SI.Time K_parameter = 1;
8 | Deltares.ChannelFlow.SimpleRouting.Branches.Delay delay1(duration = Lag_parameter, Q_nominal=Q_nominal) annotation(
9 | Placement(visible = true, transformation(origin = {-38, -6}, extent = {{-10, -10}, {10, 10}}, rotation = 0)));
10 | Deltares.ChannelFlow.SimpleRouting.Branches.Muskingum muskingum1(x=0.0, K = K_parameter, Q_nominal=Q_nominal) annotation(
11 | Placement(visible = true, transformation(origin = {2, -4}, extent = {{-10, -10}, {10, 10}}, rotation = 0)));
12 | // Nominal values for scaling
13 | parameter SI.VolumeFlowRate Q_nominal = 1.0;
14 | equation
15 | QIn.Q / Q_nominal = delay1.QIn.Q / Q_nominal;
16 | QOut.Q / Q_nominal = muskingum1.QOut.Q / Q_nominal;
17 | connect(delay1.QOut, muskingum1.QIn) annotation(
18 | Line(points = {{-30, -6}, {-6, -6}, {-6, -4}, {-6, -4}}));
19 |
20 | end LagAndK;
21 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Internal/HQTwoPort.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Internal;
2 |
3 | partial model HQTwoPort
4 | replaceable package medium = Deltares.ChannelFlow.Media.FreshWater;
5 | Deltares.ChannelFlow.Interfaces.HQCMPort HQUp(redeclare package medium = medium) annotation(Placement(visible = true, transformation(origin = {-80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0), iconTransformation(origin = {-80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0)));
6 | Deltares.ChannelFlow.Interfaces.HQCMPort HQDown(redeclare package medium = medium) annotation(Placement(visible = true, transformation(origin = {80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0), iconTransformation(origin = {80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0)), Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {2, 2})));
7 | annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Line(visible = true, origin = {-80, -0}, points = {{-20, 30}, {20, 0}, {-20, -30}}, color = {0, 0, 255}), Line(visible = true, origin = {80, 0}, points = {{-20, 30}, {20, 0}, {-20, -30}}, color = {0, 0, 255})}));
8 | end HQTwoPort;
9 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Reservoir/Internal/PartialHomotopicVolume.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic.Reservoir.Internal;
2 |
3 | partial model PartialHomotopicVolume
4 | // this partial model adds a nonlinear non convex relation between volume and water level to the reservoir.
5 | // the relation between water level and volume is specified as a fourth order polynomial.
6 | // the optimization starts with a linearized simplification, here the volume is divided by a area A to obtain the water level.
7 | // during the homotopy optimization this linear equation is gradually bended towards the fourth order polynomial with the help of theta.
8 | import SI = Modelica.Units.SI;
9 | extends Deltares.ChannelFlow.Hydraulic.Reservoir.Internal.PartialReservoir;
10 |
11 | parameter SI.Area A;
12 | // Bed level
13 | parameter SI.Position H_b;
14 | // Homotopy parameter
15 | parameter Real theta;
16 | // Water level polynomial coefficients, to be specified as parameters in the model
17 | parameter Real Hc0 = 0.0;
18 | parameter Real Hc1 = 0.0;
19 | parameter Real Hc2 = 0.0;
20 | parameter Real Hc3 = 0.0;
21 | parameter Real Hc4 = 0.0;
22 | equation
23 | // Volume - forebay relation
24 | V / A = ((1 - theta) * A * (H - H_b) + theta * (Hc0 + Hc1*H + Hc2*H^2 + Hc3*H^3 + Hc4*H^4)) / A;
25 | end PartialHomotopicVolume;
26 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Storage/Internal/PartialStorage.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic.Storage.Internal;
2 |
3 | partial model PartialStorage
4 | import SI = Modelica.Units.SI;
5 | extends Deltares.ChannelFlow.Internal.HQOnePort(HQ.Q(nominal = Q_nominal), HQ.M(nominal = Q_nominal * C_nominal));
6 | extends Deltares.ChannelFlow.Internal.QForcing(QForcing(each nominal = Q_nominal));
7 | extends Deltares.ChannelFlow.Internal.Volume;
8 | // Homotopy parameter
9 | parameter Real theta = 1.0;
10 | // Nominal values used in linearization
11 | parameter Modelica.Units.SI.Volume V_nominal;
12 | parameter Modelica.Units.SI.Density C_nominal[medium.n_substances] = fill(1e-3, medium.n_substances);
13 | // Nominal values for scaling
14 | parameter SI.VolumeFlowRate Q_nominal = 1.0;
15 | equation
16 | der(V) / Q_nominal = (HQ.Q + sum(QForcing)) / Q_nominal;
17 | /*
18 | Note: this does not compile in OMEdit.
19 | The following alternative compiles but is incompatible with pymoca
20 | for substance in 1:medium.n_substances loop
21 | HQ.M[substance] / (Q_nominal * C_nominal[substance]) = (theta * der(V * HQ.C[substance]) + (1 - theta) * Q_nominal * der(HQ.C[substance])) / (Q_nominal * C_nominal[substance]);
22 | end for;
23 | */
24 | HQ.M[:] / (Q_nominal * C_nominal[:]) = (theta * der(V * HQ.C[:]) + (1 - theta) * Q_nominal * der(HQ.C[:])) / (Q_nominal * C_nominal[:]);
25 | end PartialStorage;
26 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Branches/HomotopicLinear.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic.Branches;
2 |
3 | model HomotopicLinear
4 | /*
5 | Note: The default medium is FreshWater.
6 | To use a different medium, decalre the choice in your model file, for example
7 | replaceable package MyMedium = Deltares.ChannelFlow.Media.SalineWater;
8 | Pass this as an argument to the HomotopicLinear block (redeclare package medium=MyMedium)
9 | */
10 | import SI = Modelica.Units.SI;
11 | extends Internal.PartialHomotopic(nominal_depth = fill(uniform_nominal_depth, n_level_nodes + 1), nominal_width = linspace(width_up, width_down, n_level_nodes + 1), H_b = linspace(H_b_up, H_b_down, n_level_nodes));
12 | // Nominal depth
13 | parameter SI.Distance uniform_nominal_depth;
14 | // Upstream Width (same 'Up' as HQUp)
15 | parameter SI.Distance width_up;
16 | // Downstream Width (same 'Down' as HQDown)
17 | parameter SI.Distance width_down;
18 | // Array of Widths
19 | parameter SI.Distance width[n_level_nodes] = linspace(width_up, width_down, n_level_nodes);
20 | // Upstream Bottom Level (same 'Up' as HQUp)
21 | parameter SI.Position H_b_up;
22 | // Downstream Bottom Level (same 'Down' as HQDown)
23 | parameter SI.Position H_b_down;
24 | equation
25 | // Compute cross sections
26 | _cross_section = width .* (H .- H_b);
27 | // Compute Wetted Perimeter
28 | _wetted_perimeter = width .+ 2.0 * (H .- H_b);
29 | end HomotopicLinear;
30 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Nodes/Node.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Nodes;
2 |
3 | block Node "Block with multiple inflows and multiple outflows and forcing, where allocation is based on explicitly specified outflows."
4 | import SI = Modelica.Units.SI;
5 | extends Internal.PartialNode(redeclare parameter Integer nout(min = 1) = 1);
6 | extends Deltares.ChannelFlow.Internal.QForcing(QForcing(each nominal=Q_nominal));
7 | input SI.VolumeFlowRate QOut_control[nout - 1](each nominal=Q_nominal);
8 | equation
9 | QInSum / Q_nominal = sum(QIn.Q) / Q_nominal;
10 | QOutSum / Q_nominal = (QInSum + sum(QForcing)) / Q_nominal;
11 | for i in 1:nout - 1 loop
12 | QOut[i].Q / Q_nominal = QOut_control[i] / Q_nominal;
13 | end for;
14 | QOut[nout].Q / Q_nominal = (QOutSum - sum(QOut_control[1:nout - 1])) / Q_nominal;
15 | annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Polygon(visible = true, fillColor = {255, 170, 0}, fillPattern = FillPattern.Solid, points = {{0, 50}, {-30, 40}, {30, -40}, {0, -50}, {-30, -40}, {30, 40}}), Polygon(visible = true, fillColor = {255, 0, 0}, fillPattern = FillPattern.Solid, points = {{-50, 0}, {-40, 30}, {-30, 40}, {30, -40}, {40, -30}, {50, 0}, {40, 30}, {30, 40}, {-30, -40}, {-40, -30}})}), Diagram(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10})));
16 | end Node;
17 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/BoundaryConditions/Discharge.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic.BoundaryConditions;
2 |
3 | model Discharge "Defines a discharge"
4 | /*
5 | Note: The default medium is FreshWater.
6 | To use a different medium, decalre the choice in your model file, for example
7 | replaceable package MyMedium = Deltares.ChannelFlow.Media.SalineWater;
8 | Pass this as an argument to the Discharge block (redeclare package medium=MyMedium)
9 | */
10 | extends Deltares.ChannelFlow.Internal.HQOnePort;
11 | function smooth_switch = Deltares.ChannelFlow.Internal.Functions.SmoothSwitch;
12 | input Modelica.Units.SI.VolumeFlowRate Q;
13 | input Modelica.Units.SI.MassFlowRate M[medium.n_substances];
14 | parameter Boolean upwind = true; // If true and there is outlfow from the system (into the discharge boudnary) then the concentration of the connected element is used.
15 | equation
16 | HQ.Q + Q = 0;
17 | if upwind then
18 | // We don't use SmoothSwitch here, as we assume Q to be a constant input.
19 | if Q > 0 then
20 | HQ.M = -M;
21 | else
22 | HQ.M = -Q * HQ.C;
23 | end if;
24 | else
25 | HQ.M = -M;
26 | end if;
27 | annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Polygon(visible = true, fillColor = {255, 0, 255}, fillPattern = FillPattern.Solid, points = {{0, -40}, {50, 40}, {-50, 40}})}));
28 | end Discharge;
29 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on:
4 | push:
5 | branches:
6 | - '**'
7 | tags:
8 | - '**'
9 |
10 | jobs:
11 | build:
12 | runs-on: ubuntu-latest
13 |
14 | steps:
15 | - name: Checkout code
16 | uses: actions/checkout@v4
17 |
18 | - name: Set up Python
19 | uses: actions/setup-python@v5
20 | with:
21 | python-version: '3.9'
22 |
23 | - name: Install build dependencies
24 | run: pip install setuptools wheel
25 |
26 | - name: Build package
27 | run: python setup.py sdist bdist_wheel
28 |
29 | - name: Upload dist as artifact
30 | uses: actions/upload-artifact@v4
31 | with:
32 | name: dist
33 | path: dist/
34 |
35 | deploy:
36 | runs-on: ubuntu-latest
37 | needs: build
38 | if: startsWith(github.ref, 'refs/tags/') && contains('0123456789', github.ref[10])
39 |
40 | steps:
41 | - name: Checkout code
42 | uses: actions/checkout@v4
43 |
44 | - name: Download artifact
45 | uses: actions/download-artifact@v4
46 | with:
47 | name: dist
48 | path: dist/
49 |
50 | - name: Set up Python
51 | uses: actions/setup-python@v5
52 | with:
53 | python-version: '3.9'
54 |
55 | - name: Install twine
56 | run: pip install twine
57 |
58 | - name: Upload to PyPI
59 | env:
60 | TWINE_USERNAME: ${{ secrets.PYPI_USER }}
61 | TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }}
62 | run: twine upload dist/*
63 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Nodes/Internal/PartialNode.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Nodes.Internal;
2 |
3 | partial block PartialNode "Partial block with multiple inflows and multiple outflows, where allocation is based on explicitly specified outflows."
4 | import SI = Modelica.Units.SI;
5 | replaceable parameter Integer nout(min = 0) = 0 "Number of outflows";
6 | parameter Integer nin(min = 1) = 1 "Number of inflows.";
7 | Deltares.ChannelFlow.Interfaces.QInPort QIn[nin](each Q(nominal=Q_nominal)) annotation(Placement(visible = true, transformation(origin = {-80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0), iconTransformation(origin = {-80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0)));
8 | Deltares.ChannelFlow.Interfaces.QOutPort QOut[nout](each Q(nominal=Q_nominal)) annotation(Placement(visible = true, transformation(origin = {80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0), iconTransformation(origin = {80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0)));
9 | parameter SI.VolumeFlowRate Q_nominal = 1.0;
10 | protected
11 | SI.VolumeFlowRate QInSum(nominal=Q_nominal);
12 | SI.VolumeFlowRate QOutSum(nominal=Q_nominal);
13 | equation
14 |
15 | annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Text(visible = true, origin = {-80, 40}, extent = {{-20, -20}, {20, 20}}, textString = "%nin"), Text(visible = true, origin = {80, 40}, extent = {{-20, -20}, {20, 20}}, textString = "%nout")}));
16 | end PartialNode;
17 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | """Simple and hydraulic Modelica routing models for RTC-Tools 2.
2 |
3 | RTC-Tools is the Deltares toolbox for control and optimization of water systems.
4 | """
5 |
6 | from setuptools import setup, find_packages
7 |
8 | import versioneer
9 |
10 | DOCLINES = __doc__.split("\n")
11 |
12 | CLASSIFIERS = """\
13 | Intended Audience :: Science/Research
14 | Intended Audience :: Information Technology
15 | License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)
16 | Programming Language :: Other
17 | Topic :: Scientific/Engineering :: GIS
18 | Topic :: Scientific/Engineering :: Mathematics
19 | Topic :: Scientific/Engineering :: Physics
20 | Operating System :: Microsoft :: Windows
21 | Operating System :: POSIX
22 | Operating System :: Unix
23 | Operating System :: MacOS
24 | """
25 |
26 | setup(
27 | name="rtc-tools-channel-flow",
28 | version=versioneer.get_version(),
29 | author="Deltares",
30 | maintainer="Deltares",
31 | description=DOCLINES[0],
32 | url="http://www.deltares.nl/en/software/rtc-tools/",
33 | download_url="http://gitlab.com/deltares/rtc-tools-channel-flow/",
34 | classifiers=[_f for _f in CLASSIFIERS.split("\n") if _f],
35 | platforms=["Windows", "Linux", "Mac OS-X", "Unix"],
36 | license="LGPL",
37 | packages=find_packages("src"),
38 | package_dir={"": "src"},
39 | install_requires=["pymoca >= 0.4.2"],
40 | include_package_data=True,
41 | cmdclass=versioneer.get_cmdclass(),
42 | entry_points={
43 | "rtctools.libraries.modelica": [
44 | "library_folder = rtctools_channel_flow:modelica",
45 | ]
46 | },
47 | )
48 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Branches/Internal/PartialKNNonlinear.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Branches.Internal;
2 |
3 | partial block PartialKNNonlinear
4 | import SI = Modelica.Units.SI;
5 | extends Deltares.ChannelFlow.Internal.QSISO(QIn.Q(nominal=Q_nominal), QOut.Q(nominal=Q_nominal));
6 |
7 | // Note: correct formulation guaranteed only if implicit_step_size is set to the input step size.
8 | input SI.Duration implicit_step_size(fixed = true);
9 |
10 | parameter Internal.KNNonlinearityParameterNumerator k_internal_num "Nonlinearity parameter numerator";
11 | parameter Internal.KNNonlinearityParameterNumerator k_internal_den "Nonlinearity parameter denominator";
12 | parameter Internal.KNAlpha alpha_internal "Routing parameter";
13 | parameter SI.Position L_internal;
14 |
15 | input Modelica.Units.SI.VolumeFlowRate q_out_prev(nominal=Q_nominal);
16 | parameter Real min_divisor = Deltares.Constants.eps;
17 |
18 | // Nominal values for scaling
19 | parameter SI.VolumeFlowRate Q_nominal = 1.0;
20 | equation
21 | // We express the storage in terms of the corresponding flows.
22 | // Note that: V = L_internal * alpha * Q_out ^ k and Q_in - Q_out = der(V).
23 |
24 | // Use same trick as Muskingum
25 |
26 | implicit_step_size * (QIn.Q - QOut.Q) / (L_internal * alpha_internal) = (QOut.Q + min_divisor) ^ (k_internal_num / k_internal_den) - (q_out_prev + min_divisor) ^ (k_internal_num / k_internal_den);
27 |
28 | q_out_prev / Q_nominal = (QOut.Q - implicit_step_size * der(QOut.Q)) / Q_nominal;
29 |
30 |
31 | initial equation
32 | // Steady state inizialization
33 |
34 | QIn.Q - QOut.Q = 0.0;
35 |
36 | end PartialKNNonlinear;
37 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Branches/Internal/PartialMuskingum.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Branches.Internal;
2 |
3 | partial block PartialMuskingum
4 | extends Deltares.ChannelFlow.Internal.QSISO(QIn.Q(nominal=Q_nominal), QOut.Q(nominal=Q_nominal));
5 | import SI = Modelica.Units.SI;
6 | // Note: correct formulation guaranteed only if step_size is set to the optimization step size.
7 | input SI.Duration step_size = 0.0;
8 | parameter Modelica.Units.SI.Time K_internal "Storage constant";
9 | parameter Internal.MuskingumWeightingFactor x_internal "Weighting factor";
10 | // We don't introduce a storage state, as this would require the user to specify
11 | // its initial value. We prefer to let the user specify the initial values for the
12 | // flows
13 | parameter Modelica.Units.SI.VolumeFlowRate Q_nominal = 1.0;
14 | equation
15 | (der(QIn.Q)*(K_internal * x_internal + step_size/2) + der(QOut.Q)*(K_internal * (1 - x_internal) - step_size/2)) / Q_nominal = (QIn.Q - QOut.Q) / Q_nominal;
16 | annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Polygon(visible = true, origin = {-5, -37.5}, fillColor = {128, 128, 128}, fillPattern = FillPattern.Solid, points = {{-45, -12.5}, {-45, 17.5}, {45, 7.5}, {45, -12.5}}), Line(visible = true, origin = {-40, 10}, points = {{0, 30}, {0, -30}}), Line(visible = true, origin = {30, 5.791}, points = {{0, 34.209}, {0, -34.209}}), Line(visible = true, origin = {-5, 20}, points = {{-35, 10}, {35, -10}}), Line(visible = true, origin = {-5, 10}, points = {{-35, 0}, {35, 0}}, pattern = LinePattern.Dash)}));
17 | end PartialMuskingum;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/SimpleRouting/Reservoir/Reservoir_multi_io.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.SimpleRouting.Reservoir;
2 |
3 | block Reservoir_multi_io "Reservoir with multiple inflows/outflows."
4 | import SI = Modelica.Units.SI;
5 | // Parameters
6 | parameter Integer nin(min = 0) = 1 "Number of inflows.";
7 | parameter Integer nout(min = 0) = 1 "Number of outflows";
8 | parameter SI.VolumeFlowRate Q_nominal = 1.0;
9 | // Inflow and outflow
10 | Deltares.ChannelFlow.Interfaces.QInPort QIn[nin](each Q(nominal=Q_nominal)) annotation(Placement(visible = true, transformation(origin = {-80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0), iconTransformation(origin = {-80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0)));
11 | Deltares.ChannelFlow.Interfaces.QOutPort QOut[nout](each Q(nominal=Q_nominal)) annotation(Placement(visible = true, transformation(origin = {80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0), iconTransformation(origin = {80, 0}, extent = {{-20, -20}, {20, 20}}, rotation = 0)));
12 | input SI.VolumeFlowRate QOut_control[nout](each nominal=Q_nominal);
13 | // States
14 | SI.Volume V(min = 0, nominal = 1e6);
15 | equation
16 | // QOut from control input.
17 | for i in 1:nout loop
18 | QOut[i].Q / Q_nominal = QOut_control[i] / Q_nominal;
19 | end for;
20 | // Mass balance
21 | der(V) / Q_nominal = (sum(QIn.Q) - sum(QOut.Q)) / Q_nominal;
22 | // Annotation
23 | annotation(Icon(coordinateSystem( initialScale = 0.1, grid = {10, 10}), graphics = {Polygon(fillColor = {0, 255, 255}, fillPattern = FillPattern.Solid, points = {{40, 50}, {-45, 0}, {40, -50}, {40, 50}, {40, 50}}), Text(origin = {0, -80}, extent = {{-70, 20}, {70, -20}}, textString = "%name", fontName = "MS Shell Dlg 2")}));
24 | end Reservoir_multi_io;
25 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Structures/DischargeControlledStructure.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic.Structures;
2 |
3 | model DischargeControlledStructure "DischargeControlledStructure"
4 | /*
5 | Note: The default medium is FreshWater.
6 | To use a different medium, decalre the choice in your model file, for example
7 | replaceable package MyMedium = Deltares.ChannelFlow.Media.SalineWater;
8 | Pass this as an argument to the DischargeControlledStructure block (redeclare package medium=MyMedium)
9 | */
10 | extends Deltares.ChannelFlow.Internal.HQTwoPort;
11 | function smooth_switch = Deltares.ChannelFlow.Internal.Functions.SmoothSwitch;
12 | input Modelica.Units.SI.VolumeFlowRate Q(nominal=Q_nominal);
13 | // Homotopy parameter
14 | parameter Real theta = 1.0;
15 | // Nominal values used in linearization
16 | parameter Modelica.Units.SI.MassFlowRate Q_nominal = 1;
17 | parameter Modelica.Units.SI.Density C_nominal[medium.n_substances] = fill(1e-3, medium.n_substances);
18 | equation
19 | // Water
20 | HQUp.Q + HQDown.Q = 0;
21 | HQUp.Q = Q;
22 | // Substances
23 | HQUp.M = -HQDown.M;
24 | // Z depends on which direction the flow is, this decouples the concentration on both sides of the pump.
25 | // Z=Q*C, this equation is linearized.
26 | HQUp.M = theta * (smooth_switch(Q) * HQUp.C * Q + (1 - smooth_switch(Q)) * HQDown.C * Q) + (1 - theta) * (Q_nominal * C_nominal + C_nominal * (Q - Q_nominal) + Q_nominal * ((if Q_nominal > 0 then HQUp.C else HQDown.C) - C_nominal));
27 | annotation(Icon(coordinateSystem( initialScale = 0.1, grid = {10, 10}), graphics = {Polygon(origin = {0, -16.67}, fillColor = {255, 128, 0}, fillPattern = FillPattern.Solid, points = {{0, 66.667}, {-50, -33.333}, {50, -33.333}, {0, 66.667}})}), Diagram(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10})));
28 | end DischargeControlledStructure;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/package.mo:
--------------------------------------------------------------------------------
1 | package Deltares
2 | extends Modelica.Icons.Package;
3 | annotation(Icon(graphics = {Polygon(origin = {-8.844, 45.392}, fillColor = {127, 168, 188}, pattern = LinePattern.None, fillPattern = FillPattern.Solid, points = {{-26.221, 50.878}, {-35.465, 37.808}, {-33.553, 29.52}, {-26.221, 27.607}, {-8.369, 29.839}, {11.076, 33.026}, {28.844, 34.608}, {42.316, 32.07}, {46.779, 28.563}, {46.779, 22.825}, {42.635, 14.608}, {38.844, 10.393}, {36.578, 6.568}, {38.844, 4.608}, {48.844, 4.608}, {61.442, 2.743}, {68.844, -0.764}, {68.844, -3.314}, {68.844, -5.392}, {63.992, -5.392}, {45.822, -7.458}, {28.844, -12.559}, {6.294, -22.122}, {-11.156, -32.323}, {-31.156, -47.624}, {-44.072, -62.606}, {-48.535, -68.982}, {-51.156, -75.392}, {-53.954, -72.807}, {-51.156, -62.606}, {-44.072, -49.536}, {-33.553, -33.279}, {-17.933, -18.297}, {-7.094, -9.052}, {1.513, 0.192}, {4.7, 7.205}, {2.469, 11.987}, {-3.907, 11.987}, {-22.714, 10.393}, {-39.291, 10.393}, {-48.216, 14.608}, {-51.156, 24.608}, {-46.304, 34.608}, {-36.74, 44.608}, {-31.156, 48.646}, {-26.221, 50.878}}, smooth = Smooth.Bezier), Polygon(origin = {16.65, -33.313}, fillColor = {0, 139, 192}, pattern = LinePattern.None, fillPattern = FillPattern.Solid, points = {{-58.41, -46.687}, {-43.109, -48.612}, {-30.995, -48.612}, {-18.882, -46.687}, {3.35, -38.73}, {23.35, -23.748}, {35.629, -8.447}, {41.685, 3.313}, {41.685, 13.313}, {35.31, 17.693}, {26.384, 17.693}, {21.284, 19.287}, {21.284, 23.313}, {25.428, 26.619}, {37.541, 35.544}, {47.423, 43.313}, {47.423, 47.658}, {45.829, 51.802}, {37.86, 54.99}, {23.35, 53.313}, {8.533, 48.933}, {-10.594, 40.964}, {-26.65, 30.444}, {-36.65, 18.012}, {-38.327, 4.942}, {-32.908, -1.752}, {-26.65, -6.687}, {-12.506, -8.447}, {-3.262, -13.228}, {0.245, -21.198}, {-4.218, -29.167}, {-13.781, -36.687}, {-24.939, -40.962}, {-36.65, -43.831}, {-46.65, -43.831}, {-58.41, -43.831}, {-58.41, -46.687}}, smooth = Smooth.Bezier)}, coordinateSystem(initialScale = 0.1)));
4 | end Deltares;
5 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Reservoir/Internal/PartialHomotopicPower.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic.Reservoir.Internal;
2 |
3 | partial model PartialHomotopicPower
4 | // this partial model adds the hydropower equation to the HomotopicVolume partial model.
5 | // the head difference is dynamically computed as difference between reservoir stage and tailwater level.
6 | // the turbine efficiency is constant.
7 | // The optimization starts with a linear approximation of the power equation: head difference is assumed to be constant. This value must be provided as parameter for the node.
8 | import SI = Modelica.Units.SI;
9 | extends PartialHomotopicVolume(theta = theta);
10 | // Parameters
11 | parameter Real theta = theta;
12 | // head difference for the linear approximation for theta = 0
13 | parameter Real dH_0;
14 | // The efficiency term is the product of density of water, the gravity acceleration constant g and turbine efficiency (equation below). This term is assumed to be constant and provided as parameter within the model via Python.
15 | parameter Real efficiency_term;
16 | // The following variables are not used, we use the efficiency term instead. We keep them in for historic reasons and potential later extension.
17 | // parameter SI.Density density_water = 1000.0;
18 | // parameter Real turbine_efficiency;
19 | // The tailwater level depends on the total outflow. Such an equation must be specified in another model that inherits this model.
20 | SI.Position H_tw; // there is no equation for H_tw here. This creates an unbalanced model.
21 | // head difference Delta H
22 | SI.Position dH;
23 | // Hydro power generation
24 | Real Power(nominal = power_nominal);
25 | parameter Real power_nominal;
26 |
27 | equation
28 | // Delta H equation
29 | dH = H - H_tw;
30 | // computation of the efficiency_term (a constant term in the power equation). Not used, see above.
31 | // efficiency_term = turbine_efficiency * Deltares.Constants.g_n * density_water;
32 | // Power equation.
33 | Power / power_nominal = ((1 - theta) * (efficiency_term * Q_turbine * dH_0) + theta * (efficiency_term * Q_turbine * dH)) / power_nominal;
34 | end PartialHomotopicPower;
35 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Branches/HomotopicTrapezoidal.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic.Branches;
2 |
3 | model HomotopicTrapezoidal
4 | /*
5 | Note: The default medium is FreshWater.
6 | To use a different medium, decalre the choice in your model file, for example
7 | replaceable package MyMedium = Deltares.ChannelFlow.Media.SalineWater;
8 | Pass this as an argument to the HomotopicTrapezoidal block (redeclare package medium=MyMedium)
9 | */
10 | import SI = Modelica.Units.SI;
11 | extends Internal.PartialHomotopic(nominal_depth = fill(uniform_nominal_depth, n_level_nodes + 1), nominal_width = 0.5 * nominal_depth ./ tan(Deltares.Constants.D2R * linspace(left_slope_angle_up, left_slope_angle_down, n_level_nodes + 1)) .+ linspace(bottom_width_up, bottom_width_down, n_level_nodes + 1) .+ 0.5 * nominal_depth ./ tan(Deltares.Constants.D2R * linspace(right_slope_angle_up, right_slope_angle_down, n_level_nodes + 1)), H_b = linspace(H_b_up, H_b_down, n_level_nodes));
12 | // Nominal depth
13 | parameter SI.Distance uniform_nominal_depth;
14 | // Upstream Bottom Width (same 'Up' as HQUp)
15 | parameter SI.Distance bottom_width_up;
16 | // Downstream Bottom Width (same 'Down' as HQDown)
17 | parameter SI.Distance bottom_width_down;
18 | // Array of Bottom Widths
19 | parameter SI.Distance[n_level_nodes] bottom_width = linspace(bottom_width_up, bottom_width_down, n_level_nodes);
20 | // Upstream Left Slope Angle (same as 'Up' in HQUp). Left slope = slope left when facing along the positive flow direction.
21 | parameter Real left_slope_angle_up(unit = "deg", min = 0.0, max = 90.0) = 90.0;
22 | // Downstream Left Slope Angle (same as 'Down' in HQDown). Left slope = slope left when facing along the positive flow direction.
23 | parameter Real left_slope_angle_down(unit = "deg", min = 0.0, max = 90.0) = 90.0;
24 | // Array of Left Slope Angles. Left slope = slope left when facing along the positive flow direction.
25 | parameter Real[n_level_nodes] left_slope_angle(each unit = "deg") = linspace(left_slope_angle_up, left_slope_angle_down, n_level_nodes);
26 | // Upstream Left Slope Angle (same as 'Up' in HQUp). Right slope = slope right when facing along the positive flow direction.
27 | parameter Real right_slope_angle_up(unit = "deg", min = 0.0, max = 90.0) = 90.0;
28 | // Downstream Left Slope Angle (same as 'Down' in HQDown). Right slope = slope right when facing along the positive flow direction.
29 | parameter Real right_slope_angle_down(unit = "deg", min = 0.0, max = 90.0) = 90.0;
30 | // Array of Left Slope Angles. Right slope = slope right when facing along the positive flow direction.
31 | parameter Real[n_level_nodes] right_slope_angle(each unit = "deg") = linspace(right_slope_angle_up, right_slope_angle_down, n_level_nodes);
32 | // Upstream Bottom Level (same 'Up' as HQUp)
33 | parameter SI.Position H_b_up;
34 | // Downstream Bottom Level (same 'Down' as HQDown)
35 | parameter SI.Position H_b_down;
36 | equation
37 | // Compute nonlinear cross sections. These are replaced into the model by RTC-Tools (thanks to the underscore prefix),
38 | // into the nonlinear parts of the homotopic equations. No separate homotopy is therefore required here.
39 | _cross_section = (
40 | 0.5 * (H .- H_b) ./ tan(Deltares.Constants.D2R * left_slope_angle) .+
41 | bottom_width .+
42 | 0.5 * (H .- H_b) ./ tan(Deltares.Constants.D2R * right_slope_angle)
43 | ) .* (H .- H_b);
44 | // Compute Wetted Perimeter
45 | _wetted_perimeter = (H .- H_b) ./ sin(Deltares.Constants.D2R .* left_slope_angle) .+ bottom_width .+ (H .- H_b) ./ sin(Deltares.Constants.D2R .* right_slope_angle);
46 | end HomotopicTrapezoidal;
47 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Salt/Elements/SubstanceControlledStructure.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Salt.Elements;
2 |
3 | model SubstanceControlledStructure "SubstanceControlledStructure"
4 | /*
5 | This block is designed to be used together with the "salt_simulation_mixin" to calculate dispersive and advective transport
6 | between salty reservoir elements, do not use in optimization.
7 | */
8 | extends Deltares.ChannelFlow.Internal.HQTwoPort;
9 | import SI = Modelica.Units.SI;
10 | function smooth_abs = Deltares.ChannelFlow.Internal.Functions.SmoothAbs;
11 |
12 | parameter SI.VolumeFlowRate Q_nominal = 1;
13 | parameter SI.Concentration C_nominal = 1e-3;
14 | parameter SI.Height width = 2000;
15 | parameter SI.Temperature temperature_up; //Temperature of the upstream block
16 | parameter SI.Temperature temperature_down; //Temperature of the downstream block
17 | parameter SI.Height H_b_up; //Bottom level of the upstream block
18 | parameter SI.Height H_b_down; //Bottom level of the downstream block
19 |
20 | SI.Density rho_up(nominal=1000, start = 1000.0);
21 | SI.Density rho_down(nominal=1000, start = 1000.0);
22 | SI.Concentration salinity_psu_up(nominal=34.7, start = 34.7);
23 | SI.Concentration salinity_psu_down(nominal=34.7, start = 34.7);
24 | SI.Density rho_ref_up;
25 | SI.Density rho_ref_down;
26 |
27 | Real a_up;
28 | Real b_up;
29 | Real c_up;
30 | Real a_down;
31 | Real b_down;
32 | Real c_down;
33 | Real flux_q1_s1;
34 | Real epsilon_abs = 0.000001;
35 |
36 | equation
37 |
38 | salinity_psu_up = HQUp.C[1] / rho_up * 1000.0;
39 | salinity_psu_down = HQDown.C[1] / rho_down * 1000.0;
40 |
41 | //Using UNESCO equation of state (EOS-80)
42 | a_up = 8.24493E-1 - 4.0899E-3 * temperature_up + 7.6438E-5 * temperature_up^2.0;
43 | b_up = -5.72466E-3 + 1.0227E-4 * temperature_up - 1.6546E-6 * temperature_up^2.0;
44 | c_up = 4.8314E-4;
45 | rho_ref_up = (999.842594 + 6.793952E-2 * temperature_up - 9.095290E-3 * temperature_up^2.0 +1.001685E-4 * temperature_up^3.0 - 1.120083E-6 *temperature_up^4.0 +6.536332E-9 * temperature_up^5.0);
46 | rho_up = rho_ref_up + a_up * salinity_psu_up + b_up * salinity_psu_up^1.5 + c_up * salinity_psu_up^2.0;
47 |
48 | a_down = 8.24493E-1 - 4.0899E-3 * temperature_down + 7.6438E-5 * temperature_down^2.0;
49 | b_down = -5.72466E-3 + 1.0227E-4 * temperature_down - 1.6546E-6 * temperature_down^2.0;
50 | c_down = 4.8314E-4;
51 | rho_ref_down = (999.842594 + 6.793952E-2 * temperature_down - 9.095290E-3 * temperature_down^2.0 +1.001685E-4 * temperature_down^3.0 - 1.120083E-6 *temperature_down^4.0 +6.536332E-9 * temperature_down^5.0);
52 | rho_down = rho_ref_down + a_down * salinity_psu_down + b_down * salinity_psu_down^1.5 + c_down * salinity_psu_down^2.0;
53 |
54 | flux_q1_s1 = (2*9.81)^0.5 * width / 2 * min(HQUp.H-H_b_up, HQDown.H-H_b_down)^1.5*(smooth_abs(rho_up-rho_down, epsilon_abs)/(rho_up+rho_down))^0.5;
55 |
56 |
57 | if HQUp.Q < -flux_q1_s1 then
58 | HQUp.M[1] = HQUp.Q * HQDown.C[1];
59 | elseif HQUp.Q > flux_q1_s1 then
60 | HQUp.M[1] = HQUp.Q * HQUp.C[1];
61 | else
62 | HQUp.M[1] =0.5 * HQUp.Q * (HQUp.C[1]+ HQDown.C[1]) + (HQUp.C[1]-HQDown.C[1])* 0.5 * (2*9.81)^0.5 * width / 2 * min(HQUp.H-H_b_up, HQDown.H-H_b_down)^1.5*(smooth_abs(rho_up-rho_down, epsilon_abs)/(rho_up+rho_down))^0.5;
63 | end if;
64 |
65 | annotation(Icon(coordinateSystem( initialScale = 0.1, grid = {10, 10}), graphics = {Polygon(origin = {0, -16.67}, fillColor = {255, 128, 0}, fillPattern = FillPattern.Solid, points = {{0, 66.667}, {-50, -33.333}, {50, -33.333}, {0, 66.667}})}), Diagram(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10})));
66 | end SubstanceControlledStructure;
67 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Branches/LinearisedSV.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic.Branches;
2 |
3 | model LinearisedSV
4 | import SI = Modelica.Units.SI;
5 | extends Deltares.ChannelFlow.Internal.HQTwoPort;
6 | extends Deltares.ChannelFlow.Internal.QForcing;
7 | extends Deltares.ChannelFlow.Internal.QLateral;
8 | // Lateral inflow. A Matrix with n_QForcing, nQLateral rows and n_level_nodes columns. Each row corresponds to a QForcing, QLateral.Q and defines the distribution of that QForcing, QLateral.Q along the Branch.
9 | // NOTE: To preserve mass, each row should sum to 1.0
10 | parameter Real QForcing_map[n_QForcing, n_level_nodes] = fill(1.0 / n_level_nodes, n_QForcing, n_level_nodes);
11 | parameter Real QLateral_map[n_QLateral, n_level_nodes] = fill(1.0 / n_level_nodes, n_QLateral, n_level_nodes);
12 | // Wind stress
13 | input SI.Stress wind_stress_u(nominal = 1e-1) = 0.0; // Wind stress in x (u, easting) direction (= 0 radians, 0 degrees)
14 | input SI.Stress wind_stress_v(nominal = 1e-1) = 0.0; // Wind stress in y (v, northing) direction (= 0.5*pi radians, 90 degrees)
15 | // Flow
16 | SI.VolumeFlowRate[n_level_nodes + 1] Q;
17 | SI.VolumeFlowRate[n_level_nodes + 1] Q_relative;
18 | // Water Level
19 | SI.Position[n_level_nodes] H(min = H_b);
20 | SI.Position[n_level_nodes] Y_relative;
21 | parameter SI.Position H_nominal = 1.0;
22 | parameter SI.Position H_nominal_down = 1.0;
23 | parameter SI.Position[n_level_nodes] H_nominal_vec = linspace(H_nominal, H_nominal_down, n_level_nodes);
24 | // Length
25 | parameter SI.Distance length = 1.0;
26 | // Rotation
27 | parameter Real rotation_deg = 0.0; // Rotation of branch relative to x (u, easting) in degrees
28 | // Water density
29 | parameter SI.Density density_water = 1000.0;
30 | // Manning
31 | parameter Real friction_coefficient = 0.0;
32 | // Discretization options
33 | parameter Integer n_level_nodes = 4;
34 | // Nominal flow used in linearization
35 | parameter SI.VolumeFlowRate Q_nominal = 1.0;
36 |
37 | // Width
38 | parameter SI.Distance width = 1.0;
39 | // Upstream Bottom Level (same 'Up' as HQUp)
40 | parameter SI.Position H_b_up;
41 | // Downstream Bottom Level (same 'Down' as HQDown)
42 | parameter SI.Position H_b_down;
43 | // Array of Bottom Levels
44 | parameter SI.Position[n_level_nodes] H_b = linspace(H_b_up, H_b_down, n_level_nodes);
45 |
46 | //input SI.Duration semi_implicit_step_size = 0.0;
47 | //parameter SI.VolumeFlowRate[n_level_nodes + 1] Q0;
48 | //SI.Position[n_level_nodes] Y;
49 | //parameter SI.Position Y0[n_level_nodes];
50 |
51 | parameter SI.Distance T0[n_level_nodes];
52 | parameter SI.Velocity[n_level_nodes * 2 - 1] V0;
53 | parameter Real[n_level_nodes + 1] Delta;
54 | parameter Real[n_level_nodes] Gamma;
55 | parameter Real[n_level_nodes + 1] C0;
56 |
57 |
58 | parameter SI.VolumeFlowRate[n_QLateral] Qlateral_nominal = fill(0.0, n_QLateral);
59 | parameter SI.VolumeFlowRate[n_QForcing] Qforcing_nominal = fill(0.0, n_QForcing);
60 |
61 |
62 | protected
63 | SI.Stress _wind_stress;
64 | constant Real D2R = 3.141592653590 / 180.0;
65 | parameter SI.Angle rotation_rad = D2R * rotation_deg; // Conversion to rotation in radians
66 | parameter SI.Distance dx = length / (n_level_nodes - 1);
67 | SI.Area[n_level_nodes] _cross_section;
68 | SI.VolumeFlowRate[n_QLateral] _lat = QLateral.Q .- Qlateral_nominal;
69 | SI.VolumeFlowRate[n_level_nodes] _QPerpendicular_distribution = transpose(QForcing_map) * (QForcing .- Qforcing_nominal) .+ transpose(QLateral_map) * _lat;
70 |
71 | // output Real test_1;
72 |
73 | equation
74 | for node in 1:(n_level_nodes+1) loop
75 | Q[node] = Q_relative[node] + Q_nominal;
76 | end for;
77 |
78 | H = Y_relative + H_nominal_vec + H_b; //H is level, not depth
79 | Q_relative[1] = HQUp.Q - Q_nominal;
80 | Q_relative[n_level_nodes + 1] = (-HQDown.Q) - Q_nominal;
81 | Y_relative[1] = HQUp.H - H_nominal - H_b_up;
82 | Y_relative[n_level_nodes] = HQDown.H - H_nominal_down - H_b_down;
83 | _wind_stress = wind_stress_u * cos(rotation_rad) + wind_stress_v * sin(rotation_rad);
84 |
85 |
86 |
87 | der(Q_relative[2]) + 2 * V0[2] * ((Q_relative[3] - Q_relative[1]) / (1.5 * dx)) + (C0[2] ^ 2 - V0[2] ^ 2) * ((T0[1] + T0[2]) / 2) * ((Y_relative[2] - Y_relative[1]) / dx) + Delta[2] * Q_relative[2] - (Gamma[1] * Y_relative[1] + Gamma[2] * Y_relative[2]) / 2 - width / density_water * _wind_stress = 0;
88 |
89 | for node in 3:n_level_nodes - 1 loop
90 | der(Q_relative[node]) + 2 * V0[(node - 1) * 2] * ((Q_relative[node + 1] - Q_relative[node - 1]) / (2 * dx)) + (C0[node] ^ 2 - V0[(node - 1) * 2] ^ 2) * ((T0[node - 1] + T0[node]) / 2) * ((Y_relative[node] - Y_relative[node - 1]) / dx) + Delta[node] * Q_relative[node] - (Gamma[node - 1] * Y_relative[node - 1] + Gamma[node] * Y_relative[node]) / 2 - width / density_water * _wind_stress = 0;
91 | end for;
92 |
93 | der(Q_relative[n_level_nodes]) + 2 * V0[2 * n_level_nodes - 2] * ((Q_relative[n_level_nodes + 1] - Q_relative[n_level_nodes - 1]) / (1.5 * dx)) + (C0[n_level_nodes] ^ 2 - V0[2 * n_level_nodes - 2] ^ 2) * ((T0[n_level_nodes - 1] + T0[n_level_nodes]) / 2) * ((Y_relative[n_level_nodes] - Y_relative[n_level_nodes - 1]) / dx) + Delta[n_level_nodes] * Q_relative[n_level_nodes] - (Gamma[n_level_nodes - 1] * Y_relative[n_level_nodes - 1] + Gamma[n_level_nodes] * Y_relative[n_level_nodes]) / 2 - width / density_water * _wind_stress = 0;
94 |
95 |
96 | der(_cross_section[1]) + 2 * (Q_relative[2] - Q_relative[1]) / dx - 2 * _QPerpendicular_distribution[1] / dx = 0;
97 | for node in 2:n_level_nodes-1 loop
98 | // Middle heights calculated by mass conservation
99 | der(_cross_section[node]) + (Q_relative[node + 1] - Q_relative[node]) / dx - _QPerpendicular_distribution[node] / dx= 0;
100 | end for;
101 | // Boundary mass conservation
102 | der(_cross_section[n_level_nodes]) + 2 * (Q_relative[n_level_nodes + 1] - Q_relative[n_level_nodes]) / dx - 2 * _QPerpendicular_distribution[n_level_nodes] / dx = 0;
103 |
104 |
105 | for node in 1:n_level_nodes loop
106 | Y_relative[node] = _cross_section[node] / T0[node];
107 | end for;
108 |
109 | /*
110 | T0[1]*der(Y_relative[1]) + 2 * (Q_relative[2] - Q_relative[1]) / dx = 0;
111 | for node in 2:n_level_nodes-1 loop
112 | // Middle heights calculated by mass conservation
113 | T0[node]*der(Y_relative[node]) + (Q_relative[node + 1] - Q_relative[node]) / dx = 0;
114 | end for;
115 | // Boundary mass conservation
116 | T0[n_level_nodes]*der(Y_relative[n_level_nodes]) + 2 * (Q_relative[n_level_nodes + 1] - Q_relative[n_level_nodes]) / dx = 0;
117 | */
118 |
119 | annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Rectangle(visible = true, fillColor = {0, 255, 255}, fillPattern = FillPattern.Solid, extent = {{-60, -20}, {60, 20}})}));
120 | end LinearisedSV;
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/calculate_parameters.py:
--------------------------------------------------------------------------------
1 | import math
2 | import numpy as np
3 |
4 |
5 | class GetLinearSVVariables:
6 | def __init__(
7 | self,
8 | n_level_nodes=4,
9 | length=0,
10 | h_b_up=0,
11 | h_b_down=0,
12 | q_nominal=0,
13 | width=0,
14 | y_nominal=0,
15 | y_nominal_down=0,
16 | friction_coefficient=0,
17 | ):
18 | self.n_level_nodes = n_level_nodes
19 | self.length = length
20 | self.h_b_up = h_b_up
21 | self.h_b_down = h_b_down
22 | self.q_nominal = q_nominal
23 | self.width = width
24 | self.y_nominal = y_nominal
25 | self.y_nominal_down = y_nominal_down
26 | self.friction_coefficient = friction_coefficient
27 |
28 | def getVariables(self):
29 | s_b = (self.h_b_up - self.h_b_down) / self.length
30 | g_n = 9.80665
31 | dx = self.length / (self.n_level_nodes - 1)
32 | self.q0 = [self.q_nominal] * (self.n_level_nodes + 1)
33 | self.t0 = [self.width] * self.n_level_nodes
34 | self.y0 = np.linspace(
35 | self.y_nominal_down, self.y_nominal, self.n_level_nodes
36 | )
37 | self.a0 = [None] * self.n_level_nodes
38 | for node in range(self.n_level_nodes):
39 | self.a0[node] = self.t0[node] * self.y0[node]
40 |
41 | # Calculate self.v0
42 | self.v0 = [None] * (2 * self.n_level_nodes - 1)
43 | self.v0[0] = self.q0[0] / self.a0[0]
44 | for node in range(1, self.n_level_nodes): # Q points
45 | self.v0[node * 2 - 1] = self.q0[node] / (
46 | (self.a0[node - 1] + self.a0[node]) / 2
47 | )
48 | for node in range(1, self.n_level_nodes - 1): # H points
49 | self.v0[node * 2] = ((self.q0[node + 1] + self.q0[node]) / 2) / (
50 | self.a0[node]
51 | )
52 | self.v0[2 * self.n_level_nodes - 2] = (
53 | self.q0[self.n_level_nodes] / (self.a0[self.n_level_nodes - 1])
54 | )
55 |
56 | # Calculate self.p0
57 | self.p0 = [None] * self.n_level_nodes
58 | for node in range(self.n_level_nodes):
59 | self.p0[node] = self.t0[node] + 2 * self.y0[node]
60 |
61 | self.r = [None] * self.n_level_nodes
62 | for node in range(self.n_level_nodes):
63 | self.r[node] = self.a0[node] / self.p0[node]
64 |
65 | self.sf = [None] * (2 * self.n_level_nodes - 1)
66 | self.sf[0] = (
67 | math.pow(self.q0[0], 2) * math.pow(self.friction_coefficient, 2)
68 | ) / (math.pow((self.a0[0]), 2) * math.pow(self.r[0], 4 / 3))
69 | for node in range(1, self.n_level_nodes): # Q points
70 | self.sf[node * 2 - 1] = (
71 | math.pow(self.q0[node], 2) * math.pow(self.friction_coefficient, 2)
72 | ) / (
73 | math.pow(((self.a0[node - 1] + self.a0[node]) / 2), 2)
74 | * math.pow(((self.r[node - 1] + self.r[node]) / 2), 4 / 3)
75 | )
76 | for node in range(1, self.n_level_nodes - 1): # H points
77 | self.sf[node * 2] = (
78 | math.pow((self.q0[node + 1] + self.q0[node]) / 2, 2)
79 | * math.pow(self.friction_coefficient, 2)
80 | ) / (math.pow((self.a0[node]), 2) * math.pow(self.r[node], 4 / 3))
81 | self.sf[2 * self.n_level_nodes - 2] = (
82 | math.pow(self.q0[self.n_level_nodes], 2)
83 | * math.pow(self.friction_coefficient, 2)
84 | ) / (
85 | math.pow((self.a0[self.n_level_nodes - 1]), 2)
86 | * math.pow(self.r[self.n_level_nodes - 1], 4 / 3)
87 | )
88 |
89 | # Calculate self.c0
90 | self.c0 = [None] * (self.n_level_nodes + 1)
91 | self.c0[0] = math.sqrt(g_n * self.y0[0])
92 | for node in range(1, self.n_level_nodes):
93 | self.c0[node] = math.sqrt(g_n * (self.y0[node - 1] + self.y0[node]) / 2)
94 | self.c0[self.n_level_nodes] = math.sqrt(g_n * self.y0[self.n_level_nodes - 1])
95 |
96 | self.f0 = [None] * (2 * self.n_level_nodes - 1)
97 | self.f0[0] = self.v0[0] / self.c0[0]
98 | for node in range(1, self.n_level_nodes): # Q points
99 | self.f0[node * 2 - 1] = self.v0[node * 2 - 1] / self.c0[node]
100 | for node in range(1, self.n_level_nodes - 1): # H points
101 | self.f0[node * 2] = self.v0[node * 2 - 1] / (
102 | (self.c0[node + 1] + self.c0[node]) / 2
103 | )
104 | self.f0[2 * self.n_level_nodes - 2] = (
105 | self.v0[2 * self.n_level_nodes - 2] / self.c0[self.n_level_nodes]
106 | )
107 |
108 | self.dydx = [None] * (2 * self.n_level_nodes - 1)
109 | for node in range(2 * self.n_level_nodes - 1): # Q points
110 | self.dydx[node] = (s_b - self.sf[node]) / (1 - math.pow((self.f0[node]), 2))
111 |
112 | # Calculate self.deltas
113 | self.delta = [None] * (self.n_level_nodes + 1)
114 | self.delta[0] = (2 * g_n / self.v0[0]) * (s_b - self.dydx[0])
115 | for node in range(1, self.n_level_nodes):
116 | self.delta[node] = (2 * g_n / self.v0[node * 2 - 1]) * (
117 | s_b - self.dydx[node * 2 - 1]
118 | )
119 | self.delta[self.n_level_nodes] = (
120 | 2 * g_n / self.v0[2 * self.n_level_nodes - 2]
121 | ) * (s_b - self.dydx[2 * self.n_level_nodes - 2])
122 |
123 | # Calculate self.kappas
124 | self.kappa = [None] * self.n_level_nodes
125 | for node in range(self.n_level_nodes):
126 | self.kappa[node] = (
127 | 7 / 3
128 | - ((4 * (self.a0[node])) / (3 * self.t0[node] * self.p0[node])) * 2
129 | ) # This 2 is the value of the PDE because of rectangular shape
130 |
131 | # Calculate self.f2
132 | self.f2 = [None] * self.n_level_nodes
133 | for node in range(self.n_level_nodes):
134 | self.f2[node] = (math.pow(self.v0[node * 2], 2) * self.t0[node]) / (
135 | g_n * (self.a0[node])
136 | )
137 |
138 | # Calculate self.gammas
139 | self.gamma = [None] * self.n_level_nodes
140 | self.gamma[0] = math.pow(self.v0[0], 2) * (
141 | (self.t0[1] - self.t0[0]) / dx
142 | ) + g_n * self.t0[0] * (
143 | (1 + self.kappa[0]) * s_b
144 | - (1 + self.kappa[0] - (self.kappa[0] - 2) * self.f2[0]) * self.dydx[0]
145 | )
146 | for node in range(1, self.n_level_nodes - 1):
147 | self.gamma[node] = math.pow(self.v0[node * 2], 2) * (
148 | (self.t0[node + 1] - self.t0[node - 1]) / (2 * dx)
149 | ) + g_n * self.t0[node] * (
150 | (1 + self.kappa[node]) * s_b
151 | - (1 + self.kappa[node] - (self.kappa[node] - 2) * self.f2[node])
152 | * self.dydx[node * 2]
153 | )
154 | self.gamma[self.n_level_nodes - 1] = math.pow(
155 | self.v0[2 * self.n_level_nodes - 2], 2
156 | ) * (
157 | (self.t0[self.n_level_nodes - 1] - self.t0[self.n_level_nodes - 2]) / dx
158 | ) + g_n * self.t0[self.n_level_nodes - 1] * (
159 | (1 + self.kappa[self.n_level_nodes - 1]) * s_b
160 | - (
161 | 1
162 | + self.kappa[self.n_level_nodes - 1]
163 | - (self.kappa[self.n_level_nodes - 1] - 2)
164 | * self.f2[self.n_level_nodes - 1]
165 | )
166 | * self.dydx[2 * self.n_level_nodes - 2]
167 | )
168 |
--------------------------------------------------------------------------------
/COPYING.LESSER:
--------------------------------------------------------------------------------
1 | GNU LESSER GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 |
9 | This version of the GNU Lesser General Public License incorporates
10 | the terms and conditions of version 3 of the GNU General Public
11 | License, supplemented by the additional permissions listed below.
12 |
13 | 0. Additional Definitions.
14 |
15 | As used herein, "this License" refers to version 3 of the GNU Lesser
16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU
17 | General Public License.
18 |
19 | "The Library" refers to a covered work governed by this License,
20 | other than an Application or a Combined Work as defined below.
21 |
22 | An "Application" is any work that makes use of an interface provided
23 | by the Library, but which is not otherwise based on the Library.
24 | Defining a subclass of a class defined by the Library is deemed a mode
25 | of using an interface provided by the Library.
26 |
27 | A "Combined Work" is a work produced by combining or linking an
28 | Application with the Library. The particular version of the Library
29 | with which the Combined Work was made is also called the "Linked
30 | Version".
31 |
32 | The "Minimal Corresponding Source" for a Combined Work means the
33 | Corresponding Source for the Combined Work, excluding any source code
34 | for portions of the Combined Work that, considered in isolation, are
35 | based on the Application, and not on the Linked Version.
36 |
37 | The "Corresponding Application Code" for a Combined Work means the
38 | object code and/or source code for the Application, including any data
39 | and utility programs needed for reproducing the Combined Work from the
40 | Application, but excluding the System Libraries of the Combined Work.
41 |
42 | 1. Exception to Section 3 of the GNU GPL.
43 |
44 | You may convey a covered work under sections 3 and 4 of this License
45 | without being bound by section 3 of the GNU GPL.
46 |
47 | 2. Conveying Modified Versions.
48 |
49 | If you modify a copy of the Library, and, in your modifications, a
50 | facility refers to a function or data to be supplied by an Application
51 | that uses the facility (other than as an argument passed when the
52 | facility is invoked), then you may convey a copy of the modified
53 | version:
54 |
55 | a) under this License, provided that you make a good faith effort to
56 | ensure that, in the event an Application does not supply the
57 | function or data, the facility still operates, and performs
58 | whatever part of its purpose remains meaningful, or
59 |
60 | b) under the GNU GPL, with none of the additional permissions of
61 | this License applicable to that copy.
62 |
63 | 3. Object Code Incorporating Material from Library Header Files.
64 |
65 | The object code form of an Application may incorporate material from
66 | a header file that is part of the Library. You may convey such object
67 | code under terms of your choice, provided that, if the incorporated
68 | material is not limited to numerical parameters, data structure
69 | layouts and accessors, or small macros, inline functions and templates
70 | (ten or fewer lines in length), you do both of the following:
71 |
72 | a) Give prominent notice with each copy of the object code that the
73 | Library is used in it and that the Library and its use are
74 | covered by this License.
75 |
76 | b) Accompany the object code with a copy of the GNU GPL and this license
77 | document.
78 |
79 | 4. Combined Works.
80 |
81 | You may convey a Combined Work under terms of your choice that,
82 | taken together, effectively do not restrict modification of the
83 | portions of the Library contained in the Combined Work and reverse
84 | engineering for debugging such modifications, if you also do each of
85 | the following:
86 |
87 | a) Give prominent notice with each copy of the Combined Work that
88 | the Library is used in it and that the Library and its use are
89 | covered by this License.
90 |
91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license
92 | document.
93 |
94 | c) For a Combined Work that displays copyright notices during
95 | execution, include the copyright notice for the Library among
96 | these notices, as well as a reference directing the user to the
97 | copies of the GNU GPL and this license document.
98 |
99 | d) Do one of the following:
100 |
101 | 0) Convey the Minimal Corresponding Source under the terms of this
102 | License, and the Corresponding Application Code in a form
103 | suitable for, and under terms that permit, the user to
104 | recombine or relink the Application with a modified version of
105 | the Linked Version to produce a modified Combined Work, in the
106 | manner specified by section 6 of the GNU GPL for conveying
107 | Corresponding Source.
108 |
109 | 1) Use a suitable shared library mechanism for linking with the
110 | Library. A suitable mechanism is one that (a) uses at run time
111 | a copy of the Library already present on the user's computer
112 | system, and (b) will operate properly with a modified version
113 | of the Library that is interface-compatible with the Linked
114 | Version.
115 |
116 | e) Provide Installation Information, but only if you would otherwise
117 | be required to provide such information under section 6 of the
118 | GNU GPL, and only to the extent that such information is
119 | necessary to install and execute a modified version of the
120 | Combined Work produced by recombining or relinking the
121 | Application with a modified version of the Linked Version. (If
122 | you use option 4d0, the Installation Information must accompany
123 | the Minimal Corresponding Source and Corresponding Application
124 | Code. If you use option 4d1, you must provide the Installation
125 | Information in the manner specified by section 6 of the GNU GPL
126 | for conveying Corresponding Source.)
127 |
128 | 5. Combined Libraries.
129 |
130 | You may place library facilities that are a work based on the
131 | Library side by side in a single library together with other library
132 | facilities that are not Applications and are not covered by this
133 | License, and convey such a combined library under terms of your
134 | choice, if you do both of the following:
135 |
136 | a) Accompany the combined library with a copy of the same work based
137 | on the Library, uncombined with any other library facilities,
138 | conveyed under the terms of this License.
139 |
140 | b) Give prominent notice with the combined library that part of it
141 | is a work based on the Library, and explaining where to find the
142 | accompanying uncombined form of the same work.
143 |
144 | 6. Revised Versions of the GNU Lesser General Public License.
145 |
146 | The Free Software Foundation may publish revised and/or new versions
147 | of the GNU Lesser General Public License from time to time. Such new
148 | versions will be similar in spirit to the present version, but may
149 | differ in detail to address new problems or concerns.
150 |
151 | Each version is given a distinguishing version number. If the
152 | Library as you received it specifies that a certain numbered version
153 | of the GNU Lesser General Public License "or any later version"
154 | applies to it, you have the option of following the terms and
155 | conditions either of that published version or of any later version
156 | published by the Free Software Foundation. If the Library as you
157 | received it does not specify a version number of the GNU Lesser
158 | General Public License, you may choose any version of the GNU Lesser
159 | General Public License ever published by the Free Software Foundation.
160 |
161 | If the Library as you received it specifies that a proxy can decide
162 | whether future versions of the GNU Lesser General Public License shall
163 | apply, that proxy's public statement of acceptance of any version is
164 | permanent authorization for you to choose that version for the
165 | Library.
166 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/modelica/Deltares/ChannelFlow/Hydraulic/Branches/Internal/PartialHomotopic.mo:
--------------------------------------------------------------------------------
1 | within Deltares.ChannelFlow.Hydraulic.Branches.Internal;
2 |
3 | partial model PartialHomotopic
4 | // Note: Homotopic path stability can only be guaranteed if semi_implicit_step_size
5 | // is set to the optimization step size, and if use_convective_acceleration is set
6 | // to false. Consult Baayen and Piovesan, A continuation approach to nonlinear
7 | // model predictive control of open channel systems, 2018 for details:
8 | // https://arxiv.org/abs/1801.06507
9 | import SI = Modelica.Units.SI;
10 | extends Deltares.ChannelFlow.Internal.HQTwoPort;
11 | extends Deltares.ChannelFlow.Internal.QForcing;
12 | extends Deltares.ChannelFlow.Internal.QLateral;
13 | function smooth_switch = Deltares.ChannelFlow.Internal.Functions.SmoothSwitch;
14 | // Lateral inflow. A Matrix with n_QForcing, nQLateral rows and n_level_nodes columns. Each row corresponds to a QForcing, QLateral.Q and defines the distribution of that QForcing, QLateral.Q along the Branch.
15 | // NOTE: To preserve mass, each row should sum to 1.0
16 | parameter Real QForcing_map[n_QForcing, n_level_nodes] = fill(1.0 / n_level_nodes, n_QForcing, n_level_nodes);
17 | parameter Real QLateral_map[n_QLateral, n_level_nodes] = fill(1.0 / n_level_nodes, n_QLateral, n_level_nodes);
18 | // Wind stress
19 | input SI.Stress wind_stress_u(nominal = 1e-1) = 0.0; // Wind stress in x (u, easting) direction (= 0 radians, 0 degrees)
20 | input SI.Stress wind_stress_v(nominal = 1e-1) = 0.0; // Wind stress in y (v, northing) direction (= 0.5*pi radians, 90 degrees)
21 | // Flow
22 | SI.VolumeFlowRate[n_level_nodes + 1] Q(each nominal = abs(Q_nominal));
23 | //Assumption: the minimum water level in the channel is at least the maximum bottom level at any part of the channel,
24 | // thus for steep channels this assumption might be a bit restrictive, but operatinally still reasonable.
25 | SI.Position[n_level_nodes] H(each min=max(H_b[1],H_b[n_level_nodes]));
26 | // Array of Bottom Levels
27 | parameter SI.Position[n_level_nodes] H_b;
28 | // Length
29 | parameter SI.Distance length = 1.0;
30 | // Rotation
31 | parameter Real rotation_deg = 0.0; // Rotation of branch relative to x (u, easting) in degrees
32 | // Nominal depth and width for linearized pressure term and wind stress term
33 | parameter SI.Distance nominal_depth[n_level_nodes + 1] = fill(1.0, n_level_nodes + 1);
34 | parameter SI.Distance nominal_width[n_level_nodes + 1] = fill(1.0, n_level_nodes + 1);
35 | // Water density
36 | parameter SI.Density density_water = 1000.0;
37 | // Chézy or Manning bottom friction coefficient
38 | parameter Real friction_coefficient = 0.0;
39 | // Interpret 'friction_coefficient' as Manning instead of the default Chézy
40 | parameter Boolean use_manning = false;
41 | // Discretization options
42 | parameter Boolean use_inertia = true;
43 | parameter Boolean use_convective_acceleration = false;
44 | parameter Boolean use_upwind = true;
45 | parameter Integer n_level_nodes = 2;
46 | // Homotopy parameter
47 | parameter Real theta;
48 | // Nominal flow used in linearization
49 | parameter SI.VolumeFlowRate Q_nominal = 1.0;
50 | // Minimum value of the divisor of the friction term. This defaults to a nonzero value,
51 | // so that empty reaches won't immediately yield NaN errors.
52 | parameter Real min_divisor = Deltares.Constants.eps;
53 | // Minimum value of the sabs(Q) part of the friction term. This defaults to a nonzero value,
54 | // so that sabs(Q) = sqrt(Q^2 + min_abs_Q^2) is continuously differentiable for all Q.
55 | parameter SI.VolumeFlowRate min_abs_Q = Deltares.Constants.eps;
56 | // Time step size used to create a semi-implicit discretization of the friction term.
57 | // Zero by default, which means that a fully implicit discretization is used.
58 | input SI.Duration semi_implicit_step_size = 0.0;
59 | // Substance flow rates
60 | SI.VolumeFlowRate M[n_level_nodes + 1, medium.n_substances](each nominal = 10);
61 | // Substance concentrations
62 | SI.Density C[n_level_nodes, medium.n_substances](each min = 0, each nominal = 1);
63 | // Nominal substance concentrations used in linearization
64 | parameter Real C_nominal[medium.n_substances] = fill(1e-3, medium.n_substances);
65 | protected
66 | SI.Stress _wind_stress;
67 | Real[n_level_nodes] _dQ_sq_div_Adx(each unit = "m3/s2");
68 | parameter SI.Angle rotation_rad = Deltares.Constants.D2R * rotation_deg; // Conversion to rotation in radians
69 | parameter SI.Distance dx = length / (n_level_nodes - 1);
70 | SI.Area[n_level_nodes] _friction;
71 | SI.Area[n_level_nodes] _cross_section;
72 | SI.Area[n_level_nodes + 1] _cross_sectionq;
73 | SI.Distance[n_level_nodes] _wetted_perimeter;
74 | parameter SI.Distance[n_level_nodes] _dxq = cat(1, {dx / 2}, fill(dx, n_level_nodes - 2), {dx / 2});
75 | SI.VolumeFlowRate[n_QLateral] _lat = QLateral.Q;
76 | SI.VolumeFlowRate[n_level_nodes] _QPerpendicular_distribution = transpose(QForcing_map) * QForcing .+ transpose(QLateral_map) * _lat;
77 | equation
78 | // Store boundary values into array for convenience
79 | Q[1] = HQUp.Q;
80 | Q[n_level_nodes + 1] = -HQDown.Q;
81 | H[1] = HQUp.H;
82 | H[n_level_nodes] = HQDown.H;
83 | M[1, :] = HQUp.M;
84 | M[n_level_nodes + 1, :] = -HQDown.M;
85 | C[1, :] = HQUp.C;
86 | C[n_level_nodes, :] = HQDown.C;
87 | // Calculate wind stress
88 | _wind_stress = wind_stress_u * cos(rotation_rad) + wind_stress_v * sin(rotation_rad);
89 | // Compute cross sections for q nodes
90 | _cross_sectionq[1] = _cross_section[1];
91 | _cross_sectionq[2:n_level_nodes] = 0.5 * (_cross_section[1:n_level_nodes - 1] .+ _cross_section[2:n_level_nodes]);
92 | _cross_sectionq[n_level_nodes + 1] = _cross_section[n_level_nodes];
93 | // Compute dQ/dx for advection term
94 | _dQ_sq_div_Adx[1] = 0;
95 | for section in 2:n_level_nodes loop
96 | if (use_inertia and use_convective_acceleration) then
97 | if use_upwind then
98 | _dQ_sq_div_Adx[section] = theta * (
99 | smooth_switch(Q[section])
100 | * (
101 | Q[section] ^ 2 / (min_divisor + _cross_sectionq[section])
102 | - Q[section - 1] ^ 2 / (min_divisor + _cross_sectionq[section - 1])
103 | )
104 | / _dxq[section - 1]
105 | + (1 - smooth_switch(Q[section]))
106 | * (
107 | Q[section + 1] ^ 2 / (min_divisor + _cross_sectionq[section + 1])
108 | - Q[section] ^ 2 / (min_divisor + _cross_sectionq[section])
109 | )
110 | / _dxq[section]
111 | ) + (1 - theta) * (
112 | (
113 | Q[section + 1]
114 | * Q_nominal
115 | / (nominal_width[section + 1] * nominal_depth[section + 1])
116 | - Q[section - 1]
117 | * Q_nominal
118 | / (nominal_width[section - 1] * nominal_depth[section - 1])
119 | )
120 | / (_dxq[section - 1] + _dxq[section])
121 | );
122 | else
123 | _dQ_sq_div_Adx[section] = theta * (
124 | (
125 | Q[section + 1] ^ 2 / (min_divisor + _cross_sectionq[section + 1])
126 | - Q[section - 1] ^ 2 / (min_divisor + _cross_sectionq[section - 1])
127 | )
128 | / (_dxq[section - 1] + _dxq[section])
129 | ) + (1 - theta) * (
130 | (
131 | Q[section + 1]
132 | * Q_nominal
133 | / (nominal_width[section + 1] * nominal_depth[section + 1])
134 | - Q[section - 1]
135 | * Q_nominal
136 | / (nominal_width[section - 1] * nominal_depth[section - 1])
137 | )
138 | / (_dxq[section - 1] + _dxq[section])
139 | );
140 | end if;
141 | else
142 | _dQ_sq_div_Adx[section] = 0.0;
143 | end if;
144 | end for;
145 | // Momentum equation
146 | // Note that the equation is formulated without any divisions, to make collocation more robust.
147 | _friction[1] = 0.0;
148 | for section in 2:n_level_nodes loop
149 | if use_manning then
150 | _friction[section] = friction_coefficient^2 * (
151 | theta * (
152 | Q[section] * sqrt(Q[section]^2 + min_abs_Q^2) * (min_divisor + 0.5 * (_wetted_perimeter[section] - semi_implicit_step_size * der(_wetted_perimeter[section]) + _wetted_perimeter[section - 1] - semi_implicit_step_size * der(_wetted_perimeter[section - 1])))^(8.0 / 6.0) / (min_divisor + 0.5 * (_cross_section[section] - semi_implicit_step_size * der(_cross_section[section]) + _cross_section[section - 1] - semi_implicit_step_size * der(_cross_section[section - 1])))^(14.0 / 6.0)
153 | ) + (1 - theta) * (
154 | Q[section] * sqrt(Q_nominal^2 + min_abs_Q^2) * (nominal_depth[section] * 2 + nominal_width[section])^(8.0 / 6.0) / (nominal_width[section] * nominal_depth[section])^(14.0 / 6.0)
155 | ));
156 | else
157 | _friction[section] =
158 | theta * (
159 | Q[section] * sqrt(Q[section]^2 + min_abs_Q^2) * (0.5 * (_wetted_perimeter[section] - semi_implicit_step_size * der(_wetted_perimeter[section]) + _wetted_perimeter[section - 1] - semi_implicit_step_size * der(_wetted_perimeter[section - 1]))) / (min_divisor + friction_coefficient^2 * (0.5 * (_cross_section[section] - semi_implicit_step_size * der(_cross_section[section]) + _cross_section[section - 1] - semi_implicit_step_size * der(_cross_section[section - 1])))^2)
160 | ) + (1 - theta) * (
161 | Q[section] * sqrt(Q_nominal^2 + min_abs_Q^2) * (nominal_depth[section] * 2 + nominal_width[section]) / (min_divisor + friction_coefficient^2 * (nominal_width[section] * nominal_depth[section])^2)
162 | );
163 | end if;
164 | // Water momentum equation
165 | (if use_inertia then 1 else 0) * (der(Q[section]) + _dQ_sq_div_Adx[section]) + theta * Deltares.Constants.g_n * 0.5 * (_cross_section[section] + _cross_section[section - 1]) * (H[section] - H[section - 1]) / dx + (1 - theta) * Deltares.Constants.g_n * (nominal_width[section] * nominal_depth[section]) * (H[section] - H[section - 1]) / dx - nominal_width[section] / density_water * _wind_stress + Deltares.Constants.g_n * _friction[section] = 0;
166 | // Substance transport
167 | M[section, :] = theta * (smooth_switch(Q[section]) * (Q[section] .* C[section - 1, :]) + (1 - smooth_switch(Q[section])) * (Q[section] .* C[section, :])) + (1 - theta) * (Q_nominal * C_nominal + C_nominal * (Q[section] - Q_nominal) + Q_nominal * ((if Q_nominal > 0 then C[section - 1, :] else C[section, :]) - C_nominal));
168 | end for;
169 | // Mass balance equations
170 | // Mass balance equations for same height nodes result in relation between flows on connectors. We can therefore chain branch elements.
171 | // Note that every mass balance is over half of the element, the cross section of which varies linearly between the cross section at the boundary and the cross section in the middle.
172 | for node in 1:n_level_nodes loop
173 | // Water mass balance
174 | theta * der(_cross_section[node]) + (1 - theta) * 0.5 * (nominal_width[node + 1] + nominal_width[node]) * der(H[node]) = (Q[node] - Q[node + 1] + _QPerpendicular_distribution[node]) / _dxq[node];
175 | // Substance mass balance
176 | theta * der(_cross_section[node] * C[node, :]) + (1 - theta) * 0.5 * (nominal_width[node + 1] * nominal_depth[node + 1] + nominal_width[node] * nominal_depth[node]) * der(C[node, :]) = (M[node, :] - M[node + 1, :]) / _dxq[node];
177 | end for;
178 | annotation(Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Rectangle(visible = true, fillColor = {0, 255, 255}, fillPattern = FillPattern.Solid, extent = {{-60, -20}, {60, 20}})}));
179 | end PartialHomotopic;
180 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/channel_flow_parameter_setting.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import numpy as np
3 | from rtctools_channel_flow.calculate_parameters import GetLinearSVVariables
4 |
5 | from functools import lru_cache
6 |
7 | logger = logging.getLogger("rtctools")
8 |
9 | @lru_cache(None)
10 | def inform_once(logger, msg):
11 | logger.info(msg)
12 |
13 |
14 | class ChannelFlowParameterSettingOpimizationMixin:
15 | """
16 | Sets parameters for channel flow blocks using in optimization mode.
17 |
18 | Supported blocks:
19 | Deltares.ChannelFlow.Hydraulic.Branches.LinearisedSV
20 |
21 | :cvar linearised_sv: True if LinearisedSV branch is used.
22 | Default is ``None``.
23 | :cvar linearised_sv_branches: List of LinearisedSV branches to set parameters for.
24 | Default is ``None``.
25 | :cvar linearised_sv_use_dynamic_nominals: True if dynamic nominal water depths
26 | should be used for LinearisedSV branches.
27 | Default is ``False``.
28 | :cvar linearised_sv_nominal_levels: dict
29 | A dictionary with nominal water depths for each branch.
30 | For each branch, nominals can be provided for up and down.
31 | values can be a fixed value or a timeseries.
32 |
33 | key: branch name,
34 | key: "H_b_up" or "H_b_down":
35 | value: nominal water depths. Can be a fixed value or a timeseries.
36 | These are the values around which the linearization is done.
37 | Possible types:
38 |
39 | - fixed value: float
40 | - timeseries name: str, name of the timeseries to use for nominal depths.
41 | Note that the value at the start of the optimization run will be
42 | used as the nominal depth.
43 | key: "Q_nominal":
44 | These are the values around which the linearization is done.
45 | Possible types:
46 |
47 | - fixed value: float
48 | - timeseries name: str, name of the timeseries to use for nominal flows.
49 | Note that the value at the start of the optimization run will be
50 | used as the nominal flow.
51 |
52 |
53 | example:
54 | {my_branch_name: {
55 | "H_b_up": 2.5,
56 | "H_b_down": "H_nominal_down_timeseries",
57 | "Q_nominal": "Q_nominal_timeseries_name"
58 | }}
59 | """
60 |
61 | linearised_sv = None
62 | linearised_sv_branches = None
63 | linearised_sv_use_dynamic_nominals = False
64 | linearised_sv_nominal_levels = None
65 |
66 | def parameters(self, ensemble_member):
67 | """
68 | Set the parameters for the channel flow blocks.
69 | """
70 | p = super().parameters(ensemble_member)
71 |
72 | if self.linearised_sv:
73 | # check if linearised_sv_branches is set
74 | if self.linearised_sv_branches is None:
75 | raise ValueError(
76 | "List of linearised_sv_branches is not provided while linearised_sv "
77 | "is True. Cannot set parameters for LinearisedSV block."
78 | )
79 | p = self.set_linear_sv_parameters(p=p)
80 | if self.linearised_sv_use_dynamic_nominals:
81 | # check if linearised_sv_nominal_levels is set
82 | if self.linearised_sv_nominal_levels is None:
83 | raise ValueError(
84 | "Dictionary of linearised_sv_nominal_levels is not provided "
85 | "while linearised_sv_use_dynamic_nominals is True. Cannot set "
86 | "dynamic nominal water depths for LinearisedSV block."
87 | )
88 | p = self.set_linear_sv_dynamic_nominal(p=p)
89 | return p
90 |
91 | def set_linear_sv_parameters(self, p):
92 | """
93 | Set the parameters for the block:
94 | Deltares.ChannelFlow.Hydraulic.Branches.LinearisedSV.
95 |
96 | :param p: The parameters of the model.
97 | :return: Updated parameters with LinearisedSV parameters.
98 | """
99 |
100 | # TODO: expand this method to accept the following parameters:
101 | # p["step_size"] = 0.0
102 | # use_semi_implicit = False
103 | # use_convective_acceleration = True
104 | # use_upwind = False
105 |
106 | required_params = [
107 | ".n_level_nodes",
108 | ".length",
109 | ".H_b_up",
110 | ".H_b_down",
111 | ".Q_nominal",
112 | ".width",
113 | ".H_nominal",
114 | ".H_nominal_down",
115 | ".friction_coefficient",
116 | ]
117 |
118 | for channel in self.linearised_sv_branches:
119 | # check if all required parameters are present
120 | for param in required_params:
121 | if channel + param not in p:
122 | raise ValueError(
123 | f"Parameter {channel + param} is required to set "
124 | "LinearisedSV parameters but is missing. "
125 | "This parameter can be set via the declaration of "
126 | f"the LinearisedSV branch, {channel}, in the model "
127 | ".mo file."
128 | )
129 | variableGetter = GetLinearSVVariables(
130 | n_level_nodes=int(p[channel + ".n_level_nodes"]),
131 | length=float(p[channel + ".length"]),
132 | h_b_up=float(p[channel + ".H_b_up"]),
133 | h_b_down=float(p[channel + ".H_b_down"]),
134 | q_nominal=float(p[channel + ".Q_nominal"]),
135 | width=float(p[channel + ".width"]),
136 | y_nominal=float(p[channel + ".H_nominal"]),
137 | y_nominal_down=float(p[channel + ".H_nominal_down"]),
138 | friction_coefficient=float(p[channel + ".friction_coefficient"]),
139 | )
140 | variableGetter.getVariables()
141 | for i in range(len(variableGetter.t0)):
142 | p[channel + ".T0[" + str(i + 1) + "]"] = variableGetter.t0[i]
143 | for i in range(len(variableGetter.v0)):
144 | p[channel + ".V0[" + str(i + 1) + "]"] = variableGetter.v0[i]
145 | for i in range(len(variableGetter.delta)):
146 | p[channel + ".Delta[" + str(i + 1) + "]"] = variableGetter.delta[i]
147 | for i in range(len(variableGetter.gamma)):
148 | p[channel + ".Gamma[" + str(i + 1) + "]"] = variableGetter.gamma[i]
149 | for i in range(len(variableGetter.c0)):
150 | p[channel + ".C0[" + str(i + 1) + "]"] = variableGetter.c0[i]
151 | logger.debug(
152 | f"Set Linear SV parameters for channel {channel} for channel flow"
153 | " block Deltares.ChannelFlow.Hydraulic.Branches.LinearisedSV"
154 | )
155 |
156 | return p
157 |
158 | def set_linear_sv_dynamic_nominal(self, p):
159 | """
160 | Set the dynamic nominal water depths for the block:
161 | Deltares.ChannelFlow.Hydraulic.Branches.LinearisedSV.
162 | If the required nominal data is not provided, the
163 | default nominal depths are used.
164 |
165 | :param p: The parameters of the model.
166 |
167 | :return: Updated parameters with dynamic nominal water depths.
168 | """
169 | for channel in self.linearised_sv_branches:
170 | if channel not in self.linearised_sv_nominal_levels:
171 | logger.warning(
172 | f"Nominal water depths for channel {channel} are not provided "
173 | "while linearised_sv_use_dynamic_nominals is True. Cannot set "
174 | "dynamic nominal water depths for LinearisedSV block. Using "
175 | "default nominal depths."
176 | )
177 | continue
178 | for key in ["H_b_up", "H_b_down", "Q_nominal"]:
179 | # check if key is present for channel
180 | if key not in self.linearised_sv_nominal_levels[channel]:
181 | continue
182 | # check if nominal is a float
183 | if isinstance(self.linearised_sv_nominal_levels[channel][key], float):
184 | nominal_level = self.linearised_sv_nominal_levels[channel][key]
185 | # check if nominal is a timeseries name
186 | elif isinstance(self.linearised_sv_nominal_levels[channel][key], str):
187 | # check if timeseries exists
188 | ts_name = self.linearised_sv_nominal_levels[channel][key]
189 | if ts_name not in self.io.get_timeseries_names():
190 | logger.warning(
191 | f"Nominal water depth timeseries {ts_name} for channel "
192 | f"{channel} and key {key} does not exist. Cannot set "
193 | "dynamic nominal water depths for LinearisedSV block."
194 | )
195 | continue
196 | nominal_level = self.get_timeseries(
197 | ts_name
198 | ).values[self.timeseries_import.forecast_index]
199 | # check if timeseries has a value at forecast_index
200 | if np.isnan(nominal_level):
201 | logger.warning(
202 | f"Nominal water depth timeseries {ts_name} "
203 | f"does not have a value at forecast index "
204 | f"{self.timeseries_import.forecast_index}. Cannot set "
205 | "dynamic nominal water depths for LinearisedSV block."
206 | )
207 | continue
208 | else:
209 | logger.warning(
210 | f"Nominal water depth for channel {channel} and key {key} is "
211 | "not a float or a timeseries name. Cannot set dynamic nominal "
212 | "water depths for LinearisedSV block."
213 | )
214 | continue
215 |
216 | if key == "H_b_up":
217 | depth = nominal_level - p[channel + ".H_b_up"]
218 | # nominal should be positive and non-zero
219 | # if value is zero net nominal to 1
220 | if depth <= 0:
221 | raise ValueError(
222 | f"Calculated dynamic nominal depth level for channel {channel} is non-positive. "
223 | f"Calculated value: {depth}. Provided nominal water depth is {nominal_level} "
224 | f"and upstream bed level is {p[channel + '.H_b_up']}."
225 | )
226 | p[channel + ".H_nominal"] = depth
227 | msg = (
228 | f"Set dynamic nominal {channel + '.H_nominal'} water depth for channel {channel} "
229 | f"to {depth}."
230 | )
231 | inform_once(logger, msg)
232 | elif key == "H_b_down":
233 | depth = nominal_level - p[channel + ".H_b_down"]
234 | # nominal should be positive and non-zero
235 | # if value is zero net nominal to 1
236 | if depth <= 0:
237 | raise ValueError(
238 | f"Calculated dynamic nominal depth level for channel {channel} is non-positive. "
239 | f"Calculated value: {depth}. Provided nominal water depth is {nominal_level} "
240 | f"and downstream bed level is {p[channel + '.H_b_down']}."
241 | )
242 | p[channel + ".H_nominal_down"] = depth
243 | msg = (
244 | f"Set dynamic nominal {channel + '.H_nominal_down'} water depth for channel {channel} "
245 | f"to {depth}."
246 | )
247 | inform_once(logger, msg)
248 | elif key == "Q_nominal":
249 | p[channel + ".Q_nominal"] = nominal_level
250 | logger.debug(
251 | f"Set dynamic nominal {channel + '.Q_nominal'} flow for channel {channel} "
252 | f"to {nominal_level}."
253 | )
254 |
255 | return p
256 |
--------------------------------------------------------------------------------
/src/rtctools_channel_flow/_version.py:
--------------------------------------------------------------------------------
1 | # This file helps to compute a version number in source trees obtained from
2 | # git-archive tarball (such as those provided by githubs download-from-tag
3 | # feature). Distribution tarballs (built by setup.py sdist) and build
4 | # directories (produced by setup.py build) will contain a much shorter file
5 | # that just contains the computed version number.
6 |
7 | # This file is released into the public domain.
8 | # Generated by versioneer-0.29
9 | # https://github.com/python-versioneer/python-versioneer
10 |
11 | """Git implementation of _version.py."""
12 |
13 | import errno
14 | import os
15 | import re
16 | import subprocess
17 | import sys
18 | from typing import Any, Callable, Dict, List, Optional, Tuple
19 | import functools
20 |
21 |
22 | def get_keywords() -> Dict[str, str]:
23 | """Get the keywords needed to look up the version information."""
24 | # these strings will be replaced by git during git-archive.
25 | # setup.py/versioneer.py will grep for the variable names, so they must
26 | # each be defined on a line of their own. _version.py will just call
27 | # get_keywords().
28 | git_refnames = " (HEAD -> master, tag: 1.4.0b1, tag: 1.3.1)"
29 | git_full = "345a07b96815df279a920e1fb0fb6ecf6a2016e0"
30 | git_date = "2025-12-17 09:28:56 +0100"
31 | keywords = {"refnames": git_refnames, "full": git_full, "date": git_date}
32 | return keywords
33 |
34 |
35 | class VersioneerConfig:
36 | """Container for Versioneer configuration parameters."""
37 |
38 | VCS: str
39 | style: str
40 | tag_prefix: str
41 | parentdir_prefix: str
42 | versionfile_source: str
43 | verbose: bool
44 |
45 |
46 | def get_config() -> VersioneerConfig:
47 | """Create, populate and return the VersioneerConfig() object."""
48 | # these strings are filled in when 'setup.py versioneer' creates
49 | # _version.py
50 | cfg = VersioneerConfig()
51 | cfg.VCS = "git"
52 | cfg.style = "pep440"
53 | cfg.tag_prefix = ""
54 | cfg.parentdir_prefix = "rtctools_channel_flow-"
55 | cfg.versionfile_source = "src/rtctools_channel_flow/_version.py"
56 | cfg.verbose = False
57 | return cfg
58 |
59 |
60 | class NotThisMethod(Exception):
61 | """Exception raised if a method is not valid for the current scenario."""
62 |
63 |
64 | LONG_VERSION_PY: Dict[str, str] = {}
65 | HANDLERS: Dict[str, Dict[str, Callable]] = {}
66 |
67 |
68 | def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator
69 | """Create decorator to mark a method as the handler of a VCS."""
70 |
71 | def decorate(f: Callable) -> Callable:
72 | """Store f in HANDLERS[vcs][method]."""
73 | if vcs not in HANDLERS:
74 | HANDLERS[vcs] = {}
75 | HANDLERS[vcs][method] = f
76 | return f
77 |
78 | return decorate
79 |
80 |
81 | def run_command(
82 | commands: List[str],
83 | args: List[str],
84 | cwd: Optional[str] = None,
85 | verbose: bool = False,
86 | hide_stderr: bool = False,
87 | env: Optional[Dict[str, str]] = None,
88 | ) -> Tuple[Optional[str], Optional[int]]:
89 | """Call the given command(s)."""
90 | assert isinstance(commands, list)
91 | process = None
92 |
93 | popen_kwargs: Dict[str, Any] = {}
94 | if sys.platform == "win32":
95 | # This hides the console window if pythonw.exe is used
96 | startupinfo = subprocess.STARTUPINFO()
97 | startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
98 | popen_kwargs["startupinfo"] = startupinfo
99 |
100 | for command in commands:
101 | try:
102 | dispcmd = str([command] + args)
103 | # remember shell=False, so use git.cmd on windows, not just git
104 | process = subprocess.Popen(
105 | [command] + args,
106 | cwd=cwd,
107 | env=env,
108 | stdout=subprocess.PIPE,
109 | stderr=(subprocess.PIPE if hide_stderr else None),
110 | **popen_kwargs,
111 | )
112 | break
113 | except OSError as e:
114 | if e.errno == errno.ENOENT:
115 | continue
116 | if verbose:
117 | print("unable to run %s" % dispcmd)
118 | print(e)
119 | return None, None
120 | else:
121 | if verbose:
122 | print("unable to find command, tried %s" % (commands,))
123 | return None, None
124 | stdout = process.communicate()[0].strip().decode()
125 | if process.returncode != 0:
126 | if verbose:
127 | print("unable to run %s (error)" % dispcmd)
128 | print("stdout was %s" % stdout)
129 | return None, process.returncode
130 | return stdout, process.returncode
131 |
132 |
133 | def versions_from_parentdir(
134 | parentdir_prefix: str,
135 | root: str,
136 | verbose: bool,
137 | ) -> Dict[str, Any]:
138 | """Try to determine the version from the parent directory name.
139 |
140 | Source tarballs conventionally unpack into a directory that includes both
141 | the project name and a version string. We will also support searching up
142 | two directory levels for an appropriately named parent directory
143 | """
144 | rootdirs = []
145 |
146 | for _ in range(3):
147 | dirname = os.path.basename(root)
148 | if dirname.startswith(parentdir_prefix):
149 | return {
150 | "version": dirname[len(parentdir_prefix) :],
151 | "full-revisionid": None,
152 | "dirty": False,
153 | "error": None,
154 | "date": None,
155 | }
156 | rootdirs.append(root)
157 | root = os.path.dirname(root) # up a level
158 |
159 | if verbose:
160 | print(
161 | "Tried directories %s but none started with prefix %s"
162 | % (str(rootdirs), parentdir_prefix)
163 | )
164 | raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
165 |
166 |
167 | @register_vcs_handler("git", "get_keywords")
168 | def git_get_keywords(versionfile_abs: str) -> Dict[str, str]:
169 | """Extract version information from the given file."""
170 | # the code embedded in _version.py can just fetch the value of these
171 | # keywords. When used from setup.py, we don't want to import _version.py,
172 | # so we do it with a regexp instead. This function is not used from
173 | # _version.py.
174 | keywords: Dict[str, str] = {}
175 | try:
176 | with open(versionfile_abs, "r") as fobj:
177 | for line in fobj:
178 | if line.strip().startswith("git_refnames ="):
179 | mo = re.search(r'=\s*"(.*)"', line)
180 | if mo:
181 | keywords["refnames"] = mo.group(1)
182 | if line.strip().startswith("git_full ="):
183 | mo = re.search(r'=\s*"(.*)"', line)
184 | if mo:
185 | keywords["full"] = mo.group(1)
186 | if line.strip().startswith("git_date ="):
187 | mo = re.search(r'=\s*"(.*)"', line)
188 | if mo:
189 | keywords["date"] = mo.group(1)
190 | except OSError:
191 | pass
192 | return keywords
193 |
194 |
195 | @register_vcs_handler("git", "keywords")
196 | def git_versions_from_keywords(
197 | keywords: Dict[str, str],
198 | tag_prefix: str,
199 | verbose: bool,
200 | ) -> Dict[str, Any]:
201 | """Get version information from git keywords."""
202 | if "refnames" not in keywords:
203 | raise NotThisMethod("Short version file found")
204 | date = keywords.get("date")
205 | if date is not None:
206 | # Use only the last line. Previous lines may contain GPG signature
207 | # information.
208 | date = date.splitlines()[-1]
209 |
210 | # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant
211 | # datestamp. However we prefer "%ci" (which expands to an "ISO-8601
212 | # -like" string, which we must then edit to make compliant), because
213 | # it's been around since git-1.5.3, and it's too difficult to
214 | # discover which version we're using, or to work around using an
215 | # older one.
216 | date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
217 | refnames = keywords["refnames"].strip()
218 | if refnames.startswith("$Format"):
219 | if verbose:
220 | print("keywords are unexpanded, not using")
221 | raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
222 | refs = {r.strip() for r in refnames.strip("()").split(",")}
223 | # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
224 | # just "foo-1.0". If we see a "tag: " prefix, prefer those.
225 | TAG = "tag: "
226 | tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)}
227 | if not tags:
228 | # Either we're using git < 1.8.3, or there really are no tags. We use
229 | # a heuristic: assume all version tags have a digit. The old git %d
230 | # expansion behaves like git log --decorate=short and strips out the
231 | # refs/heads/ and refs/tags/ prefixes that would let us distinguish
232 | # between branches and tags. By ignoring refnames without digits, we
233 | # filter out many common branch names like "release" and
234 | # "stabilization", as well as "HEAD" and "master".
235 | tags = {r for r in refs if re.search(r"\d", r)}
236 | if verbose:
237 | print("discarding '%s', no digits" % ",".join(refs - tags))
238 | if verbose:
239 | print("likely tags: %s" % ",".join(sorted(tags)))
240 | for ref in sorted(tags):
241 | # sorting will prefer e.g. "2.0" over "2.0rc1"
242 | if ref.startswith(tag_prefix):
243 | r = ref[len(tag_prefix) :]
244 | # Filter out refs that exactly match prefix or that don't start
245 | # with a number once the prefix is stripped (mostly a concern
246 | # when prefix is '')
247 | if not re.match(r"\d", r):
248 | continue
249 | if verbose:
250 | print("picking %s" % r)
251 | return {
252 | "version": r,
253 | "full-revisionid": keywords["full"].strip(),
254 | "dirty": False,
255 | "error": None,
256 | "date": date,
257 | }
258 | # no suitable tags, so version is "0+unknown", but full hex is still there
259 | if verbose:
260 | print("no suitable tags, using unknown + full revision id")
261 | return {
262 | "version": "0+unknown",
263 | "full-revisionid": keywords["full"].strip(),
264 | "dirty": False,
265 | "error": "no suitable tags",
266 | "date": None,
267 | }
268 |
269 |
270 | @register_vcs_handler("git", "pieces_from_vcs")
271 | def git_pieces_from_vcs(
272 | tag_prefix: str, root: str, verbose: bool, runner: Callable = run_command
273 | ) -> Dict[str, Any]:
274 | """Get version from 'git describe' in the root of the source tree.
275 |
276 | This only gets called if the git-archive 'subst' keywords were *not*
277 | expanded, and _version.py hasn't already been rewritten with a short
278 | version string, meaning we're inside a checked out source tree.
279 | """
280 | GITS = ["git"]
281 | if sys.platform == "win32":
282 | GITS = ["git.cmd", "git.exe"]
283 |
284 | # GIT_DIR can interfere with correct operation of Versioneer.
285 | # It may be intended to be passed to the Versioneer-versioned project,
286 | # but that should not change where we get our version from.
287 | env = os.environ.copy()
288 | env.pop("GIT_DIR", None)
289 | runner = functools.partial(runner, env=env)
290 |
291 | _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=not verbose)
292 | if rc != 0:
293 | if verbose:
294 | print("Directory %s not under git control" % root)
295 | raise NotThisMethod("'git rev-parse --git-dir' returned error")
296 |
297 | # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
298 | # if there isn't one, this yields HEX[-dirty] (no NUM)
299 | describe_out, rc = runner(
300 | GITS,
301 | [
302 | "describe",
303 | "--tags",
304 | "--dirty",
305 | "--always",
306 | "--long",
307 | "--match",
308 | f"{tag_prefix}[[:digit:]]*",
309 | ],
310 | cwd=root,
311 | )
312 | # --long was added in git-1.5.5
313 | if describe_out is None:
314 | raise NotThisMethod("'git describe' failed")
315 | describe_out = describe_out.strip()
316 | full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root)
317 | if full_out is None:
318 | raise NotThisMethod("'git rev-parse' failed")
319 | full_out = full_out.strip()
320 |
321 | pieces: Dict[str, Any] = {}
322 | pieces["long"] = full_out
323 | pieces["short"] = full_out[:7] # maybe improved later
324 | pieces["error"] = None
325 |
326 | branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root)
327 | # --abbrev-ref was added in git-1.6.3
328 | if rc != 0 or branch_name is None:
329 | raise NotThisMethod("'git rev-parse --abbrev-ref' returned error")
330 | branch_name = branch_name.strip()
331 |
332 | if branch_name == "HEAD":
333 | # If we aren't exactly on a branch, pick a branch which represents
334 | # the current commit. If all else fails, we are on a branchless
335 | # commit.
336 | branches, rc = runner(GITS, ["branch", "--contains"], cwd=root)
337 | # --contains was added in git-1.5.4
338 | if rc != 0 or branches is None:
339 | raise NotThisMethod("'git branch --contains' returned error")
340 | branches = branches.split("\n")
341 |
342 | # Remove the first line if we're running detached
343 | if "(" in branches[0]:
344 | branches.pop(0)
345 |
346 | # Strip off the leading "* " from the list of branches.
347 | branches = [branch[2:] for branch in branches]
348 | if "master" in branches:
349 | branch_name = "master"
350 | elif not branches:
351 | branch_name = None
352 | else:
353 | # Pick the first branch that is returned. Good or bad.
354 | branch_name = branches[0]
355 |
356 | pieces["branch"] = branch_name
357 |
358 | # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
359 | # TAG might have hyphens.
360 | git_describe = describe_out
361 |
362 | # look for -dirty suffix
363 | dirty = git_describe.endswith("-dirty")
364 | pieces["dirty"] = dirty
365 | if dirty:
366 | git_describe = git_describe[: git_describe.rindex("-dirty")]
367 |
368 | # now we have TAG-NUM-gHEX or HEX
369 |
370 | if "-" in git_describe:
371 | # TAG-NUM-gHEX
372 | mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe)
373 | if not mo:
374 | # unparsable. Maybe git-describe is misbehaving?
375 | pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out
376 | return pieces
377 |
378 | # tag
379 | full_tag = mo.group(1)
380 | if not full_tag.startswith(tag_prefix):
381 | if verbose:
382 | fmt = "tag '%s' doesn't start with prefix '%s'"
383 | print(fmt % (full_tag, tag_prefix))
384 | pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (
385 | full_tag,
386 | tag_prefix,
387 | )
388 | return pieces
389 | pieces["closest-tag"] = full_tag[len(tag_prefix) :]
390 |
391 | # distance: number of commits since tag
392 | pieces["distance"] = int(mo.group(2))
393 |
394 | # commit: short hex revision ID
395 | pieces["short"] = mo.group(3)
396 |
397 | else:
398 | # HEX: no tags
399 | pieces["closest-tag"] = None
400 | out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root)
401 | pieces["distance"] = len(out.split()) # total number of commits
402 |
403 | # commit date: see ISO-8601 comment in git_versions_from_keywords()
404 | date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip()
405 | # Use only the last line. Previous lines may contain GPG signature
406 | # information.
407 | date = date.splitlines()[-1]
408 | pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
409 |
410 | return pieces
411 |
412 |
413 | def plus_or_dot(pieces: Dict[str, Any]) -> str:
414 | """Return a + if we don't already have one, else return a ."""
415 | if "+" in pieces.get("closest-tag", ""):
416 | return "."
417 | return "+"
418 |
419 |
420 | def render_pep440(pieces: Dict[str, Any]) -> str:
421 | """Build up version string, with post-release "local version identifier".
422 |
423 | Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
424 | get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
425 |
426 | Exceptions:
427 | 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
428 | """
429 | if pieces["closest-tag"]:
430 | rendered = pieces["closest-tag"]
431 | if pieces["distance"] or pieces["dirty"]:
432 | rendered += plus_or_dot(pieces)
433 | rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
434 | if pieces["dirty"]:
435 | rendered += ".dirty"
436 | else:
437 | # exception #1
438 | rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
439 | if pieces["dirty"]:
440 | rendered += ".dirty"
441 | return rendered
442 |
443 |
444 | def render_pep440_branch(pieces: Dict[str, Any]) -> str:
445 | """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] .
446 |
447 | The ".dev0" means not master branch. Note that .dev0 sorts backwards
448 | (a feature branch will appear "older" than the master branch).
449 |
450 | Exceptions:
451 | 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty]
452 | """
453 | if pieces["closest-tag"]:
454 | rendered = pieces["closest-tag"]
455 | if pieces["distance"] or pieces["dirty"]:
456 | if pieces["branch"] != "master":
457 | rendered += ".dev0"
458 | rendered += plus_or_dot(pieces)
459 | rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
460 | if pieces["dirty"]:
461 | rendered += ".dirty"
462 | else:
463 | # exception #1
464 | rendered = "0"
465 | if pieces["branch"] != "master":
466 | rendered += ".dev0"
467 | rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
468 | if pieces["dirty"]:
469 | rendered += ".dirty"
470 | return rendered
471 |
472 |
473 | def pep440_split_post(ver: str) -> Tuple[str, Optional[int]]:
474 | """Split pep440 version string at the post-release segment.
475 |
476 | Returns the release segments before the post-release and the
477 | post-release version number (or -1 if no post-release segment is present).
478 | """
479 | vc = str.split(ver, ".post")
480 | return vc[0], int(vc[1] or 0) if len(vc) == 2 else None
481 |
482 |
483 | def render_pep440_pre(pieces: Dict[str, Any]) -> str:
484 | """TAG[.postN.devDISTANCE] -- No -dirty.
485 |
486 | Exceptions:
487 | 1: no tags. 0.post0.devDISTANCE
488 | """
489 | if pieces["closest-tag"]:
490 | if pieces["distance"]:
491 | # update the post release segment
492 | tag_version, post_version = pep440_split_post(pieces["closest-tag"])
493 | rendered = tag_version
494 | if post_version is not None:
495 | rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"])
496 | else:
497 | rendered += ".post0.dev%d" % (pieces["distance"])
498 | else:
499 | # no commits, use the tag as the version
500 | rendered = pieces["closest-tag"]
501 | else:
502 | # exception #1
503 | rendered = "0.post0.dev%d" % pieces["distance"]
504 | return rendered
505 |
506 |
507 | def render_pep440_post(pieces: Dict[str, Any]) -> str:
508 | """TAG[.postDISTANCE[.dev0]+gHEX] .
509 |
510 | The ".dev0" means dirty. Note that .dev0 sorts backwards
511 | (a dirty tree will appear "older" than the corresponding clean one),
512 | but you shouldn't be releasing software with -dirty anyways.
513 |
514 | Exceptions:
515 | 1: no tags. 0.postDISTANCE[.dev0]
516 | """
517 | if pieces["closest-tag"]:
518 | rendered = pieces["closest-tag"]
519 | if pieces["distance"] or pieces["dirty"]:
520 | rendered += ".post%d" % pieces["distance"]
521 | if pieces["dirty"]:
522 | rendered += ".dev0"
523 | rendered += plus_or_dot(pieces)
524 | rendered += "g%s" % pieces["short"]
525 | else:
526 | # exception #1
527 | rendered = "0.post%d" % pieces["distance"]
528 | if pieces["dirty"]:
529 | rendered += ".dev0"
530 | rendered += "+g%s" % pieces["short"]
531 | return rendered
532 |
533 |
534 | def render_pep440_post_branch(pieces: Dict[str, Any]) -> str:
535 | """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] .
536 |
537 | The ".dev0" means not master branch.
538 |
539 | Exceptions:
540 | 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty]
541 | """
542 | if pieces["closest-tag"]:
543 | rendered = pieces["closest-tag"]
544 | if pieces["distance"] or pieces["dirty"]:
545 | rendered += ".post%d" % pieces["distance"]
546 | if pieces["branch"] != "master":
547 | rendered += ".dev0"
548 | rendered += plus_or_dot(pieces)
549 | rendered += "g%s" % pieces["short"]
550 | if pieces["dirty"]:
551 | rendered += ".dirty"
552 | else:
553 | # exception #1
554 | rendered = "0.post%d" % pieces["distance"]
555 | if pieces["branch"] != "master":
556 | rendered += ".dev0"
557 | rendered += "+g%s" % pieces["short"]
558 | if pieces["dirty"]:
559 | rendered += ".dirty"
560 | return rendered
561 |
562 |
563 | def render_pep440_old(pieces: Dict[str, Any]) -> str:
564 | """TAG[.postDISTANCE[.dev0]] .
565 |
566 | The ".dev0" means dirty.
567 |
568 | Exceptions:
569 | 1: no tags. 0.postDISTANCE[.dev0]
570 | """
571 | if pieces["closest-tag"]:
572 | rendered = pieces["closest-tag"]
573 | if pieces["distance"] or pieces["dirty"]:
574 | rendered += ".post%d" % pieces["distance"]
575 | if pieces["dirty"]:
576 | rendered += ".dev0"
577 | else:
578 | # exception #1
579 | rendered = "0.post%d" % pieces["distance"]
580 | if pieces["dirty"]:
581 | rendered += ".dev0"
582 | return rendered
583 |
584 |
585 | def render_git_describe(pieces: Dict[str, Any]) -> str:
586 | """TAG[-DISTANCE-gHEX][-dirty].
587 |
588 | Like 'git describe --tags --dirty --always'.
589 |
590 | Exceptions:
591 | 1: no tags. HEX[-dirty] (note: no 'g' prefix)
592 | """
593 | if pieces["closest-tag"]:
594 | rendered = pieces["closest-tag"]
595 | if pieces["distance"]:
596 | rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
597 | else:
598 | # exception #1
599 | rendered = pieces["short"]
600 | if pieces["dirty"]:
601 | rendered += "-dirty"
602 | return rendered
603 |
604 |
605 | def render_git_describe_long(pieces: Dict[str, Any]) -> str:
606 | """TAG-DISTANCE-gHEX[-dirty].
607 |
608 | Like 'git describe --tags --dirty --always -long'.
609 | The distance/hash is unconditional.
610 |
611 | Exceptions:
612 | 1: no tags. HEX[-dirty] (note: no 'g' prefix)
613 | """
614 | if pieces["closest-tag"]:
615 | rendered = pieces["closest-tag"]
616 | rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
617 | else:
618 | # exception #1
619 | rendered = pieces["short"]
620 | if pieces["dirty"]:
621 | rendered += "-dirty"
622 | return rendered
623 |
624 |
625 | def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]:
626 | """Render the given version pieces into the requested style."""
627 | if pieces["error"]:
628 | return {
629 | "version": "unknown",
630 | "full-revisionid": pieces.get("long"),
631 | "dirty": None,
632 | "error": pieces["error"],
633 | "date": None,
634 | }
635 |
636 | if not style or style == "default":
637 | style = "pep440" # the default
638 |
639 | if style == "pep440":
640 | rendered = render_pep440(pieces)
641 | elif style == "pep440-branch":
642 | rendered = render_pep440_branch(pieces)
643 | elif style == "pep440-pre":
644 | rendered = render_pep440_pre(pieces)
645 | elif style == "pep440-post":
646 | rendered = render_pep440_post(pieces)
647 | elif style == "pep440-post-branch":
648 | rendered = render_pep440_post_branch(pieces)
649 | elif style == "pep440-old":
650 | rendered = render_pep440_old(pieces)
651 | elif style == "git-describe":
652 | rendered = render_git_describe(pieces)
653 | elif style == "git-describe-long":
654 | rendered = render_git_describe_long(pieces)
655 | else:
656 | raise ValueError("unknown style '%s'" % style)
657 |
658 | return {
659 | "version": rendered,
660 | "full-revisionid": pieces["long"],
661 | "dirty": pieces["dirty"],
662 | "error": None,
663 | "date": pieces.get("date"),
664 | }
665 |
666 |
667 | def get_versions() -> Dict[str, Any]:
668 | """Get version information or return default if unable to do so."""
669 | # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
670 | # __file__, we can work backwards from there to the root. Some
671 | # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
672 | # case we can only use expanded keywords.
673 |
674 | cfg = get_config()
675 | verbose = cfg.verbose
676 |
677 | try:
678 | return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose)
679 | except NotThisMethod:
680 | pass
681 |
682 | try:
683 | root = os.path.realpath(__file__)
684 | # versionfile_source is the relative path from the top of the source
685 | # tree (where the .git directory might live) to this file. Invert
686 | # this to find the root from __file__.
687 | for _ in cfg.versionfile_source.split("/"):
688 | root = os.path.dirname(root)
689 | except NameError:
690 | return {
691 | "version": "0+unknown",
692 | "full-revisionid": None,
693 | "dirty": None,
694 | "error": "unable to find root of source tree",
695 | "date": None,
696 | }
697 |
698 | try:
699 | pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
700 | return render(pieces, cfg.style)
701 | except NotThisMethod:
702 | pass
703 |
704 | try:
705 | if cfg.parentdir_prefix:
706 | return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
707 | except NotThisMethod:
708 | pass
709 |
710 | return {
711 | "version": "0+unknown",
712 | "full-revisionid": None,
713 | "dirty": None,
714 | "error": "unable to compute version",
715 | "date": None,
716 | }
717 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------