epanet-rs 0.2.2

A fast, modern and safe re-implementation of the EPANET2 hydraulic solver, written in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
//! FFI node accessors: `EN_addnode`, `EN_getnodevalue`, `EN_setnodevalue`, etc.

use crate::ffi::enums::NodeProperty;
use crate::ffi::error_codes::ErrorCode;
use crate::ffi::project::{Project, get_simulation, get_simulation_mut};
use crate::model::demand::Demand;
use crate::model::network::modify::{
    JunctionData, JunctionUpdate, NodeUpdate, ReservoirData, TankData, TankUpdate,
};
use crate::model::node::NodeType;

use crate::ffi::enums::NodeType as ENNodeType;

use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_double, c_int};

/// # Safety
///
/// `ph` must be a valid non-null project handle returned by [`EN_createproject`].
/// `id` must be a valid non-null pointer to a NUL-terminated C string.
/// `out_index` must be a valid non-null writable pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn EN_addnode(
    ph: *mut Project,
    id: *const c_char,
    node_type: c_int,
    out_index: *mut c_int,
) -> ErrorCode {
    let simulation = get_simulation_mut!(ph);

    let c_str = unsafe { CStr::from_ptr(id) };
    let node_id = match c_str.to_str() {
        Ok(s) => s,
        Err(_) => return ErrorCode::InvalidIdName,
    };

    let node_type = match ENNodeType::from_repr(node_type) {
        Some(node_type) => node_type,
        None => return ErrorCode::InvalidParameterCode,
    };

    let result = match node_type {
        ENNodeType::Junction => simulation.network.add_junction(
            node_id,
            &JunctionData {
                elevation: 0.0,
                demands: vec![Demand {
                    basedemand: 0.0,
                    pattern: None,
                    pattern_index: None,
                    name: None,
                }],
                emitter_coefficient: 0.0,
                coordinates: None,
            },
        ),
        ENNodeType::Reservoir => simulation.network.add_reservoir(
            node_id,
            &ReservoirData {
                elevation: 0.0,
                head_pattern: None,
                coordinates: None,
            },
        ),
        ENNodeType::Tank => simulation.network.add_tank(
            node_id,
            &TankData {
                elevation: 0.0,
                initial_level: 0.0,
                min_level: 0.0,
                max_level: 0.0,
                diameter: 0.0,
                min_volume: 0.0,
                volume_curve_id: None,
                overflow: false,
                coordinates: None,
            },
        ),
    };

    if result.is_err() {
        return ErrorCode::IllegalNodeProperty;
    }
    unsafe { *out_index = (*simulation.network.node_map.get(node_id).unwrap() + 1) as c_int };
    ErrorCode::Ok
}

/// Gets the index of a node given its ID name.
/// # Safety
///
/// `ph` must be a valid non-null project handle returned by [`EN_createproject`].
/// `id` must be a valid non-null pointer to a NUL-terminated C string.
/// `out_index` must be a valid non-null writable pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn EN_getnodeindex(
    ph: *mut Project,
    id: *const c_char,
    out_index: *mut c_int,
) -> ErrorCode {
    let simulation = get_simulation!(ph);

    let c_str = unsafe { CStr::from_ptr(id) };
    let node_id = match c_str.to_str() {
        Ok(s) => s,
        Err(_) => return ErrorCode::InvalidIdName,
    };

    // get the node index from the network
    let node_index = match simulation.network.node_map.get(node_id) {
        Some(&index) => index,
        None => return ErrorCode::UndefinedNode,
    };

    // EPANET indexes from 1, so we need to add 1 to the index
    unsafe { *out_index = (node_index + 1) as c_int };

    ErrorCode::Ok
}

// Gets the ID name of a node given its index.
/// # Safety
///
/// `ph` must be a valid non-null project handle returned by [`EN_createproject`].
/// `out_id` must point to a buffer large enough for the result string including NUL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn EN_getnodeid(
    ph: *mut Project,
    index: c_int,
    out_id: *mut c_char,
) -> ErrorCode {
    let simulation = get_simulation!(ph);

    // EPANET indexes from 1, so we need to subtract 1 from the index
    let index = index - 1;

    let node_id = match simulation.network.nodes.get(index as usize) {
        Some(node) => node.id.as_ref(),
        None => return ErrorCode::UndefinedNode,
    };

    let c_str = CString::new(node_id).unwrap();

    unsafe {
        std::ptr::copy_nonoverlapping(c_str.as_ptr(), out_id, c_str.as_bytes_with_nul().len());
    }

    ErrorCode::Ok
}

