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
//! # CasADi Rust interface
//!
//! This is a Rust interface to C functions generated by Rust

#![no_std]
extern crate libc;
use libc::{c_double, c_int};

extern "C" {

    fn icasadi_num_static_parameters() -> c_int;

    fn icasadi_num_decision_variables() -> c_int;

    fn icasadi_cost_(
        u: *const c_double,
        casadi_static_params: *const c_double,
        cost_value: *mut c_double,
    ) -> c_int;

    fn icasadi_grad_(
        u: *const c_double,
        casadi_static_params: *const c_double,
        cost_jacobian: *mut c_double,
    ) -> c_int;
}

///
/// Number of static parameters
///
pub fn num_static_parameters() -> c_int {
    unsafe { icasadi_num_static_parameters() }
}

///
/// Number of decision variables
///
pub fn num_decision_variables() -> c_int {
    unsafe { icasadi_num_decision_variables() }
}

pub fn icasadi_cost(u: &[f64], casadi_static_params: &[f64], cost_value: &mut f64) -> c_int {
    unsafe { icasadi_cost_(u.as_ptr(), casadi_static_params.as_ptr(), cost_value) }
}

pub fn icasadi_grad(u: &[f64], casadi_static_params: &[f64], cost_jacobian: &mut [f64]) -> c_int {
    unsafe {
        icasadi_grad_(
            u.as_ptr(),
            casadi_static_params.as_ptr(),
            cost_jacobian.as_mut_ptr(),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn tst_num_static() {
        let np = num_static_parameters();
        assert_eq!(np, 2);
    }

    #[test]
    fn tst_num_decision_var() {
        let np = num_decision_variables();
        assert_eq!(np, 10);
    }

    #[test]
    fn tst_call_casadi_cost() {
        let u = [1.0, 2.0, 3.0, -5.0, 1.0, 10.0, 14.0, 17.0, 3.0, 5.0];
        let p = [1.0, -1.0];
        let mut cost_value = 0.0;
        icasadi_cost(&u, &p, &mut cost_value);
        assert!((68.9259 - cost_value).abs() < 1e-4);
    }

    #[test]
    fn tst_call_casadi_grad() {
        let u = [1.0, 2.0, 3.0, -5.0, 1.0, 10.0, 14.0, 17.0, 3.0, 5.0];
        let p = [1.0, -1.0];
        let mut jac = [0.0; 10];
        icasadi_grad(&u, &p, &mut jac);
        assert!((jac[0] - 0.5270086046800542).abs() < 1e-6);
        assert!((jac[5] + 6.9744770099018885).abs() < 1e-6);
    }
}