Utils Module

The Utils contains classes and functions related to basic data structure implementations in WaterPaths such as vectors, matrices, and graphs. It also defines a quadratic programming solver.

API Reference

Below is the API reference for the Utils submodule.

Submodule Components

Constants.h

namespace Constants

DataSeries.h

class DataSeries : public ControlRules
#include <DataSeries.h>

The DataSeries subclass that extends the ControlRules class by providing detailed representation for a series of data points.

Created by bernardoct on 6/21/17.

Public Functions

DataSeries(vector<double> *series_x, vector<double> *series_y)

Constructs a DataSeries object by initializing it with x and y data series. Ensures that the lengths of the independent (x) and dependent (y) series match.

Parameters:
  • series_x – Pointer to a vector<double> representing the x-values (independent variable).

  • series_y – Pointer to a vector<double> representing the y-values (dependent variable).

Throws:

std::invalid_argument – if the lengths of series_x and series_y are not equal.

const vector<double> &getSeries_x() const

Retrieves a constant reference to the x-values (independent variable) of the data series.

Returns:

A constant reference to the vector<double> containing the x-values.

virtual double get_dependent_variable(double x) override

Retrieves the dependent variable (y) corresponding to a given independent variable (x) using interpolation. If the data series contains only one point, it returns that single point.

This function overrides the get_dependent_variable method from the ControlRules class.

Parameters:

x – The value of the independent variable (x) for which the dependent variable (y) is to be calculated.

Returns:

double

Returns:

The interpolated or directly matched value of the dependent variable (y).

virtual double get_dependent_variable(int x) override

Throws an exception if called with an integer argument. This function prevents misuse by disallowing calls with an integer x for get_dependent_variable.

This function overrides the get_dependent_variable method from the ControlRules class.

Parameters:

x – An integer value that is not supported as input for this function.

Throws:

std::invalid_argument – Always thrown, with a message indicating that integers are not allowed.

Returns:

double

Public Members

const unsigned long length

The length of the DataSeries.

Private Functions

virtual double get_dependent_variable(double x, int week) override

Throws an exception if called with an double x argument and integer week argument. This function prevents misuse by disallowing calls with an double x or integer week.

This function overrides the get_dependent_variable method from the ControlRules class.

Parameters:
  • x – A double value that is not supported as input for this function.

  • week – An integer value that is not supported as input for this function.

Throws:

std::invalid_argument – Always thrown, with a message indicating that two parameters are not allowed.

Returns:

double

virtual double get_dependent_variable(int x, int week) override

Throws an exception if called with an integer x argument and integer week argument. This function prevents misuse by disallowing calls with an integer x or integer week.

This function overrides the get_dependent_variable method from the ControlRules class.

Parameters:
  • x – An integer value that is not supported as input for this function.

  • week – An integer value that is not supported as input for this function.

Throws:

std::invalid_argument – Always thrown, with a message indicating that two parameters are not allowed.

Returns:

double

Private Members

vector<double> *series_x

A vector of independent x-variable values.

vector<double> *series_y

A vector of dependent y-variable values.

Matrices.h

template<typename T>
class Matrix2D
#include <Matrices.h>

Public Functions

Matrix2D()

Default constructor for a new Matrix 2 D< T>:: Matrix 2 D object.

Template Parameters:

T – The datatype stored in the 2D matrix.

Matrix2D(int di, int dj)

Construct a new Matrix 2 D< T>:: Matrix 2 D object with specified dimensions.

Template Parameters:

T – The datatype stored in the 2D matrix.

Parameters:
  • di – The number of rows in the matrix.

  • dj – The number of columns in the matrix.

Throws:

length_error – If either di or dj are 0.

T &operator()(int i, int j)

a subscript operator that returns a reference to the element at position (i, j) in the matrix.

Template Parameters:

T – The datatype stored in the 2D matrix.

Parameters:
  • i – The row index.

  • j – The column index.

Throws:

length_error – If the indices are out of bounds.

Returns:

T&

T operator()(int i, int j) const

a subscript operator that returns a reference to the element at position (i, j) in the matrix without changing the original matrix.

Template Parameters:

T – The datatype stored in the 2D matrix.

Parameters:
  • i – The row index.

  • j – The column index.

Throws:

length_error – If the indices are out of bounds.

Returns:

T&

~Matrix2D()

Destructor for a Matrix 2 D< T>:: Matrix 2 D object.

Template Parameters:

T – The datatype stored in the 2D matrix.

Matrix2D(const Matrix2D &m)

Copy constructor for a new Matrix 2 D< T>:: Matrix 2 D object by copying another matrix.

