aces 0.0.7

Algebra of Cause-Effect Structures
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
use std::{
    collections::{btree_map, BTreeMap},
    convert::TryInto,
    io::Read,
    fs::File,
    path::Path,
    error::Error,
};
use log::Level::Trace;
use crate::{
    ContextHandle, Port, Split, AtomID, NodeID, PortID, LinkID, ForkID, JoinID, Polynomial,
    FiringComponent, Content, content::content_from_str, node, sat, AcesError,
};

#[derive(PartialEq, Debug)]
enum LinkState {
    /// Single-face link (structure containing it is incoherent).  The
    /// [`node::Face`] value is the missing face.
    Thin(node::Face),
    Fat,
}

#[derive(Debug)]
enum Resolution {
    Unsolved,
    Incoherent,
    Deadlock,
    Solved(Vec<FiringComponent>),
}

impl Default for Resolution {
    fn default() -> Self {
        Resolution::Unsolved
    }
}

/// A single c-e structure.
///
/// Internally, instances of this type own structural information (the
/// cause and effect polynomials), semantic properties (node
/// capacities for the carrier), the intermediate content
/// representation from which a c-e structure originated (optionally),
/// and some auxiliary recomputable data.  Other properties are
/// available indirectly: `CEStructure` instance owns a
/// [`ContextHandle`] which resolves to a shared [`Context`] object.
///
/// [`Context`]: crate::Context
#[derive(Debug)]
pub struct CEStructure {
    context:         ContextHandle,
    content:         Option<Box<dyn Content>>,
    resolution:      Resolution,
    causes:          BTreeMap<PortID, Polynomial<LinkID>>,
    effects:         BTreeMap<PortID, Polynomial<LinkID>>,
    carrier:         BTreeMap<NodeID, node::Capacity>,
    links:           BTreeMap<LinkID, LinkState>,
    num_thin_links:  u32,
    encoding_to_use: Option<sat::Encoding>,
    forks:           BTreeMap<NodeID, Vec<AtomID>>,
    joins:           BTreeMap<NodeID, Vec<AtomID>>,
    // FIXME define `struct Cosplits`, grouped on demand (cf. `group_cosplits`)
    co_forks: BTreeMap<AtomID, Vec<AtomID>>, // Joins -> 2^Forks
    co_joins: BTreeMap<AtomID, Vec<AtomID>>, // Forks -> 2^Joins
}

impl CEStructure {
    /// Creates an empty c-e structure in a [`Context`] given by a
    /// [`ContextHandle`].
    ///
    /// [`Context`]: crate::Context
    pub fn new(ctx: &ContextHandle) -> Self {
        Self {
            context:         ctx.clone(),
            content:         None,
            resolution:      Default::default(),
            causes:          Default::default(),
            effects:         Default::default(),
            carrier:         Default::default(),
            links:           Default::default(),
            num_thin_links:  0,
            encoding_to_use: None,
            forks:           Default::default(),
            joins:           Default::default(),
            co_forks:        Default::default(),
            co_joins:        Default::default(),
        }
    }

    pub fn set_encoding(&mut self, encoding: sat::Encoding) {
        self.encoding_to_use = Some(encoding);
    }

    fn add_split_to_host(&mut self, split_id: AtomID, face: node::Face, node_id: NodeID) {
        let split_entry = match face {
            node::Face::Tx => self.forks.entry(node_id),
            node::Face::Rx => self.joins.entry(node_id),
        };

        match split_entry {
            btree_map::Entry::Vacant(entry) => {
                entry.insert(vec![split_id]);
            }
            btree_map::Entry::Occupied(mut entry) => {
                let sids = entry.get_mut();

                if let Err(pos) = sids.binary_search(&split_id) {
                    sids.insert(pos, split_id);
                } // else idempotency of addition.
            }
        }
    }

