# Dynamically coupling system dynamics and SWAT+ models using Tinamit: application of modular tools for coupled human-water system models

Joel Z Harms, Julien J Malard-Adam, Jan F Adamowski, Ashutosh Sharma, Albert Nkwasa

► To cite this version:

Joel Z Harms, Julien J Malard-Adam, Jan F Adamowski, Ashutosh Sharma, Albert Nkwasa. Dynamically coupling system dynamics and SWAT+ models using Tinamit: application of modular tools for coupled human-water system models. Hydrology and Earth System Sciences, 2023, 27 (8), pp.1683-1693. 10.5194/hess-27-1683-2023. hal-04114972

HAL Id: hal-04114972

https://hal.inrae.fr/hal-04114972

Submitted on 2 Jun 2023

HAL is a multi-disciplinary open access
archive for the deposit and dissemination of sci-
entific research documents, whether they are pub-
lished or not. The documents may come from
teaching and research institutions in France or
abroad, or from public or private research centers.

L'archive ouverte pluridisciplinaire HAL, est
destinée au dépôt et à la diffusion de documents
scientifiques de niveau recherche, publiés ou non,
émanant des établissements d'enseignement et de
recherche français ou étrangers, des laboratoires
publics ou privés.

<figure><img src="image_1.png" /></figure>

Distributed under a Creative Commons Attribution 4.0 International License
# Dynamically coupling system dynamics and SWAT+ models using Tinamit: application of modular tools for coupled human-water system models

Joel Z. Harms<fnref n="1" />, Julien J. Malard-Adam<fnref n="1" />,<fnref n="2" />, Jan F. Adamowski<fnref n="1" />, Ashutosh Sharma<fnref n="3" />, and Albert Nkwasa<fnref n="4" />

**Correspondence:** Joel Z. Harms (joel.harms@mail.mcgill.ca)

Received: 28 August 2022 – Discussion started: 30 September 2022

Revised: 10 February 2023 – Accepted: 21 February 2023 – Published: 25 April 2023

**Abstract.** Participatory water resource management requires modeling techniques that are accurate and flexible yet stakeholder-friendly. While different modeling frameworks offer advantages and disadvantages, system dynamics (SDs) models have seen sustained use as a stakeholder-friendly approach for participatory water resource modeling. Physically based models (e.g., SWAT+) have seen sustained use to model the hydrological components of water systems. Proposed as a way to combine the relative strengths of both modeling paradigms, model coupling allows researchers to, for example, build participatory SD models with stakeholders, while delegating the hydrological components of the overall model to an external hydrological model. Recently developed to facilitate model coupling, the Tinamit Python package presents an extensible, outward-facing application programming interface (API). It allows for the development of extensions (wrappers) that expand compatibility with different physically based models. However, no watershed hydrological model has yet been connected to this API. In the present study, a socket and JavaScript Object Notation (JSON)-based communication protocol was developed with the goal of facilitating the coupling of models written in languages such as Fortran. This novel protocol served to develop a Tinamit-compatible wrapper for the hydrological model SWAT+, allowing it to be coupled to human-water SD models. The novel coupling protocol was then applied to a case study of Tanzania's Usa river catchment. This approach provides the modeler with the benefits of both physically based and

SD models, thereby allowing the detection of potentially far-reaching effects of policy-makers' decisions.

## 1 Introduction

Given the worldwide threat to hydroecological systems from both natural and anthropogenic causes (Pahl-Wostl et al., 2013; Smith, 2003), accurate and holistic modeling of the long-term consequences of water resource management (WRM) decisions is a pressing need. To capture the complexity of WRM stakeholder issues in models, approaches that integrate physical and socioeconomic components are necessary (Jakeman and Letcher, 2003). Integrated WRM models are termed human-water models (Jeong and Adamowski, 2016). Considered an important and beneficial practice in current human-water modeling, participatory model building (PMB) is often employed in creating such models (Butler and Adamowski, 2015; Halbe et al., 2014; Silgram et al., 2009; Zellner, 2008).

A stakeholder-friendly approach for water resource modeling, system dynamics (SDs) modeling, is a commonly applied PMB tool. By visually representing aspects of system complexity that would otherwise be difficult to convey, this approach can improve both stakeholders' and policy-makers' access to valuable information (Butler and Adamowski, 2015; Prodanovic and Simonovic, 2010). Having seen extensive use in integrated WRM (e.g., Fernández and Selma,

<footnote n="1">¹Department of Bioresource Engineering, McGill University, Sainte-Anne-de-Bellevue H9X 3V9, Canada</footnote>

<footnote n="2">²Institut de recherche pour le développement (IRD), UMR G-EAU, Université de Montpellier, Montpellier 34000, France</footnote>

<footnote n="3">³Department of Hydrology, Indian Institute of Technology Roorkee, Uttarakhand 247667, India</footnote>

<footnote n="4">⁴Hydrology and Hydraulic Engineering Department, Vrije Universiteit Brussel (VUB), 1050 Brussels, Belgium</footnote>
2004; Guo et al., 2001; Hassanzadeh et al., 2014; Jeong and Adamowski, 2016; Kelly (Letcher) et al., 2013; Qin et al., 2011; Saysel et al., 2002; Schlüter et al., 2019; Yeh et al., 2006), SD models were initially developed for the simulation of social systems in the context of industrial management. These models are often used to model complex nonlinear systems (Forrester, 1997; Sušnik et al., 2012). Existing SD models for WRM involve the integration of hydrological and socioeconomic processes (Langsdale et al., 2009; Sušnik et al., 2012); however, the simulation of physical system processes is not easily achieved (Malard et al., 2017), and such models' representation of hydrological processes remains a lengthy and site-specific process (Vamvakeridou-Lyroudia et al., 2008). Moreover, SD models lack the ability to easily incorporate spatial data and handle a system's spatial variability (Nikolic and Simonovic, 2015; Sušnik et al., 2012). Accordingly, hydrological components are often simplified (Prodanovic and Simonovic, 2007). Nikolic and Simonovic (2015) therefore argued that a specialized hydrological model is a necessity in integrated WRM modeling frameworks.