Template Parameters:

T – The datatype stored in the 2D matrix.

Parameters:

m – The matrix to be copied.

Throws:

length_error – If either di or dj of the original matrix are 0.

Matrix2D<T> &operator=(const Matrix2D<T> &m)

Assignment operator for a Matrix 2 D< T>:: Matrix 2 D object. This operator copies the data from another matrix to this matrix, assigning the values in the original matrix to this matrix.

Template Parameters:

T – The datatype stored in the 2D matrix.

Parameters:

m – The matrix to be copied.

Returns:

Matrix2D<T>&

Matrix2D<T> &operator+=(const Matrix2D<T> &m)

In-place addition operator that adds each element in the matrix to the corresponding element in another matrix.

Template Parameters:

T – The datatype stored in the 2D matrix.

Parameters:

m – The matrix to be added to the current matrix.

Throws:

length_error – If the dimensions of the two matrices are different.

Returns:

Matrix2D<T>&

Matrix2D<T> &operator/(const double m)

Division operator that divides each element in the matrix by a scalar.

Template Parameters:

T – The datatype stored in the 2D matrix.

Parameters:

n – The constant used to divide each element in the matrix.

Returns:

Matrix2D<T>&

void reset(T value)

Set all elements in the matrix to a specific value.

Template Parameters:

T – The datatype stored in the 2D matrix.

Parameters:

value – The value to which all elements in the matrix will be set.

Returns:

void

void print(int i) const

Print the i-th row of the matrix.

Template Parameters:

T – The datatype stored in the 2D matrix.

Parameters:

i – The row index.

Returns:

void

int get_i()

Get the number of rows in the matrix.

Template Parameters:

T – The datatype stored in the 2D matrix.

Returns:

int

int get_j()

Get the number of columns in the matrix.

Template Parameters:

T – The datatype stored in the 2D matrix.

Returns:

int

bool empty()

A flag to indicate if the matrix has been initialized.

Template Parameters:

T – The datatype stored in the 2D matrix.

Returns:

True if the matrix has not been initialized, false otherwise.

void setPartialData(int i, T *data, unsigned long length)

Set a portion of the matrix to specific values provided by the data.

Template Parameters:

T – The datatype stored in the 2D matrix.

Parameters:
  • i – The row index where the data will be set.

  • data – The data to be set.

  • length – The length of the data.

Throws:

length_error – If the indices are out of bounds.

Returns:

void

void setData(T *data, int length)

Set all elements in the matrix to specific values provided by the data.

Template Parameters:

T – The datatype stored in the 2D matrix.

Parameters:

value – The value to which all elements in the matrix will be set.

Throws:

throw_with_nested – If the size of the data does not match the size of the matrix.

Returns:

void

T *getPointerToElement(int i, int j) const

Get the memory address of the element at position (i, j) in the matrix.

Template Parameters:

T – The datatype stored in the 2D matrix.

Parameters:
  • i – The row index.

  • j – The column index.

Returns:

T*

void add_to_position(int i, int j, T *data, int length)

Adds a sequence of values to a specified position in a 2D matrix.

Template Parameters:

T – The datatype stored in the 2D matrix.

Parameters:
  • i – The row index.

  • j – The column index.

  • data – A pointer to the array of values to be added.

  • length – The length of the data array.

const vector<vector<T>> get_vector() const

Converts the 2D matrix into a nested vector.

Template Parameters:

T – The datatype stored in the 2D matrix.

Returns:

const vector<vector<T>>

Private Members

int di_

The number of rows in the matrix.

int dj_

The number of columns in the matrix.

unique_ptr<T[]> data_

The data of the matrix.

bool not_initialized = true

A flag to indicate if the matrix has been initialized.

template<typename T>
class Matrix3D
#include <Matrices.h>

Public Functions

Matrix3D()

A default constructor for a new Matrix 3D< T>:: Matrix 3D object.

Template Parameters:

T – The datatype stored in the 3D matrix.

Matrix3D(int di, int dj, int dk)

Construct a new Matrix 3D< T>:: Matrix 3D object with specified dimensions.

Template Parameters:

T – The datatype stored in the 3D matrix.

Parameters:
  • di – The number of rows in the matrix.

  • dj – The number of columns in the matrix.

  • dk – The number of slices in the matrix.

Throws:

length_error – If either di, dj, or dk are 0.

T &operator()(int i, int j, int k)

A subscript operator that returns a reference to the element at position (i, j, k) in the matrix.

Template Parameters:

T – The datatype stored in the 3D matrix.

Parameters:
  • i – the row index.

  • j – The column index.

  • k – The slice index.

Throws:

length_error – If the indices are out of bounds.

Returns:

T&

T operator()(int di, int dj, int dk) const

A subscript operator that returns a reference to the element at position (i, j, k) in the matrix without changing the original matrix.

Template Parameters:

T – The datatype stored in the 3D matrix.

Parameters:
  • i – the row index.

  • j – The column index.

  • k – The slice index.

Throws:

length_error – If the indices are out of bounds.

Returns:

T

~Matrix3D()

Destroy the Matrix 3D< T>:: Matrix 3D object.

Template Parameters:

T – The datatype stored in the 3D matrix.

Matrix3D(const Matrix3D &m)

Copy constructor for a new Matrix 3D< T>:: Matrix 3D object.

Template Parameters:

T – The datatype stored in the 3D matrix.

Parameters:

m – The Matrix3D object to be copied.

Throws:

length_error – If either di, dj, or dk of the original matrix are 0.

Matrix3D<T> &operator=(const Matrix3D<T> &m)

Assignment operator for a Matrix 3D< T>:: Matrix 3D object. This operator copies the data from another matrix to this matrix, assigning the values in the original matrix to this matrix.

Template Parameters:

T – The datatype stored in the 3D matrix.

Parameters:

m – The matrix to be copied.

Returns:

Matrix3D<T>&

Matrix3D<T> &operator+=(const Matrix3D<T> &m)

In-place addition operator that adds each element in the matrix to the corresponding element in another matrix.

Template Parameters:

T – The datatype stored in the 3D matrix.

Parameters:

m – The matrix to be added to the current matrix.

Throws:

length_error – If the dimensions of the two matrices are different.

Returns:

Matrix3D<T>&

Matrix3D<T> &operator/(const double m)

Division operator that divides each element in the matrix by a scalar.

Template Parameters:

T – The datatype stored in the 3D matrix.

Parameters:

n – The constant used to divide each element in the matrix.

Returns:

Matrix3D<T>&

Matrix2D<T> get2D(int ijk, char dim)

Extract a 2D slice from the 3D matrix along the specified dimension.

See also

setData

Template Parameters:

T – The datatype stored in the 3D matrix.

Parameters:
  • ijk – The index along the selected dimension from which the slice is taken.

  • dim – The dimension along which the slice is extracted (‘i’, ‘j’, or ‘k’).

Returns:

Matrix2D<T>

void add_to_position(int i, int j, int k, T *data, int length)

Adds a sequence of values to a specified position in a 3D matrix.

Template Parameters:

T – The datatype stored in the 3D matrix.

Parameters:
  • i – The row index.

  • j – The column index.

  • k – The slice index.

  • data – A pointer to the array of values to be added.

  • length – The number of elements in the data array.

Returns:

void

void setPartialData(int i, int j, T *data, int length)

Set a subset of data at a specific position in the matrix.

Template Parameters:

T – The datatype stored in the 3D matrix.

Parameters:
  • i – The row index where the data will be set.

  • data – The data to be set.

  • length – The length of the data.

Throws:

length_error – If the indices are out of bounds.

Returns:

void

T *getPointerToElement(int i, int j, int k) const

Gets the memory adddress of the element at position (i, j, k) in the matrix.

Template Parameters:

T – The datatype stored in the 3D matrix.

Parameters:
  • i – The row index.

  • j – The column index.

  • k – The slice index.

Returns:

T*

void reset(T value)

Resets all elements in the matrix to a specific value.

Template Parameters:

T – The datatype stored in the 3D matrix.

Parameters:

value – The value to which all elements in the matrix will be set.

Returns:

void

void print(int i) const

Print the contents of the i-th slice of the matrix.

Template Parameters:

T – The datatype stored in the 3D matrix.

Parameters:

i – The row index.

Returns:

void

void setData(T *data, int length)

Set all elements in the matrix to specific values provided by the data.

Template Parameters:

T – The datatype stored in the 3D matrix.

Parameters:

value – The value to which all elements in the matrix will be set.

Throws:

throw_with_nested – If the size of the data does not match the size of the matrix.

Returns:

void

int get_i() const

Gets the number of slices in the matrix.

Template Parameters:

T – The datatype stored in the 3D matrix.

Returns:

int

int get_j() const

Gets the number of rows in the matrix.

Template Parameters:

T – The datatype stored in the 3D matrix.

Returns:

int

int get_k() const

Gets the number of columns in the matrix.

Template Parameters:

T – The datatype stored in the 3D matrix.

Returns:

int

bool empty() const

Check if the matrix has been initialized.

Template Parameters:

T – The datatype stored in the 3D matrix.

Returns:

