Compare commits

28 Commits

Author SHA1 Message Date
HorriblePerson555
f44bac9aab Add warnings for reactor child positioning and grid sizing discrepancies 2025-10-16 15:30:51 +02:00
1dc9cd0031 Add dispersion constraint 2025-10-14 12:48:43 +02:00
2a520be33b Refactor measurement position assignment and update grid position calculation in Reactor classes to align with new generalFunctions 2025-10-10 11:27:55 +02:00
baecf2f599 Functioning code, requires improved sequencing 2025-10-02 17:39:31 +02:00
cd3a19e66f Fix boundary conditions for advection 2025-10-02 13:48:47 +02:00
3aea0e55c4 Rewrite for improved boundary condition 2025-10-01 16:50:48 +02:00
d9511dc3c7 Implement simple BCs 2025-09-30 15:36:25 +02:00
993482f8c0 Deal with mulitple parents and set downstreamReactor for improved boundary conditions 2025-09-29 16:58:46 +02:00
5f4ebdc2af Fix reference error and improve child variable naming 2025-09-29 15:45:07 +02:00
6c79d0ef9b Use improved boundary conditions for upstream and downstream reactors 2025-09-29 15:34:54 +02:00
04306d0996 Fix measurement type string for oxygen in _updateMeasurement method 2025-09-29 09:40:17 +02:00
2bc244cae7 Refactor measurement update handling in Reactor_PFR class to include default case for measurement types 2025-09-26 16:36:09 +02:00
254f9eec5a Fix measurement event listener to use correct measurement reference 2025-09-26 16:33:00 +02:00
109fd182df Refactor measurement position handling in Reactor class 2025-09-26 14:51:18 +02:00
bf5f265a76 Update measurement handling in Reactor class and rename oxygen measurement type 2025-09-26 10:17:00 +02:00
905674ce58 Update dependencies and correct node name 2025-09-24 15:27:08 +02:00
da1cff55ba Resolve merge conflicts from migration 2025-09-22 16:40:22 +02:00
9147a3f7d0 Rename repo 2025-09-22 16:19:00 +02:00
ea35038aa1 Initial commit 2025-09-22 14:11:36 +00:00
8f64fbe4e5 Add time step configuration and input handling in advanced reactor 2025-09-22 15:17:25 +02:00
7a70f60655 Fix measurement event listener registration in Reactor class 2025-09-19 13:26:45 +02:00
223c4555b8 Fix measurement reference in child registration logic 2025-09-16 15:54:31 +02:00
972d33355e Formatting 2025-09-16 11:44:29 +02:00
94ea4fe76b Fix subclass function 2025-09-15 17:39:54 +02:00
f6b026928e Enhance measurement child registration and update measurement handling in Reactor class 2025-09-15 12:48:18 +02:00
c2cd29db56 Update generalFunctions dependency and enhance reactor child registration logic 2025-09-05 15:26:00 +02:00
0b49642668 Switch general functions to new implementation 2025-09-05 13:31:42 +02:00
a4a5266040 Update package-lock 2025-09-03 12:21:15 +02:00
8 changed files with 412 additions and 120 deletions

191
LICENSE
View File