// Sets the ID name of a node given its index.
/// # Safety
///
/// `ph` must be a valid non-null project handle returned by [`EN_createproject`].
/// `id` must be a valid non-null pointer to a NUL-terminated C string.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn EN_setnodeid(
    ph: *mut Project,
    index: c_int,
    id: *const c_char,
) -> ErrorCode {
    let simulation = get_simulation_mut!(ph);

    let c_str = unsafe { CStr::from_ptr(id) };

    let new_node_id = match c_str.to_str() {
        Ok(s) => s,
        Err(_) => return ErrorCode::InvalidIdName,
    };

    // EPANET indexes from 1, so we need to subtract 1 from the index
    let index = index - 1;

    let node = match simulation.network.nodes.get_mut(index as usize) {
        Some(node) => node,
        None => return ErrorCode::UndefinedNode,
    };

    // check if the new node id is already in use
    if simulation.network.node_map.contains_key(new_node_id) {
        return ErrorCode::DuplicateId;
    }

    // remove the old node id from the node map
    simulation.network.node_map.remove(&node.id);

    // update the node id
    node.id = new_node_id.into();

    // update the node map
    simulation
        .network
        .node_map
        .insert(new_node_id.into(), index as usize);

    // update all links that point to the old node id to point to the new node id
    for link in simulation.network.links.iter_mut() {
        if link.start_node_id == node.id {
            link.start_node_id = new_node_id.into();
        }
        if link.end_node_id == node.id {
            link.end_node_id = new_node_id.into();
        }
    }

    ErrorCode::Ok
}

// Get the node type given its index.
/// # Safety
///
/// `ph` must be a valid non-null project handle returned by [`EN_createproject`].
/// `out_type` must be a valid non-null writable pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn EN_getnodetype(
    ph: *mut Project,
    index: c_int,
    out_type: *mut c_int,
) -> ErrorCode {
    let simulation = get_simulation!(ph);

    // EPANET indexes from 1, so we need to add 1 to the index
    let index = index - 1;

    let node_type = match simulation.network.nodes.get(index as usize) {
        Some(node) => &node.node_type,
        None => return ErrorCode::UndefinedNode,
    };

    let node_type_int = match node_type {
        NodeType::Junction(_) => ENNodeType::Junction as i32,
        NodeType::Reservoir(_) => ENNodeType::Reservoir as i32,
        NodeType::Tank(_) => ENNodeType::Tank as i32,
    };

    unsafe { *out_type = node_type_int };

    ErrorCode::Ok
}

