Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add check for duplicate name when adding a network. #221

Merged
merged 1 commit into from
Jul 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions pywr-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,8 @@ pub enum PywrError {
NetworkNotFound(String),
#[error("network index ({0}) not found")]
NetworkIndexNotFound(usize),
#[error("network name `{0}` already exists.")]
NetworkNameAlreadyExists(String),
#[error("parameters do not provide an initial value")]
ParameterNoInitialValue,
#[error("parameter state not found for parameter index {0}")]
Expand Down
25 changes: 22 additions & 3 deletions pywr-core/src/models/multi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,16 +114,20 @@ impl MultiNetworkModel {
.ok_or(PywrError::NetworkNotFound(name.to_string()))
}

pub fn add_network(&mut self, name: &str, network: Network) -> usize {
// TODO check for duplicate names
/// Add a [`Network`] to the model. The name must be unique.
pub fn add_network(&mut self, name: &str, network: Network) -> Result<usize, PywrError> {
if self.get_network_index_by_name(name).is_ok() {
return Err(PywrError::NetworkNameAlreadyExists(name.to_string()));
}

let idx = self.networks.len();
self.networks.push(MultiNetworkEntry {
name: name.to_string(),
network,
parameters: Vec::new(),
});

idx
Ok(idx)
}

/// Add a transfer of data from one network to another.
Expand Down Expand Up @@ -392,4 +396,19 @@ mod tests {

multi_model.step(&mut state).expect("Failed to step multi1-model.")
}

#[test]
fn test_duplicate_network_names() {
let timestepper = default_timestepper();
let scenario_collection = ScenarioGroupCollection::default();

let mut multi_model = MultiNetworkModel::new(ModelDomain::from(timestepper, scenario_collection).unwrap());

let network = Network::default();
let _network1_idx = multi_model.add_network("network1", network);
let network = Network::default();
let result = multi_model.add_network("network1", network);

assert!(result.is_err());
}
}