Skip to content

Commit

Permalink
Merge pull request #23 from rpl-cmu/easton/printing
Browse files Browse the repository at this point in the history
Printing Upgrades
  • Loading branch information
contagon authored Dec 13, 2024
2 parents 34a6964 + 6da53e5 commit 8add20a
Show file tree
Hide file tree
Showing 19 changed files with 562 additions and 126 deletions.
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ paste = "1.0.15"
downcast-rs = "1.2.1"
log = "0.4.22"
factrs-proc = { version = "0.1.0", path = "./factrs-proc" }
pad-adapter = "0.1.1"

# numerical
faer = { version = "0.19.4", default-features = false, features = [
Expand Down
2 changes: 1 addition & 1 deletion examples/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ fn main() {

// Convert the JSON string back to a Point.
let deserialized: Values = serde_json::from_str(&serialized).unwrap();
println!("deserialized = {:#?}", deserialized);
println!("deserialized = {:#}", deserialized);

// ------------------------- Serialize graph ------------------------- //
let prior = PriorResidual::new(x);
Expand Down
73 changes: 71 additions & 2 deletions src/containers/factor.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use super::{Symbol, TypedSymbol};
use pad_adapter::PadAdapter;

use super::{DefaultSymbolHandler, KeyFormatter, Symbol, TypedSymbol};
use crate::{
containers::{Key, Values},
dtype,
Expand All @@ -9,6 +11,11 @@ use crate::{
robust::{RobustCost, L2},
};

use std::{
fmt::{self, Write},
marker::PhantomData,
};

/// Main structure to represent a factor in the graph.
///
/// $$ \blue{\rho_i}(||\purple{r_i}(\green{\Theta})||_{\red{\Sigma_i}} ) $$
Expand Down Expand Up @@ -48,7 +55,6 @@ use crate::{
/// let factor = FactorBuilder::new1(residual,
/// X(0)).noise(noise).robust(robust).build();
/// ```
#[derive(Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Factor {
keys: Vec<Key>,
Expand Down Expand Up @@ -107,6 +113,69 @@ impl Factor {
}
}

impl fmt::Debug for Factor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
FactorFormatter::<DefaultSymbolHandler>::new(self).fmt(f)
}
}

/// Formatter for a factor
///
/// Specifically, this can be used if custom symbols are desired. See `tests/custom_key` for examples.
pub struct FactorFormatter<'f, KF> {
factor: &'f Factor,
kf: PhantomData<KF>,
}

impl<'f, KF> FactorFormatter<'f, KF> {
pub fn new(factor: &'f Factor) -> Self {
Self {
factor,
kf: Default::default(),
}
}
}

impl<'f, KF: KeyFormatter> fmt::Debug for FactorFormatter<'f, KF> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
f.write_str("Factor {\n")?;
let mut pad = PadAdapter::new(f);
// Keys
pad.write_str("key: [")?;
for (i, key) in self.factor.keys().iter().enumerate() {
if i > 0 {
pad.write_str(", ")?;
}
KF::fmt(&mut pad, *key)?;
}
pad.write_str("]\n")?;
// Residual
writeln!(pad, "res: {:#?}", self.factor.residual)?;
// Noise
writeln!(pad, "noi: {:#?}", self.factor.noise)?;
// Robust
writeln!(pad, "rob: {:#?}", self.factor.robust)?;
f.write_str("}")?;
} else {
f.write_str("Factor { ")?;
for (i, key) in self.factor.keys().iter().enumerate() {
if i > 0 {
f.write_str(", ")?;
}
KF::fmt(f, *key)?;
}
write!(
f,
"], residual: {:?}, noise: {:?}, robust: {:?} }}",
self.factor.residual, self.factor.noise, self.factor.robust
)?;
}

Ok(())
}
}

/// Builder for a factor.
///
/// If the noise model or robust kernel aren't set, they default to [UnitNoise]
Expand Down
57 changes: 55 additions & 2 deletions src/containers/graph.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
use pad_adapter::PadAdapter;
use std::{
fmt::{Debug, Write},
marker::PhantomData,
};

// Once "debug_closure_helpers" is stabilized, we won't need this anymore
// Need custom debug to handle pretty key printing at the moment
// Pad adapter helps with the pretty printing
use crate::containers::factor::FactorFormatter;

use faer::sparse::SymbolicSparseColMat;

use super::{Idx, Values, ValuesOrder};
use super::{DefaultSymbolHandler, Idx, KeyFormatter, Values, ValuesOrder};
use crate::{containers::Factor, dtype, linear::LinearGraph};

/// Structure to represent a nonlinear factor graph
Expand All @@ -27,7 +38,7 @@ use crate::{containers::Factor, dtype, linear::LinearGraph};
/// let mut graph = Graph::new();
/// graph.add_factor(factor);
/// ```
#[derive(Default, Debug)]
#[derive(Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Graph {
factors: Vec<Factor>,
Expand Down Expand Up @@ -97,6 +108,48 @@ impl Graph {
}
}

impl Debug for Graph {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
GraphFormatter::<DefaultSymbolHandler>::new(self).fmt(f)
}
}

/// Formatter for a graph
///
/// Specifically, this can be used if custom symbols are desired. See `tests/custom_key` for examples.
pub struct GraphFormatter<'g, KF> {
graph: &'g Graph,
kf: PhantomData<KF>,
}

impl<'g, KF> GraphFormatter<'g, KF> {
pub fn new(graph: &'g Graph) -> Self {
Self {
graph,
kf: Default::default(),
}
}
}

impl<'g, KF: KeyFormatter> Debug for GraphFormatter<'g, KF> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if f.alternate() {
f.write_str("Graph [\n")?;
let mut pad = PadAdapter::new(f);
for factor in self.graph.factors.iter() {
writeln!(pad, "{:#?},", FactorFormatter::<KF>::new(factor))?;
}
f.write_str("]")
} else {
f.write_str("Graph [ ")?;
for factor in self.graph.factors.iter() {
write!(f, "{:?}, ", FactorFormatter::<KF>::new(factor))?;
}
f.write_str("]")
}
}
}

/// Simple structure to hold the order of the graph
///
/// Specifically this is used to cache linearization results such as the order
Expand Down
8 changes: 4 additions & 4 deletions src/containers/mod.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
//! Various containers for storing variables, residuals, factors, etc.
mod symbol;
pub use symbol::{DefaultSymbol, Key, Symbol, TypedSymbol};
pub use symbol::{DefaultSymbolHandler, Key, KeyFormatter, Symbol, TypedSymbol};

mod values;
pub use values::Values;
pub use values::{Values, ValuesFormatter};

mod order;
pub use order::{Idx, ValuesOrder};

mod graph;
pub use graph::{Graph, GraphOrder};
pub use graph::{Graph, GraphFormatter, GraphOrder};

mod factor;
pub use factor::{Factor, FactorBuilder};
pub use factor::{Factor, FactorBuilder, FactorFormatter};
Loading

0 comments on commit 8add20a

Please sign in to comment.