Compare commits

..

5 Commits

Author SHA1 Message Date
AlessandroBregoli 87da2a7c9e Added doctest for parameter_learning 2 years ago
AlessandroBregoli 21ce0ffcb0 Added doc to: params, process, parameter_learning, ctmp, ctbn 2 years ago
Alessandro Bregoli d66173b961 Added doctest for ctmp 2 years ago
Alessandro Bregoli f176dd4fae Added logging to ctmp 2 years ago
AlessandroBregoli bfec2c7c60 Added log to params 2 years ago
  1. 176
      LICENSE-APACHE
  2. 23
      LICENSE-MIT
  3. 8
      README.md
  4. 1
      reCTBN/Cargo.toml
  5. 195
      reCTBN/src/parameter_learning.rs
  6. 69
      reCTBN/src/params.rs
  7. 14
      reCTBN/src/process.rs
  8. 12
      reCTBN/src/process/ctbn.rs
  9. 77
      reCTBN/src/process/ctmp.rs

@ -1,176 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product 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 NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of 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 reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

@ -1,23 +0,0 @@
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:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
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.

@ -64,11 +64,3 @@ To generate the **documentation**:
```sh ```sh
cargo rustdoc --package reCTBN --open -- --default-theme=ayu cargo rustdoc --package reCTBN --open -- --default-theme=ayu
``` ```
## License
This software is distributed under the terms of both the Apache License
(Version 2.0) and the MIT license.
See [LICENSE-APACHE](./LICENSE-APACHE) and [LICENSE-MIT](./LICENSE-MIT) for
details.

@ -15,6 +15,7 @@ statrs = "~0.16"
rand_chacha = "~0.3" rand_chacha = "~0.3"
itertools = "~0.10" itertools = "~0.10"
rayon = "~1.6" rayon = "~1.6"
log = "~0.4"
[dev-dependencies] [dev-dependencies]
approx = { package = "approx", version = "~0.5" } approx = { package = "approx", version = "~0.5" }

