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
use itertools::Itertools;
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use crate::{
estimators::{CIMEstimator, PK},
models::{CIM, CatCIM, DiGraph, Graph, Labelled},
set,
types::{Labels, Set},
};
/// A trait for scoring criteria used in score-based structure learning.
pub trait ScoringCriterion {
/// Computes the score for a given variable and its conditioning set.
///
/// # Arguments
///
/// * `x` - The variable to score.
/// * `z` - The conditioning set.
///
/// # Returns
///
/// The computed score.
///
fn call(&self, x: &Set<usize>, z: &Set<usize>) -> f64;
}
/// The Bayesian Information Criterion (BIC).
pub struct BIC<'a, E> {
estimator: &'a E,
}
impl<'a, E> BIC<'a, E> {
/// Creates a new BIC instance.
///
/// # Arguments
///
/// * `estimator` - A reference to the estimator.
///
/// # Returns
///
/// A new `BIC` instance.
///
#[inline]
pub const fn new(estimator: &'a E) -> Self {
Self { estimator }
}
}
impl<'a, E> Labelled for BIC<'a, E>
where
E: Labelled,
{
#[inline]
fn labels(&self) -> &Labels {
self.estimator.labels()
}
}
impl<E> ScoringCriterion for BIC<'_, E>
where
E: CIMEstimator<CatCIM>,
{
#[inline]
fn call(&self, x: &Set<usize>, z: &Set<usize>) -> f64 {
// Compute the intensity matrices for the sets.
let q_xz = self.estimator.fit(x, z);
// Get the sample size.
let n = q_xz
.sample_statistics()
.map(|s| s.sample_size())
.expect("Failed to get the sample size.");
// Get the log-likelihood.
let ll = q_xz
.sample_log_likelihood()
.expect("Failed to compute the log-likelihood.");
// Get the number of parameters.
let k = q_xz.parameters_size() as f64;
// Compute the BIC.
ll - 0.5 * k * f64::ln(n)
}
}
/// The hill climbing algorithm for structure learning in CTBNs.
#[derive(Clone, Debug)]
pub struct CTHC<'a, S> {
initial_graph: &'a DiGraph,
score: &'a S,
max_parents: Option<usize>,
prior_knowledge: Option<&'a PK>,
}
impl<'a, S> CTHC<'a, S>
where
S: ScoringCriterion + Labelled,
{
/// Creates a new continuous time hill climbing instance.
///
/// # Arguments
///
/// * `initial_graph` - The initial directed graph.
/// * `score` - The scoring criterion to use.
///
/// # Returns
///
/// A new `ContinuousTimeHillClimbing` instance.
///
#[inline]
pub fn new(initial_graph: &'a DiGraph, score: &'a S) -> Self {
// Assert labels of the initial graph and the estimator are the same.
assert_eq!(
initial_graph.labels(),
score.labels(),
"Labels of initial graph and estimator must be the same: \n\
\t expected: {:?}, \n\
\t found: {:?}.",
initial_graph.labels(),
score.labels()
);
Self {
initial_graph,
score,
max_parents: None,
prior_knowledge: None,
}
}
/// Sets the maximum number of parents for each vertex.
///
/// # Arguments
///
/// * `max_parents` - The maximum number of parents for each vertex.
///
/// # Returns
///
/// A mutable reference to the current instance.
///
#[inline]
pub const fn with_max_parents(mut self, max_parents: usize) -> Self {
self.max_parents = Some(max_parents);
self
}
/// Sets the prior knowledge for the algorithm.
///
/// # Arguments
///
/// * `prior_knowledge` - The prior knowledge to use.
///
/// # Returns
///
/// A mutable reference to the current instance.
///
#[inline]
pub fn with_prior_knowledge(mut self, prior_knowledge: &'a PK) -> Self {
// Assert labels of prior knowledge and initial graph are the same.
assert_eq!(
self.initial_graph.labels(),
prior_knowledge.labels(),
"Labels of initial graph and prior knowledge must be the same: \n\
\t expected: {:?}, \n\
\t found: {:?}.",
self.initial_graph.labels(),
prior_knowledge.labels()
);
// Assert prior knowledge is consistent with initial graph.
self.initial_graph
.vertices()
.into_iter()
.permutations(2)
.for_each(|edge| {
// Get the edge indices.
let (i, j) = (edge[0], edge[1]);
// Assert edge must be either present and not forbidden ...
if self.initial_graph.has_edge(i, j) {
assert!(
!prior_knowledge.is_forbidden(i, j),
"Initial graph contains forbidden edge ({i}, {j})."
);
// ... or absent and not required.
} else {
assert!(
!prior_knowledge.is_required(i, j),
"Initial graph does not contain required edge ({i}, {j})."
);
}
});
// Set prior knowledge.
self.prior_knowledge = Some(prior_knowledge);
self
}
/// Execute the CTHC algorithm.
///
/// # Returns
///
/// The fitted graph.
///
pub fn fit(&self) -> DiGraph {
// Clone the initial graph.
let mut graph = DiGraph::empty(self.initial_graph.labels());
// For each vertex in the graph ...
for i in self.initial_graph.vertices() {
// Initialize the previous score to negative infinity.
let mut prev_score = f64::NEG_INFINITY;
// Set the initial parent set as the current parent set.
let mut curr_pa = self.initial_graph.parents(&set![i]);
// Compute the score of the current parent set.
let mut curr_score = self.score.call(&set![i], &curr_pa);
// While the score of the current parent set is higher than the previous score ...
while prev_score < curr_score {
// Set the previous score to the score of the current parent set.
prev_score = curr_score;
// Get the candidate parent sets by adding ...
let poss_pa = {
// Clone the current parent set.
[curr_pa.clone()].into_iter().filter(|curr_pa|
// Check if maximum parents has been reached.
if let Some(max_parents) = self.max_parents {
curr_pa.len() < max_parents
} else {
true
}
).flat_map(|curr_pa| {
// Get the vertices that are not in the current parent set.
self.initial_graph
.vertices()
.into_iter()
.filter_map(move |j| {
if i != j {
// If the vertex is not in the current parent set ...
if let Err(p_j) = curr_pa.binary_search(&j) {
// Clone the current parent set.
let mut curr_pa = curr_pa.clone();
// Insert the vertex in order.
curr_pa.shift_insert(p_j, j);
// Return it as a candidate for addition.
return Some(curr_pa);
}
}
// Otherwise, the vertex is already present.
None
})
})
}
// ... or removing vertices.
.chain({
// Clone the current parent set.
let curr_pa = curr_pa.clone();
// Get the size of the candidate subset, avoid underflow.
let k = curr_pa.len().saturating_sub(1);
// Generate all the k-sized subsets.
curr_pa.into_iter().combinations(k).map(Set::from_iter)
});
// For each candidate parent sets ...
for next_pa in poss_pa {
// Compute the score of the candidate parent set.
let next_score = self.score.call(&set![i], &next_pa);
// If the score of the candidate parent set is higher ...
if curr_score < next_score {
// Update the current parent set to the candidate parent set.
curr_pa = next_pa;
// Update the score of the current parent set.
curr_score = next_score;
}
}
}
// Set the current parent set.
for j in curr_pa {
// Add an edge from vertex `j` to vertex `i`.
graph.add_edge(j, i);
}
}
// Return the final graph.
graph
}
}
impl<'a, S> CTHC<'a, S>
where
S: ScoringCriterion + Sync,
{
/// Execute the CTHC algorithm in parallel.
///
/// # Returns
///
/// The fitted graph.
///
pub fn par_fit(&self) -> DiGraph {
// For each vertex in the graph ...
let parents: Vec<_> = self
.initial_graph
.vertices()
.into_par_iter()
.map(|i| {
// Initialize the previous score to negative infinity.
let mut prev_score = f64::NEG_INFINITY;
// Set the initial parent set as the current parent set.
let mut curr_pa = self.initial_graph.parents(&set![i]);
// Compute the score of the current parent set.
let mut curr_score = self.score.call(&set![i], &curr_pa);
// While the score of the current parent set is higher than the previous score ...
while prev_score < curr_score {
// Set the previous score to the score of the current parent set.
prev_score = curr_score;
// Get the candidate parent sets by adding ...
let poss_pa: Vec<_> = {
// Clone the current parent set.
[curr_pa.clone()].into_iter().filter(|curr_pa|
// Check if maximum parents has been reached.
if let Some(max_parents) = self.max_parents {
curr_pa.len() < max_parents
} else {
true
}
).flat_map(|curr_pa| {
// Get the vertices that are not in the current parent set.
self.initial_graph
.vertices()
.into_iter()
.filter_map(move |j| {
if i != j {
// If the vertex is not in the current parent set ...
if let Err(p_j) = curr_pa.binary_search(&j) {
// Clone the current parent set.
let mut curr_pa = curr_pa.clone();
// Insert the vertex in order.
curr_pa.shift_insert(p_j, j);
// Return it as a candidate for addition.
return Some(curr_pa);
}
}
// Otherwise, the vertex is already present.
None
})
})
}
// ... or removing vertices.
.chain({
// Clone the current parent set.
let curr_pa = curr_pa.clone();
// Get the size of the candidate subset, avoid underflow.
let k = curr_pa.len().saturating_sub(1);
// Generate all the k-sized subsets.
curr_pa.into_iter().combinations(k).map(Set::from_iter)
})
// Collect to allow for parallel iteration.
.collect();
// For each candidate parent sets ...
if let Some((next_score, next_pa)) = poss_pa
.into_par_iter()
// Compute the score of the candidate parent set in parallel.
.map(|next_pa| (self.score.call(&set![i], &next_pa), next_pa))
// Get the one with the highest score in parallel.
.max_by(|(a, _), (b, _)| a.partial_cmp(b).unwrap())
{
// If the score of the candidate parent set is higher ...
if curr_score < next_score {
// Update the current parent set to the candidate parent set.
curr_pa = next_pa;
// Update the score of the current parent set.
curr_score = next_score;
}
}
}
// Return the current parent set.
curr_pa
})
.collect();
// Clone the initial graph.
let mut graph = DiGraph::empty(self.initial_graph.labels());
// Set the current parent set.
for (i, curr_pa) in parents.into_iter().enumerate() {
for j in curr_pa {
// Add an edge from vertex `j` to vertex `i`.
graph.add_edge(j, i);
}
}
// Return the final graph.
graph
}
}