Skip to content

Commit

Permalink
fix: linting
Browse files Browse the repository at this point in the history
  • Loading branch information
LucasBerger committed Aug 25, 2023
1 parent f11219f commit 8866b82
Show file tree
Hide file tree
Showing 10 changed files with 143 additions and 131 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
things to install:

- LKH binary (either install from source or just download)
- setup dwave.conf in user directory
- install poetry to use as a package manager for the python libraries
- install rust nightly version from 2023-07-01. use rustup to change the version used in this directory
37 changes: 21 additions & 16 deletions python/lkh-interface/src/main.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,34 @@
import argparse
from lkh import solve, LKHProblem

from lkh import LKHProblem, solve
from tsplib95.models import StandardProblem

parser = argparse.ArgumentParser(
prog='LKH-3 Interface',
description='A CLI Program to initiate solving CVRP files with LKH-3',
epilog='Made by Lucas Berger for scientific purposes')
prog="LKH-3 Interface",
description="A CLI Program to initiate solving CVRP files with LKH-3",
epilog="Made by Lucas Berger for scientific purposes",
)


parser.add_argument('tsplib_file')
parser.add_argument('--lkh-instance', default='../../bin/LKH')
parser.add_argument('--output-file')
parser.add_argument('-t', '--max-trials', default=1000)
parser.add_argument('-r', '--runs', default=10)
parser.add_argument("tsplib_file")
parser.add_argument("--lkh-instance", default="../../bin/LKH")
parser.add_argument("--output-file")
parser.add_argument("-t", "--max-trials", default=1000)
parser.add_argument("-r", "--runs", default=10)

args = parser.parse_args()


problem = LKHProblem.load(args.tsplib_file)

if sum(problem.demands.values()) <= problem.capacity:
problem.type = "TSP"

if len(problem.node_coords.values()) > 2:
extra = {}
tours = solve(args.lkh_instance, problem=problem, max_trials=args.max_trials, **extra)
tours = solve(
args.lkh_instance, problem=problem, max_trials=args.max_trials, **extra
)

tour = StandardProblem()

Expand All @@ -33,11 +37,12 @@
tour.name = problem.name + " solution"
else:
tour = StandardProblem()
tour.tours = [filter(lambda key: key not in problem.depots, problem.node_coords.keys())]
tour.tours = [
filter(lambda key: key not in problem.depots, problem.node_coords.keys())
]
tour.type = "TOUR"
tour.name = problem.name + " solution"



if (args.output_file is not None):
tour.save(args.output_file)
if args.output_file is not None:
tour.save(args.output_file)
2 changes: 1 addition & 1 deletion python/qubo_solver/README.md
Original file line number Diff line number Diff line change
@@ -1 +1 @@
qubo-solver
# Python QUBO Solver
35 changes: 18 additions & 17 deletions python/qubo_solver/src/main.py
Original file line number Diff line number Diff line change
@@ -1,40 +1,41 @@
import argparse
import os
from datetime import datetime
from typing import Literal
import os
from dimod import BINARY, BinaryQuadraticModel
import argparse

from dimod import BINARY, BinaryQuadraticModel
from solver import solve_with


def main():

parser = argparse.ArgumentParser(
prog='DWave QUBO solver',
description='A CLI Program to initiate solving COOrdinate files with DWave Systems',
epilog='Made by Lucas Berger for scientific purposes')
prog="DWave QUBO solver",
description="A CLI Program to initiate solving COOrdinate files with DWave Systems",
epilog="Made by Lucas Berger for scientific purposes",
)

parser.add_argument("coo_file")
parser.add_argument(
"type", default="sim", choices=["sim", "hybrid", "qbsolv", "direct"]
)
parser.add_argument("--output-file")

parser.add_argument('coo_file')
parser.add_argument('type', default='sim', choices=['sim', 'hybrid', 'qbsolv', 'direct'])
parser.add_argument('--output-file')

args = parser.parse_args()
type: Literal['sim', 'hybrid', 'qbsolv', 'direct'] = args.type
type: Literal["sim", "hybrid", "qbsolv", "direct"] = args.type

