Skip to content

Instantly share code, notes, and snippets.

@RHavar

RHavar/main.rs Secret

Last active August 20, 2017 03:09
Show Gist options
  • Save RHavar/d2249af67e428befb966e4fcf7d95a17 to your computer and use it in GitHub Desktop.
Save RHavar/d2249af67e428befb966e4fcf7d95a17 to your computer and use it in GitHub Desktop.
Weird results with lp-modeler
extern crate lp_modeler;
fn main() {
use lp_modeler::problem::{LpObjective, Problem, LpProblem};
use lp_modeler::operations::{LpOperations};
use lp_modeler::variables::{LpInteger, LpBinary, LpExpression, lp_sum};
use lp_modeler::solvers::{SolverTrait, CbcSolver};
use lp_modeler::problem::LpFileFormat;
let input_coins: Vec<i32> = vec![150, 200, 300, 5000, 20323];
let output_coins = vec![203];
let fee_rate = 300;
// constants
let bytes_per_input = 92;
let transaction_fixed_bytes = 12;
let bytes_per_output = 34;
// problem below
let mut problem = LpProblem::new("Coin Selection", LpObjective::Minimize);
let input_expressions: Vec<(LpBinary, LpExpression)> = input_coins.iter().enumerate().map(|(i,coin)| {
let constraint_name = format!("contains{}", i);
let ref constraint_variable = LpBinary::new(constraint_name.as_str());
(constraint_variable.clone() , *coin * constraint_variable)
}).collect();
let input_amount_expressions = input_expressions.iter().map(|&(_,ref amount)| { amount }).collect();
let input_count_expressions: Vec<LpBinary> = input_expressions.iter().map(|&(ref b,_)| { b.clone() }).collect();
let ouput_sum = output_coins.iter().fold(0, |a,b| a + b);
let input_count = lp_sum(&input_count_expressions);
let transaction_bytes = (input_count * bytes_per_input) + transaction_fixed_bytes + bytes_per_output;
//let tx_fee_required = transaction_bytes * fee_rate;
let must_be_ge_than_ouput = (lp_sum(&input_amount_expressions)).ge(ouput_sum);
problem.add_constraints(&must_be_ge_than_ouput);
// ...but let's try minimize it
let input_count = lp_sum(&input_count_expressions);
problem.add_objective_expression(&input_count);
problem.write_lp("problem.lp");
let solver = CbcSolver::new();
match solver.run(&problem) {
Ok((status, res)) => {
println!("Status {:?}", status);
for (name, value) in res.iter() {
println!("value of {} = {}", name, value);
}
},
Err(msg) => println!("{}", msg),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment