algeon-cugraph 0.1.2

Safe libcugraph execution component for Algeon
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//! Result types for centrality algorithms.
//!
//! PageRank, eigenvector centrality, Katz centrality, and betweenness
//! centrality return `cugraph_centrality_result_t` with identical field layout,
//! represented by [`CentralityResult`]. [`BetweennessCentralityResult`] wraps
//! it separately because betweenness does not populate `num_iterations` or
//! `converged`.

use std::marker::PhantomData;

use cugraph_sys::{
    cugraph_centrality_result_converged, cugraph_centrality_result_get_num_iterations,
    cugraph_centrality_result_get_values, cugraph_centrality_result_get_vertices, cugraph_centrality_result_t,
    cugraph_edge_centrality_result_get_dst_vertices, cugraph_edge_centrality_result_get_edge_ids,
    cugraph_edge_centrality_result_get_src_vertices, cugraph_edge_centrality_result_get_values,
    cugraph_edge_centrality_result_t, cugraph_hits_result_converged, cugraph_hits_result_get_authorities,
    cugraph_hits_result_get_hub_score_differences, cugraph_hits_result_get_hubs,
    cugraph_hits_result_get_number_of_iterations, cugraph_hits_result_get_vertices, cugraph_hits_result_t,
};

use crate::{
    array::RawDeviceArrayView,
    cuda::{DeviceResourceKind, drop_device_resource},
    cudf_interop::{
        centrality_result_to_dataframe, edge_betweenness_centrality_result_to_dataframe, hits_result_to_dataframe,
    },
    error::{Error, ErrorKind, Result, require_non_null},
    handle::ResourceHandleLease,
    structure::typed_results::{IntegerValues, ScoreValues, VertexIds},
    types::try_from_bool_t,
};

/// Result of a PageRank, eigenvector centrality, or Katz centrality
/// computation.
///
/// Provides access to vertex ids, centrality values, iteration count, and
/// convergence status. Freed on drop.
pub struct CentralityResult {
    raw: *mut cugraph_centrality_result_t,
    device: i32,
    // Keeps a runtime-bound cuGraph handle alive until after Drop frees `raw`.
    _resource_handle_lease: Option<ResourceHandleLease>,
    _nosend_nosync: PhantomData<*mut ()>,
}

impl std::fmt::Debug for CentralityResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CentralityResult").finish_non_exhaustive()
    }
}

impl CentralityResult {
    /// Wrap a raw centrality result pointer.
    ///
    /// # Safety
    ///
    /// `raw` must be a valid, non-null pointer returned by a cuGraph centrality
    /// C API function. Ownership is transferred to this struct.
    pub(crate) unsafe fn from_raw(
        raw: *mut cugraph_centrality_result_t,
        device: i32,
        resource_handle_lease: Option<ResourceHandleLease>,
    ) -> Result<Self> {
        let raw = require_non_null(raw, "CentralityResult::from_raw", "centrality_result")?;
        Ok(Self { raw, device, _resource_handle_lease: resource_handle_lease, _nosend_nosync: PhantomData })
    }