@@ -1,9 +1,190 @@
MIT License EUROPEAN UNION PUBLIC LICENCE v. 1.2
EUPL © the European Union 2007, 2016
Copyright (c) 2025 p.vanderwilt This European Union Public Licence (the EUPL) applies to the Work (as defined below) which is provided under the
terms of this Licence. Any use of the Work, other than as authorised under this Licence is prohibited (to the extent such
use is covered by a right of the copyright holder of the Work).
The Work is provided under the terms of this Licence when the Licensor (as defined below) has placed the following
notice immediately following the copyright notice for the Work:
Licensed under the EUPL
or has expressed by any other means his willingness to license under the EUPL.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 1.Definitions
In this Licence, the following terms have the following meaning:
The Licence:this Licence.
The Original Work:the work or software distributed or communicated by the Licensor under this Licence, available
as Source Code and also as Executable Code as the case may be.
Derivative Works:the works or software that could be created by the Licensee, based upon the Original Work or
modifications thereof. This Licence does not define the extent of modification or dependence on the Original Work
required in order to classify a work as a Derivative Work; this extent is determined by copyright law applicable in
the country mentioned in Article 15.
The Work:the Original Work or its Derivative Works.
The Source Code:the human-readable form of the Work which is the most convenient for people to study and
modify.
The Executable Code:any code which has generally been compiled and which is meant to be interpreted by
a computer as a program.
The Licensor:the natural or legal person that distributes or communicates the Work under the Licence.
Contributor(s):any natural or legal person who modifies the Work under the Licence, or otherwise contributes to
the creation of a Derivative Work.
The Licensee or You:any natural or legal person who makes any usage of the Work under the terms of the
Licence.
Distribution or Communication:any act of selling, giving, lending, renting, distributing, communicating,
transmitting, or otherwise making available, online or offline, copies of the Work or providing access to its essential
functionalities at the disposal of any other natural or legal person.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 2.Scope of the rights granted by the Licence
The Licensor hereby grants You a worldwide, royalty-free, non-exclusive, sublicensable licence to do the following, for
the duration of copyright vested in the Original Work:
— use the Work in any circumstance and for all usage,
— reproduce the Work,
— modify the Work, and make Derivative Works based upon the Work,
— communicate to the public, including the right to make available or display the Work or copies thereof to the public
and perform publicly, as the case may be, the Work,
— distribute the Work or copies thereof,
— lend and rent the Work or copies thereof,
— sublicense rights in the Work or copies thereof.
Those rights can be exercised on any media, supports and formats, whether now known or later invented, as far as the
applicable law permits so.
In the countries where moral rights apply, the Licensor waives his right to exercise his moral right to the extent allowed
by law in order to make effective the licence of the economic rights here above listed.
The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to any patents held by the Licensor, to the
extent necessary to make use of the rights granted on the Work under this Licence.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 3.Communication of the Source Code
The Licensor may provide the Work either in its Source Code form, or as Executable Code. If the Work is provided as
Executable Code, the Licensor provides in addition a machine-readable copy of the Source Code of the Work along with
each copy of the Work that the Licensor distributes or indicates, in a notice following the copyright notice attached to
the Work, a repository where the Source Code is easily and freely accessible for as long as the Licensor continues to
distribute or communicate the Work.
4.Limitations on copyright
Nothing in this Licence is intended to deprive the Licensee of the benefits from any exception or limitation to the
exclusive rights of the rights owners in the Work, of the exhaustion of those rights or of other applicable limitations
thereto.
5.Obligations of the Licensee
The grant of the rights mentioned above is subject to some restrictions and obligations imposed on the Licensee. Those
obligations are the following:
Attribution right: The Licensee shall keep intact all copyright, patent or trademarks notices and all notices that refer to
the Licence and to the disclaimer of warranties. The Licensee must include a copy of such notices and a copy of the
Licence with every copy of the Work he/she distributes or communicates. The Licensee must cause any Derivative Work
to carry prominent notices stating that the Work has been modified and the date of modification.
Copyleft clause: If the Licensee distributes or communicates copies of the Original Works or Derivative Works, this
Distribution or Communication will be done under the terms of this Licence or of a later version of this Licence unless
the Original Work is expressly distributed only under this version of the Licence — for example by communicating
EUPL v. 1.2 only. The Licensee (becoming Licensor) cannot offer or impose any additional terms or conditions on the
Work or Derivative Work that alter or restrict the terms of the Licence.
Compatibility clause: If the Licensee Distributes or Communicates Derivative Works or copies thereof based upon both
the Work and another work licensed under a Compatible Licence, this Distribution or Communication can be done
under the terms of this Compatible Licence. For the sake of this clause, Compatible Licence refers to the licences listed
in the appendix attached to this Licence. Should the Licensee's obligations under the Compatible Licence conflict with
his/her obligations under this Licence, the obligations of the Compatible Licence shall prevail.
Provision of Source Code: When distributing or communicating copies of the Work, the Licensee will provide
a machine-readable copy of the Source Code or indicate a repository where this Source will be easily and freely available
for as long as the Licensee continues to distribute or communicate the Work.
Legal Protection: This Licence does not grant permission to use the trade names, trademarks, service marks, or names
of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and
reproducing the content of the copyright notice.
6.Chain of Authorship
The original Licensor warrants that the copyright in the Original Work granted hereunder is owned by him/her or
licensed to him/her and that he/she has the power and authority to grant the Licence.
Each Contributor warrants that the copyright in the modifications he/she brings to the Work are owned by him/her or
licensed to him/her and that he/she has the power and authority to grant the Licence.
Each time You accept the Licence, the original Licensor and subsequent Contributors grant You a licence to their contributions
to the Work, under the terms of this Licence.
7.Disclaimer of Warranty
The Work is a work in progress, which is continuously improved by numerous Contributors. It is not a finished work
and may therefore contain defects or bugs inherent to this type of development.
For the above reason, the Work is provided under the Licence on an as is basis and without warranties of any kind
concerning the Work, including without limitation merchantability, fitness for a particular purpose, absence of defects or
errors, accuracy, non-infringement of intellectual property rights other than copyright as stated in Article 6 of this
Licence.
This disclaimer of warranty is an essential part of the Licence and a condition for the grant of any rights to the Work.
8.Disclaimer of Liability
Except in the cases of wilful misconduct or damages directly caused to natural persons, the Licensor will in no event be
liable for any direct or indirect, material or moral, damages of any kind, arising out of the Licence or of the use of the
Work, including without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, loss
of data or any commercial damage, even if the Licensor has been advised of the possibility of such damage. However,
the Licensor will be liable under statutory product liability laws as far such laws apply to the Work.
9.Additional agreements
While distributing the Work, You may choose to conclude an additional agreement, defining obligations or services
consistent with this Licence. However, if accepting obligations, You may act only on your own behalf and on your sole
responsibility, not on behalf of the original Licensor or any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against such Contributor by
the fact You have accepted any warranty or additional liability.
10.Acceptance of the Licence
The provisions of this Licence can be accepted by clicking on an icon I agree placed under the bottom of a window
displaying the text of this Licence or by affirming consent in any other similar way, in accordance with the rules of
applicable law. Clicking on that icon indicates your clear and irrevocable acceptance of this Licence and all of its terms
and conditions.
Similarly, you irrevocably accept this Licence and all of its terms and conditions by exercising any rights granted to You
by Article 2 of this Licence, such as the use of the Work, the creation by You of a Derivative Work or the Distribution
or Communication by You of the Work or copies thereof.
11.Information to the public
In case of any Distribution or Communication of the Work by means of electronic communication by You (for example,
by offering to download the Work from a remote location) the distribution channel or media (for example, a website)
must at least provide to the public the information requested by the applicable law regarding the Licensor, the Licence
and the way it may be accessible, concluded, stored and reproduced by the Licensee.
12.Termination of the Licence
The Licence and the rights granted hereunder will terminate automatically upon any breach by the Licensee of the terms
of the Licence.
Such a termination will not terminate the licences of any person who has received the Work from the Licensee under
the Licence, provided such persons remain in full compliance with the Licence.
13.Miscellaneous
Without prejudice of Article 9 above, the Licence represents the complete agreement between the Parties as to the
Work.
If any provision of the Licence is invalid or unenforceable under applicable law, this will not affect the validity or
enforceability of the Licence as a whole. Such provision will be construed or reformed so as necessary to make it valid
and enforceable.
The European Commission may publish other linguistic versions or new versions of this Licence or updated versions of
the Appendix, so far this is required and reasonable, without reducing the scope of the rights granted by the Licence.
New versions of the Licence will be published with a unique version number.
All linguistic versions of this Licence, approved by the European Commission, have identical value. Parties can take
advantage of the linguistic version of their choice.
14.Jurisdiction
Without prejudice to specific agreement between parties,
— any litigation resulting from the interpretation of this License, arising between the European Union institutions,
bodies, offices or agencies, as a Licensor, and any Licensee, will be subject to the jurisdiction of the Court of Justice
of the European Union, as laid down in article 272 of the Treaty on the Functioning of the European Union,
— any litigation arising between other parties and resulting from the interpretation of this License, will be subject to
the exclusive jurisdiction of the competent court where the Licensor resides or conducts its primary business.
15.Applicable Law
Without prejudice to specific agreement between parties,
— this Licence shall be governed by the law of the European Union Member State where the Licensor has his seat,
resides or has his registered office,
— this licence shall be governed by Belgian law if the Licensor has no seat, residence or registered office inside
a European Union Member State.
Appendix
Compatible Licences according to Article 5 EUPL are:
— GNU General Public License (GPL) v. 2, v. 3
— GNU Affero General Public License (AGPL) v. 3
— Open Software License (OSL) v. 2.1, v. 3.0
— Eclipse Public License (EPL) v. 1.0
— CeCILL v. 2.0, v. 2.1
— Mozilla Public Licence (MPL) v. 2
— GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3
— Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for works other than software
— European Union Public Licence (EUPL) v. 1.1, v. 1.2
— Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong Reciprocity (LiLiQ-R+).
The European Commission may update this Appendix to later versions of the above licences without producing
a new version of the EUPL, as long as they provide the rights granted in Article 2 of this Licence and protect the
covered Source Code from exclusive appropriation.
All other changes or additions to this Appendix require the production of a new EUPL version.