Specialized hydrological models generally provide hydrological variable values of interest to the WRM modeler with greater ease than a SD hydrological model. This discrepancy in efficiency occurs because, given the necessary geological and hydrological variables, functions describing key hydrological processes pre-imbedded in hydrological models can automatically calculate the magnitude of such processes for any watershed. The Soil and Water Assessment Tool (SWAT; Bieger et al., 2017; Nkwasa et al., 2020; R. Douglas-Mankin et al., 2010; Tuppad et al., 2011), a well-known, specialized, and widely applied hydrological model, was developed to help water resource managers determine water quantity and quality in watersheds and river basins (Arnold et al., 1998). SWAT has been recently succeeded by SWAT+, which offers greater flexibility and overall capacities (Bieger et al., 2017). The capacities offered by hydrological models like SWAT or SWAT+, and the suitability of SD models for socioeconomic modeling, suggest that an improved WRM modeling framework could be achieved by coupling of these two model types.

Attempts to expand SWAT's capacities, through coupling with other models or applications, have been limited to expanding its scope, fidelity, or robustness in modeling various physical processes but has yet to include the socioeconomic or participatory aspects of WRM (see D. Betrie et al., 2011; Yang et al., 2011). Perhaps due to the briefness of its existence, there is as yet no report of SWAT+ having been coupled with other models. However, other hydrological models have been coupled to SD models, e.g., the Upper Thames Systems Model (Gregersen et al., 2007). In these cases, coupling was achieved through translation of the constituent models into a single program. However, its specificity limited its application to a single watershed.

Coupling may also be achieved through the potentially more flexible file-based (Inam et al., 2017), scripting (Peck et al., 2014), or wrapper-based approaches (Gregersen et al., 2007). Malard et al. (2017) provide a review of current model coupling approaches, and examples of standards for wrapping are provided by Salas et al. (2020). In the present study, a wrapper approach was employed, since it is minimally invasive to the model itself (Gregersen et al., 2007) and was expected to offer maximum flexibility. However, wrapper approaches require a way of passing information between the two different models at runtime, an accomplishment that becomes particularly complicated when the two models are written in different programming languages and must therefore run as separate processes on the computer. Inter-process communication in wrapping can be achieved through a pipe-based approach (e.g., Open Modeling Interface or OpenMI; Gregersen et al., 2007); however, socket-based approaches are another option (Bulatewicz et al., 2013). The latter approach is quite novel for this application and could provide potential benefits, e.g., shorter execution time (see Sect. 2).

Most existing wrapping approaches have not been or cannot be used to couple SD models. However, automatic SD model wrapping with external physically based models may be achieved through the Tinamit API (Malard et al., 2017). In this process, a physically based model wrapper is developed only once for every physically based model platform; thereafter, a few lines of code allow any model built upon the same platform to be coupled with any other SD model. Tinamit has been previously applied to the evaluation of policy-makers' decisions for salinity management in Pakistan, using a coupled SahysMod and SD model (Malard et al., 2017), and for agricultural management in predominantly indigenous rural communities in Guatemala, by coupling SD models and the Python Crop Simulation Environment (PCSE; de Wit, 2022; Malard et al., 2020, 2023). However, Tinamit has not yet been applied to coupling an SD model with a hydrological model (e.g., SWAT+) and, thereby, facilitating the integrated modeling of coupled human-water systems. The concept of using Tinamit to couple SD and hydrological models has been presented; however, details of these earlier conceptualizations were mostly changed in the process of development (Harms et al., 2020, 2021). The present paper will present (i) the development of a sockets and JavaScript Object Notation (JSON)-based data exchange Python package and its C/Fortran counterpart in SWAT+, (ii) the creation of a SWAT+ wrapper, using the functionality of the Tinamit API and the data exchange Python package, to allow SWAT+ models to be automatically coupled to SD models, and (iii) the coupling and application of a SWAT+ and a human-water SD model to holistically evaluate policy-makers' decisions and their potentially far-reaching effects in the Usa river catchment, Tanzania, based on a SWAT+ model provided by Nkwasa et al. (2020).
## 2 Methodology

A Tinamit (2.0.3)-compatible SWAT+ wrapper was created using the following steps:

1. A Python package (labeled "tinamit-idm") employing socket functionality and including a generic JSON protocol was developed to serve as the basis for data exchange between Tinamit wrappers and the SWAT+ model engine (Malard and Harms, 2022; Python 3).

2. The SWAT+ engine was modified by adding C language sockets, thereby allowing communication via the JSON protocol used by tinamit-idm (Harms and Malard, 2022a; Fortran, C).

3. A SWAT+ wrapper was created using Tinamit 2.0.3 and tinamit-idm (Harms and Malard, 2022b; Python 3).

4. The case study model was coupled (Harms and Malard, 2022b; Python 3).

A socket-based approach was chosen for the inter-process communication between the models instead of a pipe-and-filter-based approach (e.g., the OpenMI standard; Gregersen et al., 2007; Bulatewicz et al., 2013). The socket-based approach was expected to save execution time, since no files are written to disk. A further advantage of our approach was that the JSON protocol used here virtually eliminated the need for language inter-operability. Almost any programming language (see JSON, n.d.) can simply create and parse JSON messages (ECMA, 2017). A conceptual overview of a complete coupled model and its parts is presented in Fig. 1.

### 2.1 tinamit-idm

A generic socket-based Python package was developed to provide basic functions that any models interchanging information during runtime might require (Malard and Harms, 2022). The functions "cambiar", "recibir", "incrementar", "finalizar", and "cerrar" define how to provide data, receive data, increment the model by a certain number of time steps, finalize the model, and close the model, respectively. The JSON protocol was of critical importance for these functions. Five distinct types of JSON message types were defined, corresponding mostly to the key functions provided by tinamit-idm. The definition of this JSON protocol was kept as general as possible to give it the necessary flexibility to be implemented as a standard for all socket-based inter-model communication using tinamit-idm and Tinamit. The JSON messages are detailed in Table 1. Keywords and variable names for the tinamit-idm code are written in Spanish. This is done to keep inter-operability with the existing Tinamit code, as tinamit-idm will be added to the next version of Tinamit. Code for the SWAT+ modifications are kept mostly in English, except for the parts needing to interface with tinamit-idm, to keep easy usability for SWAT+ users that are used to English-based code.

### 2.2 Modification of SWAT+

To give SWAT+ the ability to exchange data via sockets, SWAT+ was modified as follows (Harms and Malard, 2022a).

Argument handling was initially added so that one might specify whether SWAT+ was to be executed alone or connected to Tinamit. Arguments can be added to the command line call of the swatplus.exe file; the execution file can be called with the command "swatplus [port] [host]" (where "port" specifies the port to which SWAT+ should connect and "host" specifies the host IP, usually 127.0.0.1). One may still call "swatplus" to run only the SWAT+ model by itself.

Second, a Fortran module implementing the methods required for communication with the tinamit-idm package was added. This module was named the "tinamit_module" and is called mainly from the "time_control" module that manages SWAT+'s main simulation loop. The tinamit_module gives SWAT+ the ability to pause, receive messages from, and send messages to other models coupled via Tinamit. Furthermore, a mechanism is implemented here that allows SWAT+ to run as many time steps as the coupling code specifies before re-communicating with the Tinamit wrappers. This alleviates the need to unnecessarily pause the simulation of SWAT+ after every time step to communicate with Tinamit and allows for a more efficient execution of the simulation, depending on the data exchange interval chosen by the modeler. It also allows Tinamit to balance the varying time step lengths of the different models. The tinamit_module makes use of a C file ("socket.c"), which provides it with socket creation and reading and sending functions (hereafter referred to as the C client). The sub-processes and functions defined in the tinamit_module and the C client, in addition to the workflow between them, are illustrated in Fig. 2.

The SWAT+ model execution and socket client are initiated by the main routine. Later, "update_tinamit" is called from within the time_control subroutine at the first time step and thereafter at every specified interval. One "get-message" or Mensaje Cambiar is sent per connected variable (by the wrapper), so the get_and_send loop will be repeated until all requested current variable values have been sent to the wrapper. Then, after the connected model (in this case the SD model) is run for a time step, the set loop will be performed until updated variable values have been received (for those variables that are specified as inputs to the SWAT+ wrapper). Thereafter, the Mensaje Incrementar or "advance-message" is sent to continue the model execution for a specified number of time steps, and the process repeats until SWAT+'s time_control function is completed. Finally, update_tinamit is called by the main routine as part of the closing sequence, at which time the Mensaje Cerrar or "closing-message" will be sent to close the socket and end the run. Only standard, anticipated, or recommended behavior is shown, as it is defined within the wrapper (see Sect. 2.3). However, the sequence of messages could be altered, such as closing the client during
<figure><img src="image_2.png" /><figcaption>**Figure 1.** A schematic summary of the coupling process using the pre-existing Tinamit API and the newly developed tinamit-idm Python package. This schematic is adapted and modified from Harms et al. (2020, 2021).</figcaption></figure>

<figure><img src="image_3.png" /><figcaption>**Figure 2.** Graphic representation of the expected SWAT+ model behavior and communication with the wrapper during coupled model execution. The set loop is shown in gray, the “get_and_send” loop is shown in purple, the incrementation pathway, which informs the model engine to run for a specified number of time steps, is shown in green, and the closing sequence is in black. All other pathways of information and function calls, including those used for multiple abovementioned pathways, are shown in cyan.</figcaption></figure>

the run. This may be specified by users, according to their needs, should they decide to create their own wrapper.

## 2.3 Creation of the SWAT+ wrapper

A SWAT+ wrapper was created using the Tinamit and the tinamit-idm packages (Harms and Malard, 2022b). This wrapper is openly available on GitHub, as are the other source codes for the work mentioned in this paper. Since SWAT+ is a physically based model, a subclass of the Tinamit wrapper class "ModeloBF" class was created, called "ModeloSWATPlus". The following methods were defined for the ModeloSWATPlus subclass:

1. `__init__()` creates an instance of the ModeloSWATPlus and initializes the socket connection in addition to the model variables.

2. `unidad_tiempo()` returns the unit of time of the model for SWAT+. This was set to occur daily.

3. `iniciar_modelo()` defines how the wrapped SWAT+ model will be called to start running, sets up a working directory for the model, and ensures that the other requirements for data exchange are met.
<table><caption>**Table 1.** Presentation of the generic JSON protocol. The context and order of these messages is more clearly illustrated in Fig. 1.</caption><thead><tr><th>Message type</th><th>JSON key</th><th>Values</th><th>Description</th></tr></thead><tbody><tr><td>Mensaje cambiar</td><td></td><td></td><td>This message, sent by the cambiar function, tells the model to receive some variable's current values and is followed by the variable value.</td></tr><tr><td></td><td>"tipo"</td><td>"cambiar"</td><td>Specifies the type of command</td></tr><tr><td></td><td>"tamaño"</td><td>[integer]</td><td>Holds the length of the array buffer of the variable value</td></tr><tr><td></td><td>"var"</td><td>[name string]</td><td>Holds the name string of the variable to be received</td></tr><tr><td></td><td>"tipo_cont"</td><td>[data type string]</td><td>Holds the string of the data type of the variable values</td></tr><tr><td></td><td>"forma"</td><td>[array shape string]</td><td>Holds the shape string of the array of the variable values</td></tr><tr><td></td><td>"precisión"</td><td>[integer]</td><td>Defines the number of decimal places that non-integer numerals may be rounded to</td></tr><tr><td>Mensaje Recibir</td><td></td><td></td><td>This message is sent by the recibir function; it asks the model to send the current value of a variable, and the model responds with a Mensaje Resultado.</td></tr><tr><td></td><td>"tipo"</td><td>"leer"</td><td>Specifies the type of command</td></tr><tr><td></td><td>"var"</td><td>[name string]</td><td>Holds the name of the variable that the model should send</td></tr><tr><td></td><td>"precisión"</td><td>[integer]</td><td>Defines the number of decimal places that non-integer numerals may be rounded to</td></tr><tr><td>Mensaje Resultado</td><td></td><td></td><td>This is the only message sent by the model itself; it is only sent in response to a Mensaje Recibir and is followed by the value of the expected variable.</td></tr><tr><td></td><td>"tamaño"</td><td>[integer]</td><td>Holds the length of the array buffer of the variable values</td></tr><tr><td></td><td>"tipo_cont"</td><td>[data type string]</td><td>Holds the string of the data type of the variable values</td></tr><tr><td></td><td>"forma"</td><td>[array shape string]</td><td>Holds the shape string of the array of the variable values</td></tr><tr><td>Mensaje Incrementar</td><td></td><td></td><td>This message is sent by both the finalizar and incrementar functions; incrementar asks the model to run for a specific amount of time or number of steps in its main loop, whereas finalizar asks the model to run to completion and not receive any further messages.</td></tr><tr><td></td><td>"tipo"</td><td>"incr"</td><td>Specifies the type of command</td></tr><tr><td></td><td>"n_pasos"</td><td>[integer]</td><td>This is the number of time steps the model should take before reporting back; in the case of finalizar, this number is 0 and indicates that the model should run to completion</td></tr><tr><td>Mensaje Cerrar</td><td></td><td></td><td>This message is sent by the cerrar function and signals to the model that the simulation is done and closes the connection.</td></tr><tr><td></td><td>"tipo"</td><td>cerrar</td><td>Specifies the type of command</td></tr></tbody></table>

4. incrementar() defines how the model will be advanced during its run and how data exchange with the model may occur after a simulation step.

5. paralelizable() defines whether SWAT+ can be paralleled in different Python threads, which it can be, if run using the wrapper.

6. cerrar() ends the model run and stops the model engine. In this case, it is also responsible for ending the connection between the model and the Tinamit wrapper.

7. instalado() checks whether a SWAT+.exe or engine is installed and specified.

Steps 1–7 must be implemented by any physically based model wrapper created in Tinamit (Malard et al., 2017). The
following three are convenience functions that the authors deemed useful for any SWAT+ model in general and more specifically for the case study model execution:

1. imprimir_usos_de_tierra() prints the land use types defined for the current project so that the user does not necessarily need to read the SWAT+ input files to know which land uses are identified by which numerical value.

2. deter_área_de_hrus() reads the SWAT+ input file "hru.con" to determine and store the size of all the specified hydrological response units (HRUs), which should not change during simulation and can therefore be cached.

3. agrupar_usos_del_suelo() allows the user to group land uses into specific land use types for simpler simulation of land use changes.

This wrapper is currently an independent project but will be integrated alongside tinamit-idm into the next major Tinamit version and will then be even easier to use. At the time of the writing, Tinamit 3.0.0 is still in development.

## 2.4 Case study

A case study was built using a SWAT+ model validated for Tanzania's Usa river catchment (Nkwasa et al., 2020) and a SD model developed by the authors. Details on the SWAT+ model setup and validation can be found in Nkwasa et al. (2020). To summarize, the SWAT+ model set up for the Usa river catchment (240 km²) mainly utilized local data, with a specific focus on agricultural practices in the basin. The model validation included leaf area index (LAI) and water balance components (evapotranspiration, surface runoff, and groundwater). The case study SD model was built to show potential far-reaching effects of a hypothetical nitrogen fertilizer subsidy on total agricultural land use and water quality in the basin. It is important to note that the case study and model parameterization were chosen as a generic example of the sociological and hydrological insights made possible by coupling SWAT+ with an SD model through our approach, which is the main scope of the paper. Extensive and participatory model development and calibration with stakeholders from the Usa river catchment would be needed to use the coupled model in actual policy design. As such, the results of the case study, as presented in this paper, should be understood as an example of potential unexpected policy impacts that may be detected by using SWAT+ and SD model coupling and not as prescriptive policy recommendations for the Usa river catchment.

Vensim (Eberlein and Peterson, 1992) was used to develop the SD portion of the model and the causal loop diagram of the overall coupled model. A diagram of the overall model (Fig. 3) shows that it consists of four main loops. Given the coupling, it is difficult to call these reinforcing or balancing

loops, since they could shift behaviors during model execution. Therefore, "r" and "b" were used to note which loops seemed likely to display reinforcing or balancing behaviors, respectively. The banana production (rBP) and corn production (rCP) loops were assumed to generally be reinforcing, since an increase in agricultural land would likely also lead to an increase in production of banana and corn crops. The cultivation area loops (corn cultivation area loop is bCCA; banana cultivation area loop is bBCA) acted as balancing loops, since an increase in agricultural land would lead to a greater need for inputs and therefore increase production cost. The strength of the balancing loops was modified by the hypothetical fertilizer subsidy, since the production cost per area would decrease, thereby lowering the effect of cultivation area on net income.

The SD model described here represents a very simplified view of how a policy, such as a hypothetical fertilizer subsidy, might affect water quality in the basin. The fictional fertilizer subsidy might be implemented to maintain agricultural activity in the Usa river catchment or to increase farmer income. The implementation of such a subsidy would lower the production cost by covering a portion of the input costs, which would, in turn, increase the net farmer income. The greater net farmer income would lead to an increase in the desired agricultural land, which, in turn, would increase the cultivation rate and turn more land into agricultural land. The value of agricultural land was then passed on to the SWAT+ model. The amount of agricultural land given by the SD model was compared to the total area of HRUs in the SWAT+ model used for agricultural land use types. At every time step, the wrapper made a calculation to determine whether it was necessary to switch the land use of any HRU of the SWAT+ model to better approximate the current extents of agricultural and non-agricultural lands. Although the corn and banana crops were the main contributors to the total agricultural land considered in the SD model, the Usa river catchment SWAT+ model in fact contained many different types of agricultural and non-agricultural land uses. To simplify the SD model, the land use types were assigned to two groups, namely agricultural or non-agricultural, using the "agrupar_usos_del_suelo" function mentioned in Sect. 2.3. When the land use of an HRU was to be changed, a land use was selected from the appropriate group and assigned to this HRU. The selection happened programmatically, favoring land uses with a high popularity in each group (see Nkwasa et al., 2020, for a complete list of land uses in the Usa SWAT+ model).

