deep_causality_context 0.3.0

Context hypergraph, context node types, and contextuable traits for DeepCausality.
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
/*
 * SPDX-License-Identifier: MIT
 * Copyright (c) 2023 - 2026. The DeepCausality Authors and Contributors. All Rights Reserved.
 */

use crate::ContextId;
use crate::ContextoidId;
use crate::errors::ContextIndexError;
use crate::traits::contextuable::space_temporal::SpaceTemporal;
use crate::traits::contextuable::spatial::Spatial;
use crate::traits::contextuable::temporal::Temporal;
use crate::{Contextoid, Datable, RelationKind};

/// Trait for graph containing context-aware nodes.
///
/// D: Datable trait object
/// S: Spatial trait object
/// T: Temporable trait object
/// ST: SpaceTemporal trait object
/// V: Numeric type for dimension values
///
/// Provides methods for:
/// - Adding/removing nodes and edges
/// - Checking if nodes/edges exist
/// - Getting node references
/// - Getting graph size and counts
///
/// Nodes are Contextoid objects implementing required traits.
/// Edges have a relation kind weight.
///
/// Methods return Result or Option types for error handling.
///
#[allow(clippy::type_complexity)]
pub trait ContextuableGraph<D, S, T, ST>
where
    D: Datable + Clone,
    S: Spatial + Clone,
    T: Temporal + Clone,
    ST: SpaceTemporal + Clone,
{
    /// Adds a contextoid and returns its index.
    ///
    /// # Errors
    /// [`ContextIndexError`] when a contextoid with the same id is already in the context, since
    /// an id names one node, or when the context is frozen.
    fn add_node(&mut self, value: Contextoid<D, S, T, ST>) -> Result<usize, ContextIndexError>;
    fn contains_node(&self, index: usize) -> bool;
    fn get_node(&self, index: usize) -> Option<&Contextoid<D, S, T, ST>>;
    /// Removes the node carrying `node_id` from the base graph. Its position is never reissued,
    /// and every data and time index entry naming that position is dropped with it.
    fn remove_node(&mut self, node_id: ContextoidId) -> Result<(), ContextIndexError>;
    /// Replaces the contextoid under `node_id` with `new_node`, which may carry another id.
    ///
    /// # Errors
    /// [`ContextIndexError`] when no contextoid has `node_id`, when `new_node`'s id is already
    /// held by another contextoid, or when the context is frozen.
    fn update_node(
        &mut self,
        node_id: ContextoidId,
        new_node: Contextoid<D, S, T, ST>,
    ) -> Result<(), ContextIndexError>;
    fn add_edge(
        &mut self,
        a: usize,
        b: usize,
        weight: RelationKind,
    ) -> Result<(), ContextIndexError>;
    fn contains_edge(&self, a: usize, b: usize) -> bool;
    /// Returns the lowest relation among the edges from `a` to `b`, the same in both states, or
    /// `None` when no such edge exists. This is the read counterpart of `add_edge`: without it
    /// the relation a caller supplies is not recoverable from the context.
    fn get_edge(&self, a: usize, b: usize) -> Option<&RelationKind>;
    fn remove_edge(&mut self, a: usize, b: usize) -> Result<(), ContextIndexError>;
    fn size(&self) -> usize;
    fn is_empty(&self) -> bool;
    // Corrected method names
    fn number_of_nodes(&self) -> usize;
    fn number_of_edges(&self) -> usize;

    /// Converts the base graph to its frozen state: an immutable compressed-sparse-row layout
    /// the graph algorithms run on. Freezing takes `O(V + E)`; a frozen context is left as it is.
    ///
    /// Freezing keeps every position: no index the context stores changes, and a removed node's
    /// position reads as absent in both states. While frozen, every method that changes the base
    /// graph returns an error; reads work in both states. Extra contexts are separate graphs and
    /// keep their state.
    fn freeze(&mut self);

    /// Converts the base graph back to its mutable state, `O(V + E)`. A context that is not
    /// frozen is left as it is.
    fn unfreeze(&mut self);

    /// Whether the base graph is frozen.
    fn is_frozen(&self) -> bool;

    /// The indices of the nodes that an edge from `index` reaches, in either state, without
    /// allocating.
    ///
    /// # Errors
    /// [`ContextIndexError`] when the context holds no node at `index`.
    fn outbound_edges(
        &self,
        index: usize,
    ) -> Result<impl Iterator<Item = usize> + '_, ContextIndexError>;

    /// The indices of the nodes with an edge to `index`, in either state, without allocating.
    ///
    /// # Errors
    /// [`ContextIndexError`] when the context holds no node at `index`.
    fn inbound_edges(
        &self,
        index: usize,
    ) -> Result<impl Iterator<Item = usize> + '_, ContextIndexError>;
}

/// Trait for poly-contextuable causal graphs.
/// By default, the context graph is assumed to be a single-context graph.
///
/// This trait supports multiple contexts by extending the ContextuableGraph trait.
///
/// Extends ContextuableGraph trait with methods for:
///
/// - Creating and managing additional "contexts"
/// - Setting a current context ID
/// - Context-specific node/edge methods
///
/// Provides methods for:
///
/// - Creating new contexts
/// - Checking if a context ID exists
/// - Getting/setting current context ID
/// - Context-specific node and edge methods
///
/// Nodes are Contextoid objects implementing required traits.
/// Edges have a relation kind weight.
///
/// Methods return Result or Option types for error handling.
///
#[allow(clippy::type_complexity)]
pub trait ExtendableContextuableGraph<D, S, T, ST>
where
    D: Datable + Clone,
    S: Spatial + Clone,
    T: Temporal + Clone,
    ST: SpaceTemporal + Clone,
{
    /// Creates a new, empty, named "extra" context and adds it to the collection.
    ///
    /// The identifier is one more than the highest extra-context identifier this context has ever
    /// held, and 1 when it has held none, so an identifier added through
    /// `extra_ctx_add_new_with_id`, or one since removed, is never allocated again.
    ///
    /// # Parameters
    /// - `name`: The name the extra context is referenced by.
    /// - `capacity`: The initial storage capacity to pre-allocate for the new context's graph.
    /// - `default`: If `true`, the newly created context is immediately set as the
    ///   currently active context for subsequent `extra_ctx_*` operations.
    ///
    /// # Returns
    /// The `ContextId` assigned to the newly created context.
    fn extra_ctx_add_new(&mut self, name: &str, capacity: usize, default: bool) -> ContextId;

    /// Creates a new, named extra context with a specific, caller-provided ID.
    ///
    /// This is what a context hydrated from a store uses: the extra lands under the identifier
    /// the store holds it by.
    ///
    /// # Parameters
    /// - `id`: The `ContextId` for the new context. 0 is refused, because 0 means no extra
    ///   context is current.
    /// - `name`: The name the extra context is referenced by.
    /// - `capacity`: The initial storage capacity for the new context's graph.
    /// - `default`: If `true`, this new context is set as the currently active one.
    ///
    /// # Returns
    /// - `Ok(())` if the context was created successfully.
    ///
    /// # Errors
    /// - `ContextIndexError` if a context with the provided `id` already exists, or if `id` is 0.
    fn extra_ctx_add_new_with_id(
        &mut self,
        id: ContextId,
        name: &str,
        capacity: usize,
        default: bool,
    ) -> Result<(), ContextIndexError>;

    /// The name of the extra context with the given ID, or `None` when no extra holds it.
    fn extra_ctx_get_name(&self, id: ContextId) -> Option<&str>;

    /// Checks if an extra context with the given ID exists.
    ///
    /// # Parameters
    /// - `idx`: The `u64` ID of the context to check for.
    ///
    /// # Returns
    /// `true` if a context with the specified ID exists, `false` otherwise.
    fn extra_ctx_check_exists(&self, idx: ContextId) -> bool;

    /// Gets the ID of the currently active extra context.
    ///
    /// By convention, an ID of `0` indicates that no extra context is currently active,
    /// and operations will target the primary context.
    ///
    /// # Returns
    /// The `u64` ID of the active context.
    fn extra_ctx_get_current_id(&self) -> ContextId;

    /// Sets the active extra context to the one identified by the given ID.
    ///
    /// All subsequent `extra_ctx_*` operations will be directed to this context
    /// until it is changed or unset.
    ///
    /// # Parameters
    /// - `idx`: The `u64` ID of the context to set as active.
    ///
    /// # Returns
    /// - `Ok(())` on success.
    ///
    /// # Errors
    /// - `ContextIndexError` if no context with the specified `idx` exists.
    fn extra_ctx_set_current_id(&mut self, idx: ContextId) -> Result<(), ContextIndexError>;

    /// Unsets the currently active extra context.
    ///
    /// After this operation, `extra_ctx_get_current_id` will return `0`,
    /// indicating that no extra context is active.
    ///
    /// # Returns
    /// - `Ok(())` if a context was active and has now been unset.
    ///
    /// # Errors
    /// - `ContextIndexError` if no extra context was active to begin with.
    fn extra_ctx_unset_current_id(&mut self) -> Result<(), ContextIndexError>;

    /// Adds a `Contextoid` node to the currently active extra context.
    ///
    /// This operation is directed to the context set by `extra_ctx_set_current_id`.
    ///
    /// # Parameters
    /// - `value`: The `Contextoid` instance to add to the graph.
    ///
    /// # Returns
    /// - `Ok(usize)` containing the unique index of the newly added node within the active context's graph.
    ///
    /// # Errors
    /// - `ContextIndexError` if no extra context is currently active, or if the active extra
    ///   context already holds a contextoid with the same id. Ids are unique per graph: the base
    ///   context and each extra context may hold the same id.
    fn extra_ctx_add_node(
        &mut self,
        value: Contextoid<D, S, T, ST>,
    ) -> Result<usize, ContextIndexError>;

    /// Checks if a node with the given index exists in the currently active extra context.
    ///
    /// This operation is directed to the context set by `extra_ctx_set_current_id`.
    ///
    /// # Parameters
    /// - `index`: The index of the node to check for.
    ///
    /// # Returns
    /// - `true` if a node with the specified index exists in the active context.
    /// - `false` if the node does not exist or if no extra context is currently active.
    fn extra_ctx_contains_node(&self, index: usize) -> bool;

    /// Retrieves an immutable reference to a `Contextoid` from the currently active extra context.
    ///
    /// This operation is directed to the context set by `extra_ctx_set_current_id`.
    ///
    /// # Parameters
    /// - `index`: The index of the node to retrieve.
    ///
    /// # Returns
    /// - `Ok(&Contextoid<...>)` containing a reference to the node if found.
    ///
    /// # Errors
    /// - `ContextIndexError` if no extra context is active or if the `index` is out of bounds for the active context's graph.
    fn extra_ctx_get_node(
        &self,
        index: usize,
    ) -> Result<&Contextoid<D, S, T, ST>, ContextIndexError>;

    /// Removes a node by its index from the currently active extra context.
    ///
    /// This operation is directed to the context set by `extra_ctx_set_current_id`.
    /// Note that this will also remove all edges connected to the specified node.
    ///
    /// # Parameters
    /// - `index`: The index of the node to remove.
    ///
    /// # Returns
    /// - `Ok(())` if the node was successfully removed.
    ///
    /// # Errors
    /// - `ContextIndexError` if no extra context is active or if the `index` is out of bounds.
    fn extra_ctx_remove_node(&mut self, index: usize) -> Result<(), ContextIndexError>;

    /// Adds a directed edge between two nodes in the currently active extra context.
    ///
    /// The edge is created from node `a` to node `b`. This operation is directed
    /// to the context set by `extra_ctx_set_current_id`.
    ///
    /// # Parameters
    /// - `a`: The index of the source node.
    /// - `b`: The index of the target node.
    /// - `weight`: The `RelationKind` that describes the relationship between the nodes.
    ///
    /// # Returns
    /// - `Ok(())` if the edge was successfully added.
    ///
    /// # Errors
    /// - `ContextIndexError` if no extra context is active or if either `a` or `b` are invalid node indices.
    fn extra_ctx_add_edge(
        &mut self,
        a: usize,
        b: usize,
        weight: RelationKind,
    ) -> Result<(), ContextIndexError>;

    /// Checks if a directed edge exists between two nodes in the currently active extra context.
    ///
    /// The check is for an edge from node `a` to node `b`. This operation is directed
    /// to the context set by `extra_ctx_set_current_id`.
    ///
    /// # Parameters
    /// - `a`: The index of the source node.
    /// - `b`: The index of the target node.
    ///
    /// # Returns
    /// - `true` if a directed edge from `a` to `b` exists in the active context.
    /// - `false` if the edge does not exist, if either index is invalid, or if no
    ///   extra context is currently active.
    fn extra_ctx_contains_edge(&self, a: usize, b: usize) -> bool;

    /// Returns the relation carried by the edge from node `a` to node `b` in the currently
    /// active extra context.
    ///
    /// This is the read counterpart of `extra_ctx_add_edge`, and is directed to the context set
    /// by `extra_ctx_set_current_id`.
    ///
    /// # Parameters
    /// - `a`: The index of the source node.
    /// - `b`: The index of the target node.
    ///
    /// # Returns
    /// - `Some(&RelationKind)` when a directed edge from `a` to `b` exists in the active context.
    /// - `None` if the edge does not exist, if either index is invalid, or if no extra context is
    ///   currently active.
    fn extra_ctx_get_edge(&self, a: usize, b: usize) -> Option<&RelationKind>;

    /// Removes a directed edge between two nodes in the currently active extra context.
    ///
    /// This operation is directed to the context set by `extra_ctx_set_current_id`.
    ///
    /// # Parameters
    /// - `a`: The index of the source node of the edge to remove.
    /// - `b`: The index of the target node of the edge to remove.
    ///
    /// # Returns
    /// - `Ok(())` if the edge was successfully removed.
    ///
    /// # Errors
    /// - `ContextIndexError` if no extra context is active or if the edge does not exist.
    fn extra_ctx_remove_edge(&mut self, a: usize, b: usize) -> Result<(), ContextIndexError>;

    /// Returns the number of nodes in the currently active extra context's graph.
    ///
    /// This operation is directed to the context set by `extra_ctx_set_current_id`.
    ///
    /// # Returns
    /// - `Ok(usize)` containing the total number of nodes in the active context's graph.
    ///
    /// # Errors
    /// - `ContextIndexError` if no extra context is currently active.
    fn extra_ctx_size(&self) -> Result<usize, ContextIndexError>;

    /// Checks if the currently active extra context's graph is empty (contains no nodes).
    ///
    /// This operation is directed to the context set by `extra_ctx_set_current_id`.
    ///
    /// # Returns
    /// - `Ok(true)` if the active context's graph has zero nodes.
    /// - `Ok(false)` if it contains one or more nodes.
    ///
    /// # Errors
    /// - `ContextIndexError` if no extra context is currently active.
    fn extra_ctx_is_empty(&self) -> Result<bool, ContextIndexError>;

    /// Returns the total number of nodes in the currently active extra context's graph.
    ///
    /// This operation is directed to the context set by `extra_ctx_set_current_id`.
    ///
    /// # Returns
    /// - `Ok(usize)` containing the count of nodes in the active context's graph.
    ///
    /// # Errors
    /// - `ContextIndexError` if no extra context is currently active.
    fn extra_ctx_node_count(&self) -> Result<usize, ContextIndexError>;

    /// Returns the total number of edges in the currently active extra context's graph.
    ///
    /// This operation is directed to the context set by `extra_ctx_set_current_id`.
    ///
    /// # Returns
    /// - `Ok(usize)` containing the count of edges in the active context's graph.
    ///
    /// # Errors
    /// - `ContextIndexError` if no extra context is currently active.
    fn extra_ctx_edge_count(&self) -> Result<usize, ContextIndexError>;
}