/// Retrieves the property value of a node
/// # Safety
///
/// `ph` must be a valid non-null project handle returned by [`EN_createproject`].
/// `out_value` must be a valid non-null writable pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn EN_getnodevalue(
    ph: *mut Project,
    index: c_int,
    property: c_int,
    out_value: *mut c_double,
) -> ErrorCode {
    let simulation = get_simulation!(ph);

    // EPANET indexes from 1, so we need to subtract 1 from the index
    let index = (index - 1) as usize;

    let node = match simulation.network.nodes.get(index) {
        Some(node) => node,
        None => return ErrorCode::UndefinedNode,
    };

    let options = &simulation.network.options;
    let unit_system = &options.unit_system;
    let flow_units = &options.flow_units;
    let pressure_units = &options.pressure_units;

    let property = match NodeProperty::from_repr(property) {
        Some(property) => property,
        None => return ErrorCode::InvalidParameterCode,
    };

    let value = match property {
        NodeProperty::Elevation => node.elevation * unit_system.per_feet(),
        NodeProperty::BaseDemand => match &node.node_type {
            NodeType::Junction(junction) => junction
                .demands
                .first()
                .map(|d| d.basedemand * flow_units.per_cfs())
                .unwrap_or(0.0),
            _ => 0.0,
        },
        NodeProperty::Pattern => match &node.node_type {
            NodeType::Junction(junction) => junction
                .demands
                .first()
                .map(|d| {
                    d.pattern_index
                        .map(|index| (index + 1) as f64)
                        .unwrap_or(123.0)
                })
                .unwrap_or(123.0),
            NodeType::Reservoir(reservoir) => reservoir
                .head_pattern_index
                .map(|index| (index + 1) as f64)
                .unwrap_or(123.0),
            _ => 0.0,
        },
        NodeProperty::Emitter => match &node.node_type {
            NodeType::Junction(junction) => {
                let e = junction.emitter_coefficient;
                if e > 0.0 {
                    flow_units.per_cfs()
                        / (pressure_units.per_feet() * e).powf(1.0 / options.emitter_exponent)
                } else {
                    0.0
                }
            }
            _ => 0.0,
        },
        NodeProperty::InitQual => 0.0, // TODO: quality not implemented yet
        NodeProperty::SourceQual => 0.0, // TODO: quality not implemented yet
        NodeProperty::SourcePat => 0.0, // TODO: quality not implemented yet
        NodeProperty::SourceType => 0.0, // TODO: quality not implemented yet

        NodeProperty::TankLevel => match &node.node_type {
            NodeType::Tank(_) => {
                simulation
                    .solved_state()
                    .map_or(0.0, |state| state.heads[index] - node.elevation)
                    * unit_system.per_feet()
            }
            _ => 0.0,
        },

        NodeProperty::InitVolume => match &node.node_type {
            NodeType::Tank(tank) => {
                tank.volume_at_level(tank.initial_level) * options.unit_system.per_cubic_feet()
            }
            _ => 0.0,
        },

        NodeProperty::Demand => simulation
            .solved_state()
            .map_or(0.0, |state| state.demands[index] * flow_units.per_cfs()),
        NodeProperty::Head => simulation
            .solved_state()
            .map_or(0.0, |state| state.heads[index] * unit_system.per_feet()),
        NodeProperty::Pressure => simulation.solved_state().map_or(0.0, |state| {
            (state.heads[index] - node.elevation) * pressure_units.per_feet()
        }),
        NodeProperty::Quality => 0.0, // TODO: quality not implemented yet
        NodeProperty::TankDiam => match &node.node_type {
            NodeType::Tank(tank) => tank.diameter * options.unit_system.per_feet(),
            _ => 0.0,
        },
        NodeProperty::MinVolume => match &node.node_type {
            NodeType::Tank(tank) => tank.min_volume() * options.unit_system.per_cubic_feet(),
            _ => 0.0,
        },
        NodeProperty::MaxVolume => match &node.node_type {
            NodeType::Tank(tank) => tank.max_volume() * options.unit_system.per_cubic_feet(),
            _ => 0.0,
        },
        NodeProperty::MinLevel => match &node.node_type {
            NodeType::Tank(tank) => tank.min_level * options.unit_system.per_feet(),
            _ => 0.0,
        },
        NodeProperty::MaxLevel => match &node.node_type {
            NodeType::Tank(tank) => tank.max_level * options.unit_system.per_feet(),
            _ => 0.0,
        },

        NodeProperty::TankVolume => match &node.node_type {
            NodeType::Tank(tank) => {
                if let Some(state) = simulation.solved_state() {
                    tank.volume_at_head(state.heads[index]) * options.unit_system.per_cubic_feet()
                } else {
                    tank.volume_at_level(tank.initial_level) * options.unit_system.per_cubic_feet()
                }
            }
            _ => 0.0,
        },

        NodeProperty::CanOverflow => match &node.node_type {
            NodeType::Tank(tank) if tank.overflow => 1.0,
            _ => 0.0,
        },
        NodeProperty::DemandDeficit => 0.0,
        NodeProperty::NodeInControl => 0.0,
        NodeProperty::EmitterFlow => 0.0,
        NodeProperty::LeakageFlow => 0.0,
        NodeProperty::DemandFlow => 0.0,
        NodeProperty::FullDemand => 0.0,
        NodeProperty::SourceMass => 0.0, // TODO: mass not implemented yet
        _ => -123.0,
    };

    unsafe { *out_value = value as c_double };

    ErrorCode::Ok
}