    pub(crate) fn vertices_raw(&self) -> Result<RawDeviceArrayView<'_>> {
        // SAFETY: `self.raw` is a live centrality result owned by this
        // wrapper for the duration of the call.
        let view_ptr = require_non_null(
            unsafe { cugraph_centrality_result_get_vertices(self.raw) },
            "CentralityResult::vertices_raw",
            "vertices",
        )?;
        // SAFETY: cuGraph returns freshly allocated view metadata backed by
        // the live centrality result arrays.
        unsafe {
            RawDeviceArrayView::from_owned_view(
                view_ptr,
                Some(self.device),
                "CentralityResult::vertices_raw",
                "vertices",
            )
        }
    }

    pub(crate) fn values_raw(&self) -> Result<RawDeviceArrayView<'_>> {
        // SAFETY: `self.raw` is a live centrality result owned by this
        // wrapper for the duration of the call.
        let view_ptr = require_non_null(
            unsafe { cugraph_centrality_result_get_values(self.raw) },
            "CentralityResult::values_raw",
            "values",
        )?;
        // SAFETY: cuGraph returns freshly allocated view metadata backed by
        // the live centrality result arrays.
        unsafe {
            RawDeviceArrayView::from_owned_view(view_ptr, Some(self.device), "CentralityResult::values_raw", "values")
        }
    }

    /// Get the vertex ids as a runtime-typed device array view.
    ///
    /// Returns [`VertexIds::I32`] or [`VertexIds::I64`] depending on the
    /// graph's vertex type.
    pub fn vertex_ids(&self) -> Result<VertexIds<'_>> {
        VertexIds::from_raw(self.vertices_raw()?)
    }

    /// Get the centrality scores as a runtime-typed device array view.
    ///
    /// Returns [`ScoreValues::F32`] or [`ScoreValues::F64`] depending on the
    /// graph's weight type.
    pub fn scores(&self) -> Result<ScoreValues<'_>> {
        ScoreValues::from_raw(self.values_raw()?)
    }

    /// Number of iterations performed by the solver.
    pub fn num_iterations(&self) -> usize {
        // SAFETY: `self.raw` is a live centrality result owned by this
        // wrapper for the duration of the call.
        unsafe { cugraph_centrality_result_get_num_iterations(self.raw) }
    }

    /// Whether the algorithm converged within the maximum iterations.
    pub fn converged(&self) -> Result<bool> {
        // SAFETY: `self.raw` is a live centrality result owned by this
        // wrapper for the duration of the call.
        let b = unsafe { cugraph_centrality_result_converged(self.raw) };
        try_from_bool_t(b).ok_or_else(|| {
            Error::new(ErrorKind::Unexpected, "CentralityResult::converged")
                .with_message(format!("invalid bool_t value returned by cuGraph: {}", b.0))
        })
    }

    /// Convert this centrality result to a cudf DataFrame.
    ///
    /// Returns a 2-column DataFrame:
    /// - `"vertex"`: vertex ids with the underlying result dtype (`Int32` or `Int64`)
    /// - `"value"`: centrality values with the underlying result dtype (`Float32` or `Float64`)
    ///
    /// Device-to-device copy: unavoidable because the cugraph C API owns
    /// result memory and frees it on drop. Matches Python cudf/cugraph behavior.
    pub fn to_dataframe(&self, runtime: &cudf::Runtime) -> Result<cudf::DataFrame> {
        centrality_result_to_dataframe(self, runtime)
            .map_err(|e: Error| e.with_operation("CentralityResult::to_dataframe"))
    }
}

impl Drop for CentralityResult {
    fn drop(&mut self) {
        drop_device_resource(
            &mut self.raw,
            self.device,
            "CentralityResult::drop",
            DeviceResourceKind::CentralityResult,
        );
    }
}

/// Result of a betweenness centrality computation.
///
/// Wraps [`CentralityResult`] while omitting `num_iterations` and `converged`.
/// Upstream cuGraph builds betweenness results through the shared iterative
/// constructor defaulting `num_iterations` to 0 and `converged` to false
/// without populating convergence state. Freed on drop.
pub struct BetweennessCentralityResult(CentralityResult);

impl std::fmt::Debug for BetweennessCentralityResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BetweennessCentralityResult").finish_non_exhaustive()
    }
}

pub(crate) struct EdgeCentralityResult {
    raw: *mut cugraph_edge_centrality_result_t,
    device: i32,
    has_edge_ids: bool,
    // Keeps a runtime-bound cuGraph handle alive until after Drop frees `raw`.
    _resource_handle_lease: Option<ResourceHandleLease>,
    _nosend_nosync: PhantomData<*mut ()>,
}

impl EdgeCentralityResult {
    /// # Safety
    ///
    /// `raw` must be a valid, non-null pointer returned by a cuGraph edge
    /// centrality C API function. Ownership is transferred to this struct.
    pub(crate) unsafe fn from_raw(
        raw: *mut cugraph_edge_centrality_result_t,
        device: i32,
        has_edge_ids: bool,
        resource_handle_lease: Option<ResourceHandleLease>,
    ) -> Result<Self> {
        let raw = require_non_null(raw, "EdgeCentralityResult::from_raw", "edge_centrality_result")?;
        Ok(Self {
            raw,
            device,
            has_edge_ids,
            _resource_handle_lease: resource_handle_lease,
            _nosend_nosync: PhantomData,
        })
    }