with open(args.coo_file) as problem:
bqm = BinaryQuadraticModel.from_coo(problem, vartype=BINARY)

filename = os.path.basename(args.coo_file)

last = datetime.now().timestamp()
print("started")

sampleset = solve_with(bqm, type, filename)

now = datetime.now().timestamp()
print(f"ended after {now - last}")

if args.output_file:
with open(args.output_file, "w") as out:
out.writelines([f"{bin}\n" for bin in sampleset.first.sample.values()])
Expand Down
20 changes: 11 additions & 9 deletions python/qubo_solver/src/solver.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,30 @@
from typing import Literal
from dimod import BinaryQuadraticModel, Sampler, SimulatedAnnealingSampler, SampleSet

from dimod import BinaryQuadraticModel, Sampler, SampleSet, SimulatedAnnealingSampler
from dwave.system import DWaveSampler, EmbeddingComposite, LeapHybridSampler
from hybrid import SimplifiedQbsolv, State

solvertype = Literal['sim', 'hybrid', 'qbsolv', 'direct']
solvertype = Literal["sim", "hybrid", "qbsolv", "direct"]


def solve_with(bqm: BinaryQuadraticModel, type: solvertype, label: str) -> SampleSet:

if type == 'sim':
if type == "sim":
sampler: Sampler = SimulatedAnnealingSampler()
return sampler.sample(bqm)
elif type == 'direct':
elif type == "direct":
sampler: Sampler = EmbeddingComposite(DWaveSampler())
return sampler.sample(
bqm, num_reads=250, label=f"DWaveSampler with embedding num_reads=250 {label}"
bqm,
num_reads=250,
label=f"DWaveSampler with embedding num_reads=250 {label}",
)
elif type == 'hybrid':
elif type == "hybrid":
sampler: Sampler = LeapHybridSampler()
return sampler.sample(
bqm, time_limit=10, label=f"LeapHybridSampler num_reads=250: {label}"
)
elif type == 'qbsolv':
elif type == "qbsolv":
init_state = State.from_problem(bqm)
workflow = SimplifiedQbsolv()
final_state = workflow.run(init_state).result()
return final_state.samples

14 changes: 6 additions & 8 deletions src/logic/clustering/cluster_tsp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@ fn distance(a: &Vec<f64>, b: &Vec<f64>) -> Option<f64> {
}

impl ClusterTspClustering {
fn choose_core<'a>(&'a self, problem: &Tsp, rest: &'a Vec<usize>) -> Option<&usize> {
fn choose_core<'a>(&'a self, _problem: &Tsp, rest: &'a [usize]) -> Option<&usize> {
rest.first()
}

fn center(&self, problem: &Tsp, cluster: &Vec<usize>) -> Vec<f64> {
if cluster.len() == 0 {
if cluster.is_empty() {
return vec![
0.0f64;
problem
Expand Down Expand Up @@ -53,7 +53,7 @@ impl ClusterTspClustering {
.collect()
}

fn cluster_demand(&self, problem: &Tsp, cluster: &Vec<usize>) -> f64 {
fn cluster_demand(&self, problem: &Tsp, cluster: &[usize]) -> f64 {
problem
.demands()
.iter()
Expand Down Expand Up @@ -84,9 +84,8 @@ impl ClusteringTrait for ClusterTspClustering {
let mut assignments: Vec<Vec<usize>> = vec![];

loop {
let core = match self.choose_core(problem, &not_assigned) {
Some(core) => core,
None => break,
if self.choose_core(problem, &not_assigned).is_none() {
break;
};

let mut cluster = vec![];
Expand Down Expand Up @@ -118,8 +117,7 @@ impl ClusteringTrait for ClusterTspClustering {
cluster.push(closest.id());
not_assigned = not_assigned
.iter()
.filter(|id| **id != closest.id())
.map(|id| *id)
.filter_map(|id| if *id != closest.id() { Some(*id) } else { None })
.collect()
} else {
break 'inner;
Expand Down
Loading

0 comments on commit 8866b82

Please sign in to comment.