    fn add_split_to_suit(&mut self, split_id: AtomID, face: node::Face, co_split_ids: &[AtomID]) {
        for &co_split_id in co_split_ids.iter() {
            let split_entry = match face {
                node::Face::Tx => self.co_forks.entry(co_split_id),
                node::Face::Rx => self.co_joins.entry(co_split_id),
            };

            if log_enabled!(Trace) {
                let ctx = self.context.lock().unwrap();

                match face {
                    node::Face::Tx => {
                        trace!(
                            "Old join's co_forks[{}] -> {}",
                            ctx.with(&JoinID(co_split_id)),
                            ctx.with(&ForkID(split_id))
                        );
                    }
                    node::Face::Rx => {
                        trace!(
                            "Old fork's co_joins[{}] -> {}",
                            ctx.with(&ForkID(co_split_id)),
                            ctx.with(&JoinID(split_id))
                        );
                    }
                }
            }

            match split_entry {
                btree_map::Entry::Vacant(entry) => {
                    entry.insert(vec![split_id]);
                }
                btree_map::Entry::Occupied(mut entry) => {
                    let sids = entry.get_mut();

                    if let Err(pos) = sids.binary_search(&split_id) {
                        sids.insert(pos, split_id);
                    } // else idempotency of addition.
                }
            }
        }
    }

    fn create_splits(
        &mut self,
        face: node::Face,
        node_id: NodeID,
        poly: &Polynomial<LinkID>,
    ) -> Result<(), AcesError> {
        use node::Face::{Tx, Rx};

        for mono in poly.get_monomials() {
            let mut co_node_ids = Vec::new();
            let mut fat_co_node_ids = Vec::new();

            // Link sequence, ordered by conode ID.
            for lid in mono {
                if let Some(link_state) = self.links.get(&lid) {
                    let ctx = self.context.lock().unwrap();

                    if let Some(link) = ctx.get_link(lid) {
                        co_node_ids.push(link.get_node_id(!face));

                        match link_state {
                            LinkState::Fat => {
                                fat_co_node_ids.push(link.get_node_id(!face));
                            }
                            LinkState::Thin(_) => {} // Don't push a thin link.
                        }
                    } else {
                        return Err(AcesError::LinkMissingForID(lid))
                    }
                } else {
                    return Err(AcesError::UnlistedAtomicInMonomial)
                }
            }

            let mut co_splits = Vec::new();

            for nid in fat_co_node_ids.iter() {
                if let Some(split_ids) = match face {
                    Tx => self.joins.get(nid),
                    Rx => self.forks.get(nid),
                } {
                    let ctx = self.context.lock().unwrap();

                    for &sid in split_ids {
                        if let Some(split) = match face {
                            Tx => ctx.get_join(sid.into()),
                            Rx => ctx.get_fork(sid.into()),
                        } {
                            if split.get_suit_ids().binary_search(&node_id).is_ok() {
                                co_splits.push(sid);
                            }
                        }
                    }
                } else {
                    // This co_node has no co_splits yet, a condition
                    // which should have been detected above as a thin
                    // link.
                    return Err(AcesError::IncoherencyLeak)
                }
            }

            let split_id: AtomID = match face {
                Tx => {
                    let mut fork = Split::new_fork(node_id, co_node_ids, Default::default());
                    self.context.lock().unwrap().share_fork(&mut fork).into()
                }
                Rx => {
                    let mut join = Split::new_join(node_id, co_node_ids, Default::default());
                    self.context.lock().unwrap().share_join(&mut join).into()
                }
            };

            self.add_split_to_host(split_id, face, node_id);

            if !co_splits.is_empty() {
                self.add_split_to_suit(split_id, face, co_splits.as_slice());

                if log_enabled!(Trace) {
                    let ctx = self.context.lock().unwrap();

                    match face {
                        Tx => {
                            trace!(
                                "New fork's co_joins[{}] -> {:?}",
                                ctx.with(&ForkID(split_id)),
                                co_splits
                            );
                        }
                        Rx => {
                            trace!(
                                "New join's co_forks[{}] -> {:?}",
                                ctx.with(&JoinID(split_id)),
                                co_splits
                            );
                        }
                    }
                }

                match face {
                    Tx => self.co_joins.insert(split_id, co_splits),
                    Rx => self.co_forks.insert(split_id, co_splits),
                };
            }
        }

        Ok(())
    }

