Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[main < T] Add random walk implementation #113

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions rust/rsmgp-random-walk/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
name = "rsmgp-random-walk"
version = "0.1.0"
edition = "2018"

[dependencies]
c_str_macro = "1.0.2"
rsmgp-sys = { path = "../rsmgp-sys" }
rand = "0.8.4"

[lib]
name = "rust_random_walk"
crate-type = ["cdylib"]
65 changes: 65 additions & 0 deletions rust/rsmgp-random-walk/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
use c_str_macro::c_str;
use rand::Rng;
use rsmgp_sys::edge::*;
use rsmgp_sys::memgraph::*;
use rsmgp_sys::mgp::*;
use rsmgp_sys::path::*;
use rsmgp_sys::result::*;
use rsmgp_sys::rsmgp::*;
use rsmgp_sys::value::*;
use rsmgp_sys::{close_module, define_procedure, define_type, init_module};
use std::ffi::CString;
use std::os::raw::c_int;
use std::panic;

define_procedure!(get, |memgraph: &Memgraph| -> Result<()> {
let args = memgraph.args()?;
let result = memgraph.result_record()?;
let input_start = args.value_at(0)?;
let input_length = args.value_at(1)?;
let path = if let Value::Vertex(ref vertex) = input_start {
Path::make_with_start(vertex, memgraph)
} else {
panic!("Failed to create path from the start vertex.");
}?;
let length = if let Value::Int(value) = input_length {
value
} else {
panic!("Failed to read desired path length.");
};

let mut vertex = if let Value::Vertex(vertex) = input_start {
vertex
} else {
panic!("Failed to read start vertex.");
};
let mut rng = rand::thread_rng();
for _ in 0..length {
let edges: Vec<Edge> = vertex.out_edges()?.collect();
if edges.is_empty() {
break;
}
let edge = &edges[rng.gen_range(0..edges.len())];
vertex = edge.to_vertex()?;
path.expand(edge)?;
}

result.insert_path(c_str!("path"), &path)?;
Ok(())
});

init_module!(|memgraph: &Memgraph| -> Result<()> {
memgraph.add_read_procedure(
get,
c_str!("get"),
&[
define_type!("start", Type::Vertex),
define_type!("length", Type::Int),
],
&[],
&[define_type!("path", Type::Path)],
)?;
Ok(())
});

close_module!(|| -> Result<()> { Ok(()) });