This commit is contained in:
Michael Tryby
2018-08-28 08:50:41 -04:00
40 changed files with 3089 additions and 1828 deletions

View File

@@ -40,6 +40,7 @@
cmake_minimum_required (VERSION 2.8.8) cmake_minimum_required (VERSION 2.8.8)
project(EPANET) project(EPANET)
add_subdirectory(run)
add_subdirectory(tools/epanet-output) add_subdirectory(tools/epanet-output)
IF (BUILD_TESTS) IF (BUILD_TESTS)
@@ -51,6 +52,7 @@ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
# Sets the position independent code property for all targets # Sets the position independent code property for all targets
SET(CMAKE_POSITION_INDEPENDENT_CODE ON) SET(CMAKE_POSITION_INDEPENDENT_CODE ON)
@@ -66,40 +68,25 @@ IF (MSVC)
ENDIF (MSVC) ENDIF (MSVC)
#include_directories(include src)
# configure file groups # configure file groups
file(GLOB EPANET_SOURCES src/*.c) file(GLOB EPANET_SOURCES src/*.c src/util/*.c)
#set(EPANET_API_HEADER include/epanet2.h) file(GLOB EPANET_LIB_ALL src/* src/util/*)
set(EPANET_CLI_SOURCES run/main.c)
file(GLOB EPANET_LIB_ALL src/*)
source_group("Library" FILES ${EPANET_LIB_ALL}) source_group("Library" FILES ${EPANET_LIB_ALL})
source_group("CLI" REGULAR_EXPRESSION "run/.*")
# the shared library # the shared library
add_library(epanet SHARED ${EPANET_SOURCES}) #${EPANET_API_HEADER}) add_library(epanet SHARED ${EPANET_SOURCES}) #${EPANET_API_HEADER})
target_include_directories(epanet PUBLIC ${PROJECT_SOURCE_DIR}/include) target_include_directories(epanet PUBLIC ${PROJECT_SOURCE_DIR}/include)
# create export lib so we can link against dll using Visual Studio # create export lib so we can link against dll using Visual Studio
#include(GenerateExportHeader) add_definitions(-D WITH_GENX)
#GENERATE_EXPORT_HEADER(epanet include(GenerateExportHeader)
# BASE_NAME epanet GENERATE_EXPORT_HEADER(epanet
# EXPORT_MACRO_NAME DLLEXPORT BASE_NAME epanet
# EXPORT_FILE_NAME epanet_export.h EXPORT_MACRO_NAME DLLEXPORT
# STATIC_DEFINE SHARED_EXPORTS_BUILT_AS_STATIC) EXPORT_FILE_NAME epanet_export.h
# STATIC_DEFINE SHARED_EXPORTS_BUILT_AS_STATIC)
#file(COPY ${CMAKE_CURRENT_BINARY_DIR}/epanet_export.h
# DESTINATION ${CMAKE_CURRENT_SOURCE_DIR}/include)
file(COPY ${CMAKE_CURRENT_BINARY_DIR}/epanet_export.h
# the standalone executable DESTINATION ${CMAKE_CURRENT_SOURCE_DIR}/include)
add_executable(runepanet ${EPANET_CLI_SOURCES})
if(NOT MSVC)
target_link_libraries(runepanet LINK_PUBLIC epanet m)
else(NOT MSVC)
target_link_libraries(runepanet LINK_PUBLIC epanet)
endif(NOT MSVC)

View File

@@ -13,8 +13,9 @@ The EPANET Library is a pressurized pipe network hydraulic and water quality ana
Please see the [`version 2.1` Release Notes](https://github.com/OpenWaterAnalytics/EPANET/blob/master/ReleaseNotes2_1.md) for information relevant to users of the previous official version (2.00.12). If you would like to contribute by addressing any of the outstanding [Issues](https://github.com/OpenWaterAnalytics/EPANET/issues), then please comment on the Issue, then Fork this repo to your own account and base your commits on the [`dev` branch](https://github.com/OpenWaterAnalytics/EPANET/tree/dev). Once you are finished, you can open a Pull Request to test the code and discuss merging your changes back into the community respository. Please see the [`version 2.1` Release Notes](https://github.com/OpenWaterAnalytics/EPANET/blob/master/ReleaseNotes2_1.md) for information relevant to users of the previous official version (2.00.12). If you would like to contribute by addressing any of the outstanding [Issues](https://github.com/OpenWaterAnalytics/EPANET/issues), then please comment on the Issue, then Fork this repo to your own account and base your commits on the [`dev` branch](https://github.com/OpenWaterAnalytics/EPANET/tree/dev). Once you are finished, you can open a Pull Request to test the code and discuss merging your changes back into the community respository.
A step-by-step tutorial on how to contribute to EPANET using GitHub is also [available] (http://www.slideshare.net/demetriseliades/contributing-to-epanet-using-github-in-windows). A step-by-step tutorial on how to contribute to EPANET using GitHub is also [available](http://www.slideshare.net/demetriseliades/contributing-to-epanet-using-github-in-windows).
__Note:__ This repository is not affiliated with, or endorsed by, the USEPA. For the last "official" release of EPANET (2.00.12 UI and Toolkit) please go to the [EPA's GitHub repo](https://github.com/USEPA/Water-Distribution-Network-Model) or [the USEPA website](http://www2.epa.gov/water-research/epanet). It is also not the graphical user interface version. This is the hydraulic and water quality solver engine. __Note:__ This repository is not affiliated with, or endorsed by, the USEPA. For the last "official" release of EPANET (2.00.12 UI and Toolkit) please go to the [EPA's GitHub repo](https://github.com/USEPA/Water-Distribution-Network-Model) or [the USEPA website](http://www2.epa.gov/water-research/epanet). It is also not the graphical user interface version. This is the hydraulic and water quality solver engine.
However, if you are interested in extending EPANET for academic, personal, or commercial use, then you've come to the right place. For community discussion, FAQ, and roadmapping of the project, go to the [Community Forum](http://community.wateranalytics.org/category/epanet). However, if you are interested in extending EPANET for academic, personal, or commercial use, then you've come to the right place. For community discussion, FAQ, and roadmapping of the project, go to the [Community Forum](http://community.wateranalytics.org/category/epanet).

96
ReleaseNotes2_2.md Normal file
View File

@@ -0,0 +1,96 @@
Release Notes for EPANET 2.2 (Draft)
============================
This document describes the changes and updates that have been made to version 2.2 of EPANET.
## Thread-Safe API Functions
A duplicate set of the version 2.1 API functions has been provided that allow multiple EPANET projects to be analyzed concurrently in a thread-safe manner. These functions maintain the same name as the original but use a `EN_` prefix instead of `EN`. In addition, the first argument to each of these functions is a pointer to an `EN_Project` structure that encapsulates the network data for the particular project being analyzed. For example, instead of writing:
`ENgetnodevalue(nodeIndex, EN_ELEVATION, &elev)`
one would use:
`EN_getnodevalue(pr, nodeIndex, EN_ELEVATION, &elev)`
where `pr` is the pointer to an `EN_Project`.
Two new functions have been added to the API to manage the creation and deletion of project pointers. `EN_createproject` creates a new project along with a pointer to it, while `EN_deleteproject` deletes a project. An example of using the thread-safe version of the API is shown below:
```
#include "epanet2.h"
int runEpanet(char *finp, char *frpt)
{
EN_Project *pr = NULL;
int err;
err = EN_createproject(&pr);
if (err) return err;
err = EN_open(pr, finp, frpt, "");
if (!err) err = EN_solveH(pr);
if (!err) err = EN_report(pr);
EN_close(pr);
EN_deleteproject(pr);
return err;
}
```
## Additional Convergence Parameters
Two new analysis options have been added to provide more rigorous convergence criteria for EPANET's hydraulic solver. In the API they are named `EN_HEADERROR` and `EN_FLOWCHANGE` while in the `[OPTIONS]` section of an EPANET input file they are named `HEADERROR` and `FLOWCHANGE`, respectively.
`EN_HEADERROR` is the maximum head loss error that any network link can have for hydraulic convergence to occur. A link's head loss error is the difference between the head loss found as a function of computed flow in the link (such as by the Hazen-Williams equation for a pipe) and the difference in computed heads for the link's end nodes. The units of this parameter are feet (or meters for SI units). The default value of 0 indicates that no head error limit applies.
`EN_FLOWCHANGE` is the largest change in flow that any network element (link, emitter, or pressure-dependent demand) can have for hydraulic convergence to occur. It is specified in whatever flow units the project is using. The default value of 0 indicates that no flow change limit applies.
These new parameters augment the current `EN_ACCURACY` option which always remains in effect. In addition, both `EN_HEADERROR` and `EN_FLOWCHANGE` can be used as parameters in the `ENgetstatistic` (or `EN_getstatistic`) function to retrieve their computed values (even when their option values are 0) after a hydraulic solution has been completed.
## Improved Linear Solver Routine
EPANET's hydraulic solver requires solving a system of linear equations over a series of iterations until a set of convergence criteria are met. The coefficient matrix of this linear system is square and symmetric. It has a row for each network node and a non-zero off-diagonal coefficient for each link. The numerical effort needed to solve the linear system can be reduced if the nodes are re-ordered so that the non-zero coefficients cluster more tightly around the diagonal.
EPANET's original node re-ordering scheme has been replaced by the more powerful **Multiple Minimum Degree (MMD)** algorithm. On a series of eight networks ranging in size from 7,700 to 100,000 nodes **MMD** reduced the solution time for a single period (steady state) hydraulic analysis by an average of more than 50%.
## Pressure Dependent Demands
EPANET has always employed a Demand Driven Analysis (**DDA**) when modeling network hydraulics. Under this approach nodal demands at a given point in time are fixed values that must be delivered no matter what nodal heads and link flows are produced by a hydraulic solution. This can result in situations where required demands are satisfied at nodes that have negative pressures - a physical impossibility.
To address this issue EPANET has been extended to use a Pressure Driven Analysis (**PDA**) if so desired. Under **PDA**, the demand *D* delivered at a node depends on the node's available pressure *P* according to:
$$D =D_f\left(\frac{P-P_{min}}{P_{req}-P_{min}}\right)^{P_{exp}} for P_{0}<=P<=P_{req}$$where *D<sub>f</sub>* is the full demand required, *P<sub>min</sub>* is the pressure below which demand is zero, *P<sub>req</sub>* is the pressure required to deliver the full required demand and *P<sub>exp</sub>* is an exponent. When *P < P<sub>min</sub>* demand is 0 and when *P > P<sub>req</sub>* demand equals *D<sub>f</sub>*.
To implement pressure dependent analysis four new parameters have been added to the [OPTIONS] section of the EPANET input file:
| Parameter | Description | Default |
|--|--|--|
| DEMAND MODEL | either DDA or PDA | DDA |
| MINIMUM PRESSURE | value for *P<sub>min</sub>* | 0
| REQUIRED PRESSURE | value for *P<sub>req</sub>* | 0
| PRESSURE EXPONENT | value for *P<sub>exp</sub>* | 0.5 |
These parameters can also be set and retrieved in code using the following API functions
```
int ENsetdemandmodel(int modelType, double pMin, double pReq, double pExp);
int ENgetdemandmodel(int *modelType, double *pMin, double *pReq, double *pExp);
```
for the legacy API and
```
int EN_setdemandmodel(EN_Project *pr, int modelType, double pMin, double pReq, double pExp);
int EN_getdemandmodel(EN_Project *pr, int *modelType, double *pMin, double *pReq, double *pExp);
```
for the thread-safe API. Some additional points regarding the new **PDA** option are:
- If no DEMAND MODEL and its parameters are specified then the analysis defaults to being demand driven (**DDA**).
- This implementation of **PDA** assumes that the same parameters apply to all nodes in the network. Extending the framework to allow different parameters for specific nodes is straightforward to do but is left as a future feature to implement.
- *P<sub>0</sub>* is allowed to equal to *P<sub>req</sub>*. This condition can be used to find a solution that results in the smallest amount of demand reductions needed to insure that no node delivers positive demand at a pressure below *P<sub>min</min>*.
## Code Changes
- The header file `vars.h` containing global variables has been eliminated. Instead a number of new structures incorporating these variables has been added to `types.h`. These structures have been incorporated into the new `EN_Project` structure, also defined in `types.h`, which gets passed into each of the thread-safe API functions as a pointer.
- Each of the legacy API functions now simply calls its thread-safe counterpart passing in a pointer to a default global`EN_Project` variable that is declared in `types.h`.
- Throughout all code modules, global variables that were previously accessed through `vars.h` are now accessed using the `EN_Project` pointer that is passed into the functions where the variables appear.
- The exceedingly long `hydraul.c` file has been split into four separate files:
- `hydraul.c` now contains just the code needed to initialize a hydraulic analysis, set demands and control actions at each time step, and determine the length of the next time step to take.
- `hydsolver.c` implements EPANET's hydraulic solver at a single point in time.
- `hydcoeffs.c` computes values of the matrix coefficients (derived from link head losses and their gradients) used by the hydraulic solver.
- `hydstatus.c` checks for status changes in valves and pumps as requested by the hydraulic solver.
- The Multiple Minimum Degree re-ordering algorithm appears in a new file named `genmmd.c`. This is 1990's legacy code that is readily available on the web and can be found in several linear equation solver libraries.

View File

@@ -78,6 +78,8 @@ Public Const EN_NEXTEVENT = 14
Public Const EN_ITERATIONS = 0 Public Const EN_ITERATIONS = 0
Public Const EN_RELATIVEERROR = 1 Public Const EN_RELATIVEERROR = 1
Public Const EN_MAXHEADERROR = 2
Public Const EN_MAXFLOWCHANGE = 3
Public Const EN_NODECOUNT = 0 'Component counts Public Const EN_NODECOUNT = 0 'Component counts
Public Const EN_TANKCOUNT = 1 Public Const EN_TANKCOUNT = 1
@@ -126,6 +128,9 @@ Public Const EN_MLD = 7
Public Const EN_CMH = 8 Public Const EN_CMH = 8
Public Const EN_CMD = 9 Public Const EN_CMD = 9
Public Const EN_DDA = 0 ' Demand driven analysis
Public Const EN_PDA = 1 ' Pressure driven analysis
Public Const EN_TRIALS = 0 ' Misc. options Public Const EN_TRIALS = 0 ' Misc. options
Public Const EN_ACCURACY = 1 Public Const EN_ACCURACY = 1
Public Const EN_TOLERANCE = 2 Public Const EN_TOLERANCE = 2
@@ -233,6 +238,9 @@ Public Const EN_G_CURVE = 4 ' General\default curve
Declare Function ENgetversion Lib "epanet2.dll" (value As Long) As Long Declare Function ENgetversion Lib "epanet2.dll" (value As Long) As Long
Declare Function ENgetdemandmodel Lib "epanet2.dll" (type as long, pmin as Single, preq as Single, pexp as Single) As Long
Declare Function ENsetdemandmodel Lib "epanet2.dll" (ByVal type as long, ByVal pmin as Single, ByVal preq as Single, ByVal pexp as Single) As Long
Declare Function ENsetflowunits Lib "epanet2.dll" (ByVal code As Long) As Long Declare Function ENsetflowunits Lib "epanet2.dll" (ByVal code As Long) As Long
Declare Function ENsetcontrol Lib "epanet2.dll" (ByVal Cindex As Long, ByVal Ctype As Long, ByVal Lindex As Long, ByVal setting As Single, ByVal Nindex As Long, ByVal Level As Single) As Long Declare Function ENsetcontrol Lib "epanet2.dll" (ByVal Cindex As Long, ByVal Ctype As Long, ByVal Lindex As Long, ByVal setting As Single, ByVal Nindex As Long, ByVal Level As Single) As Long
Declare Function ENsetnodevalue Lib "epanet2.dll" (ByVal index As Long, ByVal code As Long, ByVal value As Single) As Long Declare Function ENsetnodevalue Lib "epanet2.dll" (ByVal index As Long, ByVal code As Long, ByVal value As Single) As Long

View File

@@ -30,37 +30,40 @@
#define EN_API_FLOAT_TYPE float #define EN_API_FLOAT_TYPE float
#endif #endif
// --- define WINDOWS #ifdef WITH_GENX
#undef WINDOWS #include "epanet_export.h"
#ifdef _WIN32 #else
#define WINDOWS // --- define WINDOWS
#endif #undef WINDOWS
#ifdef __WIN32__ #ifdef _WIN32
#define WINDOWS #define WINDOWS
#endif #endif
#ifdef __WIN32__
#define WINDOWS
#endif
// --- define DLLEXPORT // --- define DLLEXPORT
#ifndef DLLEXPORT #ifndef DLLEXPORT
#ifdef WINDOWS #ifdef WINDOWS
#ifdef __cplusplus #ifdef __cplusplus
#define DLLEXPORT extern "C" __declspec(dllexport) #define DLLEXPORT __declspec(dllexport)
#else #else
#define DLLEXPORT __declspec(dllexport) __stdcall #define DLLEXPORT __declspec(dllexport) __stdcall
#endif // __cplusplus #endif // __cplusplus
#elif defined(CYGWIN) #elif defined(CYGWIN)
#define DLLEXPORT __stdcall #define DLLEXPORT __stdcall
#elif defined(__APPLE__) #elif defined(__APPLE__)
#ifdef __cplusplus #ifdef __cplusplus
#define DLLEXPORT #define DLLEXPORT
#else
#define DLLEXPORT
#endif
#else #else
#define DLLEXPORT #define DLLEXPORT
#endif #endif
#else
#define DLLEXPORT
#endif #endif
#endif #endif
//#include "epanet_export.h"
// --- Define the EPANET toolkit constants // --- Define the EPANET toolkit constants
@@ -141,10 +144,11 @@ typedef enum {
EN_NEXTEVENTIDX = 15 EN_NEXTEVENTIDX = 15
} EN_TimeProperty; } EN_TimeProperty;
typedef enum { typedef enum {
EN_ITERATIONS = 0, EN_ITERATIONS = 0,
EN_RELATIVEERROR = 1 EN_RELATIVEERROR = 1,
EN_MAXHEADERROR = 2,
EN_MAXFLOWCHANGE = 3
} EN_AnalysisStatistic; } EN_AnalysisStatistic;
typedef enum { typedef enum {
@@ -153,7 +157,7 @@ typedef enum {
EN_LINKCOUNT = 2, /**< Number of Links (Pipes + Pumps + Valves) */ EN_LINKCOUNT = 2, /**< Number of Links (Pipes + Pumps + Valves) */
EN_PATCOUNT = 3, /**< Number of Time Patterns */ EN_PATCOUNT = 3, /**< Number of Time Patterns */
EN_CURVECOUNT = 4, /**< Number of Curves */ EN_CURVECOUNT = 4, /**< Number of Curves */
EN_CONTROLCOUNT = 5, /**< Number of Control Statements */ EN_CONTROLCOUNT = 5, /**< Number of Control Statements */
EN_RULECOUNT = 6 /**< Number of Rule-based Control Statements */ EN_RULECOUNT = 6 /**< Number of Rule-based Control Statements */
} EN_CountType; } EN_CountType;
@@ -208,6 +212,10 @@ typedef enum {
EN_CMD = 9 EN_CMD = 9
} EN_FlowUnits; } EN_FlowUnits;
typedef enum { /* Demand model types. */
EN_DDA = 0, /**< Demand driven analysis */
EN_PDA = 1 /**< Pressure driven analysis */
} EN_DemandModel;
/// Simulation Option codes /// Simulation Option codes
typedef enum { typedef enum {
@@ -271,7 +279,8 @@ extern "C" {
/** /**
@brief The EPANET Project wrapper object @brief The EPANET Project wrapper object
*/ */
typedef struct EN_Project EN_Project; typedef void *EN_ProjectHandle;
typedef struct EN_Pattern EN_Pattern; typedef struct EN_Pattern EN_Pattern;
typedef struct EN_Curve EN_Curve; typedef struct EN_Curve EN_Curve;
@@ -288,7 +297,8 @@ extern "C" {
as it carries out its computations. If this feature is not as it carries out its computations. If this feature is not
needed then the argument should be NULL. needed then the argument should be NULL.
*/ */
int DLLEXPORT ENepanet(char *inpFile, char *rptFile, char *binOutFile, void (*callback) (char *)); int DLLEXPORT ENepanet(const char *inpFile, const char *rptFile,
const char *binOutFile, void (*callback) (char *));
/** /**
@brief Initializes an EPANET session @brief Initializes an EPANET session
@@ -524,7 +534,29 @@ extern "C" {
@return Error code @return Error code
*/ */
int DLLEXPORT ENsetflowunits(int code); int DLLEXPORT ENsetflowunits(int code);
/**
@brief Retrieves the type of demand model in use and its parameters
@param[out] type Type of demand model (EN_DDA or EN_PDA)
@param[out] pmin Pressure below which there is no demand
@param[out] preq Pressure required to deliver full demand
@param[out] pexp Pressure exponent in demand function
@return Error code
*/
int DLLEXPORT ENgetdemandmodel(int *type, EN_API_FLOAT_TYPE *pmin,
EN_API_FLOAT_TYPE *preq, EN_API_FLOAT_TYPE *pexp);
/**
@brief Sets the type of demand model to use and its parameters
@param type Type of demand model (EN_DDA or EN_PDA)
@param pmin Pressure below which there is no demand
@param preq Pressure required to deliver full demand
@param pexp Pressure exponent in demand function
@return Error code
*/
int DLLEXPORT ENsetdemandmodel(int type, EN_API_FLOAT_TYPE pmin,
EN_API_FLOAT_TYPE preq, EN_API_FLOAT_TYPE pexp);
/** /**
@brief Retrieves the index of the time pattern with specified ID @brief Retrieves the index of the time pattern with specified ID
@param id String ID of the time pattern @param id String ID of the time pattern
@@ -806,7 +838,7 @@ extern "C" {
int DLLEXPORT ENsetnodevalue(int index, int code, EN_API_FLOAT_TYPE v); int DLLEXPORT ENsetnodevalue(int index, int code, EN_API_FLOAT_TYPE v);
/** /**
@brief Set a proprty value for a link. @brief Set a property value for a link.
@param index The index of a link. First link is index 1. @param index The index of a link. First link is index 1.
@param code The code for the property to set. @param code The code for the property to set.
@param v The value to set for this link and property. @param v The value to set for this link and property.
@@ -1131,115 +1163,131 @@ extern "C" {
int DLLEXPORT ENdeletelink(int linkIndex); int DLLEXPORT ENdeletelink(int linkIndex);
/*************************************************** /***************************************************
Threadsafe versions of all epanet functions Threadsafe versions of all epanet functions
***************************************************/ ***************************************************/
int DLLEXPORT EN_alloc(EN_Project **p); int DLLEXPORT EN_createproject(EN_ProjectHandle *ph);
int DLLEXPORT EN_free(EN_Project *p); int DLLEXPORT EN_deleteproject(EN_ProjectHandle *ph);
int DLLEXPORT EN_epanet(char *inpFile, char *rptFile, char *binOutFile, void (*callback) (char *));
int DLLEXPORT EN_init(EN_Project *p, char *rptFile, char *binOutFile, EN_FlowUnits UnitsType, EN_FormType HeadlossFormula); void DLLEXPORT EN_clearError(EN_ProjectHandle ph);
int DLLEXPORT EN_open(EN_Project *p, char *inpFile, char *rptFile, char *binOutFile); int DLLEXPORT EN_checkError(EN_ProjectHandle ph, char** msg_buffer);
int DLLEXPORT EN_saveinpfile(EN_Project *p, char *filename);
int DLLEXPORT EN_close(EN_Project *p); //int DLLEXPORT EN_epanet(EN_ProjectHandle ph, const char *f1, const char *f2,
int DLLEXPORT EN_solveH(EN_Project *p); // const char *f3, void(*pviewprog)(char *));
int DLLEXPORT EN_saveH(EN_Project *p); int DLLEXPORT EN_init(EN_ProjectHandle *ph, char *rptFile, char *binOutFile,
int DLLEXPORT EN_openH(EN_Project *p); EN_FlowUnits UnitsType, EN_FormType HeadlossFormula);
int DLLEXPORT EN_initH(EN_Project *p, int EN_SaveOption);
int DLLEXPORT EN_runH(EN_Project *p, long *currentTime); int DLLEXPORT EN_open(EN_ProjectHandle ph, const char *inpFile,
int DLLEXPORT EN_nextH(EN_Project *p, long *tStep); const char *rptFile, const char *binOutFile);
int DLLEXPORT EN_closeH(EN_Project *p);
int DLLEXPORT EN_savehydfile(EN_Project *p, char *filename); int DLLEXPORT EN_saveinpfile(EN_ProjectHandle ph, char *filename);
int DLLEXPORT EN_usehydfile(EN_Project *p, char *filename);
int DLLEXPORT EN_solveQ(EN_Project *p); int DLLEXPORT EN_close(EN_ProjectHandle ph);
int DLLEXPORT EN_openQ(EN_Project *p); int DLLEXPORT EN_solveH(EN_ProjectHandle ph);
int DLLEXPORT EN_initQ(EN_Project *p, int saveFlag);
int DLLEXPORT EN_runQ(EN_Project *p, long *currentTime); int DLLEXPORT EN_saveH(EN_ProjectHandle ph);
int DLLEXPORT EN_nextQ(EN_Project *p, long *tStep); int DLLEXPORT EN_openH(EN_ProjectHandle ph);
int DLLEXPORT EN_stepQ(EN_Project *p, long *timeLeft); int DLLEXPORT EN_initH(EN_ProjectHandle ph, int EN_SaveOption);
int DLLEXPORT EN_closeQ(EN_Project *p); int DLLEXPORT EN_runH(EN_ProjectHandle ph, long *currentTime);
int DLLEXPORT EN_writeline(EN_Project *p, char *line); int DLLEXPORT EN_nextH(EN_ProjectHandle ph, long *tStep);
int DLLEXPORT EN_report(EN_Project *p); int DLLEXPORT EN_closeH(EN_ProjectHandle ph);
int DLLEXPORT EN_resetreport(EN_Project *p); int DLLEXPORT EN_savehydfile(EN_ProjectHandle ph, char *filename);
int DLLEXPORT EN_setreport(EN_Project *p, char *reportFormat); int DLLEXPORT EN_usehydfile(EN_ProjectHandle ph, char *filename);
int DLLEXPORT EN_getcontrol(EN_Project *p, int controlIndex, int *controlType, int *linkIndex, EN_API_FLOAT_TYPE *setting, int *nodeIndex, EN_API_FLOAT_TYPE *level);
int DLLEXPORT EN_getcount(EN_Project *p, EN_CountType code, int *count); int DLLEXPORT EN_solveQ(EN_ProjectHandle ph);
int DLLEXPORT EN_getoption(EN_Project *p, EN_Option opt, EN_API_FLOAT_TYPE *value); int DLLEXPORT EN_openQ(EN_ProjectHandle ph);
int DLLEXPORT EN_gettimeparam(EN_Project *p, int code, long *value); int DLLEXPORT EN_initQ(EN_ProjectHandle ph, int saveFlag);
int DLLEXPORT EN_getflowunits(EN_Project *p, int *code); int DLLEXPORT EN_runQ(EN_ProjectHandle ph, long *currentTime);
int DLLEXPORT EN_setflowunits(EN_Project *p, int code); int DLLEXPORT EN_nextQ(EN_ProjectHandle ph, long *tStep);
int DLLEXPORT EN_getpatternindex(EN_Project *p, char *id, int *index); int DLLEXPORT EN_stepQ(EN_ProjectHandle ph, long *timeLeft);
int DLLEXPORT EN_getpatternid(EN_Project *p, int index, char *id); int DLLEXPORT EN_closeQ(EN_ProjectHandle ph);
int DLLEXPORT EN_getpatternlen(EN_Project *p, int index, int *len); int DLLEXPORT EN_writeline(EN_ProjectHandle ph, char *line);
int DLLEXPORT EN_getpatternvalue(EN_Project *p, int index, int period, EN_API_FLOAT_TYPE *value);
int DLLEXPORT EN_getaveragepatternvalue(EN_Project *p, int index, EN_API_FLOAT_TYPE *value); int DLLEXPORT EN_report(EN_ProjectHandle ph);
int DLLEXPORT EN_getqualtype(EN_Project *p, int *qualcode, int *tracenode); int DLLEXPORT EN_resetreport(EN_ProjectHandle ph);
int DLLEXPORT EN_setreport(EN_ProjectHandle ph, char *reportFormat);
int DLLEXPORT EN_getcontrol(EN_ProjectHandle ph, int controlIndex, int *controlType, int *linkIndex, EN_API_FLOAT_TYPE *setting, int *nodeIndex, EN_API_FLOAT_TYPE *level);
int DLLEXPORT EN_getcount(EN_ProjectHandle ph, EN_CountType code, int *count);
int DLLEXPORT EN_getoption(EN_ProjectHandle ph, EN_Option opt, EN_API_FLOAT_TYPE *value);
int DLLEXPORT EN_gettimeparam(EN_ProjectHandle ph, int code, long *value);
int DLLEXPORT EN_getflowunits(EN_ProjectHandle ph, int *code);
int DLLEXPORT EN_setflowunits(EN_ProjectHandle ph, int code);
int DLLEXPORT EN_getpatternindex(EN_ProjectHandle ph, char *id, int *index);
int DLLEXPORT EN_getpatternid(EN_ProjectHandle ph, int index, char *id);
int DLLEXPORT EN_getpatternlen(EN_ProjectHandle ph, int index, int *len);
int DLLEXPORT EN_getpatternvalue(EN_ProjectHandle ph, int index, int period, EN_API_FLOAT_TYPE *value);
int DLLEXPORT EN_getaveragepatternvalue(EN_ProjectHandle ph, int index, EN_API_FLOAT_TYPE *value);
int DLLEXPORT EN_getqualtype(EN_ProjectHandle ph, int *qualcode, int *tracenode);
int DLLEXPORT EN_geterror(int errcode, char *errmsg, int maxLen); int DLLEXPORT EN_geterror(int errcode, char *errmsg, int maxLen);
int DLLEXPORT EN_getstatistic(EN_Project *p, int code, EN_API_FLOAT_TYPE* value);
int DLLEXPORT EN_getnodeindex(EN_Project *p, char *id, int *index); int DLLEXPORT EN_getstatistic(EN_ProjectHandle ph, int code, EN_API_FLOAT_TYPE* value);
int DLLEXPORT EN_getnodeid(EN_Project *p, int index, char *id); int DLLEXPORT EN_getnodeindex(EN_ProjectHandle ph, char *id, int *index);
int DLLEXPORT EN_getnodetype(EN_Project *p, int index, int *code); int DLLEXPORT EN_getnodeid(EN_ProjectHandle ph, int index, char *id);
int DLLEXPORT EN_getnodevalue(EN_Project *p, int index, int code, EN_API_FLOAT_TYPE *value); int DLLEXPORT EN_getnodetype(EN_ProjectHandle ph, int index, int *code);
int DLLEXPORT EN_getcoord(EN_Project *p, int index, EN_API_FLOAT_TYPE *x, EN_API_FLOAT_TYPE *y); int DLLEXPORT EN_getnodevalue(EN_ProjectHandle ph, int index, int code, EN_API_FLOAT_TYPE *value);
int DLLEXPORT EN_setcoord(EN_Project *p, int index, EN_API_FLOAT_TYPE x, EN_API_FLOAT_TYPE y); int DLLEXPORT EN_getcoord(EN_ProjectHandle ph, int index, EN_API_FLOAT_TYPE *x, EN_API_FLOAT_TYPE *y);
int DLLEXPORT EN_getnumdemands(EN_Project *p, int nodeIndex, int *numDemands); int DLLEXPORT EN_setcoord(EN_ProjectHandle ph, int index, EN_API_FLOAT_TYPE x, EN_API_FLOAT_TYPE y);
int DLLEXPORT EN_getbasedemand(EN_Project *p, int nodeIndex, int demandIndex, EN_API_FLOAT_TYPE *baseDemand); int DLLEXPORT EN_getnumdemands(EN_ProjectHandle ph, int nodeIndex, int *numDemands);
int DLLEXPORT EN_getdemandpattern(EN_Project *p, int nodeIndex, int demandIndex, int *pattIndex); int DLLEXPORT EN_getbasedemand(EN_ProjectHandle ph, int nodeIndex, int demandIndex, EN_API_FLOAT_TYPE *baseDemand);
int DLLEXPORT EN_getlinkindex(EN_Project *p, char *id, int *index); int DLLEXPORT EN_getdemandpattern(EN_ProjectHandle ph, int nodeIndex, int demandIndex, int *pattIndex);
int DLLEXPORT EN_getlinkid(EN_Project *p, int index, char *id); int DLLEXPORT EN_getlinkindex(EN_ProjectHandle ph, char *id, int *index);
int DLLEXPORT EN_getlinktype(EN_Project *p, int index, EN_LinkType *code); int DLLEXPORT EN_getlinkid(EN_ProjectHandle ph, int index, char *id);
int DLLEXPORT EN_setlinktype(EN_Project *p, char *id, EN_LinkType type); int DLLEXPORT EN_getlinktype(EN_ProjectHandle ph, int index, EN_LinkType *code);
int DLLEXPORT EN_getlinknodes(EN_Project *p, int index, int *node1, int *node2); int DLLEXPORT EN_setlinktype(EN_ProjectHandle ph, char *id, EN_LinkType type);
int DLLEXPORT EN_getlinkvalue(EN_Project *p, int index, EN_LinkProperty code, EN_API_FLOAT_TYPE *value); int DLLEXPORT EN_getlinknodes(EN_ProjectHandle ph, int index, int *node1, int *node2);
int DLLEXPORT EN_getcurve(EN_Project *p, int curveIndex, char* id, int *nValues, EN_API_FLOAT_TYPE **xValues, EN_API_FLOAT_TYPE **yValues); int DLLEXPORT EN_getlinkvalue(EN_ProjectHandle ph, int index, EN_LinkProperty code, EN_API_FLOAT_TYPE *value);
int DLLEXPORT EN_getheadcurveindex(EN_Project *p, int pumpIndex, int *curveIndex); int DLLEXPORT EN_getcurve(EN_ProjectHandle ph, int curveIndex, char* id, int *nValues, EN_API_FLOAT_TYPE **xValues, EN_API_FLOAT_TYPE **yValues);
int DLLEXPORT EN_setheadcurveindex(EN_Project *p, int pumpIndex, int curveIndex); int DLLEXPORT EN_getheadcurveindex(EN_ProjectHandle ph, int pumpIndex, int *curveIndex);
int DLLEXPORT EN_getpumptype(EN_Project *p, int linkIndex, int *outType); int DLLEXPORT EN_setheadcurveindex(EN_ProjectHandle ph, int pumpIndex, int curveIndex);
int DLLEXPORT EN_getcurvetype(EN_Project *p, int curveIndex, int *outType); int DLLEXPORT EN_getpumptype(EN_ProjectHandle ph, int linkIndex, int *outType);
int DLLEXPORT EN_getcurvetype(EN_ProjectHandle ph, int curveIndex, int *outType);
int DLLEXPORT EN_getversion(int *version); int DLLEXPORT EN_getversion(int *version);
int DLLEXPORT EN_setcontrol(EN_Project *p, int cindex, int ctype, int lindex, EN_API_FLOAT_TYPE setting, int nindex, EN_API_FLOAT_TYPE level);
int DLLEXPORT EN_setnodevalue(EN_Project *p, int index, int code, EN_API_FLOAT_TYPE v); int DLLEXPORT EN_setcontrol(EN_ProjectHandle ph, int cindex, int ctype, int lindex, EN_API_FLOAT_TYPE setting, int nindex, EN_API_FLOAT_TYPE level);
int DLLEXPORT EN_setlinkvalue(EN_Project *p, int index, int code, EN_API_FLOAT_TYPE v); int DLLEXPORT EN_setnodevalue(EN_ProjectHandle ph, int index, int code, EN_API_FLOAT_TYPE v);
int DLLEXPORT EN_addpattern(EN_Project *p, char *id); int DLLEXPORT EN_setlinkvalue(EN_ProjectHandle ph, int index, int code, EN_API_FLOAT_TYPE v);
int DLLEXPORT EN_setpattern(EN_Project *p, int index, EN_API_FLOAT_TYPE *f, int len); int DLLEXPORT EN_addpattern(EN_ProjectHandle ph, char *id);
int DLLEXPORT EN_setpatternvalue(EN_Project *p, int index, int period, EN_API_FLOAT_TYPE value); int DLLEXPORT EN_setpattern(EN_ProjectHandle ph, int index, EN_API_FLOAT_TYPE *f, int len);
int DLLEXPORT EN_settimeparam(EN_Project *p, int code, long value); int DLLEXPORT EN_setpatternvalue(EN_ProjectHandle ph, int index, int period, EN_API_FLOAT_TYPE value);
int DLLEXPORT EN_setoption(EN_Project *p, int code, EN_API_FLOAT_TYPE v); int DLLEXPORT EN_settimeparam(EN_ProjectHandle ph, int code, long value);
int DLLEXPORT EN_setstatusreport(EN_Project *p, int code); int DLLEXPORT EN_setoption(EN_ProjectHandle ph, int code, EN_API_FLOAT_TYPE v);
int DLLEXPORT EN_setqualtype(EN_Project *p, int qualcode, char *chemname, char *chemunits, char *tracenode); int DLLEXPORT EN_setstatusreport(EN_ProjectHandle ph, int code);
int DLLEXPORT EN_getqualinfo(EN_Project *p, int *qualcode, char *chemname, char *chemunits, int *tracenode); int DLLEXPORT EN_setqualtype(EN_ProjectHandle ph, int qualcode, char *chemname, char *chemunits, char *tracenode);
int DLLEXPORT EN_setbasedemand(EN_Project *p, int nodeIndex, int demandIdx, EN_API_FLOAT_TYPE baseDemand);
int DLLEXPORT EN_getcurveindex(EN_Project *p, char *id, int *index); int DLLEXPORT EN_getdemandmodel(EN_ProjectHandle ph, int *type, EN_API_FLOAT_TYPE *pmin,
int DLLEXPORT EN_getcurveid(EN_Project *p, int index, char *id); EN_API_FLOAT_TYPE *preq, EN_API_FLOAT_TYPE *pexp);
int DLLEXPORT EN_getcurvelen(EN_Project *p, int index, int *len); int DLLEXPORT EN_setdemandmodel(EN_ProjectHandle ph, int type, EN_API_FLOAT_TYPE pmin,
int DLLEXPORT EN_getcurvevalue(EN_Project *p, int curveIndex, int pointIndex, EN_API_FLOAT_TYPE *x, EN_API_FLOAT_TYPE *y); EN_API_FLOAT_TYPE preq, EN_API_FLOAT_TYPE pexp);
int DLLEXPORT EN_setcurvevalue(EN_Project *p, int curveIndex, int pointIndex, EN_API_FLOAT_TYPE x, EN_API_FLOAT_TYPE y);
int DLLEXPORT EN_setcurve(EN_Project *p, int index, EN_API_FLOAT_TYPE *x, EN_API_FLOAT_TYPE *y, int len); int DLLEXPORT EN_getqualinfo(EN_ProjectHandle ph, int *qualcode, char *chemname, char *chemunits, int *tracenode);
int DLLEXPORT EN_addcurve(EN_Project *p, char *id); int DLLEXPORT EN_setbasedemand(EN_ProjectHandle ph, int nodeIndex, int demandIdx, EN_API_FLOAT_TYPE baseDemand);
int DLLEXPORT EN_getrule(EN_Project *p, int index, int *nPremises, int *nTrueActions, int *nFalseActions, EN_API_FLOAT_TYPE *priority); int DLLEXPORT EN_getcurveindex(EN_ProjectHandle ph, char *id, int *index);
int DLLEXPORT EN_setrulepriority(EN_Project *p, int index, EN_API_FLOAT_TYPE priority); int DLLEXPORT EN_getcurveid(EN_ProjectHandle ph, int index, char *id);
int DLLEXPORT EN_getpremise(EN_Project *p, int indexRule, int indexPremise, int *logop, int *object, int *indexObj, int *variable, int *relop, int *status, EN_API_FLOAT_TYPE *value); int DLLEXPORT EN_getcurvelen(EN_ProjectHandle ph, int index, int *len);
int DLLEXPORT EN_setpremise(EN_Project *p, int indexRule, int indexPremise, int logop, int object, int indexObj, int variable, int relop, int status, EN_API_FLOAT_TYPE value); int DLLEXPORT EN_getcurvevalue(EN_ProjectHandle ph, int curveIndex, int pointIndex, EN_API_FLOAT_TYPE *x, EN_API_FLOAT_TYPE *y);
int DLLEXPORT EN_setpremiseindex(EN_Project *p, int indexRule, int indexPremise, int indexObj); int DLLEXPORT EN_setcurvevalue(EN_ProjectHandle ph, int curveIndex, int pointIndex, EN_API_FLOAT_TYPE x, EN_API_FLOAT_TYPE y);
int DLLEXPORT EN_setpremisestatus(EN_Project *p, int indexRule, int indexPremise, int status); int DLLEXPORT EN_setcurve(EN_ProjectHandle ph, int index, EN_API_FLOAT_TYPE *x, EN_API_FLOAT_TYPE *y, int len);
int DLLEXPORT EN_setpremisevalue(EN_Project *p, int indexRule, int indexPremise, EN_API_FLOAT_TYPE value); int DLLEXPORT EN_addcurve(EN_ProjectHandle ph, char *id);
int DLLEXPORT EN_gettrueaction(EN_Project *p, int indexRule, int indexAction, int *indexLink, int *status, EN_API_FLOAT_TYPE *setting); int DLLEXPORT EN_getrule(EN_ProjectHandle ph, int index, int *nPremises, int *nTrueActions, int *nFalseActions, EN_API_FLOAT_TYPE *priority);
int DLLEXPORT EN_settrueaction(EN_Project *p, int indexRule, int indexAction, int indexLink, int status, EN_API_FLOAT_TYPE setting); int DLLEXPORT EN_setrulepriority(EN_ProjectHandle ph, int index, EN_API_FLOAT_TYPE priority);
int DLLEXPORT EN_getfalseaction(EN_Project *p, int indexRule, int indexAction, int *indexLink, int *status, EN_API_FLOAT_TYPE *setting); int DLLEXPORT EN_getpremise(EN_ProjectHandle ph, int indexRule, int indexPremise, int *logop, int *object, int *indexObj, int *variable, int *relop, int *status, EN_API_FLOAT_TYPE *value);
int DLLEXPORT EN_setfalseaction(EN_Project *p, int indexRule, int indexAction, int indexLink, int status, EN_API_FLOAT_TYPE setting); int DLLEXPORT EN_setpremise(EN_ProjectHandle ph, int indexRule, int indexPremise, int logop, int object, int indexObj, int variable, int relop, int status, EN_API_FLOAT_TYPE value);
int DLLEXPORT EN_getruleID(EN_Project *p, int indexRule, char* id); int DLLEXPORT EN_setpremiseindex(EN_ProjectHandle ph, int indexRule, int indexPremise, int indexObj);
int DLLEXPORT EN_addnode(EN_Project *p, char *id, EN_NodeType nodeType); int DLLEXPORT EN_setpremisestatus(EN_ProjectHandle ph, int indexRule, int indexPremise, int status);
int DLLEXPORT EN_addlink(EN_Project *p, char *id, EN_LinkType linkType, char *fromNode, char *toNode); int DLLEXPORT EN_setpremisevalue(EN_ProjectHandle ph, int indexRule, int indexPremise, EN_API_FLOAT_TYPE value);
int DLLEXPORT EN_deletenode(EN_Project *p, int nodeIndex); int DLLEXPORT EN_gettrueaction(EN_ProjectHandle ph, int indexRule, int indexAction, int *indexLink, int *status, EN_API_FLOAT_TYPE *setting);
int DLLEXPORT EN_deletelink(EN_Project *p, int linkIndex); int DLLEXPORT EN_settrueaction(EN_ProjectHandle ph, int indexRule, int indexAction, int indexLink, int status, EN_API_FLOAT_TYPE setting);
int DLLEXPORT EN_getfalseaction(EN_ProjectHandle ph, int indexRule, int indexAction, int *indexLink, int *status, EN_API_FLOAT_TYPE *setting);
int DLLEXPORT EN_setfalseaction(EN_ProjectHandle ph, int indexRule, int indexAction, int indexLink, int status, EN_API_FLOAT_TYPE setting);
int DLLEXPORT EN_getruleID(EN_ProjectHandle ph, int indexRule, char* id);
int DLLEXPORT EN_addnode(EN_ProjectHandle ph, char *id, EN_NodeType nodeType);
int DLLEXPORT EN_addlink(EN_ProjectHandle ph, char *id, EN_LinkType linkType, char *fromNode, char *toNode);
int DLLEXPORT EN_deletenode(EN_ProjectHandle ph, int nodeIndex);
int DLLEXPORT EN_deletelink(EN_ProjectHandle ph, int linkIndex);
#if defined(__cplusplus) #if defined(__cplusplus)
} }

28
run/CMakeLists.txt Normal file
View File

@@ -0,0 +1,28 @@
# EPANET COMMAND LINE EXECUTABLE
cmake_minimum_required (VERSION 3.0.2)
# Sets for output directory for executables and libraries.
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
# Sets the position independent code property for all targets.
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
# Set up file groups for exe target
set(EPANET_CLI_SOURCES main.c)
include_directories(include)
source_group("CLI" FILES ${EPANET_CLI_SOURCES})
# Creates the EPANET command line executable
add_definitions(-D WITH_GENX)
add_executable(runepanet ${EPANET_CLI_SOURCES})
if(NOT WIN32)
target_link_libraries(runepanet LINK_PUBLIC epanet m)
else(NOT WIN32)
target_link_libraries(runepanet LINK_PUBLIC epanet)
endif(NOT WIN32)

View File

@@ -5,8 +5,8 @@
#define MAXMSG 255 /* Max. # characters in message text */ #define MAXMSG 255 /* Max. # characters in message text */
#define MAXWARNCODE 99 #define MAXWARNCODE 99
/* text copied here, no more need of include "text.h" */ /* text copied here, no more need of include "text.h" */
#define FMT01 "\nEPANET Version %d.%d.%d" #define FMT01 "\nEPANET Version %d.%d.%d\n"
#define FMT03 "\n Correct syntax is:\n %s <input file> <output file>\n" #define FMT03 "\nUsage:\n %s <input_filename> <report_filename> [<binary_filename>]\n"
#define FMT09 "\n\nEPANET completed." #define FMT09 "\n\nEPANET completed."
#define FMT10 "\nEPANET completed. There are warnings." #define FMT10 "\nEPANET completed. There are warnings."
#define FMT11 "\nEPANET completed. There are errors." #define FMT11 "\nEPANET completed. There are errors."

View File

@@ -74,6 +74,10 @@ char *PressUnitsTxt[] = {w_PSI,
w_KPA, w_KPA,
w_METERS}; w_METERS};
char *DemandModelTxt[] = { w_DDA,
w_PDA,
NULL };
char *QualTxt[] = {w_NONE, char *QualTxt[] = {w_NONE,
w_CHEM, w_CHEM,
w_AGE, w_AGE,

File diff suppressed because it is too large Load Diff

View File

@@ -36,10 +36,11 @@ int allocdata(EN_Project *pr); /* Allocates memory
void freeTmplist(STmplist *); /* Frees items in linked list */ void freeTmplist(STmplist *); /* Frees items in linked list */
void freeFloatlist(SFloatlist *); /* Frees list of floats */ void freeFloatlist(SFloatlist *); /* Frees list of floats */
void freedata(EN_Project *pr); /* Frees allocated memory */ void freedata(EN_Project *pr); /* Frees allocated memory */
int openfiles(EN_Project *pr, char *,char *,char *); /* Opens input & report files */ int openfiles(EN_Project *pr, const char *,
const char *,const char *); /* Opens input & report files */
int openhydfile(EN_Project *pr); /* Opens hydraulics file */ int openhydfile(EN_Project *pr); /* Opens hydraulics file */
int openoutfile(EN_Project *pr); /* Opens binary output file */ int openoutfile(EN_Project *pr); /* Opens binary output file */
int strcomp(char *, char *); /* Compares two strings */ int strcomp(const char *, const char *); /* Compares two strings */
char* getTmpName(EN_Project *p, char* fname); /* Gets temporary file name */ char* getTmpName(EN_Project *p, char* fname); /* Gets temporary file name */
double interp(int n, double x[], double y[], double interp(int n, double x[], double y[],
double xx); /* Interpolates a data curve */ double xx); /* Interpolates a data curve */
@@ -51,7 +52,7 @@ int findvalve(EN_Network *n, int); /* Find valve index from node
int findpump(EN_Network *n, int); /* Find pump index from node index */ // (AH) int findpump(EN_Network *n, int); /* Find pump index from node index */ // (AH)
char *geterrmsg(int errcode, char *msg); /* Gets text of error message */ char *geterrmsg(int errcode, char *msg); /* Gets text of error message */
void errmsg(EN_Project *p, int); /* Reports program error */ void errmsg(EN_Project *p, int); /* Reports program error */
void writecon(char *); /* Writes text to console */ void writecon(const char *); /* Writes text to console */
void writewin(void (*vp)(char *), char *); /* Passes text to calling app */ void writewin(void (*vp)(char *), char *); /* Passes text to calling app */
/* ------- INPUT1.C --------------------*/ /* ------- INPUT1.C --------------------*/
@@ -126,6 +127,8 @@ void freerules(EN_Project *pr); /* Frees rule base memory
int writeRuleinInp(EN_Project *pr, FILE *f, /* Writes rule to an INP file */ int writeRuleinInp(EN_Project *pr, FILE *f, /* Writes rule to an INP file */
int RuleIdx); int RuleIdx);
int writeRuleinInp(EN_Project *pr, FILE *f, int RuleIdx);
/* ------------- REPORT.C --------------*/ /* ------------- REPORT.C --------------*/
int writereport(EN_Project *pr); /* Writes formatted report */ int writereport(EN_Project *pr); /* Writes formatted report */
void writelogo(EN_Project *pr); /* Writes program logo */ void writelogo(EN_Project *pr); /* Writes program logo */
@@ -158,28 +161,13 @@ void inithyd(EN_Project *pr, int initFlags); /* Re-sets initial condition
int runhyd(EN_Project *pr, long *); /* Solves 1-period hydraulics */ int runhyd(EN_Project *pr, long *); /* Solves 1-period hydraulics */
int nexthyd(EN_Project *pr, long *); /* Moves to next time period */ int nexthyd(EN_Project *pr, long *); /* Moves to next time period */
void closehyd(EN_Project *pr); /* Closes hydraulics solver */ void closehyd(EN_Project *pr); /* Closes hydraulics solver */
int allocmatrix(EN_Project *pr); /* Allocates matrix coeffs. */
void freematrix(EN_Project *pr); /* Frees matrix coeffs. */
void initlinkflow(EN_Project *pr, int, char,
double); /* Initializes link flow */
void setlinkflow(EN_Project *pr, int, double); /* Sets link flow via headloss*/
void setlinkstatus(EN_Project *pr, int, char, void setlinkstatus(EN_Project *pr, int, char,
StatType *, double *); /* Sets link status */ StatType *, double *); /* Sets link status */
void setlinksetting(EN_Project *pr, int, double, void setlinksetting(EN_Project *pr, int, double,
StatType *, double *); /* Sets pump/valve setting */ StatType *, double *); /* Sets pump/valve setting */
void demands(EN_Project *pr); /* Computes current demands */
int controls(EN_Project *pr); /* Controls link settings */
long timestep(EN_Project *pr); /* Computes new time step */
int tanktimestep(EN_Project *pr, long *); /* Time till tanks fill/drain */ int tanktimestep(EN_Project *pr, long *); /* Time till tanks fill/drain */
void controltimestep(EN_Project *pr, long *); /* Time till control action */
void ruletimestep(EN_Project *pr, long *); /* Time till rule action */
void addenergy(EN_Project *pr, long); /* Accumulates energy usage */
void getenergy(EN_Project *pr, int, double *, void getenergy(EN_Project *pr, int, double *,
double *); /* Computes link energy use */ double *); /* Computes link energy use */
void tanklevels(EN_Project *pr, long); /* Computes new tank levels */
double tankvolume(EN_Project *pr, int,double); /* Finds tank vol. from grade */ double tankvolume(EN_Project *pr, int,double); /* Finds tank vol. from grade */
double tankgrade(EN_Project *pr, int,double); /* Finds tank grade from vol. */ double tankgrade(EN_Project *pr, int,double); /* Finds tank grade from vol. */
@@ -188,8 +176,13 @@ int hydsolve(EN_Project *pr, int *,double *); /* Solves network equations
/* ----------- HYDCOEFFS.C --------------*/ /* ----------- HYDCOEFFS.C --------------*/
void resistcoeff(EN_Project *pr, int k); /* Finds pipe flow resistance */ void resistcoeff(EN_Project *pr, int k); /* Finds pipe flow resistance */
void hlosscoeff(EN_Project *pr, int k); /* Finds link head loss coeff */ void headlosscoeffs(EN_Project *pr); // Finds link head loss coeffs.
void matrixcoeffs(EN_Project *pr); /* Finds hyd. matrix coeffs. */ void matrixcoeffs(EN_Project *pr); /* Finds hyd. matrix coeffs. */
double emitflowchange(EN_Project *pr, int i); /* Change in emitter outflow */
double demandflowchange(EN_Project *pr, int i, // Change in demand outflow
double dp, double n);
void demandparams(EN_Project *pr, double *dp, // PDA function parameters
double *n);
/* ----------- SMATRIX.C ---------------*/ /* ----------- SMATRIX.C ---------------*/
int createsparse(EN_Project *pr); /* Creates sparse matrix */ int createsparse(EN_Project *pr); /* Creates sparse matrix */

View File

@@ -29,15 +29,21 @@ const double AB = 3.28895476345e-03; // 5.74/(4000^.9)
const double AC = -5.14214965799e-03; // AA*AB const double AC = -5.14214965799e-03; // AA*AB
// External functions // External functions
//void resistcoeff(EN_Project *pr, int k); //void resistcoeff(EN_Project *pr, int k);
//void hlosscoeff(EN_Project *pr, int k); //void headlosscoeffs(EN_Project *pr);
//void matrixcoeffs(EN_Project *pr); //void matrixcoeffs(EN_Project *pr);
//double emitflowchange(EN_Project *pr, int i);
//double demandflowchange(EN_Project *pr, int i, double dp, double n);
//void demandparams(EN_Project *pr, double *dp, double *n);
// Local functions // Local functions
static void linkcoeffs(EN_Project *pr); static void linkcoeffs(EN_Project *pr);
static void nodecoeffs(EN_Project *pr); static void nodecoeffs(EN_Project *pr);
static void valvecoeffs(EN_Project *pr); static void valvecoeffs(EN_Project *pr);
static void emittercoeffs(EN_Project *pr); static void emittercoeffs(EN_Project *pr);
static void demandcoeffs(EN_Project *pr);
static void demandheadloss(double d, double dfull, double dp,
double n, double *hloss, double *hgrad);
static void pipecoeff(EN_Project *pr, int k); static void pipecoeff(EN_Project *pr, int k);
static void DWpipecoeff(EN_Project *pr, int k); static void DWpipecoeff(EN_Project *pr, int k);
@@ -55,7 +61,6 @@ static void psvcoeff(EN_Project *pr, int k, int n1, int n2);
static void fcvcoeff(EN_Project *pr, int k, int n1, int n2); static void fcvcoeff(EN_Project *pr, int k, int n1, int n2);
void resistcoeff(EN_Project *pr, int k) void resistcoeff(EN_Project *pr, int k)
/* /*
**-------------------------------------------------------------------- **--------------------------------------------------------------------
@@ -83,13 +88,14 @@ void resistcoeff(EN_Project *pr, int k)
switch (hyd->Formflag) switch (hyd->Formflag)
{ {
case HW: case HW:
link->R = 4.727*L / pow(e, hyd->Hexp) / pow(d, 4.871); link->R = 4.727 * L / pow(e, hyd->Hexp) / pow(d, 4.871);
break; break;
case DW: case DW:
link->R = L / 2.0 / 32.2 / d / SQR(PI*SQR(d) / 4.0); link->R = L / 2.0 / 32.2 / d / SQR(PI * SQR(d) / 4.0);
break; break;
case CM: case CM:
link->R = SQR(4.0*e / (1.49*PI*d*d)) * pow((d / 4.0), -1.333)*L; link->R = SQR(4.0 * e / (1.49 * PI * SQR(d))) *
pow((d / 4.0), -1.333) * L;
} }
break; break;
@@ -106,45 +112,46 @@ void resistcoeff(EN_Project *pr, int k)
} }
void hlosscoeff(EN_Project *pr, int k) void headlosscoeffs(EN_Project *pr)
/* /*
**-------------------------------------------------------------- **--------------------------------------------------------------
** Input: k = link index ** Input: none
** Output: none ** Output: none
** Purpose: computes P and Y coefficients for a link ** Purpose: computes coefficients P (1 / head loss gradient)
** and Y (head loss / gradient) for all links.
**-------------------------------------------------------------- **--------------------------------------------------------------
*/ */
{ {
int k;
EN_Network *net = &pr->network; EN_Network *net = &pr->network;
hydraulics_t *hyd = &pr->hydraulics; hydraulics_t *hyd = &pr->hydraulics;
solver_t *sol = &hyd->solver;
Slink *link = &net->Link[k];
switch (link->Type) for (k = 1; k <= net->Nlinks; k++)
{ {
case EN_CVPIPE: switch (net->Link[k].Type)
case EN_PIPE: {
pipecoeff(pr, k); case EN_CVPIPE:
break; case EN_PIPE:
case EN_PUMP: pipecoeff(pr, k);
pumpcoeff(pr, k); break;
break; case EN_PUMP:
case EN_PBV: pumpcoeff(pr, k);
pbvcoeff(pr, k); break;
break; case EN_PBV:
case EN_TCV: pbvcoeff(pr, k);
tcvcoeff(pr, k); break;
break; case EN_TCV:
case EN_GPV: tcvcoeff(pr, k);
gpvcoeff(pr, k); break;
break; case EN_GPV:
case EN_FCV: gpvcoeff(pr, k);
case EN_PRV: break;
case EN_PSV: case EN_FCV:
if (hyd->LinkSetting[k] == MISSING) { case EN_PRV:
valvecoeff(pr, k); case EN_PSV:
if (hyd->LinkSetting[k] == MISSING) valvecoeff(pr, k);
else hyd->solver.P[k] = 0.0;
} }
else sol->P[k] = 0.0;
} }
} }
@@ -162,13 +169,23 @@ void matrixcoeffs(EN_Project *pr)
solver_t *sol = &hyd->solver; solver_t *sol = &hyd->solver;
EN_Network *net = &pr->network; EN_Network *net = &pr->network;
// Reset values of all diagonal coeffs. (Aii), off-diagonal
// coeffs. (Aij), r.h.s. coeffs. (F) and node flow balance (X_tmp)
memset(sol->Aii, 0, (net->Nnodes + 1) * sizeof(double)); memset(sol->Aii, 0, (net->Nnodes + 1) * sizeof(double));
memset(sol->Aij, 0, (hyd->Ncoeffs + 1) * sizeof(double)); memset(sol->Aij, 0, (hyd->Ncoeffs + 1) * sizeof(double));
memset(sol->F, 0, (net->Nnodes + 1) * sizeof(double)); memset(sol->F, 0, (net->Nnodes + 1) * sizeof(double));
memset(hyd->X_tmp, 0, (net->Nnodes + 1) * sizeof(double)); memset(hyd->X_tmp, 0, (net->Nnodes + 1) * sizeof(double));
// Compute matrix coeffs. from links, emitters, and nodal demands
linkcoeffs(pr); linkcoeffs(pr);
emittercoeffs(pr); emittercoeffs(pr);
demandcoeffs(pr);
// Update nodal flow balances with demands and add onto r.h.s. coeffs.
nodecoeffs(pr); nodecoeffs(pr);
// Finally, find coeffs. for PRV/PSV/FCV control valves whose
// status is not fixed to OPEN/CLOSED
valvecoeffs(pr); valvecoeffs(pr);
} }
@@ -189,7 +206,7 @@ void linkcoeffs(EN_Project *pr)
solver_t *sol = &hyd->solver; solver_t *sol = &hyd->solver;
Slink *link; Slink *link;
// Examine each link of network */ // Examine each link of network
for (k = 1; k <= net->Nlinks; k++) for (k = 1; k <= net->Nlinks; k++)
{ {
if (sol->P[k] == 0.0) continue; if (sol->P[k] == 0.0) continue;
@@ -197,7 +214,7 @@ void linkcoeffs(EN_Project *pr)
n1 = link->N1; // Start node of link n1 = link->N1; // Start node of link
n2 = link->N2; // End node of link n2 = link->N2; // End node of link
// Update net nodal inflows (X), solution matrix (A) and RHS array (F) // Update net nodal inflows (X_tmp), solution matrix (A) and RHS array (F)
// (Use covention that flow out of node is (-), flow into node is (+)) // (Use covention that flow out of node is (-), flow into node is (+))
hyd->X_tmp[n1] -= hyd->LinkFlows[k]; hyd->X_tmp[n1] -= hyd->LinkFlows[k];
hyd->X_tmp[n2] += hyd->LinkFlows[k]; hyd->X_tmp[n2] += hyd->LinkFlows[k];
@@ -212,21 +229,18 @@ void linkcoeffs(EN_Project *pr)
sol->F[sol->Row[n1]] += sol->Y[k]; // RHS coeff. sol->F[sol->Row[n1]] += sol->Y[k]; // RHS coeff.
} }
// Node n1 is a tank // Node n1 is a tank/reservoir
else { else sol->F[sol->Row[n2]] += (sol->P[k] * hyd->NodeHead[n1]);
sol->F[sol->Row[n2]] += (sol->P[k] * hyd->NodeHead[n1]);
}
// Node n2 is junction // Node n2 is junction
if (n2 <= net->Njuncs) { if (n2 <= net->Njuncs)
{
sol->Aii[sol->Row[n2]] += sol->P[k]; // Diagonal coeff. sol->Aii[sol->Row[n2]] += sol->P[k]; // Diagonal coeff.
sol->F[sol->Row[n2]] -= sol->Y[k]; // RHS coeff. sol->F[sol->Row[n2]] -= sol->Y[k]; // RHS coeff.
} }
// Node n2 is a tank // Node n2 is a tank/reservoir
else { else sol->F[sol->Row[n1]] += (sol->P[k] * hyd->NodeHead[n2]);
sol->F[sol->Row[n1]] += (sol->P[k] * hyd->NodeHead[n2]);
}
} }
} }
@@ -236,7 +250,7 @@ void nodecoeffs(EN_Project *pr)
**---------------------------------------------------------------- **----------------------------------------------------------------
** Input: none ** Input: none
** Output: none ** Output: none
** Purpose: completes calculation of nodal flow imbalance (X) ** Purpose: completes calculation of nodal flow imbalance (X_tmp)
** & flow correction (F) arrays ** & flow correction (F) arrays
**---------------------------------------------------------------- **----------------------------------------------------------------
*/ */
@@ -250,7 +264,7 @@ void nodecoeffs(EN_Project *pr)
// flow imbalance & add imbalance to RHS array F. // flow imbalance & add imbalance to RHS array F.
for (i = 1; i <= net->Njuncs; i++) for (i = 1; i <= net->Njuncs; i++)
{ {
hyd->X_tmp[i] -= hyd->NodeDemand[i]; hyd->X_tmp[i] -= hyd->DemandFlows[i];
sol->F[sol->Row[i]] += hyd->X_tmp[i]; sol->F[sol->Row[i]] += hyd->X_tmp[i];
} }
} }
@@ -276,15 +290,20 @@ void valvecoeffs(EN_Project *pr)
// Examine each valve // Examine each valve
for (i = 1; i <= net->Nvalves; i++) for (i = 1; i <= net->Nvalves; i++)
{ {
// Find valve's link index
valve = &net->Valve[i]; valve = &net->Valve[i];
k = valve->Link; // Link index of valve k = valve->Link;
// Coeffs. for fixed status valves have already been computed
if (hyd->LinkSetting[k] == MISSING) continue;
// Start & end nodes of valve's link
link = &net->Link[k]; link = &net->Link[k];
if (hyd->LinkSetting[k] == MISSING) { n1 = link->N1;
continue; // Valve status fixed
}
n1 = link->N1; // Start & end nodes
n2 = link->N2; n2 = link->N2;
switch (link->Type) // Call valve-specific function
// Call valve-specific function
switch (link->Type)
{ {
case EN_PRV: case EN_PRV:
prvcoeff(pr, k, n1, n2); prvcoeff(pr, k, n1, n2);
@@ -330,17 +349,17 @@ void emittercoeffs(EN_Project *pr)
for (i = 1; i <= net->Njuncs; i++) for (i = 1; i <= net->Njuncs; i++)
{ {
node = &net->Node[i]; node = &net->Node[i];
if (node->Ke == 0.0) { if (node->Ke == 0.0) continue;
continue;
}
ke = MAX(CSMALL, node->Ke); // emitter coeff. ke = MAX(CSMALL, node->Ke); // emitter coeff.
q = hyd->EmitterFlows[i]; // emitter flow q = hyd->EmitterFlows[i]; // emitter flow
z = ke * pow(ABS(q), hyd->Qexp); // emitter head loss z = ke * pow(ABS(q), hyd->Qexp); // emitter head loss
p = hyd->Qexp * z / ABS(q); // head loss gradient p = hyd->Qexp * z / ABS(q); // head loss gradient
if (p < hyd->RQtol) { if (p < hyd->RQtol)
{
p = 1.0 / hyd->RQtol; p = 1.0 / hyd->RQtol;
} }
else { else
{
p = 1.0 / p; // inverse head loss gradient p = 1.0 / p; // inverse head loss gradient
} }
y = SGN(q)*z*p; // head loss / gradient y = SGN(q)*z*p; // head loss / gradient
@@ -351,6 +370,173 @@ void emittercoeffs(EN_Project *pr)
} }
double emitflowchange(EN_Project *pr, int i)
/*
**--------------------------------------------------------------
** Input: i = node index
** Output: returns change in flow at an emitter node
** Purpose: computes flow change at an emitter node
**--------------------------------------------------------------
*/
{
double ke, p;
hydraulics_t *hyd = &pr->hydraulics;
Snode *node = &pr->network.Node[i];
ke = MAX(CSMALL, node->Ke);
p = hyd->Qexp * ke * pow(ABS(hyd->EmitterFlows[i]), (hyd->Qexp - 1.0));
if (p < hyd->RQtol) p = 1 / hyd->RQtol;
else p = 1.0 / p;
return(hyd->EmitterFlows[i] / hyd->Qexp - p * (hyd->NodeHead[i] - node->El));
}
void demandparams(EN_Project *pr, double *dp, double *n)
/*
**--------------------------------------------------------------
** Input: none
** Output: dp = pressure range over which demands can vary
** n = exponent in head loss v. demand function
** Purpose: retrieves parameters that define a pressure dependent
** demand function.
**--------------------------------------------------------------
*/
{
hydraulics_t *hyd = &pr->hydraulics;
// If required pressure equals minimum pressure, use a linear demand
// curve with a 0.01 PSI pressure range to approximate an all or
// nothing demand solution
if (hyd->Preq == hyd->Pmin)
{
*dp = 0.01 / PSIperFT;
*n = 1.0;
}
// Otherwise use the user-supplied demand curve parameters
else
{
*dp = hyd->Preq - hyd->Pmin;
*n = 1.0 / hyd->Pexp;
}
}
void demandcoeffs(EN_Project *pr)
/*
**--------------------------------------------------------------
** Input: none
** Output: none
** Purpose: computes matrix coeffs. for pressure dependent demands
**
** Note: Pressure dependent demands are modelled like emitters
** with Hloss = Pserv * (D / Dfull)^(1/Pexp)
** where D (actual demand) is zero for negative pressure
** and is Dfull above pressure Pserv.
**--------------------------------------------------------------
*/
{
int i, row;
double dp, // pressure range over which demand can vary (ft)
n, // exponent in head loss v. demand function
hloss, // head loss in supplying demand (ft)
hgrad; // gradient of demand head loss (ft/cfs)
hydraulics_t *hyd = &pr->hydraulics;
solver_t *sol = &hyd->solver;
EN_Network *net = &pr->network;
// Get demand function parameters
if (hyd->DemandModel == DDA) return;
demandparams(pr, &dp, &n);
// Examine each junction node
for (i = 1; i <= net->Njuncs; i++)
{
// Skip junctions with non-positive demands
if (hyd->NodeDemand[i] <= 0.0) continue;
// Find head loss for demand outflow at node's elevation
demandheadloss(hyd->DemandFlows[i], hyd->NodeDemand[i], dp, n,
&hloss, &hgrad);
// Update row of solution matrix A & its r.h.s. F
row = sol->Row[i];
sol->Aii[row] += 1.0 / hgrad;
sol->F[row] += (hloss + net->Node[i].El + hyd->Pmin) / hgrad;
}
}
double demandflowchange(EN_Project *pr, int i, double dp, double n)
/*
**--------------------------------------------------------------
** Input: i = node index
** dp = pressure range fro demand funtion (ft)
** n = exponent in head v. demand function
** Output: returns change in pressure dependent demand flow
** Purpose: computes change in outflow at at a node subject to
** pressure dependent demands
**--------------------------------------------------------------
*/
{
double hloss, hgrad;
hydraulics_t *hyd = &pr->hydraulics;
demandheadloss(hyd->DemandFlows[i], hyd->NodeDemand[i], dp, n, &hloss, &hgrad);
return (hloss - hyd->NodeHead[i] + pr->network.Node[i].El + hyd->Pmin) / hgrad;
}
void demandheadloss(double d, double dfull, double dp, double n,
double *hloss, double *hgrad)
/*
**--------------------------------------------------------------
** Input: d = actual junction demand (cfs)
** dfull = full junction demand required (cfs)
** dp = pressure range for demand function (ft)
** n = exponent in head v. demand function
** Output: hloss = head loss delivering demand d (ft)
** hgrad = gradient of head loss (ft/cfs)
** Purpose: computes head loss and its gradient for delivering
** a pressure dependent demand flow.
**--------------------------------------------------------------
*/
{
const double RB = 1.0e9;
const double EPS = 0.001;
double r = d / dfull;
// Use upper barrier function for excess demand above full value
if (r > 1.0)
{
*hgrad = RB;
*hloss = dp + RB * (d - dfull);
}
// Use lower barrier function for negative demand
else if (r < 0)
{
*hgrad = RB;
*hloss = RB * d;
}
// Use linear head loss function for near zero demand
else if (r < EPS)
{
*hgrad = dp * pow(EPS, n - 1.0) / dfull;
*hloss = (*hgrad) * d;
}
// Otherwise use power head loss function
else
{
*hgrad = n * dp * pow(r, n - 1.0) / dfull;
*hloss = (*hgrad) * d / n;
}
}
void pipecoeff(EN_Project *pr, int k) void pipecoeff(EN_Project *pr, int k)
/* /*
**-------------------------------------------------------------- **--------------------------------------------------------------
@@ -382,8 +568,9 @@ void pipecoeff(EN_Project *pr, int k)
return; return;
} }
// ... head loss formula is Darcy-Weisbach // Use custom function for Darcy-Weisbach formula
if (hyd->Formflag == DW) { if (hyd->Formflag == DW)
{
DWpipecoeff(pr, k); DWpipecoeff(pr, k);
return; return;
} }
@@ -550,7 +737,8 @@ void pumpcoeff(EN_Project *pr, int k)
Spump *pump; Spump *pump;
// Use high resistance pipe if pump closed or cannot deliver head // Use high resistance pipe if pump closed or cannot deliver head
if (hyd->LinkStatus[k] <= CLOSED || setting == 0.0) { if (hyd->LinkStatus[k] <= CLOSED || setting == 0.0)
{
sol->P[k] = 1.0 / CBIG; sol->P[k] = 1.0 / CBIG;
sol->Y[k] = hyd->LinkFlows[k]; sol->Y[k] = hyd->LinkFlows[k];
return; return;
@@ -580,9 +768,7 @@ void pumpcoeff(EN_Project *pr, int k)
h0 = SQR(setting) * pump->H0; h0 = SQR(setting) * pump->H0;
n = pump->N; n = pump->N;
r = pump->R * pow(setting, 2.0 - n); r = pump->R * pow(setting, 2.0 - n);
if (n != 1.0) { if (n != 1.0) r = n * r * pow(q, n - 1.0);
r = n * r * pow(q, n - 1.0);
}
// Compute inverse headloss gradient (P) and flow correction factor (Y) // Compute inverse headloss gradient (P) and flow correction factor (Y)
sol->P[k] = 1.0 / MAX(r, hyd->RQtol); sol->P[k] = 1.0 / MAX(r, hyd->RQtol);
@@ -615,15 +801,9 @@ void curvecoeff(EN_Project *pr, int i, double q, double *h0, double *r)
// Find linear segment of curve that brackets flow q // Find linear segment of curve that brackets flow q
k2 = 0; k2 = 0;
while (k2 < npts && x[k2] < q) while (k2 < npts && x[k2] < q) k2++;
k2++; if (k2 == 0) k2++;
else if (k2 == npts) k2--;
if (k2 == 0)
k2++;
else if (k2 == npts)
k2--;
k1 = k2 - 1; k1 = k2 - 1;
// Compute slope and intercept of this segment // Compute slope and intercept of this segment
@@ -653,13 +833,12 @@ void gpvcoeff(EN_Project *pr, int k)
solver_t *sol = &hyd->solver; solver_t *sol = &hyd->solver;
// Treat as a pipe if valve closed // Treat as a pipe if valve closed
if (hyd->LinkStatus[k] == CLOSED) { if (hyd->LinkStatus[k] == CLOSED) valvecoeff(pr, k);
valvecoeff(pr, k);
}
// Otherwise utilize headloss curve // Otherwise utilize headloss curve
// whose index is stored in K // whose index is stored in K
else { else
{
// Find slope & intercept of headloss curve. // Find slope & intercept of headloss curve.
q = ABS(hyd->LinkFlows[k]); q = ABS(hyd->LinkFlows[k]);
q = MAX(q, TINY); q = MAX(q, TINY);
@@ -687,18 +866,22 @@ void pbvcoeff(EN_Project *pr, int k)
Slink *link = &pr->network.Link[k]; Slink *link = &pr->network.Link[k];
// If valve fixed OPEN or CLOSED then treat as a pipe // If valve fixed OPEN or CLOSED then treat as a pipe
if (hyd->LinkSetting[k] == MISSING || hyd->LinkSetting[k] == 0.0) { if (hyd->LinkSetting[k] == MISSING || hyd->LinkSetting[k] == 0.0)
{
valvecoeff(pr, k); valvecoeff(pr, k);
} }
// If valve is active // If valve is active
else { else
{
// Treat as a pipe if minor loss > valve setting // Treat as a pipe if minor loss > valve setting
if (link->Km * SQR(hyd->LinkFlows[k]) > hyd->LinkSetting[k]) { if (link->Km * SQR(hyd->LinkFlows[k]) > hyd->LinkSetting[k])
{
valvecoeff(pr, k); valvecoeff(pr, k);
} }
// Otherwise force headloss across valve to be equal to setting // Otherwise force headloss across valve to be equal to setting
else { else
{
sol->P[k] = CBIG; sol->P[k] = CBIG;
sol->Y[k] = hyd->LinkSetting[k] * CBIG; sol->Y[k] = hyd->LinkSetting[k] * CBIG;
} }
@@ -723,7 +906,8 @@ void tcvcoeff(EN_Project *pr, int k)
km = link->Km; km = link->Km;
// If valve not fixed OPEN or CLOSED, compute its loss coeff. // If valve not fixed OPEN or CLOSED, compute its loss coeff.
if (hyd->LinkSetting[k] != MISSING) { if (hyd->LinkSetting[k] != MISSING)
{
link->Km = 0.02517 * hyd->LinkSetting[k] / (SQR(link->Diam)*SQR(link->Diam)); link->Km = 0.02517 * hyd->LinkSetting[k] / (SQR(link->Diam)*SQR(link->Diam));
} }
@@ -768,7 +952,8 @@ void prvcoeff(EN_Project *pr, int k, int n1, int n2)
sol->Y[k] = hyd->LinkFlows[k] + hyd->X_tmp[n2]; // Force flow balance sol->Y[k] = hyd->LinkFlows[k] + hyd->X_tmp[n2]; // Force flow balance
sol->F[j] += (hset * CBIG); // Force head = hset sol->F[j] += (hset * CBIG); // Force head = hset
sol->Aii[j] += CBIG; // at downstream node sol->Aii[j] += CBIG; // at downstream node
if (hyd->X_tmp[n2] < 0.0) { if (hyd->X_tmp[n2] < 0.0)
{
sol->F[i] += hyd->X_tmp[n2]; sol->F[i] += hyd->X_tmp[n2];
} }
return; return;
@@ -818,7 +1003,8 @@ void psvcoeff(EN_Project *pr, int k, int n1, int n2)
sol->Y[k] = hyd->LinkFlows[k] - hyd->X_tmp[n1]; // Force flow balance sol->Y[k] = hyd->LinkFlows[k] - hyd->X_tmp[n1]; // Force flow balance
sol->F[i] += (hset * CBIG); // Force head = hset sol->F[i] += (hset * CBIG); // Force head = hset
sol->Aii[i] += CBIG; // at upstream node sol->Aii[i] += CBIG; // at upstream node
if (hyd->X_tmp[n1] > 0.0) { if (hyd->X_tmp[n1] > 0.0)
{
sol->F[j] += hyd->X_tmp[n1]; sol->F[j] += hyd->X_tmp[n1];
} }
return; return;
@@ -919,9 +1105,7 @@ void valvecoeff(EN_Project *pr, int k)
if (link->Km > 0.0) if (link->Km > 0.0)
{ {
p = 2.0 * link->Km * fabs(flow); p = 2.0 * link->Km * fabs(flow);
if (p < hyd->RQtol) { if (p < hyd->RQtol) p = hyd->RQtol;
p = hyd->RQtol;
}
sol->P[k] = 1.0 / p; sol->P[k] = 1.0 / p;
sol->Y[k] = flow / 2.0; sol->Y[k] = flow / 2.0;
} }

View File

@@ -60,6 +60,20 @@ AUTHOR: L. Rossman
#define QZERO 1.e-6 /* Equivalent to zero flow */ #define QZERO 1.e-6 /* Equivalent to zero flow */
// Local functions
int allocmatrix(EN_Project *pr);
void freematrix(EN_Project *pr);
void initlinkflow(EN_Project *pr, int, char, double);
void setlinkflow(EN_Project *pr, int, double);
void demands(EN_Project *pr);
int controls(EN_Project *pr);
long timestep(EN_Project *pr);
void controltimestep(EN_Project *pr, long *);
void ruletimestep(EN_Project *pr, long *);
void addenergy(EN_Project *pr, long);
void tanklevels(EN_Project *pr, long);
int openhyd(EN_Project *pr) int openhyd(EN_Project *pr)
/* /*
*-------------------------------------------------------------- *--------------------------------------------------------------
@@ -194,15 +208,12 @@ int runhyd(EN_Project *pr, long *t)
/* Solve network hydraulic equations */ /* Solve network hydraulic equations */
errcode = hydsolve(pr,&iter,&relerr); errcode = hydsolve(pr,&iter,&relerr);
if (!errcode) { if (!errcode) {
/* Report new status & save results */ /* Report new status & save results */
if (rep->Statflag) { if (rep->Statflag) {
writehydstat(pr,iter,relerr); writehydstat(pr,iter,relerr);
} }
/* solution info */
hyd->relativeError = relerr;
hyd->iterations = iter;
/*** Updated 3/1/01 ***/ /*** Updated 3/1/01 ***/
/* If system unbalanced and no extra trials */ /* If system unbalanced and no extra trials */
@@ -316,6 +327,7 @@ int allocmatrix(EN_Project *pr)
s->Aii = (double *) calloc(net->Nnodes+1,sizeof(double)); s->Aii = (double *) calloc(net->Nnodes+1,sizeof(double));
s->Aij = (double *) calloc(hyd->Ncoeffs+1,sizeof(double)); s->Aij = (double *) calloc(hyd->Ncoeffs+1,sizeof(double));
s->F = (double *) calloc(net->Nnodes+1,sizeof(double)); s->F = (double *) calloc(net->Nnodes+1,sizeof(double));
hyd->DemandFlows = (double *)calloc(net->Nnodes + 1, sizeof(double));
hyd->EmitterFlows = (double *) calloc(net->Nnodes+1,sizeof(double)); hyd->EmitterFlows = (double *) calloc(net->Nnodes+1,sizeof(double));
s->P = (double *) calloc(net->Nlinks+1,sizeof(double)); s->P = (double *) calloc(net->Nlinks+1,sizeof(double));
s->Y = (double *) calloc(net->Nlinks+1,sizeof(double)); s->Y = (double *) calloc(net->Nlinks+1,sizeof(double));
@@ -324,6 +336,7 @@ int allocmatrix(EN_Project *pr)
ERRCODE(MEMCHECK(s->Aii)); ERRCODE(MEMCHECK(s->Aii));
ERRCODE(MEMCHECK(s->Aij)); ERRCODE(MEMCHECK(s->Aij));
ERRCODE(MEMCHECK(s->F)); ERRCODE(MEMCHECK(s->F));
ERRCODE(MEMCHECK(hyd->DemandFlows));
ERRCODE(MEMCHECK(hyd->EmitterFlows)); ERRCODE(MEMCHECK(hyd->EmitterFlows));
ERRCODE(MEMCHECK(s->P)); ERRCODE(MEMCHECK(s->P));
ERRCODE(MEMCHECK(s->Y)); ERRCODE(MEMCHECK(s->Y));
@@ -348,6 +361,7 @@ void freematrix(EN_Project *pr)
free(s->Aii); free(s->Aii);
free(s->Aij); free(s->Aij);
free(s->F); free(s->F);
free(hyd->DemandFlows);
free(hyd->EmitterFlows); free(hyd->EmitterFlows);
free(s->P); free(s->P);
free(s->Y); free(s->Y);
@@ -551,7 +565,6 @@ void setlinksetting(EN_Project *pr, int index, double value, StatType *s, doubl
} }
void demands(EN_Project *pr) void demands(EN_Project *pr)
/* /*
**-------------------------------------------------------------------- **--------------------------------------------------------------------
@@ -591,6 +604,9 @@ void demands(EN_Project *pr)
sum += djunc; sum += djunc;
} }
hyd->NodeDemand[i] = sum; hyd->NodeDemand[i] = sum;
// Initialize pressure dependent demand
hyd->DemandFlows[i] = sum;
} }
/* Update head at fixed grade nodes with time patterns. */ /* Update head at fixed grade nodes with time patterns. */

File diff suppressed because it is too large Load Diff

462
src/hydstatus.c Normal file
View File

@@ -0,0 +1,462 @@
/*
*********************************************************************
HYDSTATUS.C -- Hydraulic status updating for the EPANET Program
*******************************************************************
*/
#include <stdio.h>
#include "types.h"
#include "funcs.h"
// External functions
int valvestatus(EN_Project *pr);
int linkstatus(EN_Project *pr);
// Local functions
static StatType cvstatus(EN_Project *pr, StatType, double, double);
static StatType pumpstatus(EN_Project *pr, int, double);
static StatType prvstatus(EN_Project *pr, int, StatType, double, double, double);
static StatType psvstatus(EN_Project *pr, int, StatType, double, double, double);
static StatType fcvstatus(EN_Project *pr, int, StatType, double, double);
static void tankstatus(EN_Project *pr, int, int, int);
int valvestatus(EN_Project *pr)
/*
**-----------------------------------------------------------------
** Input: none
** Output: returns 1 if any pressure or flow control valve
** changes status, 0 otherwise
** Purpose: updates status for PRVs & PSVs whose status
** is not fixed to OPEN/CLOSED
**-----------------------------------------------------------------
*/
{
int change = FALSE, // Status change flag
i, k, // Valve & link indexes
n1, n2; // Start & end nodes
StatType status; // Valve status settings
double hset; // Valve head setting
Slink *link;
EN_Network *net = &pr->network;
hydraulics_t *hyd = &pr->hydraulics;
report_options_t *rep = &pr->report;
// Examine each valve
for (i = 1; i <= net->Nvalves; i++)
{
// Get valve's link and its index
k = net->Valve[i].Link;
link = &net->Link[k];
// Ignore valve if its status is fixed to OPEN/CLOSED
if (hyd->LinkSetting[k] == MISSING) continue;
// Get start/end node indexes & save current status
n1 = link->N1;
n2 = link->N2;
status = hyd->LinkStatus[k];
// Evaluate valve's new status
switch (link->Type)
{
case EN_PRV:
hset = net->Node[n2].El + hyd->LinkSetting[k];
hyd->LinkStatus[k] = prvstatus(pr, k, status, hset,
hyd->NodeHead[n1], hyd->NodeHead[n2]);
break;
case EN_PSV:
hset = net->Node[n1].El + hyd->LinkSetting[k];
hyd->LinkStatus[k] = psvstatus(pr, k, status, hset,
hyd->NodeHead[n1], hyd->NodeHead[n2]);
break;
default:
continue;
}
// Check for a status change
if (status != hyd->LinkStatus[k])
{
if (rep->Statflag == FULL)
{
writestatchange(pr, k, status, hyd->LinkStatus[k]);
}
change = TRUE;
}
}
return change;
} /* End of valvestatus() */
int linkstatus(EN_Project *pr)
/*
**--------------------------------------------------------------
** Input: none
** Output: returns 1 if any link changes status, 0 otherwise
** Purpose: determines new status for pumps, CVs, FCVs & pipes
** to tanks.
**--------------------------------------------------------------
*/
{
int change = FALSE, // Status change flag
k, // Link index
n1, // Start node index
n2; // End node index
double dh; // Head difference across link
StatType status; // Current status
EN_Network *net = &pr->network;
hydraulics_t *hyd = &pr->hydraulics;
report_options_t *rep = &pr->report;
Slink *link;
// Examine each link
for (k = 1; k <= net->Nlinks; k++)
{
link = &net->Link[k];
n1 = link->N1;
n2 = link->N2;
dh = hyd->NodeHead[n1] - hyd->NodeHead[n2];
// Re-open temporarily closed links (status = XHEAD or TEMPCLOSED)
status = hyd->LinkStatus[k];
if (status == XHEAD || status == TEMPCLOSED)
{
hyd->LinkStatus[k] = OPEN;
}
// Check for status changes in CVs and pumps
if (link->Type == EN_CVPIPE)
{
hyd->LinkStatus[k] = cvstatus(pr, hyd->LinkStatus[k], dh,
hyd->LinkFlows[k]);
}
if (link->Type == EN_PUMP && hyd->LinkStatus[k] >= OPEN &&
hyd->LinkSetting[k] > 0.0)
{
hyd->LinkStatus[k] = pumpstatus(pr, k, -dh);
}
// Check for status changes in non-fixed FCVs
if (link->Type == EN_FCV && hyd->LinkSetting[k] != MISSING)
{
hyd->LinkStatus[k] = fcvstatus(pr, k, status, hyd->NodeHead[n1],
hyd->NodeHead[n2]);
}
// Check for flow into (out of) full (empty) tanks
if (n1 > net->Njuncs || n2 > net->Njuncs)
{
tankstatus(pr, k, n1, n2);
}
// Note any change in link status; do not revise link flow
if (status != hyd->LinkStatus[k])
{
change = TRUE;
if (rep->Statflag == FULL)
{
writestatchange(pr, k, status, hyd->LinkStatus[k]);
}
}
}
return change;
}
StatType cvstatus(EN_Project *pr, StatType s, double dh, double q)
/*
**--------------------------------------------------
** Input: s = current link status
** dh = head loss across link
** q = link flow
** Output: returns new link status
** Purpose: updates status of a check valve link.
**--------------------------------------------------
*/
{
hydraulics_t *hyd = &pr->hydraulics;
// Prevent reverse flow through CVs
if (ABS(dh) > hyd->Htol)
{
if (dh < -hyd->Htol) return CLOSED;
else if (q < -hyd->Qtol) return CLOSED;
else return OPEN;
}
else
{
if (q < -hyd->Qtol) return CLOSED;
else return s;
}
}
StatType pumpstatus(EN_Project *pr, int k, double dh)
/*
**--------------------------------------------------
** Input: k = link index
** dh = head gain across link
** Output: returns new pump status
** Purpose: updates status of an open pump.
**--------------------------------------------------
*/
{
int p;
double hmax;
hydraulics_t *hyd = &pr->hydraulics;
EN_Network *net = &pr->network;
// Find maximum head (hmax) pump can deliver
p = findpump(net, k);
if (net->Pump[p].Ptype == CONST_HP)
{
// Use huge value for constant HP pump
hmax = BIG;
}
else
{
// Use speed-adjusted shut-off head for other pumps
hmax = SQR(hyd->LinkSetting[k]) * net->Pump[p].Hmax;
}
// Check if currrent head gain exceeds pump's max. head
if (dh > hmax + hyd->Htol) return XHEAD;
// No check is made to see if flow exceeds pump's max. flow
return OPEN;
}
StatType prvstatus(EN_Project *pr, int k, StatType s, double hset,
double h1, double h2)
/*
**-----------------------------------------------------------
** Input: k = link index
** s = current status
** hset = valve head setting
** h1 = head at upstream node
** h2 = head at downstream node
** Output: returns new valve status
** Purpose: updates status of a pressure reducing valve.
**-----------------------------------------------------------
*/
{
StatType status; // Valve's new status
double hml; // Head loss when fully opened
hydraulics_t *hyd = &pr->hydraulics;
double htol = hyd->Htol;
Slink *link = &pr->network.Link[k];
// Head loss when fully open
hml = link->Km * SQR(hyd->LinkFlows[k]);
// Rules for updating valve's status from current value s
status = s;
switch (s)
{
case ACTIVE:
if (hyd->LinkFlows[k] < -hyd->Qtol) status = CLOSED;
else if (h1 - hml < hset - htol) status = OPEN;
else status = ACTIVE;
break;
case OPEN:
if (hyd->LinkFlows[k] < -hyd->Qtol) status = CLOSED;
else if (h2 >= hset + htol) status = ACTIVE;
else status = OPEN;
break;
case CLOSED:
if (h1 >= hset + htol && h2 < hset - htol) status = ACTIVE;
else if (h1 < hset - htol && h1 > h2 + htol) status = OPEN;
else status = CLOSED;
break;
case XPRESSURE:
if (hyd->LinkFlows[k] < -hyd->Qtol) status = CLOSED;
break;
default:
break;
}
return status;
}
StatType psvstatus(EN_Project *pr, int k, StatType s, double hset,
double h1, double h2)
/*
**-----------------------------------------------------------
** Input: k = link index
** s = current status
** hset = valve head setting
** h1 = head at upstream node
** h2 = head at downstream node
** Output: returns new valve status
** Purpose: updates status of a pressure sustaining valve.
**-----------------------------------------------------------
*/
{
StatType status; // Valve's new status
double hml; // Head loss when fully opened
hydraulics_t *hyd = &pr->hydraulics;
double htol = hyd->Htol;
Slink *link = &pr->network.Link[k];
// Head loss when fully open
hml = link->Km * SQR(hyd->LinkFlows[k]);
// Rules for updating valve's status from current value s
status = s;
switch (s)
{
case ACTIVE:
if (hyd->LinkFlows[k] < -hyd->Qtol) status = CLOSED;
else if (h2 + hml > hset + htol) status = OPEN;
else status = ACTIVE;
break;
case OPEN:
if (hyd->LinkFlows[k] < -hyd->Qtol) status = CLOSED;
else if (h1 < hset - htol) status = ACTIVE;
else status = OPEN;
break;
case CLOSED:
if (h2 > hset + htol && h1 > h2 + htol) status = OPEN;
else if (h1 >= hset + htol && h1 > h2 + htol) status = ACTIVE;
else status = CLOSED;
break;
case XPRESSURE:
if (hyd->LinkFlows[k] < -hyd->Qtol) status = CLOSED;
break;
default:
break;
}
return status;
}
StatType fcvstatus(EN_Project *pr, int k, StatType s, double h1, double h2)
/*
**-----------------------------------------------------------
** Input: k = link index
** s = current status
** h1 = head at upstream node
** h2 = head at downstream node
** Output: returns new valve status
** Purpose: updates status of a flow control valve.
**
** Valve status changes to XFCV if flow reversal.
** If current status is XFCV and current flow is
** above setting, then valve becomes active.
** If current status is XFCV, and current flow
** positive but still below valve setting, then
** status remains same.
**-----------------------------------------------------------
*/
{
StatType status; // New valve status
hydraulics_t *hyd = &pr->hydraulics;
status = s;
if (h1 - h2 < -hyd->Htol)
{
status = XFCV;
}
else if (hyd->LinkFlows[k] < -hyd->Qtol)
{
status = XFCV;
}
else if (s == XFCV && hyd->LinkFlows[k] >= hyd->LinkSetting[k])
{
status = ACTIVE;
}
return status;
}
void tankstatus(EN_Project *pr, int k, int n1, int n2)
/*
**----------------------------------------------------------------
** Input: k = link index
** n1 = start node of link
** n2 = end node of link
** Output: none
** Purpose: closes link flowing into full or out of empty tank
**----------------------------------------------------------------
*/
{
int i, n;
double h, q;
Stank *tank;
hydraulics_t *hyd = &pr->hydraulics;
EN_Network *net = &pr->network;
Slink *link = &net->Link[k];
// Return if link is closed
if (hyd->LinkStatus[k] <= CLOSED) return;
// Make node n1 be the tank, reversing flow (q) if need be
q = hyd->LinkFlows[k];
i = n1 - net->Njuncs;
if (i <= 0)
{
i = n2 - net->Njuncs;
if (i <= 0) return;
n = n1;
n1 = n2;
n2 = n;
q = -q;
}
// Ignore reservoirs
tank = &net->Tank[i];
if (tank->A == 0.0) return;
// Find head difference across link
h = hyd->NodeHead[n1] - hyd->NodeHead[n2];
// If tank is full, then prevent flow into it
if (hyd->NodeHead[n1] >= tank->Hmax - hyd->Htol)
{
// Case 1: Link is a pump discharging into tank
if (link->Type == EN_PUMP)
{
if (link->N2 == n1) hyd->LinkStatus[k] = TEMPCLOSED;
}
// Case 2: Downstream head > tank head
// (e.g., an open outflow check valve would close)
else if (cvstatus(pr, OPEN, h, q) == CLOSED)
{
hyd->LinkStatus[k] = TEMPCLOSED;
}
}
// If tank is empty, then prevent flow out of it
if (hyd->NodeHead[n1] <= tank->Hmin + hyd->Htol)
{
// Case 1: Link is a pump discharging from tank
if (link->Type == EN_PUMP)
{
if (link->N1 == n1) hyd->LinkStatus[k] = TEMPCLOSED;
}
// Case 2: Tank head > downstream head
// (e.g., a closed outflow check valve would open)
else if (cvstatus(pr, CLOSED, h, q) == OPEN)
{
hyd->LinkStatus[k] = TEMPCLOSED;
}
}
}

View File

@@ -26,14 +26,14 @@ data describing a piping network to a file in EPANET's text format.
#else #else
#include <stdlib.h> #include <stdlib.h>
#endif #endif
#include "hash.h" #include "hash.h"
#include "text.h" #include "text.h"
#include "types.h" #include "types.h"
#include "epanet2.h"
#include "funcs.h" #include "funcs.h"
#include <math.h> #include <math.h>
#define EXTERN extern //#define EXTERN extern
#include "vars.h" //#include "vars.h"
/* Defined in enumstxt.h in EPANET.C */ /* Defined in enumstxt.h in EPANET.C */
extern char *LinkTxt[]; extern char *LinkTxt[];
@@ -624,6 +624,13 @@ int saveinpfile(EN_Project *pr, char *fname)
if (hyd->FlowChangeLimit > 0.0) { if (hyd->FlowChangeLimit > 0.0) {
fprintf(f, "\n FLOWCHANGE %-.8f", hyd->FlowChangeLimit * pr->Ucf[FLOW]); fprintf(f, "\n FLOWCHANGE %-.8f", hyd->FlowChangeLimit * pr->Ucf[FLOW]);
} }
if (hyd->DemandModel == PDA)
{
fprintf(f, "\n DEMAND MODEL PDA");
fprintf(f, "\n MINIMUM PRESSURE %-.4f", hyd->Pmin * pr->Ucf[PRESSURE]);
fprintf(f, "\n REQUIRED PRESSURE %-.4f", hyd->Preq * pr->Ucf[PRESSURE]);
fprintf(f, "\n PRESSURE EXPONENT %-.4f", hyd->Pexp);
}
/* Write [REPORT] section */ /* Write [REPORT] section */

View File

@@ -33,8 +33,6 @@ AUTHOR: L. Rossman
#include "epanet2.h" #include "epanet2.h"
#include "funcs.h" #include "funcs.h"
#include <math.h> #include <math.h>
#define EXTERN extern
#include "vars.h"
/* /*
--------------------- Module Global Variables ---------------------- --------------------- Module Global Variables ----------------------
@@ -128,8 +126,12 @@ void setdefaults(EN_Project *pr)
hyd->Qtol = QTOL; /* Default flow tolerance */ hyd->Qtol = QTOL; /* Default flow tolerance */
hyd->Hacc = HACC; /* Default hydraulic accuracy */ hyd->Hacc = HACC; /* Default hydraulic accuracy */
hyd->FlowChangeLimit = 0.0; /* Default flow change limit */ hyd->FlowChangeLimit = 0.0; // Default flow change limit
hyd->HeadErrorLimit = 0.0; /* Default head error limit */ hyd->HeadErrorLimit = 0.0; // Default head error limit
hyd->DemandModel = DDA; // Demand driven analysis
hyd->Pmin = 0.0; // Minimum demand pressure (ft)
hyd->Preq = 0.0; // Required demand pressure (ft)
hyd->Pexp = 0.5; // Pressure function exponent
qu->Ctol = MISSING; /* No pre-set quality tolerance */ qu->Ctol = MISSING; /* No pre-set quality tolerance */
hyd->MaxIter = MAXITER; /* Default max. hydraulic trials */ hyd->MaxIter = MAXITER; /* Default max. hydraulic trials */
@@ -581,6 +583,8 @@ void convertunits(EN_Project *pr)
demand->Base /= pr->Ucf[DEMAND]; demand->Base /= pr->Ucf[DEMAND];
} }
} }
hyd->Pmin /= pr->Ucf[PRESSURE];
hyd->Preq /= pr->Ucf[PRESSURE];
/* Convert emitter discharge coeffs. to head loss coeff. */ /* Convert emitter discharge coeffs. to head loss coeff. */
ucf = pow(pr->Ucf[FLOW], hyd->Qexp) / pr->Ucf[PRESSURE]; ucf = pow(pr->Ucf[FLOW], hyd->Qexp) / pr->Ucf[PRESSURE];

View File

@@ -37,8 +37,6 @@ The following utility functions are all called from INPUT3.C
#include "epanet2.h" #include "epanet2.h"
#include "funcs.h" #include "funcs.h"
#include <math.h> #include <math.h>
#define EXTERN extern
#include "vars.h"
#define MAXERRS 10 /* Max. input errors reported */ #define MAXERRS 10 /* Max. input errors reported */
@@ -822,9 +820,10 @@ int match(const char *str, const char *substr)
break; break;
/* Check if substr matches remainder of str. */ /* Check if substr matches remainder of str. */
for (i = i, j = 0; substr[j]; i++, j++) for (j = 0; substr[j]; i++, j++)
if (!str[i] || UCHAR(str[i]) != UCHAR(substr[j])) if (!str[i] || UCHAR(str[i]) != UCHAR(substr[j]))
return (0); return (0);
return (1); return (1);
} /* end of match */ } /* end of match */