    /// Constructs new [`Polynomial`] from a sequence of sequences of
    /// [`NodeID`]s and adds it to causes of a node of this
    /// `CEStructure`.
    ///
    /// This method is incremental: new polynomial is added to old
    /// polynomial that is already attached to the `node_id` as node's
    /// causes (there is always some polynomial attached, if not
    /// explicitly, then implicitly, as the default _&theta;_).
    pub fn add_causes<'a, I>(&mut self, node_id: NodeID, poly_ids: I) -> Result<(), AcesError>
    where
        I: IntoIterator + 'a,
        I::Item: IntoIterator<Item = &'a NodeID>,
    {
        let poly =
            Polynomial::from_nodes_in_context(&self.context, node::Face::Rx, node_id, poly_ids);

        let mut port = Port::new(node::Face::Rx, node_id);
        let port_id = self.context.lock().unwrap().share_port(&mut port);

        for &lid in poly.get_atomics() {
            if let Some(what_missing) = self.links.get_mut(&lid) {
                if *what_missing == LinkState::Thin(node::Face::Rx) {
                    // Fat link: occurs in causes and effects.
                    *what_missing = LinkState::Fat;
                    self.num_thin_links -= 1;
                } else {
                    // Link reoccurrence in causes.
                }
            } else {
                // Thin, cause-only link: occurs in causes, but not in effects.
                self.links.insert(lid, LinkState::Thin(node::Face::Tx));
                self.num_thin_links += 1;
            }
        }

        self.create_splits(node::Face::Rx, node_id, &poly)?;

        // FIXME add to old if any
        self.causes.insert(port_id, poly);

        self.carrier.entry(node_id).or_insert_with(Default::default);

        Ok(())
    }

    /// Constructs new [`Polynomial`] from a sequence of sequences of
    /// [`NodeID`]s and adds it to effects of a node of this
    /// `CEStructure`.
    ///
    /// This method is incremental: new polynomial is added to old
    /// polynomial that is already attached to the `node_id` as node's
    /// effects (there is always some polynomial attached, if not
    /// explicitly, then implicitly, as the default _&theta;_).
    pub fn add_effects<'a, I>(&mut self, node_id: NodeID, poly_ids: I) -> Result<(), AcesError>
    where
        I: IntoIterator + 'a,
        I::Item: IntoIterator<Item = &'a NodeID>,
    {
        let poly =
            Polynomial::from_nodes_in_context(&self.context, node::Face::Tx, node_id, poly_ids);

        let mut port = Port::new(node::Face::Tx, node_id);
        let port_id = self.context.lock().unwrap().share_port(&mut port);

        for &lid in poly.get_atomics() {
            if let Some(what_missing) = self.links.get_mut(&lid) {
                if *what_missing == LinkState::Thin(node::Face::Tx) {
                    // Fat link: occurs in causes and effects.
                    *what_missing = LinkState::Fat;
                    self.num_thin_links -= 1;
                } else {
                    // Link reoccurrence in effects.
                }
            } else {
                // Thin, effect-only link: occurs in effects, but not in causes.
                self.links.insert(lid, LinkState::Thin(node::Face::Rx));
                self.num_thin_links += 1;
            }
        }

        self.create_splits(node::Face::Tx, node_id, &poly)?;

        // FIXME add to old if any
        self.effects.insert(port_id, poly);

        self.carrier.entry(node_id).or_insert_with(Default::default);

        Ok(())
    }