True if the matrix has not been initialized, false otherwise.

Private Members

int di_ = NON_INITIALIZED

The number of rows in the matrix.

int dj_ = NON_INITIALIZED

The number of columns in the matrix.

int dk_ = NON_INITIALIZED

The number of slices in the matrix.

unique_ptr<T[]> data_

ObjectivesCalculator.h

class ObjectivesCalculator
#include <ObjectivesCalculator.h>

The ObjectivesCalculator class calculates the objectives of the model based on the data collected during the simulation.

Created by bernardoct on 8/25/17.

Public Static Functions

static double calculateReliabilityObjective(const vector<UtilitiesDataCollector*> &utility_collector, vector<unsigned long> realizations = vector<unsigned long>(0))

Calculates the reliability objective based on storage capacity ratios. The reliability objective is defined as 1 minus the maximum annual failure ratio across realizations.

Parameters:
  • utility_collectorVector of UtilitiesDataCollector pointers containing utility data for all realizations.

  • realizationsVector of realization indices to be evaluated. If empty, evaluates all realizations.

Throws:

std::logic_error – if the objective value is infinite.

Returns:

The calculated reliability objective as a double.

static double calculateRestrictionFrequencyObjective(const vector<RestrictionsDataCollector*> &restriction_data, vector<unsigned long> realizations = vector<unsigned long>(0))

Calculates the restriction frequency objective. The restriction frequency objective measures the average ratio of years with restrictions to total years across all realizations.

Parameters:
  • restriction_dataVector of RestrictionsDataCollector pointers containing restriction data for all realizations.

  • realizationsVector of realization indices to be evaluated. If empty, evaluates all realizations.

Throws:

std::logic_error – if the objective value is infinite.

Returns:

The calculated restriction frequency objective as a double.

static double calculateNetPresentCostInfrastructureObjective(const vector<UtilitiesDataCollector*> &utility_data, vector<unsigned long> realizations = vector<unsigned long>(0))

Calculates the net present cost (NPC) of infrastructure. This objective averages the total NPC across all realizations.

Parameters:
  • utility_dataVector of UtilitiesDataCollector pointers containing utility data for all realizations.

  • realizationsVector of realization indices to be evaluated. If empty, evaluates all realizations.

Returns:

The average NPC as a double.

static double calculatePeakFinancialCostsObjective(const vector<UtilitiesDataCollector*> &utility_data, vector<unsigned long> realizations = vector<unsigned long>(0))

Calculates the peak financial costs objective. This objective is based on the maximum annual financial cost ratio across all realizations. It will also print a statement if the total financial cost is absurdly high (>10^10).

Parameters:
  • utility_dataVector of UtilitiesDataCollector pointers containing utility data for all realizations.

  • realizationsVector of realization indices to be evaluated. If empty, evaluates all realizations.

Throws:

std::logic_error – if the objective value is infinite.

Returns:

The average peak financial cost as a double.

static double calculateWorseCaseCostsObjective(const vector<UtilitiesDataCollector*> &utility_data, vector<unsigned long> realizations = vector<unsigned long>(0))

Calculates the worst-case financial costs objective. The worst-case cost is defined as the financial cost at the specified worst-case percentile across all realizations.

Parameters:
  • utility_dataVector of UtilitiesDataCollector pointers containing utility data for all realizations.

  • realizationsVector of realization indices to be evaluated. If empty, evaluates all realizations.

Throws:

std::logic_error – if the objective value is infinite.

Returns:

The worst-case financial cost as a double.

static double calculateUnitTotalCostObjective(const vector<UtilitiesDataCollector*> &utility_data, vector<unsigned long> realizations = vector<unsigned long>(0))

Calculates the unit total cost objective. This objective is based on the ratio of infrastructure cost to total water demand, normalized by the first-year demand. The unit cost output is in $mil/MGD that should be converted to $/kGal for comparison with other objectives.

Parameters:
  • utility_dataVector of UtilitiesDataCollector pointers containing utility data for all realizations.

  • realizationsVector of realization indices to be evaluated. If empty, evaluates all realizations.

Returns:

The average unit total cost as a double.

static double calculateNetPresentCostInfrastructureObjectiveForVariableDebtService(const vector<UtilitiesDataCollector*> &utility_data, vector<unsigned long> realizations = vector<unsigned long>(0))

Calculates the net present cost (NPC) for variable debt service. This objective averages the total NPC for variable debt service across all realizations.

Parameters:
  • utility_dataVector of UtilitiesDataCollector pointers containing utility data for all realizations.

  • realizationsVector of realization indices to be evaluated. If empty, evaluates all realizations.