    fn raw_view(
        &self,
        getter: unsafe extern "C" fn(
            *mut cugraph_edge_centrality_result_t,
        ) -> *mut cugraph_sys::cugraph_type_erased_device_array_view_t,
        operation: &'static str,
        pointer_name: &'static str,
    ) -> Result<RawDeviceArrayView<'_>> {
        let view_ptr = require_non_null(
            // SAFETY: `self.raw` is a live edge centrality result owned by
            // this wrapper for the duration of the call.
            unsafe { getter(self.raw) },
            operation,
            pointer_name,
        )?;
        // SAFETY: cuGraph returns freshly allocated view metadata backed by
        // the live edge centrality result arrays.
        unsafe { RawDeviceArrayView::from_owned_view(view_ptr, Some(self.device), operation, pointer_name) }
    }

    pub(crate) fn sources(&self, operation: &'static str) -> Result<VertexIds<'_>> {
        VertexIds::from_raw(self.raw_view(cugraph_edge_centrality_result_get_src_vertices, operation, "sources")?)
    }

    pub(crate) fn destinations(&self, operation: &'static str) -> Result<VertexIds<'_>> {
        VertexIds::from_raw(self.raw_view(
            cugraph_edge_centrality_result_get_dst_vertices,
            operation,
            "destinations",
        )?)
    }

    pub(crate) fn values(&self, operation: &'static str) -> Result<ScoreValues<'_>> {
        ScoreValues::from_raw(self.raw_view(cugraph_edge_centrality_result_get_values, operation, "values")?)
    }

    pub(crate) fn edge_ids(&self, operation: &'static str) -> Result<Option<IntegerValues<'_>>> {
        if !self.has_edge_ids {
            return Ok(None);
        }
        IntegerValues::from_raw(self.raw_view(cugraph_edge_centrality_result_get_edge_ids, operation, "edge_ids")?)
            .map(Some)
    }
}

impl Drop for EdgeCentralityResult {
    fn drop(&mut self) {
        drop_device_resource(
            &mut self.raw,
            self.device,
            "EdgeCentralityResult::drop",
            DeviceResourceKind::EdgeCentralityResult,
        );
    }
}

/// Result of an edge betweenness centrality computation.
pub struct EdgeBetweennessCentralityResult(EdgeCentralityResult);

impl std::fmt::Debug for EdgeBetweennessCentralityResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EdgeBetweennessCentralityResult").finish_non_exhaustive()
    }
}

impl EdgeBetweennessCentralityResult {
    /// # Safety
    ///
    /// `raw` must be a valid, non-null pointer returned by
    /// `cugraph_edge_betweenness_centrality`. Ownership is transferred to
    /// this struct.
    pub(crate) unsafe fn from_raw(
        raw: *mut cugraph_edge_centrality_result_t,
        device: i32,
        has_edge_ids: bool,
        resource_handle_lease: Option<ResourceHandleLease>,
    ) -> Result<Self> {
        // SAFETY: caller upholds the contract documented on this fn, which matches
        // `EdgeCentralityResult::from_raw`'s requirements (valid non-null pointer
        // with transferred ownership).
        Ok(Self(unsafe { EdgeCentralityResult::from_raw(raw, device, has_edge_ids, resource_handle_lease) }?))
    }

    /// Source vertices for each edge centrality score.
    pub fn sources(&self) -> Result<VertexIds<'_>> {
        self.0.sources("EdgeBetweennessCentralityResult::sources")
    }

    /// Destination vertices for each edge centrality score.
    pub fn destinations(&self) -> Result<VertexIds<'_>> {
        self.0.destinations("EdgeBetweennessCentralityResult::destinations")
    }

    /// Optional edge ids. Returns `None` for graphs built without edge ids.
    pub fn edge_ids(&self) -> Result<Option<IntegerValues<'_>>> {
        self.0.edge_ids("EdgeBetweennessCentralityResult::edge_ids")
    }

    /// Edge betweenness centrality scores.
    pub fn scores(&self) -> Result<ScoreValues<'_>> {
        self.0.values("EdgeBetweennessCentralityResult::scores")
    }

    /// Convert this edge betweenness centrality result to a cudf DataFrame.
    pub fn to_dataframe(&self, runtime: &cudf::Runtime) -> Result<cudf::DataFrame> {
        edge_betweenness_centrality_result_to_dataframe(self, runtime)
            .map_err(|e: Error| e.with_operation("EdgeBetweennessCentralityResult::to_dataframe"))
    }
}

/// Result of a HITS computation.
pub struct HitsResult {
    raw: *mut cugraph_hits_result_t,
    device: i32,
    // Keeps a runtime-bound cuGraph handle alive until after Drop frees `raw`.
    _resource_handle_lease: Option<ResourceHandleLease>,
    _nosend_nosync: PhantomData<*mut ()>,
}

impl std::fmt::Debug for HitsResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HitsResult").finish_non_exhaustive()
    }
}

impl HitsResult {
    /// # Safety
    ///
    /// `raw` must be a valid, non-null pointer returned by `cugraph_hits` or
    /// `cugraph_hits_allow_nonconvergence`. Ownership is transferred to this struct.
    pub(crate) unsafe fn from_raw(
        raw: *mut cugraph_hits_result_t,
        device: i32,
        resource_handle_lease: Option<ResourceHandleLease>,
    ) -> Result<Self> {
        let raw = require_non_null(raw, "HitsResult::from_raw", "hits_result")?;
        Ok(Self { raw, device, _resource_handle_lease: resource_handle_lease, _nosend_nosync: PhantomData })
    }

    fn raw_view(
        &self,
        getter: unsafe extern "C" fn(
            *mut cugraph_hits_result_t,
        ) -> *mut cugraph_sys::cugraph_type_erased_device_array_view_t,
        operation: &'static str,
        pointer_name: &'static str,
    ) -> Result<RawDeviceArrayView<'_>> {
        let view_ptr = require_non_null(
            // SAFETY: `self.raw` is a live HITS result owned by this wrapper
            // for the duration of the call.
            unsafe { getter(self.raw) },
            operation,
            pointer_name,
        )?;
        // SAFETY: cuGraph returns freshly allocated view metadata backed by
        // the live HITS result arrays.
        unsafe { RawDeviceArrayView::from_owned_view(view_ptr, Some(self.device), operation, pointer_name) }
    }

    /// Vertex ids for the hub and authority scores.
    pub fn vertex_ids(&self) -> Result<VertexIds<'_>> {
        VertexIds::from_raw(self.raw_view(cugraph_hits_result_get_vertices, "HitsResult::vertex_ids", "vertices")?)
    }

    /// Hub scores.
    pub fn hub_scores(&self) -> Result<ScoreValues<'_>> {
        ScoreValues::from_raw(self.raw_view(cugraph_hits_result_get_hubs, "HitsResult::hub_scores", "hubs")?)
    }

    /// Authority scores.
    pub fn authority_scores(&self) -> Result<ScoreValues<'_>> {
        ScoreValues::from_raw(self.raw_view(
            cugraph_hits_result_get_authorities,
            "HitsResult::authority_scores",
            "authorities",
        )?)
    }

    /// Difference between hub scores in the final two iterations.
    pub fn hub_score_differences(&self) -> f64 {
        // SAFETY: `self.raw` is a live HITS result owned by this wrapper.
        unsafe { cugraph_hits_result_get_hub_score_differences(self.raw) }
    }

    /// Number of HITS iterations performed.
    pub fn number_of_iterations(&self) -> usize {
        // SAFETY: `self.raw` is a live HITS result owned by this wrapper.
        unsafe { cugraph_hits_result_get_number_of_iterations(self.raw) }
    }

    /// Whether HITS converged within its maximum iterations.
    pub fn converged(&self) -> Result<bool> {
        // SAFETY: `self.raw` is a live HITS result owned by this wrapper.
        let b = unsafe { cugraph_hits_result_converged(self.raw) };
        try_from_bool_t(b).ok_or_else(|| {
            Error::new(ErrorKind::Unexpected, "HitsResult::converged")
                .with_message(format!("invalid bool_t value returned by cuGraph: {}", b.0))
        })
    }

    /// Convert this HITS result to a cudf DataFrame.
    pub fn to_dataframe(&self, runtime: &cudf::Runtime) -> Result<cudf::DataFrame> {
        hits_result_to_dataframe(self, runtime).map_err(|e: Error| e.with_operation("HitsResult::to_dataframe"))
    }
}