    pub fn from_content(
        ctx: &ContextHandle,
        mut content: Box<dyn Content>,
    ) -> Result<Self, Box<dyn Error>> {
        let mut ces = CEStructure::new(ctx);

        for node_id in content.get_carrier_ids() {
            if let Some(poly_ids) = content.get_causes_by_id(node_id) {
                if poly_ids.is_empty() {
                    let node_name = ctx.lock().unwrap().get_node_name(node_id).unwrap().to_owned();

                    return Err(Box::new(AcesError::EmptyCausesOfInternalNode(node_name)))
                }

                ces.add_causes(node_id, poly_ids)?;
            }

            if let Some(poly_ids) = content.get_effects_by_id(node_id) {
                if poly_ids.is_empty() {
                    let node_name = ctx.lock().unwrap().get_node_name(node_id).unwrap().to_owned();

                    return Err(Box::new(AcesError::EmptyEffectsOfInternalNode(node_name)))
                }

                ces.add_effects(node_id, poly_ids)?;
            }
        }

        ces.content = Some(content);
        Ok(ces)
    }

    /// Creates a new c-e structure from a textual description and in
    /// a [`Context`] given by a [`ContextHandle`].
    ///
    /// [`Context`]: crate::Context
    pub fn from_str<S: AsRef<str>>(ctx: &ContextHandle, script: S) -> Result<Self, Box<dyn Error>> {
        let content = content_from_str(ctx, script)?;

        Self::from_content(ctx, content)
    }

    /// Creates a new c-e structure from a script file to be found
    /// along the `path` and in a [`Context`] given by a
    /// [`ContextHandle`].
    ///
    /// [`Context`]: crate::Context
    pub fn from_file<P: AsRef<Path>>(ctx: &ContextHandle, path: P) -> Result<Self, Box<dyn Error>> {
        let mut fp = File::open(path)?;
        let mut script = String::new();
        fp.read_to_string(&mut script)?;

        Self::from_str(ctx, &script)
    }

    pub fn get_context(&self) -> &ContextHandle {
        &self.context
    }

    pub fn get_name(&self) -> Option<&str> {
        if let Some(ref content) = self.content {
            content.get_name()
        } else {
            None
        }
    }

    /// Returns link coherence status indicating whether this object
    /// represents a proper c-e structure.
    ///
    /// C-e structure is coherent iff it has no thin links, where a
    /// link is thin iff it occurs either in causes or in effects, but
    /// not in both.  Internally, there is a thin links counter
    /// associated with each `CEStructure` object.  This counter is
    /// updated whenever a polynomial is added to the structure.
    pub fn is_coherent(&self) -> bool {
        self.num_thin_links == 0
    }

    pub fn get_port_link_formula(&self) -> Result<sat::Formula, Box<dyn Error>> {
        let mut formula = sat::Formula::new(&self.context);

        for (&pid, poly) in self.causes.iter() {
            formula.add_polynomial(pid, poly)?;
            formula.add_antiport(pid)?;
        }

        for (&pid, poly) in self.effects.iter() {
            formula.add_polynomial(pid, poly)?;
        }

        for (&lid, _) in self.links.iter() {
            formula.add_link_coherence(lid)?;
        }

        Ok(formula)
    }

    /// Given a flat list of co-splits, groups them by their host
    /// nodes (i.e. by suit members of the considered split), and
    /// returns a vector of vectors of [`AtomID`]s.
    ///
    /// The result, if interpreted in terms of SAT encoding, is a
    /// conjunction of exclusive choices of co-splits.
    fn group_cosplits(&self, cosplit_ids: &[AtomID]) -> Result<Vec<Vec<AtomID>>, AcesError> {
        if cosplit_ids.len() < 2 {
            if cosplit_ids.is_empty() {
                Err(AcesError::IncoherencyLeak)
            } else {
                Ok(vec![cosplit_ids.to_vec()])
            }
        } else {
            let ctx = self.context.lock().unwrap();
            let mut cohost_map: BTreeMap<NodeID, Vec<AtomID>> = BTreeMap::new();

            for &cosplit_id in cosplit_ids.iter() {
                let cosplit = ctx.get_split(cosplit_id).ok_or(AcesError::SplitMissingForID)?;
                let cohost_id = cosplit.get_host_id();

                match cohost_map.entry(cohost_id) {
                    btree_map::Entry::Vacant(entry) => {
                        entry.insert(vec![cosplit_id]);
                    }
                    btree_map::Entry::Occupied(mut entry) => {
                        let sids = entry.get_mut();

                        if let Err(pos) = sids.binary_search(&cosplit_id) {
                            sids.insert(pos, cosplit_id);
                        } else {
                            warn!("Multiple occurrences of {} in cosplit array", ctx.with(cosplit));
                        }
                    }
                }
            }

            Ok(cohost_map.into_iter().map(|(_, v)| v).collect())
        }
    }