View File

@@ -1,3 +1,17 @@
# asm3 # reactor
Reactor: Advanced Hydraulic Tank & Biological Process Simulator
A comprehensive reactor class for wastewater treatment simulation featuring plug flow hydraulics, ASM1-ASM3 biological modeling, and multi-sectional concentration tracking. Implements hydraulic retention time calculations, dispersion modeling, and real-time biological reaction kinetics for accurate process simulation.
Key Features:
Plug Flow Hydraulics: Multi-section reactor with configurable sectioning factor and dispersion modeling
ASM1 Integration: Complete biological nutrient removal modeling with 13 state variables (COD, nitrogen, phosphorus)
Dynamic Volume Control: Automatic section management with overflow handling and retention time calculations
Oxygen Transfer: Saturation-limited O2 transfer with Fick's law slowdown effects and solubility curves
Real-time Kinetics: Continuous biological reaction rate calculations with configurable time acceleration
Weighted Averaging: Volume-based concentration mixing for accurate mass balance calculations
Child Registration: Integration with diffuser systems and upstream/downstream reactor networks
Supports complex biological treatment train modeling with temperature compensation, sludge calculations, and comprehensive process monitoring for wastewater treatment plant optimization and regulatory compliance.
Implementation of the asm3 model (doi:10.1016/S0273-1223(98)00785-9)

28
package-lock.json generated
View File

@@ -1,22 +1,22 @@
{ {
"name": "asm3", "name": "reactor",
"version": "0.0.1", "version": "0.0.1",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "asm3", "name": "reactor",
"version": "0.0.1", "version": "0.0.1",
"license": "SEE LICENSE", "license": "SEE LICENSE",
"dependencies": { "dependencies": {
"generalFunctions": "git+https://gitea.centraal.wbd-rd.nl/p.vanderwilt/generalFunctions.git", "generalFunctions": "git+https://gitea.centraal.wbd-rd.nl/RnD/generalFunctions.git",
"mathjs": "^14.5.2" "mathjs": "^14.5.2"
} }
}, },
"node_modules/@babel/runtime": { "node_modules/@babel/runtime": {
"version": "7.28.2", "version": "7.28.4",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.2.tgz", "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.4.tgz",
"integrity": "sha512-KHp2IflsnGywDjBWDkR9iEqiWSpc8GIi0lgTT3mOElT0PP1tG26P4tmFI2YvAdzgq9RGyoHZQEIEdZy6Ec5xCA==", "integrity": "sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=6.9.0" "node": ">=6.9.0"
@@ -48,12 +48,12 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/fraction.js": { "node_modules/fraction.js": {
"version": "5.2.2", "version": "5.3.4",
"resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.2.2.tgz", "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz",
"integrity": "sha512-uXBDv5knpYmv/2gLzWQ5mBHGBRk9wcKTeWu6GLTUEQfjCxO09uM/mHDrojlL+Q1mVGIIFo149Gba7od1XPgSzQ==", "integrity": "sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">= 12" "node": "*"
}, },
"funding": { "funding": {
"type": "github", "type": "github",
@@ -62,7 +62,7 @@
}, },
"node_modules/generalFunctions": { "node_modules/generalFunctions": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "git+https://gitea.centraal.wbd-rd.nl/p.vanderwilt/generalFunctions.git#f13ee68938ea9d4b3a17ad90618c72634769c777", "resolved": "git+https://gitea.centraal.wbd-rd.nl/RnD/generalFunctions.git#efc97d6cd17399391b011298e47e8c1b1599592d",
"license": "SEE LICENSE" "license": "SEE LICENSE"
}, },
"node_modules/javascript-natural-sort": { "node_modules/javascript-natural-sort": {
@@ -72,9 +72,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/mathjs": { "node_modules/mathjs": {
"version": "14.6.0", "version": "14.8.0",
"resolved": "https://registry.npmjs.org/mathjs/-/mathjs-14.6.0.tgz", "resolved": "https://registry.npmjs.org/mathjs/-/mathjs-14.8.0.tgz",
"integrity": "sha512-5vI2BLB5GKQmiSK9BH6hVkZ+GgqpdnOgEfmHl7mqVmdQObLynr63KueyYYLCQMzj66q69mV2XZZGQqqxeftQbA==", "integrity": "sha512-DN4wmAjNzFVJ9vHqpAJ3vX0UF306u/1DgGKh7iVPuAFH19JDRd9NAaQS764MsKbSwDB6uBSkQEmgVmKdgYaCoQ==",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.26.10", "@babel/runtime": "^7.26.10",

View File

@@ -1,10 +1,10 @@
{ {
"name": "asm3", "name": "reactor",
"version": "0.0.1", "version": "0.0.1",
"description": "Implementation of the asm3 model for Node-Red", "description": "Implementation of the asm3 model for Node-Red",
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://gitea.centraal.wbd-rd.nl/p.vanderwilt/asm3.git" "url": "https://gitea.centraal.wbd-rd.nl/RnD/reactor.git"
}, },
"keywords": [ "keywords": [
"asm3", "asm3",
@@ -15,19 +15,19 @@
], ],
"license": "SEE LICENSE", "license": "SEE LICENSE",
"author": "P.R. van der Wilt", "author": "P.R. van der Wilt",
"main": "advancedReactor.js", "main": "reactor.js",
"scripts": { "scripts": {
"test": "node advancedReactor.js" "test": "node reactor.js"
}, },
"node-red": { "node-red": {
"nodes": { "nodes": {
"advancedReactor": "advancedReactor.js", "reactor": "reactor.js",
"recirculation-pump": "additional_nodes/recirculation-pump.js", "recirculation-pump": "additional_nodes/recirculation-pump.js",
"settling-basin": "additional_nodes/settling-basin.js" "settling-basin": "additional_nodes/settling-basin.js"
} }
}, },
"dependencies": { "dependencies": {
"generalFunctions": "git+https://gitea.centraal.wbd-rd.nl/p.vanderwilt/generalFunctions.git", "generalFunctions": "git+https://gitea.centraal.wbd-rd.nl/RnD/generalFunctions.git",
"mathjs": "^14.5.2" "mathjs": "^14.5.2"
} }
} }

View File

@@ -1,7 +1,7 @@
<script src="/advancedReactor/menu.js"></script> <script src="/reactor/menu.js"></script>
<script type="text/javascript"> <script type="text/javascript">
RED.nodes.registerType("advancedReactor", { RED.nodes.registerType("reactor", {
category: "WWTP", category: "WWTP",
color: "#c4cce0", color: "#c4cce0",
defaults: { defaults: {
@@ -28,6 +28,8 @@
X_A_init: { value: 0.001, required: true }, X_A_init: { value: 0.001, required: true },
X_TS_init: { value: 125.0009, required: true }, X_TS_init: { value: 125.0009, required: true },
timeStep: { value: 1, required: true },
enableLog: { value: false }, enableLog: { value: false },
logLevel: { value: "error" }, logLevel: { value: "error" },
@@ -39,13 +41,13 @@
outputLabels: ["process", "dbase", "parent"], outputLabels: ["process", "dbase", "parent"],
icon: "font-awesome/fa-recycle", icon: "font-awesome/fa-recycle",
label: function() { label: function() {
return this.name || "advancedReactor"; return this.name || "Reactor";
}, },
oneditprepare: function() { oneditprepare: function() {
// wait for the menu scripts to load // wait for the menu scripts to load
const waitForMenuData = () => { const waitForMenuData = () => {
if (window.EVOLV?.nodes?.advancedReactor?.initEditor) { if (window.EVOLV?.nodes?.reactor?.initEditor) {
window.EVOLV.nodes.advancedReactor.initEditor(this); window.EVOLV.nodes.reactor.initEditor(this);
} else { } else {
setTimeout(waitForMenuData, 50); setTimeout(waitForMenuData, 50);
} }
@@ -99,6 +101,10 @@
type:"num", type:"num",
types:["num"] types:["num"]
}) })
$("#node-input-timeStep").typedInput({
type:"num",
types:["num"]
})
// Set initial visibility on dialog open // Set initial visibility on dialog open
const initialType = $("#node-input-reactor_type").typedInput("value"); const initialType = $("#node-input-reactor_type").typedInput("value");
if (initialType === "CSTR") { if (initialType === "CSTR") {
@@ -109,8 +115,8 @@
}, },
oneditsave: function() { oneditsave: function() {
// save logger fields // save logger fields
if (window.EVOLV?.nodes?.['advancedReactor']?.loggerMenu?.saveEditor) { if (window.EVOLV?.nodes?.reactor?.loggerMenu?.saveEditor) {
window.EVOLV.nodes['advancedReactor'].loggerMenu.saveEditor(this); window.EVOLV.nodes.reactor.loggerMenu.saveEditor(this);
} }
// save position field // save position field
@@ -130,7 +136,7 @@
}); });
</script> </script>
<script type="text/html" data-template-name="advancedReactor"> <script type="text/html" data-template-name="reactor">
<div class="form-row"> <div class="form-row">
<label for="node-input-name"><i class="fa fa-tag"></i> Name</label> <label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
<input type="text" id="node-input-name" placeholder="Name"> <input type="text" id="node-input-name" placeholder="Name">
@@ -222,6 +228,11 @@
<label for="node-input-X_TS_init"><i class="fa fa-tag"></i> Initial total suspended solids [g TSS m-3]</label> <label for="node-input-X_TS_init"><i class="fa fa-tag"></i> Initial total suspended solids [g TSS m-3]</label>
<input type="text" id="node-input-X_TS_init" class="concentrations"> <input type="text" id="node-input-X_TS_init" class="concentrations">
</div> </div>
<h2> Simulation parameters </h2>
<div class="form-row">
<label for="node-input-timeStep"><i class="fa fa-tag"></i> Time step [s]</label>
<input type="text" id="node-input-timeStep" placeholder="s">
</div>
<!-- Logger fields injected here --> <!-- Logger fields injected here -->
<div id="logger-fields-placeholder"></div> <div id="logger-fields-placeholder"></div>
@@ -232,6 +243,6 @@
</script> </script>
<script type="text/html" data-help-name="advancedReactor"> <script type="text/html" data-help-name="reactor">
<p>New reactor node</p> <p>New reactor node</p>
</script> </script>

View File

@@ -1,4 +1,4 @@
const nameOfNode = "advancedReactor"; // name of the node, should match file name and node type in Node-RED const nameOfNode = "reactor"; // name of the node, should match file name and node type in Node-RED
const nodeClass = require('./src/nodeClass.js'); // node class const nodeClass = require('./src/nodeClass.js'); // node class
const { MenuManager } = require('generalFunctions'); const { MenuManager } = require('generalFunctions');

View File

@@ -49,7 +49,7 @@ class nodeClass {
this.source.setDispersion = msg; this.source.setDispersion = msg;
break; break;
case 'registerChild': case 'registerChild':
// Register this node as a child of the parent node // Register this node as a parent of the child node
const childId = msg.payload; const childId = msg.payload;
const childObj = this.RED.nodes.getNode(childId); const childObj = this.RED.nodes.getNode(childId);
this.source.childRegistrationUtils.registerChild(childObj.source, msg.positionVsParent); this.source.childRegistrationUtils.registerChild(childObj.source, msg.positionVsParent);
@@ -104,7 +104,8 @@ class nodeClass {
parseFloat(uiConfig.X_STO_init), parseFloat(uiConfig.X_STO_init),
parseFloat(uiConfig.X_A_init), parseFloat(uiConfig.X_A_init),
parseFloat(uiConfig.X_TS_init) parseFloat(uiConfig.X_TS_init)
] ],
timeStep: parseFloat(uiConfig.timeStep)
} }
} }

View File