@ -7,7 +7,17 @@ use ndarray::prelude::*;
use crate::params::*; use crate::params::*;
use crate::{process, tools::Dataset}; use crate::{process, tools::Dataset};
/// It defines the required methods for learn the `Parameters` from data.
pub trait ParameterLearning: Sync { pub trait ParameterLearning: Sync {
/// Fit the parameter of the `node` over a `dataset` given a `parent_set`
///
/// # Arguments
///
/// * `net`: a `NetworkProcess` instance
/// * `dataset`: a dataset compatible with `net` used for computing the sufficient statistics
/// * `node`: the node index for which we want to compute the sufficient statistics
/// * `parent_set`: an `Option` containing the parent set used for computing the parameters of
/// `node`. If `None`, the parent set defined in `net` will be used.
fn fit<T: process::NetworkProcess>( fn fit<T: process::NetworkProcess>(
&self, &self,
net: &T, net: &T,
@ -17,6 +27,19 @@ pub trait ParameterLearning: Sync {
) -> Params; ) -> Params;
} }
/// Compute the sufficient statistics of a parameters computed from a dataset
///
/// # Arguments
///
/// * `net`: a `NetworkProcess` instance
/// * `dataset`: a dataset compatible with `net` used for computing the sufficient statistics
/// * `node`: the node index for which we want to compute the sufficient statistics
/// * `parent_set`: the set of nodes (identified by indices) we want to use as parents of `node`
///
/// # Return
///
/// * A tuple containing the number of transitions (`Array3<usize>`) and the residence time
/// (`Array2<f64>`).
pub fn sufficient_statistics<T: process::NetworkProcess>( pub fn sufficient_statistics<T: process::NetworkProcess>(
net: &T, net: &T,
dataset: &Dataset, dataset: &Dataset,
@ -70,6 +93,89 @@ pub fn sufficient_statistics<T: process::NetworkProcess>(
return (M, T); return (M, T);
} }
/// Maximum Likelihood Estimation method for learning the parameters given a dataset.
///
/// # Example
/// ```rust
///
/// use std::collections::BTreeSet;
/// use reCTBN::process::NetworkProcess;
/// use reCTBN::params;
/// use reCTBN::process::ctbn::*;
/// use ndarray::arr3;
/// use reCTBN::tools::*;
/// use reCTBN::parameter_learning::*;
/// use approx::AbsDiffEq;
///
/// //Create the domain for a discrete node
/// let mut domain = BTreeSet::new();
/// domain.insert(String::from("A"));
/// domain.insert(String::from("B"));
///
/// //Create the parameters for a discrete node using the domain
/// let param = params::DiscreteStatesContinousTimeParams::new("X1".to_string(), domain);
///
/// //Create the node using the parameters
/// let X1 = params::Params::DiscreteStatesContinousTime(param);
///
/// let mut domain = BTreeSet::new();
/// domain.insert(String::from("A"));
/// domain.insert(String::from("B"));
/// let param = params::DiscreteStatesContinousTimeParams::new("X2".to_string(), domain);
/// let X2 = params::Params::DiscreteStatesContinousTime(param);
///
/// //Initialize a ctbn
/// let mut net = CtbnNetwork::new();
///
/// //Add nodes
/// let X1 = net.add_node(X1).unwrap();
/// let X2 = net.add_node(X2).unwrap();
///
/// //Add an edge
/// net.add_edge(X1, X2);
///
/// //Add the CIMs for each node
/// match &mut net.get_node_mut(X1) {
/// params::Params::DiscreteStatesContinousTime(param) => {
/// assert_eq!(Ok(()), param.set_cim(arr3(&[[[-0.1, 0.1], [1.0, -1.0]]])));
/// }
/// }
/// match &mut net.get_node_mut(X2) {
/// params::Params::DiscreteStatesContinousTime(param) => {
/// assert_eq!(
/// Ok(()),
/// param.set_cim(arr3(&[
/// [[-0.01, 0.01], [5.0, -5.0]],
/// [[-5.0, 5.0], [0.01, -0.01]]
/// ]))
/// );
/// }
/// }
///
/// //Generate a synthetic dataset from net
/// let data = trajectory_generator(&net, 100, 100.0, Some(6347747169756259));
///
/// //Initialize the `struct MLE`
/// let pl = MLE{};
///
/// // Fit the parameters for X2
/// let p = match pl.fit(&net, &data, X2, None) {
/// params::Params::DiscreteStatesContinousTime(p) => p,
/// };
///
/// // Check the shape of the CIM
/// assert_eq!(p.get_cim().as_ref().unwrap().shape(), [2, 2, 2]);
///
/// // Check if the learned parameters are close enough to the real ones.
/// assert!(p.get_cim().as_ref().unwrap().abs_diff_eq(
/// &arr3(&[
/// [[-0.01, 0.01], [5.0, -5.0]],
/// [[-5.0, 5.0], [0.01, -0.01]]
/// ]),
/// 0.1
/// ));
/// ```
pub struct MLE {} pub struct MLE {}
impl ParameterLearning for MLE { impl ParameterLearning for MLE {
@ -114,6 +220,95 @@ impl ParameterLearning for MLE {
} }
} }
/// Bayesian Approach for learning the parameters given a dataset.
///
/// # Arguments
///
/// `alpha`: hyperparameter for the priori over the number of transitions.
/// `tau`: hyperparameter for the priori over the residence time.
///
/// # Example
///
/// ```rust
///
/// use std::collections::BTreeSet;
/// use reCTBN::process::NetworkProcess;
/// use reCTBN::params;
/// use reCTBN::process::ctbn::*;
/// use ndarray::arr3;
/// use reCTBN::tools::*;
/// use reCTBN::parameter_learning::*;
/// use approx::AbsDiffEq;
///
/// //Create the domain for a discrete node
/// let mut domain = BTreeSet::new();
/// domain.insert(String::from("A"));
/// domain.insert(String::from("B"));
///
/// //Create the parameters for a discrete node using the domain
/// let param = params::DiscreteStatesContinousTimeParams::new("X1".to_string(), domain);
///
/// //Create the node using the parameters
/// let X1 = params::Params::DiscreteStatesContinousTime(param);
///
/// let mut domain = BTreeSet::new();
/// domain.insert(String::from("A"));
/// domain.insert(String::from("B"));
/// let param = params::DiscreteStatesContinousTimeParams::new("X2".to_string(), domain);
/// let X2 = params::Params::DiscreteStatesContinousTime(param);
///
/// //Initialize a ctbn
/// let mut net = CtbnNetwork::new();
///
/// //Add nodes
/// let X1 = net.add_node(X1).unwrap();
/// let X2 = net.add_node(X2).unwrap();
///
/// //Add an edge
/// net.add_edge(X1, X2);
///
/// //Add the CIMs for each node
/// match &mut net.get_node_mut(X1) {
/// params::Params::DiscreteStatesContinousTime(param) => {
/// assert_eq!(Ok(()), param.set_cim(arr3(&[[[-0.1, 0.1], [1.0, -1.0]]])));
/// }
/// }
/// match &mut net.get_node_mut(X2) {
/// params::Params::DiscreteStatesContinousTime(param) => {
/// assert_eq!(
/// Ok(()),
/// param.set_cim(arr3(&[
/// [[-0.01, 0.01], [5.0, -5.0]],
/// [[-5.0, 5.0], [0.01, -0.01]]
/// ]))
/// );
/// }
/// }
///
/// //Generate a synthetic dataset from net
/// let data = trajectory_generator(&net, 100, 100.0, Some(6347747169756259));
///
/// //Initialize the `struct BayesianApproach`
/// let pl = BayesianApproach{alpha: 1, tau: 1.0};
///
/// // Fit the parameters for X2
/// let p = match pl.fit(&net, &data, X2, None) {
/// params::Params::DiscreteStatesContinousTime(p) => p,
/// };
///
/// // Check the shape of the CIM
/// assert_eq!(p.get_cim().as_ref().unwrap().shape(), [2, 2, 2]);
///
/// // Check if the learned parameters are close enough to the real ones.
/// assert!(p.get_cim().as_ref().unwrap().abs_diff_eq(
/// &arr3(&[
/// [[-0.01, 0.01], [5.0, -5.0]],
/// [[-5.0, 5.0], [0.01, -0.01]]
/// ]),
/// 0.1
/// ));
/// ```
pub struct BayesianApproach { pub struct BayesianApproach {
pub alpha: usize, pub alpha: usize,
pub tau: f64, pub tau: f64,

@ -3,6 +3,7 @@
use std::collections::BTreeSet; use std::collections::BTreeSet;
use enum_dispatch::enum_dispatch; use enum_dispatch::enum_dispatch;
use log::{debug, error, trace, warn};
use ndarray::prelude::*; use ndarray::prelude::*;
use rand::Rng; use rand::Rng;
use rand_chacha::ChaCha8Rng; use rand_chacha::ChaCha8Rng;
@ -29,6 +30,7 @@ pub enum StateType {
/// methods required to describes a generic node. /// methods required to describes a generic node.
#[enum_dispatch(Params)] #[enum_dispatch(Params)]
pub trait ParamsTrait { pub trait ParamsTrait {
///Reset the parameters
fn reset_params(&mut self); fn reset_params(&mut self);
/// Randomly generate a possible state of the node disregarding the state of the node and it's /// Randomly generate a possible state of the node disregarding the state of the node and it's
@ -98,6 +100,7 @@ pub struct DiscreteStatesContinousTimeParams {
impl DiscreteStatesContinousTimeParams { impl DiscreteStatesContinousTimeParams {
pub fn new(label: String, domain: BTreeSet<String>) -> DiscreteStatesContinousTimeParams { pub fn new(label: String, domain: BTreeSet<String>) -> DiscreteStatesContinousTimeParams {
debug!("Creation of node {}", label);
DiscreteStatesContinousTimeParams { DiscreteStatesContinousTimeParams {
label, label,
domain, domain,
@ -109,6 +112,7 @@ impl DiscreteStatesContinousTimeParams {
/// Getter function for CIM /// Getter function for CIM
pub fn get_cim(&self) -> &Option<Array3<f64>> { pub fn get_cim(&self) -> &Option<Array3<f64>> {
debug!("Getting cim from node {}", self.label);
&self.cim &self.cim
} }
@ -119,10 +123,12 @@ impl DiscreteStatesContinousTimeParams {
/// * **Invalid CIM inserted** - it replaces the `self.cim` value with `None` and it returns /// * **Invalid CIM inserted** - it replaces the `self.cim` value with `None` and it returns
/// `ParamsError`. /// `ParamsError`.
pub fn set_cim(&mut self, cim: Array3<f64>) -> Result<(), ParamsError> { pub fn set_cim(&mut self, cim: Array3<f64>) -> Result<(), ParamsError> {
debug!("Setting cim for node {}", self.label);
self.cim = Some(cim); self.cim = Some(cim);
match self.validate_params() { match self.validate_params() {
Ok(()) => Ok(()), Ok(()) => Ok(()),
Err(e) => { Err(e) => {
warn!("Validation cim faild for node {}", self.label);
self.cim = None; self.cim = None;
Err(e) Err(e)
} }
@ -131,39 +137,54 @@ impl DiscreteStatesContinousTimeParams {
/// Unchecked version of the setter function for CIM. /// Unchecked version of the setter function for CIM.
pub fn set_cim_unchecked(&mut self, cim: Array3<f64>) { pub fn set_cim_unchecked(&mut self, cim: Array3<f64>) {
debug!("Setting cim (unchecked) for node {}", self.label);
self.cim = Some(cim); self.cim = Some(cim);
} }
/// Getter function for transitions. /// Getter function for transitions.
pub fn get_transitions(&self) -> &Option<Array3<usize>> { pub fn get_transitions(&self) -> &Option<Array3<usize>> {
debug!("Get transitions from node {}", self.label);
&self.transitions &self.transitions
} }
/// Setter function for transitions. /// Setter function for transitions.
pub fn set_transitions(&mut self, transitions: Array3<usize>) { pub fn set_transitions(&mut self, transitions: Array3<usize>) {
debug!("Set transitions for node {}", self.label);
self.transitions = Some(transitions); self.transitions = Some(transitions);
} }
/// Getter function for residence_time. /// Getter function for residence_time.
pub fn get_residence_time(&self) -> &Option<Array2<f64>> { pub fn get_residence_time(&self) -> &Option<Array2<f64>> {
debug!("Get residence time from node {}", self.label);
&self.residence_time &self.residence_time
} }
/// Setter function for residence_time. /// Setter function for residence_time.
pub fn set_residence_time(&mut self, residence_time: Array2<f64>) { pub fn set_residence_time(&mut self, residence_time: Array2<f64>) {
debug!("Set residence time for node {}", self.label);
self.residence_time = Some(residence_time); self.residence_time = Some(residence_time);
} }
} }
impl ParamsTrait for DiscreteStatesContinousTimeParams { impl ParamsTrait for DiscreteStatesContinousTimeParams {
fn reset_params(&mut self) { fn reset_params(&mut self) {
debug!(
"Setting cim, transitions and residence_time to None for node {}",
self.label
);
self.cim = Option::None; self.cim = Option::None;
self.transitions = Option::None; self.transitions = Option::None;
self.residence_time = Option::None; self.residence_time = Option::None;
} }
fn get_random_state_uniform(&self, rng: &mut ChaCha8Rng) -> StateType { fn get_random_state_uniform(&self, rng: &mut ChaCha8Rng) -> StateType {
StateType::Discrete(rng.gen_range(0..(self.domain.len()))) let state = StateType::Discrete(rng.gen_range(0..(self.domain.len())));
trace!(
"Generate random state uniform. Node: {} - State: {:?}",
self.get_label(),
&state
);
return state;
} }
fn get_random_residence_time( fn get_random_residence_time(
@ -179,11 +200,20 @@ impl ParamsTrait for DiscreteStatesContinousTimeParams {
Option::Some(cim) => { Option::Some(cim) => {
let lambda = cim[[u, state, state]] * -1.0; let lambda = cim[[u, state, state]] * -1.0;
let x: f64 = rng.gen_range(0.0..=1.0); let x: f64 = rng.gen_range(0.0..=1.0);
Ok(-x.ln() / lambda) let ret = -x.ln() / lambda;
trace!(
"Generate random residence time. Node: {} - Time: {}",
self.get_label(),
ret
);
Ok(ret)
} }
Option::None => Err(ParamsError::ParametersNotInitialized(String::from( Option::None => {
warn!("Cim not initialized for node {}", self.get_label());
Err(ParamsError::ParametersNotInitialized(String::from(
"CIM not initialized", "CIM not initialized",
))), )))
}
} }
} }
@ -220,11 +250,21 @@ impl ParamsTrait for DiscreteStatesContinousTimeParams {
next_state.0 + 1 next_state.0 + 1
}; };
Ok(StateType::Discrete(next_state)) let next_state = StateType::Discrete(next_state);
trace!(
"Generate random state. Node: {} - State: {:?}",
self.get_label(),
next_state
);
Ok(next_state)
} }
Option::None => Err(ParamsError::ParametersNotInitialized(String::from( Option::None => {
warn!("Cim not initialized for node {}", self.get_label());
Err(ParamsError::ParametersNotInitialized(String::from(
"CIM not initialized", "CIM not initialized",
))), )))
}
} }
} }
@ -243,6 +283,7 @@ impl ParamsTrait for DiscreteStatesContinousTimeParams {
// Check if the cim is initialized // Check if the cim is initialized
if let None = self.cim { if let None = self.cim {
warn!("Cim not initialized for node {}", self.get_label());
return Err(ParamsError::ParametersNotInitialized(String::from( return Err(ParamsError::ParametersNotInitialized(String::from(
"CIM not initialized", "CIM not initialized",
))); )));
@ -250,11 +291,13 @@ impl ParamsTrait for DiscreteStatesContinousTimeParams {
let cim = self.cim.as_ref().unwrap(); let cim = self.cim.as_ref().unwrap();
// Check if the inner dimensions of the cim are equal to the cardinality of the variable // Check if the inner dimensions of the cim are equal to the cardinality of the variable
if cim.shape()[1] != domain_size || cim.shape()[2] != domain_size { if cim.shape()[1] != domain_size || cim.shape()[2] != domain_size {
return Err(ParamsError::InvalidCIM(format!( let message = format!(
"Incompatible shape {:?} with domain {:?}", "Incompatible shape {:?} with domain {:?}",
cim.shape(), cim.shape(),
domain_size domain_size
))); );
warn!("{}", message);
return Err(ParamsError::InvalidCIM(message));
} }
// Check if the diagonal of each cim is non-positive // Check if the diagonal of each cim is non-positive
@ -262,6 +305,10 @@ impl ParamsTrait for DiscreteStatesContinousTimeParams {
.axis_iter(Axis(0)) .axis_iter(Axis(0))
.any(|x| x.diag().iter().any(|x| x >= &0.0)) .any(|x| x.diag().iter().any(|x| x >= &0.0))
{ {
warn!(
"The diagonal of each cim for node {} must be non-positive",
self.get_label()
);
return Err(ParamsError::InvalidCIM(String::from( return Err(ParamsError::InvalidCIM(String::from(
"The diagonal of each cim must be non-positive", "The diagonal of each cim must be non-positive",
))); )));
@ -273,6 +320,10 @@ impl ParamsTrait for DiscreteStatesContinousTimeParams {
.iter() .iter()
.any(|x| f64::abs(x.clone()) > f64::EPSILON.sqrt()) .any(|x| f64::abs(x.clone()) > f64::EPSILON.sqrt())
{ {
warn!(
"The sum of each row of the cim for node {} must be 0",
self.get_label()
);
return Err(ParamsError::InvalidCIM(String::from( return Err(ParamsError::InvalidCIM(String::from(
"The sum of each row must be 0", "The sum of each row must be 0",
))); )));

@ -23,8 +23,20 @@ pub type NetworkProcessState = Vec<params::StateType>;
/// as a CTBN). /// as a CTBN).
pub trait NetworkProcess: Sync { pub trait NetworkProcess: Sync {
fn initialize_adj_matrix(&mut self); fn initialize_adj_matrix(&mut self);
/// Add a **node** to the network
///
/// # Arguments
///
/// * `n` - instantiation of the `enum params::Params` describing a node
///
/// # Return
///
/// * A `Result` containing the `node_idx` automatically assigned if everything is fine,
/// or a `NetworkError` if something went wrong.
fn add_node(&mut self, n: params::Params) -> Result<usize, NetworkError>; fn add_node(&mut self, n: params::Params) -> Result<usize, NetworkError>;
/// Add an **directed edge** between a two nodes of the network.
/// Add a **directed edge** between a two nodes of the network.
/// ///
/// # Arguments /// # Arguments
/// ///

@ -2,6 +2,7 @@
use std::collections::BTreeSet; use std::collections::BTreeSet;
use log::info;
use ndarray::prelude::*; use ndarray::prelude::*;
use crate::params::{DiscreteStatesContinousTimeParams, Params, ParamsTrait, StateType}; use crate::params::{DiscreteStatesContinousTimeParams, Params, ParamsTrait, StateType};
@ -77,6 +78,7 @@ impl CtbnNetwork {
/// ///
/// * The equivalent *CtmpProcess* computed from the current CtbnNetwork /// * The equivalent *CtmpProcess* computed from the current CtbnNetwork
pub fn amalgamation(&self) -> CtmpProcess { pub fn amalgamation(&self) -> CtmpProcess {
info!("Network Amalgamation Started");
let variables_domain = let variables_domain =
Array1::from_iter(self.nodes.iter().map(|x| x.get_reserved_space_as_parent())); Array1::from_iter(self.nodes.iter().map(|x| x.get_reserved_space_as_parent()));
@ -138,21 +140,15 @@ impl CtbnNetwork {
return array_state; return array_state;
} }
/// Get the Adjacency Matrix.
pub fn get_adj_matrix(&self) -> Option<&Array2<u16>> {
self.adj_matrix.as_ref()
}
} }
impl process::NetworkProcess for CtbnNetwork { impl process::NetworkProcess for CtbnNetwork {
/// Initialize an Adjacency matrix.
fn initialize_adj_matrix(&mut self) { fn initialize_adj_matrix(&mut self) {
self.adj_matrix = Some(Array2::<u16>::zeros( self.adj_matrix = Some(Array2::<u16>::zeros(
(self.nodes.len(), self.nodes.len()).f(), (self.nodes.len(), self.nodes.len()).f(),
)); ));
} }
/// Add a new node.
fn add_node(&mut self, mut n: Params) -> Result<usize, process::NetworkError> { fn add_node(&mut self, mut n: Params) -> Result<usize, process::NetworkError> {
n.reset_params(); n.reset_params();
self.adj_matrix = Option::None; self.adj_matrix = Option::None;
@ -160,7 +156,6 @@ impl process::NetworkProcess for CtbnNetwork {
Ok(self.nodes.len() - 1) Ok(self.nodes.len() - 1)
} }
/// Connect two nodes with a new edge.
fn add_edge(&mut self, parent: usize, child: usize) { fn add_edge(&mut self, parent: usize, child: usize) {
if let None = self.adj_matrix { if let None = self.adj_matrix {
self.initialize_adj_matrix(); self.initialize_adj_matrix();
@ -176,7 +171,6 @@ impl process::NetworkProcess for CtbnNetwork {
0..self.nodes.len() 0..self.nodes.len()
} }
/// Get the number of nodes of the network.
fn get_number_of_nodes(&self) -> usize { fn get_number_of_nodes(&self) -> usize {
self.nodes.len() self.nodes.len()
} }
@ -221,7 +215,6 @@ impl process::NetworkProcess for CtbnNetwork {
.0 .0
} }
/// Get all the parents of the given node.
fn get_parent_set(&self, node: usize) -> BTreeSet<usize> { fn get_parent_set(&self, node: usize) -> BTreeSet<usize> {
self.adj_matrix self.adj_matrix
.as_ref() .as_ref()
@ -233,7 +226,6 @@ impl process::NetworkProcess for CtbnNetwork {
.collect() .collect()
} }
/// Get all the children of the given node.
fn get_children_set(&self, node: usize) -> BTreeSet<usize> { fn get_children_set(&self, node: usize) -> BTreeSet<usize> {
self.adj_matrix self.adj_matrix
.as_ref() .as_ref()

@ -6,6 +6,75 @@ use crate::{
}; };
use super::{NetworkProcess, NetworkProcessState}; use super::{NetworkProcess, NetworkProcessState};
use log::warn;
/// This structure represents a Continuous Time Markov process
///
/// * Arguments
///
/// * `param` - An Option containing the parameters of the process
///
///```rust
/// use std::collections::BTreeSet;
/// use reCTBN::process::NetworkProcess;
/// use reCTBN::params;
/// use reCTBN::process::ctbn::*;
/// use ndarray::arr3;
///
/// //Create the domain for a discrete node
/// let mut domain = BTreeSet::new();
/// domain.insert(String::from("A"));
/// domain.insert(String::from("B"));
///
/// //Create the parameters for a discrete node using the domain
/// let param = params::DiscreteStatesContinousTimeParams::new("X1".to_string(), domain);
///
/// //Create the node using the parameters
/// let X1 = params::Params::DiscreteStatesContinousTime(param);
///
/// let mut domain = BTreeSet::new();
/// domain.insert(String::from("A"));
/// domain.insert(String::from("B"));
/// let param = params::DiscreteStatesContinousTimeParams::new("X2".to_string(), domain);
/// let X2 = params::Params::DiscreteStatesContinousTime(param);
///
/// //Initialize a ctbn
/// let mut net = CtbnNetwork::new();
///
/// //Add nodes
/// let X1 = net.add_node(X1).unwrap();
/// let X2 = net.add_node(X2).unwrap();
///
/// //Add an edge
/// net.add_edge(X1, X2);
/// match &mut net.get_node_mut(X1) {
/// params::Params::DiscreteStatesContinousTime(param) => {
/// assert_eq!(Ok(()), param.set_cim(arr3(&[[[-0.1, 0.1], [1.0, -1.0]]])));
/// }
/// }
///
/// match &mut net.get_node_mut(X2) {
/// params::Params::DiscreteStatesContinousTime(param) => {
/// assert_eq!(
/// Ok(()),
/// param.set_cim(arr3(&[
/// [[-0.01, 0.01], [5.0, -5.0]],
/// [[-5.0, 5.0], [0.01, -0.01]]
/// ]))
/// );
/// }
/// }
/// //Amalgamate the ctbn into a CtmpProcess
/// let ctmp = net.amalgamation();
///
/// //Extract the amalgamated params from the ctmp
///let params::Params::DiscreteStatesContinousTime(p_ctmp) = &ctmp.get_node(0);
///let p_ctmp = p_ctmp.get_cim().as_ref().unwrap();
///
/// //The shape of the params for an amalgamated ctmp can be computed as a Cartesian product of the
/// //domains variables of the ctbn
/// assert_eq!(p_ctmp.shape()[1], 4);
///```
pub struct CtmpProcess { pub struct CtmpProcess {
param: Option<Params>, param: Option<Params>,
@ -28,13 +97,17 @@ impl NetworkProcess for CtmpProcess {
self.param = Some(n); self.param = Some(n);
Ok(0) Ok(0)
} }
Some(_) => Err(process::NetworkError::NodeInsertionError( Some(_) => {
warn!("A CTMP do not support more than one node");
Err(process::NetworkError::NodeInsertionError(
"CtmpProcess has only one node".to_string(), "CtmpProcess has only one node".to_string(),
)), ))
}
} }
} }
fn add_edge(&mut self, _parent: usize, _child: usize) { fn add_edge(&mut self, _parent: usize, _child: usize) {
warn!("A CTMP cannot have edges");
unimplemented!("CtmpProcess has only one node") unimplemented!("CtmpProcess has only one node")
} }

Loading…
Cancel
Save