    pub fn get_fork_join_formula(&self) -> Result<sat::Formula, Box<dyn Error>> {
        let mut formula = sat::Formula::new(&self.context);

        for (node_id, fork_atom_ids) in self.forks.iter() {
            if let Some(join_atom_ids) = self.joins.get(node_id) {
                formula.add_antisplits(fork_atom_ids.as_slice(), join_atom_ids.as_slice())?;
            }

            formula.add_sidesplits(fork_atom_ids.as_slice())?;
        }

        for (_, join_atom_ids) in self.joins.iter() {
            formula.add_sidesplits(join_atom_ids.as_slice())?;
        }

        for (&join_id, cofork_ids) in self.co_forks.iter() {
            let cosplits = self.group_cosplits(cofork_ids.as_slice())?;
            formula.add_cosplits(join_id, cosplits)?;
        }

        for (&fork_id, cojoin_ids) in self.co_joins.iter() {
            let cosplits = self.group_cosplits(cojoin_ids.as_slice())?;
            formula.add_cosplits(fork_id, cosplits)?;
        }

        Ok(formula)
    }

    pub fn solve(&mut self, minimal_mode: bool) -> Result<(), Box<dyn Error>> {
        if !self.is_coherent() {
            self.resolution = Resolution::Incoherent;

            Err(Box::new(AcesError::IncoherentStructure(
                self.get_name().unwrap_or("anonymous").to_owned(),
            )))
        } else {
            let formula = if let Some(encoding) = self.encoding_to_use {
                match encoding {
                    sat::Encoding::PortLink => self.get_port_link_formula()?,
                    sat::Encoding::ForkJoin => self.get_fork_join_formula()?,
                }
            } else {
                // FIXME choose one or the other, heuristically
                self.get_port_link_formula()?
            };

            debug!("Raw {:?}", formula);
            info!("Formula: {}", formula);

            let mut solver = sat::Solver::new(&self.context);
            solver.add_formula(&formula)?;
            solver.inhibit_empty_solution()?;

            info!("Start of {}-solution search", if minimal_mode { "min" } else { "all" });
            solver.set_minimal_mode(minimal_mode);

            if let Some(first_solution) = solver.next() {
                let mut fcs = Vec::new();

                debug!("1. Raw {:?}", first_solution);
                fcs.push(first_solution.try_into()?);

                for (count, solution) in solver.enumerate() {
                    debug!("{}. Raw {:?}", count + 2, solution);
                    fcs.push(solution.try_into()?);
                }

                self.resolution = Resolution::Solved(fcs);
            } else if solver.is_sat().is_some() {
                info!("\nStructural deadlock (found no solutions).");
                self.resolution = Resolution::Deadlock;
            } else if solver.was_interrupted() {
                warn!("Solving was interrupted");
                self.resolution = Resolution::Unsolved;
            } else if let Some(err) = solver.take_last_error() {
                error!("Solving failed: {}", err);
                self.resolution = Resolution::Unsolved;
            } else {
                unreachable!()
            }

            Ok(())
        }
    }

    pub fn get_firing_components(&self) -> Option<&[FiringComponent]> {
        if let Resolution::Solved(ref fcs) = self.resolution {
            Some(fcs.as_slice())
        } else {
            None
        }
    }
}