@@ -12,6 +12,7 @@ const math = create(all, mathConfig);
const S_O_INDEX = 0; const S_O_INDEX = 0;
const NUM_SPECIES = 13; const NUM_SPECIES = 13;
const BC_PADDING = 2;
const DEBUG = false; const DEBUG = false;
class Reactor { class Reactor {
@@ -27,6 +28,10 @@ class Reactor {
this.measurements = new MeasurementContainer(); this.measurements = new MeasurementContainer();
this.upstreamReactor = null; this.upstreamReactor = null;
this.childRegistrationUtils = new childRegistrationUtils(this); // Child registration utility this.childRegistrationUtils = new childRegistrationUtils(this); // Child registration utility
this.parent = []; // Gets assigned via child registration
this.upstreamReactor = null;
this.downstreamReactor = null;
this.asm = new ASM3(); this.asm = new ASM3();
@@ -40,20 +45,8 @@ class Reactor {
this.kla = config.kla; // if NaN, use externaly provided OTR [d-1] this.kla = config.kla; // if NaN, use externaly provided OTR [d-1]
this.currentTime = Date.now(); // milliseconds since epoch [ms] this.currentTime = Date.now(); // milliseconds since epoch [ms]
this.timeStep = 1 / (24*60*15); // time step [d] this.timeStep = 1 / (24*60*60) * this.config.timeStep; // time step in seconds, converted to days.
this.speedUpFactor = 60; // speed up factor for simulation, 60 means 1 minute per simulated second this.speedUpFactor = 100; // speed up factor for simulation, 60 means 1 minute per simulated second
}
updateMeasurement(variant, subType, value, position) {
this.logger.debug(`---------------------- updating ${subType} ------------------ `);
switch (subType) {
case "temperature":
this.temperature = value;
break;
default:
this.logger.error(`Type '${subType}' not recognized for measured update.`);
return;
}
} }
/** /**
@@ -109,6 +102,86 @@ class Reactor {
} }
} }
registerChild(child, softwareType) {
switch (softwareType) {
case "measurement":
this.logger.debug(`Registering measurement child.`);
this._connectMeasurement(child);
break;
case "reactor":
this.logger.debug(`Registering reactor child.`);
this._connectReactor(child);
break;
default:
this.logger.error(`Unrecognized softwareType: ${softwareType}`);
}
}
_connectMeasurement(measurementChild) {
if (!measurementChild) {
this.logger.warn("Invalid measurement provided.");
return;
}
const position = measurementChild.config.functionality.positionVsParent;
const measurementType = measurementChild.config.asset.type;
const eventName = `${measurementType}.measured.${position}`;
// Register event listener for measurement updates
measurementChild.measurements.emitter.on(eventName, (eventData) => {
this.logger.debug(`${position} ${measurementType} from ${eventData.childName}: ${eventData.value} ${eventData.unit}`);
// Store directly in parent's measurement container
this.measurements
.type(measurementType)
.variant("measured")
.position(position)
.value(eventData.value, eventData.timestamp, eventData.unit);
this._updateMeasurement(measurementType, eventData.value, position, eventData);
});
}
_connectReactor(reactorChild) {
if (!reactorChild) {
this.logger.warn("Invalid reactor provided.");
return;
}
if (reactorChild.functionality.positionVsParent != "upstream") {
this.logger.warn("Reactor children of reactors should always be upstream.");
}
if (math.abs(reactorChild.d_x - this.d_x) / this.d_x < 0.025) {
this.logger.warn("Significant grid sizing discrepancies between adjacent reactors! Change resolutions to match reactors grid step, or implement boundary value interpolation.");
}
this.upstreamReactor = reactorChild;
reactorChild.downstreamReactor = this;
reactorChild.emitter.on("stateChange", (data) => {
this.logger.debug(`State change of upstream reactor detected.`);
this.updateState(data);
});
}
_updateMeasurement(measurementType, value, position, context) {
this.logger.debug(`---------------------- updating ${measurementType} ------------------ `);
switch (measurementType) {
case "temperature":
if (position == "atEquipment") {
this.temperature = value;
}
break;
default:
this.logger.error(`Type '${measurementType}' not recognized for measured update.`);
return;
}
}
/** /**
* Update the reactor state based on the new time. * Update the reactor state based on the new time.
* @param {number} newTime - New time to update reactor state to, in milliseconds since epoch. * @param {number} newTime - New time to update reactor state to, in milliseconds since epoch.
@@ -181,11 +254,15 @@ class Reactor_PFR extends Reactor {
this.alpha = config.alpha; this.alpha = config.alpha;
this.state = Array.from(Array(this.n_x), () => config.initialState.slice()) this.state = Array.from(Array(this.n_x), () => config.initialState.slice());
this.extendedState = Array.from(Array(this.n_x + 2*BC_PADDING), () => new Array(NUM_SPECIES).fill(0));
// initialise extended state
this.state.forEach((row, i) => this.extendedState[i+BC_PADDING] = row);
this.D = 0.0; // axial dispersion [m2 d-1] this.D = 0.0; // axial dispersion [m2 d-1]
this.D_op = this._makeDoperator(true, true); this.D_op = this._makeDoperator();
assertNoNaN(this.D_op, "Derivative operator"); assertNoNaN(this.D_op, "Derivative operator");
this.D2_op = this._makeD2operator(); this.D2_op = this._makeD2operator();
@@ -197,15 +274,16 @@ class Reactor_PFR extends Reactor {
* @param {object} input - Input object (msg) containing payload with dispersion value [m2 d-1]. * @param {object} input - Input object (msg) containing payload with dispersion value [m2 d-1].
*/ */
set setDispersion(input) { set setDispersion(input) {
this.D = input.payload; this.D = this._constrainDispersion(input.payload);
} }
updateState(newTime) { updateState(newTime) {
super.updateState(newTime); super.updateState(newTime);
let Pe_local = this.d_x*math.sum(this.Fs)/(this.D*this.A) // let Pe_local = this.d_x*math.sum(this.Fs)/(this.D*this.A)
this.D = this._constrainDispersion(this.D);
let Co_D = this.D*this.timeStep/(this.d_x*this.d_x); let Co_D = this.D*this.timeStep/(this.d_x*this.d_x);
(Pe_local >= 2) && this.logger.warn(`Local Péclet number (${Pe_local}) is too high! Increase reactor resolution.`); // (Pe_local >= 2) && this.logger.warn(`Local Péclet number (${Pe_local}) is too high! Increase reactor resolution.`);
(Co_D >= 0.5) && this.logger.warn(`Courant number (${Co_D}) is too high! Reduce time step size.`); (Co_D >= 0.5) && this.logger.warn(`Courant number (${Co_D}) is too high! Reduce time step size.`);
if(DEBUG) { if(DEBUG) {
@@ -223,25 +301,26 @@ class Reactor_PFR extends Reactor {
* @returns {Array} - New reactor state. * @returns {Array} - New reactor state.
*/ */
tick(time_step) { tick(time_step) {
const dispersion = math.multiply(this.D / (this.d_x*this.d_x), this.D2_op, this.state); this._applyBoundaryConditions();
const advection = math.multiply(-1 * math.sum(this.Fs) / (this.A*this.d_x), this.D_op, this.state);
const reaction = this.state.map((state_slice) => this.asm.compute_dC(state_slice, this.temperature)); const dispersion = math.multiply(this.D / (this.d_x*this.d_x), this.D2_op, this.extendedState);
const transfer = Array.from(Array(this.n_x), () => new Array(NUM_SPECIES).fill(0)); const advection = math.multiply(-1 * math.sum(this.Fs) / (this.A*this.d_x), this.D_op, this.extendedState);
const reaction = this.extendedState.map((state_slice) => this.asm.compute_dC(state_slice, this.temperature));
const transfer = Array.from(Array(this.n_x+2*BC_PADDING), () => new Array(NUM_SPECIES).fill(0));
if (isNaN(this.kla)) { // calculate OTR if kla is not NaN, otherwise use externally calculated OTR if (isNaN(this.kla)) { // calculate OTR if kla is not NaN, otherwise use externally calculated OTR
for (let i = 1; i < this.n_x - 1; i++) { for (let i = BC_PADDING+1; i < BC_PADDING+this.n_x - 1; i++) {
transfer[i][S_O_INDEX] = this.OTR * this.n_x/(this.n_x-2); transfer[i][S_O_INDEX] = this.OTR * this.n_x/(this.n_x-2);
} }
} else { } else {
for (let i = 1; i < this.n_x - 1; i++) { for (let i = BC_PADDING+1; i < BC_PADDING+this.n_x - 1; i++) {
transfer[i][S_O_INDEX] = this._calcOTR(this.state[i][S_O_INDEX], this.temperature) * this.n_x/(this.n_x-2); transfer[i][S_O_INDEX] = this._calcOTR(this.extendedState[i][S_O_INDEX], this.temperature) * this.n_x/(this.n_x-2);
} }
} }
const dC_total = math.multiply(math.add(dispersion, advection, reaction, transfer), time_step); const dC_total = math.multiply(math.add(dispersion, advection, reaction, transfer).slice(BC_PADDING, this.n_x+BC_PADDING), time_step);
const stateNew = math.add(this.state, dC_total); const stateNew = math.add(this.state, dC_total);
this._applyBoundaryConditions(stateNew);
if (DEBUG) { if (DEBUG) {
assertNoNaN(dispersion, "dispersion"); assertNoNaN(dispersion, "dispersion");
@@ -252,74 +331,70 @@ class Reactor_PFR extends Reactor {
} }
this.state = this._arrayClip2Zero(stateNew); this.state = this._arrayClip2Zero(stateNew);
this.state.forEach((row, i) => this.extendedState[i+BC_PADDING] = row);
return stateNew; return stateNew;
} }
updateMeasurement(variant, subType, value, position) { _updateMeasurement(measurementType, value, position, context) {
switch(subType) { switch(measurementType) {
case "oxygen": case "quantity (oxygen)":
grid_pos = Math.round(position * this.n_x); let grid_pos = Math.round(context.distance / this.config.length * this.n_x);
this.state[grid_pos][S_O_INDEX] = value; // naive approach for reconciling measurements and simulation this.state[grid_pos][S_O_INDEX] = value; // naive approach for reconciling measurements and simulation
return; break;
default:
super._updateMeasurement(measurementType, value, position, context);
} }
super.updateMeasurement(variant, subType, value, position);
} }
/** /**
* Apply boundary conditions to the reactor state. * Apply boundary conditions to the reactor state.
* for inlet, apply generalised Danckwerts BC, if there is not flow, apply Neumann BC with no flux * for inlet, apply generalised Danckwerts BC, if there is not flow, apply Neumann BC with no flux
* for outlet, apply regular Danckwerts BC (Neumann BC with no flux) * for outlet, apply regular Danckwerts BC (Neumann BC with no flux)
* @param {Array} state - Current reactor state without enforced BCs.
*/ */
_applyBoundaryConditions(state) { _applyBoundaryConditions() {
if (this.upstreamReactor) {
for (let i = 0; i < BC_PADDING; i++) {
this.extendedState[i] = this.upstreamReactor.state.at(i-BC_PADDING);
}
} else {
if (math.sum(this.Fs) > 0) { // Danckwerts BC if (math.sum(this.Fs) > 0) { // Danckwerts BC
const BC_C_in = math.multiply(1 / math.sum(this.Fs), [this.Fs], this.Cs_in)[0]; const BC_C_in = math.multiply(1 / math.sum(this.Fs), [this.Fs], this.Cs_in)[0];
const BC_dispersion_term = (1-this.alpha)*this.D*this.A/(math.sum(this.Fs)*this.d_x); const BC_dispersion_term = (1-this.alpha)*this.D*this.A/(math.sum(this.Fs)*this.d_x);
state[0] = math.multiply(1/(1+BC_dispersion_term), math.add(BC_C_in, math.multiply(BC_dispersion_term, state[1]))); this.extendedState[BC_PADDING] = math.multiply(1/(1+BC_dispersion_term), math.add(BC_C_in, math.multiply(BC_dispersion_term, this.extendedState[BC_PADDING+1])));
this.extendedState[BC_PADDING-1] = math.add(math.multiply(2, this.extendedState[BC_PADDING]), math.multiply(-2, this.extendedState[BC_PADDING+2]), this.extendedState[BC_PADDING+3]);
} else { } else {
state[0] = state[1]; for (let i = 0; i < BC_PADDING; i++) {
this.extendedState[i] = this.extendedState[BC_PADDING];
} }
}
}
if (this.downstreamReactor) {
for (let i = 0; i < BC_PADDING; i++) {
this.extendedState[this.n_x+BC_PADDING+i] = this.downstreamReactor.state[i];
}
} else {
// Neumann BC (no flux) // Neumann BC (no flux)
state[this.n_x-1] = state[this.n_x-2]; for (let i = 0; i < BC_PADDING; i++) {
this.extendedState[BC_PADDING+this.n_x+i] = this.extendedState.at(-1-BC_PADDING);
}
}
} }
/** /**
* Create finite difference first derivative operator. * Create finite difference first derivative operator.
* @param {boolean} central - Use central difference scheme if true, otherwise use upwind scheme.
* @param {boolean} higher_order - Use higher order scheme if true, otherwise use first order scheme.
* @returns {Array} - First derivative operator matrix. * @returns {Array} - First derivative operator matrix.
*/ */
_makeDoperator(central = false, higher_order = false) { // create gradient operator _makeDoperator() { // create gradient operator
if (higher_order) { const D_size = this.n_x+2*BC_PADDING;
if (central) { const I = math.resize(math.diag(Array(D_size).fill(1/12), -2), [D_size, D_size]);
const I = math.resize(math.diag(Array(this.n_x).fill(1/12), -2), [this.n_x, this.n_x]); const A = math.resize(math.diag(Array(D_size).fill(-2/3), -1), [D_size, D_size]);
const A = math.resize(math.diag(Array(this.n_x).fill(-2/3), -1), [this.n_x, this.n_x]); const B = math.resize(math.diag(Array(D_size).fill(2/3), 1), [D_size, D_size]);
const B = math.resize(math.diag(Array(this.n_x).fill(2/3), 1), [this.n_x, this.n_x]); const C = math.resize(math.diag(Array(D_size).fill(-1/12), 2), [D_size, D_size]);
const C = math.resize(math.diag(Array(this.n_x).fill(-1/12), 2), [this.n_x, this.n_x]);
const D = math.add(I, A, B, C); const D = math.add(I, A, B, C);
const NearBoundary = Array(this.n_x).fill(0.0); // set by BCs elsewhere
NearBoundary[0] = -1/4; D.forEach((row, i) => i < BC_PADDING || i >= this.n_x+BC_PADDING ? row.fill(0) : row);
NearBoundary[1] = -5/6;
NearBoundary[2] = 3/2;
NearBoundary[3] = -1/2;
NearBoundary[4] = 1/12;
D[1] = NearBoundary;
NearBoundary.reverse();
D[this.n_x-2] = math.multiply(-1, NearBoundary);
D[0] = Array(this.n_x).fill(0); // set by BCs elsewhere
D[this.n_x-1] = Array(this.n_x).fill(0);
return D; return D;
} else {
throw new Error("Upwind higher order method not implemented! Use central scheme instead.");
}
} else {
const I = math.resize(math.diag(Array(this.n_x).fill(1 / (1+central)), central), [this.n_x, this.n_x]);
const A = math.resize(math.diag(Array(this.n_x).fill(-1 / (1+central)), -1), [this.n_x, this.n_x]);
const D = math.add(I, A);
D[0] = Array(this.n_x).fill(0); // set by BCs elsewhere
D[this.n_x-1] = Array(this.n_x).fill(0);
return D;
}
} }
/** /**
@@ -327,14 +402,24 @@ class Reactor_PFR extends Reactor {
* @returns {Array} - Second derivative operator matrix. * @returns {Array} - Second derivative operator matrix.
*/ */
_makeD2operator() { // create the central second derivative operator _makeD2operator() { // create the central second derivative operator
const I = math.diag(Array(this.n_x).fill(-2), 0); const D_size = this.n_x+2*BC_PADDING;
const A = math.resize(math.diag(Array(this.n_x).fill(1), 1), [this.n_x, this.n_x]); const I = math.diag(Array(D_size).fill(-2), 0);
const B = math.resize(math.diag(Array(this.n_x).fill(1), -1), [this.n_x, this.n_x]); const A = math.resize(math.diag(Array(D_size).fill(1), 1), [D_size, D_size]);
const B = math.resize(math.diag(Array(D_size).fill(1), -1), [D_size, D_size]);
const D2 = math.add(I, A, B); const D2 = math.add(I, A, B);
D2[0] = Array(this.n_x).fill(0); // set by BCs elsewhere // set by BCs elsewhere
D2[this.n_x - 1] = Array(this.n_x).fill(0); D2.forEach((row, i) => i < BC_PADDING || i >= this.n_x+BC_PADDING ? row.fill(0) : row);
return D2; return D2;
} }
_constrainDispersion(D) {
const Dmin = math.sum(this.Fs) * this.d_x / (1.999 * this.A);
if (D < Dmin) {
this.logger.warn(`Local Péclet number too high! Constraining given dispersion (${D}) to minimal value (${Dmin}).`);
return Dmin;
}
return D;
}
} }
module.exports = { Reactor_CSTR, Reactor_PFR }; module.exports = { Reactor_CSTR, Reactor_PFR };