View File

@@ -32,12 +32,11 @@ All functions in this module are called from newline() in INPUT2.C.
#include "text.h" #include "text.h"
#include "types.h" #include "types.h"
#include <math.h> #include <math.h>
#define EXTERN extern
#include "vars.h"
/* Defined in enumstxt.h in EPANET.C */ /* Defined in enumstxt.h in EPANET.C */
extern char *MixTxt[]; extern char *MixTxt[];
extern char *Fldname[]; extern char *Fldname[];
extern char *DemandModelTxt[];
/* Defined in INPUT2.C */ /* Defined in INPUT2.C */
@@ -1763,6 +1762,7 @@ int optionchoice(EN_Project *pr, int n)
** VERIFY filename ** VERIFY filename
** UNBALANCED STOP/CONTINUE {Niter} ** UNBALANCED STOP/CONTINUE {Niter}
** PATTERN id ** PATTERN id
** DEMAND MODEL DDA/PDA/PPA
**-------------------------------------------------------------- **--------------------------------------------------------------
*/ */
{ {
@@ -1771,131 +1771,125 @@ int optionchoice(EN_Project *pr, int n)
quality_t *qu = &pr->quality; quality_t *qu = &pr->quality;
parser_data_t *par = &pr->parser; parser_data_t *par = &pr->parser;
out_file_t *out = &pr->out_files; out_file_t *out = &pr->out_files;
int choice;
/* Check if 1st token matches a parameter name and */ /* Check if 1st token matches a parameter name and */
/* process the input for the matched parameter */ /* process the input for the matched parameter */
if (n < 0) if (n < 0) return (201);
return (201); if (match(par->Tok[0], w_UNITS))
if (match(par->Tok[0], w_UNITS)) { {
if (n < 1) if (n < 1) return (0);
return (0); else if (match(par->Tok[1], w_CFS)) par->Flowflag = CFS;
else if (match(par->Tok[1], w_CFS)) else if (match(par->Tok[1], w_GPM)) par->Flowflag = GPM;
par->Flowflag = CFS; else if (match(par->Tok[1], w_AFD)) par->Flowflag = AFD;
else if (match(par->Tok[1], w_GPM)) else if (match(par->Tok[1], w_MGD)) par->Flowflag = MGD;
par->Flowflag = GPM; else if (match(par->Tok[1], w_IMGD)) par->Flowflag = IMGD;
else if (match(par->Tok[1], w_AFD)) else if (match(par->Tok[1], w_LPS)) par->Flowflag = LPS;
par->Flowflag = AFD; else if (match(par->Tok[1], w_LPM)) par->Flowflag = LPM;
else if (match(par->Tok[1], w_MGD)) else if (match(par->Tok[1], w_CMH)) par->Flowflag = CMH;
par->Flowflag = MGD; else if (match(par->Tok[1], w_CMD)) par->Flowflag = CMD;
else if (match(par->Tok[1], w_IMGD)) else if (match(par->Tok[1], w_MLD)) par->Flowflag = MLD;
par->Flowflag = IMGD; else if (match(par->Tok[1], w_SI)) par->Flowflag = LPS;
else if (match(par->Tok[1], w_LPS)) else return (201);
par->Flowflag = LPS; }
else if (match(par->Tok[1], w_LPM))
par->Flowflag = LPM; else if (match(par->Tok[0], w_PRESSURE))
else if (match(par->Tok[1], w_CMH)) {
par->Flowflag = CMH; if (n < 1) return (0);
else if (match(par->Tok[1], w_CMD)) else if (match(par->Tok[1], w_EXPONENT)) return -1;
par->Flowflag = CMD; else if (match(par->Tok[1], w_PSI)) par->Pressflag = PSI;
else if (match(par->Tok[1], w_MLD)) else if (match(par->Tok[1], w_KPA)) par->Pressflag = KPA;
par->Flowflag = MLD; else if (match(par->Tok[1], w_METERS)) par->Pressflag = METERS;
else if (match(par->Tok[1], w_SI)) else return (201);
par->Flowflag = LPS; }
else
return (201); else if (match(par->Tok[0], w_HEADLOSS))
} else if (match(par->Tok[0], w_PRESSURE)) { {
if (n < 1) if (n < 1) return (0);
return (0); else if (match(par->Tok[1], w_HW)) hyd->Formflag = HW;
else if (match(par->Tok[1], w_PSI)) else if (match(par->Tok[1], w_DW)) hyd->Formflag = DW;
par->Pressflag = PSI; else if (match(par->Tok[1], w_CM)) hyd->Formflag = CM;
else if (match(par->Tok[1], w_KPA)) else return (201);
par->Pressflag = KPA; }
else if (match(par->Tok[1], w_METERS))
par->Pressflag = METERS; else if (match(par->Tok[0], w_HYDRAULIC))
else {
return (201); if (n < 2) return (0);
} else if (match(par->Tok[0], w_HEADLOSS)) { else if (match(par->Tok[1], w_USE)) out->Hydflag = USE;
if (n < 1) else if (match(par->Tok[1], w_SAVE)) out->Hydflag = SAVE;
return (0); else return (201);
else if (match(par->Tok[1], w_HW))
hyd->Formflag = HW;
else if (match(par->Tok[1], w_DW))
hyd->Formflag = DW;
else if (match(par->Tok[1], w_CM))
hyd->Formflag = CM;
else
return (201);
} else if (match(par->Tok[0], w_HYDRAULIC)) {
if (n < 2)
return (0);
else if (match(par->Tok[1], w_USE))
out->Hydflag = USE;
else if (match(par->Tok[1], w_SAVE))
out->Hydflag = SAVE;
else
return (201);
strncpy(out->HydFname, par->Tok[2], MAXFNAME); strncpy(out->HydFname, par->Tok[2], MAXFNAME);
} else if (match(par->Tok[0], w_QUALITY)) { }
if (n < 1)
return (0); else if (match(par->Tok[0], w_QUALITY))
else if (match(par->Tok[1], w_NONE)) {
qu->Qualflag = NONE; if (n < 1) return (0);
else if (match(par->Tok[1], w_CHEM)) else if (match(par->Tok[1], w_NONE)) qu->Qualflag = NONE;
qu->Qualflag = CHEM; else if (match(par->Tok[1], w_CHEM)) qu->Qualflag = CHEM;
else if (match(par->Tok[1], w_AGE)) else if (match(par->Tok[1], w_AGE)) qu->Qualflag = AGE;
qu->Qualflag = AGE; else if (match(par->Tok[1], w_TRACE)) qu->Qualflag = TRACE;
else if (match(par->Tok[1], w_TRACE)) else
qu->Qualflag = TRACE; {
else { qu->Qualflag = CHEM;
qu->Qualflag = CHEM; strncpy(qu->ChemName, par->Tok[1], MAXID);
strncpy(qu->ChemName, par->Tok[1], MAXID); if (n >= 2) strncpy(qu->ChemUnits, par->Tok[2], MAXID);
if (n >= 2)
strncpy(qu->ChemUnits, par->Tok[2], MAXID);
} }
if (qu->Qualflag == TRACE) /* Source tracing option */ if (qu->Qualflag == TRACE) /* Source tracing option */
{ {
/* Copy Trace Node ID to par->Tok[0] for error reporting */ /* Copy Trace Node ID to par->Tok[0] for error reporting */
strcpy(par->Tok[0], ""); strcpy(par->Tok[0], "");
if (n < 2) if (n < 2) return (212);
return (212);
strcpy(par->Tok[0], par->Tok[2]); strcpy(par->Tok[0], par->Tok[2]);
qu->TraceNode = findnode(net,par->Tok[2]); qu->TraceNode = findnode(net,par->Tok[2]);
if (qu->TraceNode == 0) if (qu->TraceNode == 0) return (212);
return (212);
strncpy(qu->ChemName, u_PERCENT, MAXID); strncpy(qu->ChemName, u_PERCENT, MAXID);
strncpy(qu->ChemUnits, par->Tok[2], MAXID); strncpy(qu->ChemUnits, par->Tok[2], MAXID);
} }
if (qu->Qualflag == AGE) { if (qu->Qualflag == AGE)
{
strncpy(qu->ChemName, w_AGE, MAXID); strncpy(qu->ChemName, w_AGE, MAXID);
strncpy(qu->ChemUnits, u_HOURS, MAXID); strncpy(qu->ChemUnits, u_HOURS, MAXID);
} }
} else if (match(par->Tok[0], w_MAP)) { }
if (n < 1)
return (0); else if (match(par->Tok[0], w_MAP))
{
if (n < 1) return (0);
strncpy(pr->MapFname, par->Tok[1], MAXFNAME); /* Map file name */ strncpy(pr->MapFname, par->Tok[1], MAXFNAME); /* Map file name */
} else if (match(par->Tok[0], w_VERIFY)) { }
else if (match(par->Tok[0], w_VERIFY))
{
/* Backward compatibility for verification file */ /* Backward compatibility for verification file */
} else if (match(par->Tok[0], w_UNBALANCED)) /* Unbalanced option */ }
else if (match(par->Tok[0], w_UNBALANCED)) /* Unbalanced option */
{ {
if (n < 1) if (n < 1) return (0);
return (0); if (match(par->Tok[1], w_STOP)) hyd->ExtraIter = -1;
if (match(par->Tok[1], w_STOP)) else if (match(par->Tok[1], w_CONTINUE))
hyd->ExtraIter = -1; {
else if (match(par->Tok[1], w_CONTINUE)) { if (n >= 2) hyd->ExtraIter = atoi(par->Tok[2]);
if (n >= 2) else hyd->ExtraIter = 0;
hyd->ExtraIter = atoi(par->Tok[2]); }
else else return (201);
hyd->ExtraIter = 0; }
} else
return (201); else if (match(par->Tok[0], w_PATTERN)) /* Pattern option */
} else if (match(par->Tok[0], w_PATTERN)) /* Pattern option */
{ {
if (n < 1) if (n < 1) return (0);
return (0);
strncpy(par->DefPatID, par->Tok[1], MAXID); strncpy(par->DefPatID, par->Tok[1], MAXID);
} else }
return (-1);
else if (match(par->Tok[0], w_DEMAND))
{
if (n < 2) return 0;
if (!match(par->Tok[1], w_MODEL)) return -1;
choice = findmatch(par->Tok[2], DemandModelTxt);
if (choice < 0) return 201;
hyd->DemandModel = choice;
}
else return (-1);
return (0); return (0);
} /* end of optionchoice */ } /* end of optionchoice */
@@ -1916,6 +1910,9 @@ int optionvalue(EN_Project *pr, int n)
** HEADLIMIT value ** HEADLIMIT value
** FLOWLIMIT value ** FLOWLIMIT value
** MINIMUM PRESSURE value
** REQUIRED PRESSURE value
** PRESSURE EXPONENT value
** TOLERANCE value ** TOLERANCE value
** SEGMENTS value (not used) ** SEGMENTS value (not used)
@@ -1939,39 +1936,40 @@ int optionvalue(EN_Project *pr, int n)
double y; double y;
/* Check for obsolete SEGMENTS keyword */ /* Check for obsolete SEGMENTS keyword */
//if (match(par->Tok[0], w_SEGMENTS)) if (match(tok0, w_SEGMENTS)) return (0);
if (match(tok0, w_SEGMENTS))
return (0);
/* Check for missing value (which is permissible) */ /* Check for missing value (which is permissible) */
if (match(tok0, w_SPECGRAV) || match(tok0, w_EMITTER) || if (match(tok0, w_SPECGRAV) || match(tok0, w_EMITTER) ||
match(tok0, w_DEMAND)) match(tok0, w_DEMAND) || match(tok0, w_MINIMUM) ||
match(tok0, w_REQUIRED) || match(tok0, w_PRESSURE) ||
match(tok0, w_PRECISION))
{
nvalue = 2; nvalue = 2;
if (n < nvalue) }
return (0); if (n < nvalue) return (0);
/* Check for valid numerical input */ /* Check for valid numerical input */
if (!getfloat(par->Tok[nvalue], &y)) if (!getfloat(par->Tok[nvalue], &y)) return (213);
return (213);
/* Check for WQ tolerance option (which can be 0) */ /* Check for WQ tolerance option (which can be 0) */
if (match(tok0, w_TOLERANCE)) { if (match(tok0, w_TOLERANCE))
if (y < 0.0) {
return (213); if (y < 0.0) return (213);
qu->Ctol = y; /* Quality tolerance*/ qu->Ctol = y; /* Quality tolerance*/
return (0); return (0);
} }
/* Check for Diffusivity option */ /* Check for Diffusivity option */
if (match(tok0, w_DIFFUSIVITY)) { if (match(tok0, w_DIFFUSIVITY))
if (y < 0.0) {
return (213); if (y < 0.0) return (213);
qu->Diffus = y; qu->Diffus = y;
return (0); return (0);
} }
/* Check for Damping Limit option */ /* Check for Damping Limit option */
if (match(tok0, w_DAMPLIMIT)) { if (match(tok0, w_DAMPLIMIT))
{
hyd->DampLimit = y; hyd->DampLimit = y;
return (0); return (0);
} }
@@ -1992,41 +1990,51 @@ int optionvalue(EN_Project *pr, int n)
return 0; return 0;
} }
/* Check for pressure dependent demand params */
else if (match(tok0, w_MINIMUM))
{
if (y < 0.0) return 213;
hyd->Pmin = y;
return 0;
}
else if (match(tok0, w_REQUIRED))
{
if (y < 0.0) return 213;
hyd->Preq = y;
return 0;
}
else if (match(tok0, w_PRESSURE))
{
if (y < 0.0) return 213;
hyd->Pexp = y;
return 0;
}
/* All other options must be > 0 */ /* All other options must be > 0 */
if (y <= 0.0) if (y <= 0.0) return (213);
return (213);
/* Assign value to specified option */ /* Assign value to specified option */
if (match(tok0, w_VISCOSITY)) if (match(tok0, w_VISCOSITY)) hyd->Viscos = y; /* Viscosity */
hyd->Viscos = y; /* Viscosity */ else if (match(tok0, w_SPECGRAV)) hyd->SpGrav = y; /* Spec. gravity */
else if (match(tok0, w_SPECGRAV)) else if (match(tok0, w_TRIALS)) hyd->MaxIter = (int)y; /* Max. trials */
hyd->SpGrav = y; /* Spec. gravity */
else if (match(tok0, w_TRIALS))
hyd->MaxIter = (int)y; /* Max. trials */
else if (match(tok0, w_ACCURACY)) /* Accuracy */ else if (match(tok0, w_ACCURACY)) /* Accuracy */
{ {
y = MAX(y, 1.e-5); y = MAX(y, 1.e-5);
y = MIN(y, 1.e-1); y = MIN(y, 1.e-1);
hyd->Hacc = y; hyd->Hacc = y;
} }
else if (match(tok0, w_HTOL)) else if (match(tok0, w_HTOL)) hyd->Htol = y;
hyd->Htol = y; else if (match(tok0, w_QTOL)) hyd->Qtol = y;
else if (match(tok0, w_QTOL)) else if (match(tok0, w_RQTOL))
hyd->Qtol = y; {
else if (match(tok0, w_RQTOL)) { if (y >= 1.0) return (213);
if (y >= 1.0)
return (213);
hyd->RQtol = y; hyd->RQtol = y;
} else if (match(tok0, w_CHECKFREQ)) }
hyd->CheckFreq = (int)y; else if (match(tok0, w_CHECKFREQ)) hyd->CheckFreq = (int)y;
else if (match(tok0, w_MAXCHECK)) else if (match(tok0, w_MAXCHECK)) hyd->MaxCheck = (int)y;
hyd->MaxCheck = (int)y; else if (match(tok0, w_EMITTER)) hyd->Qexp = 1.0 / y;
else if (match(tok0, w_EMITTER)) else if (match(tok0, w_DEMAND)) hyd->Dmult = y;
hyd->Qexp = 1.0 / y; else return (201);
else if (match(tok0, w_DEMAND))
hyd->Dmult = y;
else
return (201);
return (0); return (0);
} /* end of optionvalue */ } /* end of optionvalue */
@@ -2091,7 +2099,8 @@ int getpumpcurve(EN_Project *pr, int n)
return (0); return (0);
} }
int powercurve(double h0, double h1, double h2, double q1, double q2, double *a, double *b, double *c) int powercurve(double h0, double h1, double h2, double q1, double q2,
double *a, double *b, double *c)
/* /*
**--------------------------------------------------------- **---------------------------------------------------------
** Input: h0 = shutoff head ** Input: h0 = shutoff head

View File

@@ -19,14 +19,12 @@ AUTHOR: L. Rossman
#else #else
#include <stdlib.h> #include <stdlib.h>
#endif #endif
#include "epanet2.h"
#include "funcs.h" #include "funcs.h"
#include "text.h" #include "text.h"
#include "types.h" #include "types.h"
#include <math.h> #include <math.h>
#define EXTERN extern
#include "hash.h" #include "hash.h"
#include "vars.h"
/* write x[1] to x[n] to file */ /* write x[1] to x[n] to file */
size_t f_save(REAL4 *x, int n, FILE *file) { size_t f_save(REAL4 *x, int n, FILE *file) {

View File

@@ -54,15 +54,13 @@ AUTHOR: L. Rossman
#else #else
#include <stdlib.h> #include <stdlib.h>
#endif #endif
#include "hash.h" #include "hash.h"
#include "text.h" #include "text.h"
#include "types.h" #include "types.h"
#include "epanet2.h"
#include "funcs.h" #include "funcs.h"
#include <math.h> #include <math.h>
#define EXTERN extern
#include "mempool.h" #include "mempool.h"
#include "vars.h"
/* /*
** Macros to identify upstream & downstream nodes of a link ** Macros to identify upstream & downstream nodes of a link

View File

@@ -32,15 +32,13 @@ formatted string S to the report file.
#else #else
#include <stdlib.h> #include <stdlib.h>
#endif #endif
#include "epanet2.h"
#include "funcs.h" #include "funcs.h"
#include "hash.h" #include "hash.h"
#include "text.h" #include "text.h"
#include "types.h" #include "types.h"
#include <math.h> #include <math.h>
#include <time.h> #include <time.h>
#define EXTERN extern
#include "vars.h"
#undef WINDOWS #undef WINDOWS
#ifdef _WIN32 #ifdef _WIN32
@@ -50,12 +48,13 @@ formatted string S to the report file.
#define MAXCOUNT 10 /* Max. # of disconnected nodes listed */ #define MAXCOUNT 10 /* Max. # of disconnected nodes listed */
/* Defined in enumstxt.h in EPANET.C */ /* Defined in enumstxt.h */
extern char *NodeTxt[]; extern char *NodeTxt[];
extern char *LinkTxt[]; extern char *LinkTxt[];
extern char *StatTxt[]; extern char *StatTxt[];
extern char *TstatTxt[]; extern char *TstatTxt[];
extern char *RptFormTxt[]; extern char *RptFormTxt[];
extern char *DemandModelTxt[];
typedef REAL4 *Pfloat; typedef REAL4 *Pfloat;
void writenodetable(EN_Project *pr, Pfloat *); void writenodetable(EN_Project *pr, Pfloat *);
@@ -224,6 +223,8 @@ void writesummary(EN_Project *pr)
writeline(pr, s); writeline(pr, s);
sprintf(s, FMT25, RptFormTxt[hyd->Formflag]); sprintf(s, FMT25, RptFormTxt[hyd->Formflag]);
writeline(pr, s); writeline(pr, s);
sprintf(s, FMT25a, DemandModelTxt[hyd->DemandModel]);
writeline(pr, s);
sprintf(s, FMT26, time->Hstep * pr->Ucf[TIME], rep->Field[TIME].Units); sprintf(s, FMT26, time->Hstep * pr->Ucf[TIME], rep->Field[TIME].Units);
writeline(pr, s); writeline(pr, s);
sprintf(s, FMT27, hyd->Hacc); sprintf(s, FMT27, hyd->Hacc);

View File

@@ -29,13 +29,11 @@ AUTHOR: L. Rossman
#else #else
#include <stdlib.h> #include <stdlib.h>
#endif #endif
#include "epanet2.h"
#include "funcs.h" #include "funcs.h"
#include "hash.h" #include "hash.h"
#include "text.h" #include "text.h"
#include "types.h" #include "types.h"
#define EXTERN extern
#include "vars.h"
enum Rulewords { enum Rulewords {
r_RULE, r_RULE,
@@ -114,7 +112,7 @@ int takeactions(EN_Project *pr);
void clearactlist(rules_t *rules); void clearactlist(rules_t *rules);
void clearrules(EN_Project *pr); void clearrules(EN_Project *pr);
void ruleerrmsg(EN_Project *pr, int); void ruleerrmsg(EN_Project *pr, int);
int writeRuleinInp(EN_Project *pr, FILE *f, int RuleIdx); //int writeRuleinInp(EN_Project *pr, FILE *f, int RuleIdx);
void initrules(rules_t *rules) void initrules(rules_t *rules)
/* /*

View File

@@ -145,6 +145,12 @@ AUTHOR: L. Rossman
#define w_FLOWCHANGE "FLOWCHANGE" #define w_FLOWCHANGE "FLOWCHANGE"
#define w_HEADERROR "HEADERROR" #define w_HEADERROR "HEADERROR"
#define w_MODEL "MODEL"
#define w_DDA "DDA"
#define w_PDA "PDA"
#define w_REQUIRED "REQ"
#define w_EXPONENT "EXP"
#define w_SECONDS "SEC" #define w_SECONDS "SEC"
#define w_MINUTES "MIN" #define w_MINUTES "MIN"
#define w_HOURS "HOU" #define w_HOURS "HOU"
@@ -323,6 +329,9 @@ AUTHOR: L. Rossman
#define t_perM3 " /m3" #define t_perM3 " /m3"
#define t_perMGAL "/Mgal" #define t_perMGAL "/Mgal"
#define t_DIFFER "DIFFERENTIAL" #define t_DIFFER "DIFFERENTIAL"
#define t_FIXED "Fixed Demands"
#define t_POWER "Power Function"
#define t_ORIFICE "Orifice Flow"
/* ------------------ Format Messages ------------------*/ /* ------------------ Format Messages ------------------*/
@@ -338,17 +347,12 @@ AUTHOR: L. Rossman
"* Version %d.%d *" "* Version %d.%d *"
#define LOGO6 \ #define LOGO6 \
"******************************************************************" "******************************************************************"
#define FMT01 "\n... EPANET Version %d.%d\n"
#define FMT02 "\n o Retrieving network data" #define FMT02 "\n o Retrieving network data"
#define FMT03 "\n Correct syntax is:\n %s <input file> <output file>\n"
#define FMT04 "\n Cannot use duplicate file names." #define FMT04 "\n Cannot use duplicate file names."
#define FMT05 "\n Cannot open input file " #define FMT05 "\n Cannot open input file "
#define FMT06 "\n Cannot open report file " #define FMT06 "\n Cannot open report file "
#define FMT07 "\n Cannot open output file " #define FMT07 "\n Cannot open output file "
#define FMT08 "\n Cannot open temporary output file" #define FMT08 "\n Cannot open temporary output file"
#define FMT09 "\n\n... EPANET completed.\n"
#define FMT10 "\n\n... EPANET completed. There are warnings.\n"
#define FMT11 "\n\n... EPANET completed. There are errors.\n"
#define FMT14 "\n o Computing hydraulics at hour " #define FMT14 "\n o Computing hydraulics at hour "
#define FMT15 "\n o Computing water quality at hour " #define FMT15 "\n o Computing water quality at hour "
#define FMT16 "\n o Transferring results to file" #define FMT16 "\n o Transferring results to file"
@@ -362,6 +366,7 @@ AUTHOR: L. Rossman
#define FMT23 " Number of Pumps ................... %-d" #define FMT23 " Number of Pumps ................... %-d"
#define FMT24 " Number of Valves .................. %-d" #define FMT24 " Number of Valves .................. %-d"
#define FMT25 " Headloss Formula .................. %s" #define FMT25 " Headloss Formula .................. %s"
#define FMT25a " Nodal Demand Model ................ %s"
#define FMT26 " Hydraulic Timestep ................ %-.2f %s" #define FMT26 " Hydraulic Timestep ................ %-.2f %s"
#define FMT27 " Hydraulic Accuracy ................ %-.6f" #define FMT27 " Hydraulic Accuracy ................ %-.6f"
@@ -420,7 +425,8 @@ AUTHOR: L. Rossman
/*** End of update ***/ /*** End of update ***/
#define FMT66 " maximum flow change = %.4f for Link %s" #define FMT66 " maximum flow change = %.4f for Link %s"
#define FMT67 " maximum head error = %.4f for Link %s\n" #define FMT67 " maximum flow change = %.4f for Node %s"
#define FMT68 " maximum head error = %.4f for Link %s\n"
/* -------------------- Energy Report Table ------------------- */ /* -------------------- Energy Report Table ------------------- */
#define FMT71 "Energy Usage:" #define FMT71 "Energy Usage:"

View File

@@ -23,6 +23,8 @@ AUTHOR: L. Rossman
#include "epanet2.h" #include "epanet2.h"
#include "hash.h" #include "hash.h"
#include "mempool.h" #include "mempool.h"
#include "util/errormanager.h"
/*********************************************************/ /*********************************************************/
/* All floats have been re-declared as doubles (7/3/07). */ /* All floats have been re-declared as doubles (7/3/07). */
@@ -299,6 +301,11 @@ typedef enum {
MAX_ENERGY_STATS MAX_ENERGY_STATS
} EnergyStats; } EnergyStats;
typedef enum {
DDA, // Demand Driven Analysis
PDA // Pressure Driven Analysis
} DemandModelType;
/* /*
------------------------------------------------------ ------------------------------------------------------
Global Data Structures Global Data Structures
@@ -760,7 +767,8 @@ typedef struct {
typedef struct { typedef struct {
double double
*NodeDemand, /* Node actual demand */ *NodeDemand, // Node actual total outflow
*DemandFlows, // Demand outflows
*EmitterFlows, /* Emitter flows */ *EmitterFlows, /* Emitter flows */
*LinkSetting, /* Link settings */ *LinkSetting, /* Link settings */
*LinkFlows, /* Link flows */ *LinkFlows, /* Link flows */
@@ -769,10 +777,13 @@ typedef struct {
Qtol, /* Flow rate tolerance */ Qtol, /* Flow rate tolerance */
RQtol, /* Flow resistance tolerance */ RQtol, /* Flow resistance tolerance */
Hexp, /* Exponent in headloss formula */ Hexp, /* Exponent in headloss formula */
Qexp, /* Exponent in orifice formula */ Qexp, /* Exponent in emitter formula */
Pexp, // Exponent in demand formula
Pmin, // Pressure needed for any demand
Preq, // Pressure needed for full demand
Dmult, /* Demand multiplier */ Dmult, /* Demand multiplier */
Hacc, /* Hydraulics solution accuracy */
Hacc, /* Hydraulics solution accuracy */
FlowChangeLimit, /* Hydraulics flow change limit */ FlowChangeLimit, /* Hydraulics flow change limit */
HeadErrorLimit, /* Hydraulics head error limit */ HeadErrorLimit, /* Hydraulics head error limit */
@@ -788,7 +799,8 @@ typedef struct {
int int
DefPat, /* Default demand pattern */ DefPat, /* Default demand pattern */
Epat; /* Energy cost time pattern */ Epat, /* Energy cost time pattern */
DemandModel; // Fixed or pressure dependent
StatType StatType
*LinkStatus, /* Link status */ *LinkStatus, /* Link status */
@@ -806,8 +818,10 @@ typedef struct {
Formflag; /* Hydraulic formula flag */ Formflag; /* Hydraulic formula flag */
/* Info about hydraulic solution */ /* Info about hydraulic solution */
double relativeError; double RelativeError;
int iterations; double MaxHeadError;
double MaxFlowChange;
int Iterations;
/* Flag used to halt taking further time steps */ /* Flag used to halt taking further time steps */
int Haltflag; int Haltflag;
@@ -849,7 +863,7 @@ typedef struct {
/* project wrapper */ /* project wrapper */
struct EN_Project { typedef struct EN_Project {
EN_Network network; /// the network description struct EN_Network network; /// the network description struct
hydraulics_t hydraulics; hydraulics_t hydraulics;
@@ -871,8 +885,10 @@ struct EN_Project {
Title[MAXTITLE][MAXMSG+1], /// Problem title Title[MAXTITLE][MAXMSG+1], /// Problem title
MapFname[MAXFNAME+1]; /// Map file name MapFname[MAXFNAME+1]; /// Map file name
error_handle_t* error_handle; //Simple error manager
void (* viewprog) (char *); /* Pointer to progress viewing function */ void (* viewprog) (char *); /* Pointer to progress viewing function */
}; } EN_Project;
#endif #endif

73
src/util/errormanager.c Normal file
View File

@@ -0,0 +1,73 @@
//-----------------------------------------------------------------------------
//
// errormanager.c
//
// Purpose: Provides a simple interface for managing runtime error messages.
//
// Date: 08/25/2017
//
// Author: Michael E. Tryby
// US EPA - ORD/NRMRL
//-----------------------------------------------------------------------------
#include "errormanager.h"
error_handle_t* new_errormanager(void (*p_error_message)(int, char*, int))
//
// Purpose: Constructs a new error handle.
//
{
error_handle_t* error_handle;
error_handle = (error_handle_t*)calloc(1, sizeof(error_handle_t));
if (error_handle != NULL)
error_handle->p_msg_lookup = p_error_message;
return error_handle;
}
void dst_errormanager(error_handle_t* error_handle)
//
// Purpose: Destroys the error handle.
//
{
free(error_handle);
}
int set_error(error_handle_t* error_handle, int errorcode)
//
// Purpose: Sets an error code in the handle.
//
{
// If the error code is 0 no action is taken and 0 is returned.
// This is a feature not a bug.
if (errorcode)
error_handle->error_status = errorcode;
return errorcode;
}
char* check_error(error_handle_t* error_handle)
//
// Purpose: Returns the error message or NULL.
//
// Note: Caller must free memory allocated by check_error
//
{
char* temp = NULL;
if (error_handle->error_status != 0) {
temp = (char*) calloc(ERR_MAXMSG, sizeof(char));
if (temp)
error_handle->p_msg_lookup(error_handle->error_status, temp, ERR_MAXMSG);
}
return temp;
}
void clear_error(error_handle_t* error_handle)
//
// Purpose: Clears the error from the handle.
//
{
error_handle->error_status = 0;
}

30
src/util/errormanager.h Normal file
View File

@@ -0,0 +1,30 @@
/*
* errormanager.h
*
* Created on: Aug 25, 2017
*
* Author: Michael E. Tryby
* US EPA - ORD/NRMRL
*/
#ifndef ERRORMANAGER_H_
#define ERRORMANAGER_H_
#include <stdlib.h>
#include <string.h>
#define ERR_MAXMSG 256
typedef struct error_s {
int error_status;
void (*p_msg_lookup)(int, char*, int);
} error_handle_t;
error_handle_t* new_errormanager(void (*p_error_message)(int, char*, int));
void dst_errormanager(error_handle_t* error_handle);
int set_error(error_handle_t* error_handle, int errorcode);
char* check_error(error_handle_t* error_handle);
void clear_error(error_handle_t* error_handle);
#endif /* ERRORMANAGER_H_ */

View File

@@ -11,6 +11,6 @@
// this single global variable is used only when the library is called in "legacy mode" // this single global variable is used only when the library is called in "legacy mode"
// with the 2.1-style API. // with the 2.1-style API.
EXTERN EN_Project *_defaultModel; EXTERN void *_defaultModel;
#endif #endif

View File

@@ -37,8 +37,7 @@ foreach(testSrc ${TEST_SRCS})
#link to Boost libraries AND your targets and dependencies #link to Boost libraries AND your targets and dependencies
target_link_libraries(${testName} ${Boost_LIBRARIES} epanet epanet-output) target_link_libraries(${testName} ${Boost_LIBRARIES} epanet epanet-output)
#Finally add it to test execution
#Finally add it to test execution -
#Notice the WORKING_DIRECTORY and COMMAND #Notice the WORKING_DIRECTORY and COMMAND
add_test(NAME ${testName} add_test(NAME ${testName}
COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${testName} COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${testName}

BIN
tests/data/example1.out Normal file

Binary file not shown.

178
tests/data/net1.inp Normal file
View File

@@ -0,0 +1,178 @@
[TITLE]
EPANET Example Network 1
A simple example of modeling chlorine decay. Both bulk and
wall reactions are included.
[JUNCTIONS]
;ID Elev Demand Pattern
10 710 0 ;
11 710 150 ;
12 700 150 ;
13 695 100 ;
21 700 150 ;
22 695 200 ;
23 690 150 ;
31 700 100 ;
32 710 100 ;
[RESERVOIRS]
;ID Head Pattern
9 800 ;
[TANKS]
;ID Elevation InitLevel MinLevel MaxLevel Diameter MinVol VolCurve
2 850 120 100 150 50.5 0 ;
[PIPES]
;ID Node1 Node2 Length Diameter Roughness MinorLoss Status
10 10 11 10530 18 100 0 Open ;
11 11 12 5280 14 100 0 Open ;
12 12 13 5280 10 100 0 Open ;
21 21 22 5280 10 100 0 Open ;
22 22 23 5280 12 100 0 Open ;
31 31 32 5280 6 100 0 Open ;
110 2 12 200 18 100 0 Open ;
111 11 21 5280 10 100 0 Open ;
112 12 22 5280 12 100 0 Open ;
113 13 23 5280 8 100 0 Open ;
121 21 31 5280 8 100 0 Open ;
122 22 32 5280 6 100 0 Open ;
[PUMPS]
;ID Node1 Node2 Parameters
9 9 10 HEAD 1 ;
[VALVES]
;ID Node1 Node2 Diameter Type Setting MinorLoss
[TAGS]
[DEMANDS]
;Junction Demand Pattern Category
[STATUS]
;ID Status/Setting
[PATTERNS]
;ID Multipliers
;Demand Pattern
1 1.0 1.2 1.4 1.6 1.4 1.2
1 1.0 0.8 0.6 0.4 0.6 0.8
[CURVES]
;ID X-Value Y-Value
;PUMP: Pump Curve for Pump 9
1 1500 250
[CONTROLS]
LINK 9 OPEN IF NODE 2 BELOW 110
LINK 9 CLOSED IF NODE 2 ABOVE 140
[RULES]
[ENERGY]
Global Efficiency 75
Global Price 0.0
Demand Charge 0.0
[EMITTERS]
;Junction Coefficient
[QUALITY]
;Node InitQual
10 0.5
11 0.5
12 0.5
13 0.5
21 0.5
22 0.5
23 0.5
31 0.5
32 0.5
9 1.0
2 1.0
[SOURCES]
;Node Type Quality Pattern
[REACTIONS]
;Type Pipe/Tank Coefficient
[REACTIONS]
Order Bulk 1
Order Tank 1
Order Wall 1
Global Bulk -.5
Global Wall -1
Limiting Potential 0.0
Roughness Correlation 0.0
[MIXING]
;Tank Model
[TIMES]
Duration 24:00
Hydraulic Timestep 1:00
Quality Timestep 0:05
Pattern Timestep 2:00
Pattern Start 0:00
Report Timestep 1:00
Report Start 0:00
Start ClockTime 12 am
Statistic None
[REPORT]
Status Yes
Summary No
Page 0
[OPTIONS]
Units GPM
Headloss H-W
Specific Gravity 1.0
Viscosity 1.0
Trials 40
Accuracy 0.001
CHECKFREQ 2
MAXCHECK 10
DAMPLIMIT 0
Unbalanced Continue 10
Pattern 1
Demand Multiplier 1.0
Emitter Exponent 0.5
Quality Chlorine mg/L
Diffusivity 1.0
Tolerance 0.01
[COORDINATES]
;Node X-Coord Y-Coord
10 20.00 70.00
11 30.00 70.00
12 50.00 70.00
13 70.00 70.00
21 30.00 40.00
22 50.00 40.00
23 70.00 40.00
31 30.00 10.00
32 50.00 10.00
9 10.00 70.00
2 50.00 90.00
[VERTICES]
;Link X-Coord Y-Coord
[LABELS]
;X-Coord Y-Coord Label & Anchor Node
6.99 73.63 "Source"
13.48 68.13 "Pump"
43.85 91.21 "Tank"
[BACKDROP]
DIMENSIONS 7.00 6.00 73.00 94.00
UNITS None
FILE
OFFSET 0.00 0.00
[END]

View File

@@ -22,8 +22,7 @@
#include "epanet_output.h" #include "epanet_output.h"
#define DATA_PATH "./example1.out"
#define DATA_PATH "./net1.out"
using namespace std; using namespace std;
@@ -117,7 +116,6 @@ struct Fixture{
float* array; float* array;
int array_dim; int array_dim;
}; };
BOOST_AUTO_TEST_SUITE(test_output_fixture) BOOST_AUTO_TEST_SUITE(test_output_fixture)
@@ -144,6 +142,15 @@ BOOST_FIXTURE_TEST_CASE(test_getNetSize, Fixture)
ENR_free((void**)&i_array); ENR_free((void**)&i_array);
} }
BOOST_FIXTURE_TEST_CASE(test_getUnits, Fixture) {
int flag;
error = ENR_getUnits(p_handle, ENR_qualUnits, &flag);
BOOST_REQUIRE(error == 0);
BOOST_CHECK_EQUAL(flag, ENR_MGL);
}
BOOST_FIXTURE_TEST_CASE(test_getElementName, Fixture) { BOOST_FIXTURE_TEST_CASE(test_getElementName, Fixture) {
char* name = new char[MAXID]; char* name = new char[MAXID];
int length, index = 1; int length, index = 1;
@@ -179,7 +186,6 @@ BOOST_FIXTURE_TEST_CASE(test_getNodeAttribute, Fixture) {
std::vector<float> ref_vec; std::vector<float> ref_vec;
ref_vec.assign(ref_array, ref_array + ref_dim); ref_vec.assign(ref_array, ref_array + ref_dim);
std::vector<float> test_vec; std::vector<float> test_vec;
test_vec.assign(array, array + array_dim); test_vec.assign(array, array + array_dim);

207
tests/test_toolkit.cpp Normal file
View File

@@ -0,0 +1,207 @@
//
// test_epanet_toolkit.cpp
//
// Date Created: January 24, 2018
//
// Author: Michael E. Tryby
// US EPA - ORD/NRMRL
//
//#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE "toolkit"
#include <boost/test/included/unit_test.hpp>
#include <string>
#include "epanet2.h"
// NOTE: Project Home needs to be updated to run unit test
#define DATA_PATH_INP "./net1.inp"
#define DATA_PATH_RPT "./test.rpt"
#define DATA_PATH_OUT "./test.out"
using namespace std;
BOOST_AUTO_TEST_SUITE (test_toolkit)
BOOST_AUTO_TEST_CASE (test_alloc_free)
{
int error = 0;
EN_ProjectHandle ph = NULL;
error = EN_createproject(&ph);
BOOST_REQUIRE(error == 0);
BOOST_CHECK(ph != NULL);
error = EN_deleteproject(&ph);
BOOST_REQUIRE(error == 0);
BOOST_CHECK(ph == NULL);
}
BOOST_AUTO_TEST_CASE (test_open_close)
{
EN_ProjectHandle ph = NULL;
EN_createproject(&ph);
std::string path_inp = std::string(DATA_PATH_INP);
std::string path_rpt = std::string(DATA_PATH_RPT);
std::string path_out = std::string(DATA_PATH_OUT);
int error = EN_open(ph, path_inp.c_str(), path_rpt.c_str(), path_out.c_str());
BOOST_REQUIRE(error == 0);
error = EN_close(ph);
BOOST_REQUIRE(error == 0);
EN_deleteproject(&ph);
}
BOOST_AUTO_TEST_CASE(test_epanet)
{
std::string path_inp = std::string(DATA_PATH_INP);
std::string path_rpt = std::string(DATA_PATH_RPT);
std::string path_out = std::string(DATA_PATH_OUT);
int error = ENepanet(path_inp.c_str(), path_rpt.c_str(), path_out.c_str(), NULL);
BOOST_REQUIRE(error == 0);
}
BOOST_AUTO_TEST_SUITE_END()
struct Fixture{
Fixture() {
path_inp = std::string(DATA_PATH_INP);
path_rpt = std::string(DATA_PATH_RPT);
path_out = std::string(DATA_PATH_OUT);
EN_createproject(&ph);
error = EN_open(ph, path_inp.c_str(), path_rpt.c_str(), path_out.c_str());
}
~Fixture() {
error = EN_close(ph);
EN_deleteproject(&ph);
}
std::string path_inp;
std::string path_rpt;
std::string path_out;
int error;
EN_ProjectHandle ph;
};
BOOST_AUTO_TEST_SUITE(test_epanet_fixture)
BOOST_FIXTURE_TEST_CASE(test_epanet, Fixture)
{
error = EN_solveH(ph);
BOOST_REQUIRE(error == 0);
error = EN_solveQ(ph);
BOOST_REQUIRE(error == 0);
error = EN_report(ph);
BOOST_REQUIRE(error == 0);
}
BOOST_FIXTURE_TEST_CASE(test_hyd_step, Fixture)
{
int flag = 00;
long t, tstep;
error = EN_openH(ph);
BOOST_REQUIRE(error == 0);
error = EN_initH(ph, flag);
BOOST_REQUIRE(error == 0);
do {
error = EN_runH(ph, &t);
BOOST_REQUIRE(error == 0);
error = EN_nextH(ph, &tstep);
BOOST_REQUIRE(error == 0);
} while (tstep > 0);
error = EN_closeH(ph);
BOOST_REQUIRE(error == 0);
}
BOOST_FIXTURE_TEST_CASE(test_qual_step, Fixture)
{
int flag = 0;
long t, tstep;
error = EN_solveH(ph);
BOOST_REQUIRE(error == 0);
error = EN_openQ(ph);
BOOST_REQUIRE(error == 0);
error = EN_initQ(ph, flag);
BOOST_REQUIRE(error == 0);
do {
error = EN_runQ(ph, &t);
BOOST_REQUIRE(error == 0);
error = EN_nextQ(ph, &tstep);
BOOST_REQUIRE(error == 0);
} while (tstep > 0);
error = EN_closeQ(ph);
BOOST_REQUIRE(error == 0);
}
BOOST_FIXTURE_TEST_CASE(test_progressive_stepping, Fixture)
{
int flag = EN_NOSAVE;
long t, tstep_h, tstep_q;
error = EN_openH(ph);
BOOST_REQUIRE(error == 0);
error = EN_initH(ph, flag);
BOOST_REQUIRE(error == 0);
error = EN_openQ(ph);
BOOST_REQUIRE(error == 0);
error = EN_initQ(ph, flag);
BOOST_REQUIRE(error == 0);
do {
error = EN_runH(ph, &t);
BOOST_REQUIRE(error == 0);
error = EN_runQ(ph, &t);
BOOST_REQUIRE(error == 0);
error = EN_nextH(ph, &tstep_h);
BOOST_REQUIRE(error == 0);
error = EN_nextQ(ph, &tstep_q);
BOOST_REQUIRE(error == 0);
} while (tstep_h > 0);
error = EN_closeH(ph);
BOOST_REQUIRE(error == 0);
error = EN_closeQ(ph);
BOOST_REQUIRE(error == 0);
}
BOOST_AUTO_TEST_SUITE_END()

View File

@@ -25,8 +25,8 @@ set SCRIPT_HOME=%~dp0
set TEST_HOME=%~1 set TEST_HOME=%~1
set EXAMPLES_VER=1.0.2-dev.1 set EXAMPLES_VER=1.0.2-dev.2
set BENCHMARK_VER=220dev1 set BENCHMARK_VER=220dev2
set TESTFILES_URL=https://github.com/OpenWaterAnalytics/epanet-example-networks/archive/v%EXAMPLES_VER%.zip set TESTFILES_URL=https://github.com/OpenWaterAnalytics/epanet-example-networks/archive/v%EXAMPLES_VER%.zip

View File

@@ -18,22 +18,42 @@
typedef void* ENR_Handle; typedef void* ENR_Handle;
typedef enum { typedef enum {
ENR_node = 1, ENR_node = 1,
ENR_link = 2 ENR_link = 2
} ENR_ElementType; } ENR_ElementType;
typedef enum { typedef enum {
ENR_getSeries = 1, ENR_flowUnits = 1,
ENR_getAttribute = 2, ENR_pressUnits = 2,
ENR_getResult = 3, ENR_qualUnits = 3
ENR_getReacts = 4, } ENR_Units;
ENR_getEnergy = 5
} ENR_ApiFunction;
typedef enum { typedef enum {
ENR_flowUnits = 1, ENR_CFS = 0,
ENR_pressUnits = 2 ENR_GPM = 1,
} ENR_Units; ENR_MGD = 2,
ENR_IMGD = 3,
ENR_AFD = 4,
ENR_LPS = 5,
ENR_LPM = 6,
ENR_MLD = 7,
ENR_CMH = 8,
ENR_CMD = 9
} ENR_FlowUnits;
typedef enum {
ENR_PSI = 0,
ENR_MTR = 1,
ENR_KPA = 2
} ENR_PressUnits;
typedef enum {
ENR_NONE = 0,
ENR_MGL = 1,
ENR_UGL = 2,
ENR_HOURS = 3,
ENR_PRCNT = 4
} ENR_QualUnits;
typedef enum { typedef enum {
ENR_reportStart = 1, ENR_reportStart = 1,
@@ -43,21 +63,21 @@ typedef enum {
}ENR_Time; }ENR_Time;
typedef enum { typedef enum {
ENR_demand = 1, ENR_demand = 1,
ENR_head = 2, ENR_head = 2,
ENR_pressure = 3, ENR_pressure = 3,
ENR_quality = 4 ENR_quality = 4
} ENR_NodeAttribute; } ENR_NodeAttribute;
typedef enum { typedef enum {
ENR_flow = 1, ENR_flow = 1,
ENR_velocity = 2, ENR_velocity = 2,
ENR_headloss = 3, ENR_headloss = 3,
ENR_avgQuality = 4, ENR_avgQuality = 4,
ENR_status = 5, ENR_status = 5,
ENR_setting = 6, ENR_setting = 6,
ENR_rxRate = 7, ENR_rxRate = 7,
ENR_frctnFctr = 8 ENR_frctnFctr = 8
} ENR_LinkAttribute; } ENR_LinkAttribute;

View File

@@ -57,7 +57,8 @@
#define MINNREC 14 // Minimum allowable number of records #define MINNREC 14 // Minimum allowable number of records
#define PROLOGUE 884 // Preliminary fixed length section of header #define PROLOGUE 884 // Preliminary fixed length section of header
#define MAXID_P1 32 // Max. # characters in ID name #define MAXID_P1 32 // EPANET max characters in ID name PLUS 1
#define MAXMSG_P1 80 // EPANET max characters in message text PLUS 1
#define NELEMENTTYPES 5 // Number of element types #define NELEMENTTYPES 5 // Number of element types
#define NENERGYRESULTS 6 // Number of energy results #define NENERGYRESULTS 6 // Number of energy results
@@ -303,6 +304,8 @@ int DLLEXPORT ENR_getUnits(ENR_Handle p_handle, ENR_Units code, int* unitFlag)
*/ */
{ {
int errorcode = 0; int errorcode = 0;
F_OFF offset;
char temp[MAXID_P1];
data_t* p_data; data_t* p_data;
*unitFlag = -1; *unitFlag = -1;
@@ -315,15 +318,37 @@ int DLLEXPORT ENR_getUnits(ENR_Handle p_handle, ENR_Units code, int* unitFlag)
switch (code) switch (code)
{ {
case ENR_flowUnits: case ENR_flowUnits:
fseek(p_data->file, 9*WORDSIZE, SEEK_SET); _fseek(p_data->file, 9*WORDSIZE, SEEK_SET);
fread(unitFlag, WORDSIZE, 1, p_data->file); fread(unitFlag, WORDSIZE, 1, p_data->file);
break; break;
case ENR_pressUnits: case ENR_pressUnits:
fseek(p_data->file, 10*WORDSIZE, SEEK_SET); _fseek(p_data->file, 10*WORDSIZE, SEEK_SET);
fread(unitFlag, WORDSIZE, 1, p_data->file); fread(unitFlag, WORDSIZE, 1, p_data->file);
break; break;
case ENR_qualUnits:
offset = 7*WORDSIZE;
_fseek(p_data->file, offset, SEEK_SET);
fread(unitFlag, WORDSIZE, 1, p_data->file);
if (*unitFlag == 0) *unitFlag = ENR_NONE;
else if (*unitFlag == 1) {
offset = 15*WORDSIZE + 3*MAXMSG_P1 + 2*(MAXFNAME+1) + MAXID_P1;
_fseek(p_data->file, offset, SEEK_SET);
fread(temp, MAXID_P1, 1, p_data->file);
if (!strcmp(temp, "mg/L")) *unitFlag = ENR_MGL;
else *unitFlag = ENR_UGL;
}
else if (*unitFlag == 2) *unitFlag = ENR_HOURS;
else *unitFlag = ENR_PRCNT;
break;
default: errorcode = 421; default: errorcode = 421;
} }
} }
@@ -378,6 +403,12 @@ int DLLEXPORT ENR_getTimes(ENR_Handle p_handle, ENR_Time code, int* time)
return set_error(p_data->error_handle, errorcode); return set_error(p_data->error_handle, errorcode);
} }
int DLLEXPORT ENR_getChemData(ENR_Handle p_handle, char** name, int* length)
{
return 0;
}
int DLLEXPORT ENR_getElementName(ENR_Handle p_handle, ENR_ElementType type, int DLLEXPORT ENR_getElementName(ENR_Handle p_handle, ENR_ElementType type,
int elementIndex, char** name, int* length) int elementIndex, char** name, int* length)
/*------------------------------------------------------------------------ /*------------------------------------------------------------------------
@@ -815,7 +846,7 @@ void errorLookup(int errcode, char* dest_msg, int dest_len)
default: msg = ERRERR; default: msg = ERRERR;
} }
strncpy(dest_msg, msg, MAXMSG); strncpy(dest_msg, msg, MSG_MAXLEN);
} }
int validateFile(ENR_Handle p_handle) int validateFile(ENR_Handle p_handle)

View File

@@ -10,7 +10,7 @@
#ifndef MESSAGES_H_ #ifndef MESSAGES_H_
#define MESSAGES_H_ #define MESSAGES_H_
/*------------------- Error Messages --------------------*/ /*------------------- Error Messages --------------------*/
#define MAXMSG 53 #define MSG_MAXLEN 53
#define WARN10 "Warning: model run issued warnings" #define WARN10 "Warning: model run issued warnings"

View File

@@ -1,102 +0,0 @@
#
# epanet_output_test.py
#
# Created: 11/8/2017
# Author: Michael E. Tryby
# US EPA - ORD/NRMRL
#
# Unit testing for EPANET Output API using pytest.
#
import pytest
import numpy as np
import epanet_output as oapi
from data import OUTPUT_FILE_EXAMPLE1
@pytest.fixture()
def enr_handle(request):
_handle = oapi.enr_init()
oapi.enr_open(_handle, OUTPUT_FILE_EXAMPLE1)
def enr_close():
oapi.enr_close()
request.addfinalizer(enr_close)
return _handle
def test_get_times(enr_handle):
num_periods = oapi.enr_get_times(enr_handle, oapi.Time.NUM_PERIODS)
assert num_periods == 25
# def test_get_size(file_path):
# handle = oapi.enr_init()
# oapi.enr_open(handle, file_path)
#
# size = oapi.enr_get_net_size(handle)
#
# print(size)
#
# handle = oapi.enr_close()
#
# def test_get_names(file_path):
# handle = oapi.enr_init()
# oapi.enr_open(handle, file_path)
#
# name = oapi.enr_get_element_name(handle, oapi.ElementType.NODE, 10)
#
# print(name)
#
# handle = oapi.enr_close()
#
# def test_get_energy(file_path):
# handle = oapi.enr_init()
# oapi.enr_open(handle, file_path)
#
# result = oapi.enr_get_energy_usage(handle, 1)
#
# print(result)
#
# handle = oapi.enr_close()
#
# def test_get_react(file_path):
# handle = oapi.enr_init()
# oapi.enr_open(handle, file_path)
#
# result = oapi.enr_get_net_reacts(handle)
#
# print(result)
#
# handle = oapi.enr_close()
#
def test_get_node_attribute(enr_handle):
ref_array = np.array([ 1., 0.44407997, 0.43766347, 0.42827705, 0.41342604,
0.42804748, 0.44152543, 0.40502965, 0.38635802, 1., 0.96745253])
array = oapi.enr_get_node_attribute(enr_handle, 1, oapi.NodeAttribute.QUALITY)
assert len(array) == 11
assert np.allclose(array, ref_array)
def test_get_link_attribute(enr_handle):
ref_array = np.array([ 1848.58117676, 1220.42736816, 130.11161804,
187.68930054, 119.88839722, 40.46448898, -748.58111572, 478.15377808,
191.73458862, 30.11160851, 140.4644928, 59.53551483, 1848.58117676])
array = oapi.enr_get_link_attribute(enr_handle, 1, oapi.LinkAttribute.FLOW)
assert len(array) == 13
assert np.allclose(array, ref_array)
# if __name__ == "__main__":
#
# file_path = "M:\\net mydocuments\\EPA Projects\\EPAnet Examples\\net1.out"
# test_get_times(file_path)
# test_get_size(file_path)
# test_get_names(file_path)
# test_get_energy(file_path)
# test_get_react(file_path)
# test_get_node_attribute(file_path)
# test_get_link_attribute(file_path)
#

View File

@@ -18,12 +18,12 @@ setlocal
set NRTEST_SCRIPT_PATH=%~1 set NRTEST_SCRIPT_PATH=%~1
set TEST_SUITE_PATH=%~2 set TEST_SUITE_PATH=%~2
set BENCHMARK_VER=220dev1 set BENCHMARK_VER=220dev2
set NRTEST_EXECUTE_CMD=python %NRTEST_SCRIPT_PATH%\nrtest execute set NRTEST_EXECUTE_CMD=python %NRTEST_SCRIPT_PATH%\nrtest execute
set TEST_APP_PATH=apps\epanet-%3.json set TEST_APP_PATH=apps\epanet-%3.json
set TESTS=tests\examples tests\exeter tests\large tests\network_one tests\small tests\tanks tests\valves set TESTS=tests\examples tests\exeter tests\large tests\network_one tests\press_depend tests\small tests\tanks tests\valves
set TEST_OUTPUT_PATH=benchmark\epanet-%3 set TEST_OUTPUT_PATH=benchmark\epanet-%3
set NRTEST_COMPARE_CMD=python %NRTEST_SCRIPT_PATH%\nrtest compare set NRTEST_COMPARE_CMD=python %NRTEST_SCRIPT_PATH%\nrtest compare

View File

@@ -21,9 +21,9 @@ Find /i "x86" < checkOS.tmp > StringCheck.tmp
If %ERRORLEVEL% == 1 ( If %ERRORLEVEL% == 1 (
CALL "%SDK_PATH%bin\"SetEnv.cmd /x64 /release CALL "%SDK_PATH%bin\"SetEnv.cmd /x64 /release
rem : create EPANET2.DLL rem : create EPANET2.DLL
cl -o epanet2.dll epanet.c hash.c hydraul.c hydcoeffs.c hydsolver.c inpfile.c input1.c input2.c input3.c mempool.c output.c quality.c report.c rules.c smatrix.c genmmd.c /I ..\include /I ..\run /link /DLL cl -o epanet2.dll epanet.c util\errormanager.c hash.c hydraul.c hydcoeffs.c hydstatus.c hydsolver.c inpfile.c input1.c input2.c input3.c mempool.c output.c quality.c report.c rules.c smatrix.c genmmd.c /I ..\include /I ..\run /link /DLL
rem : create EPANET2.EXE rem : create EPANET2.EXE
cl -o epanet2.exe epanet.c ..\run\main.c hash.c hydraul.c hydcoeffs.c hydsolver.c inpfile.c input1.c input2.c input3.c mempool.c output.c quality.c report.c rules.c smatrix.c genmmd.c /I ..\include /I ..\run /I ..\src /link cl -o epanet2.exe epanet.c util\errormanager.c ..\run\main.c hash.c hydraul.c hydcoeffs.c hydstatus.c hydsolver.c inpfile.c input1.c input2.c input3.c mempool.c output.c quality.c report.c rules.c smatrix.c genmmd.c /I ..\include /I ..\run /I ..\src /link
md "%Build_PATH%"\64bit md "%Build_PATH%"\64bit
move /y "%SRC_PATH%"\*.dll "%Build_PATH%"\64bit move /y "%SRC_PATH%"\*.dll "%Build_PATH%"\64bit
move /y "%SRC_PATH%"\*.exe "%Build_PATH%"\64bit move /y "%SRC_PATH%"\*.exe "%Build_PATH%"\64bit
@@ -35,9 +35,9 @@ rem : 32 bit with DEF
CALL "%SDK_PATH%bin\"SetEnv.cmd /x86 /release CALL "%SDK_PATH%bin\"SetEnv.cmd /x86 /release
echo "32 bit with epanet2.def mapping" echo "32 bit with epanet2.def mapping"
rem : create EPANET2.DLL rem : create EPANET2.DLL
cl -o epanet2.dll epanet.c hash.c hydraul.c hydcoeffs.c hydsolver.c inpfile.c input1.c input2.c input3.c mempool.c output.c quality.c report.c rules.c smatrix.c genmmd.c /I ..\include /I ..\run /link /DLL /def:..\win_build\WinSDK\epanet2.def /MAP cl -o epanet2.dll epanet.c util\errormanager.c hash.c hydraul.c hydcoeffs.c hydstatus.c hydsolver.c inpfile.c input1.c input2.c input3.c mempool.c output.c quality.c report.c rules.c smatrix.c genmmd.c /I ..\include /I ..\run /link /DLL /def:..\win_build\WinSDK\epanet2.def /MAP
rem : create EPANET2.EXE rem : create EPANET2.EXE
cl -o epanet2.exe epanet.c ..\run\main.c hash.c hydraul.c hydcoeffs.c hydsolver.c inpfile.c input1.c input2.c input3.c mempool.c output.c quality.c report.c rules.c smatrix.c genmmd.c /I ..\include /I ..\run /I ..\src /link cl -o epanet2.exe epanet.c util\errormanager.c ..\run\main.c hash.c hydraul.c hydcoeffs.c hydstatus.c hydsolver.c inpfile.c input1.c input2.c input3.c mempool.c output.c quality.c report.c rules.c smatrix.c genmmd.c /I ..\include /I ..\run /I ..\src /link
md "%Build_PATH%"\32bit md "%Build_PATH%"\32bit
move /y "%SRC_PATH%"\*.dll "%Build_PATH%"\32bit move /y "%SRC_PATH%"\*.dll "%Build_PATH%"\32bit
move /y "%SRC_PATH%"\*.exe "%Build_PATH%"\32bit move /y "%SRC_PATH%"\*.exe "%Build_PATH%"\32bit
@@ -51,4 +51,3 @@ del "%SRC_PATH%"\*.map
del "%SRC_PATH%"\*.tmp del "%SRC_PATH%"\*.tmp
cd "%Build_PATH%" cd "%Build_PATH%"

View File

@@ -93,4 +93,7 @@ EXPORTS
ENdeletelink = _ENdeletelink@4 ENdeletelink = _ENdeletelink@4
ENdeletenode = _ENdeletenode@4 ENdeletenode = _ENdeletenode@4
ENsetlinktype = _ENsetlinktype@8 ENsetlinktype = _ENsetlinktype@8
ENgetcurvetype = _ENgetcurvetype@8 ENgetdemandmodel = _ENgetdemandmodel@16
ENsetdemandmodel = _ENsetdemandmodel@16
ENgetcurvetype = _ENgetcurvetype@8