impl Drop for HitsResult {
    fn drop(&mut self) {
        drop_device_resource(&mut self.raw, self.device, "HitsResult::drop", DeviceResourceKind::HitsResult);
    }
}

impl BetweennessCentralityResult {
    /// Wrap a raw centrality result pointer as a `BetweennessCentralityResult`.
    ///
    /// # Safety
    ///
    /// `raw` must be a valid, non-null pointer returned by
    /// `cugraph_betweenness_centrality`. Ownership is transferred to this
    /// struct.
    pub(crate) unsafe fn from_raw(
        raw: *mut cugraph_centrality_result_t,
        device: i32,
        resource_handle_lease: Option<ResourceHandleLease>,
    ) -> Result<Self> {
        // SAFETY: the caller transfers ownership of a live cuGraph result to
        // this wrapper on success.
        Ok(Self(unsafe { CentralityResult::from_raw(raw, device, resource_handle_lease) }?))
    }

    /// Get the vertex ids as a runtime-typed device array view.
    ///
    /// Returns [`VertexIds::I32`] or [`VertexIds::I64`] depending on the
    /// graph's vertex type.
    pub fn vertex_ids(&self) -> Result<VertexIds<'_>> {
        self.0.vertex_ids()
    }

    /// Get the betweenness centrality scores as a runtime-typed device array view.
    ///
    /// Returns [`ScoreValues::F32`] or [`ScoreValues::F64`] depending on the
    /// graph's weight type.
    pub fn scores(&self) -> Result<ScoreValues<'_>> {
        self.0.scores()
    }
}

impl BetweennessCentralityResult {
    /// Convert this betweenness centrality result to a cudf DataFrame.
    ///
    /// Returns a 2-column DataFrame:
    /// - `"vertex"`: vertex ids with the underlying result dtype (`Int32` or `Int64`)
    /// - `"value"`: betweenness centrality values with the underlying result
    ///   dtype (`Float32` or `Float64`)
    ///
    /// Device-to-device copy: unavoidable because the cugraph C API owns
    /// result memory and frees it on drop. Matches Python cudf/cugraph behavior.
    pub fn to_dataframe(&self, runtime: &cudf::Runtime) -> Result<cudf::DataFrame> {
        centrality_result_to_dataframe(&self.0, runtime)
            .map_err(|e: Error| e.with_operation("BetweennessCentralityResult::to_dataframe"))
    }
}

#[cfg(test)]
mod tests {
    use std::ptr;

    use super::*;

    #[test]
    fn centrality_result_from_raw_rejects_null() {
        // SAFETY: this exercises the constructor's null guard only.
        let err = match unsafe { CentralityResult::from_raw(ptr::null_mut(), 0, None) } {
            Err(err) => err,
            Ok(_) => panic!("null must be rejected"),
        };
        assert_eq!(err.kind(), ErrorKind::Unexpected);
        assert_eq!(err.operation(), "CentralityResult::from_raw");
    }

    #[test]
    fn edge_centrality_result_from_raw_rejects_null() {
        // SAFETY: this exercises the constructor's null guard only.
        let err = match unsafe { EdgeCentralityResult::from_raw(ptr::null_mut(), 0, false, None) } {
            Err(err) => err,
            Ok(_) => panic!("null must be rejected"),
        };
        assert_eq!(err.kind(), ErrorKind::Unexpected);
        assert_eq!(err.operation(), "EdgeCentralityResult::from_raw");
    }

    #[test]
    fn hits_result_from_raw_rejects_null() {
        // SAFETY: this exercises the constructor's null guard only.
        let err = match unsafe { HitsResult::from_raw(ptr::null_mut(), 0, None) } {
            Err(err) => err,
            Ok(_) => panic!("null must be rejected"),
        };
        assert_eq!(err.kind(), ErrorKind::Unexpected);
        assert_eq!(err.operation(), "HitsResult::from_raw");
    }
}