Returns:

The average NPC for variable debt service as a double.

Solutions.h

namespace Solutions

Utils.h

class Utils
#include <Utils.h>

The Utils class defines a set of utility functions that are used throughout the model.

Created by bernardo on 1/13/17.

Public Static Functions

static vector<vector<double>> parse2DCsvFile(basic_string<char, char_traits<char>, allocator<char>> file_name, unsigned long max_lines = 10000000, vector<unsigned long> rows_to_read = vector<unsigned long>())

Reads a CSV file into a 2D vector of doubles. This function parses the contents of a CSV file and returns it as a 2D vector, optionally reading a limited number of lines or specific rows.

Parameters:
  • file_name – The full path of the input CSV file.

  • max_lines – The maximum number of lines to read from the file.

  • rows_to_read – Optional; a vector of row indices to read from the file.

Throws:

std::invalid_argument – if the file is not found or appears to be space-separated.

Returns:

A vector of vectors containing the parsed data as doubles.

static vector<double> parse1DCsvFile(basic_string<char, char_traits<char>, allocator<char>> file_name, unsigned long max_lines = 10000000, vector<unsigned long> rows_to_read = vector<unsigned long>())

Reads a CSV file into a 1D vector of doubles. Parses a CSV file and extracts its data into a 1D vector with optional row filtering.

Parameters:
  • file_name – The full path of the input CSV file.

  • max_lines – The maximum number of lines to read from the file.

  • rows_to_read – Optional; a vector of row indices to read from the file.

Throws:

std::invalid_argument – if the file cannot be read.

Returns:

A vector containing the parsed data as doubles.

static vector<WaterSource*> copyWaterSourceVector(vector<WaterSource*> water_sources_original)

Creates a copy of a vector of WaterSource objects. This function deep copies water source objects based on their derived types.

Parameters:

water_sources_original – The original vector of WaterSource pointers.

Throws:

std::invalid_argument – if a water source type is not implemented.

Returns:

A new vector containing deep copies of the input water sources.

static vector<Utility*> copyUtilityVector(vector<Utility*> utility_original, bool clear_water_sources = false)

Creates a copy of a vector of Utility objects. Optionally clears water sources in the copied utilities.

Parameters:
  • utility_original – The original vector of Utility pointers.

  • clear_water_sources – Whether to clear water sources in the copied utilities.

Returns:

A new vector containing deep copies of the input utilities.

static vector<DroughtMitigationPolicy*> copyDroughtMitigationPolicyVector(vector<DroughtMitigationPolicy*> drought_mitigation_policy_original)

Creates a copy of a vector of DroughtMitigationPolicy objects. This function duplicates drought mitigation policies based on their derived types.

Parameters:

drought_mitigation_policy_original – The original vector of DroughtMitigationPolicy pointers.

Returns:

A new vector containing deep copies of the input policies.

static vector<MinEnvFlowControl*> copyMinEnvFlowControlVector(vector<MinEnvFlowControl*> min_env_flow_controls_original)

Creates a copy of a vector of MinEnvFlowControl objects. This function duplicates a vector of environmental flow controls based on their specific derived types.

Parameters:

min_env_flow_controls_original – The original vector of MinEnvFlowControl pointers.

Throws:

std::invalid_argument – if a control type is not implemented.

Returns:

A new vector containing deep copies of the input objects.

static bool isFirstWeekOfTheYear(int week)

Determines if a given week corresponds to the first week of the year.

Parameters:

week – The week number to check.

Returns:

True if the given week is the first week of the year; otherwise, false.

static int weekOfTheYear(int week)

Returns the week of the year for a given week index.

Parameters:

week – The week number to process.

Returns:

The corresponding week of the year.

static void removeIntFromVector(vector<int> &vec, int el)

Deletes a specified element from an integer vector.

Parameters:
  • vec – The vector from which to remove the element.

  • el – The integer value to be removed.

Returns:

void

static void print_exception(const exception &e, int level = 0)

Prints details of an exception with nesting levels. Recursively prints exception messages and nested exceptions.

Parameters:
  • e – The exception to be printed.

  • level – The current nesting level for formatting purposes.

Returns:

void

static vector<Bond*> copyBonds(vector<Bond*> bonds_original)

Creates a copy of a vector of Bond objects. This function deep copies bond objects based on their derived types.

Parameters:

bonds_original – The original vector of Bond pointers.

Throws:

std::invalid_argument – if a bond type is not implemented.

Returns:

A new vector containing deep copies of the input bonds.

static void createDir(string directory)

Creates a directory at the specified path.

Parameters:

directory – The path of the directory to create.

Returns:

void