Skip to content

Commit

Permalink
clippy
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexandreDubray committed Aug 4, 2023
1 parent 5bf3ca2 commit 0594ae7
Show file tree
Hide file tree
Showing 6 changed files with 52 additions and 48 deletions.
48 changes: 24 additions & 24 deletions src/compiler/circuit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ struct DistributionNode {
/// the next node to be evaluated is i+1 and is likely to be stored in cache.
/// - When a node sends its value to its outputs, the same optimization happens (as loading the first output is likely to implies that
/// the following outputs are in cache).
pub struct DAC {
pub struct Dac {
/// Internal nodes of the circuit
nodes: Vec<CircuitNode>,
/// Input nodes of the circuit
Expand All @@ -91,7 +91,7 @@ pub struct DAC {
outputs: Vec<CircuitNodeIndex>,
}

impl DAC {
impl Dac {

/// Creates a new empty DAC. An input node is created for each distribution in the graph.
pub fn new(graph: &Graph) -> Self {
Expand Down Expand Up @@ -160,7 +160,7 @@ impl DAC {
self.nodes[output.0].input_distributions.push((distribution, value));
}

fn swap(&mut self, new: &mut Vec<usize>, old: &mut Vec<usize>, i: usize, j: usize) {
fn swap(&mut self, new: &mut [usize], old: &mut [usize], i: usize, j: usize) {
self.nodes.swap(i, j);
new[old[i]] = j;
new[old[j]] = i;
Expand Down Expand Up @@ -287,7 +287,7 @@ impl DAC {
/// In such case it can be bypass (it does not change its input)
fn is_neutral(&self, node: usize) -> bool {
!self.nodes[node].to_remove &&
self.nodes[node].outputs.len() != 0 &&
!self.nodes[node].outputs.is_empty() &&
self.nodes[node].inputs.len() + self.nodes[node].input_distributions.len() == 1
}

Expand All @@ -307,10 +307,10 @@ impl DAC {
changed = true;
self.nodes[node].to_remove = true;
// Either it has an input from another internal node, or from a distribution node
if self.nodes[node].inputs.len() != 0 {
if !self.nodes[node].inputs.is_empty() {
let input = *self.nodes[node].inputs.iter().next().unwrap();
// Removing the node from the output of the input node
if let Some(idx) = self.nodes[input.0].outputs.iter().position(|x| (*x).0 == node) {
if let Some(idx) = self.nodes[input.0].outputs.iter().position(|x| x.0 == node) {
self.nodes[input.0].outputs.remove(idx);
}
for out_id in 0..self.nodes[node].outputs.len() {
Expand Down Expand Up @@ -419,7 +419,7 @@ impl DAC {
// Various methods for dumping the compiled diagram, including standardized format and graphviz (inspired from https://github.com/xgillard/ddo )

// Visualization as graphviz DOT file
impl DAC {
impl Dac {

fn distribution_node_id(&self, node: DistributionNodeIndex) -> usize {
node.0
Expand All @@ -444,15 +444,15 @@ impl DAC {

for node in (0..self.distribution_nodes.len()).map(DistributionNodeIndex) {
let id = self.distribution_node_id(node);
out.push_str(&DAC::node(id, &dist_node_attributes, &format!("d{}", id)));
out.push_str(&Dac::node(id, &dist_node_attributes, &format!("d{}", id)));
}

for node in (0..self.nodes.len()).map(CircuitNodeIndex) {
let id = self.sp_node_id(node);
if self.nodes[node.0].is_mul {
out.push_str(&DAC::node(id, &prod_node_attributes, &prod_node_label));
out.push_str(&Dac::node(id, &prod_node_attributes, &prod_node_label));
} else {
out.push_str(&DAC::node(id, &sum_node_attributes, &sum_node_label));
out.push_str(&Dac::node(id, &sum_node_attributes, &sum_node_label));
}
}

Expand All @@ -462,7 +462,7 @@ impl DAC {
for (output, value) in self.distribution_nodes[node.0].outputs.iter().copied() {
let to = self.sp_node_id(output);
let f_value = format!("{:.5}",self.distribution_nodes[node.0].probabilities[value]);
out.push_str(&DAC::edge(from, to, Some(f_value)));
out.push_str(&Dac::edge(from, to, Some(f_value)));
}
}

Expand All @@ -472,7 +472,7 @@ impl DAC {
let end = start + self.nodes[node.0].number_outputs;
for output in self.outputs[start..end].iter().copied() {
let to = self.sp_node_id(output);
out.push_str(&DAC::edge(from, to, None));
out.push_str(&Dac::edge(from, to, None));
}
}
out.push_str("}\n");
Expand All @@ -485,17 +485,17 @@ impl DAC {

fn edge(from: usize, to: usize, label: Option<String>) -> String {
let label = if let Some(v) = label {
format!("{}", v)
v
} else {
format!("")
String::new()
};
format!("\t{from} -> {to} [penwidth=1,label=\"{label}\"];\n")
}
}

// Custom text format for the network

impl fmt::Display for DAC {
impl fmt::Display for Dac {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "dspn {} {}", self.distribution_nodes.len(), self.nodes.len())?;
for node in self.distribution_nodes.iter() {
Expand All @@ -506,7 +506,7 @@ impl fmt::Display for DAC {
for (output, value) in node.outputs.iter().copied() {
write!(f, " {} {}", output.0, value)?;
}
writeln!(f, "")?;
writeln!(f)?;
}
for node in self.nodes.iter() {
if node.is_mul {
Expand All @@ -517,13 +517,13 @@ impl fmt::Display for DAC {
for output_id in node.ouput_start..(node.ouput_start+node.number_outputs) {
write!(f, " {}", self.outputs[output_id].0)?;
}
writeln!(f, "")?;
writeln!(f)?;
}
fmt::Result::Ok(())
}
}

impl DAC {
impl Dac {

pub fn from_file(filepath: &PathBuf) -> Self {
let mut spn = Self {
Expand All @@ -538,7 +538,7 @@ impl DAC {
let split = l.split_whitespace().collect::<Vec<&str>>();
if l.starts_with("dspn") {
// Do things ?
} else if l.starts_with("d") {
} else if l.starts_with('d') {
let dom_size = split[1].parse::<usize>().unwrap();
let probabilities = split[2..(2+dom_size)].iter().map(|s| s.parse::<f64>().unwrap()).collect::<Vec<f64>>();
let mut outputs: Vec<(CircuitNodeIndex, usize)> = vec![];
Expand All @@ -551,18 +551,18 @@ impl DAC {
probabilities,
outputs,
});
} else if l.starts_with("x") || l.starts_with("+") {
} else if l.starts_with('x') || l.starts_with('+') {
let start = spn.outputs.len();
for i in 1..split.len() {
spn.outputs.push(CircuitNodeIndex(split[i].parse::<usize>().unwrap()));
for item in split.iter().skip(1) {
spn.outputs.push(CircuitNodeIndex(item.parse::<usize>().unwrap()));
}
let end = spn.outputs.len();
spn.nodes.push(CircuitNode {
value: if l.starts_with("x") { f128!(1.0) } else { f128!(0.0) },
value: if l.starts_with('x') { f128!(1.0) } else { f128!(0.0) },
outputs: vec![],
inputs: FxHashSet::default(),
input_distributions: vec![],
is_mul: l.starts_with("x"),
is_mul: l.starts_with('x'),
ouput_start: start,
number_outputs: end - start,
layer: 0,
Expand Down
8 changes: 4 additions & 4 deletions src/compiler/exact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ where
}
}

fn expand_sum_node(&mut self, spn: &mut DAC, component: ComponentIndex, distribution: DistributionIndex) -> Option<CircuitNodeIndex> {
fn expand_sum_node(&mut self, spn: &mut Dac, component: ComponentIndex, distribution: DistributionIndex) -> Option<CircuitNodeIndex> {
let mut children: Vec<CircuitNodeIndex> = vec![];
for variable in self.graph.distribution_variable_iter(distribution) {
self.state.save_state();
Expand All @@ -104,7 +104,7 @@ where
}
}

fn expand_prod_node(&mut self, spn: &mut DAC, component: ComponentIndex) -> Option<CircuitNodeIndex> {
fn expand_prod_node(&mut self, spn: &mut Dac, component: ComponentIndex) -> Option<CircuitNodeIndex> {
let mut prod_node: Option<CircuitNodeIndex> = if self.propagator.has_assignments() || self.propagator.has_unconstrained_distribution() {
let node = spn.add_prod_node();
for (distribution, variable, value) in self.propagator.assignments_iter() {
Expand Down Expand Up @@ -176,7 +176,7 @@ where
prod_node
}

pub fn compile(&mut self) -> Option<DAC> {
pub fn compile(&mut self) -> Option<Dac> {
// First set the number of clause in the propagator. This can not be done at the initialization of the propagator
// because we need it to parse the input file as some variables might be detected as always being true or false.
self.propagator.set_number_clauses(self.graph.number_clauses());
Expand All @@ -185,7 +185,7 @@ where
Err(_) => None,
Ok(_) => {
self.branching_heuristic.init(&self.graph, &self.state);
let mut spn = DAC::new(&self.graph);
let mut spn = Dac::new(&self.graph);
match self.expand_prod_node(&mut spn, ComponentIndex(0)) {
None => None,
Some(_) => {
Expand Down
18 changes: 9 additions & 9 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use heuristics::branching::*;
use search::{ExactDefaultSolver, ExactQuietSolver, ApproximateDefaultSolver, ApproximateQuietSolver};
use propagator::FTReachablePropagator;
use compiler::exact::ExactDACCompiler;
use compiler::circuit::DAC;
use compiler::circuit::Dac;

#[derive(Debug, Parser)]
#[clap(name="Schlandals", version, author, about)]
Expand Down Expand Up @@ -118,10 +118,10 @@ enum Branching {
}

fn read_compiled(input: PathBuf, dotfile: Option<PathBuf>) {
let mut dac = DAC::from_file(&input);
let mut dac = Dac::from_file(&input);
if let Some(f) = dotfile {
let out = dac.as_graphviz();
let mut outfile = File::create(&f).unwrap();
let mut outfile = File::create(f).unwrap();
match outfile.write(out.as_bytes()) {
Ok(_) => (),
Err(e) => println!("Culd not write the PC into the file: {:?}", e),
Expand Down Expand Up @@ -150,14 +150,14 @@ fn run_compilation(input: PathBuf, branching: Branching, fdac: Option<PathBuf>,
println!("Compilation successful");
if let Some(f) = dotfile {
let out = dac.as_graphviz();
let mut outfile = File::create(&f).unwrap();
let mut outfile = File::create(f).unwrap();
match outfile.write(out.as_bytes()) {
Ok(_) => (),
Err(e) => println!("Culd not write the circuit into the dot file: {:?}", e),
}
}
if let Some(f) = fdac {
let mut outfile = File::create(&f).unwrap();
let mut outfile = File::create(f).unwrap();
match outfile.write(format!("{}", dac).as_bytes()) {
Ok(_) => (),
Err(e) => println!("Culd not write the circuit into the fdac file: {:?}", e),
Expand All @@ -179,8 +179,8 @@ fn run_approx_search(input: PathBuf, branching: Branching, statistics: bool, mem
Branching::MinOutDegree => Box::<MinOutDegree>::default(),
Branching::MaxDegree => Box::<MaxDegree>::default(),
};
let mlimit = if memory.is_some() {
memory.unwrap()
let mlimit = if let Some(m) = memory {
m
} else {
let sys = System::new_all();
sys.total_memory() / 1000000
Expand Down Expand Up @@ -221,8 +221,8 @@ fn run_search(input: PathBuf, branching: Branching, statistics: bool, memory: Op
Branching::MinOutDegree => Box::<MinOutDegree>::default(),
Branching::MaxDegree => Box::<MaxDegree>::default(),
};
let mlimit = if memory.is_some() {
memory.unwrap()
let mlimit = if let Some(m) = memory {
m
} else {
let sys = System::new_all();
sys.total_memory() / 1000000
Expand Down
18 changes: 11 additions & 7 deletions src/propagator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,12 @@ pub struct FTReachablePropagator<const C: bool> {
propagation_prob: Float,
}

impl<const C: bool> Default for FTReachablePropagator<C> {
fn default() -> Self {
Self::new()
}
}

impl<const C: bool> FTReachablePropagator<C> {

pub fn new() -> Self {
Expand Down Expand Up @@ -137,14 +143,12 @@ impl<const C: bool> FTReachablePropagator<C> {
fn propagate_unconstrained_distribution(&mut self, g: &Graph, distribution: DistributionIndex, state: &StateManager) {
if C {
self.unconstrained_distributions.push(distribution);
} else {
if g.distribution_number_false(distribution, state) != 0 {
let mut p = f128!(0.0);
for w in g.distribution_variable_iter(distribution).filter(|v| !g.is_variable_fixed(*v, state)).map(|v| g.get_variable_weight(v).unwrap()) {
p += w;
}
self.propagation_prob *= &p;
} else if g.distribution_number_false(distribution, state) != 0 {
let mut p = f128!(0.0);
for w in g.distribution_variable_iter(distribution).filter(|v| !g.is_variable_fixed(*v, state)).map(|v| g.get_variable_weight(v).unwrap()) {
p += w;
}
self.propagation_prob *= &p;
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/search/approximate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,8 +289,8 @@ where
if ub <= 0.0 {
return Some(f128!(0.0));
}
if ub.clone() <= lb.clone()*(1.0 + self.epsilon).powf(2.0) {
let approximation = f128!((lb.clone()*&ub).sqrt());
if ub <= lb.clone()*(1.0 + self.epsilon).powf(2.0) {
let approximation = f128!((lb*&ub).sqrt());
Some(approximation)
} else {
None
Expand Down
4 changes: 2 additions & 2 deletions tests/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use schlandals::*;
use schlandals::search::ExactQuietSolver;
use search_trail::StateManager;
use schlandals::compiler::exact::ExactDACCompiler;
use schlandals::compiler::circuit::DAC;
use schlandals::compiler::circuit::Dac;

use std::path::PathBuf;
use tempfile::Builder;
Expand Down Expand Up @@ -64,7 +64,7 @@ macro_rules! test_input_with_branching {
let spn = compiler.compile().unwrap();
let mut file = Builder::new().prefix("tmp").suffix(".pc").tempfile().unwrap();
writeln!(file, "{}", spn).unwrap();
let mut read_spn = DAC::from_file(&PathBuf::from(&file.path()));
let mut read_spn = Dac::from_file(&PathBuf::from(&file.path()));
let sol = read_spn.evaluate();
let expected = Float::with_val(113, $value);
assert!((expected - sol).abs() < 0.000001);
Expand Down

0 comments on commit 0594ae7

Please sign in to comment.