SWAT+ completed the main reinforcing loops (rBP and rCP) by returning the total basin-wide banana production and corn production, which were expected to increase with increasing area dedicated to agricultural land. Values for the banana cultivation area and corn cultivation area were also returned by the SWAT+ wrapper portion of the model. These were also expected to increase with an increasing expanse of agricultural lands. The inclusion of SWAT+ was of further
<figure><img src="image_4.png" /><figcaption>**Figure 3.** Representation of the case study model as a causal loop diagram. The main loops are represented in blue for the loops of banana production (rBP) and corn production (rCP), yellow for the loops of corn cultivation area (bCCA) and banana cultivation area (bBCA), and green for the overlapping parts of all loops. This figure is adapted and substantially modified from Harms et al. (2021).</figcaption></figure>

importance since SWAT+ provided the NO3-N concentration in channels, an indicator of water quality in this case study. This allowed an analysis of the risk to water quality degradation posed by the policies tested, i.e., 0% fertilizer subsidy (baseline scenario), 45% subsidy (subsidy scenario), and 90% subsidy (high-subsidy scenario). A total of 10 simulations were performed for each scenario.

We restate here that the values of the non-SWAT+ variables were chosen arbitrarily to illustrate processes that might occur in real-life situations. Many simplifying assumptions were applied, most importantly in only considering the production of corn and bananas, in addition to assuming a constant fertilizer cost per hectare of cultivated land.

The source code, in addition to the SD model used, are provided (see the code availability section at the end of the paper).

## 3 Results and discussion

The results of the coupled simulations are given in Fig. 4 and include the mean of 10 runs, along with the standard deviation. Variation arose between runs due to the land use change algorithm used in the wrapper. The land use type assigned to an HRU, where land use was changed, was chosen at random from a group of appropriate land uses (either non-agricultural or agricultural in this case), with a weighted probability that favors land uses already dominant in the watershed.

Increasing the subsidized fraction of nitrogen fertilizer achieved the goal of maintaining agricultural production in the area (Fig. 4). It not only stabilized but also reversed the decreasing trend encountered in the baseline (0% subsidy) scenario and increased the amount of agricultural land un-

der the 45% and 90% subsidy scenarios. By decreasing production costs, the subsidies encourage increased investment in agriculture, the conversion of more land, and eventually increased leaching through a socioeconomic pathway. This happens because the policy tilts the economic equilibrium point of optimal agricultural land towards more agricultural activity; the SWAT model then links this dynamic to environmental pollution through the increasing nitrate-nitrogen concentration in the channels of the basin. This relationship was easily explored through the coupling of the SWAT+ and SD variables. Generally, the water resource manager may obtain any hydrological value that SWAT+ calculates (such as river flow and nitrate nitrogen content, as used in this study), without developing any new algorithms for these processes. In this case study, hydrological variables are incorporated directly, through the nitrogen concentration variable, and indirectly, as SWAT+ uses hydrological variables internally to model the crop yield. This allows the researcher to focus on the development of the model to represent the socioeconomic relations in a participatory manner.

The model coupling approach shown here empowers researchers and policy-makers by giving them access to both an inclusive understanding of the system through participatory model building and the physical consequences of possible paths of action. More than that, it empowers stakeholders by allowing more focus on their involvement in decision-making. Furthermore, this approach works for any watershed in which a SWAT+ model can be created and, similarly, any SD model. Although the initial modification of SWAT+, the development of the server and client parts for inter-process communication, and the construction of a SWAT+ wrapper were tedious and lengthy endeavors, the ability to couple any SD model to any other SWAT+ model far outweighed
<figure><img src="image_5.png" /><figcaption>**Figure 4.** The results from the coupled models with 0%, 45%, and 90% subsidized fertilizer. In total, 10 runs were performed. The mean and standard deviation (shaded area) are plotted.</figcaption></figure>

the time and work required. This was demonstrated in earlier work with Tinamit (Malard et al., 2017, 2020, 2023). Through this method, the researchers were able to focus on representing the socioeconomic processes in the watershed, or in potentially involving further stakeholders, without requiring a re-implementation of location-specific hydrological processes.

Additionally, since a generalized JSON protocol was used in concert with socket technology, inter-process communication was achieved between diverse languages (Python, Fortran, and C, in this case), without the need for writing and reading files to disk. Other coupling methods which have employed file- and pipe-based approaches (Gregersen et al., 2007; Inam et al., 2017) or translated the entire model into a single programming language (Prodanovic and Simonovic, 2010) have shown potential shortcomings, e.g., longer execution time, extensive implementation work, and a resultant lack of flexibility. Since no files were written or read during execution when the socket-based data exchange was in use, the model execution time was likely to benefit. This technology could furthermore be adapted to a multitude of other Fortran (or C)-based models without major modifications to the client part of the socket code (i.e., the socket.c file), as the C socket client is as generic as the JSON protocol used by tinamit-idm. The server code in tinamit-idm, especially in conjunction with Tinamit, lays the groundwork for developing wrappers for models written in any language that can interpret JSON and will simplify the development of other physically based model wrappers.

## 4 Limitations

Compared to OpenMI, Tinamit has neither the same status nor the history of use and trust and does not yet support a similar range of models. Therefore, the OpenMI standard may currently have an advantage when different physically based models are to be coupled for a project. However, Tinamit is unique in its ability to create wrappers for SD models, which are some of the most popular tools for integrated WRM models or, more broadly, participatory model building. Additionally, the work presented here is likely to improve the usefulness of Tinamit, not only through the possibility of easily integrating SWAT+ into a participatory WRM model but also because it provides standards, methodologies, and examples that simplify the addition of further models to Tinamit.

Currently, the SWAT+-coupling-capable version is only available for Linux systems, although Windows and MacOS versions are in development. During development, the Windows version of the socket code in the modified SWAT+ version created difficulties during compilation. These difficulties were exacerbated by differences between Windows sockets and C sockets. The MacOS version is nearing the end of its development, but at the time of writing, the Linux version of the modified SWAT+ was the only functional version available. However, all Python packages presented (i.e., Tinamit and tinamit-idm) are functional on all current major operating systems.

A selection of about 190 numerical-type SWAT+ variables have been made available for coupling, including some util-
ity functions and variables specific to the case study; however, there are likely functions and variables that other modelers might find useful to couple that have not been included. Therefore, we expect and encourage modelers to not only use but also collaboratively modify and improve the current codes and expand the number of supported variables and functionalities to their needs as we continue to do the same. This is possible since all code mentioned in this project is published in open-source repositories (see the code availability section at the end of the paper).

## 5 Conclusions

To make holistic decisions for human-water systems, both the socioeconomic and the physical systems need to be understood. Since different models and modeling platforms have different strengths, combining multiple models through coupling may provide a more complete modeling platform. Coupling processes can be difficult and coding intensive, so this study developed a simple approach specialized for participatory models based on Tinamit. The work presented in the present paper provides algorithms and functionalities, the tinamit-idm package, and a modified SWAT+ executable with socket functionality. These can function as templates for the development of future coupled Fortran models. The Fortran-compatible C client from the modified SWAT+ executable can potentially be applied to make any Fortran model much more easily coupled with Tinamit than it would be in this initial project. The use of sockets and the JSON protocol is a promising step, as it largely bypasses the need for language interoperability and potentially improves execution time compared to other model coupling platforms. Expansion of the abilities of Tinamit makes it more useful for participatory WRM and other participatory modeling work. In the case study presented here, the coupled model was able to portray the overall results of both the human, socioeconomic, and the physical resource systems at play with considerable ease. The modeler was able to obtain results for hydrological variables without having to define all the relationships manually in the SD model, thereby allowing a focus on representing socioeconomic processes. In closing, we hope that the code and technology presented in this paper will contribute to improving participatory WRM modeling work and make it easier to apply to real-world decision-making scenarios, while also providing developers with ideas and templates for the further development of Tinamit and other model coupling platforms.

**Code and data availability.** The source codes of the software presented in this paper, including the case study, are available. The currently archived versions are cited in the text (https://doi.org/10.5281/ZENODO.6902755, Harms and Malard, 2022a; https://doi.org/10.5281/ZENODO.7630281, Harms and Malard, 2022b; https://doi.org/10.5281/zenodo.6884988, Malard

and Harms, 2022), and any updated versions are available publicly on GitHub. The links to the GitHub repositories are as follows: tinamit-idm at https://github.com/joelz575/tinamit_idm (last access: 22 February 2023), SWAT+ (modified for Tinamit compatibility) at https://github.com/joelz575/swatplus (last access: 22 February 2023), and the SWAT+ wrapper and coupling example at https://github.com/joelz575/swatplus-tinamit-coupling (last access: 22 February 2023).

We do not have additional data to report, and the model files that are provided with the case study code contain all of the data that we used.

**Author contributions.** Conceptualization for this work was done by JJMA, JFA, and AS. The methodology was designed by JJMA and JFA. Funding was acquired by JZH, JJMA, and JFA. JFA administered the project, while supervision was carried out by JJMA and JFA. Software was developed by JZH and JJMA. AN provided modeling resources for the development of the case study. Code testing and validation was carried out by JZH, who was also responsible for the visualization of the work and the creation of the figures. The original draft was prepared by JZH, JJMA, and JFA, while all authors were engaged in the review and editing of the final draft.

**Competing interests.** The contact author has declared that none of the authors has any competing interests.

**Disclaimer.** Publisher's note: Copernicus Publications remains neutral with regard to jurisdictional claims in published maps and institutional affiliations.

**Acknowledgements.** This research has been supported in part by a National Sciences and Engineering Research Council of Canada (NSERC) Undergraduate Student Research Award (USRA), supplemented by the Fonds de recherche du Québec (FRQNT), held by Joel Z. Harms. This research has further been supported by a grant from NSERC held by Jan F. Adamowski. Ashutosh Sharma has been supported by the Shastri Indo-Canadian Institute (SICI) under the Shastri Research Student Fellowship (SRSF) scheme to carry out this research at McGill University.

**Financial support.** This research has been supported by the Fonds de recherche du Québec – Nature et technologies (grant no. 297038), the Natural Sciences and Engineering Research Council of Canada (USRA; grant no. 552014-2020), and the Natural Sciences and Engineering Research Council of Canada (NSERC; grant no. G219643 RGPIN-2020-05325).

**Review statement.** This paper was edited by Nadia Ursino and reviewed by two anonymous referees.
References

JSON: https://www.json.org/json-en.html, last access: 12 March 2022.

Arnold, J. G., Srinivasan, R., Muttiah, R. S., and Williams, J. R.: Large Area Hydrologic Modeling and Assessment Part I: Model Development1, J. Am. Water Resour. Assoc., 34, 73–89, https://doi.org/10.1111/j.1752-1688.1998.tb05961.x, 1998.

Betrie, G. D., van Griensven, A., Mohamed, Y. A., Popescu, I., Mynett, A. E., and Hummel, S.: Linking SWAT and SOBEK Using Open Modeling Interface (OpenMI) for Sediment Transport Simulation in the Blue Nile River Basin, Trans. ASABE, 54, 1749–1757, https://doi.org/10.13031/2013.39847, 2011.

Bieger, K., Arnold, J. G., Rathjens, H., White, M. J., Bosch, D. D., Allen, P. M., Volk, M., and Srinivasan, R.: Introduction to SWAT+, A Completely Restructured Version of the Soil and Water Assessment Tool, J. Am. Water Resour. Assoc., 53, 115–130, https://doi.org/10.1111/1752-1688.12482, 2017.

Bulatewicz, T., Allen, A., Peterson, J. M., Staggenborg, S., Welch, S. M., and Steward, D. R.: The Simple Script Wrapper for OpenMI: Enabling interdisciplinary modeling studies, Environ. Model. Softw., 39, 283–294, https://doi.org/10.1016/j.envsoft.2012.07.006, 2013.

Butler, C. and Adamowski, J.: Empowering marginalized communities in water resources management: Addressing inequitable practices in Participatory Model Building, J. Environ. Manage., 153, 153–162, https://doi.org/10.1016/j.jenvman.2015.02.010, 2015.