// Set the property value of a node
/// # Safety
///
/// `ph` must be a valid non-null project handle returned by [`EN_createproject`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn EN_setnodevalue(
    ph: *mut Project,
    index: c_int,
    property: c_int,
    value: c_double,
) -> ErrorCode {
    let simulation = get_simulation_mut!(ph);

    // EPANET indexes from 1, so we need to subtract 1 from the index
    let index = (index - 1) as usize;

    let network = &mut simulation.network;

    let node_id = match network.nodes.get(index) {
        Some(node) => node.id.clone(),
        None => return ErrorCode::UndefinedNode,
    };

    let property = match NodeProperty::from_repr(property) {
        Some(property) => property,
        None => return ErrorCode::InvalidParameterCode,
    };

    let result = match property {
        NodeProperty::Elevation => network.update_node(
            &node_id,
            &NodeUpdate {
                elevation: Some(value),
                ..Default::default()
            },
        ),
        NodeProperty::BaseDemand => network.update_junction(
            &node_id,
            &JunctionUpdate {
                basedemand: Some(value),
                ..Default::default()
            },
        ),
        NodeProperty::Emitter => network.update_junction(
            &node_id,
            &JunctionUpdate {
                emitter_coefficient: Some(value),
                ..Default::default()
            },
        ),
        NodeProperty::TankDiam => network.update_tank(
            &node_id,
            &TankUpdate {
                diameter: Some(value),
                ..Default::default()
            },
        ),
        NodeProperty::MinLevel => network.update_tank(
            &node_id,
            &TankUpdate {
                min_level: Some(value),
                ..Default::default()
            },
        ),
        NodeProperty::MaxLevel => network.update_tank(
            &node_id,
            &TankUpdate {
                max_level: Some(value),
                ..Default::default()
            },
        ),
        NodeProperty::TankLevel => network.update_tank(
            &node_id,
            &TankUpdate {
                initial_level: Some(value),
                ..Default::default()
            },
        ),
        NodeProperty::Pattern => {
            let pattern_id = match network.patterns.get(value as usize - 1) {
                Some(pattern) => pattern.id.clone(),
                None => return ErrorCode::UndefinedPattern,
            };
            network.update_junction(
                &node_id,
                &JunctionUpdate {
                    pattern: Some(Some(pattern_id)),
                    ..Default::default()
                },
            )
        }
        // TODO: implement missing properties
        _ => return ErrorCode::InvalidParameterCode,
    };

    if result.is_err() {
        return ErrorCode::IllegalNodeProperty;
    }

    ErrorCode::Ok
}

/// # Safety
///
/// `ph` must be a valid non-null project handle returned by [`EN_createproject`].
/// `out_x` must be a valid non-null writable pointer.
/// `out_y` must be a valid non-null writable pointer.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn EN_getcoord(
    ph: *mut Project,
    index: c_int,
    out_x: *mut c_double,
    out_y: *mut c_double,
) -> ErrorCode {
    let simulation = get_simulation!(ph);

    // EPANET indexes from 1, so we need to subtract 1 from the index
    let index = (index - 1) as usize;

    let node = match simulation.network.nodes.get(index) {
        Some(node) => node,
        None => return ErrorCode::UndefinedNode,
    };

    if let Some(coordinates) = node.coordinates {
        unsafe { *out_x = coordinates.0 as c_double };
        unsafe { *out_y = coordinates.1 as c_double };
    } else {
        return ErrorCode::NodeNoCoordinates;
    }

    ErrorCode::Ok
}

/// # Safety
///
/// `ph` must be a valid non-null project handle returned by [`EN_createproject`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn EN_setcoord(
    ph: *mut Project,
    index: c_int,
    x: c_double,
    y: c_double,
) -> ErrorCode {
    let simulation = get_simulation_mut!(ph);

    // EPANET indexes from 1, so we need to subtract 1 from the index
    let index = (index - 1) as usize;

    let node = match simulation.network.nodes.get_mut(index) {
        Some(node) => node,
        None => return ErrorCode::UndefinedNode,
    };
    node.coordinates = Some((x, y));
    ErrorCode::Ok
}

/// # Safety
///
/// `ph` must be a valid non-null project handle returned by [`EN_createproject`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn EN_deletenode(
    ph: *mut Project,
    index: c_int,
    action_code: c_int,
) -> ErrorCode {
    let simulation = get_simulation_mut!(ph);

    // EPANET indexes from 1, so we need to subtract 1 from the index
    let index = (index - 1) as usize;

    let node_id = match simulation.network.nodes.get(index) {
        Some(node) => node.id.clone(),
        None => return ErrorCode::UndefinedNode,
    };

    let result = simulation.network.remove_node(&node_id, action_code == 0);
    if result.is_err() {
        return ErrorCode::DeleteNodeOrLinkInControl;
    }

    ErrorCode::Ok
}