Python package #1

Merged
h4kor merged 7 commits from python_package into main 2022-11-20 16:14:56 +00:00
15 changed files with 518 additions and 247 deletions

2
.gitignore vendored
View File

@ -1,2 +1,4 @@
/target
result/
venv/

3
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"editor.formatOnSave": true,
}

254
Cargo.lock generated
View File

@ -2,6 +2,18 @@
# It is not intended for manual editing.
version = 3
[[package]]
name = "autocfg"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "cfg-if"
version = "1.0.0"
@ -20,24 +32,157 @@ dependencies = [
]
[[package]]
name = "graph"
name = "graph_force"
version = "0.1.0"
dependencies = [
"pyo3",
"rand",
]
[[package]]
name = "indoc"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adab1eaa3408fb7f0c777a73e7465fd5656136fc93b670eb6df3c88c2c1344e3"
[[package]]
name = "libc"
version = "0.2.137"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc7fcc620a3bff7cdd7a365be3376c97191aeaccc2a603e600951e452615bf89"
[[package]]
name = "lock_api"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "435011366fe56583b16cf956f9df0095b405b82d76425bc8981c0e22e60ec4df"
dependencies = [
"autocfg",
"scopeguard",
]
[[package]]
name = "memoffset"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce"
dependencies = [
"autocfg",
]
[[package]]
name = "once_cell"
version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86f0b0d4bf799edbc74508c1e8bf170ff5f41238e5f8225603ca7caaae2b7860"
[[package]]
name = "parking_lot"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f"
dependencies = [
"lock_api",
"parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4dc9e0dc2adc1c69d09143aff38d3d30c5c3f0df0dad82e6d25547af174ebec0"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
"windows-sys",
]
[[package]]
name = "ppv-lite86"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"
[[package]]
name = "proc-macro2"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725"
dependencies = [
"unicode-ident",
]
[[package]]
name = "pyo3"
version = "0.17.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "268be0c73583c183f2b14052337465768c07726936a260f480f0857cb95ba543"
dependencies = [
"cfg-if",
"indoc",
"libc",
"memoffset",
"parking_lot",
"pyo3-build-config",
"pyo3-ffi",
"pyo3-macros",
"unindent",
]
[[package]]
name = "pyo3-build-config"
version = "0.17.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28fcd1e73f06ec85bf3280c48c67e731d8290ad3d730f8be9dc07946923005c8"
dependencies = [
"once_cell",
"target-lexicon",
]
[[package]]
name = "pyo3-ffi"
version = "0.17.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f6cb136e222e49115b3c51c32792886defbfb0adead26a688142b346a0b9ffc"
dependencies = [
"libc",
"pyo3-build-config",
]
[[package]]
name = "pyo3-macros"
version = "0.17.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94144a1266e236b1c932682136dc35a9dee8d3589728f68130c7c3861ef96b28"
dependencies = [
"proc-macro2",
"pyo3-macros-backend",
"quote",
"syn",
]
[[package]]
name = "pyo3-macros-backend"
version = "0.17.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8df9be978a2d2f0cdebabb03206ed73b11314701a5bfe71b0d753b81997777f"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "quote"
version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rand"
version = "0.8.5"
@ -68,8 +213,115 @@ dependencies = [
"getrandom",
]
[[package]]
name = "redox_syscall"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a"
dependencies = [
"bitflags",
]
[[package]]
name = "scopeguard"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
[[package]]
name = "smallvec"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0"
[[package]]
name = "syn"
version = "1.0.103"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "target-lexicon"
version = "0.12.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9410d0f6853b1d94f0e519fb95df60f29d2c1eff2d921ffdf01a4c8a3b54f12d"
[[package]]
name = "unicode-ident"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3"
[[package]]
name = "unindent"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58ee9362deb4a96cef4d437d1ad49cffc9b9e92d202b6995674e928ce684f112"
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "windows-sys"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d2aa71f6f0cbe00ae5167d90ef3cfe66527d6f613ca78ac8024c3ccab9a19e"
[[package]]
name = "windows_aarch64_msvc"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd0f252f5a35cac83d6311b2e795981f5ee6e67eb1f9a7f64eb4500fbc4dcdb4"
[[package]]
name = "windows_i686_gnu"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fbeae19f6716841636c28d695375df17562ca208b2b7d0dc47635a50ae6c5de7"
[[package]]
name = "windows_i686_msvc"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84c12f65daa39dd2babe6e442988fc329d6243fdce47d7d2d155b8d874862246"
[[package]]
name = "windows_x86_64_gnu"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf7b1b21b5362cbc318f686150e5bcea75ecedc74dd157d874d754a2ca44b0ed"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09d525d2ba30eeb3297665bd434a54297e4170c7f1a44cad4ef58095b4cd2028"
[[package]]
name = "windows_x86_64_msvc"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f40009d85759725a34da6d89a94e63d7bdc50a862acf0dbc7c8e488f1edcb6f5"

View File

@ -1,9 +1,13 @@
[package]
name = "graph"
name = "graph_force"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
name = "graph_force"
crate-type = ["cdylib"]
[dependencies]
rand = "0.8.5"
pyo3 = { version = "0.17.3", features = ["extension-module"] }

25
README.md Normal file
View File

@ -0,0 +1,25 @@
# Graph Force
A python/rust library for embedding graphs in 2D space, using force-directed layouts.
## Development
### Setup
```
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
```
### Build
```
maturin develop
```
## Usage
```python
import graph_force
edges = [(0, 1), (1, 2), (2, 3), (3, 0)]
pos = graph_force.layout_from_edge_list(4, edges)
```

14
pyproject.toml Normal file
View File

@ -0,0 +1,14 @@
[build-system]
requires = ["maturin>=0.14,<0.15"]
build-backend = "maturin"
[project]
name = "graph_force"
requires-python = ">=3.7"
classifiers = [
"Programming Language :: Rust",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
]

1
requirements.txt Normal file
View File

@ -0,0 +1 @@
maturin==0.14.1

View File

@ -1,3 +1,4 @@
use rand::Rng;
use std::sync::{Arc, RwLock};
pub struct Node {
pub x: f32,
@ -10,3 +11,26 @@ pub struct Edge {
pub type EdgeMatrix = Arc<RwLock<Vec<Vec<Edge>>>>;
pub type NodeVector = Arc<Vec<RwLock<Node>>>;
pub fn new_edge_matrix(size: usize) -> EdgeMatrix {
let mut matrix = Vec::with_capacity(size);
for _ in 0..size {
let mut row = Vec::with_capacity(size);
for _ in 0..size {
row.push(Edge { weight: 0.0 });
}
matrix.push(row);
}
Arc::new(RwLock::new(matrix))
}
pub fn new_node_vector(size: usize) -> NodeVector {
let mut nodes = Vec::with_capacity(size);
for _ in 0..size {
nodes.push(RwLock::new(Node {
x: rand::thread_rng().gen_range(-0.5..0.5),
y: rand::thread_rng().gen_range(-0.5..0.5),
}));
}
Arc::new(nodes)
}

25
src/lib.rs Normal file
View File

@ -0,0 +1,25 @@
mod graph;
mod runner;
mod spring_model;
mod utils;
use pyo3::prelude::*;
/// Formats the sum of two numbers as string.
#[pyfunction(number_of_nodes, edges, "*", iter = 500, threads = 0)]
fn layout_from_edge_list(
number_of_nodes: usize,
edges: Vec<(u32, u32)>,
iter: usize,
threads: usize,
) -> PyResult<Vec<(f32, f32)>> {
let r = runner::Runner::new(iter, threads);
Ok(r.layout(number_of_nodes, edges))
}
/// A Python module implemented in Rust.
#[pymodule]
fn graph_force(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(layout_from_edge_list, m)?)?;
Ok(())
}

View File

@ -1,116 +0,0 @@
mod utils;
mod spring_model;
mod my_model;
mod graph;
use rand::Rng;
use std::fs::File;
use std::io::prelude::*;
use std::sync::{Arc, RwLock};
use std::thread;
use graph::{EdgeMatrix, NodeVector, Node, Edge};
fn nodes_list(size: usize) -> NodeVector {
let mut nodes = Vec::new();
for _ in 0..size {
let node = RwLock::new(Node {
x: rand::thread_rng().gen_range(-0.5..0.5),
y: rand::thread_rng().gen_range(-0.5..0.5),
});
nodes.push(node);
}
Arc::new(nodes)
}
fn connection_matrix(size: usize) -> EdgeMatrix {
let mut matrix = Vec::with_capacity(size);
for _ in 0..size {
let mut row = Vec::with_capacity(size);
for _ in 0..size {
row.push(Edge { weight: 0.0 });
}
matrix.push(row);
}
Arc::new(RwLock::new(matrix))
}
/**
* Read Graph data from file
* Format:
* - Little endian
* - 4 bytes: number of nodes(int)
* - 12 bytes: nodeA(int), nodeB(int), weight(float)
*/
fn read_graph(file_name: &str) -> (usize, EdgeMatrix) {
let mut file = File::open(file_name).expect("file not found");
let mut size_buffer = [0; 4];
file.read_exact(&mut size_buffer).expect("buffer overflow");
let size = u32::from_le_bytes(size_buffer) as usize;
let matrix_ptr = connection_matrix(size);
{
let mut matrix = matrix_ptr.write().unwrap();
let mut buffer = [0; 12];
while file.read_exact(&mut buffer).is_ok() {
let node_a = u32::from_le_bytes(buffer[0..4].try_into().unwrap()) as usize;
let node_b = u32::from_le_bytes(buffer[4..8].try_into().unwrap()) as usize;
let weight = f32::from_le_bytes(buffer[8..12].try_into().unwrap());
matrix[node_a][node_b].weight = weight;
matrix[node_b][node_a].weight = weight;
}
}
(size, matrix_ptr)
}
fn main() -> std::io::Result<()> {
const ITER: usize = 5000;
const THREADS: usize = 8;
// let edges = connection_matrix(size);
let (size, edges): (usize, EdgeMatrix) = read_graph("../debug_graph.bin");
println!("Size: {}", size);
let mut nodes = nodes_list(size);
let mut nodes_next = nodes_list(size);
// let model = Arc::new(RwLock::new(spring_model::InitialModel::new(edges, size)));
let model = Arc::new(RwLock::new(my_model::MyModel::new(edges, size, ITER)));
let chunks = utils::gen_chunks(size, THREADS);
for epoch in 0..ITER {
model.write().unwrap().prepare(&nodes);
let mut handles = vec![];
for i in 0..THREADS {
let nodes = nodes.clone();
let nodes_next = nodes_next.clone();
let chunk = chunks[i].clone();
let model = model.clone();
let handle = thread::spawn(move || {
for n in chunk {
let update = model.read().unwrap().step(&nodes,n);
let mut result = nodes_next[n].write().unwrap();
result.x = update.x;
result.y = update.y;
}
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
// swap nodes and nodes_next
let tmp = nodes.clone();
nodes = nodes_next.clone();
nodes_next = tmp.clone();
let mut file = File::create(format!("result/{:04}.txt", epoch))?;
for i in 0..size {
let node = nodes[i].read().unwrap();
// println!("{} {}", node.x, node.y);
file.write_all(format!("{} {}\n", node.x, node.y).as_bytes())?;
}
}
Ok(())
}

View File

@ -1,97 +0,0 @@
use crate::graph::{EdgeMatrix, NodeVector, Node};
pub struct MyModel {
edges: EdgeMatrix,
ranks: Vec<f32>,
size: usize,
opt_dist: f32,
c: f32,
dc: f32,
}
impl MyModel {
pub fn new(edges: EdgeMatrix, size: usize, iterations: usize) -> MyModel {
let opt_dist = 1.0;
let c = 0.1;
let mut ranks = vec![0.0; size];
{
let edges = edges.read().unwrap();
for i in 0..size {
ranks[i] = edges[i].iter().map(|e| e.weight).sum();
}
}
MyModel{
edges,
ranks,
size,
opt_dist,
c: c,
dc: c / ((iterations + 1) as f32)
}
}
pub fn prepare(& mut self, _nodes: &NodeVector) {
self.c -= self.dc;
}
pub fn step(&self, nodes: &NodeVector, i_node: usize) -> Node {
let node = nodes[i_node].read().unwrap();
let edges = self.edges.read().unwrap();
let node_x = node.x;
let node_y = node.y;
let mut sum_x = 0.0;
let mut sum_y = 0.0;
for o in 0..self.size {
if o == i_node {
continue;
}
let o_x: f32;
let o_y: f32;
{
let other = nodes[o].read().unwrap();
o_x = other.x;
o_y = other.y;
}
let d_x = o_x - node_x;
let d_y = o_y - node_y;
let dist = (d_x * d_x + d_y * d_y).sqrt();
let unit_x = d_x / dist;
let unit_y = d_y / dist;
let edge = edges[i_node][o].weight;
if edge == 0.0 {
let f_rep = dist.powi(2).recip().min(self.opt_dist);
let f_rep_x = f_rep * unit_x;
let f_rep_y = f_rep * unit_y;
sum_x -= f_rep_x;
sum_y -= f_rep_y;
} else {
let f_spring = 0.5 * (dist - self.opt_dist);
let f_spring_x = f_spring * unit_x;
let f_spring_y = f_spring * unit_y;
sum_x += f_spring_x;
sum_y += f_spring_y;
}
}
// limit the movement
// TODO: find a good upper bound
let sum_l = (sum_x * sum_x + sum_y * sum_y).sqrt().max(1e-6).recip() * self.c;
let sum_x = sum_x * sum_l;
let sum_y = sum_y * sum_l;
Node {
x: node_x + sum_x,
y: node_y + sum_y,
}
}
}

26
src/reader.rs Normal file
View File

@ -0,0 +1,26 @@
/**
* Read Graph data from file
* Format:
* - Little endian
* - 4 bytes: number of nodes(int)
* - 12 bytes: nodeA(int), nodeB(int), weight(float)
*/
fn read_graph(file_name: &str) -> (usize, EdgeMatrix) {
let mut file = File::open(file_name).expect("file not found");
let mut size_buffer = [0; 4];
file.read_exact(&mut size_buffer).expect("buffer overflow");
let size = u32::from_le_bytes(size_buffer) as usize;
let matrix_ptr = connection_matrix(size);
{
let mut matrix = matrix_ptr.write().unwrap();
let mut buffer = [0; 12];
while file.read_exact(&mut buffer).is_ok() {
let node_a = u32::from_le_bytes(buffer[0..4].try_into().unwrap()) as usize;
let node_b = u32::from_le_bytes(buffer[4..8].try_into().unwrap()) as usize;
let weight = f32::from_le_bytes(buffer[8..12].try_into().unwrap());
matrix[node_a][node_b].weight = weight;
matrix[node_b][node_a].weight = weight;
}
}
(size, matrix_ptr)
}

99
src/runner.rs Normal file
View File

@ -0,0 +1,99 @@
use crate::graph::{new_edge_matrix, new_node_vector, EdgeMatrix};
use crate::spring_model;
use crate::utils;
use std::sync::{Arc, RwLock};
use std::thread;
pub struct Runner {
iterations: usize,
threads: usize,
}
impl Runner {
pub fn new(iterations: usize, threads: usize) -> Self {
if threads == 0 {
match std::thread::available_parallelism() {
Ok(threads) => Runner {
iterations,
threads: threads.get(),
},
Err(_) => Runner {
iterations,
threads: 1,
},
}
} else {
Runner {
iterations,
threads,
}
}
}
pub fn layout(
self: &Self,
number_of_nodes: usize,
edge_list: Vec<(u32, u32)>,
) -> Vec<(f32, f32)> {
// let edges = connection_matrix(size);
let edges = edge_matrix_from_edge_list(number_of_nodes, edge_list);
let mut nodes = new_node_vector(number_of_nodes);
let mut nodes_next = new_node_vector(number_of_nodes);
// let model = Arc::new(RwLock::new(spring_model::InitialModel::new(edges, number_of_nodes)));
let model = Arc::new(RwLock::new(spring_model::MyModel::new(
edges,
number_of_nodes,
self.iterations,
)));
let chunks = utils::gen_chunks(number_of_nodes, self.threads);
for _epoch in 0..self.iterations {
model.write().unwrap().prepare(&nodes);
let mut handles = vec![];
for i in 0..self.threads {
let nodes = nodes.clone();
let nodes_next = nodes_next.clone();
let chunk = chunks[i].clone();
let model = model.clone();
let handle = thread::spawn(move || {
for n in chunk {
let update = model.read().unwrap().step(&nodes, n);
let mut result = nodes_next[n].write().unwrap();
result.x = update.x;
result.y = update.y;
}
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
// swap nodes and nodes_next
let tmp = nodes.clone();
nodes = nodes_next.clone();
nodes_next = tmp.clone();
}
let mut result = vec![];
for node in nodes.iter() {
let node = node.read().unwrap();
result.push((node.x, node.y));
}
result
}
}
fn edge_matrix_from_edge_list(number_of_nodes: usize, edge_list: Vec<(u32, u32)>) -> EdgeMatrix {
let matrix_ptr = new_edge_matrix(number_of_nodes as usize);
{
let mut matrix = matrix_ptr.write().unwrap();
for (node_a, node_b) in edge_list {
matrix[node_a as usize][node_b as usize].weight = 1.0;
matrix[node_b as usize][node_a as usize].weight = 1.0;
}
}
matrix_ptr
}

View File

@ -1,38 +1,41 @@
use crate::graph::{EdgeMatrix, NodeVector, Node};
use crate::graph::{EdgeMatrix, Node, NodeVector};
const C_REP: f32 = 0.1;
const C_SPRING: f32 = 0.1;
pub struct InitialModel {
pub struct MyModel {
edges: EdgeMatrix,
size: usize,
opt_dist: f32,
t: f32,
c: f32,
dc: f32,
}
impl InitialModel {
impl MyModel {
pub fn new(edges: EdgeMatrix, size: usize, iterations: usize) -> MyModel {
let opt_dist = 1.0;
let c = 0.1;
pub fn new(edges: EdgeMatrix, size: usize) -> InitialModel {
let opt_dist = 1.0 / (size as f32).sqrt();
InitialModel{ edges, size, opt_dist, t: 0.1 }
MyModel {
edges,
size,
opt_dist,
c: c,
dc: c / ((iterations + 1) as f32),
}
}
pub fn prepare(& mut self, nodes: &NodeVector) {
self.t = 0.1 * f32::max(
nodes.iter().map(|n| n.read().unwrap().x.abs()).reduce(|a, b| a.max(b)).unwrap(),
nodes.iter().map(|n| n.read().unwrap().y.abs()).reduce(|a, b| a.max(b)).unwrap()
);
pub fn prepare(&mut self, _nodes: &NodeVector) {
self.c -= self.dc;
}
pub fn step(&self, nodes: &NodeVector, i_node: usize) -> Node {
let node = nodes[i_node].read().unwrap();
let edges = self.edges.read().unwrap();
let mut node_x = node.x;
let mut node_y = node.y;
let node_x = node.x;
let node_y = node.y;
let mut sum_x = 0.0;
let mut sum_y = 0.0;
for o in 0..self.size {
if o == i_node {
continue;
@ -47,30 +50,37 @@ impl InitialModel {
let d_x = o_x - node_x;
let d_y = o_y - node_y;
let dist = (d_x * d_x + d_y * d_y).sqrt().max(0.01);
let dist = (d_x * d_x + d_y * d_y).sqrt();
let unit_x = d_x / dist;
let unit_y = d_y / dist;
let edge = edges[i_node][o].weight;
if edge == 0.0 {
let f_rep = (C_REP / (dist).powi(2)).min(self.t);
let f_rep = dist.powi(2).recip().min(self.opt_dist);
let f_rep_x = f_rep * unit_x;
let f_rep_y = f_rep * unit_y;
node_x -= f_rep_x;
node_y -= f_rep_y;
sum_x -= f_rep_x;
sum_y -= f_rep_y;
} else {
let f_spring = (C_SPRING * (dist / self.opt_dist).log(2.0)).min(self.t);
let f_spring = 0.5 * (dist - self.opt_dist);
let f_spring_x = f_spring * unit_x;
let f_spring_y = f_spring * unit_y;
node_x += f_spring_x;
node_y += f_spring_y;
sum_x += f_spring_x;
sum_y += f_spring_y;
}
}
// limit the movement
// TODO: find a good upper bound
let sum_l = (sum_x * sum_x + sum_y * sum_y).sqrt().max(1e-6).recip() * self.c;
let sum_x = sum_x * sum_l;
let sum_y = sum_y * sum_l;
Node {
x: node_x,
y: node_y,
}
x: node_x + sum_x,
y: node_y + sum_y,
}
}
}

View File

@ -15,7 +15,7 @@ pub fn gen_chunks(n: usize, chunks: usize) -> Vec<Range<usize>> {
borders
}
#[cfg(test)]
mod test {
use super::*;
@ -36,5 +36,4 @@ mod test {
let borders = gen_chunks(10, 1);
assert_eq!(borders, vec![(0..10)]);
}
}