de Wit, A.: PCSE: The Python Crop Simulation Environment – Python Crop Simulation Environment 5.5 documentation, https://pcse.readthedocs.io/en/stable (last access: 22 March 2023), 2022.

Douglas-Mankin, K. R., Srinivasan, R., and Arnold, J.: Soil and Water Assessment Tool (SWAT) Model: Current Developments and Applications, Trans. ASABE, 53, 1423–1431, https://doi.org/10.13031/2013.34915, 2010.

Eberlein, R. L. and Peterson, D. W.: Understanding models with VensimTM, Eur. J. Oper. Res., 59, 216–219, https://doi.org/10.1016/0377-2217(92)90018-5, 1992.

ECMA: Standard ECMA-404 The JSON Data Interchange Syntax, Ecma International, Geneva, Switzerland, 2017.

Fernández, J. M. and Selma, M. A. E.: The dynamics of water scarcity on irrigated landscapes: Mazarrón and Aguilas in south-eastern Spain, Syst. Dyn. Rev., 20, 117–137, https://doi.org/10.1002/sdr.290, 2004.

Forrester, J. W.: Industrial Dynamics, J. Oper. Res. Soc., 48, 1037–1041, https://doi.org/10.1057/palgrave.jors.2600946, 1997.

Gregersen, J. B., Gijsbers, P. J. A., and Westen, S. J. P.: OpenMI: Open modelling interface, J. Hydroinformatics, 9, 175–191, https://doi.org/10.2166/hydro.2007.023, 2007.

Guo, H. C., Liu, L., Huang, G. H., Fuller, G. A., Zou, R., and Yin, Y. Y.: A system dynamics approach for regional environmental planning and management: A study for the Lake Erhai Basin, J. Environ. Manage., 61, 93–111, https://doi.org/10.1006/jema.2000.0400, 2001.

Halbe, J., Adamowski, J., M. Bennett, E., Pahl-Wostl, C., and Farahbakhsh, K.: Functional organization analysis for the design of sustainable engineering systems, Ecol. Eng., 73, 80–91, https://doi.org/10.1016/j.ecoleng.2014.08.011, 2014.

Harms, J. Z. and Malard, J. J.: joelz575/swatplus: None, Zenodo [code], https://doi.org/10.5281/ZENODO.6902755, 2022a.

Harms, J. Z. and Malard, J. J.: joelz575/swatplus-tinamit-coupling: SWAT+/SD Coupling Case-Study, Zenodo [code], https://doi.org/10.5281/ZENODO.7630281, 2022b.

Harms, J. Z., Malard, J. J., and Adamowski, J. F.: Coupling of socioeconomic system dynamic models with the SWAT+ hydrologic model for accessible Integrated Water Resource Management model development, https://doi.org/10.13140/RG.2.2.17397.04320, Undergraduate Student Research Award (USRA) Poster Presentations, McGill University, https://doi.org/10.13140/RG.2.2.17397.04320, 2020.

Harms, J. Z., Malard, J. J., and Adamowski, J. F.: Dynamic Coupling of SWAT+ with System Dynamics Models using Tinamit and a Socket Based Protocol, EGU General Assembly 2021, online, 19–30 Apr 2021, EGU21-6731, https://doi.org/10.5194/egusphere-egu21-6731, 2021.

Hassanzadeh, E., Elshorbagy, A., Wheater, H., and Gober, P.: Managing water in complex systems: An integrated water resources model for Saskatchewan, Canada, Environ. Model. Softw., 58, 12–26, https://doi.org/10.1016/j.envsoft.2014.03.015, 2014.

Inam, A., Adamowski, J., Prasher, S., Halbe, J., Malard, J., and Albano, R.: Coupling of a distributed stakeholder-built system dynamics socio-economic model with SAHYS-MOD for sustainable soil salinity management. Part 2: Model coupling and application, J. Hydrol., 551, 278–299, https://doi.org/10.1016/j.jhydrol.2017.03.040, 2017.

Jakeman, A. J. and Letcher, R. A.: Integrated assessment and modelling: features, principles and examples for catchment management, Appl. Comput. Res. Environ. Probl., 18, 491–501, https://doi.org/10.1016/S1364-8152(03)00024-0, 2003.

Jeong, H. and Adamowski, J.: A system dynamics based socio-hydrological model for agricultural wastewater reuse at the watershed scale, Agric. Water Manag., 171, 89–107, https://doi.org/10.1016/j.agwat.2016.03.019, 2016.

Kelly (Letcher), R. A., Jakeman, A. J., Barreteau, O., Borsuk, M. E., ElSawah, S., Hamilton, S. H., Henriksen, H. J., Kuikka, S., Maier, H. R., Rizzoli, A. E., van Delden, H., and Voinov, A. A.: Selecting among five common modelling approaches for integrated environmental assessment and management, Environ. Model. Softw., 47, 159–181, https://doi.org/10.1016/j.envsoft.2013.05.005, 2013.

Langsdale, S. M., Beall, A., Carmichael, J., Cohen, S. J., Forster, C. B., and Neale, T.: Exploring the Implications of Climate Change on Water Resources through Participatory Modeling: Case Study of the Okanagan Basin, British Columbia, J. Water Resour. Plan. Manag., 135, 373–381, https://doi.org/10.1061/(ASCE)0733-9496(2009)135:5(373), 2009.

Malard, J. J. and Harms, J. Z.: joelz575/tinamit_idm: tinamit-idm (git-hub-release), Zenodo [code], https://doi.org/10.5281/zenodo.6884988, 2022.

Malard, J. J., Inam, A., Hassanzadeh, E., Adamowski, J., Tuy, H. A., and Melgar-Quiñonez, H.: Development of a software tool for rapid, reproducible, and stakeholder-friendly dynamic coupling of system dynamics and physically-based models, Environ. Model. Softw., 96, 410–420, https://doi.org/10.1016/j.envsoft.2017.06.053, 2017.

Malard, J. J., Adamowski, J., Tuy, H., and Melgar-Quiñonez, H.: Couplage d'un modèle des dynamiques des systèmes avec un
modèle agricole: développement de politiques pour luter contre l'insécurité alimentaire face aux changements climatiques dans un système agricole Indigène à petite échelle au Tz'olöj Ya' (Guatemala), Manuscr. Submitt. Publ., 2020.

Malard, J. J., Adamowski, J., Tuy, H., and Melgar-Quiñonez, H.: Rukusaxi̱k ri k'utb'äl richin kisilonem nuk'ulem roma rutojtob'enik runuk'ulem rik'ilal chikiwäch rujaloj ruwäch q'ij pa Tz'olöj Ya' chuqa' pa K'iche', Iximulew, Eutopia, accepted, 2023.

Nikolic, V. V. and Simonovic, S. P.: Multi-method Modeling Framework for Support of Integrated Water Resources Management, Environ. Process., 2, 461–483, https://doi.org/10.1007/s40710-015-0082-6, 2015.

Nkwasa, A., Chawanda, C. J., Msigwa, A., Komakech, H. C., Verbeiren, B., and van Griensven, A.: How Can We Represent Seasonal Land Use Dynamics in SWAT and SWAT+ Models for African Cultivated Catchments?, Water, 12, 1541, https://doi.org/10.3390/w12061541, 2020.

Pahl-Wostl, C., Arthington, A., Bogardi, J., Bunn, S. E., Hoff, H., Lebel, L., Nikitina, E., Palmer, M., Poff, L. N., Richards, K., Schlüter, M., Schulze, R., St-Hilaire, A., Tharme, R., Tockner, K., and Tsegai, D.: Environmental flows and water governance: managing sustainable water uses, Curr. Opin. Environ. Sustain., 5, 341–351, https://doi.org/10.1016/j.cosust.2013.06.009, 2013.

Peck, A., Neuwirth, C., and Simonovic, S. P.: Coupling System Dynamics with Geographic Information Systems: CCAr Project Report, Department of Civil and Environmental Engineering, The University of Western Ontario, London, Ontario, Canada, 2014.

Prodanovic, P. and Simonovic, S. P.: Integrated Water Resources Modelling of the Upper Thames River Basin, in: 18th Canadian Hydrotechnical Conference (18ième congrès spécialisé hydrotechnique canadienne) Challenges for Water Resources Engineering in a Changing World, 18th Canadian Hydrotechnical Conference (18ième congrès spécialisé hydrotechnique canadienne), Winnipeg, Manitoba, 10, 2007.

Prodanovic, P. and Simonovic, S. P.: An Operational Model for Support of Integrated Watershed Management, Water Resour. Manag., 24, 1161–1194, https://doi.org/10.1007/s11269-009-9490-6, 2010.

Qin, H.-P., Su, Q., and Khu, S.-T.: An integrated model for water management in a rapidly urbanizing catchment, Environ. Model. Softw., 26, 1502–1514, https://doi.org/10.1016/j.envsoft.2011.07.003, 2011.

Salas, D., Liang, X., Navarro, M., Liang, Y., and Luna, D.: An open-data open-model framework for hydrological models' integration, evaluation and application, Environ. Model. Softw., 126, 104622, https://doi.org/10.1016/j.envsoft.2020.104622, 2020.

Saysel, A. K., Barlas, Y., and Yenigün, O.: Environmental sustainability in an agricultural development project: a system dynamics approach, J. Environ. Manage., 64, 247–260, https://doi.org/10.1006/jema.2001.0488, 2002.

Schlüter, M., Müller, B., and Frank, K.: The potential of models and modeling for social-ecological systems research: the reference frame ModSES, Ecol. Soc., 24, https://www.jstor.org/stable/26796919, 2019.

Silgram, M., Anthony, S. G., Collins, A. L., Strőmqvist, J., Bouraoui, F., Schoumans, O., Porto, A. L., Groenendijk, P., Arheimer, B., Mimikou, M., and Johnsson, H.: Evaluation of diffuse pollution model applications in EUROHARP catchments with limited data, J. Environ. Monit., 11, 554–571, https://doi.org/10.1039/B901181A, 2009.

Smith, V. H.: Eutrophication of freshwater and coastal marine ecosystems a global problem, Environ. Sci. Pollut. Res., 10, 126–139, https://doi.org/10.1065/espr2002.12.142, 2003.

Sušnik, J., Vamvakeridou-Lyroudia, L. S., Savić, D. A., and Kapelan, Z.: Integrated System Dynamics Modelling for water scarcity assessment: Case study of the Kairouan region, Sci. Total Environ., 440, 290–306, https://doi.org/10.1016/j.scitotenv.2012.05.085, 2012.

Tuppad, P., Douglas-Mankin, K. R., Lee, T., Srinivasan, R., and Arnold, J. G.: Soil and Water Assessment Tool (SWAT) Hydrologic/Water Quality Model: Extended Capability and Wider Adoption, Trans. ASABE, 54, 1677–1684, https://doi.org/10.13031/2013.39856, 2011.

Vamvakeridou-Lyroudia, L. S., Leduc, C., and Savic, D. A.: System Dynamics Modelling: the Merguellil Valley Water System, Centre for Water Systems, Univ. of Exeter, UK, https://emps.exeter.ac.uk/media/universityofexeter/emps/research/cws/downloads/SDM-Tunisia_Merguellil-Report.pdf (last access: 11 April 2023), 2008.

Yang, S., Dong, G., Zheng, D., Xiao, H., Gao, Y., and Lang, Y.: Coupling Xinanjiang model and SWAT to simulate agricultural non-point source pollution in Songtao watershed of Hainan, China, Ecol. Model., 222, 3701–3717, https://doi.org/10.1016/j.ecolmodel.2011.09.004, 2011.

Yeh, S.-C., Wang, C.-A., and Yu, H.-C.: Simulation of soil erosion and nutrient impact using an integrated system dynamics model in a watershed in Taiwan, Environ. Model. Softw., 21, 937–948, https://doi.org/10.1016/j.envsoft.2005.04.005, 2006.

Zellner, M. L.: Embracing Complexity and Uncertainty: The Potential of Agent-Based Modeling for Environmental Planning and Policy, Plan. Theory Pract., 9, 437–457, https://doi.org/10.1080/14649350802481470, 2008.