Struct mosek::Task

source ·
pub struct Task { /* private fields */ }
Expand description

The Task structure encapsulates a MOSEK Task containing problem data, parameters and other information used to solve the optimization problem, and provides the API for interacting with the task data.

The Task object does not support callbacks, but can be passed or shared between threads. If callbacks are needed, use the with_callbacks metho to convert it into a TaskCB object.

Implementations§

source§

impl Task

source

pub fn with_capacity( env: Option<&Env>, numcon: i32, numvar: i32 ) -> Option<Task>

Create a new task in the given environment or with the default environment with a given capacity

source

pub fn from_env(env: Option<&Env>) -> Option<Task>

Create a new task in the given environment or with the default environment

source

pub fn clone(&self) -> Option<Task>

Create a new task in the given environment or with the default environment

Examples found in repository?
examples/concurrent1.rs (line 47)
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
fn optimize_concurrent(task       : &mut mosek::Task,
                       optimizers : &[i32]) -> Vec<(usize,i32,mosek::Task)> {
    let stop = Arc::new(Mutex::new(false));
    optimizers.iter().enumerate()
        .filter_map(|(i,&ot)|
                    if let Some(mut t) = task.clone() {
                        if let Err(_) = t.put_int_param(mosek::Iparam::OPTIMIZER, ot as i32) { None }
                        else {
                            let stopopt = Arc::clone(&stop);
                            Some((i,thread::spawn(move || optimize(t,stopopt))))
                        }
                    }
                    else { None })
        .filter_map(|(i,th)|
                    match th.join().unwrap() {
                        None => None,
                        Some((r,t)) => Some((i,r,t)) } )
        .collect()
}

fn optimize_concurrent_mio(task  : & mut mosek::Task,
                           seeds : &[i32]) -> Vec<(usize,i32,mosek::Task)> {
    let stop = Arc::new(Mutex::new(false));

    seeds.iter().enumerate()
        .filter_map(|(i,&seed)| {
            if let Some(mut t) = task.clone() {
                if let Err(_) = t.put_int_param(mosek::Iparam::MIO_SEED, seed) { None }
                else {
                    let stopopt = Arc::clone(&stop);
                    Some((i,thread::spawn(move || optimize(t,stopopt))))
                }
            }
            else { None }})
        .filter_map(|(i,th)|
                    match th.join().unwrap() {
                        None => None,
                        Some((r,t)) => Some((i,r,t)) } )
        .collect()
}
source

pub fn new() -> Option<Task>

Create a new task in the default environment

Examples found in repository?
examples/writecallback.rs (line 28)
27
28
29
30
31
32
33
34
35
fn main() -> Result<(),String> {
    let mut task = Task::new().unwrap();
    task.read_ptf_string(DFLT_FILE).unwrap();

    task.write_data_stream(|s| if let Err(_) = stdout().write_all(s) { 0 } else { s.len() },
                           Dataformat::PTF,
                           Compresstype::NONE)?;
    Ok(())
}
More examples
Hide additional examples
examples/helloworld.rs (line 15)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
fn main() -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
        };

    task.append_vars(1)?;                           // 1 variable x
    task.put_c_j(0, 1.0)?;                          // c_0 = 1.0
    task.put_var_bound(0, Boundkey::RA, 2.0, 3.0)?; // 2.0 <= x <= 3.0
    task.put_obj_sense(Objsense::MINIMIZE)?;        // minimize

    task.optimize()?;                               // Optimize

    let mut x = vec![0.0; 1];
    task.get_xx(Soltype::ITR, x.as_mut_slice())?;   // Get solution
    println!("Solution x = {}", x[0]);              // Print solution
    return Result::Ok(());
}
examples/opt_server_sync.rs (line 32)
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
fn opt_server_sync(inputfile : FileOrText, addr : String, cert : Option<String>) -> Result<(),String> {
    let mut task = Task::new().unwrap().with_callbacks();
    task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    // Load some data into the task
    match inputfile {
        FileOrText::File(filename) => task.read_data(filename.as_str())?,
        FileOrText::Text(data) => task.read_ptf_string(data.as_str())?
    }

    // Set OptServer URL
    task.put_optserver_host(addr.as_str())?;

    // Path to certificate, if any
    if let Some(cert) = cert {
        task.put_str_param(Sparam::REMOTE_TLS_CERT_PATH, cert.as_str())?;
    }

    // Optimize remotely, no access token
    let _trm = task.optimize()?;

    task.solution_summary(Streamtype::LOG)?;

    Ok(())
}
examples/pinfeas.rs (line 16)
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
fn test_problem() -> Result<mosek::Task,String> {
    let mut task = mosek::Task::new().unwrap();
    task.append_vars(7)?;
    task.append_cons(7)?;
    task.put_c_list(&[0,1,2,3,4,5,6],
                    &[1.0,2.0,5.0,2.0,1.0,2.0,1.0])?;
    task.put_aij_list(&[0,0,1,1,2,2,2,3,3,4,5,5,6,6],
                      &[0,1,2,3,4,5,6,0,4,1,2,5,3,6],
                      &[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0])?;
    task.put_con_bound_slice(0, 7,
                             &[Boundkey::UP,Boundkey::UP,Boundkey::UP,Boundkey::FX,Boundkey::FX,Boundkey::FX,Boundkey::FX],
                             &[-INF, -INF, -INF, 1100.0, 200.0, 500.0, 500.0],
                             &[200.0, 1000.0, 1000.0, 1100.0, 200.0, 500.0, 500.0])?;
    task.put_var_bound_slice_const(0, 7, Boundkey::UP, 0.0, INF)?;
    Ok(task)
}
examples/feasrepairex1.rs (line 37)
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
fn feasrepairex1(filename : FileOrText) -> Result<(),String> {

    let mut task = Task::new().unwrap().with_callbacks();
    task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    match filename {
        FileOrText::File(fname) => task.read_data(fname.as_str())?,
        FileOrText::Text(data) => task.read_lp_string(data.as_str())?
    }
    task.put_int_param(mosek::Iparam::LOG_FEAS_REPAIR, 3)?;

    let wc = vec![1.0; task.get_num_con()? as usize];
    let wx = vec![1.0; task.get_num_var()? as usize];
    task.primal_repair(wc.as_slice(),wc.as_slice(),wx.as_slice(),wx.as_slice())?;

    let sum_viol = task.get_dou_inf(mosek::Dinfitem::PRIMAL_REPAIR_PENALTY_OBJ)?;

    println!("Minimized sum of violations = {}", sum_viol);

    let _ = task.optimize()?;

    task.solution_summary(mosek::Streamtype::MSG)?;

    Ok(())
}
examples/callback.rs (line 109)
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
fn callbackmain(which : &str, data : FileOrText) -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = Task::new().unwrap();
    match data {
        FileOrText::Text(data)  => { task.read_ptf_string(data)? },
        FileOrText::File(fname) => { task.read_data(fname)? }
    }

    task.write_data("callback.ptf")?;

    match which {
        "psim"   => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::PRIMAL_SIMPLEX)?,
        "dsim"   => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::DUAL_SIMPLEX)?,
        "intpnt" => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::INTPNT)?,
        s => return Err(format!("Invalid argument '{}'",s))
    }

    /* Directs the log task stream to the 'printstr' function. */
    task.with_stream_callback(
        Streamtype::LOG,
        & mut |msg| print!("{}",msg),
        |task|
            task.with_info_callback(
                & mut callback,
                |task|
                    task.optimize()
            )
    )?;

    Result::Ok(())
}
source

pub fn with_stream_callback<F, G, R>( &mut self, whichstream: i32, streamfunc: &F, func: G ) -> R
where G: FnMut(&mut Task) -> R, F: Fn(&str),

Temporarily attach a stream printer function to the task.

§Arguments
  • whichstream Which stream to attach to (See Streamtype)
  • streamfunc The callback function
  • func The function to call with the updated task. The stream callback will be attached for the duration of this call.
Examples found in repository?
examples/callback.rs (lines 125-134)
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
fn callbackmain(which : &str, data : FileOrText) -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = Task::new().unwrap();
    match data {
        FileOrText::Text(data)  => { task.read_ptf_string(data)? },
        FileOrText::File(fname) => { task.read_data(fname)? }
    }

    task.write_data("callback.ptf")?;

    match which {
        "psim"   => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::PRIMAL_SIMPLEX)?,
        "dsim"   => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::DUAL_SIMPLEX)?,
        "intpnt" => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::INTPNT)?,
        s => return Err(format!("Invalid argument '{}'",s))
    }

    /* Directs the log task stream to the 'printstr' function. */
    task.with_stream_callback(
        Streamtype::LOG,
        & mut |msg| print!("{}",msg),
        |task|
            task.with_info_callback(
                & mut callback,
                |task|
                    task.optimize()
            )
    )?;

    Result::Ok(())
}
More examples
Hide additional examples
examples/opt_server_async.rs (lines 39-51)
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
fn opt_server_async(inputfile : FileOrText, addr : String, numpolls : usize, cert : Option<String>) -> Result<(),String> {
    // Path to certificate, if any

    let token = {
        Task::new().unwrap()
            .with_stream_callback(
                Streamtype::LOG,
                &mut |msg| print!("{}",msg),
                |task| {
                    match inputfile {
                        FileOrText::File(ref filename) => task.read_data(filename.as_str()).unwrap(),
                        FileOrText::Text(ref data)     => task.read_ptf_string(data.as_str()).unwrap()
                    }
                    if let Some(ref cert) = cert {
                        task.put_str_param(Sparam::REMOTE_TLS_CERT_PATH,cert.as_str())?;
                    }
                    task.async_optimize(addr.as_str(),"")
                }).expect("Failed to submit async optimization")
    };

    println!("Task token = '{}'", token);

    println!("Setting log stream...");
    Task::new().unwrap().with_stream_callback(
        Streamtype::LOG,
        & mut |msg| print!("{}",msg),
        |task| task.with_callback(
            &mut|caller| { println!("caller = {}",caller); false },
            |task| {
                println!("Reading input file '{:?}'...",inputfile);
                match inputfile {
                    FileOrText::File(ref filename) => task.read_data(filename.as_str()).unwrap(),
                    FileOrText::Text(ref data)     => task.read_ptf_string(data.as_str()).unwrap()
                }
                if let Some(ref cert) = cert {
                    task.put_str_param(Sparam::REMOTE_TLS_CERT_PATH,cert.as_str())?;
                }

                println!("Starting polling loop...");
                for i in 0..numpolls {
                    sleep(Duration::new(1,0));

                    println!("\tpoll {}...", i);

                    let mut trm  : i32 = 0;
                    let mut resp : i32 = 0;

                    let respavailable = task.async_poll(addr.as_str(),
                                                        "",
                                                        token.as_str(),
                                                        & mut resp,
                                                        & mut trm)?;

                    if respavailable {
                        println!("solution available!");

                        task.async_get_result(addr.as_str(),
                                              "",
                                              token.as_str(),
                                              & mut resp,
                                              & mut trm)?;

                        task.solution_summary (Streamtype::LOG)?;
                        return Ok(());
                    }
                }

                println!("max num polls reached, stopping host.");
                task.async_stop (addr.as_str(), "", token.as_str())?;
                Err("Max num polls".to_string())
            }))
}
examples/ceo1.rs (lines 45-99)
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
fn main() -> Result<(),String> {
    let numcon = 1;
    let numvar = 3;

    let bkc = mosek::Boundkey::FX;
    let blc = 1.0;
    let buc = 1.0;

    let bkx = vec![ Boundkey::FR,
                    Boundkey::FR,
                    Boundkey::FR ];
    let blx = vec![ -INF, -INF, -INF ];
    let bux = vec![ INF, INF, INF ];
    let c   = vec![ 1.0, 1.0, 0.0 ];
    let a   = vec![ 1.0, 1.0, 1.0 ];
    let asub = vec![0, 1, 2];
    //let csub = new int[numvar];
    //double[] xx  = new double[numvar];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG, 
            &mut|msg| print!("{}",msg),
            |task| task.with_callback(
                &mut |caller| { println!("caller = {}",caller); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                       The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                      /* Append 'numvar' variables.
                         The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    /* Define the linear part of the problem */
                    task.put_c_slice(0, numvar, c.as_slice())?;
                    task.put_a_row(0, asub.as_slice(), a.as_slice())?;
                    task.put_con_bound(0, bkc, blc, buc)?;
                    task.put_var_bound_slice(0, numvar, bkx.as_slice(), blx.as_slice(), bux.as_slice())?;

                    /* Add a conic constraint */
                    task.append_afes(3)?;
                    let afeidxs = vec![0,  1,  2  ];
                    let b       = vec![0.0,0.0,0.0];
                    let domidx  = task.append_primal_exp_cone_domain()?;
                    task.put_afe_f_row_list(afeidxs.as_slice(),
                                            vec![1,1,1].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![1.0,1.0,1.0].as_slice())?;
                    task.append_acc(domidx,afeidxs.as_slice(),b.as_slice())?;

                    task.put_obj_sense(Objsense::MINIMIZE)?;

                    println!("optimize");
                    /* Solve the problem */
                    task.optimize()?;
                    // Print a summary containing information
                    // about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    /* Get status information about the solution */
                    let solsta = task.get_sol_sta(Soltype::ITR)?;

                    assert!(solsta == Solsta::OPTIMAL);
                    
                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITR, & mut xx[..])?;
                    
                    println!("Optimal primal solution");
                    for j in 0..numvar as usize {
                        println!("x[{}]: {:.4}",j,xx[j]);
                    }
                    Ok(())
                }))
}
examples/concurrent1.rs (lines 163-170)
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
fn concurrent1(data : FileOrText, timelimit : Option<String>) -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
        };

    match data {
        FileOrText::File(fname) => task.read_data(fname.as_str())?,
        FileOrText::Text(text)  => task.read_ptf_string(text.as_str())?
    }
    if let Some(timelimit) = timelimit {
        task.put_dou_param(mosek::Dparam::OPTIMIZER_MAX_TIME, timelimit.parse().unwrap())?;
    }

    let numintvar = task.get_num_int_var()?;

    let r = if numintvar == 0 {
        let optimizers = &[mosek::Optimizertype::CONIC,
                           mosek::Optimizertype::DUAL_SIMPLEX,
                           mosek::Optimizertype::PRIMAL_SIMPLEX];
        optimize_concurrent(& mut task, optimizers)
    }
    else {
        let seeds = &[ 42, 13, 71749373 ];
        optimize_concurrent_mio(& mut task, seeds)
    };


    let sense = task.get_obj_sense()?;
    // Pick the feasible result. For non-integer problems all
    // solutions should be the same if more than one is returned, but
    // for integer problems tasks may have hit the time limit and
    // returned non-optimal solutions.

    let n = r.len();

    if n == 0 {
        println!("All optimizers failed.");
    }
    else if numintvar > 0 {
        let (ii,_,tasks) = split3vec(r);

        let pobjs : Vec<(usize,f64)> =
            ii.iter().zip(tasks.iter()).enumerate()
            .filter_map(|(k,(_i,t))|
                match (*t).solution_def(Soltype::ITG) {
                    Ok(true) => match t.get_sol_sta(Soltype::ITG).unwrap() {
                        Solsta::PRIM_FEAS|Solsta::INTEGER_OPTIMAL => Some((k,t.get_primal_obj(Soltype::ITG).unwrap())),
                        _ => None
                    },
                    _ => None
                })
            .collect();

        let &(besti,bestobj) = pobjs.iter()
            .max_by(|(_,o1),(_,o2)|
                    match sense {
                        Objsense::MAXIMIZE => if o1 < o2 {Ordering::Less} else if o2 < o1 {Ordering::Greater} else {Ordering::Equal},
                        _ => if o1 > o2 {Ordering::Less} else if o2 > o1 {Ordering::Greater} else {Ordering::Equal}
                    }).unwrap();

        drop_except(tasks,besti).unwrap()
            .with_stream_callback(
                Streamtype::LOG, 
                &mut |msg| print!("{}",msg),
                |t| { 
                    t.optimizer_summary(mosek::Streamtype::LOG)?;
                    t.solution_summary(mosek::Streamtype::LOG)?;
                    Ok::<(),String>(())
                })?;

        println!("{} optimizers succeeded:",pobjs.len());
        for &(k,v) in pobjs.iter() {
            println!("Optimizer with seed #{} produced result : {:.5e}",ii[k],v);
        }

        println!("\tBest solution is #{}: {:.5e}",ii[besti],bestobj);
    }
    else {
        let (ii,_,tasks) = split3vec(r);

        let pobjs : Vec<(usize,f64)> =
            tasks.iter().enumerate()
            .filter_map(|(k,t)|
                        match t.get_sol_sta(Soltype::BAS) {
                            Ok(Solsta::PRIM_FEAS)|Ok(Solsta::OPTIMAL) => Some((k,t.get_primal_obj(Soltype::BAS).unwrap())),
                            _ => None
                        }.or_else(|| match t.get_sol_sta(Soltype::ITR) {
                            Ok(Solsta::PRIM_FEAS)|Ok(Solsta::OPTIMAL) => Some((k,t.get_primal_obj(Soltype::ITR).unwrap())),
                            _ => None
                        }))
            .collect();

        let &(besti,bestobj) = pobjs.iter()
            .max_by(|(_,o1),(_,o2)|
                    match sense {
                        Objsense::MAXIMIZE => if o1 < o2 {Ordering::Less} else if o2 < o1 {Ordering::Greater} else {Ordering::Equal},
                        _ => if o1 > o2 {Ordering::Less} else if o2 > o1 {Ordering::Greater} else {Ordering::Equal}
                    }).unwrap();

        drop_except(tasks,besti).unwrap()
            .with_stream_callback(
                Streamtype::LOG, 
                &mut|msg| print!("{}",msg),
                |t| {
                    t.optimizer_summary(mosek::Streamtype::LOG)?;
                    t.solution_summary(mosek::Streamtype::LOG)?;
                    Ok::<(),String>(())
                })?;

        println!("{} optimizers succeeded:",pobjs.len());
        for &(k,v) in pobjs.iter() {
            println!("Optimizer with seed #{} produced result : {:.5e}",ii[k],v);
        }

        println!("\tBest solution is #{}: {:.5e}",ii[besti],bestobj);
    }


    Result::Ok(())
}
examples/milo1.rs (lines 38-125)
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
fn main() -> Result<(),String> {
    let numcon : i32 = 2;
    let numvar : i32 = 2;

    let infinity = 0.0; // only for symbolic purposes, value never used

    let bkc = vec![Boundkey::UP, Boundkey::LO];
    let blc = vec![ -infinity,         -4.0 ];
    let buc = vec![ 250.0,             infinity ];

    let bkx = vec![ Boundkey::LO, Boundkey::LO  ];
    let blx = vec![ 0.0,               0.0 ];
    let bux = vec![ infinity,          infinity ];

    let c   = vec![1.0, 0.64];

    let asub = vec![0,   1,
                    0,    1];
    let aval = vec![50.0, 3.0, 31.0, -2.0];

    let ptrb : Vec<usize> = vec![ 0, 2 ];
    let ptre : Vec<usize> = vec![ 2, 4 ];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG,
            &mut |msg| print!("{}",msg),
            |task| task.with_itg_sol_callback(
                &mut |xx| { println!("Found a new solution = {:?}",xx); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                    The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                    /* Append 'numvar' variables.
                    The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    for ((((j,cj),bk),bl),bu) in (0..numvar).zip(c.iter()).zip(bkx.iter()).zip(blx.iter()).zip(bux.iter()) {
                        /* Set the linear term c_j in the objective.*/
                        task.put_c_j(j, *cj)?;
                        /* Set the bounds on variable j.
                           blx[j] <= x_j <= bux[j] */
                        task.put_var_bound(j, *bk, *bl, *bu)?;
                        /* Input column j of A */
                        task.put_a_col(j,                     /* Variable (column) index.*/
                                       &asub[ptrb[j as usize]..ptre[j as usize]],               /* Row index of non-zeros in column j.*/
                                       &aval[ptrb[j as usize]..ptre[j as usize]])?;              /* Non-zero Values of column j. */
                    }
                    // Set the bounds on constraints.
                    // for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] 
                    for (((i,bk),bl),bu) in (0..numcon).zip(bkc.iter()).zip(blc.iter()).zip(buc.iter()) {
                        task.put_con_bound(i, *bk, *bl, *bu)?;
                    }

                    /* Specify integer variables. */
                    for j in 0..numvar {
                        task.put_var_type(j, Variabletype::TYPE_INT)?;
                    }
                    /* Set max solution time */
                    task.put_dou_param(Dparam::MIO_MAX_TIME, 60.0)?;

                    /* A maximization problem */
                    task.put_obj_sense(Objsense::MAXIMIZE)?;
                    /* Solve the problem */

                    let _trm = task.optimize()?;

                    // Print a summary containing information
                    //   about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITG, xx.as_mut_slice())?;

                    /* Get status information about the solution */

                    match task.get_sol_sta(Soltype::ITG)? {
                        Solsta::INTEGER_OPTIMAL => {
                            println!("Optimal solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::PRIM_FEAS => {
                            println!("Feasible solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::UNKNOWN => {
                          match task.get_pro_sta(Soltype::ITG)? {
                              Prosta::PRIM_INFEAS_OR_UNBOUNDED => {
                                  println!("Problem status Infeasible or unbounded");
                              }
                              Prosta::PRIM_INFEAS => {
                                  println!("Problem status Infeasible.");
                              }
                              Prosta::UNKNOWN => {
                                  println!("Problem status unknown.");
                              }
                              _ => {
                                  println!("Other problem status.");
                              }
                          }
                        }
                        _ => {
                            println!("Other solution status");
                        }
                    }
                    Ok(())
                }))
}
source

pub fn with_callback<F, G, R>(&mut self, cbfunc: &mut F, body: G) -> R
where G: FnOnce(&mut Task) -> R, F: FnMut(i32) -> bool,

Temporarily attach a code callback to the task.

For the duration of the call of body, the code callback will be set to cbfunc.

§Arguments
  • cbfunc A callback function that may be called repeatedly
  • body A function (& mut Task) -> R that is called exactly once.
Examples found in repository?
examples/concurrent1.rs (lines 25-34)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
fn optimize(mut t : mosek::Task, stop : Arc<Mutex<bool>>) -> Option<(i32,mosek::Task)> {
    let cbstop = Arc::clone(&stop);
    if let Some(trm) = t.with_callback(
        &mut |_| cbstop.lock().and_then(|p| Ok(*p)).unwrap_or(false),
        |task|
            if let Ok(trm) = task.optimize() {
                let mut st = stop.lock().unwrap();
                *st = true;
                Some(trm)
            } else {
                None
            }) {
        Some((trm,t))
    }
    else {
        None
    }
}
More examples
Hide additional examples
examples/opt_server_async.rs (lines 60-104)
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
fn opt_server_async(inputfile : FileOrText, addr : String, numpolls : usize, cert : Option<String>) -> Result<(),String> {
    // Path to certificate, if any

    let token = {
        Task::new().unwrap()
            .with_stream_callback(
                Streamtype::LOG,
                &mut |msg| print!("{}",msg),
                |task| {
                    match inputfile {
                        FileOrText::File(ref filename) => task.read_data(filename.as_str()).unwrap(),
                        FileOrText::Text(ref data)     => task.read_ptf_string(data.as_str()).unwrap()
                    }
                    if let Some(ref cert) = cert {
                        task.put_str_param(Sparam::REMOTE_TLS_CERT_PATH,cert.as_str())?;
                    }
                    task.async_optimize(addr.as_str(),"")
                }).expect("Failed to submit async optimization")
    };

    println!("Task token = '{}'", token);

    println!("Setting log stream...");
    Task::new().unwrap().with_stream_callback(
        Streamtype::LOG,
        & mut |msg| print!("{}",msg),
        |task| task.with_callback(
            &mut|caller| { println!("caller = {}",caller); false },
            |task| {
                println!("Reading input file '{:?}'...",inputfile);
                match inputfile {
                    FileOrText::File(ref filename) => task.read_data(filename.as_str()).unwrap(),
                    FileOrText::Text(ref data)     => task.read_ptf_string(data.as_str()).unwrap()
                }
                if let Some(ref cert) = cert {
                    task.put_str_param(Sparam::REMOTE_TLS_CERT_PATH,cert.as_str())?;
                }

                println!("Starting polling loop...");
                for i in 0..numpolls {
                    sleep(Duration::new(1,0));

                    println!("\tpoll {}...", i);

                    let mut trm  : i32 = 0;
                    let mut resp : i32 = 0;

                    let respavailable = task.async_poll(addr.as_str(),
                                                        "",
                                                        token.as_str(),
                                                        & mut resp,
                                                        & mut trm)?;

                    if respavailable {
                        println!("solution available!");

                        task.async_get_result(addr.as_str(),
                                              "",
                                              token.as_str(),
                                              & mut resp,
                                              & mut trm)?;

                        task.solution_summary (Streamtype::LOG)?;
                        return Ok(());
                    }
                }

                println!("max num polls reached, stopping host.");
                task.async_stop (addr.as_str(), "", token.as_str())?;
                Err("Max num polls".to_string())
            }))
}
examples/ceo1.rs (lines 48-99)
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
fn main() -> Result<(),String> {
    let numcon = 1;
    let numvar = 3;

    let bkc = mosek::Boundkey::FX;
    let blc = 1.0;
    let buc = 1.0;

    let bkx = vec![ Boundkey::FR,
                    Boundkey::FR,
                    Boundkey::FR ];
    let blx = vec![ -INF, -INF, -INF ];
    let bux = vec![ INF, INF, INF ];
    let c   = vec![ 1.0, 1.0, 0.0 ];
    let a   = vec![ 1.0, 1.0, 1.0 ];
    let asub = vec![0, 1, 2];
    //let csub = new int[numvar];
    //double[] xx  = new double[numvar];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG, 
            &mut|msg| print!("{}",msg),
            |task| task.with_callback(
                &mut |caller| { println!("caller = {}",caller); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                       The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                      /* Append 'numvar' variables.
                         The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    /* Define the linear part of the problem */
                    task.put_c_slice(0, numvar, c.as_slice())?;
                    task.put_a_row(0, asub.as_slice(), a.as_slice())?;
                    task.put_con_bound(0, bkc, blc, buc)?;
                    task.put_var_bound_slice(0, numvar, bkx.as_slice(), blx.as_slice(), bux.as_slice())?;

                    /* Add a conic constraint */
                    task.append_afes(3)?;
                    let afeidxs = vec![0,  1,  2  ];
                    let b       = vec![0.0,0.0,0.0];
                    let domidx  = task.append_primal_exp_cone_domain()?;
                    task.put_afe_f_row_list(afeidxs.as_slice(),
                                            vec![1,1,1].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![1.0,1.0,1.0].as_slice())?;
                    task.append_acc(domidx,afeidxs.as_slice(),b.as_slice())?;

                    task.put_obj_sense(Objsense::MINIMIZE)?;

                    println!("optimize");
                    /* Solve the problem */
                    task.optimize()?;
                    // Print a summary containing information
                    // about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    /* Get status information about the solution */
                    let solsta = task.get_sol_sta(Soltype::ITR)?;

                    assert!(solsta == Solsta::OPTIMAL);
                    
                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITR, & mut xx[..])?;
                    
                    println!("Optimal primal solution");
                    for j in 0..numvar as usize {
                        println!("x[{}]: {:.4}",j,xx[j]);
                    }
                    Ok(())
                }))
}
source

pub fn with_info_callback<F, G, R>(&mut self, cbfunc: &mut F, body: G) -> R
where G: FnOnce(&mut Task) -> R, F: FnMut(i32, &[f64], &[i32], &[i64]) -> bool,

Temporarily attach an info callback to the task.

For the duration of the call of body, the code callback will be set to cbfunc.

§Arguments
  • cbfunc A callback function that may be called repeatedly
  • body A function (& mut Task) -> R that is called exactly once.
Examples found in repository?
examples/callback.rs (lines 129-133)
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
fn callbackmain(which : &str, data : FileOrText) -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = Task::new().unwrap();
    match data {
        FileOrText::Text(data)  => { task.read_ptf_string(data)? },
        FileOrText::File(fname) => { task.read_data(fname)? }
    }

    task.write_data("callback.ptf")?;

    match which {
        "psim"   => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::PRIMAL_SIMPLEX)?,
        "dsim"   => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::DUAL_SIMPLEX)?,
        "intpnt" => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::INTPNT)?,
        s => return Err(format!("Invalid argument '{}'",s))
    }

    /* Directs the log task stream to the 'printstr' function. */
    task.with_stream_callback(
        Streamtype::LOG,
        & mut |msg| print!("{}",msg),
        |task|
            task.with_info_callback(
                & mut callback,
                |task|
                    task.optimize()
            )
    )?;

    Result::Ok(())
}
source

pub fn with_itg_sol_callback<F, G, R>(&mut self, cbfunc: &mut F, body: G) -> R
where G: FnOnce(&mut Task) -> R, F: FnMut(&[f64]) -> bool,

Temporarily attach an info callback to the task.

For the duration of the call of body, the code callback will be set to cbfunc.

§Arguments
  • cbfunc A callback function that may be called repeatedly
  • body A function (& mut Task) -> R that is called exactly once.
Examples found in repository?
examples/milo1.rs (lines 41-125)
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
fn main() -> Result<(),String> {
    let numcon : i32 = 2;
    let numvar : i32 = 2;

    let infinity = 0.0; // only for symbolic purposes, value never used

    let bkc = vec![Boundkey::UP, Boundkey::LO];
    let blc = vec![ -infinity,         -4.0 ];
    let buc = vec![ 250.0,             infinity ];

    let bkx = vec![ Boundkey::LO, Boundkey::LO  ];
    let blx = vec![ 0.0,               0.0 ];
    let bux = vec![ infinity,          infinity ];

    let c   = vec![1.0, 0.64];

    let asub = vec![0,   1,
                    0,    1];
    let aval = vec![50.0, 3.0, 31.0, -2.0];

    let ptrb : Vec<usize> = vec![ 0, 2 ];
    let ptre : Vec<usize> = vec![ 2, 4 ];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG,
            &mut |msg| print!("{}",msg),
            |task| task.with_itg_sol_callback(
                &mut |xx| { println!("Found a new solution = {:?}",xx); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                    The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                    /* Append 'numvar' variables.
                    The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    for ((((j,cj),bk),bl),bu) in (0..numvar).zip(c.iter()).zip(bkx.iter()).zip(blx.iter()).zip(bux.iter()) {
                        /* Set the linear term c_j in the objective.*/
                        task.put_c_j(j, *cj)?;
                        /* Set the bounds on variable j.
                           blx[j] <= x_j <= bux[j] */
                        task.put_var_bound(j, *bk, *bl, *bu)?;
                        /* Input column j of A */
                        task.put_a_col(j,                     /* Variable (column) index.*/
                                       &asub[ptrb[j as usize]..ptre[j as usize]],               /* Row index of non-zeros in column j.*/
                                       &aval[ptrb[j as usize]..ptre[j as usize]])?;              /* Non-zero Values of column j. */
                    }
                    // Set the bounds on constraints.
                    // for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] 
                    for (((i,bk),bl),bu) in (0..numcon).zip(bkc.iter()).zip(blc.iter()).zip(buc.iter()) {
                        task.put_con_bound(i, *bk, *bl, *bu)?;
                    }

                    /* Specify integer variables. */
                    for j in 0..numvar {
                        task.put_var_type(j, Variabletype::TYPE_INT)?;
                    }
                    /* Set max solution time */
                    task.put_dou_param(Dparam::MIO_MAX_TIME, 60.0)?;

                    /* A maximization problem */
                    task.put_obj_sense(Objsense::MAXIMIZE)?;
                    /* Solve the problem */

                    let _trm = task.optimize()?;

                    // Print a summary containing information
                    //   about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITG, xx.as_mut_slice())?;

                    /* Get status information about the solution */

                    match task.get_sol_sta(Soltype::ITG)? {
                        Solsta::INTEGER_OPTIMAL => {
                            println!("Optimal solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::PRIM_FEAS => {
                            println!("Feasible solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::UNKNOWN => {
                          match task.get_pro_sta(Soltype::ITG)? {
                              Prosta::PRIM_INFEAS_OR_UNBOUNDED => {
                                  println!("Problem status Infeasible or unbounded");
                              }
                              Prosta::PRIM_INFEAS => {
                                  println!("Problem status Infeasible.");
                              }
                              Prosta::UNKNOWN => {
                                  println!("Problem status unknown.");
                              }
                              _ => {
                                  println!("Other problem status.");
                              }
                          }
                        }
                        _ => {
                            println!("Other solution status");
                        }
                    }
                    Ok(())
                }))
}
source

pub fn with_callbacks(self) -> TaskCB

This converts the Task object into a TaskCB object. The main difference is the the TaskCB enables attaching callback functions (message printing and information callbacks), and that it due to the callbacks cannot be shared between multiple threads.

Examples found in repository?
examples/opt_server_sync.rs (line 32)
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
fn opt_server_sync(inputfile : FileOrText, addr : String, cert : Option<String>) -> Result<(),String> {
    let mut task = Task::new().unwrap().with_callbacks();
    task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    // Load some data into the task
    match inputfile {
        FileOrText::File(filename) => task.read_data(filename.as_str())?,
        FileOrText::Text(data) => task.read_ptf_string(data.as_str())?
    }

    // Set OptServer URL
    task.put_optserver_host(addr.as_str())?;

    // Path to certificate, if any
    if let Some(cert) = cert {
        task.put_str_param(Sparam::REMOTE_TLS_CERT_PATH, cert.as_str())?;
    }

    // Optimize remotely, no access token
    let _trm = task.optimize()?;

    task.solution_summary(Streamtype::LOG)?;

    Ok(())
}
More examples
Hide additional examples
examples/feasrepairex1.rs (line 37)
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
fn feasrepairex1(filename : FileOrText) -> Result<(),String> {

    let mut task = Task::new().unwrap().with_callbacks();
    task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    match filename {
        FileOrText::File(fname) => task.read_data(fname.as_str())?,
        FileOrText::Text(data) => task.read_lp_string(data.as_str())?
    }
    task.put_int_param(mosek::Iparam::LOG_FEAS_REPAIR, 3)?;

    let wc = vec![1.0; task.get_num_con()? as usize];
    let wx = vec![1.0; task.get_num_var()? as usize];
    task.primal_repair(wc.as_slice(),wc.as_slice(),wx.as_slice(),wx.as_slice())?;

    let sum_viol = task.get_dou_inf(mosek::Dinfitem::PRIMAL_REPAIR_PENALTY_OBJ)?;

    println!("Minimized sum of violations = {}", sum_viol);

    let _ = task.optimize()?;

    task.solution_summary(mosek::Streamtype::MSG)?;

    Ok(())
}
examples/simple.rs (line 30)
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
fn simple(filename : FileOrText, outfile : Option<String>) -> Result<(),String> {
    let mut task = Task::new().unwrap().with_callbacks();
    task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    // We assume that a problem file was given as the first command
    // line argument (received in `args')
    match filename {
        FileOrText::File(fname) => {
            task.read_data(fname.as_str())?
        },
        FileOrText::Text(data) => {
            task.read_ptf_string(data.as_str())?
        }
    }
    // Solve the problem
    let _ = task.optimize()?;

    // Print a summary of the solution
    task.solution_summary(Streamtype::LOG)?;

    // If an output file was specified, save problem to file
    if let Some(outfile) = outfile {
        // If using OPF format, these parameters will specify what to include in output
        task.put_int_param(Iparam::OPF_WRITE_SOLUTIONS,  Onoffkey::ON)?;
        task.put_int_param(Iparam::OPF_WRITE_PROBLEM,    Onoffkey::ON)?;
        task.put_int_param(Iparam::OPF_WRITE_HINTS,      Onoffkey::OFF)?;
        task.put_int_param(Iparam::OPF_WRITE_PARAMETERS, Onoffkey::OFF)?;

        task.put_int_param(Iparam::PTF_WRITE_SOLUTIONS,  Onoffkey::ON)?;

        task.write_data(outfile.as_str())?;
    }
    Ok(())
}
examples/response.rs (line 34)
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
fn main() -> Result<(),String> {
    let args: Vec<String> = env::args().collect();

    let mut task = Task::new().unwrap().with_callbacks();
    if args.len() < 2 {
        task.read_ptf_string(CQO1_PTF)?;
    }
    else {
        task.read_data(args[1].as_str())?;
    }

    // Perform optimization.
    let trm = task.optimize()?;
    task.solution_summary(Streamtype::LOG)?;

    // Handle solution status. We expect Optimal
    let solsta = task.get_sol_sta(Soltype::ITR)?;

    match solsta {
        Solsta::OPTIMAL => {
            // Fetch and print the solution
            println!("An optimal interior point solution is located.");
            let numvar = task.get_num_var()?;
            let mut xx = vec![0.0; numvar as usize];
            task.get_xx(Soltype::ITR, xx.as_mut_slice())?;
            println!("xx = {:?}",xx)
        },
        Solsta::DUAL_INFEAS_CER =>
          println!("Dual infeasibility certificate found."),
        Solsta::PRIM_INFEAS_CER =>
          println!("Primal infeasibility certificate found."),
        Solsta::UNKNOWN => {
          // The solutions status is unknown. The termination code
          // indicates why the optimizer terminated prematurely.
          println!("The solution status is unknown.");
          let (symname,desc) = mosek::get_code_desc(trm)?;
          println!("   Termination code: {} {}\n", symname, desc)
        },
        _ =>
          println!("Unexpected solution status {}\n",solsta)
    }
    Ok(())
}
examples/pinfeas.rs (line 50)
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
fn main() -> Result<(),String> {
    // In this example we set up a simple problem
    // One could use any task or a task read from a file
    let mut task = test_problem()?.with_callbacks();

    let n = task.get_num_var()?;
    let m = task.get_num_con()?;

    // Useful for debugging
    task.write_data("pinfeas.ptf")?; // Write file in human-readable format
    // Attach a log stream printer to the task
    task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    // Perform the optimization.
    task.optimize()?;
    task.solution_summary(Streamtype::LOG)?;

    // Check problem status, we use the interior point solution
    if task.get_pro_sta(Soltype::ITR)? == Prosta::PRIM_INFEAS {
        // Set the tolerance at which we consider a dual value as essential
        let eps = 1e-7;

        println!("Variable bounds important for infeasibility: ");
        let mut slx = vec![0.0; n as usize]; task.get_slx(Soltype::ITR, slx.as_mut_slice())?;
        let mut sux = vec![0.0; n as usize]; task.get_sux(Soltype::ITR, sux.as_mut_slice())?;
        analyze_certificate(slx.as_slice(), sux.as_slice(), eps);

        println!("Constraint bounds important for infeasibility: ");
        let mut slc = vec![0.0; m as usize]; task.get_slc(Soltype::ITR, slc.as_mut_slice())?;
        let mut suc = vec![0.0; m as usize]; task.get_suc(Soltype::ITR, suc.as_mut_slice())?;
        analyze_certificate(slc.as_mut_slice(), suc.as_mut_slice(), eps);
    }
    else {
        println!("The problem is not primal infeasible, no certificate to show");
    }
    Ok(())
}
examples/logistic.rs (line 147)
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
fn logistic_regression(X : &[f64],
                       Y : &[bool],
                       lamb : f64) -> Result<Vec<f64>,String> {
    let n = Y.len() as i32;
    let d = (X.len()/Y.len()) as i32;  // num samples, dimension

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
        }.with_callbacks();
    task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    // Variables [r; theta; t]
    let nvar : i32 = 1+d+n;
    task.append_vars(nvar)?;
    task.put_var_bound_slice_const(0, nvar, Boundkey::FR, -INF, INF)?;
    let (r,theta,t) = (0i32,1i32,1+d);
    task.put_var_name(r,"r")?;
    for j in 0..d { task.put_var_name(theta+j,format!("theta[{}]",j).as_str())?; }
    for j in 0..n { task.put_var_name(t+j,format!("t[{}]",j).as_str())?; }

    // Objective lambda*r + sum(t)
    task.put_c_j(r, lamb)?;
    for i in 0..n { task.put_c_j(t+i, 1.0)?; }
    task.put_obj_sense(Objsense::MINIMIZE)?;

    // Softplus function constraints
    softplus(& mut task, d, n, theta, t, X, Y)?;

    // Regularization
    // Append a sequence of linear expressions (r, theta) to F
    let numafe = task.get_num_afe()?;
    task.append_afes(1+d as i64)?;
    task.put_afe_f_entry(numafe, r, 1.0)?;
    for i in 0..d {
        task.put_afe_f_entry(numafe + i as i64 + 1, theta + i, 1.0)?;
    }

    // Add the constraint
    {
        let dom = task.append_quadratic_cone_domain((1+d) as i64)?;
        task.append_acc_seq(dom,
                            numafe,
                            vec![0.0; 1+d as usize].as_slice())?;
    }
    // Solution
    task.write_data("logistic.ptf")?;
    task.optimize()?;

    let mut xx = vec![0.0; d as usize];
    task.get_xx_slice(Soltype::ITR, theta, theta+d as i32,xx.as_mut_slice())?;
    Ok(xx)
}
source

pub fn write_data_stream<F>( &self, func: F, format: i32, compress: i32 ) -> Result<(), String>
where F: FnMut(&[u8]) -> usize,

Examples found in repository?
examples/writecallback.rs (lines 31-33)
27
28
29
30
31
32
33
34
35
fn main() -> Result<(),String> {
    let mut task = Task::new().unwrap();
    task.read_ptf_string(DFLT_FILE).unwrap();

    task.write_data_stream(|s| if let Err(_) = stdout().write_all(s) { 0 } else { s.len() },
                           Dataformat::PTF,
                           Compresstype::NONE)?;
    Ok(())
}
source

pub fn analyze_names( &self, whichstream_: i32, nametype_: i32 ) -> Result<(), String>

Analyze the names and issue an error for the first invalid name.

§Arguments
  • whichstream_ Index of the stream.

    See Streamtype

  • nametype_ The type of names e.g. valid in MPS or LP files.

    See Nametype

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.analyzenames

source

pub fn analyze_problem(&self, whichstream_: i32) -> Result<(), String>

Analyze the data of a task.

§Arguments
  • whichstream_ Index of the stream.

    See Streamtype

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.analyzeproblem

source

pub fn analyze_solution( &self, whichstream_: i32, whichsol_: i32 ) -> Result<(), String>

Print information related to the quality of the solution.

§Arguments
  • whichstream_ Index of the stream.

    See Streamtype

  • whichsol_ Selects a solution.

    See Soltype

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.analyzesolution

source

pub fn append_acc( &mut self, domidx_: i64, afeidxlist_: &[i64], b_: &[f64] ) -> Result<(), String>

Appends an affine conic constraint to the task.

§Arguments
  • domidx_ Domain index.
  • afeidxlist_ List of affine expression indexes.
  • b_ The vector of constant terms modifying affine expressions. Optional.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appendacc

Examples found in repository?
examples/ceo1.rs (line 75)
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
fn main() -> Result<(),String> {
    let numcon = 1;
    let numvar = 3;

    let bkc = mosek::Boundkey::FX;
    let blc = 1.0;
    let buc = 1.0;

    let bkx = vec![ Boundkey::FR,
                    Boundkey::FR,
                    Boundkey::FR ];
    let blx = vec![ -INF, -INF, -INF ];
    let bux = vec![ INF, INF, INF ];
    let c   = vec![ 1.0, 1.0, 0.0 ];
    let a   = vec![ 1.0, 1.0, 1.0 ];
    let asub = vec![0, 1, 2];
    //let csub = new int[numvar];
    //double[] xx  = new double[numvar];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG, 
            &mut|msg| print!("{}",msg),
            |task| task.with_callback(
                &mut |caller| { println!("caller = {}",caller); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                       The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                      /* Append 'numvar' variables.
                         The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    /* Define the linear part of the problem */
                    task.put_c_slice(0, numvar, c.as_slice())?;
                    task.put_a_row(0, asub.as_slice(), a.as_slice())?;
                    task.put_con_bound(0, bkc, blc, buc)?;
                    task.put_var_bound_slice(0, numvar, bkx.as_slice(), blx.as_slice(), bux.as_slice())?;

                    /* Add a conic constraint */
                    task.append_afes(3)?;
                    let afeidxs = vec![0,  1,  2  ];
                    let b       = vec![0.0,0.0,0.0];
                    let domidx  = task.append_primal_exp_cone_domain()?;
                    task.put_afe_f_row_list(afeidxs.as_slice(),
                                            vec![1,1,1].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![1.0,1.0,1.0].as_slice())?;
                    task.append_acc(domidx,afeidxs.as_slice(),b.as_slice())?;

                    task.put_obj_sense(Objsense::MINIMIZE)?;

                    println!("optimize");
                    /* Solve the problem */
                    task.optimize()?;
                    // Print a summary containing information
                    // about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    /* Get status information about the solution */
                    let solsta = task.get_sol_sta(Soltype::ITR)?;

                    assert!(solsta == Solsta::OPTIMAL);
                    
                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITR, & mut xx[..])?;
                    
                    println!("Optimal primal solution");
                    for j in 0..numvar as usize {
                        println!("x[{}]: {:.4}",j,xx[j]);
                    }
                    Ok(())
                }))
}
source

pub fn append_accs( &mut self, domidxs_: &[i64], afeidxlist_: &[i64], b_: &[f64] ) -> Result<(), String>

Appends a number of affine conic constraint to the task.

§Arguments
  • domidxs_ Domain indices.
  • afeidxlist_ List of affine expression indexes.
  • b_ The vector of constant terms modifying affine expressions. Optional.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appendaccs

source

pub fn append_acc_seq( &mut self, domidx_: i64, afeidxfirst_: i64, b_: &[f64] ) -> Result<(), String>

Appends an affine conic constraint to the task.

§Arguments
  • domidx_ Domain index.
  • afeidxfirst_ Index of the first affine expression.
  • b_ The vector of constant terms modifying affine expressions. Optional.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appendaccseq

Examples found in repository?
examples/portfolio_2_frontier.rs (lines 85-87)
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
fn portfolio(n : i32,
             mu : &[f64],
             GT : &[f64],
             x0  : &[f64],
             alphas : &[f64],
             w : f64) -> Result<Vec<(f64,f64)>,String> {
    let k = (GT.len() / n as usize) as i32;
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(t) => t,
        None => return Err("Failed to create task".to_string()),
    };
    //task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    task.append_vars(n+1)?;
    task.append_cons(1)?;

    /* Objective */
    task.put_obj_sense(Objsense::MAXIMIZE)?;

    let x : Vec<i32> = (0i32..n).collect();
    let s = n;

    /* Total budget */
    let total_budget = w + x0.iter().sum::<f64>();

    /* Total budget constraint - set bounds l^c = u^c */
    task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
    task.put_con_name(0i32,"budget")?;
    task.put_c_slice(0,n,mu)?;

    /* x variables. */
    for (j,xj) in x.iter().enumerate() {
        /* Coefficients in the first row of A */
        task.put_aij(0, *xj, 1.0)?;
        /* No short-selling - x^l = 0, x^u = inf */
        task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
        task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
    }
    task.put_var_name(s, "s")?;
    task.put_var_bound(s, mosek::Boundkey::FR, 0.0, 0.0)?;

    // risk bound
    // (s,0.5,GT * x) in Q_r
    {
        let acci = task.get_num_acc()?;
        let afei = task.get_num_afe()?;

        task.append_afes(k as i64 + 2)?;
        let dom = task.append_r_quadratic_cone_domain(k as i64+2)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 2].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_f_entry(afei,s,1.0)?;
        task.put_afe_g(afei+1,0.5)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 2, j as i32, *v)?;
        }
    }

    let frontier : Vec<(f64,f64)> = alphas.iter().filter_map(|alpha| {
        /* Sets the objective function coefficient for s. */
        if      let Err(_) = task.put_c_j(s, - *alpha) { None }
        else if let Err(_) = task.optimize() { None }
        else if let Err(_) = task.write_data(format!("portfolio_2_frontier-{}.ptf",alpha).as_str()) { None }
        else if let Ok(solsta) = task.get_sol_sta(Soltype::ITR) {
            // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
            match solsta {
                Solsta::OPTIMAL => {
                    let mut xx = vec![0.0; n as usize+1];
                    if let Err(_) = task.get_xx(Soltype::ITR,xx.as_mut_slice()) { None }
                    else {
                        Some((*alpha,mu.iter().zip(xx.iter()).map(|(m,x)| m * x).sum::<f64>()))
                    }
                }
                _ => None
            }
        }
        else {
            None
        }
    }).collect();

    Ok(frontier)
}
More examples
Hide additional examples
examples/portfolio_5_card.rs (lines 138-140)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
source

pub fn append_accs_seq( &mut self, domidxs_: &[i64], numafeidx_: i64, afeidxfirst_: i64, b_: &[f64] ) -> Result<(), String>

Appends a number of affine conic constraint to the task.

§Arguments
  • domidxs_ Domain indices.
  • numafeidx_ Number of affine expressions in the affine expression list (must equal the sum of dimensions of the domains).
  • afeidxfirst_ Index of the first affine expression.
  • b_ The vector of constant terms modifying affine expressions. Optional.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appendaccsseq

source

pub fn append_afes(&mut self, num_: i64) -> Result<(), String>

Appends a number of empty affine expressions to the optimization task.

§Arguments
  • num_ Number of empty affine expressions which should be appended.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appendafes

Examples found in repository?
examples/portfolio_2_frontier.rs (line 83)
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
fn portfolio(n : i32,
             mu : &[f64],
             GT : &[f64],
             x0  : &[f64],
             alphas : &[f64],
             w : f64) -> Result<Vec<(f64,f64)>,String> {
    let k = (GT.len() / n as usize) as i32;
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(t) => t,
        None => return Err("Failed to create task".to_string()),
    };
    //task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    task.append_vars(n+1)?;
    task.append_cons(1)?;

    /* Objective */
    task.put_obj_sense(Objsense::MAXIMIZE)?;

    let x : Vec<i32> = (0i32..n).collect();
    let s = n;

    /* Total budget */
    let total_budget = w + x0.iter().sum::<f64>();

    /* Total budget constraint - set bounds l^c = u^c */
    task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
    task.put_con_name(0i32,"budget")?;
    task.put_c_slice(0,n,mu)?;

    /* x variables. */
    for (j,xj) in x.iter().enumerate() {
        /* Coefficients in the first row of A */
        task.put_aij(0, *xj, 1.0)?;
        /* No short-selling - x^l = 0, x^u = inf */
        task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
        task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
    }
    task.put_var_name(s, "s")?;
    task.put_var_bound(s, mosek::Boundkey::FR, 0.0, 0.0)?;

    // risk bound
    // (s,0.5,GT * x) in Q_r
    {
        let acci = task.get_num_acc()?;
        let afei = task.get_num_afe()?;

        task.append_afes(k as i64 + 2)?;
        let dom = task.append_r_quadratic_cone_domain(k as i64+2)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 2].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_f_entry(afei,s,1.0)?;
        task.put_afe_g(afei+1,0.5)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 2, j as i32, *v)?;
        }
    }

    let frontier : Vec<(f64,f64)> = alphas.iter().filter_map(|alpha| {
        /* Sets the objective function coefficient for s. */
        if      let Err(_) = task.put_c_j(s, - *alpha) { None }
        else if let Err(_) = task.optimize() { None }
        else if let Err(_) = task.write_data(format!("portfolio_2_frontier-{}.ptf",alpha).as_str()) { None }
        else if let Ok(solsta) = task.get_sol_sta(Soltype::ITR) {
            // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
            match solsta {
                Solsta::OPTIMAL => {
                    let mut xx = vec![0.0; n as usize+1];
                    if let Err(_) = task.get_xx(Soltype::ITR,xx.as_mut_slice()) { None }
                    else {
                        Some((*alpha,mu.iter().zip(xx.iter()).map(|(m,x)| m * x).sum::<f64>()))
                    }
                }
                _ => None
            }
        }
        else {
            None
        }
    }).collect();

    Ok(frontier)
}
More examples
Hide additional examples
examples/ceo1.rs (line 66)
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
fn main() -> Result<(),String> {
    let numcon = 1;
    let numvar = 3;

    let bkc = mosek::Boundkey::FX;
    let blc = 1.0;
    let buc = 1.0;

    let bkx = vec![ Boundkey::FR,
                    Boundkey::FR,
                    Boundkey::FR ];
    let blx = vec![ -INF, -INF, -INF ];
    let bux = vec![ INF, INF, INF ];
    let c   = vec![ 1.0, 1.0, 0.0 ];
    let a   = vec![ 1.0, 1.0, 1.0 ];
    let asub = vec![0, 1, 2];
    //let csub = new int[numvar];
    //double[] xx  = new double[numvar];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG, 
            &mut|msg| print!("{}",msg),
            |task| task.with_callback(
                &mut |caller| { println!("caller = {}",caller); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                       The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                      /* Append 'numvar' variables.
                         The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    /* Define the linear part of the problem */
                    task.put_c_slice(0, numvar, c.as_slice())?;
                    task.put_a_row(0, asub.as_slice(), a.as_slice())?;
                    task.put_con_bound(0, bkc, blc, buc)?;
                    task.put_var_bound_slice(0, numvar, bkx.as_slice(), blx.as_slice(), bux.as_slice())?;

                    /* Add a conic constraint */
                    task.append_afes(3)?;
                    let afeidxs = vec![0,  1,  2  ];
                    let b       = vec![0.0,0.0,0.0];
                    let domidx  = task.append_primal_exp_cone_domain()?;
                    task.put_afe_f_row_list(afeidxs.as_slice(),
                                            vec![1,1,1].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![1.0,1.0,1.0].as_slice())?;
                    task.append_acc(domidx,afeidxs.as_slice(),b.as_slice())?;

                    task.put_obj_sense(Objsense::MINIMIZE)?;

                    println!("optimize");
                    /* Solve the problem */
                    task.optimize()?;
                    // Print a summary containing information
                    // about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    /* Get status information about the solution */
                    let solsta = task.get_sol_sta(Soltype::ITR)?;

                    assert!(solsta == Solsta::OPTIMAL);
                    
                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITR, & mut xx[..])?;
                    
                    println!("Optimal primal solution");
                    for j in 0..numvar as usize {
                        println!("x[{}]: {:.4}",j,xx[j]);
                    }
                    Ok(())
                }))
}
examples/portfolio_5_card.rs (line 136)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
source

pub fn append_barvars(&mut self, dim_: &[i32]) -> Result<(), String>

Appends semidefinite variables to the problem.

§Arguments
  • dim_ Dimensions of symmetric matrix variables to be added.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appendbarvars

source

pub fn append_cone( &mut self, ct_: i32, conepar_: f64, submem_: &[i32] ) -> Result<(), String>

Appends a new conic constraint to the problem.

§Arguments
  • ct_ Specifies the type of the cone.

    See Conetype

  • conepar_ For the power cone it denotes the exponent alpha. For other cone types it is unused and can be set to 0.

  • submem_ Variable subscripts of the members in the cone.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appendcone

source

pub fn append_cone_seq( &mut self, ct_: i32, conepar_: f64, nummem_: i32, j_: i32 ) -> Result<(), String>

Appends a new conic constraint to the problem.

§Arguments
  • ct_ Specifies the type of the cone.

    See Conetype

  • conepar_ For the power cone it denotes the exponent alpha. For other cone types it is unused and can be set to 0.

  • nummem_ Number of member variables in the cone.

  • j_ Index of the first variable in the conic constraint.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appendconeseq

source

pub fn append_cones_seq( &mut self, ct_: &[i32], conepar_: &[f64], nummem_: &[i32], j_: i32 ) -> Result<(), String>

Appends multiple conic constraints to the problem.

§Arguments
  • ct_ Specifies the type of the cone.

    See Conetype

  • conepar_ For the power cone it denotes the exponent alpha. For other cone types it is unused and can be set to 0.

  • nummem_ Numbers of member variables in the cones.

  • j_ Index of the first variable in the first cone to be appended.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appendconesseq

source

pub fn append_cons(&mut self, num_: i32) -> Result<(), String>

Appends a number of constraints to the optimization task.

§Arguments
  • num_ Number of constraints which should be appended.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appendcons

Examples found in repository?
examples/pinfeas.rs (line 18)
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
fn test_problem() -> Result<mosek::Task,String> {
    let mut task = mosek::Task::new().unwrap();
    task.append_vars(7)?;
    task.append_cons(7)?;
    task.put_c_list(&[0,1,2,3,4,5,6],
                    &[1.0,2.0,5.0,2.0,1.0,2.0,1.0])?;
    task.put_aij_list(&[0,0,1,1,2,2,2,3,3,4,5,5,6,6],
                      &[0,1,2,3,4,5,6,0,4,1,2,5,3,6],
                      &[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0])?;
    task.put_con_bound_slice(0, 7,
                             &[Boundkey::UP,Boundkey::UP,Boundkey::UP,Boundkey::FX,Boundkey::FX,Boundkey::FX,Boundkey::FX],
                             &[-INF, -INF, -INF, 1100.0, 200.0, 500.0, 500.0],
                             &[200.0, 1000.0, 1000.0, 1100.0, 200.0, 500.0, 500.0])?;
    task.put_var_bound_slice_const(0, 7, Boundkey::UP, 0.0, INF)?;
    Ok(task)
}
More examples
Hide additional examples
examples/solvelinear.rs (line 42)
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
fn setup(task : & mut mosek::Task,
         aval : &[f64],
         asub : &[i32],
         ptrb : &[i64],
         ptre : &[i64],
         numvar : i32) -> Result<Vec<i32>,String> {

    // mosek.stakey[] skx = new mosek.stakey [numvar];
    // mosek.stakey[] skc = new mosek.stakey [numvar];

    // for (int i = 0; i < numvar ; ++i) {
    //   skx[i] = mosek.stakey.bas;
    //   skc[i] = mosek.stakey.fix;
    // }

    task.append_vars(numvar)?;
    task.append_cons(numvar)?;

    task.put_a_col_slice(0,numvar,ptrb,ptre,asub,aval)?;

    task.put_con_bound_slice_const(0,numvar,Boundkey::FX,0.0,0.0)?;
    task.put_var_bound_slice_const(0,numvar,Boundkey::FR,-INF,INF)?;

    /* Define a basic solution by specifying
       status keys for variables & constraints. */
    task.delete_solution(Soltype::BAS)?;

    task.put_skc_slice(Soltype::BAS, 0, numvar, vec![Stakey::FIX; numvar as usize].as_slice())?;
    task.put_skx_slice(Soltype::BAS, 0, numvar, vec![Stakey::BAS; numvar as usize].as_slice())?;

    let mut basis = vec![0; numvar as usize];
    task.init_basis_solve(basis.as_mut_slice())?;
    Ok(basis)
  }
examples/portfolio_2_frontier.rs (line 50)
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
fn portfolio(n : i32,
             mu : &[f64],
             GT : &[f64],
             x0  : &[f64],
             alphas : &[f64],
             w : f64) -> Result<Vec<(f64,f64)>,String> {
    let k = (GT.len() / n as usize) as i32;
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(t) => t,
        None => return Err("Failed to create task".to_string()),
    };
    //task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    task.append_vars(n+1)?;
    task.append_cons(1)?;

    /* Objective */
    task.put_obj_sense(Objsense::MAXIMIZE)?;

    let x : Vec<i32> = (0i32..n).collect();
    let s = n;

    /* Total budget */
    let total_budget = w + x0.iter().sum::<f64>();

    /* Total budget constraint - set bounds l^c = u^c */
    task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
    task.put_con_name(0i32,"budget")?;
    task.put_c_slice(0,n,mu)?;

    /* x variables. */
    for (j,xj) in x.iter().enumerate() {
        /* Coefficients in the first row of A */
        task.put_aij(0, *xj, 1.0)?;
        /* No short-selling - x^l = 0, x^u = inf */
        task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
        task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
    }
    task.put_var_name(s, "s")?;
    task.put_var_bound(s, mosek::Boundkey::FR, 0.0, 0.0)?;

    // risk bound
    // (s,0.5,GT * x) in Q_r
    {
        let acci = task.get_num_acc()?;
        let afei = task.get_num_afe()?;

        task.append_afes(k as i64 + 2)?;
        let dom = task.append_r_quadratic_cone_domain(k as i64+2)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 2].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_f_entry(afei,s,1.0)?;
        task.put_afe_g(afei+1,0.5)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 2, j as i32, *v)?;
        }
    }

    let frontier : Vec<(f64,f64)> = alphas.iter().filter_map(|alpha| {
        /* Sets the objective function coefficient for s. */
        if      let Err(_) = task.put_c_j(s, - *alpha) { None }
        else if let Err(_) = task.optimize() { None }
        else if let Err(_) = task.write_data(format!("portfolio_2_frontier-{}.ptf",alpha).as_str()) { None }
        else if let Ok(solsta) = task.get_sol_sta(Soltype::ITR) {
            // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
            match solsta {
                Solsta::OPTIMAL => {
                    let mut xx = vec![0.0; n as usize+1];
                    if let Err(_) = task.get_xx(Soltype::ITR,xx.as_mut_slice()) { None }
                    else {
                        Some((*alpha,mu.iter().zip(xx.iter()).map(|(m,x)| m * x).sum::<f64>()))
                    }
                }
                _ => None
            }
        }
        else {
            None
        }
    }).collect();

    Ok(frontier)
}
examples/ceo1.rs (line 53)
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
fn main() -> Result<(),String> {
    let numcon = 1;
    let numvar = 3;

    let bkc = mosek::Boundkey::FX;
    let blc = 1.0;
    let buc = 1.0;

    let bkx = vec![ Boundkey::FR,
                    Boundkey::FR,
                    Boundkey::FR ];
    let blx = vec![ -INF, -INF, -INF ];
    let bux = vec![ INF, INF, INF ];
    let c   = vec![ 1.0, 1.0, 0.0 ];
    let a   = vec![ 1.0, 1.0, 1.0 ];
    let asub = vec![0, 1, 2];
    //let csub = new int[numvar];
    //double[] xx  = new double[numvar];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG, 
            &mut|msg| print!("{}",msg),
            |task| task.with_callback(
                &mut |caller| { println!("caller = {}",caller); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                       The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                      /* Append 'numvar' variables.
                         The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    /* Define the linear part of the problem */
                    task.put_c_slice(0, numvar, c.as_slice())?;
                    task.put_a_row(0, asub.as_slice(), a.as_slice())?;
                    task.put_con_bound(0, bkc, blc, buc)?;
                    task.put_var_bound_slice(0, numvar, bkx.as_slice(), blx.as_slice(), bux.as_slice())?;

                    /* Add a conic constraint */
                    task.append_afes(3)?;
                    let afeidxs = vec![0,  1,  2  ];
                    let b       = vec![0.0,0.0,0.0];
                    let domidx  = task.append_primal_exp_cone_domain()?;
                    task.put_afe_f_row_list(afeidxs.as_slice(),
                                            vec![1,1,1].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![1.0,1.0,1.0].as_slice())?;
                    task.append_acc(domidx,afeidxs.as_slice(),b.as_slice())?;

                    task.put_obj_sense(Objsense::MINIMIZE)?;

                    println!("optimize");
                    /* Solve the problem */
                    task.optimize()?;
                    // Print a summary containing information
                    // about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    /* Get status information about the solution */
                    let solsta = task.get_sol_sta(Soltype::ITR)?;

                    assert!(solsta == Solsta::OPTIMAL);
                    
                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITR, & mut xx[..])?;
                    
                    println!("Optimal primal solution");
                    for j in 0..numvar as usize {
                        println!("x[{}]: {:.4}",j,xx[j]);
                    }
                    Ok(())
                }))
}
examples/reoptimization.rs (line 51)
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
fn main() -> Result<(),String> {

    let numcon = 3;
    let numvar = 3;
    let c = &[1.5, 2.5, 3.0 ];
    let bkc = &[ Boundkey::UP,
                 Boundkey::UP,
                 Boundkey::UP ];
    let blc = &[ -INF,
                 -INF,
                 -INF ];
    let buc = &[ 100000.0,
                 50000.0,
                 60000.0 ];
    let bkx = &[ Boundkey::LO,
                 Boundkey::LO,
                 Boundkey::LO
                             ];
    let blx = &[ 0.0, 0.0, 0.0 ];
    let bux = &[ INF,
                 INF,
                 INF ];

    let asub = &[
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ] ];

    let aval = &[
        &[ 2.0, 3.0, 2.0 ],
        &[ 4.0, 2.0, 3.0 ],
        &[ 3.0, 3.0, 2.0 ] ];


    let mut task = Task::new().unwrap();
    /* Append the constraints. */
    task.append_cons(numcon)?;

    /* Append the variables. */
    task.append_vars(numvar)?;

    /* Put C. */
    for (j,&cj) in (0..numvar).zip(c.iter()) {
        task.put_c_j(j,cj)?;
    }
    /* Put constraint bounds. */
    for (i,&bki,&bli,&bui) in izip!(0..numcon,bkc,blc,buc) {
        task.put_con_bound(i, bki, bli, bui)?;
    }

    /* Put variable bounds. */
    for (j,&bki,&bli,&bui) in izip!(0..numvar,bkx,blx,bux) {
        task.put_var_bound(j, bki, bli, bui)?;
    }

    /* Put A. */
    if numcon > 0 {
        for (j,&asubj,&avalj) in izip!(0..numvar,asub,aval) {
            task.put_a_col(j,
                           asubj,
                           avalj)?;
        }
    }

    /* A maximization problem */
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    /* Solve the problem */
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /****************** Make a change to the A matrix ******************/
    task.put_aij(0, 0, 3.0)?;
    let _trm = task.optimize()?;
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /***************** Add a new variable ******************************/
    /* Get index of new variable. */

    let varidx = task.get_num_var()?;

    /* Append a new variable x_3 to the problem */
    task.append_vars(1)?;
    let numvar = numvar + 1;

    /* Set bounds on new varaible */
    task.put_var_bound(varidx, Boundkey::LO, 0.0, INF)?;

    /* Change objective */
    task.put_c_j(varidx, 1.0)?;

    /* Put new values in the A matrix */
    let acolsub = &[0i32, 2];
    let acolval = &[4.0, 1.0];

    task.put_a_col(varidx, /* column index */
                   acolsub,
                   acolval)?;

    /* Change optimizer to simplex free and reoptimize */
    task.put_int_param(mosek::Iparam::OPTIMIZER, mosek::Optimizertype::FREE_SIMPLEX)?;
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Add a new constraint ***************************/
    /* Get index of new constraint. */
    let conidx = task.get_num_con()?;

    /* Append a new constraint */
    task.append_cons(1)?;
    let numcon = numcon + 1;

    /* Set bounds on new constraint */
    task.put_con_bound(conidx,
                       Boundkey::UP,
                       -INF,
                       30000.0)?;

    /* Put new values in the A matrix */
    let arowsub = &[0i32,   1,   2,   3  ];
    let arowval = &[1.0, 2.0, 1.0, 1.0 ];

    task.put_a_row(conidx, /* row index */
                   arowsub,
                   arowval)?;

    let _trm = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Change constraint bounds ********************/
    let newbkc = &[Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP];
    let newblc = &[-INF,
                   -INF,
                   -INF,
                   -INF];
    let newbuc = &[ 80000.0, 40000.0, 50000.0, 22000.0 ];

    task.put_con_bound_slice(0, numcon, newbkc, newblc, newbuc)?;

    let _ = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    Ok(())
}
examples/portfolio_5_card.rs (line 94)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
source

pub fn append_djcs(&mut self, num_: i64) -> Result<(), String>

Appends a number of empty disjunctive constraints to the task.

§Arguments
  • num_ Number of empty disjunctive constraints which should be appended.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appenddjcs

source

pub fn append_dual_exp_cone_domain(&mut self) -> Result<i64, String>

Appends the dual exponential cone domain.

§Returns
  • domidx Index of the domain.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appenddualexpconedomain

source

pub fn append_dual_geo_mean_cone_domain( &mut self, n_: i64 ) -> Result<i64, String>

Appends the dual geometric mean cone domain.

§Arguments
  • n_ Dimmension of the domain.
§Returns
  • domidx Index of the domain.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appenddualgeomeanconedomain

source

pub fn append_dual_power_cone_domain( &mut self, n_: i64, alpha_: &[f64] ) -> Result<i64, String>

Appends the dual power cone domain.

§Arguments
  • n_ Dimension of the domain.
  • alpha_ The sequence proportional to exponents. Must be positive.
§Returns
  • domidx Index of the domain.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appenddualpowerconedomain

source

pub fn append_primal_exp_cone_domain(&mut self) -> Result<i64, String>

Appends the primal exponential cone domain.

§Returns
  • domidx Index of the domain.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appendprimalexpconedomain

Examples found in repository?
examples/ceo1.rs (line 69)
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
fn main() -> Result<(),String> {
    let numcon = 1;
    let numvar = 3;

    let bkc = mosek::Boundkey::FX;
    let blc = 1.0;
    let buc = 1.0;

    let bkx = vec![ Boundkey::FR,
                    Boundkey::FR,
                    Boundkey::FR ];
    let blx = vec![ -INF, -INF, -INF ];
    let bux = vec![ INF, INF, INF ];
    let c   = vec![ 1.0, 1.0, 0.0 ];
    let a   = vec![ 1.0, 1.0, 1.0 ];
    let asub = vec![0, 1, 2];
    //let csub = new int[numvar];
    //double[] xx  = new double[numvar];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG, 
            &mut|msg| print!("{}",msg),
            |task| task.with_callback(
                &mut |caller| { println!("caller = {}",caller); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                       The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                      /* Append 'numvar' variables.
                         The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    /* Define the linear part of the problem */
                    task.put_c_slice(0, numvar, c.as_slice())?;
                    task.put_a_row(0, asub.as_slice(), a.as_slice())?;
                    task.put_con_bound(0, bkc, blc, buc)?;
                    task.put_var_bound_slice(0, numvar, bkx.as_slice(), blx.as_slice(), bux.as_slice())?;

                    /* Add a conic constraint */
                    task.append_afes(3)?;
                    let afeidxs = vec![0,  1,  2  ];
                    let b       = vec![0.0,0.0,0.0];
                    let domidx  = task.append_primal_exp_cone_domain()?;
                    task.put_afe_f_row_list(afeidxs.as_slice(),
                                            vec![1,1,1].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![1.0,1.0,1.0].as_slice())?;
                    task.append_acc(domidx,afeidxs.as_slice(),b.as_slice())?;

                    task.put_obj_sense(Objsense::MINIMIZE)?;

                    println!("optimize");
                    /* Solve the problem */
                    task.optimize()?;
                    // Print a summary containing information
                    // about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    /* Get status information about the solution */
                    let solsta = task.get_sol_sta(Soltype::ITR)?;

                    assert!(solsta == Solsta::OPTIMAL);
                    
                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITR, & mut xx[..])?;
                    
                    println!("Optimal primal solution");
                    for j in 0..numvar as usize {
                        println!("x[{}]: {:.4}",j,xx[j]);
                    }
                    Ok(())
                }))
}
source

pub fn append_primal_geo_mean_cone_domain( &mut self, n_: i64 ) -> Result<i64, String>

Appends the primal geometric mean cone domain.

§Arguments
  • n_ Dimmension of the domain.
§Returns
  • domidx Index of the domain.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appendprimalgeomeanconedomain

source

pub fn append_primal_power_cone_domain( &mut self, n_: i64, alpha_: &[f64] ) -> Result<i64, String>

Appends the primal power cone domain.

§Arguments
  • n_ Dimension of the domain.
  • alpha_ The sequence proportional to exponents. Must be positive.
§Returns
  • domidx Index of the domain.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appendprimalpowerconedomain

source

pub fn append_quadratic_cone_domain(&mut self, n_: i64) -> Result<i64, String>

Appends the n dimensional quadratic cone domain.

§Arguments
  • n_ Dimmension of the domain.
§Returns
  • domidx Index of the domain.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appendquadraticconedomain

Examples found in repository?
examples/portfolio_5_card.rs (line 137)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
source

pub fn append_r_domain(&mut self, n_: i64) -> Result<i64, String>

Appends the n dimensional real number domain.

§Arguments
  • n_ Dimmension of the domain.
§Returns
  • domidx Index of the domain.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appendrdomain

source

pub fn append_rminus_domain(&mut self, n_: i64) -> Result<i64, String>

Appends the n dimensional negative orthant to the list of domains.

§Arguments
  • n_ Dimmension of the domain.
§Returns
  • domidx Index of the domain.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appendrminusdomain

source

pub fn append_rplus_domain(&mut self, n_: i64) -> Result<i64, String>

Appends the n dimensional positive orthant to the list of domains.

§Arguments
  • n_ Dimmension of the domain.
§Returns
  • domidx Index of the domain.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appendrplusdomain

source

pub fn append_r_quadratic_cone_domain(&mut self, n_: i64) -> Result<i64, String>

Appends the n dimensional rotated quadratic cone domain.

§Arguments
  • n_ Dimmension of the domain.
§Returns
  • domidx Index of the domain.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appendrquadraticconedomain

Examples found in repository?
examples/portfolio_2_frontier.rs (line 84)
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
fn portfolio(n : i32,
             mu : &[f64],
             GT : &[f64],
             x0  : &[f64],
             alphas : &[f64],
             w : f64) -> Result<Vec<(f64,f64)>,String> {
    let k = (GT.len() / n as usize) as i32;
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(t) => t,
        None => return Err("Failed to create task".to_string()),
    };
    //task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    task.append_vars(n+1)?;
    task.append_cons(1)?;

    /* Objective */
    task.put_obj_sense(Objsense::MAXIMIZE)?;

    let x : Vec<i32> = (0i32..n).collect();
    let s = n;

    /* Total budget */
    let total_budget = w + x0.iter().sum::<f64>();

    /* Total budget constraint - set bounds l^c = u^c */
    task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
    task.put_con_name(0i32,"budget")?;
    task.put_c_slice(0,n,mu)?;

    /* x variables. */
    for (j,xj) in x.iter().enumerate() {
        /* Coefficients in the first row of A */
        task.put_aij(0, *xj, 1.0)?;
        /* No short-selling - x^l = 0, x^u = inf */
        task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
        task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
    }
    task.put_var_name(s, "s")?;
    task.put_var_bound(s, mosek::Boundkey::FR, 0.0, 0.0)?;

    // risk bound
    // (s,0.5,GT * x) in Q_r
    {
        let acci = task.get_num_acc()?;
        let afei = task.get_num_afe()?;

        task.append_afes(k as i64 + 2)?;
        let dom = task.append_r_quadratic_cone_domain(k as i64+2)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 2].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_f_entry(afei,s,1.0)?;
        task.put_afe_g(afei+1,0.5)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 2, j as i32, *v)?;
        }
    }

    let frontier : Vec<(f64,f64)> = alphas.iter().filter_map(|alpha| {
        /* Sets the objective function coefficient for s. */
        if      let Err(_) = task.put_c_j(s, - *alpha) { None }
        else if let Err(_) = task.optimize() { None }
        else if let Err(_) = task.write_data(format!("portfolio_2_frontier-{}.ptf",alpha).as_str()) { None }
        else if let Ok(solsta) = task.get_sol_sta(Soltype::ITR) {
            // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
            match solsta {
                Solsta::OPTIMAL => {
                    let mut xx = vec![0.0; n as usize+1];
                    if let Err(_) = task.get_xx(Soltype::ITR,xx.as_mut_slice()) { None }
                    else {
                        Some((*alpha,mu.iter().zip(xx.iter()).map(|(m,x)| m * x).sum::<f64>()))
                    }
                }
                _ => None
            }
        }
        else {
            None
        }
    }).collect();

    Ok(frontier)
}
source

pub fn append_rzero_domain(&mut self, n_: i64) -> Result<i64, String>

Appends the n dimensional 0 domain.

§Arguments
  • n_ Dimmension of the domain.
§Returns
  • domidx Index of the domain.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appendrzerodomain

source

pub fn append_sparse_sym_mat( &mut self, dim_: i32, subi_: &[i32], subj_: &[i32], valij_: &[f64] ) -> Result<i64, String>

Appends a general sparse symmetric matrix to the storage of symmetric matrices.

§Arguments
  • dim_ Dimension of the symmetric matrix that is appended.
  • subi_ Row subscript in the triplets.
  • subj_ Column subscripts in the triplets.
  • valij_ Values of each triplet.
§Returns
  • idx Unique index assigned to the inputted matrix.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appendsparsesymmat

source

pub fn append_sparse_sym_mat_list( &mut self, dims_: &[i32], nz_: &[i64], subi_: &[i32], subj_: &[i32], valij_: &[f64], idx_: &mut [i64] ) -> Result<(), String>

Appends a general sparse symmetric matrix to the storage of symmetric matrices.

§Arguments
  • dims_ Dimensions of the symmetric matrixes.
  • nz_ Number of nonzeros for each matrix.
  • subi_ Row subscript in the triplets.
  • subj_ Column subscripts in the triplets.
  • valij_ Values of each triplet.
  • idx_ Unique index assigned to the inputted matrix.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appendsparsesymmatlist

source

pub fn append_svec_psd_cone_domain(&mut self, n_: i64) -> Result<i64, String>

Appends the vectorized SVEC PSD cone domain.

§Arguments
  • n_ Dimension of the domain.
§Returns
  • domidx Index of the domain.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appendsvecpsdconedomain

source

pub fn append_vars(&mut self, num_: i32) -> Result<(), String>

Appends a number of variables to the optimization task.

§Arguments
  • num_ Number of variables which should be appended.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.appendvars

Examples found in repository?
examples/helloworld.rs (line 20)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
fn main() -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
        };

    task.append_vars(1)?;                           // 1 variable x
    task.put_c_j(0, 1.0)?;                          // c_0 = 1.0
    task.put_var_bound(0, Boundkey::RA, 2.0, 3.0)?; // 2.0 <= x <= 3.0
    task.put_obj_sense(Objsense::MINIMIZE)?;        // minimize

    task.optimize()?;                               // Optimize

    let mut x = vec![0.0; 1];
    task.get_xx(Soltype::ITR, x.as_mut_slice())?;   // Get solution
    println!("Solution x = {}", x[0]);              // Print solution
    return Result::Ok(());
}
More examples
Hide additional examples
examples/pinfeas.rs (line 17)
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
fn test_problem() -> Result<mosek::Task,String> {
    let mut task = mosek::Task::new().unwrap();
    task.append_vars(7)?;
    task.append_cons(7)?;
    task.put_c_list(&[0,1,2,3,4,5,6],
                    &[1.0,2.0,5.0,2.0,1.0,2.0,1.0])?;
    task.put_aij_list(&[0,0,1,1,2,2,2,3,3,4,5,5,6,6],
                      &[0,1,2,3,4,5,6,0,4,1,2,5,3,6],
                      &[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0])?;
    task.put_con_bound_slice(0, 7,
                             &[Boundkey::UP,Boundkey::UP,Boundkey::UP,Boundkey::FX,Boundkey::FX,Boundkey::FX,Boundkey::FX],
                             &[-INF, -INF, -INF, 1100.0, 200.0, 500.0, 500.0],
                             &[200.0, 1000.0, 1000.0, 1100.0, 200.0, 500.0, 500.0])?;
    task.put_var_bound_slice_const(0, 7, Boundkey::UP, 0.0, INF)?;
    Ok(task)
}
examples/solvelinear.rs (line 41)
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
fn setup(task : & mut mosek::Task,
         aval : &[f64],
         asub : &[i32],
         ptrb : &[i64],
         ptre : &[i64],
         numvar : i32) -> Result<Vec<i32>,String> {

    // mosek.stakey[] skx = new mosek.stakey [numvar];
    // mosek.stakey[] skc = new mosek.stakey [numvar];

    // for (int i = 0; i < numvar ; ++i) {
    //   skx[i] = mosek.stakey.bas;
    //   skc[i] = mosek.stakey.fix;
    // }

    task.append_vars(numvar)?;
    task.append_cons(numvar)?;

    task.put_a_col_slice(0,numvar,ptrb,ptre,asub,aval)?;

    task.put_con_bound_slice_const(0,numvar,Boundkey::FX,0.0,0.0)?;
    task.put_var_bound_slice_const(0,numvar,Boundkey::FR,-INF,INF)?;

    /* Define a basic solution by specifying
       status keys for variables & constraints. */
    task.delete_solution(Soltype::BAS)?;

    task.put_skc_slice(Soltype::BAS, 0, numvar, vec![Stakey::FIX; numvar as usize].as_slice())?;
    task.put_skx_slice(Soltype::BAS, 0, numvar, vec![Stakey::BAS; numvar as usize].as_slice())?;

    let mut basis = vec![0; numvar as usize];
    task.init_basis_solve(basis.as_mut_slice())?;
    Ok(basis)
  }
examples/portfolio_2_frontier.rs (line 49)
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
fn portfolio(n : i32,
             mu : &[f64],
             GT : &[f64],
             x0  : &[f64],
             alphas : &[f64],
             w : f64) -> Result<Vec<(f64,f64)>,String> {
    let k = (GT.len() / n as usize) as i32;
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(t) => t,
        None => return Err("Failed to create task".to_string()),
    };
    //task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    task.append_vars(n+1)?;
    task.append_cons(1)?;

    /* Objective */
    task.put_obj_sense(Objsense::MAXIMIZE)?;

    let x : Vec<i32> = (0i32..n).collect();
    let s = n;

    /* Total budget */
    let total_budget = w + x0.iter().sum::<f64>();

    /* Total budget constraint - set bounds l^c = u^c */
    task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
    task.put_con_name(0i32,"budget")?;
    task.put_c_slice(0,n,mu)?;

    /* x variables. */
    for (j,xj) in x.iter().enumerate() {
        /* Coefficients in the first row of A */
        task.put_aij(0, *xj, 1.0)?;
        /* No short-selling - x^l = 0, x^u = inf */
        task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
        task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
    }
    task.put_var_name(s, "s")?;
    task.put_var_bound(s, mosek::Boundkey::FR, 0.0, 0.0)?;

    // risk bound
    // (s,0.5,GT * x) in Q_r
    {
        let acci = task.get_num_acc()?;
        let afei = task.get_num_afe()?;

        task.append_afes(k as i64 + 2)?;
        let dom = task.append_r_quadratic_cone_domain(k as i64+2)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 2].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_f_entry(afei,s,1.0)?;
        task.put_afe_g(afei+1,0.5)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 2, j as i32, *v)?;
        }
    }

    let frontier : Vec<(f64,f64)> = alphas.iter().filter_map(|alpha| {
        /* Sets the objective function coefficient for s. */
        if      let Err(_) = task.put_c_j(s, - *alpha) { None }
        else if let Err(_) = task.optimize() { None }
        else if let Err(_) = task.write_data(format!("portfolio_2_frontier-{}.ptf",alpha).as_str()) { None }
        else if let Ok(solsta) = task.get_sol_sta(Soltype::ITR) {
            // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
            match solsta {
                Solsta::OPTIMAL => {
                    let mut xx = vec![0.0; n as usize+1];
                    if let Err(_) = task.get_xx(Soltype::ITR,xx.as_mut_slice()) { None }
                    else {
                        Some((*alpha,mu.iter().zip(xx.iter()).map(|(m,x)| m * x).sum::<f64>()))
                    }
                }
                _ => None
            }
        }
        else {
            None
        }
    }).collect();

    Ok(frontier)
}
examples/ceo1.rs (line 57)
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
fn main() -> Result<(),String> {
    let numcon = 1;
    let numvar = 3;

    let bkc = mosek::Boundkey::FX;
    let blc = 1.0;
    let buc = 1.0;

    let bkx = vec![ Boundkey::FR,
                    Boundkey::FR,
                    Boundkey::FR ];
    let blx = vec![ -INF, -INF, -INF ];
    let bux = vec![ INF, INF, INF ];
    let c   = vec![ 1.0, 1.0, 0.0 ];
    let a   = vec![ 1.0, 1.0, 1.0 ];
    let asub = vec![0, 1, 2];
    //let csub = new int[numvar];
    //double[] xx  = new double[numvar];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG, 
            &mut|msg| print!("{}",msg),
            |task| task.with_callback(
                &mut |caller| { println!("caller = {}",caller); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                       The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                      /* Append 'numvar' variables.
                         The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    /* Define the linear part of the problem */
                    task.put_c_slice(0, numvar, c.as_slice())?;
                    task.put_a_row(0, asub.as_slice(), a.as_slice())?;
                    task.put_con_bound(0, bkc, blc, buc)?;
                    task.put_var_bound_slice(0, numvar, bkx.as_slice(), blx.as_slice(), bux.as_slice())?;

                    /* Add a conic constraint */
                    task.append_afes(3)?;
                    let afeidxs = vec![0,  1,  2  ];
                    let b       = vec![0.0,0.0,0.0];
                    let domidx  = task.append_primal_exp_cone_domain()?;
                    task.put_afe_f_row_list(afeidxs.as_slice(),
                                            vec![1,1,1].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![1.0,1.0,1.0].as_slice())?;
                    task.append_acc(domidx,afeidxs.as_slice(),b.as_slice())?;

                    task.put_obj_sense(Objsense::MINIMIZE)?;

                    println!("optimize");
                    /* Solve the problem */
                    task.optimize()?;
                    // Print a summary containing information
                    // about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    /* Get status information about the solution */
                    let solsta = task.get_sol_sta(Soltype::ITR)?;

                    assert!(solsta == Solsta::OPTIMAL);
                    
                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITR, & mut xx[..])?;
                    
                    println!("Optimal primal solution");
                    for j in 0..numvar as usize {
                        println!("x[{}]: {:.4}",j,xx[j]);
                    }
                    Ok(())
                }))
}
examples/reoptimization.rs (line 54)
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
fn main() -> Result<(),String> {

    let numcon = 3;
    let numvar = 3;
    let c = &[1.5, 2.5, 3.0 ];
    let bkc = &[ Boundkey::UP,
                 Boundkey::UP,
                 Boundkey::UP ];
    let blc = &[ -INF,
                 -INF,
                 -INF ];
    let buc = &[ 100000.0,
                 50000.0,
                 60000.0 ];
    let bkx = &[ Boundkey::LO,
                 Boundkey::LO,
                 Boundkey::LO
                             ];
    let blx = &[ 0.0, 0.0, 0.0 ];
    let bux = &[ INF,
                 INF,
                 INF ];

    let asub = &[
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ] ];

    let aval = &[
        &[ 2.0, 3.0, 2.0 ],
        &[ 4.0, 2.0, 3.0 ],
        &[ 3.0, 3.0, 2.0 ] ];


    let mut task = Task::new().unwrap();
    /* Append the constraints. */
    task.append_cons(numcon)?;

    /* Append the variables. */
    task.append_vars(numvar)?;

    /* Put C. */
    for (j,&cj) in (0..numvar).zip(c.iter()) {
        task.put_c_j(j,cj)?;
    }
    /* Put constraint bounds. */
    for (i,&bki,&bli,&bui) in izip!(0..numcon,bkc,blc,buc) {
        task.put_con_bound(i, bki, bli, bui)?;
    }

    /* Put variable bounds. */
    for (j,&bki,&bli,&bui) in izip!(0..numvar,bkx,blx,bux) {
        task.put_var_bound(j, bki, bli, bui)?;
    }

    /* Put A. */
    if numcon > 0 {
        for (j,&asubj,&avalj) in izip!(0..numvar,asub,aval) {
            task.put_a_col(j,
                           asubj,
                           avalj)?;
        }
    }

    /* A maximization problem */
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    /* Solve the problem */
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /****************** Make a change to the A matrix ******************/
    task.put_aij(0, 0, 3.0)?;
    let _trm = task.optimize()?;
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /***************** Add a new variable ******************************/
    /* Get index of new variable. */

    let varidx = task.get_num_var()?;

    /* Append a new variable x_3 to the problem */
    task.append_vars(1)?;
    let numvar = numvar + 1;

    /* Set bounds on new varaible */
    task.put_var_bound(varidx, Boundkey::LO, 0.0, INF)?;

    /* Change objective */
    task.put_c_j(varidx, 1.0)?;

    /* Put new values in the A matrix */
    let acolsub = &[0i32, 2];
    let acolval = &[4.0, 1.0];

    task.put_a_col(varidx, /* column index */
                   acolsub,
                   acolval)?;

    /* Change optimizer to simplex free and reoptimize */
    task.put_int_param(mosek::Iparam::OPTIMIZER, mosek::Optimizertype::FREE_SIMPLEX)?;
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Add a new constraint ***************************/
    /* Get index of new constraint. */
    let conidx = task.get_num_con()?;

    /* Append a new constraint */
    task.append_cons(1)?;
    let numcon = numcon + 1;

    /* Set bounds on new constraint */
    task.put_con_bound(conidx,
                       Boundkey::UP,
                       -INF,
                       30000.0)?;

    /* Put new values in the A matrix */
    let arowsub = &[0i32,   1,   2,   3  ];
    let arowval = &[1.0, 2.0, 1.0, 1.0 ];

    task.put_a_row(conidx, /* row index */
                   arowsub,
                   arowval)?;

    let _trm = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Change constraint bounds ********************/
    let newbkc = &[Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP];
    let newblc = &[-INF,
                   -INF,
                   -INF,
                   -INF];
    let newbuc = &[ 80000.0, 40000.0, 50000.0, 22000.0 ];

    task.put_con_bound_slice(0, numcon, newbkc, newblc, newbuc)?;

    let _ = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    Ok(())
}
source

pub fn async_get_log( &mut self, addr_: &str, accesstoken_: &str, token_: &str ) -> Result<(), String>

Get the optimizer log from a remote job.

§Arguments
  • addr_ Address of the solver server
  • accesstoken_ Access token string.
  • token_ Job token

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.asyncgetlog

source

pub fn async_get_result( &mut self, address_: &str, accesstoken_: &str, token_: &str, resp_: &mut i32, trm_: &mut i32 ) -> Result<bool, String>

Request a solution from a remote job.

§Arguments
  • address_ Address of the OptServer.

  • accesstoken_ Access token.

  • token_ The task token.

  • resp_ Is the response code from the remote solver.

    See Rescode

  • trm_ Is either OK or a termination response code.

    See Rescode

§Returns
  • respavailable Indicates if a remote response is available.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.asyncgetresult

Examples found in repository?
examples/opt_server_async.rs (lines 90-94)
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
fn opt_server_async(inputfile : FileOrText, addr : String, numpolls : usize, cert : Option<String>) -> Result<(),String> {
    // Path to certificate, if any

    let token = {
        Task::new().unwrap()
            .with_stream_callback(
                Streamtype::LOG,
                &mut |msg| print!("{}",msg),
                |task| {
                    match inputfile {
                        FileOrText::File(ref filename) => task.read_data(filename.as_str()).unwrap(),
                        FileOrText::Text(ref data)     => task.read_ptf_string(data.as_str()).unwrap()
                    }
                    if let Some(ref cert) = cert {
                        task.put_str_param(Sparam::REMOTE_TLS_CERT_PATH,cert.as_str())?;
                    }
                    task.async_optimize(addr.as_str(),"")
                }).expect("Failed to submit async optimization")
    };

    println!("Task token = '{}'", token);

    println!("Setting log stream...");
    Task::new().unwrap().with_stream_callback(
        Streamtype::LOG,
        & mut |msg| print!("{}",msg),
        |task| task.with_callback(
            &mut|caller| { println!("caller = {}",caller); false },
            |task| {
                println!("Reading input file '{:?}'...",inputfile);
                match inputfile {
                    FileOrText::File(ref filename) => task.read_data(filename.as_str()).unwrap(),
                    FileOrText::Text(ref data)     => task.read_ptf_string(data.as_str()).unwrap()
                }
                if let Some(ref cert) = cert {
                    task.put_str_param(Sparam::REMOTE_TLS_CERT_PATH,cert.as_str())?;
                }

                println!("Starting polling loop...");
                for i in 0..numpolls {
                    sleep(Duration::new(1,0));

                    println!("\tpoll {}...", i);

                    let mut trm  : i32 = 0;
                    let mut resp : i32 = 0;

                    let respavailable = task.async_poll(addr.as_str(),
                                                        "",
                                                        token.as_str(),
                                                        & mut resp,
                                                        & mut trm)?;

                    if respavailable {
                        println!("solution available!");

                        task.async_get_result(addr.as_str(),
                                              "",
                                              token.as_str(),
                                              & mut resp,
                                              & mut trm)?;

                        task.solution_summary (Streamtype::LOG)?;
                        return Ok(());
                    }
                }

                println!("max num polls reached, stopping host.");
                task.async_stop (addr.as_str(), "", token.as_str())?;
                Err("Max num polls".to_string())
            }))
}
source

pub fn async_optimize( &mut self, address_: &str, accesstoken_: &str ) -> Result<String, String>

Offload the optimization task to a solver server in asynchronous mode.

§Arguments
  • address_ Address of the OptServer.
  • accesstoken_ Access token.
§Returns
  • token Returns the task token.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.asyncoptimize

Examples found in repository?
examples/opt_server_async.rs (line 50)
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
fn opt_server_async(inputfile : FileOrText, addr : String, numpolls : usize, cert : Option<String>) -> Result<(),String> {
    // Path to certificate, if any

    let token = {
        Task::new().unwrap()
            .with_stream_callback(
                Streamtype::LOG,
                &mut |msg| print!("{}",msg),
                |task| {
                    match inputfile {
                        FileOrText::File(ref filename) => task.read_data(filename.as_str()).unwrap(),
                        FileOrText::Text(ref data)     => task.read_ptf_string(data.as_str()).unwrap()
                    }
                    if let Some(ref cert) = cert {
                        task.put_str_param(Sparam::REMOTE_TLS_CERT_PATH,cert.as_str())?;
                    }
                    task.async_optimize(addr.as_str(),"")
                }).expect("Failed to submit async optimization")
    };

    println!("Task token = '{}'", token);

    println!("Setting log stream...");
    Task::new().unwrap().with_stream_callback(
        Streamtype::LOG,
        & mut |msg| print!("{}",msg),
        |task| task.with_callback(
            &mut|caller| { println!("caller = {}",caller); false },
            |task| {
                println!("Reading input file '{:?}'...",inputfile);
                match inputfile {
                    FileOrText::File(ref filename) => task.read_data(filename.as_str()).unwrap(),
                    FileOrText::Text(ref data)     => task.read_ptf_string(data.as_str()).unwrap()
                }
                if let Some(ref cert) = cert {
                    task.put_str_param(Sparam::REMOTE_TLS_CERT_PATH,cert.as_str())?;
                }

                println!("Starting polling loop...");
                for i in 0..numpolls {
                    sleep(Duration::new(1,0));

                    println!("\tpoll {}...", i);

                    let mut trm  : i32 = 0;
                    let mut resp : i32 = 0;

                    let respavailable = task.async_poll(addr.as_str(),
                                                        "",
                                                        token.as_str(),
                                                        & mut resp,
                                                        & mut trm)?;

                    if respavailable {
                        println!("solution available!");

                        task.async_get_result(addr.as_str(),
                                              "",
                                              token.as_str(),
                                              & mut resp,
                                              & mut trm)?;

                        task.solution_summary (Streamtype::LOG)?;
                        return Ok(());
                    }
                }

                println!("max num polls reached, stopping host.");
                task.async_stop (addr.as_str(), "", token.as_str())?;
                Err("Max num polls".to_string())
            }))
}
source

pub fn async_poll( &mut self, address_: &str, accesstoken_: &str, token_: &str, resp_: &mut i32, trm_: &mut i32 ) -> Result<bool, String>

Requests information about the status of the remote job.

§Arguments
  • address_ Address of the OptServer.

  • accesstoken_ Access token.

  • token_ The task token.

  • resp_ Is the response code from the remote solver.

    See Rescode

  • trm_ Is either OK or a termination response code.

    See Rescode

§Returns
  • respavailable Indicates if a remote response is available.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.asyncpoll

Examples found in repository?
examples/opt_server_async.rs (lines 81-85)
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
fn opt_server_async(inputfile : FileOrText, addr : String, numpolls : usize, cert : Option<String>) -> Result<(),String> {
    // Path to certificate, if any

    let token = {
        Task::new().unwrap()
            .with_stream_callback(
                Streamtype::LOG,
                &mut |msg| print!("{}",msg),
                |task| {
                    match inputfile {
                        FileOrText::File(ref filename) => task.read_data(filename.as_str()).unwrap(),
                        FileOrText::Text(ref data)     => task.read_ptf_string(data.as_str()).unwrap()
                    }
                    if let Some(ref cert) = cert {
                        task.put_str_param(Sparam::REMOTE_TLS_CERT_PATH,cert.as_str())?;
                    }
                    task.async_optimize(addr.as_str(),"")
                }).expect("Failed to submit async optimization")
    };

    println!("Task token = '{}'", token);

    println!("Setting log stream...");
    Task::new().unwrap().with_stream_callback(
        Streamtype::LOG,
        & mut |msg| print!("{}",msg),
        |task| task.with_callback(
            &mut|caller| { println!("caller = {}",caller); false },
            |task| {
                println!("Reading input file '{:?}'...",inputfile);
                match inputfile {
                    FileOrText::File(ref filename) => task.read_data(filename.as_str()).unwrap(),
                    FileOrText::Text(ref data)     => task.read_ptf_string(data.as_str()).unwrap()
                }
                if let Some(ref cert) = cert {
                    task.put_str_param(Sparam::REMOTE_TLS_CERT_PATH,cert.as_str())?;
                }

                println!("Starting polling loop...");
                for i in 0..numpolls {
                    sleep(Duration::new(1,0));

                    println!("\tpoll {}...", i);

                    let mut trm  : i32 = 0;
                    let mut resp : i32 = 0;

                    let respavailable = task.async_poll(addr.as_str(),
                                                        "",
                                                        token.as_str(),
                                                        & mut resp,
                                                        & mut trm)?;

                    if respavailable {
                        println!("solution available!");

                        task.async_get_result(addr.as_str(),
                                              "",
                                              token.as_str(),
                                              & mut resp,
                                              & mut trm)?;

                        task.solution_summary (Streamtype::LOG)?;
                        return Ok(());
                    }
                }

                println!("max num polls reached, stopping host.");
                task.async_stop (addr.as_str(), "", token.as_str())?;
                Err("Max num polls".to_string())
            }))
}
source

pub fn async_stop( &mut self, address_: &str, accesstoken_: &str, token_: &str ) -> Result<(), String>

Request that the job identified by the token is terminated.

§Arguments
  • address_ Address of the OptServer.
  • accesstoken_ Access token.
  • token_ The task token.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.asyncstop

Examples found in repository?
examples/opt_server_async.rs (line 102)
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
fn opt_server_async(inputfile : FileOrText, addr : String, numpolls : usize, cert : Option<String>) -> Result<(),String> {
    // Path to certificate, if any

    let token = {
        Task::new().unwrap()
            .with_stream_callback(
                Streamtype::LOG,
                &mut |msg| print!("{}",msg),
                |task| {
                    match inputfile {
                        FileOrText::File(ref filename) => task.read_data(filename.as_str()).unwrap(),
                        FileOrText::Text(ref data)     => task.read_ptf_string(data.as_str()).unwrap()
                    }
                    if let Some(ref cert) = cert {
                        task.put_str_param(Sparam::REMOTE_TLS_CERT_PATH,cert.as_str())?;
                    }
                    task.async_optimize(addr.as_str(),"")
                }).expect("Failed to submit async optimization")
    };

    println!("Task token = '{}'", token);

    println!("Setting log stream...");
    Task::new().unwrap().with_stream_callback(
        Streamtype::LOG,
        & mut |msg| print!("{}",msg),
        |task| task.with_callback(
            &mut|caller| { println!("caller = {}",caller); false },
            |task| {
                println!("Reading input file '{:?}'...",inputfile);
                match inputfile {
                    FileOrText::File(ref filename) => task.read_data(filename.as_str()).unwrap(),
                    FileOrText::Text(ref data)     => task.read_ptf_string(data.as_str()).unwrap()
                }
                if let Some(ref cert) = cert {
                    task.put_str_param(Sparam::REMOTE_TLS_CERT_PATH,cert.as_str())?;
                }

                println!("Starting polling loop...");
                for i in 0..numpolls {
                    sleep(Duration::new(1,0));

                    println!("\tpoll {}...", i);

                    let mut trm  : i32 = 0;
                    let mut resp : i32 = 0;

                    let respavailable = task.async_poll(addr.as_str(),
                                                        "",
                                                        token.as_str(),
                                                        & mut resp,
                                                        & mut trm)?;

                    if respavailable {
                        println!("solution available!");

                        task.async_get_result(addr.as_str(),
                                              "",
                                              token.as_str(),
                                              & mut resp,
                                              & mut trm)?;

                        task.solution_summary (Streamtype::LOG)?;
                        return Ok(());
                    }
                }

                println!("max num polls reached, stopping host.");
                task.async_stop (addr.as_str(), "", token.as_str())?;
                Err("Max num polls".to_string())
            }))
}
source

pub fn basis_cond( &mut self, nrmbasis_: &mut f64, nrminvbasis_: &mut f64 ) -> Result<(), String>

Computes conditioning information for the basis matrix.

§Arguments
  • nrmbasis_ An estimate for the 1-norm of the basis.
  • nrminvbasis_ An estimate for the 1-norm of the inverse of the basis.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.basiscond

source

pub fn check_mem(&mut self, file_: &str, line_: i32) -> Result<(), String>

Checks the memory allocated by the task.

§Arguments
  • file_ File from which the function is called.
  • line_ Line in the file from which the function is called.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.checkmemtask

source

pub fn chg_con_bound( &mut self, i_: i32, lower_: i32, finite_: i32, value_: f64 ) -> Result<(), String>

Changes the bounds for one constraint.

§Arguments
  • i_ Index of the constraint for which the bounds should be changed.
  • lower_ If non-zero, then the lower bound is changed, otherwise the upper bound is changed.
  • finite_ If non-zero, then the given value is assumed to be finite.
  • value_ New value for the bound.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.chgconbound

source

pub fn chg_var_bound( &mut self, j_: i32, lower_: i32, finite_: i32, value_: f64 ) -> Result<(), String>

Changes the bounds for one variable.

§Arguments
  • j_ Index of the variable for which the bounds should be changed.
  • lower_ If non-zero, then the lower bound is changed, otherwise the upper bound is changed.
  • finite_ If non-zero, then the given value is assumed to be finite.
  • value_ New value for the bound.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.chgvarbound

source

pub fn commit_changes(&mut self) -> Result<(), String>

source

pub fn delete_solution(&mut self, whichsol_: i32) -> Result<(), String>

Undefine a solution and free the memory it uses.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.deletesolution

Examples found in repository?
examples/solvelinear.rs (line 51)
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
fn setup(task : & mut mosek::Task,
         aval : &[f64],
         asub : &[i32],
         ptrb : &[i64],
         ptre : &[i64],
         numvar : i32) -> Result<Vec<i32>,String> {

    // mosek.stakey[] skx = new mosek.stakey [numvar];
    // mosek.stakey[] skc = new mosek.stakey [numvar];

    // for (int i = 0; i < numvar ; ++i) {
    //   skx[i] = mosek.stakey.bas;
    //   skc[i] = mosek.stakey.fix;
    // }

    task.append_vars(numvar)?;
    task.append_cons(numvar)?;

    task.put_a_col_slice(0,numvar,ptrb,ptre,asub,aval)?;

    task.put_con_bound_slice_const(0,numvar,Boundkey::FX,0.0,0.0)?;
    task.put_var_bound_slice_const(0,numvar,Boundkey::FR,-INF,INF)?;

    /* Define a basic solution by specifying
       status keys for variables & constraints. */
    task.delete_solution(Soltype::BAS)?;

    task.put_skc_slice(Soltype::BAS, 0, numvar, vec![Stakey::FIX; numvar as usize].as_slice())?;
    task.put_skx_slice(Soltype::BAS, 0, numvar, vec![Stakey::BAS; numvar as usize].as_slice())?;

    let mut basis = vec![0; numvar as usize];
    task.init_basis_solve(basis.as_mut_slice())?;
    Ok(basis)
  }
source

pub fn dual_sensitivity( &self, subj_: &[i32], leftpricej_: &mut [f64], rightpricej_: &mut [f64], leftrangej_: &mut [f64], rightrangej_: &mut [f64] ) -> Result<(), String>

Performs sensitivity analysis on objective coefficients.

§Arguments
  • subj_ Indexes of objective coefficients to analyze.
  • leftpricej_ Left shadow prices for requested coefficients.
  • rightpricej_ Right shadow prices for requested coefficients.
  • leftrangej_ Left range for requested coefficients.
  • rightrangej_ Right range for requested coefficients.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.dualsensitivity

source

pub fn empty_afe_barf_row(&mut self, afeidx_: i64) -> Result<(), String>

Clears a row in barF

§Arguments
  • afeidx_ Row index of barF.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.emptyafebarfrow

source

pub fn empty_afe_barf_row_list( &mut self, afeidxlist_: &[i64] ) -> Result<(), String>

Clears rows in barF.

§Arguments
  • afeidxlist_ Indices of rows in barF to clear.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.emptyafebarfrowlist

source

pub fn empty_afe_f_col(&mut self, varidx_: i32) -> Result<(), String>

Clears a column in F.

§Arguments
  • varidx_ Variable index.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.emptyafefcol

source

pub fn empty_afe_f_col_list(&mut self, varidx_: &[i32]) -> Result<(), String>

Clears columns in F.

§Arguments
  • varidx_ Indices of variables in F to clear.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.emptyafefcollist

source

pub fn empty_afe_f_row(&mut self, afeidx_: i64) -> Result<(), String>

Clears a row in F.

§Arguments
  • afeidx_ Row index.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.emptyafefrow

source

pub fn empty_afe_f_row_list(&mut self, afeidx_: &[i64]) -> Result<(), String>

Clears rows in F.

§Arguments
  • afeidx_ Indices of rows in F to clear.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.emptyafefrowlist

source

pub fn evaluate_acc( &self, whichsol_: i32, accidx_: i64, activity_: &mut [f64] ) -> Result<(), String>

Evaluates the activity of an affine conic constraint.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • accidx_ The index of the affine conic constraint.

  • activity_ The activity of the affine conic constraint. The array should have length equal to the dimension of the constraint.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.evaluateacc

source

pub fn evaluate_accs( &self, whichsol_: i32, activity_: &mut [f64] ) -> Result<(), String>

Evaluates the activities of all affine conic constraints.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • activity_ The activity of affine conic constraints. The array should have length equal to the sum of dimensions of all affine conic constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.evaluateaccs

source

pub fn generate_acc_names( &mut self, sub_: &[i64], fmt_: &str, dims_: &[i32], sp_: &[i64], namedaxisidxs_: &[i32], names_: &[String] ) -> Result<(), String>

Generates systematic names for affine conic constraints.

§Arguments
  • sub_ Indexes of the affine conic constraints.
  • fmt_ The variable name formatting string.
  • dims_ Dimensions in the shape.
  • sp_ Items that should be named.
  • namedaxisidxs_ List if named index axes
  • names_ All axis names.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.generateaccnames

source

pub fn generate_barvar_names( &mut self, subj_: &[i32], fmt_: &str, dims_: &[i32], sp_: &[i64], namedaxisidxs_: &[i32], names_: &[String] ) -> Result<(), String>

Generates systematic names for variables.

§Arguments
  • subj_ Indexes of the variables.
  • fmt_ The variable name formatting string.
  • dims_ Dimensions in the shape.
  • sp_ Items that should be named.
  • namedaxisidxs_ List if named index axes
  • names_ All axis names.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.generatebarvarnames

source

pub fn generate_cone_names( &mut self, subk_: &[i32], fmt_: &str, dims_: &[i32], sp_: &[i64], namedaxisidxs_: &[i32], names_: &[String] ) -> Result<(), String>

Generates systematic names for cone.

§Arguments
  • subk_ Indexes of the cone.
  • fmt_ The cone name formatting string.
  • dims_ Dimensions in the shape.
  • sp_ Items that should be named.
  • namedaxisidxs_ List if named index axes
  • names_ All axis names.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.generateconenames

source

pub fn generate_con_names( &mut self, subi_: &[i32], fmt_: &str, dims_: &[i32], sp_: &[i64], namedaxisidxs_: &[i32], names_: &[String] ) -> Result<(), String>

Generates systematic names for constraints.

§Arguments
  • subi_ Indexes of the constraints.
  • fmt_ The constraint name formatting string.
  • dims_ Dimensions in the shape.
  • sp_ Items that should be named.
  • namedaxisidxs_ List if named index axes
  • names_ All axis names.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.generateconnames

source

pub fn generate_djc_names( &mut self, sub_: &[i64], fmt_: &str, dims_: &[i32], sp_: &[i64], namedaxisidxs_: &[i32], names_: &[String] ) -> Result<(), String>

Generates systematic names for affine conic constraints.

§Arguments
  • sub_ Indexes of the disjunctive constraints.
  • fmt_ The variable name formatting string.
  • dims_ Dimensions in the shape.
  • sp_ Items that should be named.
  • namedaxisidxs_ List if named index axes
  • names_ All axis names.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.generatedjcnames

source

pub fn generate_var_names( &mut self, subj_: &[i32], fmt_: &str, dims_: &[i32], sp_: &[i64], namedaxisidxs_: &[i32], names_: &[String] ) -> Result<(), String>

Generates systematic names for variables.

§Arguments
  • subj_ Indexes of the variables.
  • fmt_ The variable name formatting string.
  • dims_ Dimensions in the shape.
  • sp_ Items that should be named.
  • namedaxisidxs_ List if named index axes
  • names_ All axis names.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.generatevarnames

source

pub fn get_acc_afe_idx_list( &self, accidx_: i64, afeidxlist_: &mut [i64] ) -> Result<(), String>

Obtains the list of affine expressions appearing in the affine conic constraint.

§Arguments
  • accidx_ Index of the affine conic constraint.
  • afeidxlist_ List of indexes of affine expressions appearing in the constraint.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getaccafeidxlist

source

pub fn get_acc_b(&self, accidx_: i64, b_: &mut [f64]) -> Result<(), String>

Obtains the additional constant term vector appearing in the affine conic constraint.

§Arguments
  • accidx_ Index of the affine conic constraint.
  • b_ The vector b appearing in the constraint.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getaccb

source

pub fn get_acc_barf_block_triplet( &self, acc_afe_: &mut [i64], bar_var_: &mut [i32], blk_row_: &mut [i32], blk_col_: &mut [i32], blk_val_: &mut [f64] ) -> Result<i64, String>

Obtains barF, implied by the ACCs, in block triplet form.

§Arguments
  • acc_afe_ Index of the AFE within the concatenated list of AFEs in ACCs.
  • bar_var_ Symmetric matrix variable index.
  • blk_row_ Block row index.
  • blk_col_ Block column index.
  • blk_val_ The numerical value associated with each block triplet.
§Returns
  • numtrip Number of elements in the block triplet form.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getaccbarfblocktriplet

source

pub fn get_acc_barf_num_block_triplets(&self) -> Result<i64, String>

Obtains an upper bound on the number of elements in the block triplet form of barf, as used within the ACCs.

§Returns
  • numtrip An upper bound on the number of elements in the block triplet form of barf, as used within the ACCs.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getaccbarfnumblocktriplets

source

pub fn get_acc_domain(&mut self, accidx_: i64) -> Result<i64, String>

Obtains the domain appearing in the affine conic constraint.

§Arguments
  • accidx_ The index of the affine conic constraint.
§Returns
  • domidx The index of domain in the affine conic constraint.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getaccdomain

source

pub fn get_acc_dot_y( &self, whichsol_: i32, accidx_: i64, doty_: &mut [f64] ) -> Result<(), String>

Obtains the doty vector for an affine conic constraint.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • accidx_ The index of the affine conic constraint.

  • doty_ The dual values for this affine conic constraint. The array should have length equal to the dimension of the constraint.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getaccdoty

source

pub fn get_acc_dot_y_s( &self, whichsol_: i32, doty_: &mut [f64] ) -> Result<(), String>

Obtains the doty vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • doty_ The dual values of affine conic constraints. The array should have length equal to the sum of dimensions of all affine conic constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getaccdotys

source

pub fn get_acc_f_numnz(&mut self) -> Result<i64, String>

Obtains the total number of nonzeros in the ACC implied F matrix.

§Returns
  • accfnnz Number of nonzeros in the F matrix implied by ACCs.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getaccfnumnz

source

pub fn get_acc_f_trip( &mut self, frow_: &mut [i64], fcol_: &mut [i32], fval_: &mut [f64] ) -> Result<(), String>

Obtains the F matrix (implied by the AFE ordering within the ACCs) in triplet format.

§Arguments
  • frow_ Row indices of nonzeros in the implied F matrix.
  • fcol_ Column indices of nonzeros in the implied F matrix.
  • fval_ Values of nonzero entries in the implied F matrix.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getaccftrip

source

pub fn get_acc_g_vector(&self, g_: &mut [f64]) -> Result<(), String>

The g vector as used within the ACCs.

§Arguments
  • g_ The g vector as used within the ACCs.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getaccgvector

source

pub fn get_acc_n(&mut self, accidx_: i64) -> Result<i64, String>

Obtains the dimension of the affine conic constraint.

§Arguments
  • accidx_ The index of the affine conic constraint.
§Returns
  • n The dimension of the affine conic constraint (equal to the dimension of its domain).

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getaccn

source

pub fn get_acc_name(&self, accidx_: i64) -> Result<String, String>

Obtains the name of an affine conic constraint.

§Arguments
  • accidx_ Index of an affine conic constraint.
§Returns
  • name Returns the required name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getaccname

source

pub fn get_acc_name_len(&self, accidx_: i64) -> Result<i32, String>

Obtains the length of the name of an affine conic constraint.

§Arguments
  • accidx_ Index of an affine conic constraint.
§Returns
  • len Returns the length of the indicated name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getaccnamelen

source

pub fn get_acc_n_tot(&mut self) -> Result<i64, String>

Obtains the total dimension of all affine conic constraints.

§Returns
  • n The total dimension of all affine conic constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getaccntot

source

pub fn get_accs( &self, domidxlist_: &mut [i64], afeidxlist_: &mut [i64], b_: &mut [f64] ) -> Result<(), String>

Obtains full data of all affine conic constraints.

§Arguments
  • domidxlist_ The list of domains appearing in all affine conic constraints.
  • afeidxlist_ The concatenation of index lists of affine expressions appearing in all affine conic constraints.
  • b_ The concatenation of vectors b appearing in all affine conic constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getaccs

source

pub fn get_a_col( &self, j_: i32, nzj_: &mut i32, subj_: &mut [i32], valj_: &mut [f64] ) -> Result<(), String>

Obtains one column of the linear constraint matrix.

§Arguments
  • j_ Index of the column.
  • nzj_ Number of non-zeros in the column obtained.
  • subj_ Row indices of the non-zeros in the column obtained.
  • valj_ Numerical values in the column obtained.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getacol

source

pub fn get_a_col_num_nz(&self, i_: i32) -> Result<i32, String>

Obtains the number of non-zero elements in one column of the linear constraint matrix

§Arguments
  • i_ Index of the column.
§Returns
  • nzj Number of non-zeros in the j’th column of (A).

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getacolnumnz

source

pub fn get_a_col_slice( &self, first_: i32, last_: i32, ptrb_: &mut [i64], ptre_: &mut [i64], sub_: &mut [i32], val_: &mut [f64] ) -> Result<(), String>

Obtains a sequence of columns from the coefficient matrix.

§Arguments
  • first_ Index of the first column in the sequence.
  • last_ Index of the last column in the sequence plus one.
  • ptrb_ Column start pointers.
  • ptre_ Column end pointers.
  • sub_ Contains the row subscripts.
  • val_ Contains the coefficient values.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getacolslice64

source

pub fn get_a_col_slice_num_nz( &self, first_: i32, last_: i32 ) -> Result<i64, String>

Obtains the number of non-zeros in a slice of columns of the coefficient matrix.

§Arguments
  • first_ Index of the first column in the sequence.
  • last_ Index of the last column plus one in the sequence.
§Returns
  • numnz Number of non-zeros in the slice.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getacolslicenumnz64

source

pub fn get_a_col_slice_trip( &self, first_: i32, last_: i32, subi_: &mut [i32], subj_: &mut [i32], val_: &mut [f64] ) -> Result<(), String>

Obtains a sequence of columns from the coefficient matrix in triplet format.

§Arguments
  • first_ Index of the first column in the sequence.
  • last_ Index of the last column in the sequence plus one.
  • subi_ Constraint subscripts.
  • subj_ Column subscripts.
  • val_ Values.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getacolslicetrip

source

pub fn get_afe_barf_block_triplet( &self, afeidx_: &mut [i64], barvaridx_: &mut [i32], subk_: &mut [i32], subl_: &mut [i32], valkl_: &mut [f64] ) -> Result<i64, String>

Obtains barF in block triplet form.

§Arguments
  • afeidx_ Constraint index.
  • barvaridx_ Symmetric matrix variable index.
  • subk_ Block row index.
  • subl_ Block column index.
  • valkl_ The numerical value associated with each block triplet.
§Returns
  • numtrip Number of elements in the block triplet form.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getafebarfblocktriplet

source

pub fn get_afe_barf_num_block_triplets(&self) -> Result<i64, String>

Obtains an upper bound on the number of elements in the block triplet form of barf.

§Returns
  • numtrip An upper bound on the number of elements in the block triplet form of barf.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getafebarfnumblocktriplets

source

pub fn get_afe_barf_num_row_entries( &mut self, afeidx_: i64 ) -> Result<i32, String>

Obtains the number of nonzero entries in a row of barF.

§Arguments
  • afeidx_ Row index of barF.
§Returns
  • numentr Number of nonzero entries in a row of barF.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getafebarfnumrowentries

source

pub fn get_afe_barf_row( &mut self, afeidx_: i64, barvaridx_: &mut [i32], ptrterm_: &mut [i64], numterm_: &mut [i64], termidx_: &mut [i64], termweight_: &mut [f64] ) -> Result<(), String>

Obtains nonzero entries in one row of barF.

§Arguments
  • afeidx_ Row index of barF.
  • barvaridx_ Semidefinite variable indices.
  • ptrterm_ Pointers to the description of entries.
  • numterm_ Number of terms in each entry.
  • termidx_ Indices of semidefinite matrices from E.
  • termweight_ Weights appearing in the weighted sum representation.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getafebarfrow

source

pub fn get_afe_barf_row_info( &mut self, afeidx_: i64, numentr_: &mut i32, numterm_: &mut i64 ) -> Result<(), String>

Obtains information about one row of barF.

§Arguments
  • afeidx_ Row index of barF.
  • numentr_ Number of nonzero entries in a row of barF.
  • numterm_ Number of terms in the weighted sums representation of the row of barF.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getafebarfrowinfo

source

pub fn get_afe_f_num_nz(&mut self) -> Result<i64, String>

Obtains the total number of nonzeros in F.

§Returns
  • numnz Number of nonzeros in F.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getafefnumnz

source

pub fn get_afe_f_row( &mut self, afeidx_: i64, numnz_: &mut i32, varidx_: &mut [i32], val_: &mut [f64] ) -> Result<(), String>

Obtains one row of F in sparse format.

§Arguments
  • afeidx_ Row index.
  • numnz_ Number of non-zeros in the row obtained.
  • varidx_ Column indices of the non-zeros in the row obtained.
  • val_ Values of the non-zeros in the row obtained.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getafefrow

source

pub fn get_afe_f_row_num_nz(&mut self, afeidx_: i64) -> Result<i32, String>

Obtains the number of nonzeros in a row of F.

§Arguments
  • afeidx_ Row index.
§Returns
  • numnz Number of non-zeros in the row.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getafefrownumnz

source

pub fn get_afe_f_trip( &mut self, afeidx_: &mut [i64], varidx_: &mut [i32], val_: &mut [f64] ) -> Result<(), String>

Obtains the F matrix in triplet format.

§Arguments
  • afeidx_ Row indices of nonzeros.
  • varidx_ Column indices of nonzeros.
  • val_ Values of nonzero entries.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getafeftrip

source

pub fn get_afe_g(&mut self, afeidx_: i64) -> Result<f64, String>

Obtains a single coefficient in g.

§Arguments
  • afeidx_ Element index.
§Returns
  • g The entry in g.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getafeg

source

pub fn get_afe_g_slice( &self, first_: i64, last_: i64, g_: &mut [f64] ) -> Result<(), String>

Obtains a sequence of coefficients from the vector g.

§Arguments
  • first_ First index in the sequence.
  • last_ Last index plus 1 in the sequence.
  • g_ The slice of g as a dense vector.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getafegslice

source

pub fn get_aij(&self, i_: i32, j_: i32) -> Result<f64, String>

Obtains a single coefficient in linear constraint matrix.

§Arguments
  • i_ Row index of the coefficient to be returned.
  • j_ Column index of the coefficient to be returned.
§Returns
  • aij Returns the requested coefficient.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getaij

source

pub fn get_a_piece_num_nz( &self, firsti_: i32, lasti_: i32, firstj_: i32, lastj_: i32 ) -> Result<i32, String>

Obtains the number non-zeros in a rectangular piece of the linear constraint matrix.

§Arguments
  • firsti_ Index of the first row in the rectangular piece.
  • lasti_ Index of the last row plus one in the rectangular piece.
  • firstj_ Index of the first column in the rectangular piece.
  • lastj_ Index of the last column plus one in the rectangular piece.
§Returns
  • numnz Number of non-zero elements in the rectangular piece of the linear constraint matrix.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getapiecenumnz

source

pub fn get_a_row( &self, i_: i32, nzi_: &mut i32, subi_: &mut [i32], vali_: &mut [f64] ) -> Result<(), String>

Obtains one row of the linear constraint matrix.

§Arguments
  • i_ Index of the row.
  • nzi_ Number of non-zeros in the row obtained.
  • subi_ Column indices of the non-zeros in the row obtained.
  • vali_ Numerical values of the row obtained.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getarow

source

pub fn get_a_row_num_nz(&self, i_: i32) -> Result<i32, String>

Obtains the number of non-zero elements in one row of the linear constraint matrix

§Arguments
  • i_ Index of the row.
§Returns
  • nzi Number of non-zeros in the i’th row of A.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getarownumnz

source

pub fn get_a_row_slice( &self, first_: i32, last_: i32, ptrb_: &mut [i64], ptre_: &mut [i64], sub_: &mut [i32], val_: &mut [f64] ) -> Result<(), String>

Obtains a sequence of rows from the coefficient matrix.

§Arguments
  • first_ Index of the first row in the sequence.
  • last_ Index of the last row in the sequence plus one.
  • ptrb_ Row start pointers.
  • ptre_ Row end pointers.
  • sub_ Contains the column subscripts.
  • val_ Contains the coefficient values.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getarowslice64

source

pub fn get_a_row_slice_num_nz( &self, first_: i32, last_: i32 ) -> Result<i64, String>

Obtains the number of non-zeros in a slice of rows of the coefficient matrix.

§Arguments
  • first_ Index of the first row in the sequence.
  • last_ Index of the last row plus one in the sequence.
§Returns
  • numnz Number of non-zeros in the slice.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getarowslicenumnz64

source

pub fn get_a_row_slice_trip( &self, first_: i32, last_: i32, subi_: &mut [i32], subj_: &mut [i32], val_: &mut [f64] ) -> Result<(), String>

Obtains a sequence of rows from the coefficient matrix in sparse triplet format.

§Arguments
  • first_ Index of the first row in the sequence.
  • last_ Index of the last row in the sequence plus one.
  • subi_ Constraint subscripts.
  • subj_ Column subscripts.
  • val_ Values.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getarowslicetrip

source

pub fn get_a_trip( &self, subi_: &mut [i32], subj_: &mut [i32], val_: &mut [f64] ) -> Result<(), String>

Obtains the A matrix in sparse triplet format.

§Arguments
  • subi_ Constraint subscripts.
  • subj_ Column subscripts.
  • val_ Values.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getatrip

source

pub fn get_a_truncate_tol(&self, tolzero_: &mut [f64]) -> Result<(), String>

Gets the current A matrix truncation threshold.

§Arguments
  • tolzero_ Truncation tolerance.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getatruncatetol

source

pub fn get_bara_block_triplet( &self, subi_: &mut [i32], subj_: &mut [i32], subk_: &mut [i32], subl_: &mut [i32], valijkl_: &mut [f64] ) -> Result<i64, String>

Obtains barA in block triplet form.

§Arguments
  • subi_ Constraint index.
  • subj_ Symmetric matrix variable index.
  • subk_ Block row index.
  • subl_ Block column index.
  • valijkl_ The numerical value associated with each block triplet.
§Returns
  • num Number of elements in the block triplet form.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getbarablocktriplet

source

pub fn get_bara_idx( &self, idx_: i64, i_: &mut i32, j_: &mut i32, sub_: &mut [i64], weights_: &mut [f64] ) -> Result<i64, String>

Obtains information about an element in barA.

§Arguments
  • idx_ Position of the element in the vectorized form.
  • i_ Row index of the element at position idx.
  • j_ Column index of the element at position idx.
  • sub_ A list indexes of the elements from symmetric matrix storage that appear in the weighted sum.
  • weights_ The weights associated with each term in the weighted sum.
§Returns
  • num Number of terms in weighted sum that forms the element.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getbaraidx

source

pub fn get_bara_idx_i_j( &self, idx_: i64, i_: &mut i32, j_: &mut i32 ) -> Result<(), String>

Obtains information about an element in barA.

§Arguments
  • idx_ Position of the element in the vectorized form.
  • i_ Row index of the element at position idx.
  • j_ Column index of the element at position idx.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getbaraidxij

source

pub fn get_bara_idx_info(&self, idx_: i64) -> Result<i64, String>

Obtains the number of terms in the weighted sum that form a particular element in barA.

§Arguments
  • idx_ The internal position of the element for which information should be obtained.
§Returns
  • num Number of terms in the weighted sum that form the specified element in barA.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getbaraidxinfo

source

pub fn get_bara_sparsity( &self, numnz_: &mut i64, idxij_: &mut [i64] ) -> Result<(), String>

Obtains the sparsity pattern of the barA matrix.

§Arguments
  • numnz_ Number of nonzero elements in barA.
  • idxij_ Position of each nonzero element in the vector representation of barA.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getbarasparsity

source

pub fn get_barc_block_triplet( &self, subj_: &mut [i32], subk_: &mut [i32], subl_: &mut [i32], valjkl_: &mut [f64] ) -> Result<i64, String>

Obtains barC in block triplet form.

§Arguments
  • subj_ Symmetric matrix variable index.
  • subk_ Block row index.
  • subl_ Block column index.
  • valjkl_ The numerical value associated with each block triplet.
§Returns
  • num Number of elements in the block triplet form.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getbarcblocktriplet

source

pub fn get_barc_idx( &self, idx_: i64, j_: &mut i32, num_: &mut i64, sub_: &mut [i64], weights_: &mut [f64] ) -> Result<(), String>

Obtains information about an element in barc.

§Arguments
  • idx_ Index of the element for which information should be obtained.
  • j_ Row index in barc.
  • num_ Number of terms in the weighted sum.
  • sub_ Elements appearing the weighted sum.
  • weights_ Weights of terms in the weighted sum.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getbarcidx

source

pub fn get_barc_idx_info(&self, idx_: i64) -> Result<i64, String>

Obtains information about an element in barc.

§Arguments
  • idx_ Index of the element for which information should be obtained. The value is an index of a symmetric sparse variable.
§Returns
  • num Number of terms that appear in the weighted sum that forms the requested element.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getbarcidxinfo

source

pub fn get_barc_idx_j(&self, idx_: i64, j_: &mut i32) -> Result<(), String>

Obtains the row index of an element in barc.

§Arguments
  • idx_ Index of the element for which information should be obtained.
  • j_ Row index in barc.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getbarcidxj

source

pub fn get_barc_sparsity( &self, numnz_: &mut i64, idxj_: &mut [i64] ) -> Result<(), String>

Get the positions of the nonzero elements in barc.

§Arguments
  • numnz_ Number of nonzero elements in barc.
  • idxj_ Internal positions of the nonzeros elements in barc.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getbarcsparsity

source

pub fn get_bars_j( &self, whichsol_: i32, j_: i32, barsj_: &mut [f64] ) -> Result<(), String>

Obtains the dual solution for a semidefinite variable.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • j_ Index of the semidefinite variable.

  • barsj_ Value of the j’th dual variable of barx.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getbarsj

source

pub fn get_bars_slice( &self, whichsol_: i32, first_: i32, last_: i32, slicesize_: i64, barsslice_: &mut [f64] ) -> Result<(), String>

Obtains the dual solution for a sequence of semidefinite variables.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • first_ Index of the first semidefinite variable in the slice.

  • last_ Index of the last semidefinite variable in the slice plus one.

  • slicesize_ Denotes the length of the array barsslice.

  • barsslice_ Dual solution values of symmetric matrix variables in the slice, stored sequentially.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getbarsslice

source

pub fn get_barvar_name(&self, i_: i32) -> Result<String, String>

Obtains the name of a semidefinite variable.

§Arguments
  • i_ Index of the variable.
§Returns
  • name The requested name is copied to this buffer.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getbarvarname

source

pub fn get_barvar_name_index( &self, somename_: &str, asgn_: &mut i32 ) -> Result<i32, String>

Obtains the index of semidefinite variable from its name.

§Arguments
  • somename_ The name of the variable.
  • asgn_ Non-zero if the name somename is assigned to some semidefinite variable.
§Returns
  • index The index of a semidefinite variable with the name somename (if one exists).

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getbarvarnameindex

source

pub fn get_barvar_name_len(&self, i_: i32) -> Result<i32, String>

Obtains the length of the name of a semidefinite variable.

§Arguments
  • i_ Index of the variable.
§Returns
  • len Returns the length of the indicated name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getbarvarnamelen

source

pub fn get_barx_j( &self, whichsol_: i32, j_: i32, barxj_: &mut [f64] ) -> Result<(), String>

Obtains the primal solution for a semidefinite variable.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • j_ Index of the semidefinite variable.

  • barxj_ Value of the j’th variable of barx.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getbarxj

source

pub fn get_barx_slice( &self, whichsol_: i32, first_: i32, last_: i32, slicesize_: i64, barxslice_: &mut [f64] ) -> Result<(), String>

Obtains the primal solution for a sequence of semidefinite variables.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • first_ Index of the first semidefinite variable in the slice.

  • last_ Index of the last semidefinite variable in the slice plus one.

  • slicesize_ Denotes the length of the array barxslice.

  • barxslice_ Solution values of symmetric matrix variables in the slice, stored sequentially.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getbarxslice

source

pub fn get_c(&self, c_: &mut [f64]) -> Result<(), String>

Obtains all objective coefficients.

§Arguments
  • c_ Linear terms of the objective as a dense vector. The length is the number of variables.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getc

source

pub fn get_cfix(&self) -> Result<f64, String>

Obtains the fixed term in the objective.

§Returns
  • cfix Fixed term in the objective.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getcfix

source

pub fn get_c_j(&self, j_: i32, cj_: &mut f64) -> Result<(), String>

Obtains one objective coefficient.

§Arguments
  • j_ Index of the variable for which the c coefficient should be obtained.
  • cj_ The c coefficient value.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getcj

source

pub fn get_c_list(&self, subj_: &[i32], c_: &mut [f64]) -> Result<(), String>

Obtains a sequence of coefficients from the objective.

§Arguments
  • subj_ A list of variable indexes.
  • c_ Linear terms of the requested list of the objective as a dense vector.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getclist

source

pub fn get_con_bound( &self, i_: i32, bk_: &mut i32, bl_: &mut f64, bu_: &mut f64 ) -> Result<(), String>

Obtains bound information for one constraint.

§Arguments
  • i_ Index of the constraint for which the bound information should be obtained.

  • bk_ Bound keys.

    See Boundkey

  • bl_ Values for lower bounds.

  • bu_ Values for upper bounds.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getconbound

source

pub fn get_con_bound_slice( &self, first_: i32, last_: i32, bk_: &mut [i32], bl_: &mut [f64], bu_: &mut [f64] ) -> Result<(), String>

Obtains bounds information for a slice of the constraints.

§Arguments
  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • bk_ Bound keys.

    See Boundkey

  • bl_ Values for lower bounds.

  • bu_ Values for upper bounds.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getconboundslice

source

pub fn get_cone( &mut self, k_: i32, ct_: &mut i32, conepar_: &mut f64, nummem_: &mut i32, submem_: &mut [i32] ) -> Result<(), String>

Obtains a cone.

§Arguments
  • k_ Index of the cone.

  • ct_ Specifies the type of the cone.

    See Conetype

  • conepar_ For the power cone it denotes the exponent alpha. For other cone types it is unused and can be set to 0.

  • nummem_ Number of member variables in the cone.

  • submem_ Variable subscripts of the members in the cone.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getcone

source

pub fn get_cone_info( &self, k_: i32, ct_: &mut i32, conepar_: &mut f64, nummem_: &mut i32 ) -> Result<(), String>

Obtains information about a cone.

§Arguments
  • k_ Index of the cone.

  • ct_ Specifies the type of the cone.

    See Conetype

  • conepar_ For the power cone it denotes the exponent alpha. For other cone types it is unused and can be set to 0.

  • nummem_ Number of member variables in the cone.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getconeinfo

source

pub fn get_cone_name(&self, i_: i32) -> Result<String, String>

Obtains the name of a cone.

§Arguments
  • i_ Index of the cone.
§Returns
  • name The required name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getconename

source

pub fn get_cone_name_index( &self, somename_: &str, asgn_: &mut i32 ) -> Result<i32, String>

Checks whether the name has been assigned to any cone.

§Arguments
  • somename_ The name which should be checked.
  • asgn_ Is non-zero if the name somename is assigned to some cone.
§Returns
  • index If the name somename is assigned to some cone, this is the index of the cone.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getconenameindex

source

pub fn get_cone_name_len(&self, i_: i32) -> Result<i32, String>

Obtains the length of the name of a cone.

§Arguments
  • i_ Index of the cone.
§Returns
  • len Returns the length of the indicated name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getconenamelen

source

pub fn get_con_name(&self, i_: i32) -> Result<String, String>

Obtains the name of a constraint.

§Arguments
  • i_ Index of the constraint.
§Returns
  • name The required name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getconname

source

pub fn get_con_name_index( &self, somename_: &str, asgn_: &mut i32 ) -> Result<i32, String>

Checks whether the name has been assigned to any constraint.

§Arguments
  • somename_ The name which should be checked.
  • asgn_ Is non-zero if the name somename is assigned to some constraint.
§Returns
  • index If the name somename is assigned to a constraint, then return the index of the constraint.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getconnameindex

source

pub fn get_con_name_len(&self, i_: i32) -> Result<i32, String>

Obtains the length of the name of a constraint.

§Arguments
  • i_ Index of the constraint.
§Returns
  • len Returns the length of the indicated name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getconnamelen

source

pub fn get_c_slice( &self, first_: i32, last_: i32, c_: &mut [f64] ) -> Result<(), String>

Obtains a sequence of coefficients from the objective.

§Arguments
  • first_ First index in the sequence.
  • last_ Last index plus 1 in the sequence.
  • c_ Linear terms of the requested slice of the objective as a dense vector.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getcslice

source

pub fn get_dim_barvar_j(&self, j_: i32) -> Result<i32, String>

Obtains the dimension of a symmetric matrix variable.

§Arguments
  • j_ Index of the semidefinite variable whose dimension is requested.
§Returns
  • dimbarvarj The dimension of the j’th semidefinite variable.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdimbarvarj

source

pub fn get_djc_afe_idx_list( &self, djcidx_: i64, afeidxlist_: &mut [i64] ) -> Result<(), String>

Obtains the list of affine expression indexes in a disjunctive constraint.

§Arguments
  • djcidx_ Index of the disjunctive constraint.
  • afeidxlist_ List of affine expression indexes.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdjcafeidxlist

source

pub fn get_djc_b(&self, djcidx_: i64, b_: &mut [f64]) -> Result<(), String>

Obtains the optional constant term vector of a disjunctive constraint.

§Arguments
  • djcidx_ Index of the disjunctive constraint.
  • b_ The vector b.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdjcb

source

pub fn get_djc_domain_idx_list( &self, djcidx_: i64, domidxlist_: &mut [i64] ) -> Result<(), String>

Obtains the list of domain indexes in a disjunctive constraint.

§Arguments
  • djcidx_ Index of the disjunctive constraint.
  • domidxlist_ List of term sizes.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdjcdomainidxlist

source

pub fn get_djc_name(&self, djcidx_: i64) -> Result<String, String>

Obtains the name of a disjunctive constraint.

§Arguments
  • djcidx_ Index of a disjunctive constraint.
§Returns
  • name Returns the required name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdjcname

source

pub fn get_djc_name_len(&self, djcidx_: i64) -> Result<i32, String>

Obtains the length of the name of a disjunctive constraint.

§Arguments
  • djcidx_ Index of a disjunctive constraint.
§Returns
  • len Returns the length of the indicated name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdjcnamelen

source

pub fn get_djc_num_afe(&mut self, djcidx_: i64) -> Result<i64, String>

Obtains the number of affine expressions in the disjunctive constraint.

§Arguments
  • djcidx_ Index of the disjunctive constraint.
§Returns
  • numafe Number of affine expressions in the disjunctive constraint.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdjcnumafe

source

pub fn get_djc_num_afe_tot(&mut self) -> Result<i64, String>

Obtains the number of affine expressions in all disjunctive constraints.

§Returns
  • numafetot Number of affine expressions in all disjunctive constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdjcnumafetot

source

pub fn get_djc_num_domain(&mut self, djcidx_: i64) -> Result<i64, String>

Obtains the number of domains in the disjunctive constraint.

§Arguments
  • djcidx_ Index of the disjunctive constraint.
§Returns
  • numdomain Number of domains in the disjunctive constraint.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdjcnumdomain

source

pub fn get_djc_num_domain_tot(&mut self) -> Result<i64, String>

Obtains the number of domains in all disjunctive constraints.

§Returns
  • numdomaintot Number of domains in all disjunctive constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdjcnumdomaintot

source

pub fn get_djc_num_term(&mut self, djcidx_: i64) -> Result<i64, String>

Obtains the number terms in the disjunctive constraint.

§Arguments
  • djcidx_ Index of the disjunctive constraint.
§Returns
  • numterm Number of terms in the disjunctive constraint.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdjcnumterm

source

pub fn get_djc_num_term_tot(&mut self) -> Result<i64, String>

Obtains the number of terms in all disjunctive constraints.

§Returns
  • numtermtot Total number of terms in all disjunctive constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdjcnumtermtot

source

pub fn get_djcs( &self, domidxlist_: &mut [i64], afeidxlist_: &mut [i64], b_: &mut [f64], termsizelist_: &mut [i64], numterms_: &mut [i64] ) -> Result<(), String>

Obtains full data of all disjunctive constraints.

§Arguments
  • domidxlist_ The concatenation of index lists of domains appearing in all disjunctive constraints.
  • afeidxlist_ The concatenation of index lists of affine expressions appearing in all disjunctive constraints.
  • b_ The concatenation of vectors b appearing in all disjunctive constraints.
  • termsizelist_ The concatenation of lists of term sizes appearing in all disjunctive constraints.
  • numterms_ The number of terms in each of the disjunctive constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdjcs

source

pub fn get_djc_term_size_list( &self, djcidx_: i64, termsizelist_: &mut [i64] ) -> Result<(), String>

Obtains the list of term sizes in a disjunctive constraint.

§Arguments
  • djcidx_ Index of the disjunctive constraint.
  • termsizelist_ List of term sizes.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdjctermsizelist

source

pub fn get_domain_n(&self, domidx_: i64) -> Result<i64, String>

Obtains the dimension of the domain.

§Arguments
  • domidx_ Index of the domain.
§Returns
  • n Dimension of the domain.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdomainn

source

pub fn get_domain_name(&self, domidx_: i64) -> Result<String, String>

Obtains the name of a domain.

§Arguments
  • domidx_ Index of a domain.
§Returns
  • name Returns the required name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdomainname

source

pub fn get_domain_name_len(&self, domidx_: i64) -> Result<i32, String>

Obtains the length of the name of a domain.

§Arguments
  • domidx_ Index of a domain.
§Returns
  • len Returns the length of the indicated name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdomainnamelen

source

pub fn get_domain_type(&self, domidx_: i64) -> Result<i32, String>

Returns the type of the domain.

§Arguments
  • domidx_ Index of the domain.
§Returns
  • domtype The type of the domain.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdomaintype

source

pub fn get_dou_inf(&self, whichdinf_: i32) -> Result<f64, String>

Obtains a double information item.

§Arguments
  • whichdinf_ Specifies a double information item.

    See Dinfitem

§Returns
  • dvalue The value of the required double information item.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdouinf

Examples found in repository?
examples/parameters.rs (line 47)
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
fn main() -> Result<(),String> {
    let mut task = Task::new().unwrap();
    println!("Test MOSEK parameter get/set functions");

    // Set log level (integer parameter)
    task.put_int_param(Iparam::LOG, 1)?;
    // Select interior-point optimizer... (integer parameter)
    task.put_int_param(Iparam::OPTIMIZER, Optimizertype::INTPNT)?;
    // ... without basis identification (integer parameter)
    task.put_int_param(Iparam::INTPNT_BASIS,Basindtype::NEVER)?;
    // Set relative gap tolerance (double parameter)
    task.put_dou_param(Dparam::INTPNT_CO_TOL_REL_GAP, 1.0e-7)?;

    // The same using explicit string names
    task.put_param("MSK_DPAR_INTPNT_CO_TOL_REL_GAP", "1.0e-7")?;
    task.put_na_dou_param("MSK_DPAR_INTPNT_CO_TOL_REL_GAP",  1.0e-7 )?;

    // Incorrect value

    if let Err(_) = task.put_dou_param(Dparam::INTPNT_CO_TOL_REL_GAP, -1.0) {
        println!("Wrong parameter value");
    }


    let param = task.get_dou_param(Dparam::INTPNT_CO_TOL_REL_GAP)?;
    println!("Current value for parameter intpnt_co_tol_rel_gap = $param");

    // Define and solve an optimization problem here
    // optimize(task,)
    // After optimization:

    println!("Get MOSEK information items");

    let tm = task.get_dou_inf(Dinfitem::OPTIMIZER_TIME)?;
    let iter = task.get_int_inf(Iinfitem::INTPNT_ITER)?;

    println!("Time: {}",tm);
    println!("Iterations: {}",iter);
    Ok(())
}
More examples
Hide additional examples
examples/parallel.rs (line 76)
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
fn parallel(files : Vec<FileOrText>) -> Result<(),String> {
    // Create an example list of tasks to optimize
    let mut tasks : Vec<(String,Task)> = files.iter().filter_map(|fname| {
        let mut t = Task::new().unwrap();
        match fname {
            FileOrText::File(fname) => {
                if let Err(_) = t.read_data(fname.as_str()) { None }
                else {
                    t.put_int_param(mosek::Iparam::NUM_THREADS, 2).unwrap();
                    Some((fname.as_str().to_string(),t))
                }
            },
            FileOrText::Text(data) => {
                if let Err(_) = t.read_ptf_string(data.as_str()) { None }
                else {
                    t.put_int_param(mosek::Iparam::NUM_THREADS, 2).unwrap();
                    Some(("-".to_string(),t))
                }
            }
        }
    }).collect();

    let mut res = vec![0i32; tasks.len()];
    let mut trm = vec![0i32; tasks.len()];
    {
        let taskrs : Vec<& mut Task> = tasks.iter_mut().map(|(_a,b)| b).collect();

        // Size of thread pool available for all tasks
        let threadpoolsize : i32 = 6;

        // Optimize all the given tasks in parallel
        mosek::optimize_batch(false,          // No race
                              -1.0,           // No time limit
                              threadpoolsize,
                              taskrs.as_slice(),          // Array of tasks to optimize
                              trm.as_mut_slice(),
                              res.as_mut_slice())?;
    }

    for (resi,trmi,(fname,ti)) in izip!(res,trm,tasks.iter()) {
        println!("Task  {}  res {}   trm {}   obj_val  {}  time {}",
                 fname,
                 resi,
                 trmi,
                 ti.get_dou_inf(mosek::Dinfitem::INTPNT_PRIMAL_OBJ)?,
                 ti.get_dou_inf(mosek::Dinfitem::OPTIMIZER_TIME)?);
    }
    Ok(())
}
source

pub fn get_dou_param(&self, param_: i32) -> Result<f64, String>

Obtains a double parameter.

§Arguments
  • param_ Which parameter.

    See Dparam

§Returns
  • parvalue Parameter value.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdouparam

Examples found in repository?
examples/parameters.rs (line 38)
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
fn main() -> Result<(),String> {
    let mut task = Task::new().unwrap();
    println!("Test MOSEK parameter get/set functions");

    // Set log level (integer parameter)
    task.put_int_param(Iparam::LOG, 1)?;
    // Select interior-point optimizer... (integer parameter)
    task.put_int_param(Iparam::OPTIMIZER, Optimizertype::INTPNT)?;
    // ... without basis identification (integer parameter)
    task.put_int_param(Iparam::INTPNT_BASIS,Basindtype::NEVER)?;
    // Set relative gap tolerance (double parameter)
    task.put_dou_param(Dparam::INTPNT_CO_TOL_REL_GAP, 1.0e-7)?;

    // The same using explicit string names
    task.put_param("MSK_DPAR_INTPNT_CO_TOL_REL_GAP", "1.0e-7")?;
    task.put_na_dou_param("MSK_DPAR_INTPNT_CO_TOL_REL_GAP",  1.0e-7 )?;

    // Incorrect value

    if let Err(_) = task.put_dou_param(Dparam::INTPNT_CO_TOL_REL_GAP, -1.0) {
        println!("Wrong parameter value");
    }


    let param = task.get_dou_param(Dparam::INTPNT_CO_TOL_REL_GAP)?;
    println!("Current value for parameter intpnt_co_tol_rel_gap = $param");

    // Define and solve an optimization problem here
    // optimize(task,)
    // After optimization:

    println!("Get MOSEK information items");

    let tm = task.get_dou_inf(Dinfitem::OPTIMIZER_TIME)?;
    let iter = task.get_int_inf(Iinfitem::INTPNT_ITER)?;

    println!("Time: {}",tm);
    println!("Iterations: {}",iter);
    Ok(())
}
source

pub fn get_dual_obj( &self, whichsol_: i32, dualobj_: &mut f64 ) -> Result<(), String>

Computes the dual objective value associated with the solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • dualobj_ Objective value corresponding to the dual solution.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdualobj

source

pub fn get_dual_solution_norms( &self, whichsol_: i32, nrmy_: &mut f64, nrmslc_: &mut f64, nrmsuc_: &mut f64, nrmslx_: &mut f64, nrmsux_: &mut f64, nrmsnx_: &mut f64, nrmbars_: &mut f64 ) -> Result<(), String>

Compute norms of the dual solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • nrmy_ The norm of the y vector.

  • nrmslc_ The norm of the slc vector.

  • nrmsuc_ The norm of the suc vector.

  • nrmslx_ The norm of the slx vector.

  • nrmsux_ The norm of the sux vector.

  • nrmsnx_ The norm of the snx vector.

  • nrmbars_ The norm of the bars vector.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdualsolutionnorms

source

pub fn get_dviol_acc( &self, whichsol_: i32, accidxlist_: &[i64], viol_: &mut [f64] ) -> Result<(), String>

Computes the violation of the dual solution for set of affine conic constraints.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • accidxlist_ An array of indexes of conic constraints.

  • viol_ List of violations corresponding to sub.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdviolacc

source

pub fn get_dviol_barvar( &self, whichsol_: i32, sub_: &[i32], viol_: &mut [f64] ) -> Result<(), String>

Computes the violation of dual solution for a set of semidefinite variables.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • sub_ An array of indexes of barx variables.

  • viol_ List of violations corresponding to sub.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdviolbarvar

source

pub fn get_dviol_con( &self, whichsol_: i32, sub_: &[i32], viol_: &mut [f64] ) -> Result<(), String>

Computes the violation of a dual solution associated with a set of constraints.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • sub_ An array of indexes of constraints.

  • viol_ List of violations corresponding to sub.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdviolcon

source

pub fn get_dviol_cones( &self, whichsol_: i32, sub_: &[i32], viol_: &mut [f64] ) -> Result<(), String>

Computes the violation of a solution for set of dual conic constraints.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • sub_ An array of indexes of conic constraints.

  • viol_ List of violations corresponding to sub.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdviolcones

source

pub fn get_dviol_var( &self, whichsol_: i32, sub_: &[i32], viol_: &mut [f64] ) -> Result<(), String>

Computes the violation of a dual solution associated with a set of scalar variables.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • sub_ An array of indexes of x variables.

  • viol_ List of violations corresponding to sub.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getdviolvar

source

pub fn get_inf_index( &self, inftype_: i32, infname_: &str, infindex_: &mut i32 ) -> Result<(), String>

Obtains the index of a named information item.

§Arguments
  • inftype_ Type of the information item.

    See Inftype

  • infname_ Name of the information item.

  • infindex_ The item index.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getinfindex

source

pub fn get_inf_max( &self, inftype_: i32, infmax_: &mut [i32] ) -> Result<(), String>

Obtains the maximum index of an information item of a given type.

§Arguments
  • inftype_ Type of the information item.

    See Inftype

  • infmax_ The maximum index (plus 1) requested.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getinfmax

source

pub fn get_inf_name( &self, inftype_: i32, whichinf_: i32 ) -> Result<String, String>

Obtains the name of an information item.

§Arguments
  • inftype_ Type of the information item.

    See Inftype

  • whichinf_ An information item.

§Returns
  • infname Name of the information item.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getinfname

source

pub fn get_int_inf(&self, whichiinf_: i32) -> Result<i32, String>

Obtains an integer information item.

§Arguments
  • whichiinf_ Specifies an integer information item.

    See Iinfitem

§Returns
  • ivalue The value of the required integer information item.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getintinf

Examples found in repository?
examples/parameters.rs (line 48)
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
fn main() -> Result<(),String> {
    let mut task = Task::new().unwrap();
    println!("Test MOSEK parameter get/set functions");

    // Set log level (integer parameter)
    task.put_int_param(Iparam::LOG, 1)?;
    // Select interior-point optimizer... (integer parameter)
    task.put_int_param(Iparam::OPTIMIZER, Optimizertype::INTPNT)?;
    // ... without basis identification (integer parameter)
    task.put_int_param(Iparam::INTPNT_BASIS,Basindtype::NEVER)?;
    // Set relative gap tolerance (double parameter)
    task.put_dou_param(Dparam::INTPNT_CO_TOL_REL_GAP, 1.0e-7)?;

    // The same using explicit string names
    task.put_param("MSK_DPAR_INTPNT_CO_TOL_REL_GAP", "1.0e-7")?;
    task.put_na_dou_param("MSK_DPAR_INTPNT_CO_TOL_REL_GAP",  1.0e-7 )?;

    // Incorrect value

    if let Err(_) = task.put_dou_param(Dparam::INTPNT_CO_TOL_REL_GAP, -1.0) {
        println!("Wrong parameter value");
    }


    let param = task.get_dou_param(Dparam::INTPNT_CO_TOL_REL_GAP)?;
    println!("Current value for parameter intpnt_co_tol_rel_gap = $param");

    // Define and solve an optimization problem here
    // optimize(task,)
    // After optimization:

    println!("Get MOSEK information items");

    let tm = task.get_dou_inf(Dinfitem::OPTIMIZER_TIME)?;
    let iter = task.get_int_inf(Iinfitem::INTPNT_ITER)?;

    println!("Time: {}",tm);
    println!("Iterations: {}",iter);
    Ok(())
}
source

pub fn get_int_param(&self, param_: i32) -> Result<i32, String>

Obtains an integer parameter.

§Arguments
  • param_ Which parameter.

    See Iparam

§Returns
  • parvalue Parameter value.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getintparam

source

pub fn get_len_barvar_j(&self, j_: i32) -> Result<i64, String>

Obtains the length of one semidefinite variable.

§Arguments
  • j_ Index of the semidefinite variable whose length if requested.
§Returns
  • lenbarvarj Number of scalar elements in the lower triangular part of the semidefinite variable.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getlenbarvarj

source

pub fn get_lint_inf(&self, whichliinf_: i32) -> Result<i64, String>

Obtains a long integer information item.

§Arguments
  • whichliinf_ Specifies a long information item.

    See Liinfitem

§Returns
  • ivalue The value of the required long integer information item.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getlintinf

source

pub fn get_max_name_len(&self, maxlen_: &mut i32) -> Result<(), String>

Obtains the maximum length (not including terminating zero character) of any objective, constraint, variable, domain or cone name.

§Arguments
  • maxlen_ The maximum length of any name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getmaxnamelen

source

pub fn get_max_num_a_nz(&self) -> Result<i64, String>

Obtains number of preallocated non-zeros in the linear constraint matrix.

§Returns
  • maxnumanz Number of preallocated non-zero linear matrix elements.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getmaxnumanz64

source

pub fn get_max_num_barvar(&self) -> Result<i32, String>

Obtains maximum number of symmetric matrix variables for which space is currently preallocated.

§Returns
  • maxnumbarvar Maximum number of symmetric matrix variables for which space is currently preallocated.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getmaxnumbarvar

source

pub fn get_max_num_con(&self, maxnumcon_: &mut i32) -> Result<(), String>

Obtains the number of preallocated constraints in the optimization task.

§Arguments
  • maxnumcon_ Number of preallocated constraints in the optimization task.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getmaxnumcon

source

pub fn get_max_num_cone(&self, maxnumcone_: &mut i32) -> Result<(), String>

Obtains the number of preallocated cones in the optimization task.

§Arguments
  • maxnumcone_ Number of preallocated conic constraints in the optimization task.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getmaxnumcone

source

pub fn get_max_num_q_nz(&self, maxnumqnz_: &mut i64) -> Result<(), String>

Obtains the number of preallocated non-zeros for all quadratic terms in objective and constraints.

§Arguments
  • maxnumqnz_ Number of non-zero elements preallocated in quadratic coefficient matrices.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getmaxnumqnz64

source

pub fn get_max_num_var(&self, maxnumvar_: &mut i32) -> Result<(), String>

Obtains the maximum number variables allowed.

§Arguments
  • maxnumvar_ Number of preallocated variables in the optimization task.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getmaxnumvar

source

pub fn get_mem_usage( &self, meminuse_: &mut i64, maxmemuse_: &mut i64 ) -> Result<(), String>

Obtains information about the amount of memory used by a task.

§Arguments
  • meminuse_ Amount of memory currently used by the task.
  • maxmemuse_ Maximum amount of memory used by the task until now.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getmemusagetask

source

pub fn get_mio_num_threads(&self) -> Result<i32, String>

Obtains the number of threads used by the mixed integer optimizer.

§Returns
  • numthreads The number of threads.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getmionumthreads

source

pub fn get_na_dou_inf( &self, infitemname_: &str, dvalue_: &mut f64 ) -> Result<(), String>

Obtains a named double information item.

§Arguments
  • infitemname_ The name of a double information item.
  • dvalue_ The value of the required double information item.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnadouinf

source

pub fn get_na_dou_param( &self, paramname_: &str, parvalue_: &mut f64 ) -> Result<(), String>

Obtains a double parameter.

§Arguments
  • paramname_ Name of a parameter.
  • parvalue_ Parameter value.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnadouparam

source

pub fn get_na_int_inf( &self, infitemname_: &str, ivalue_: &mut i32 ) -> Result<(), String>

Obtains a named integer information item.

§Arguments
  • infitemname_ The name of an integer information item.
  • ivalue_ The value of the required integer information item.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnaintinf

source

pub fn get_na_int_param( &self, paramname_: &str, parvalue_: &mut i32 ) -> Result<(), String>

Obtains an integer parameter.

§Arguments
  • paramname_ Name of a parameter.
  • parvalue_ Parameter value.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnaintparam

source

pub fn get_na_str_param( &self, paramname_: &str, sizeparamname_: i32, len_: &mut i32 ) -> Result<String, String>

Obtains a string parameter.

§Arguments
  • paramname_ Name of a parameter.
  • sizeparamname_ Size of the name buffer.
  • len_ Returns the length of the parameter value.
§Returns
  • parvalue Parameter value.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnastrparam

source

pub fn get_num_acc(&mut self) -> Result<i64, String>

Obtains the number of affine conic constraints.

§Returns
  • num The number of affine conic constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnumacc

Examples found in repository?
examples/portfolio_2_frontier.rs (line 80)
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
fn portfolio(n : i32,
             mu : &[f64],
             GT : &[f64],
             x0  : &[f64],
             alphas : &[f64],
             w : f64) -> Result<Vec<(f64,f64)>,String> {
    let k = (GT.len() / n as usize) as i32;
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(t) => t,
        None => return Err("Failed to create task".to_string()),
    };
    //task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    task.append_vars(n+1)?;
    task.append_cons(1)?;

    /* Objective */
    task.put_obj_sense(Objsense::MAXIMIZE)?;

    let x : Vec<i32> = (0i32..n).collect();
    let s = n;

    /* Total budget */
    let total_budget = w + x0.iter().sum::<f64>();

    /* Total budget constraint - set bounds l^c = u^c */
    task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
    task.put_con_name(0i32,"budget")?;
    task.put_c_slice(0,n,mu)?;

    /* x variables. */
    for (j,xj) in x.iter().enumerate() {
        /* Coefficients in the first row of A */
        task.put_aij(0, *xj, 1.0)?;
        /* No short-selling - x^l = 0, x^u = inf */
        task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
        task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
    }
    task.put_var_name(s, "s")?;
    task.put_var_bound(s, mosek::Boundkey::FR, 0.0, 0.0)?;

    // risk bound
    // (s,0.5,GT * x) in Q_r
    {
        let acci = task.get_num_acc()?;
        let afei = task.get_num_afe()?;

        task.append_afes(k as i64 + 2)?;
        let dom = task.append_r_quadratic_cone_domain(k as i64+2)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 2].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_f_entry(afei,s,1.0)?;
        task.put_afe_g(afei+1,0.5)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 2, j as i32, *v)?;
        }
    }

    let frontier : Vec<(f64,f64)> = alphas.iter().filter_map(|alpha| {
        /* Sets the objective function coefficient for s. */
        if      let Err(_) = task.put_c_j(s, - *alpha) { None }
        else if let Err(_) = task.optimize() { None }
        else if let Err(_) = task.write_data(format!("portfolio_2_frontier-{}.ptf",alpha).as_str()) { None }
        else if let Ok(solsta) = task.get_sol_sta(Soltype::ITR) {
            // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
            match solsta {
                Solsta::OPTIMAL => {
                    let mut xx = vec![0.0; n as usize+1];
                    if let Err(_) = task.get_xx(Soltype::ITR,xx.as_mut_slice()) { None }
                    else {
                        Some((*alpha,mu.iter().zip(xx.iter()).map(|(m,x)| m * x).sum::<f64>()))
                    }
                }
                _ => None
            }
        }
        else {
            None
        }
    }).collect();

    Ok(frontier)
}
More examples
Hide additional examples
examples/portfolio_5_card.rs (line 134)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
source

pub fn get_num_afe(&mut self) -> Result<i64, String>

Obtains the number of affine expressions.

§Returns
  • numafe Number of affine expressions.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnumafe

Examples found in repository?
examples/portfolio_2_frontier.rs (line 81)
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
fn portfolio(n : i32,
             mu : &[f64],
             GT : &[f64],
             x0  : &[f64],
             alphas : &[f64],
             w : f64) -> Result<Vec<(f64,f64)>,String> {
    let k = (GT.len() / n as usize) as i32;
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(t) => t,
        None => return Err("Failed to create task".to_string()),
    };
    //task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    task.append_vars(n+1)?;
    task.append_cons(1)?;

    /* Objective */
    task.put_obj_sense(Objsense::MAXIMIZE)?;

    let x : Vec<i32> = (0i32..n).collect();
    let s = n;

    /* Total budget */
    let total_budget = w + x0.iter().sum::<f64>();

    /* Total budget constraint - set bounds l^c = u^c */
    task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
    task.put_con_name(0i32,"budget")?;
    task.put_c_slice(0,n,mu)?;

    /* x variables. */
    for (j,xj) in x.iter().enumerate() {
        /* Coefficients in the first row of A */
        task.put_aij(0, *xj, 1.0)?;
        /* No short-selling - x^l = 0, x^u = inf */
        task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
        task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
    }
    task.put_var_name(s, "s")?;
    task.put_var_bound(s, mosek::Boundkey::FR, 0.0, 0.0)?;

    // risk bound
    // (s,0.5,GT * x) in Q_r
    {
        let acci = task.get_num_acc()?;
        let afei = task.get_num_afe()?;

        task.append_afes(k as i64 + 2)?;
        let dom = task.append_r_quadratic_cone_domain(k as i64+2)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 2].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_f_entry(afei,s,1.0)?;
        task.put_afe_g(afei+1,0.5)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 2, j as i32, *v)?;
        }
    }

    let frontier : Vec<(f64,f64)> = alphas.iter().filter_map(|alpha| {
        /* Sets the objective function coefficient for s. */
        if      let Err(_) = task.put_c_j(s, - *alpha) { None }
        else if let Err(_) = task.optimize() { None }
        else if let Err(_) = task.write_data(format!("portfolio_2_frontier-{}.ptf",alpha).as_str()) { None }
        else if let Ok(solsta) = task.get_sol_sta(Soltype::ITR) {
            // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
            match solsta {
                Solsta::OPTIMAL => {
                    let mut xx = vec![0.0; n as usize+1];
                    if let Err(_) = task.get_xx(Soltype::ITR,xx.as_mut_slice()) { None }
                    else {
                        Some((*alpha,mu.iter().zip(xx.iter()).map(|(m,x)| m * x).sum::<f64>()))
                    }
                }
                _ => None
            }
        }
        else {
            None
        }
    }).collect();

    Ok(frontier)
}
More examples
Hide additional examples
examples/portfolio_5_card.rs (line 133)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
source

pub fn get_num_a_nz(&self) -> Result<i32, String>

Obtains the number of non-zeros in the coefficient matrix.

§Returns
  • numanz Number of non-zero elements in the linear constraint matrix.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnumanz

source

pub fn get_num_a_nz_64(&self) -> Result<i64, String>

Obtains the number of non-zeros in the coefficient matrix.

§Returns
  • numanz Number of non-zero elements in the linear constraint matrix.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnumanz64

source

pub fn get_num_bara_block_triplets(&self) -> Result<i64, String>

Obtains an upper bound on the number of scalar elements in the block triplet form of bara.

§Returns
  • num An upper bound on the number of elements in the block triplet form of bara.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnumbarablocktriplets

source

pub fn get_num_bara_nz(&self) -> Result<i64, String>

Get the number of nonzero elements in barA.

§Returns
  • nz The number of nonzero block elements in barA.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnumbaranz

source

pub fn get_num_barc_block_triplets(&self) -> Result<i64, String>

Obtains an upper bound on the number of elements in the block triplet form of barc.

§Returns
  • num An upper bound on the number of elements in the block triplet form of barc.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnumbarcblocktriplets

source

pub fn get_num_barc_nz(&self) -> Result<i64, String>

Obtains the number of nonzero elements in barc.

§Returns
  • nz The number of nonzero elements in barc.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnumbarcnz

source

pub fn get_num_barvar(&self) -> Result<i32, String>

Obtains the number of semidefinite variables.

§Returns
  • numbarvar Number of semidefinite variables in the problem.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnumbarvar

source

pub fn get_num_con(&self) -> Result<i32, String>

Obtains the number of constraints.

§Returns
  • numcon Number of constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnumcon

Examples found in repository?
examples/reoptimization.rs (line 138)
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
fn main() -> Result<(),String> {

    let numcon = 3;
    let numvar = 3;
    let c = &[1.5, 2.5, 3.0 ];
    let bkc = &[ Boundkey::UP,
                 Boundkey::UP,
                 Boundkey::UP ];
    let blc = &[ -INF,
                 -INF,
                 -INF ];
    let buc = &[ 100000.0,
                 50000.0,
                 60000.0 ];
    let bkx = &[ Boundkey::LO,
                 Boundkey::LO,
                 Boundkey::LO
                             ];
    let blx = &[ 0.0, 0.0, 0.0 ];
    let bux = &[ INF,
                 INF,
                 INF ];

    let asub = &[
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ] ];

    let aval = &[
        &[ 2.0, 3.0, 2.0 ],
        &[ 4.0, 2.0, 3.0 ],
        &[ 3.0, 3.0, 2.0 ] ];


    let mut task = Task::new().unwrap();
    /* Append the constraints. */
    task.append_cons(numcon)?;

    /* Append the variables. */
    task.append_vars(numvar)?;

    /* Put C. */
    for (j,&cj) in (0..numvar).zip(c.iter()) {
        task.put_c_j(j,cj)?;
    }
    /* Put constraint bounds. */
    for (i,&bki,&bli,&bui) in izip!(0..numcon,bkc,blc,buc) {
        task.put_con_bound(i, bki, bli, bui)?;
    }

    /* Put variable bounds. */
    for (j,&bki,&bli,&bui) in izip!(0..numvar,bkx,blx,bux) {
        task.put_var_bound(j, bki, bli, bui)?;
    }

    /* Put A. */
    if numcon > 0 {
        for (j,&asubj,&avalj) in izip!(0..numvar,asub,aval) {
            task.put_a_col(j,
                           asubj,
                           avalj)?;
        }
    }

    /* A maximization problem */
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    /* Solve the problem */
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /****************** Make a change to the A matrix ******************/
    task.put_aij(0, 0, 3.0)?;
    let _trm = task.optimize()?;
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /***************** Add a new variable ******************************/
    /* Get index of new variable. */

    let varidx = task.get_num_var()?;

    /* Append a new variable x_3 to the problem */
    task.append_vars(1)?;
    let numvar = numvar + 1;

    /* Set bounds on new varaible */
    task.put_var_bound(varidx, Boundkey::LO, 0.0, INF)?;

    /* Change objective */
    task.put_c_j(varidx, 1.0)?;

    /* Put new values in the A matrix */
    let acolsub = &[0i32, 2];
    let acolval = &[4.0, 1.0];

    task.put_a_col(varidx, /* column index */
                   acolsub,
                   acolval)?;

    /* Change optimizer to simplex free and reoptimize */
    task.put_int_param(mosek::Iparam::OPTIMIZER, mosek::Optimizertype::FREE_SIMPLEX)?;
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Add a new constraint ***************************/
    /* Get index of new constraint. */
    let conidx = task.get_num_con()?;

    /* Append a new constraint */
    task.append_cons(1)?;
    let numcon = numcon + 1;

    /* Set bounds on new constraint */
    task.put_con_bound(conidx,
                       Boundkey::UP,
                       -INF,
                       30000.0)?;

    /* Put new values in the A matrix */
    let arowsub = &[0i32,   1,   2,   3  ];
    let arowval = &[1.0, 2.0, 1.0, 1.0 ];

    task.put_a_row(conidx, /* row index */
                   arowsub,
                   arowval)?;

    let _trm = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Change constraint bounds ********************/
    let newbkc = &[Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP];
    let newblc = &[-INF,
                   -INF,
                   -INF,
                   -INF];
    let newbuc = &[ 80000.0, 40000.0, 50000.0, 22000.0 ];

    task.put_con_bound_slice(0, numcon, newbkc, newblc, newbuc)?;

    let _ = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    Ok(())
}
More examples
Hide additional examples
examples/portfolio_5_card.rs (line 93)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
source

pub fn get_num_cone(&self) -> Result<i32, String>

Obtains the number of cones.

§Returns
  • numcone Number of conic constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnumcone

source

pub fn get_num_cone_mem(&self, k_: i32, nummem_: &mut i32) -> Result<(), String>

Obtains the number of members in a cone.

§Arguments
  • k_ Index of the cone.
  • nummem_ Number of member variables in the cone.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnumconemem

source

pub fn get_num_djc(&mut self) -> Result<i64, String>

Obtains the number of disjunctive constraints.

§Returns
  • num The number of disjunctive constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnumdjc

source

pub fn get_num_domain(&mut self) -> Result<i64, String>

Obtain the number of domains defined.

§Returns
  • numdomain Number of domains in the task.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnumdomain

source

pub fn get_num_int_var(&self) -> Result<i32, String>

Obtains the number of integer-constrained variables.

§Returns
  • numintvar Number of integer variables.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnumintvar

Examples found in repository?
examples/concurrent1.rs (line 115)
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
fn concurrent1(data : FileOrText, timelimit : Option<String>) -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
        };

    match data {
        FileOrText::File(fname) => task.read_data(fname.as_str())?,
        FileOrText::Text(text)  => task.read_ptf_string(text.as_str())?
    }
    if let Some(timelimit) = timelimit {
        task.put_dou_param(mosek::Dparam::OPTIMIZER_MAX_TIME, timelimit.parse().unwrap())?;
    }

    let numintvar = task.get_num_int_var()?;

    let r = if numintvar == 0 {
        let optimizers = &[mosek::Optimizertype::CONIC,
                           mosek::Optimizertype::DUAL_SIMPLEX,
                           mosek::Optimizertype::PRIMAL_SIMPLEX];
        optimize_concurrent(& mut task, optimizers)
    }
    else {
        let seeds = &[ 42, 13, 71749373 ];
        optimize_concurrent_mio(& mut task, seeds)
    };


    let sense = task.get_obj_sense()?;
    // Pick the feasible result. For non-integer problems all
    // solutions should be the same if more than one is returned, but
    // for integer problems tasks may have hit the time limit and
    // returned non-optimal solutions.

    let n = r.len();

    if n == 0 {
        println!("All optimizers failed.");
    }
    else if numintvar > 0 {
        let (ii,_,tasks) = split3vec(r);

        let pobjs : Vec<(usize,f64)> =
            ii.iter().zip(tasks.iter()).enumerate()
            .filter_map(|(k,(_i,t))|
                match (*t).solution_def(Soltype::ITG) {
                    Ok(true) => match t.get_sol_sta(Soltype::ITG).unwrap() {
                        Solsta::PRIM_FEAS|Solsta::INTEGER_OPTIMAL => Some((k,t.get_primal_obj(Soltype::ITG).unwrap())),
                        _ => None
                    },
                    _ => None
                })
            .collect();

        let &(besti,bestobj) = pobjs.iter()
            .max_by(|(_,o1),(_,o2)|
                    match sense {
                        Objsense::MAXIMIZE => if o1 < o2 {Ordering::Less} else if o2 < o1 {Ordering::Greater} else {Ordering::Equal},
                        _ => if o1 > o2 {Ordering::Less} else if o2 > o1 {Ordering::Greater} else {Ordering::Equal}
                    }).unwrap();

        drop_except(tasks,besti).unwrap()
            .with_stream_callback(
                Streamtype::LOG, 
                &mut |msg| print!("{}",msg),
                |t| { 
                    t.optimizer_summary(mosek::Streamtype::LOG)?;
                    t.solution_summary(mosek::Streamtype::LOG)?;
                    Ok::<(),String>(())
                })?;

        println!("{} optimizers succeeded:",pobjs.len());
        for &(k,v) in pobjs.iter() {
            println!("Optimizer with seed #{} produced result : {:.5e}",ii[k],v);
        }

        println!("\tBest solution is #{}: {:.5e}",ii[besti],bestobj);
    }
    else {
        let (ii,_,tasks) = split3vec(r);

        let pobjs : Vec<(usize,f64)> =
            tasks.iter().enumerate()
            .filter_map(|(k,t)|
                        match t.get_sol_sta(Soltype::BAS) {
                            Ok(Solsta::PRIM_FEAS)|Ok(Solsta::OPTIMAL) => Some((k,t.get_primal_obj(Soltype::BAS).unwrap())),
                            _ => None
                        }.or_else(|| match t.get_sol_sta(Soltype::ITR) {
                            Ok(Solsta::PRIM_FEAS)|Ok(Solsta::OPTIMAL) => Some((k,t.get_primal_obj(Soltype::ITR).unwrap())),
                            _ => None
                        }))
            .collect();

        let &(besti,bestobj) = pobjs.iter()
            .max_by(|(_,o1),(_,o2)|
                    match sense {
                        Objsense::MAXIMIZE => if o1 < o2 {Ordering::Less} else if o2 < o1 {Ordering::Greater} else {Ordering::Equal},
                        _ => if o1 > o2 {Ordering::Less} else if o2 > o1 {Ordering::Greater} else {Ordering::Equal}
                    }).unwrap();

        drop_except(tasks,besti).unwrap()
            .with_stream_callback(
                Streamtype::LOG, 
                &mut|msg| print!("{}",msg),
                |t| {
                    t.optimizer_summary(mosek::Streamtype::LOG)?;
                    t.solution_summary(mosek::Streamtype::LOG)?;
                    Ok::<(),String>(())
                })?;

        println!("{} optimizers succeeded:",pobjs.len());
        for &(k,v) in pobjs.iter() {
            println!("Optimizer with seed #{} produced result : {:.5e}",ii[k],v);
        }

        println!("\tBest solution is #{}: {:.5e}",ii[besti],bestobj);
    }


    Result::Ok(())
}
source

pub fn get_num_param( &self, partype_: i32, numparam_: &mut i32 ) -> Result<(), String>

Obtains the number of parameters of a given type.

§Arguments
  • partype_ Parameter type.

    See Parametertype

  • numparam_ Returns the number of parameters of the requested type.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnumparam

source

pub fn get_num_q_con_k_nz(&self, k_: i32) -> Result<i64, String>

Obtains the number of non-zero quadratic terms in a constraint.

§Arguments
  • k_ Index of the constraint for which the number quadratic terms should be obtained.
§Returns
  • numqcnz Number of quadratic terms.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnumqconknz64

source

pub fn get_num_q_obj_nz(&self) -> Result<i64, String>

Obtains the number of non-zero quadratic terms in the objective.

§Returns
  • numqonz Number of non-zero elements in the quadratic objective terms.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnumqobjnz64

source

pub fn get_num_sym_mat(&self, num_: &mut i64) -> Result<(), String>

Obtains the number of symmetric matrices stored.

§Arguments
  • num_ The number of symmetric sparse matrices.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnumsymmat

source

pub fn get_num_var(&self) -> Result<i32, String>

Obtains the number of variables.

§Returns
  • numvar Number of variables.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getnumvar

Examples found in repository?
examples/reoptimization.rs (line 84)
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
fn main() -> Result<(),String> {

    let numcon = 3;
    let numvar = 3;
    let c = &[1.5, 2.5, 3.0 ];
    let bkc = &[ Boundkey::UP,
                 Boundkey::UP,
                 Boundkey::UP ];
    let blc = &[ -INF,
                 -INF,
                 -INF ];
    let buc = &[ 100000.0,
                 50000.0,
                 60000.0 ];
    let bkx = &[ Boundkey::LO,
                 Boundkey::LO,
                 Boundkey::LO
                             ];
    let blx = &[ 0.0, 0.0, 0.0 ];
    let bux = &[ INF,
                 INF,
                 INF ];

    let asub = &[
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ] ];

    let aval = &[
        &[ 2.0, 3.0, 2.0 ],
        &[ 4.0, 2.0, 3.0 ],
        &[ 3.0, 3.0, 2.0 ] ];


    let mut task = Task::new().unwrap();
    /* Append the constraints. */
    task.append_cons(numcon)?;

    /* Append the variables. */
    task.append_vars(numvar)?;

    /* Put C. */
    for (j,&cj) in (0..numvar).zip(c.iter()) {
        task.put_c_j(j,cj)?;
    }
    /* Put constraint bounds. */
    for (i,&bki,&bli,&bui) in izip!(0..numcon,bkc,blc,buc) {
        task.put_con_bound(i, bki, bli, bui)?;
    }

    /* Put variable bounds. */
    for (j,&bki,&bli,&bui) in izip!(0..numvar,bkx,blx,bux) {
        task.put_var_bound(j, bki, bli, bui)?;
    }

    /* Put A. */
    if numcon > 0 {
        for (j,&asubj,&avalj) in izip!(0..numvar,asub,aval) {
            task.put_a_col(j,
                           asubj,
                           avalj)?;
        }
    }

    /* A maximization problem */
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    /* Solve the problem */
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /****************** Make a change to the A matrix ******************/
    task.put_aij(0, 0, 3.0)?;
    let _trm = task.optimize()?;
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /***************** Add a new variable ******************************/
    /* Get index of new variable. */

    let varidx = task.get_num_var()?;

    /* Append a new variable x_3 to the problem */
    task.append_vars(1)?;
    let numvar = numvar + 1;

    /* Set bounds on new varaible */
    task.put_var_bound(varidx, Boundkey::LO, 0.0, INF)?;

    /* Change objective */
    task.put_c_j(varidx, 1.0)?;

    /* Put new values in the A matrix */
    let acolsub = &[0i32, 2];
    let acolval = &[4.0, 1.0];

    task.put_a_col(varidx, /* column index */
                   acolsub,
                   acolval)?;

    /* Change optimizer to simplex free and reoptimize */
    task.put_int_param(mosek::Iparam::OPTIMIZER, mosek::Optimizertype::FREE_SIMPLEX)?;
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Add a new constraint ***************************/
    /* Get index of new constraint. */
    let conidx = task.get_num_con()?;

    /* Append a new constraint */
    task.append_cons(1)?;
    let numcon = numcon + 1;

    /* Set bounds on new constraint */
    task.put_con_bound(conidx,
                       Boundkey::UP,
                       -INF,
                       30000.0)?;

    /* Put new values in the A matrix */
    let arowsub = &[0i32,   1,   2,   3  ];
    let arowval = &[1.0, 2.0, 1.0, 1.0 ];

    task.put_a_row(conidx, /* row index */
                   arowsub,
                   arowval)?;

    let _trm = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Change constraint bounds ********************/
    let newbkc = &[Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP];
    let newblc = &[-INF,
                   -INF,
                   -INF,
                   -INF];
    let newbuc = &[ 80000.0, 40000.0, 50000.0, 22000.0 ];

    task.put_con_bound_slice(0, numcon, newbkc, newblc, newbuc)?;

    let _ = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    Ok(())
}
source

pub fn get_obj_name(&self) -> Result<String, String>

Obtains the name assigned to the objective function.

§Returns
  • objname Assigned the objective name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getobjname

source

pub fn get_obj_name_len(&self) -> Result<i32, String>

Obtains the length of the name assigned to the objective function.

§Returns
  • len Assigned the length of the objective name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getobjnamelen

source

pub fn get_obj_sense(&self) -> Result<i32, String>

Gets the objective sense.

§Returns
  • sense The returned objective sense.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getobjsense

Examples found in repository?
examples/concurrent1.rs (line 129)
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
fn concurrent1(data : FileOrText, timelimit : Option<String>) -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
        };

    match data {
        FileOrText::File(fname) => task.read_data(fname.as_str())?,
        FileOrText::Text(text)  => task.read_ptf_string(text.as_str())?
    }
    if let Some(timelimit) = timelimit {
        task.put_dou_param(mosek::Dparam::OPTIMIZER_MAX_TIME, timelimit.parse().unwrap())?;
    }

    let numintvar = task.get_num_int_var()?;

    let r = if numintvar == 0 {
        let optimizers = &[mosek::Optimizertype::CONIC,
                           mosek::Optimizertype::DUAL_SIMPLEX,
                           mosek::Optimizertype::PRIMAL_SIMPLEX];
        optimize_concurrent(& mut task, optimizers)
    }
    else {
        let seeds = &[ 42, 13, 71749373 ];
        optimize_concurrent_mio(& mut task, seeds)
    };


    let sense = task.get_obj_sense()?;
    // Pick the feasible result. For non-integer problems all
    // solutions should be the same if more than one is returned, but
    // for integer problems tasks may have hit the time limit and
    // returned non-optimal solutions.

    let n = r.len();

    if n == 0 {
        println!("All optimizers failed.");
    }
    else if numintvar > 0 {
        let (ii,_,tasks) = split3vec(r);

        let pobjs : Vec<(usize,f64)> =
            ii.iter().zip(tasks.iter()).enumerate()
            .filter_map(|(k,(_i,t))|
                match (*t).solution_def(Soltype::ITG) {
                    Ok(true) => match t.get_sol_sta(Soltype::ITG).unwrap() {
                        Solsta::PRIM_FEAS|Solsta::INTEGER_OPTIMAL => Some((k,t.get_primal_obj(Soltype::ITG).unwrap())),
                        _ => None
                    },
                    _ => None
                })
            .collect();

        let &(besti,bestobj) = pobjs.iter()
            .max_by(|(_,o1),(_,o2)|
                    match sense {
                        Objsense::MAXIMIZE => if o1 < o2 {Ordering::Less} else if o2 < o1 {Ordering::Greater} else {Ordering::Equal},
                        _ => if o1 > o2 {Ordering::Less} else if o2 > o1 {Ordering::Greater} else {Ordering::Equal}
                    }).unwrap();

        drop_except(tasks,besti).unwrap()
            .with_stream_callback(
                Streamtype::LOG, 
                &mut |msg| print!("{}",msg),
                |t| { 
                    t.optimizer_summary(mosek::Streamtype::LOG)?;
                    t.solution_summary(mosek::Streamtype::LOG)?;
                    Ok::<(),String>(())
                })?;

        println!("{} optimizers succeeded:",pobjs.len());
        for &(k,v) in pobjs.iter() {
            println!("Optimizer with seed #{} produced result : {:.5e}",ii[k],v);
        }

        println!("\tBest solution is #{}: {:.5e}",ii[besti],bestobj);
    }
    else {
        let (ii,_,tasks) = split3vec(r);

        let pobjs : Vec<(usize,f64)> =
            tasks.iter().enumerate()
            .filter_map(|(k,t)|
                        match t.get_sol_sta(Soltype::BAS) {
                            Ok(Solsta::PRIM_FEAS)|Ok(Solsta::OPTIMAL) => Some((k,t.get_primal_obj(Soltype::BAS).unwrap())),
                            _ => None
                        }.or_else(|| match t.get_sol_sta(Soltype::ITR) {
                            Ok(Solsta::PRIM_FEAS)|Ok(Solsta::OPTIMAL) => Some((k,t.get_primal_obj(Soltype::ITR).unwrap())),
                            _ => None
                        }))
            .collect();

        let &(besti,bestobj) = pobjs.iter()
            .max_by(|(_,o1),(_,o2)|
                    match sense {
                        Objsense::MAXIMIZE => if o1 < o2 {Ordering::Less} else if o2 < o1 {Ordering::Greater} else {Ordering::Equal},
                        _ => if o1 > o2 {Ordering::Less} else if o2 > o1 {Ordering::Greater} else {Ordering::Equal}
                    }).unwrap();

        drop_except(tasks,besti).unwrap()
            .with_stream_callback(
                Streamtype::LOG, 
                &mut|msg| print!("{}",msg),
                |t| {
                    t.optimizer_summary(mosek::Streamtype::LOG)?;
                    t.solution_summary(mosek::Streamtype::LOG)?;
                    Ok::<(),String>(())
                })?;

        println!("{} optimizers succeeded:",pobjs.len());
        for &(k,v) in pobjs.iter() {
            println!("Optimizer with seed #{} produced result : {:.5e}",ii[k],v);
        }

        println!("\tBest solution is #{}: {:.5e}",ii[besti],bestobj);
    }


    Result::Ok(())
}
source

pub fn get_param_max( &self, partype_: i32, parammax_: &mut i32 ) -> Result<(), String>

Obtains the maximum index of a parameter of a given type.

§Arguments
  • partype_ Parameter type.

    See Parametertype

  • parammax_ The maximum index (plus 1) of the given parameter type.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getparammax

source

pub fn get_param_name( &self, partype_: i32, param_: i32 ) -> Result<String, String>

Obtains the name of a parameter.

§Arguments
  • partype_ Parameter type.

    See Parametertype

  • param_ Which parameter.

§Returns
  • parname Parameter name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getparamname

source

pub fn get_power_domain_alpha( &mut self, domidx_: i64, alpha_: &mut [f64] ) -> Result<(), String>

Obtains the exponent vector of a power domain.

§Arguments
  • domidx_ Index of the domain.
  • alpha_ The exponent vector of the domain.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getpowerdomainalpha

source

pub fn get_power_domain_info( &mut self, domidx_: i64, n_: &mut i64, nleft_: &mut i64 ) -> Result<(), String>

Obtains structural information about a power domain.

§Arguments
  • domidx_ Index of the domain.
  • n_ Dimension of the domain.
  • nleft_ Number of variables on the left hand side.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getpowerdomaininfo

source

pub fn get_primal_obj(&self, whichsol_: i32) -> Result<f64, String>

Computes the primal objective value for the desired solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

§Returns
  • primalobj Objective value corresponding to the primal solution.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getprimalobj

Examples found in repository?
examples/concurrent1.rs (line 148)
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
fn concurrent1(data : FileOrText, timelimit : Option<String>) -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
        };

    match data {
        FileOrText::File(fname) => task.read_data(fname.as_str())?,
        FileOrText::Text(text)  => task.read_ptf_string(text.as_str())?
    }
    if let Some(timelimit) = timelimit {
        task.put_dou_param(mosek::Dparam::OPTIMIZER_MAX_TIME, timelimit.parse().unwrap())?;
    }

    let numintvar = task.get_num_int_var()?;

    let r = if numintvar == 0 {
        let optimizers = &[mosek::Optimizertype::CONIC,
                           mosek::Optimizertype::DUAL_SIMPLEX,
                           mosek::Optimizertype::PRIMAL_SIMPLEX];
        optimize_concurrent(& mut task, optimizers)
    }
    else {
        let seeds = &[ 42, 13, 71749373 ];
        optimize_concurrent_mio(& mut task, seeds)
    };


    let sense = task.get_obj_sense()?;
    // Pick the feasible result. For non-integer problems all
    // solutions should be the same if more than one is returned, but
    // for integer problems tasks may have hit the time limit and
    // returned non-optimal solutions.

    let n = r.len();

    if n == 0 {
        println!("All optimizers failed.");
    }
    else if numintvar > 0 {
        let (ii,_,tasks) = split3vec(r);

        let pobjs : Vec<(usize,f64)> =
            ii.iter().zip(tasks.iter()).enumerate()
            .filter_map(|(k,(_i,t))|
                match (*t).solution_def(Soltype::ITG) {
                    Ok(true) => match t.get_sol_sta(Soltype::ITG).unwrap() {
                        Solsta::PRIM_FEAS|Solsta::INTEGER_OPTIMAL => Some((k,t.get_primal_obj(Soltype::ITG).unwrap())),
                        _ => None
                    },
                    _ => None
                })
            .collect();

        let &(besti,bestobj) = pobjs.iter()
            .max_by(|(_,o1),(_,o2)|
                    match sense {
                        Objsense::MAXIMIZE => if o1 < o2 {Ordering::Less} else if o2 < o1 {Ordering::Greater} else {Ordering::Equal},
                        _ => if o1 > o2 {Ordering::Less} else if o2 > o1 {Ordering::Greater} else {Ordering::Equal}
                    }).unwrap();

        drop_except(tasks,besti).unwrap()
            .with_stream_callback(
                Streamtype::LOG, 
                &mut |msg| print!("{}",msg),
                |t| { 
                    t.optimizer_summary(mosek::Streamtype::LOG)?;
                    t.solution_summary(mosek::Streamtype::LOG)?;
                    Ok::<(),String>(())
                })?;

        println!("{} optimizers succeeded:",pobjs.len());
        for &(k,v) in pobjs.iter() {
            println!("Optimizer with seed #{} produced result : {:.5e}",ii[k],v);
        }

        println!("\tBest solution is #{}: {:.5e}",ii[besti],bestobj);
    }
    else {
        let (ii,_,tasks) = split3vec(r);

        let pobjs : Vec<(usize,f64)> =
            tasks.iter().enumerate()
            .filter_map(|(k,t)|
                        match t.get_sol_sta(Soltype::BAS) {
                            Ok(Solsta::PRIM_FEAS)|Ok(Solsta::OPTIMAL) => Some((k,t.get_primal_obj(Soltype::BAS).unwrap())),
                            _ => None
                        }.or_else(|| match t.get_sol_sta(Soltype::ITR) {
                            Ok(Solsta::PRIM_FEAS)|Ok(Solsta::OPTIMAL) => Some((k,t.get_primal_obj(Soltype::ITR).unwrap())),
                            _ => None
                        }))
            .collect();

        let &(besti,bestobj) = pobjs.iter()
            .max_by(|(_,o1),(_,o2)|
                    match sense {
                        Objsense::MAXIMIZE => if o1 < o2 {Ordering::Less} else if o2 < o1 {Ordering::Greater} else {Ordering::Equal},
                        _ => if o1 > o2 {Ordering::Less} else if o2 > o1 {Ordering::Greater} else {Ordering::Equal}
                    }).unwrap();

        drop_except(tasks,besti).unwrap()
            .with_stream_callback(
                Streamtype::LOG, 
                &mut|msg| print!("{}",msg),
                |t| {
                    t.optimizer_summary(mosek::Streamtype::LOG)?;
                    t.solution_summary(mosek::Streamtype::LOG)?;
                    Ok::<(),String>(())
                })?;

        println!("{} optimizers succeeded:",pobjs.len());
        for &(k,v) in pobjs.iter() {
            println!("Optimizer with seed #{} produced result : {:.5e}",ii[k],v);
        }

        println!("\tBest solution is #{}: {:.5e}",ii[besti],bestobj);
    }


    Result::Ok(())
}
More examples
Hide additional examples
examples/portfolio_5_card.rs (line 176)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
source

pub fn get_primal_solution_norms( &self, whichsol_: i32, nrmxc_: &mut f64, nrmxx_: &mut f64, nrmbarx_: &mut f64 ) -> Result<(), String>

Compute norms of the primal solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • nrmxc_ The norm of the xc vector.

  • nrmxx_ The norm of the xx vector.

  • nrmbarx_ The norm of the barX vector.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getprimalsolutionnorms

source

pub fn get_prob_type(&self) -> Result<i32, String>

Obtains the problem type.

§Returns
  • probtype The problem type.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getprobtype

source

pub fn get_pro_sta(&self, whichsol_: i32) -> Result<i32, String>

Obtains the problem status.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

§Returns
  • problemsta Problem status.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getprosta

Examples found in repository?
examples/milo1.rs (line 105)
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
fn main() -> Result<(),String> {
    let numcon : i32 = 2;
    let numvar : i32 = 2;

    let infinity = 0.0; // only for symbolic purposes, value never used

    let bkc = vec![Boundkey::UP, Boundkey::LO];
    let blc = vec![ -infinity,         -4.0 ];
    let buc = vec![ 250.0,             infinity ];

    let bkx = vec![ Boundkey::LO, Boundkey::LO  ];
    let blx = vec![ 0.0,               0.0 ];
    let bux = vec![ infinity,          infinity ];

    let c   = vec![1.0, 0.64];

    let asub = vec![0,   1,
                    0,    1];
    let aval = vec![50.0, 3.0, 31.0, -2.0];

    let ptrb : Vec<usize> = vec![ 0, 2 ];
    let ptre : Vec<usize> = vec![ 2, 4 ];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG,
            &mut |msg| print!("{}",msg),
            |task| task.with_itg_sol_callback(
                &mut |xx| { println!("Found a new solution = {:?}",xx); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                    The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                    /* Append 'numvar' variables.
                    The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    for ((((j,cj),bk),bl),bu) in (0..numvar).zip(c.iter()).zip(bkx.iter()).zip(blx.iter()).zip(bux.iter()) {
                        /* Set the linear term c_j in the objective.*/
                        task.put_c_j(j, *cj)?;
                        /* Set the bounds on variable j.
                           blx[j] <= x_j <= bux[j] */
                        task.put_var_bound(j, *bk, *bl, *bu)?;
                        /* Input column j of A */
                        task.put_a_col(j,                     /* Variable (column) index.*/
                                       &asub[ptrb[j as usize]..ptre[j as usize]],               /* Row index of non-zeros in column j.*/
                                       &aval[ptrb[j as usize]..ptre[j as usize]])?;              /* Non-zero Values of column j. */
                    }
                    // Set the bounds on constraints.
                    // for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] 
                    for (((i,bk),bl),bu) in (0..numcon).zip(bkc.iter()).zip(blc.iter()).zip(buc.iter()) {
                        task.put_con_bound(i, *bk, *bl, *bu)?;
                    }

                    /* Specify integer variables. */
                    for j in 0..numvar {
                        task.put_var_type(j, Variabletype::TYPE_INT)?;
                    }
                    /* Set max solution time */
                    task.put_dou_param(Dparam::MIO_MAX_TIME, 60.0)?;

                    /* A maximization problem */
                    task.put_obj_sense(Objsense::MAXIMIZE)?;
                    /* Solve the problem */

                    let _trm = task.optimize()?;

                    // Print a summary containing information
                    //   about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITG, xx.as_mut_slice())?;

                    /* Get status information about the solution */

                    match task.get_sol_sta(Soltype::ITG)? {
                        Solsta::INTEGER_OPTIMAL => {
                            println!("Optimal solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::PRIM_FEAS => {
                            println!("Feasible solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::UNKNOWN => {
                          match task.get_pro_sta(Soltype::ITG)? {
                              Prosta::PRIM_INFEAS_OR_UNBOUNDED => {
                                  println!("Problem status Infeasible or unbounded");
                              }
                              Prosta::PRIM_INFEAS => {
                                  println!("Problem status Infeasible.");
                              }
                              Prosta::UNKNOWN => {
                                  println!("Problem status unknown.");
                              }
                              _ => {
                                  println!("Other problem status.");
                              }
                          }
                        }
                        _ => {
                            println!("Other solution status");
                        }
                    }
                    Ok(())
                }))
}
source

pub fn get_pviol_acc( &self, whichsol_: i32, accidxlist_: &[i64], viol_: &mut [f64] ) -> Result<(), String>

Computes the violation of a solution for set of affine conic constraints.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • accidxlist_ An array of indexes of conic constraints.

  • viol_ List of violations corresponding to sub.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getpviolacc

source

pub fn get_pviol_barvar( &self, whichsol_: i32, sub_: &[i32], viol_: &mut [f64] ) -> Result<(), String>

Computes the violation of a primal solution for a list of semidefinite variables.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • sub_ An array of indexes of barX variables.

  • viol_ List of violations corresponding to sub.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getpviolbarvar

source

pub fn get_pviol_con( &self, whichsol_: i32, sub_: &[i32], viol_: &mut [f64] ) -> Result<(), String>

Computes the violation of a primal solution associated to a constraint.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • sub_ An array of indexes of constraints.

  • viol_ List of violations corresponding to sub.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getpviolcon

source

pub fn get_pviol_cones( &self, whichsol_: i32, sub_: &[i32], viol_: &mut [f64] ) -> Result<(), String>

Computes the violation of a solution for set of conic constraints.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • sub_ An array of indexes of conic constraints.

  • viol_ List of violations corresponding to sub.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getpviolcones

source

pub fn get_pviol_djc( &self, whichsol_: i32, djcidxlist_: &[i64], viol_: &mut [f64] ) -> Result<(), String>

Computes the violation of a solution for set of disjunctive constraints.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • djcidxlist_ An array of indexes of disjunctive constraints.

  • viol_ List of violations corresponding to sub.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getpvioldjc

source

pub fn get_pviol_var( &self, whichsol_: i32, sub_: &[i32], viol_: &mut [f64] ) -> Result<(), String>

Computes the violation of a primal solution for a list of scalar variables.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • sub_ An array of indexes of x variables.

  • viol_ List of violations corresponding to sub.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getpviolvar

source

pub fn get_q_con_k( &self, k_: i32, qcsubi_: &mut [i32], qcsubj_: &mut [i32], qcval_: &mut [f64] ) -> Result<i64, String>

Obtains all the quadratic terms in a constraint.

§Arguments
  • k_ Which constraint.
  • qcsubi_ Row subscripts for quadratic constraint matrix.
  • qcsubj_ Column subscripts for quadratic constraint matrix.
  • qcval_ Quadratic constraint coefficient values.
§Returns
  • numqcnz Number of quadratic terms.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getqconk64

source

pub fn get_q_obj( &self, numqonz_: &mut i64, qosubi_: &mut [i32], qosubj_: &mut [i32], qoval_: &mut [f64] ) -> Result<(), String>

Obtains all the quadratic terms in the objective.

§Arguments
  • numqonz_ Number of non-zero elements in the quadratic objective terms.
  • qosubi_ Row subscripts for quadratic objective coefficients.
  • qosubj_ Column subscripts for quadratic objective coefficients.
  • qoval_ Quadratic objective coefficient values.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getqobj64

source

pub fn get_q_obj_i_j( &self, i_: i32, j_: i32, qoij_: &mut f64 ) -> Result<(), String>

Obtains one coefficient from the quadratic term of the objective

§Arguments
  • i_ Row index of the coefficient.
  • j_ Column index of coefficient.
  • qoij_ The required coefficient.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getqobjij

source

pub fn get_reduced_costs( &self, whichsol_: i32, first_: i32, last_: i32, redcosts_: &mut [f64] ) -> Result<(), String>

Obtains the reduced costs for a sequence of variables.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • first_ The index of the first variable in the sequence.

  • last_ The index of the last variable in the sequence plus 1.

  • redcosts_ Returns the requested reduced costs.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getreducedcosts

source

pub fn get_skc(&self, whichsol_: i32, skc_: &mut [i32]) -> Result<(), String>

Obtains the status keys for the constraints.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • skc_ Status keys for the constraints.

    See Stakey

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getskc

source

pub fn get_skc_slice( &self, whichsol_: i32, first_: i32, last_: i32, skc_: &mut [i32] ) -> Result<(), String>

Obtains the status keys for a slice of the constraints.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • skc_ Status keys for the constraints.

    See Stakey

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getskcslice

source

pub fn get_skn(&self, whichsol_: i32, skn_: &mut [i32]) -> Result<(), String>

Obtains the status keys for the conic constraints.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • skn_ Status keys for the conic constraints.

    See Stakey

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getskn

source

pub fn get_skx(&self, whichsol_: i32, skx_: &mut [i32]) -> Result<(), String>

Obtains the status keys for the scalar variables.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • skx_ Status keys for the variables.

    See Stakey

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getskx

source

pub fn get_skx_slice( &self, whichsol_: i32, first_: i32, last_: i32, skx_: &mut [i32] ) -> Result<(), String>

Obtains the status keys for a slice of the scalar variables.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • skx_ Status keys for the variables.

    See Stakey

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getskxslice

source

pub fn get_slc(&self, whichsol_: i32, slc_: &mut [f64]) -> Result<(), String>

Obtains the slc vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • slc_ Dual variables corresponding to the lower bounds on the constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getslc

source

pub fn get_slc_slice( &self, whichsol_: i32, first_: i32, last_: i32, slc_: &mut [f64] ) -> Result<(), String>

Obtains a slice of the slc vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • slc_ Dual variables corresponding to the lower bounds on the constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getslcslice

source

pub fn get_slx(&self, whichsol_: i32, slx_: &mut [f64]) -> Result<(), String>

Obtains the slx vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • slx_ Dual variables corresponding to the lower bounds on the variables.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getslx

source

pub fn get_slx_slice( &self, whichsol_: i32, first_: i32, last_: i32, slx_: &mut [f64] ) -> Result<(), String>

Obtains a slice of the slx vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • slx_ Dual variables corresponding to the lower bounds on the variables.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getslxslice

source

pub fn get_snx(&self, whichsol_: i32, snx_: &mut [f64]) -> Result<(), String>

Obtains the snx vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • snx_ Dual variables corresponding to the conic constraints on the variables.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getsnx

source

pub fn get_snx_slice( &self, whichsol_: i32, first_: i32, last_: i32, snx_: &mut [f64] ) -> Result<(), String>

Obtains a slice of the snx vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • snx_ Dual variables corresponding to the conic constraints on the variables.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getsnxslice

source

pub fn get_sol_sta(&self, whichsol_: i32) -> Result<i32, String>

Obtains the solution status.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

§Returns
  • solutionsta Solution status.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getsolsta

Examples found in repository?
examples/portfolio_2_frontier.rs (line 102)
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
fn portfolio(n : i32,
             mu : &[f64],
             GT : &[f64],
             x0  : &[f64],
             alphas : &[f64],
             w : f64) -> Result<Vec<(f64,f64)>,String> {
    let k = (GT.len() / n as usize) as i32;
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(t) => t,
        None => return Err("Failed to create task".to_string()),
    };
    //task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    task.append_vars(n+1)?;
    task.append_cons(1)?;

    /* Objective */
    task.put_obj_sense(Objsense::MAXIMIZE)?;

    let x : Vec<i32> = (0i32..n).collect();
    let s = n;

    /* Total budget */
    let total_budget = w + x0.iter().sum::<f64>();

    /* Total budget constraint - set bounds l^c = u^c */
    task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
    task.put_con_name(0i32,"budget")?;
    task.put_c_slice(0,n,mu)?;

    /* x variables. */
    for (j,xj) in x.iter().enumerate() {
        /* Coefficients in the first row of A */
        task.put_aij(0, *xj, 1.0)?;
        /* No short-selling - x^l = 0, x^u = inf */
        task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
        task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
    }
    task.put_var_name(s, "s")?;
    task.put_var_bound(s, mosek::Boundkey::FR, 0.0, 0.0)?;

    // risk bound
    // (s,0.5,GT * x) in Q_r
    {
        let acci = task.get_num_acc()?;
        let afei = task.get_num_afe()?;

        task.append_afes(k as i64 + 2)?;
        let dom = task.append_r_quadratic_cone_domain(k as i64+2)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 2].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_f_entry(afei,s,1.0)?;
        task.put_afe_g(afei+1,0.5)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 2, j as i32, *v)?;
        }
    }

    let frontier : Vec<(f64,f64)> = alphas.iter().filter_map(|alpha| {
        /* Sets the objective function coefficient for s. */
        if      let Err(_) = task.put_c_j(s, - *alpha) { None }
        else if let Err(_) = task.optimize() { None }
        else if let Err(_) = task.write_data(format!("portfolio_2_frontier-{}.ptf",alpha).as_str()) { None }
        else if let Ok(solsta) = task.get_sol_sta(Soltype::ITR) {
            // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
            match solsta {
                Solsta::OPTIMAL => {
                    let mut xx = vec![0.0; n as usize+1];
                    if let Err(_) = task.get_xx(Soltype::ITR,xx.as_mut_slice()) { None }
                    else {
                        Some((*alpha,mu.iter().zip(xx.iter()).map(|(m,x)| m * x).sum::<f64>()))
                    }
                }
                _ => None
            }
        }
        else {
            None
        }
    }).collect();

    Ok(frontier)
}
More examples
Hide additional examples
examples/ceo1.rs (line 87)
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
fn main() -> Result<(),String> {
    let numcon = 1;
    let numvar = 3;

    let bkc = mosek::Boundkey::FX;
    let blc = 1.0;
    let buc = 1.0;

    let bkx = vec![ Boundkey::FR,
                    Boundkey::FR,
                    Boundkey::FR ];
    let blx = vec![ -INF, -INF, -INF ];
    let bux = vec![ INF, INF, INF ];
    let c   = vec![ 1.0, 1.0, 0.0 ];
    let a   = vec![ 1.0, 1.0, 1.0 ];
    let asub = vec![0, 1, 2];
    //let csub = new int[numvar];
    //double[] xx  = new double[numvar];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG, 
            &mut|msg| print!("{}",msg),
            |task| task.with_callback(
                &mut |caller| { println!("caller = {}",caller); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                       The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                      /* Append 'numvar' variables.
                         The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    /* Define the linear part of the problem */
                    task.put_c_slice(0, numvar, c.as_slice())?;
                    task.put_a_row(0, asub.as_slice(), a.as_slice())?;
                    task.put_con_bound(0, bkc, blc, buc)?;
                    task.put_var_bound_slice(0, numvar, bkx.as_slice(), blx.as_slice(), bux.as_slice())?;

                    /* Add a conic constraint */
                    task.append_afes(3)?;
                    let afeidxs = vec![0,  1,  2  ];
                    let b       = vec![0.0,0.0,0.0];
                    let domidx  = task.append_primal_exp_cone_domain()?;
                    task.put_afe_f_row_list(afeidxs.as_slice(),
                                            vec![1,1,1].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![1.0,1.0,1.0].as_slice())?;
                    task.append_acc(domidx,afeidxs.as_slice(),b.as_slice())?;

                    task.put_obj_sense(Objsense::MINIMIZE)?;

                    println!("optimize");
                    /* Solve the problem */
                    task.optimize()?;
                    // Print a summary containing information
                    // about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    /* Get status information about the solution */
                    let solsta = task.get_sol_sta(Soltype::ITR)?;

                    assert!(solsta == Solsta::OPTIMAL);
                    
                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITR, & mut xx[..])?;
                    
                    println!("Optimal primal solution");
                    for j in 0..numvar as usize {
                        println!("x[{}]: {:.4}",j,xx[j]);
                    }
                    Ok(())
                }))
}
examples/concurrent1.rs (line 147)
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
fn concurrent1(data : FileOrText, timelimit : Option<String>) -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
        };

    match data {
        FileOrText::File(fname) => task.read_data(fname.as_str())?,
        FileOrText::Text(text)  => task.read_ptf_string(text.as_str())?
    }
    if let Some(timelimit) = timelimit {
        task.put_dou_param(mosek::Dparam::OPTIMIZER_MAX_TIME, timelimit.parse().unwrap())?;
    }

    let numintvar = task.get_num_int_var()?;

    let r = if numintvar == 0 {
        let optimizers = &[mosek::Optimizertype::CONIC,
                           mosek::Optimizertype::DUAL_SIMPLEX,
                           mosek::Optimizertype::PRIMAL_SIMPLEX];
        optimize_concurrent(& mut task, optimizers)
    }
    else {
        let seeds = &[ 42, 13, 71749373 ];
        optimize_concurrent_mio(& mut task, seeds)
    };


    let sense = task.get_obj_sense()?;
    // Pick the feasible result. For non-integer problems all
    // solutions should be the same if more than one is returned, but
    // for integer problems tasks may have hit the time limit and
    // returned non-optimal solutions.

    let n = r.len();

    if n == 0 {
        println!("All optimizers failed.");
    }
    else if numintvar > 0 {
        let (ii,_,tasks) = split3vec(r);

        let pobjs : Vec<(usize,f64)> =
            ii.iter().zip(tasks.iter()).enumerate()
            .filter_map(|(k,(_i,t))|
                match (*t).solution_def(Soltype::ITG) {
                    Ok(true) => match t.get_sol_sta(Soltype::ITG).unwrap() {
                        Solsta::PRIM_FEAS|Solsta::INTEGER_OPTIMAL => Some((k,t.get_primal_obj(Soltype::ITG).unwrap())),
                        _ => None
                    },
                    _ => None
                })
            .collect();

        let &(besti,bestobj) = pobjs.iter()
            .max_by(|(_,o1),(_,o2)|
                    match sense {
                        Objsense::MAXIMIZE => if o1 < o2 {Ordering::Less} else if o2 < o1 {Ordering::Greater} else {Ordering::Equal},
                        _ => if o1 > o2 {Ordering::Less} else if o2 > o1 {Ordering::Greater} else {Ordering::Equal}
                    }).unwrap();

        drop_except(tasks,besti).unwrap()
            .with_stream_callback(
                Streamtype::LOG, 
                &mut |msg| print!("{}",msg),
                |t| { 
                    t.optimizer_summary(mosek::Streamtype::LOG)?;
                    t.solution_summary(mosek::Streamtype::LOG)?;
                    Ok::<(),String>(())
                })?;

        println!("{} optimizers succeeded:",pobjs.len());
        for &(k,v) in pobjs.iter() {
            println!("Optimizer with seed #{} produced result : {:.5e}",ii[k],v);
        }

        println!("\tBest solution is #{}: {:.5e}",ii[besti],bestobj);
    }
    else {
        let (ii,_,tasks) = split3vec(r);

        let pobjs : Vec<(usize,f64)> =
            tasks.iter().enumerate()
            .filter_map(|(k,t)|
                        match t.get_sol_sta(Soltype::BAS) {
                            Ok(Solsta::PRIM_FEAS)|Ok(Solsta::OPTIMAL) => Some((k,t.get_primal_obj(Soltype::BAS).unwrap())),
                            _ => None
                        }.or_else(|| match t.get_sol_sta(Soltype::ITR) {
                            Ok(Solsta::PRIM_FEAS)|Ok(Solsta::OPTIMAL) => Some((k,t.get_primal_obj(Soltype::ITR).unwrap())),
                            _ => None
                        }))
            .collect();

        let &(besti,bestobj) = pobjs.iter()
            .max_by(|(_,o1),(_,o2)|
                    match sense {
                        Objsense::MAXIMIZE => if o1 < o2 {Ordering::Less} else if o2 < o1 {Ordering::Greater} else {Ordering::Equal},
                        _ => if o1 > o2 {Ordering::Less} else if o2 > o1 {Ordering::Greater} else {Ordering::Equal}
                    }).unwrap();

        drop_except(tasks,besti).unwrap()
            .with_stream_callback(
                Streamtype::LOG, 
                &mut|msg| print!("{}",msg),
                |t| {
                    t.optimizer_summary(mosek::Streamtype::LOG)?;
                    t.solution_summary(mosek::Streamtype::LOG)?;
                    Ok::<(),String>(())
                })?;

        println!("{} optimizers succeeded:",pobjs.len());
        for &(k,v) in pobjs.iter() {
            println!("Optimizer with seed #{} produced result : {:.5e}",ii[k],v);
        }

        println!("\tBest solution is #{}: {:.5e}",ii[besti],bestobj);
    }


    Result::Ok(())
}
examples/portfolio_5_card.rs (line 168)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
examples/milo1.rs (line 91)
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
fn main() -> Result<(),String> {
    let numcon : i32 = 2;
    let numvar : i32 = 2;

    let infinity = 0.0; // only for symbolic purposes, value never used

    let bkc = vec![Boundkey::UP, Boundkey::LO];
    let blc = vec![ -infinity,         -4.0 ];
    let buc = vec![ 250.0,             infinity ];

    let bkx = vec![ Boundkey::LO, Boundkey::LO  ];
    let blx = vec![ 0.0,               0.0 ];
    let bux = vec![ infinity,          infinity ];

    let c   = vec![1.0, 0.64];

    let asub = vec![0,   1,
                    0,    1];
    let aval = vec![50.0, 3.0, 31.0, -2.0];

    let ptrb : Vec<usize> = vec![ 0, 2 ];
    let ptre : Vec<usize> = vec![ 2, 4 ];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG,
            &mut |msg| print!("{}",msg),
            |task| task.with_itg_sol_callback(
                &mut |xx| { println!("Found a new solution = {:?}",xx); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                    The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                    /* Append 'numvar' variables.
                    The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    for ((((j,cj),bk),bl),bu) in (0..numvar).zip(c.iter()).zip(bkx.iter()).zip(blx.iter()).zip(bux.iter()) {
                        /* Set the linear term c_j in the objective.*/
                        task.put_c_j(j, *cj)?;
                        /* Set the bounds on variable j.
                           blx[j] <= x_j <= bux[j] */
                        task.put_var_bound(j, *bk, *bl, *bu)?;
                        /* Input column j of A */
                        task.put_a_col(j,                     /* Variable (column) index.*/
                                       &asub[ptrb[j as usize]..ptre[j as usize]],               /* Row index of non-zeros in column j.*/
                                       &aval[ptrb[j as usize]..ptre[j as usize]])?;              /* Non-zero Values of column j. */
                    }
                    // Set the bounds on constraints.
                    // for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] 
                    for (((i,bk),bl),bu) in (0..numcon).zip(bkc.iter()).zip(blc.iter()).zip(buc.iter()) {
                        task.put_con_bound(i, *bk, *bl, *bu)?;
                    }

                    /* Specify integer variables. */
                    for j in 0..numvar {
                        task.put_var_type(j, Variabletype::TYPE_INT)?;
                    }
                    /* Set max solution time */
                    task.put_dou_param(Dparam::MIO_MAX_TIME, 60.0)?;

                    /* A maximization problem */
                    task.put_obj_sense(Objsense::MAXIMIZE)?;
                    /* Solve the problem */

                    let _trm = task.optimize()?;

                    // Print a summary containing information
                    //   about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITG, xx.as_mut_slice())?;

                    /* Get status information about the solution */

                    match task.get_sol_sta(Soltype::ITG)? {
                        Solsta::INTEGER_OPTIMAL => {
                            println!("Optimal solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::PRIM_FEAS => {
                            println!("Feasible solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::UNKNOWN => {
                          match task.get_pro_sta(Soltype::ITG)? {
                              Prosta::PRIM_INFEAS_OR_UNBOUNDED => {
                                  println!("Problem status Infeasible or unbounded");
                              }
                              Prosta::PRIM_INFEAS => {
                                  println!("Problem status Infeasible.");
                              }
                              Prosta::UNKNOWN => {
                                  println!("Problem status unknown.");
                              }
                              _ => {
                                  println!("Other problem status.");
                              }
                          }
                        }
                        _ => {
                            println!("Other solution status");
                        }
                    }
                    Ok(())
                }))
}
source

pub fn get_solution( &self, whichsol_: i32, problemsta_: &mut i32, solutionsta_: &mut i32, skc_: &mut [i32], skx_: &mut [i32], skn_: &mut [i32], xc_: &mut [f64], xx_: &mut [f64], y_: &mut [f64], slc_: &mut [f64], suc_: &mut [f64], slx_: &mut [f64], sux_: &mut [f64], snx_: &mut [f64] ) -> Result<(), String>

Obtains the complete solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • problemsta_ Problem status.

    See Prosta

  • solutionsta_ Solution status.

    See Solsta

  • skc_ Status keys for the constraints.

    See Stakey

  • skx_ Status keys for the variables.

    See Stakey

  • skn_ Status keys for the conic constraints.

    See Stakey

  • xc_ Primal constraint solution.

  • xx_ Primal variable solution.

  • y_ Vector of dual variables corresponding to the constraints.

  • slc_ Dual variables corresponding to the lower bounds on the constraints.

  • suc_ Dual variables corresponding to the upper bounds on the constraints.

  • slx_ Dual variables corresponding to the lower bounds on the variables.

  • sux_ Dual variables corresponding to the upper bounds on the variables.

  • snx_ Dual variables corresponding to the conic constraints on the variables.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getsolution

source

pub fn get_solution_info( &self, whichsol_: i32, pobj_: &mut f64, pviolcon_: &mut f64, pviolvar_: &mut f64, pviolbarvar_: &mut f64, pviolcone_: &mut f64, pviolitg_: &mut f64, dobj_: &mut f64, dviolcon_: &mut f64, dviolvar_: &mut f64, dviolbarvar_: &mut f64, dviolcone_: &mut f64 ) -> Result<(), String>

Obtains information about of a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • pobj_ The primal objective value.

  • pviolcon_ Maximal primal bound violation for a xc variable.

  • pviolvar_ Maximal primal bound violation for a xx variable.

  • pviolbarvar_ Maximal primal bound violation for a barx variable.

  • pviolcone_ Maximal primal violation of the solution with respect to the conic constraints.

  • pviolitg_ Maximal violation in the integer constraints.

  • dobj_ Dual objective value.

  • dviolcon_ Maximal dual bound violation for a xc variable.

  • dviolvar_ Maximal dual bound violation for a xx variable.

  • dviolbarvar_ Maximal dual bound violation for a bars variable.

  • dviolcone_ Maximum violation of the dual solution in the dual conic constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getsolutioninfo

source

pub fn get_solution_info_new( &self, whichsol_: i32, pobj_: &mut f64, pviolcon_: &mut f64, pviolvar_: &mut f64, pviolbarvar_: &mut f64, pviolcone_: &mut f64, pviolacc_: &mut f64, pvioldjc_: &mut f64, pviolitg_: &mut f64, dobj_: &mut f64, dviolcon_: &mut f64, dviolvar_: &mut f64, dviolbarvar_: &mut f64, dviolcone_: &mut f64, dviolacc_: &mut f64 ) -> Result<(), String>

Obtains information about of a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • pobj_ The primal objective value.

  • pviolcon_ Maximal primal bound violation for a xc variable.

  • pviolvar_ Maximal primal bound violation for a xx variable.

  • pviolbarvar_ Maximal primal bound violation for a barx variable.

  • pviolcone_ Maximal primal violation of the solution with respect to the conic constraints.

  • pviolacc_ Maximal primal violation of the solution with respect to the affine conic constraints.

  • pvioldjc_ Maximal primal violation of the solution with respect to the disjunctive constraints.

  • pviolitg_ Maximal violation in the integer constraints.

  • dobj_ Dual objective value.

  • dviolcon_ Maximal dual bound violation for a xc variable.

  • dviolvar_ Maximal dual bound violation for a xx variable.

  • dviolbarvar_ Maximal dual bound violation for a bars variable.

  • dviolcone_ Maximum violation of the dual solution in the dual conic constraints.

  • dviolacc_ Maximum violation of the dual solution in the dual affine conic constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getsolutioninfonew

source

pub fn get_solution_new( &self, whichsol_: i32, problemsta_: &mut i32, solutionsta_: &mut i32, skc_: &mut [i32], skx_: &mut [i32], skn_: &mut [i32], xc_: &mut [f64], xx_: &mut [f64], y_: &mut [f64], slc_: &mut [f64], suc_: &mut [f64], slx_: &mut [f64], sux_: &mut [f64], snx_: &mut [f64], doty_: &mut [f64] ) -> Result<(), String>

Obtains the complete solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • problemsta_ Problem status.

    See Prosta

  • solutionsta_ Solution status.

    See Solsta

  • skc_ Status keys for the constraints.

    See Stakey

  • skx_ Status keys for the variables.

    See Stakey

  • skn_ Status keys for the conic constraints.

    See Stakey

  • xc_ Primal constraint solution.

  • xx_ Primal variable solution.

  • y_ Vector of dual variables corresponding to the constraints.

  • slc_ Dual variables corresponding to the lower bounds on the constraints.

  • suc_ Dual variables corresponding to the upper bounds on the constraints.

  • slx_ Dual variables corresponding to the lower bounds on the variables.

  • sux_ Dual variables corresponding to the upper bounds on the variables.

  • snx_ Dual variables corresponding to the conic constraints on the variables.

  • doty_ Dual variables corresponding to affine conic constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getsolutionnew

source

pub fn get_solution_slice( &self, whichsol_: i32, solitem_: i32, first_: i32, last_: i32, values_: &mut [f64] ) -> Result<(), String>

Obtains a slice of the solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • solitem_ Which part of the solution is required.

    See Solitem

  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • values_ The values of the requested solution elements.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getsolutionslice

source

pub fn get_sparse_sym_mat( &self, idx_: i64, subi_: &mut [i32], subj_: &mut [i32], valij_: &mut [f64] ) -> Result<(), String>

Gets a single symmetric matrix from the matrix store.

§Arguments
  • idx_ Index of the matrix to retrieve.
  • subi_ Row subscripts of the matrix non-zero elements.
  • subj_ Column subscripts of the matrix non-zero elements.
  • valij_ Coefficients of the matrix non-zero elements.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getsparsesymmat

source

pub fn get_str_param( &self, param_: i32, len_: &mut i32 ) -> Result<String, String>

Obtains the value of a string parameter.

§Arguments
  • param_ Which parameter.

    See Sparam

  • len_ The length of the parameter value.

§Returns
  • parvalue If this is not a null pointer, the parameter value is stored here.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getstrparam

source

pub fn get_str_param_len(&self, param_: i32) -> Result<i32, String>

Obtains the length of a string parameter.

§Arguments
  • param_ Which parameter.

    See Sparam

§Returns
  • len The length of the parameter value.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getstrparamlen

source

pub fn get_suc(&self, whichsol_: i32, suc_: &mut [f64]) -> Result<(), String>

Obtains the suc vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • suc_ Dual variables corresponding to the upper bounds on the constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getsuc

source

pub fn get_suc_slice( &self, whichsol_: i32, first_: i32, last_: i32, suc_: &mut [f64] ) -> Result<(), String>

Obtains a slice of the suc vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • suc_ Dual variables corresponding to the upper bounds on the constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getsucslice

source

pub fn get_sux(&self, whichsol_: i32, sux_: &mut [f64]) -> Result<(), String>

Obtains the sux vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • sux_ Dual variables corresponding to the upper bounds on the variables.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getsux

source

pub fn get_sux_slice( &self, whichsol_: i32, first_: i32, last_: i32, sux_: &mut [f64] ) -> Result<(), String>

Obtains a slice of the sux vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • sux_ Dual variables corresponding to the upper bounds on the variables.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getsuxslice

source

pub fn get_symb_con(&self, i_: i32, value_: &mut i32) -> Result<String, String>

Obtains a cone type string identifier.

§Arguments
  • i_ Index.
  • value_ The corresponding value.
§Returns
  • name Name of the i’th symbolic constant.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getsymbcon

source

pub fn get_sym_mat_info( &self, idx_: i64, dim_: &mut i32, nz_: &mut i64, mattype_: &mut i32 ) -> Result<(), String>

Obtains information about a matrix from the symmetric matrix storage.

§Arguments
  • idx_ Index of the matrix for which information is requested.

  • dim_ Returns the dimension of the requested matrix.

  • nz_ Returns the number of non-zeros in the requested matrix.

  • mattype_ Returns the type of the requested matrix.

    See Symmattype

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getsymmatinfo

source

pub fn get_task_name(&self) -> Result<String, String>

Obtains the task name.

§Returns
  • taskname Returns the task name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.gettaskname

source

pub fn get_task_name_len(&self) -> Result<i32, String>

Obtains the length the task name.

§Returns
  • len Returns the length of the task name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.gettasknamelen

source

pub fn get_var_bound( &self, i_: i32, bk_: &mut i32, bl_: &mut f64, bu_: &mut f64 ) -> Result<(), String>

Obtains bound information for one variable.

§Arguments
  • i_ Index of the variable for which the bound information should be obtained.

  • bk_ Bound keys.

    See Boundkey

  • bl_ Values for lower bounds.

  • bu_ Values for upper bounds.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getvarbound

source

pub fn get_var_bound_slice( &self, first_: i32, last_: i32, bk_: &mut [i32], bl_: &mut [f64], bu_: &mut [f64] ) -> Result<(), String>

Obtains bounds information for a slice of the variables.

§Arguments
  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • bk_ Bound keys.

    See Boundkey

  • bl_ Values for lower bounds.

  • bu_ Values for upper bounds.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getvarboundslice

source

pub fn get_var_name(&self, j_: i32) -> Result<String, String>

Obtains the name of a variable.

§Arguments
  • j_ Index of a variable.
§Returns
  • name Returns the required name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getvarname

source

pub fn get_var_name_index( &self, somename_: &str, asgn_: &mut i32 ) -> Result<i32, String>

Checks whether the name has been assigned to any variable.

§Arguments
  • somename_ The name which should be checked.
  • asgn_ Is non-zero if the name somename is assigned to a variable.
§Returns
  • index If the name somename is assigned to a variable, then return the index of the variable.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getvarnameindex

source

pub fn get_var_name_len(&self, i_: i32) -> Result<i32, String>

Obtains the length of the name of a variable.

§Arguments
  • i_ Index of a variable.
§Returns
  • len Returns the length of the indicated name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getvarnamelen

source

pub fn get_var_type(&self, j_: i32) -> Result<i32, String>

Gets the variable type of one variable.

§Arguments
  • j_ Index of the variable.
§Returns
  • vartype Variable type of variable index j.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getvartype

source

pub fn get_var_type_list( &self, subj_: &[i32], vartype_: &mut [i32] ) -> Result<(), String>

Obtains the variable type for one or more variables.

§Arguments
  • subj_ A list of variable indexes.

  • vartype_ Returns the variables types corresponding the variable indexes requested.

    See Variabletype

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getvartypelist

source

pub fn get_xc(&self, whichsol_: i32, xc_: &mut [f64]) -> Result<(), String>

Obtains the xc vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • xc_ Primal constraint solution.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getxc

source

pub fn get_xc_slice( &self, whichsol_: i32, first_: i32, last_: i32, xc_: &mut [f64] ) -> Result<(), String>

Obtains a slice of the xc vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • xc_ Primal constraint solution.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getxcslice

source

pub fn get_xx(&self, whichsol_: i32, xx_: &mut [f64]) -> Result<(), String>

Obtains the xx vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • xx_ Primal variable solution.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getxx

Examples found in repository?
examples/helloworld.rs (line 28)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
fn main() -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
        };

    task.append_vars(1)?;                           // 1 variable x
    task.put_c_j(0, 1.0)?;                          // c_0 = 1.0
    task.put_var_bound(0, Boundkey::RA, 2.0, 3.0)?; // 2.0 <= x <= 3.0
    task.put_obj_sense(Objsense::MINIMIZE)?;        // minimize

    task.optimize()?;                               // Optimize

    let mut x = vec![0.0; 1];
    task.get_xx(Soltype::ITR, x.as_mut_slice())?;   // Get solution
    println!("Solution x = {}", x[0]);              // Print solution
    return Result::Ok(());
}
More examples
Hide additional examples
examples/portfolio_2_frontier.rs (line 107)
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
fn portfolio(n : i32,
             mu : &[f64],
             GT : &[f64],
             x0  : &[f64],
             alphas : &[f64],
             w : f64) -> Result<Vec<(f64,f64)>,String> {
    let k = (GT.len() / n as usize) as i32;
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(t) => t,
        None => return Err("Failed to create task".to_string()),
    };
    //task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    task.append_vars(n+1)?;
    task.append_cons(1)?;

    /* Objective */
    task.put_obj_sense(Objsense::MAXIMIZE)?;

    let x : Vec<i32> = (0i32..n).collect();
    let s = n;

    /* Total budget */
    let total_budget = w + x0.iter().sum::<f64>();

    /* Total budget constraint - set bounds l^c = u^c */
    task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
    task.put_con_name(0i32,"budget")?;
    task.put_c_slice(0,n,mu)?;

    /* x variables. */
    for (j,xj) in x.iter().enumerate() {
        /* Coefficients in the first row of A */
        task.put_aij(0, *xj, 1.0)?;
        /* No short-selling - x^l = 0, x^u = inf */
        task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
        task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
    }
    task.put_var_name(s, "s")?;
    task.put_var_bound(s, mosek::Boundkey::FR, 0.0, 0.0)?;

    // risk bound
    // (s,0.5,GT * x) in Q_r
    {
        let acci = task.get_num_acc()?;
        let afei = task.get_num_afe()?;

        task.append_afes(k as i64 + 2)?;
        let dom = task.append_r_quadratic_cone_domain(k as i64+2)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 2].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_f_entry(afei,s,1.0)?;
        task.put_afe_g(afei+1,0.5)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 2, j as i32, *v)?;
        }
    }

    let frontier : Vec<(f64,f64)> = alphas.iter().filter_map(|alpha| {
        /* Sets the objective function coefficient for s. */
        if      let Err(_) = task.put_c_j(s, - *alpha) { None }
        else if let Err(_) = task.optimize() { None }
        else if let Err(_) = task.write_data(format!("portfolio_2_frontier-{}.ptf",alpha).as_str()) { None }
        else if let Ok(solsta) = task.get_sol_sta(Soltype::ITR) {
            // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
            match solsta {
                Solsta::OPTIMAL => {
                    let mut xx = vec![0.0; n as usize+1];
                    if let Err(_) = task.get_xx(Soltype::ITR,xx.as_mut_slice()) { None }
                    else {
                        Some((*alpha,mu.iter().zip(xx.iter()).map(|(m,x)| m * x).sum::<f64>()))
                    }
                }
                _ => None
            }
        }
        else {
            None
        }
    }).collect();

    Ok(frontier)
}
examples/ceo1.rs (line 92)
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
fn main() -> Result<(),String> {
    let numcon = 1;
    let numvar = 3;

    let bkc = mosek::Boundkey::FX;
    let blc = 1.0;
    let buc = 1.0;

    let bkx = vec![ Boundkey::FR,
                    Boundkey::FR,
                    Boundkey::FR ];
    let blx = vec![ -INF, -INF, -INF ];
    let bux = vec![ INF, INF, INF ];
    let c   = vec![ 1.0, 1.0, 0.0 ];
    let a   = vec![ 1.0, 1.0, 1.0 ];
    let asub = vec![0, 1, 2];
    //let csub = new int[numvar];
    //double[] xx  = new double[numvar];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG, 
            &mut|msg| print!("{}",msg),
            |task| task.with_callback(
                &mut |caller| { println!("caller = {}",caller); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                       The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                      /* Append 'numvar' variables.
                         The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    /* Define the linear part of the problem */
                    task.put_c_slice(0, numvar, c.as_slice())?;
                    task.put_a_row(0, asub.as_slice(), a.as_slice())?;
                    task.put_con_bound(0, bkc, blc, buc)?;
                    task.put_var_bound_slice(0, numvar, bkx.as_slice(), blx.as_slice(), bux.as_slice())?;

                    /* Add a conic constraint */
                    task.append_afes(3)?;
                    let afeidxs = vec![0,  1,  2  ];
                    let b       = vec![0.0,0.0,0.0];
                    let domidx  = task.append_primal_exp_cone_domain()?;
                    task.put_afe_f_row_list(afeidxs.as_slice(),
                                            vec![1,1,1].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![1.0,1.0,1.0].as_slice())?;
                    task.append_acc(domidx,afeidxs.as_slice(),b.as_slice())?;

                    task.put_obj_sense(Objsense::MINIMIZE)?;

                    println!("optimize");
                    /* Solve the problem */
                    task.optimize()?;
                    // Print a summary containing information
                    // about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    /* Get status information about the solution */
                    let solsta = task.get_sol_sta(Soltype::ITR)?;

                    assert!(solsta == Solsta::OPTIMAL);
                    
                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITR, & mut xx[..])?;
                    
                    println!("Optimal primal solution");
                    for j in 0..numvar as usize {
                        println!("x[{}]: {:.4}",j,xx[j]);
                    }
                    Ok(())
                }))
}
examples/reoptimization.rs (lines 85-86)
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
fn main() -> Result<(),String> {

    let numcon = 3;
    let numvar = 3;
    let c = &[1.5, 2.5, 3.0 ];
    let bkc = &[ Boundkey::UP,
                 Boundkey::UP,
                 Boundkey::UP ];
    let blc = &[ -INF,
                 -INF,
                 -INF ];
    let buc = &[ 100000.0,
                 50000.0,
                 60000.0 ];
    let bkx = &[ Boundkey::LO,
                 Boundkey::LO,
                 Boundkey::LO
                             ];
    let blx = &[ 0.0, 0.0, 0.0 ];
    let bux = &[ INF,
                 INF,
                 INF ];

    let asub = &[
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ] ];

    let aval = &[
        &[ 2.0, 3.0, 2.0 ],
        &[ 4.0, 2.0, 3.0 ],
        &[ 3.0, 3.0, 2.0 ] ];


    let mut task = Task::new().unwrap();
    /* Append the constraints. */
    task.append_cons(numcon)?;

    /* Append the variables. */
    task.append_vars(numvar)?;

    /* Put C. */
    for (j,&cj) in (0..numvar).zip(c.iter()) {
        task.put_c_j(j,cj)?;
    }
    /* Put constraint bounds. */
    for (i,&bki,&bli,&bui) in izip!(0..numcon,bkc,blc,buc) {
        task.put_con_bound(i, bki, bli, bui)?;
    }

    /* Put variable bounds. */
    for (j,&bki,&bli,&bui) in izip!(0..numvar,bkx,blx,bux) {
        task.put_var_bound(j, bki, bli, bui)?;
    }

    /* Put A. */
    if numcon > 0 {
        for (j,&asubj,&avalj) in izip!(0..numvar,asub,aval) {
            task.put_a_col(j,
                           asubj,
                           avalj)?;
        }
    }

    /* A maximization problem */
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    /* Solve the problem */
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /****************** Make a change to the A matrix ******************/
    task.put_aij(0, 0, 3.0)?;
    let _trm = task.optimize()?;
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /***************** Add a new variable ******************************/
    /* Get index of new variable. */

    let varidx = task.get_num_var()?;

    /* Append a new variable x_3 to the problem */
    task.append_vars(1)?;
    let numvar = numvar + 1;

    /* Set bounds on new varaible */
    task.put_var_bound(varidx, Boundkey::LO, 0.0, INF)?;

    /* Change objective */
    task.put_c_j(varidx, 1.0)?;

    /* Put new values in the A matrix */
    let acolsub = &[0i32, 2];
    let acolval = &[4.0, 1.0];

    task.put_a_col(varidx, /* column index */
                   acolsub,
                   acolval)?;

    /* Change optimizer to simplex free and reoptimize */
    task.put_int_param(mosek::Iparam::OPTIMIZER, mosek::Optimizertype::FREE_SIMPLEX)?;
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Add a new constraint ***************************/
    /* Get index of new constraint. */
    let conidx = task.get_num_con()?;

    /* Append a new constraint */
    task.append_cons(1)?;
    let numcon = numcon + 1;

    /* Set bounds on new constraint */
    task.put_con_bound(conidx,
                       Boundkey::UP,
                       -INF,
                       30000.0)?;

    /* Put new values in the A matrix */
    let arowsub = &[0i32,   1,   2,   3  ];
    let arowval = &[1.0, 2.0, 1.0, 1.0 ];

    task.put_a_row(conidx, /* row index */
                   arowsub,
                   arowval)?;

    let _trm = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Change constraint bounds ********************/
    let newbkc = &[Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP];
    let newblc = &[-INF,
                   -INF,
                   -INF,
                   -INF];
    let newbuc = &[ 80000.0, 40000.0, 50000.0, 22000.0 ];

    task.put_con_bound_slice(0, numcon, newbkc, newblc, newbuc)?;

    let _ = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    Ok(())
}
examples/milo1.rs (line 87)
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
fn main() -> Result<(),String> {
    let numcon : i32 = 2;
    let numvar : i32 = 2;

    let infinity = 0.0; // only for symbolic purposes, value never used

    let bkc = vec![Boundkey::UP, Boundkey::LO];
    let blc = vec![ -infinity,         -4.0 ];
    let buc = vec![ 250.0,             infinity ];

    let bkx = vec![ Boundkey::LO, Boundkey::LO  ];
    let blx = vec![ 0.0,               0.0 ];
    let bux = vec![ infinity,          infinity ];

    let c   = vec![1.0, 0.64];

    let asub = vec![0,   1,
                    0,    1];
    let aval = vec![50.0, 3.0, 31.0, -2.0];

    let ptrb : Vec<usize> = vec![ 0, 2 ];
    let ptre : Vec<usize> = vec![ 2, 4 ];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG,
            &mut |msg| print!("{}",msg),
            |task| task.with_itg_sol_callback(
                &mut |xx| { println!("Found a new solution = {:?}",xx); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                    The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                    /* Append 'numvar' variables.
                    The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    for ((((j,cj),bk),bl),bu) in (0..numvar).zip(c.iter()).zip(bkx.iter()).zip(blx.iter()).zip(bux.iter()) {
                        /* Set the linear term c_j in the objective.*/
                        task.put_c_j(j, *cj)?;
                        /* Set the bounds on variable j.
                           blx[j] <= x_j <= bux[j] */
                        task.put_var_bound(j, *bk, *bl, *bu)?;
                        /* Input column j of A */
                        task.put_a_col(j,                     /* Variable (column) index.*/
                                       &asub[ptrb[j as usize]..ptre[j as usize]],               /* Row index of non-zeros in column j.*/
                                       &aval[ptrb[j as usize]..ptre[j as usize]])?;              /* Non-zero Values of column j. */
                    }
                    // Set the bounds on constraints.
                    // for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] 
                    for (((i,bk),bl),bu) in (0..numcon).zip(bkc.iter()).zip(blc.iter()).zip(buc.iter()) {
                        task.put_con_bound(i, *bk, *bl, *bu)?;
                    }

                    /* Specify integer variables. */
                    for j in 0..numvar {
                        task.put_var_type(j, Variabletype::TYPE_INT)?;
                    }
                    /* Set max solution time */
                    task.put_dou_param(Dparam::MIO_MAX_TIME, 60.0)?;

                    /* A maximization problem */
                    task.put_obj_sense(Objsense::MAXIMIZE)?;
                    /* Solve the problem */

                    let _trm = task.optimize()?;

                    // Print a summary containing information
                    //   about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITG, xx.as_mut_slice())?;

                    /* Get status information about the solution */

                    match task.get_sol_sta(Soltype::ITG)? {
                        Solsta::INTEGER_OPTIMAL => {
                            println!("Optimal solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::PRIM_FEAS => {
                            println!("Feasible solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::UNKNOWN => {
                          match task.get_pro_sta(Soltype::ITG)? {
                              Prosta::PRIM_INFEAS_OR_UNBOUNDED => {
                                  println!("Problem status Infeasible or unbounded");
                              }
                              Prosta::PRIM_INFEAS => {
                                  println!("Problem status Infeasible.");
                              }
                              Prosta::UNKNOWN => {
                                  println!("Problem status unknown.");
                              }
                              _ => {
                                  println!("Other problem status.");
                              }
                          }
                        }
                        _ => {
                            println!("Other solution status");
                        }
                    }
                    Ok(())
                }))
}
source

pub fn get_xx_slice( &self, whichsol_: i32, first_: i32, last_: i32, xx_: &mut [f64] ) -> Result<(), String>

Obtains a slice of the xx vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • xx_ Primal variable solution.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getxxslice

Examples found in repository?
examples/portfolio_5_card.rs (line 175)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
source

pub fn get_y(&self, whichsol_: i32, y_: &mut [f64]) -> Result<(), String>

Obtains the y vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • y_ Vector of dual variables corresponding to the constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.gety

source

pub fn get_y_slice( &self, whichsol_: i32, first_: i32, last_: i32, y_: &mut [f64] ) -> Result<(), String>

Obtains a slice of the y vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • y_ Vector of dual variables corresponding to the constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.getyslice

source

pub fn infeasibility_report( &mut self, whichstream_: i32, whichsol_: i32 ) -> Result<(), String>

Prints the infeasibility report to an output stream.

§Arguments
  • whichstream_ Index of the stream.

    See Streamtype

  • whichsol_ Selects a solution.

    See Soltype

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.infeasibilityreport

source

pub fn init_basis_solve(&mut self, basis_: &mut [i32]) -> Result<(), String>

Prepare a task for basis solver.

§Arguments
  • basis_ The array of basis indexes to use.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.initbasissolve

Examples found in repository?
examples/solvelinear.rs (line 57)
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
fn setup(task : & mut mosek::Task,
         aval : &[f64],
         asub : &[i32],
         ptrb : &[i64],
         ptre : &[i64],
         numvar : i32) -> Result<Vec<i32>,String> {

    // mosek.stakey[] skx = new mosek.stakey [numvar];
    // mosek.stakey[] skc = new mosek.stakey [numvar];

    // for (int i = 0; i < numvar ; ++i) {
    //   skx[i] = mosek.stakey.bas;
    //   skc[i] = mosek.stakey.fix;
    // }

    task.append_vars(numvar)?;
    task.append_cons(numvar)?;

    task.put_a_col_slice(0,numvar,ptrb,ptre,asub,aval)?;

    task.put_con_bound_slice_const(0,numvar,Boundkey::FX,0.0,0.0)?;
    task.put_var_bound_slice_const(0,numvar,Boundkey::FR,-INF,INF)?;

    /* Define a basic solution by specifying
       status keys for variables & constraints. */
    task.delete_solution(Soltype::BAS)?;

    task.put_skc_slice(Soltype::BAS, 0, numvar, vec![Stakey::FIX; numvar as usize].as_slice())?;
    task.put_skx_slice(Soltype::BAS, 0, numvar, vec![Stakey::BAS; numvar as usize].as_slice())?;

    let mut basis = vec![0; numvar as usize];
    task.init_basis_solve(basis.as_mut_slice())?;
    Ok(basis)
  }
source

pub fn input_data( &mut self, maxnumcon_: i32, maxnumvar_: i32, c_: &[f64], cfix_: f64, aptrb_: &[i64], aptre_: &[i64], asub_: &[i32], aval_: &[f64], bkc_: &[i32], blc_: &[f64], buc_: &[f64], bkx_: &[i32], blx_: &[f64], bux_: &[f64] ) -> Result<(), String>

Input the linear part of an optimization task in one function call.

§Arguments
  • maxnumcon_ Number of preallocated constraints in the optimization task.

  • maxnumvar_ Number of preallocated variables in the optimization task.

  • c_ Linear terms of the objective as a dense vector. The length is the number of variables.

  • cfix_ Fixed term in the objective.

  • aptrb_ Row or column start pointers.

  • aptre_ Row or column end pointers.

  • asub_ Coefficient subscripts.

  • aval_ Coefficient values.

  • bkc_ Bound keys for the constraints.

    See Boundkey

  • blc_ Lower bounds for the constraints.

  • buc_ Upper bounds for the constraints.

  • bkx_ Bound keys for the variables.

    See Boundkey

  • blx_ Lower bounds for the variables.

  • bux_ Upper bounds for the variables.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.inputdata64

source

pub fn is_dou_par_name( &self, parname_: &str, param_: &mut i32 ) -> Result<(), String>

Checks a double parameter name.

§Arguments
  • parname_ Parameter name.

  • param_ Returns the parameter corresponding to the name, if one exists.

    See Dparam

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.isdouparname

source

pub fn is_int_par_name( &self, parname_: &str, param_: &mut i32 ) -> Result<(), String>

Checks an integer parameter name.

§Arguments
  • parname_ Parameter name.

  • param_ Returns the parameter corresponding to the name, if one exists.

    See Iparam

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.isintparname

source

pub fn is_str_par_name( &self, parname_: &str, param_: &mut i32 ) -> Result<(), String>

Checks a string parameter name.

§Arguments
  • parname_ Parameter name.

  • param_ Returns the parameter corresponding to the name, if one exists.

    See Sparam

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.isstrparname

Directs all output from a task stream to a file.

§Arguments
  • whichstream_ Index of the stream.

    See Streamtype

  • filename_ A valid file name.

  • append_ If this argument is 0 the output file will be overwritten, otherwise it will be appended to.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.linkfiletotaskstream

source

pub fn one_solution_summary( &self, whichstream_: i32, whichsol_: i32 ) -> Result<(), String>

Prints a short summary of a specified solution.

§Arguments
  • whichstream_ Index of the stream.

    See Streamtype

  • whichsol_ Selects a solution.

    See Soltype

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.onesolutionsummary

source

pub fn optimize_rmt( &mut self, address_: &str, accesstoken_: &str, trmcode_: &mut i32 ) -> Result<(), String>

Offload the optimization task to a solver server and wait for the solution.

§Arguments
  • address_ Address of the OptServer.

  • accesstoken_ Access token.

  • trmcode_ Is either OK or a termination response code.

    See Rescode

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.optimizermt

source

pub fn optimizer_summary(&self, whichstream_: i32) -> Result<(), String>

Prints a short summary with optimizer statistics from last optimization.

§Arguments
  • whichstream_ Index of the stream.

    See Streamtype

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.optimizersummary

Examples found in repository?
examples/concurrent1.rs (line 167)
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
fn concurrent1(data : FileOrText, timelimit : Option<String>) -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
        };

    match data {
        FileOrText::File(fname) => task.read_data(fname.as_str())?,
        FileOrText::Text(text)  => task.read_ptf_string(text.as_str())?
    }
    if let Some(timelimit) = timelimit {
        task.put_dou_param(mosek::Dparam::OPTIMIZER_MAX_TIME, timelimit.parse().unwrap())?;
    }

    let numintvar = task.get_num_int_var()?;

    let r = if numintvar == 0 {
        let optimizers = &[mosek::Optimizertype::CONIC,
                           mosek::Optimizertype::DUAL_SIMPLEX,
                           mosek::Optimizertype::PRIMAL_SIMPLEX];
        optimize_concurrent(& mut task, optimizers)
    }
    else {
        let seeds = &[ 42, 13, 71749373 ];
        optimize_concurrent_mio(& mut task, seeds)
    };


    let sense = task.get_obj_sense()?;
    // Pick the feasible result. For non-integer problems all
    // solutions should be the same if more than one is returned, but
    // for integer problems tasks may have hit the time limit and
    // returned non-optimal solutions.

    let n = r.len();

    if n == 0 {
        println!("All optimizers failed.");
    }
    else if numintvar > 0 {
        let (ii,_,tasks) = split3vec(r);

        let pobjs : Vec<(usize,f64)> =
            ii.iter().zip(tasks.iter()).enumerate()
            .filter_map(|(k,(_i,t))|
                match (*t).solution_def(Soltype::ITG) {
                    Ok(true) => match t.get_sol_sta(Soltype::ITG).unwrap() {
                        Solsta::PRIM_FEAS|Solsta::INTEGER_OPTIMAL => Some((k,t.get_primal_obj(Soltype::ITG).unwrap())),
                        _ => None
                    },
                    _ => None
                })
            .collect();

        let &(besti,bestobj) = pobjs.iter()
            .max_by(|(_,o1),(_,o2)|
                    match sense {
                        Objsense::MAXIMIZE => if o1 < o2 {Ordering::Less} else if o2 < o1 {Ordering::Greater} else {Ordering::Equal},
                        _ => if o1 > o2 {Ordering::Less} else if o2 > o1 {Ordering::Greater} else {Ordering::Equal}
                    }).unwrap();

        drop_except(tasks,besti).unwrap()
            .with_stream_callback(
                Streamtype::LOG, 
                &mut |msg| print!("{}",msg),
                |t| { 
                    t.optimizer_summary(mosek::Streamtype::LOG)?;
                    t.solution_summary(mosek::Streamtype::LOG)?;
                    Ok::<(),String>(())
                })?;

        println!("{} optimizers succeeded:",pobjs.len());
        for &(k,v) in pobjs.iter() {
            println!("Optimizer with seed #{} produced result : {:.5e}",ii[k],v);
        }

        println!("\tBest solution is #{}: {:.5e}",ii[besti],bestobj);
    }
    else {
        let (ii,_,tasks) = split3vec(r);

        let pobjs : Vec<(usize,f64)> =
            tasks.iter().enumerate()
            .filter_map(|(k,t)|
                        match t.get_sol_sta(Soltype::BAS) {
                            Ok(Solsta::PRIM_FEAS)|Ok(Solsta::OPTIMAL) => Some((k,t.get_primal_obj(Soltype::BAS).unwrap())),
                            _ => None
                        }.or_else(|| match t.get_sol_sta(Soltype::ITR) {
                            Ok(Solsta::PRIM_FEAS)|Ok(Solsta::OPTIMAL) => Some((k,t.get_primal_obj(Soltype::ITR).unwrap())),
                            _ => None
                        }))
            .collect();

        let &(besti,bestobj) = pobjs.iter()
            .max_by(|(_,o1),(_,o2)|
                    match sense {
                        Objsense::MAXIMIZE => if o1 < o2 {Ordering::Less} else if o2 < o1 {Ordering::Greater} else {Ordering::Equal},
                        _ => if o1 > o2 {Ordering::Less} else if o2 > o1 {Ordering::Greater} else {Ordering::Equal}
                    }).unwrap();

        drop_except(tasks,besti).unwrap()
            .with_stream_callback(
                Streamtype::LOG, 
                &mut|msg| print!("{}",msg),
                |t| {
                    t.optimizer_summary(mosek::Streamtype::LOG)?;
                    t.solution_summary(mosek::Streamtype::LOG)?;
                    Ok::<(),String>(())
                })?;

        println!("{} optimizers succeeded:",pobjs.len());
        for &(k,v) in pobjs.iter() {
            println!("Optimizer with seed #{} produced result : {:.5e}",ii[k],v);
        }

        println!("\tBest solution is #{}: {:.5e}",ii[besti],bestobj);
    }


    Result::Ok(())
}
source

pub fn optimize(&mut self) -> Result<i32, String>

Optimizes the problem.

§Returns
  • trmcode Is either OK or a termination response code.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.optimizetrm

Examples found in repository?
examples/concurrent1.rs (line 28)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
fn optimize(mut t : mosek::Task, stop : Arc<Mutex<bool>>) -> Option<(i32,mosek::Task)> {
    let cbstop = Arc::clone(&stop);
    if let Some(trm) = t.with_callback(
        &mut |_| cbstop.lock().and_then(|p| Ok(*p)).unwrap_or(false),
        |task|
            if let Ok(trm) = task.optimize() {
                let mut st = stop.lock().unwrap();
                *st = true;
                Some(trm)
            } else {
                None
            }) {
        Some((trm,t))
    }
    else {
        None
    }
}
More examples
Hide additional examples
examples/helloworld.rs (line 25)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
fn main() -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
        };

    task.append_vars(1)?;                           // 1 variable x
    task.put_c_j(0, 1.0)?;                          // c_0 = 1.0
    task.put_var_bound(0, Boundkey::RA, 2.0, 3.0)?; // 2.0 <= x <= 3.0
    task.put_obj_sense(Objsense::MINIMIZE)?;        // minimize

    task.optimize()?;                               // Optimize

    let mut x = vec![0.0; 1];
    task.get_xx(Soltype::ITR, x.as_mut_slice())?;   // Get solution
    println!("Solution x = {}", x[0]);              // Print solution
    return Result::Ok(());
}
examples/callback.rs (line 132)
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
fn callbackmain(which : &str, data : FileOrText) -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = Task::new().unwrap();
    match data {
        FileOrText::Text(data)  => { task.read_ptf_string(data)? },
        FileOrText::File(fname) => { task.read_data(fname)? }
    }

    task.write_data("callback.ptf")?;

    match which {
        "psim"   => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::PRIMAL_SIMPLEX)?,
        "dsim"   => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::DUAL_SIMPLEX)?,
        "intpnt" => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::INTPNT)?,
        s => return Err(format!("Invalid argument '{}'",s))
    }

    /* Directs the log task stream to the 'printstr' function. */
    task.with_stream_callback(
        Streamtype::LOG,
        & mut |msg| print!("{}",msg),
        |task|
            task.with_info_callback(
                & mut callback,
                |task|
                    task.optimize()
            )
    )?;

    Result::Ok(())
}
examples/portfolio_2_frontier.rs (line 100)
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
fn portfolio(n : i32,
             mu : &[f64],
             GT : &[f64],
             x0  : &[f64],
             alphas : &[f64],
             w : f64) -> Result<Vec<(f64,f64)>,String> {
    let k = (GT.len() / n as usize) as i32;
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(t) => t,
        None => return Err("Failed to create task".to_string()),
    };
    //task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    task.append_vars(n+1)?;
    task.append_cons(1)?;

    /* Objective */
    task.put_obj_sense(Objsense::MAXIMIZE)?;

    let x : Vec<i32> = (0i32..n).collect();
    let s = n;

    /* Total budget */
    let total_budget = w + x0.iter().sum::<f64>();

    /* Total budget constraint - set bounds l^c = u^c */
    task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
    task.put_con_name(0i32,"budget")?;
    task.put_c_slice(0,n,mu)?;

    /* x variables. */
    for (j,xj) in x.iter().enumerate() {
        /* Coefficients in the first row of A */
        task.put_aij(0, *xj, 1.0)?;
        /* No short-selling - x^l = 0, x^u = inf */
        task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
        task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
    }
    task.put_var_name(s, "s")?;
    task.put_var_bound(s, mosek::Boundkey::FR, 0.0, 0.0)?;

    // risk bound
    // (s,0.5,GT * x) in Q_r
    {
        let acci = task.get_num_acc()?;
        let afei = task.get_num_afe()?;

        task.append_afes(k as i64 + 2)?;
        let dom = task.append_r_quadratic_cone_domain(k as i64+2)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 2].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_f_entry(afei,s,1.0)?;
        task.put_afe_g(afei+1,0.5)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 2, j as i32, *v)?;
        }
    }

    let frontier : Vec<(f64,f64)> = alphas.iter().filter_map(|alpha| {
        /* Sets the objective function coefficient for s. */
        if      let Err(_) = task.put_c_j(s, - *alpha) { None }
        else if let Err(_) = task.optimize() { None }
        else if let Err(_) = task.write_data(format!("portfolio_2_frontier-{}.ptf",alpha).as_str()) { None }
        else if let Ok(solsta) = task.get_sol_sta(Soltype::ITR) {
            // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
            match solsta {
                Solsta::OPTIMAL => {
                    let mut xx = vec![0.0; n as usize+1];
                    if let Err(_) = task.get_xx(Soltype::ITR,xx.as_mut_slice()) { None }
                    else {
                        Some((*alpha,mu.iter().zip(xx.iter()).map(|(m,x)| m * x).sum::<f64>()))
                    }
                }
                _ => None
            }
        }
        else {
            None
        }
    }).collect();

    Ok(frontier)
}
examples/ceo1.rs (line 81)
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
fn main() -> Result<(),String> {
    let numcon = 1;
    let numvar = 3;

    let bkc = mosek::Boundkey::FX;
    let blc = 1.0;
    let buc = 1.0;

    let bkx = vec![ Boundkey::FR,
                    Boundkey::FR,
                    Boundkey::FR ];
    let blx = vec![ -INF, -INF, -INF ];
    let bux = vec![ INF, INF, INF ];
    let c   = vec![ 1.0, 1.0, 0.0 ];
    let a   = vec![ 1.0, 1.0, 1.0 ];
    let asub = vec![0, 1, 2];
    //let csub = new int[numvar];
    //double[] xx  = new double[numvar];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG, 
            &mut|msg| print!("{}",msg),
            |task| task.with_callback(
                &mut |caller| { println!("caller = {}",caller); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                       The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                      /* Append 'numvar' variables.
                         The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    /* Define the linear part of the problem */
                    task.put_c_slice(0, numvar, c.as_slice())?;
                    task.put_a_row(0, asub.as_slice(), a.as_slice())?;
                    task.put_con_bound(0, bkc, blc, buc)?;
                    task.put_var_bound_slice(0, numvar, bkx.as_slice(), blx.as_slice(), bux.as_slice())?;

                    /* Add a conic constraint */
                    task.append_afes(3)?;
                    let afeidxs = vec![0,  1,  2  ];
                    let b       = vec![0.0,0.0,0.0];
                    let domidx  = task.append_primal_exp_cone_domain()?;
                    task.put_afe_f_row_list(afeidxs.as_slice(),
                                            vec![1,1,1].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![1.0,1.0,1.0].as_slice())?;
                    task.append_acc(domidx,afeidxs.as_slice(),b.as_slice())?;

                    task.put_obj_sense(Objsense::MINIMIZE)?;

                    println!("optimize");
                    /* Solve the problem */
                    task.optimize()?;
                    // Print a summary containing information
                    // about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    /* Get status information about the solution */
                    let solsta = task.get_sol_sta(Soltype::ITR)?;

                    assert!(solsta == Solsta::OPTIMAL);
                    
                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITR, & mut xx[..])?;
                    
                    println!("Optimal primal solution");
                    for j in 0..numvar as usize {
                        println!("x[{}]: {:.4}",j,xx[j]);
                    }
                    Ok(())
                }))
}
examples/reoptimization.rs (line 82)
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
fn main() -> Result<(),String> {

    let numcon = 3;
    let numvar = 3;
    let c = &[1.5, 2.5, 3.0 ];
    let bkc = &[ Boundkey::UP,
                 Boundkey::UP,
                 Boundkey::UP ];
    let blc = &[ -INF,
                 -INF,
                 -INF ];
    let buc = &[ 100000.0,
                 50000.0,
                 60000.0 ];
    let bkx = &[ Boundkey::LO,
                 Boundkey::LO,
                 Boundkey::LO
                             ];
    let blx = &[ 0.0, 0.0, 0.0 ];
    let bux = &[ INF,
                 INF,
                 INF ];

    let asub = &[
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ] ];

    let aval = &[
        &[ 2.0, 3.0, 2.0 ],
        &[ 4.0, 2.0, 3.0 ],
        &[ 3.0, 3.0, 2.0 ] ];


    let mut task = Task::new().unwrap();
    /* Append the constraints. */
    task.append_cons(numcon)?;

    /* Append the variables. */
    task.append_vars(numvar)?;

    /* Put C. */
    for (j,&cj) in (0..numvar).zip(c.iter()) {
        task.put_c_j(j,cj)?;
    }
    /* Put constraint bounds. */
    for (i,&bki,&bli,&bui) in izip!(0..numcon,bkc,blc,buc) {
        task.put_con_bound(i, bki, bli, bui)?;
    }

    /* Put variable bounds. */
    for (j,&bki,&bli,&bui) in izip!(0..numvar,bkx,blx,bux) {
        task.put_var_bound(j, bki, bli, bui)?;
    }

    /* Put A. */
    if numcon > 0 {
        for (j,&asubj,&avalj) in izip!(0..numvar,asub,aval) {
            task.put_a_col(j,
                           asubj,
                           avalj)?;
        }
    }

    /* A maximization problem */
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    /* Solve the problem */
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /****************** Make a change to the A matrix ******************/
    task.put_aij(0, 0, 3.0)?;
    let _trm = task.optimize()?;
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /***************** Add a new variable ******************************/
    /* Get index of new variable. */

    let varidx = task.get_num_var()?;

    /* Append a new variable x_3 to the problem */
    task.append_vars(1)?;
    let numvar = numvar + 1;

    /* Set bounds on new varaible */
    task.put_var_bound(varidx, Boundkey::LO, 0.0, INF)?;

    /* Change objective */
    task.put_c_j(varidx, 1.0)?;

    /* Put new values in the A matrix */
    let acolsub = &[0i32, 2];
    let acolval = &[4.0, 1.0];

    task.put_a_col(varidx, /* column index */
                   acolsub,
                   acolval)?;

    /* Change optimizer to simplex free and reoptimize */
    task.put_int_param(mosek::Iparam::OPTIMIZER, mosek::Optimizertype::FREE_SIMPLEX)?;
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Add a new constraint ***************************/
    /* Get index of new constraint. */
    let conidx = task.get_num_con()?;

    /* Append a new constraint */
    task.append_cons(1)?;
    let numcon = numcon + 1;

    /* Set bounds on new constraint */
    task.put_con_bound(conidx,
                       Boundkey::UP,
                       -INF,
                       30000.0)?;

    /* Put new values in the A matrix */
    let arowsub = &[0i32,   1,   2,   3  ];
    let arowval = &[1.0, 2.0, 1.0, 1.0 ];

    task.put_a_row(conidx, /* row index */
                   arowsub,
                   arowval)?;

    let _trm = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Change constraint bounds ********************/
    let newbkc = &[Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP];
    let newblc = &[-INF,
                   -INF,
                   -INF,
                   -INF];
    let newbuc = &[ 80000.0, 40000.0, 50000.0, 22000.0 ];

    task.put_con_bound_slice(0, numcon, newbkc, newblc, newbuc)?;

    let _ = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    Ok(())
}
source

pub fn primal_repair( &mut self, wlc_: &[f64], wuc_: &[f64], wlx_: &[f64], wux_: &[f64] ) -> Result<(), String>

Repairs a primal infeasible optimization problem by adjusting the bounds on the constraints and variables.

§Arguments
  • wlc_ Weights associated with relaxing lower bounds on the constraints.
  • wuc_ Weights associated with relaxing the upper bound on the constraints.
  • wlx_ Weights associated with relaxing the lower bounds of the variables.
  • wux_ Weights associated with relaxing the upper bounds of variables.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.primalrepair

source

pub fn primal_sensitivity( &mut self, subi_: &[i32], marki_: &[i32], subj_: &[i32], markj_: &[i32], leftpricei_: &mut [f64], rightpricei_: &mut [f64], leftrangei_: &mut [f64], rightrangei_: &mut [f64], leftpricej_: &mut [f64], rightpricej_: &mut [f64], leftrangej_: &mut [f64], rightrangej_: &mut [f64] ) -> Result<(), String>

Perform sensitivity analysis on bounds.

§Arguments
  • subi_ Indexes of constraints to analyze.

  • marki_ Mark which constraint bounds to analyze.

    See Mark

  • subj_ Indexes of variables to analyze.

  • markj_ Mark which variable bounds to analyze.

    See Mark

  • leftpricei_ Left shadow price for constraints.

  • rightpricei_ Right shadow price for constraints.

  • leftrangei_ Left range for constraints.

  • rightrangei_ Right range for constraints.

  • leftpricej_ Left shadow price for variables.

  • rightpricej_ Right shadow price for variables.

  • leftrangej_ Left range for variables.

  • rightrangej_ Right range for variables.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.primalsensitivity

source

pub fn print_param(&self) -> Result<(), String>

Prints the current parameter settings.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.printparam

source

pub fn put_acc( &mut self, accidx_: i64, domidx_: i64, afeidxlist_: &[i64], b_: &[f64] ) -> Result<(), String>

Puts an affine conic constraint.

§Arguments
  • accidx_ Affine conic constraint index.
  • domidx_ Domain index.
  • afeidxlist_ List of affine expression indexes.
  • b_ The vector of constant terms modifying affine expressions. Optional.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putacc

source

pub fn put_acc_b(&mut self, accidx_: i64, b_: &[f64]) -> Result<(), String>

Puts the constant vector b in an affine conic constraint.

§Arguments
  • accidx_ Affine conic constraint index.
  • b_ The vector of constant terms modifying affine expressions. Optional.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putaccb

source

pub fn put_acc_b_j( &mut self, accidx_: i64, j_: i64, bj_: f64 ) -> Result<(), String>

Sets one element in the b vector of an affine conic constraint.

§Arguments
  • accidx_ Affine conic constraint index.
  • j_ The index of an element in b to change.
  • bj_ The new value of b[j].

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putaccbj

source

pub fn put_acc_dot_y( &self, whichsol_: i32, accidx_: i64, doty_: &mut [f64] ) -> Result<(), String>

Puts the doty vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • accidx_ The index of the affine conic constraint.

  • doty_ The dual values for this affine conic constraint. The array should have length equal to the dimension of the constraint.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putaccdoty

source

pub fn put_acc_list( &mut self, accidxs_: &[i64], domidxs_: &[i64], afeidxlist_: &[i64], b_: &[f64] ) -> Result<(), String>

Puts a number of affine conic constraints.

§Arguments
  • accidxs_ Affine conic constraint indices.
  • domidxs_ Domain indices.
  • afeidxlist_ List of affine expression indexes.
  • b_ The vector of constant terms modifying affine expressions. Optional.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putacclist

source

pub fn put_acc_name(&mut self, accidx_: i64, name_: &str) -> Result<(), String>

Sets the name of an affine conic constraint.

§Arguments
  • accidx_ Index of the affine conic constraint.
  • name_ The name of the affine conic constraint.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putaccname

Examples found in repository?
examples/portfolio_2_frontier.rs (line 88)
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
fn portfolio(n : i32,
             mu : &[f64],
             GT : &[f64],
             x0  : &[f64],
             alphas : &[f64],
             w : f64) -> Result<Vec<(f64,f64)>,String> {
    let k = (GT.len() / n as usize) as i32;
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(t) => t,
        None => return Err("Failed to create task".to_string()),
    };
    //task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    task.append_vars(n+1)?;
    task.append_cons(1)?;

    /* Objective */
    task.put_obj_sense(Objsense::MAXIMIZE)?;

    let x : Vec<i32> = (0i32..n).collect();
    let s = n;

    /* Total budget */
    let total_budget = w + x0.iter().sum::<f64>();

    /* Total budget constraint - set bounds l^c = u^c */
    task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
    task.put_con_name(0i32,"budget")?;
    task.put_c_slice(0,n,mu)?;

    /* x variables. */
    for (j,xj) in x.iter().enumerate() {
        /* Coefficients in the first row of A */
        task.put_aij(0, *xj, 1.0)?;
        /* No short-selling - x^l = 0, x^u = inf */
        task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
        task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
    }
    task.put_var_name(s, "s")?;
    task.put_var_bound(s, mosek::Boundkey::FR, 0.0, 0.0)?;

    // risk bound
    // (s,0.5,GT * x) in Q_r
    {
        let acci = task.get_num_acc()?;
        let afei = task.get_num_afe()?;

        task.append_afes(k as i64 + 2)?;
        let dom = task.append_r_quadratic_cone_domain(k as i64+2)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 2].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_f_entry(afei,s,1.0)?;
        task.put_afe_g(afei+1,0.5)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 2, j as i32, *v)?;
        }
    }

    let frontier : Vec<(f64,f64)> = alphas.iter().filter_map(|alpha| {
        /* Sets the objective function coefficient for s. */
        if      let Err(_) = task.put_c_j(s, - *alpha) { None }
        else if let Err(_) = task.optimize() { None }
        else if let Err(_) = task.write_data(format!("portfolio_2_frontier-{}.ptf",alpha).as_str()) { None }
        else if let Ok(solsta) = task.get_sol_sta(Soltype::ITR) {
            // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
            match solsta {
                Solsta::OPTIMAL => {
                    let mut xx = vec![0.0; n as usize+1];
                    if let Err(_) = task.get_xx(Soltype::ITR,xx.as_mut_slice()) { None }
                    else {
                        Some((*alpha,mu.iter().zip(xx.iter()).map(|(m,x)| m * x).sum::<f64>()))
                    }
                }
                _ => None
            }
        }
        else {
            None
        }
    }).collect();

    Ok(frontier)
}
More examples
Hide additional examples
examples/portfolio_5_card.rs (line 141)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
source

pub fn put_a_col( &mut self, j_: i32, subj_: &[i32], valj_: &[f64] ) -> Result<(), String>

Replaces all elements in one column of the linear constraint matrix.

§Arguments
  • j_ Column index.
  • subj_ Row indexes of non-zero values in column.
  • valj_ New non-zero values of column.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putacol

Examples found in repository?
examples/reoptimization.rs (lines 73-75)
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
fn main() -> Result<(),String> {

    let numcon = 3;
    let numvar = 3;
    let c = &[1.5, 2.5, 3.0 ];
    let bkc = &[ Boundkey::UP,
                 Boundkey::UP,
                 Boundkey::UP ];
    let blc = &[ -INF,
                 -INF,
                 -INF ];
    let buc = &[ 100000.0,
                 50000.0,
                 60000.0 ];
    let bkx = &[ Boundkey::LO,
                 Boundkey::LO,
                 Boundkey::LO
                             ];
    let blx = &[ 0.0, 0.0, 0.0 ];
    let bux = &[ INF,
                 INF,
                 INF ];

    let asub = &[
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ] ];

    let aval = &[
        &[ 2.0, 3.0, 2.0 ],
        &[ 4.0, 2.0, 3.0 ],
        &[ 3.0, 3.0, 2.0 ] ];


    let mut task = Task::new().unwrap();
    /* Append the constraints. */
    task.append_cons(numcon)?;

    /* Append the variables. */
    task.append_vars(numvar)?;

    /* Put C. */
    for (j,&cj) in (0..numvar).zip(c.iter()) {
        task.put_c_j(j,cj)?;
    }
    /* Put constraint bounds. */
    for (i,&bki,&bli,&bui) in izip!(0..numcon,bkc,blc,buc) {
        task.put_con_bound(i, bki, bli, bui)?;
    }

    /* Put variable bounds. */
    for (j,&bki,&bli,&bui) in izip!(0..numvar,bkx,blx,bux) {
        task.put_var_bound(j, bki, bli, bui)?;
    }

    /* Put A. */
    if numcon > 0 {
        for (j,&asubj,&avalj) in izip!(0..numvar,asub,aval) {
            task.put_a_col(j,
                           asubj,
                           avalj)?;
        }
    }

    /* A maximization problem */
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    /* Solve the problem */
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /****************** Make a change to the A matrix ******************/
    task.put_aij(0, 0, 3.0)?;
    let _trm = task.optimize()?;
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /***************** Add a new variable ******************************/
    /* Get index of new variable. */

    let varidx = task.get_num_var()?;

    /* Append a new variable x_3 to the problem */
    task.append_vars(1)?;
    let numvar = numvar + 1;

    /* Set bounds on new varaible */
    task.put_var_bound(varidx, Boundkey::LO, 0.0, INF)?;

    /* Change objective */
    task.put_c_j(varidx, 1.0)?;

    /* Put new values in the A matrix */
    let acolsub = &[0i32, 2];
    let acolval = &[4.0, 1.0];

    task.put_a_col(varidx, /* column index */
                   acolsub,
                   acolval)?;

    /* Change optimizer to simplex free and reoptimize */
    task.put_int_param(mosek::Iparam::OPTIMIZER, mosek::Optimizertype::FREE_SIMPLEX)?;
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Add a new constraint ***************************/
    /* Get index of new constraint. */
    let conidx = task.get_num_con()?;

    /* Append a new constraint */
    task.append_cons(1)?;
    let numcon = numcon + 1;

    /* Set bounds on new constraint */
    task.put_con_bound(conidx,
                       Boundkey::UP,
                       -INF,
                       30000.0)?;

    /* Put new values in the A matrix */
    let arowsub = &[0i32,   1,   2,   3  ];
    let arowval = &[1.0, 2.0, 1.0, 1.0 ];

    task.put_a_row(conidx, /* row index */
                   arowsub,
                   arowval)?;

    let _trm = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Change constraint bounds ********************/
    let newbkc = &[Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP];
    let newblc = &[-INF,
                   -INF,
                   -INF,
                   -INF];
    let newbuc = &[ 80000.0, 40000.0, 50000.0, 22000.0 ];

    task.put_con_bound_slice(0, numcon, newbkc, newblc, newbuc)?;

    let _ = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    Ok(())
}
More examples
Hide additional examples
examples/milo1.rs (lines 59-61)
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
fn main() -> Result<(),String> {
    let numcon : i32 = 2;
    let numvar : i32 = 2;

    let infinity = 0.0; // only for symbolic purposes, value never used

    let bkc = vec![Boundkey::UP, Boundkey::LO];
    let blc = vec![ -infinity,         -4.0 ];
    let buc = vec![ 250.0,             infinity ];

    let bkx = vec![ Boundkey::LO, Boundkey::LO  ];
    let blx = vec![ 0.0,               0.0 ];
    let bux = vec![ infinity,          infinity ];

    let c   = vec![1.0, 0.64];

    let asub = vec![0,   1,
                    0,    1];
    let aval = vec![50.0, 3.0, 31.0, -2.0];

    let ptrb : Vec<usize> = vec![ 0, 2 ];
    let ptre : Vec<usize> = vec![ 2, 4 ];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG,
            &mut |msg| print!("{}",msg),
            |task| task.with_itg_sol_callback(
                &mut |xx| { println!("Found a new solution = {:?}",xx); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                    The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                    /* Append 'numvar' variables.
                    The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    for ((((j,cj),bk),bl),bu) in (0..numvar).zip(c.iter()).zip(bkx.iter()).zip(blx.iter()).zip(bux.iter()) {
                        /* Set the linear term c_j in the objective.*/
                        task.put_c_j(j, *cj)?;
                        /* Set the bounds on variable j.
                           blx[j] <= x_j <= bux[j] */
                        task.put_var_bound(j, *bk, *bl, *bu)?;
                        /* Input column j of A */
                        task.put_a_col(j,                     /* Variable (column) index.*/
                                       &asub[ptrb[j as usize]..ptre[j as usize]],               /* Row index of non-zeros in column j.*/
                                       &aval[ptrb[j as usize]..ptre[j as usize]])?;              /* Non-zero Values of column j. */
                    }
                    // Set the bounds on constraints.
                    // for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] 
                    for (((i,bk),bl),bu) in (0..numcon).zip(bkc.iter()).zip(blc.iter()).zip(buc.iter()) {
                        task.put_con_bound(i, *bk, *bl, *bu)?;
                    }

                    /* Specify integer variables. */
                    for j in 0..numvar {
                        task.put_var_type(j, Variabletype::TYPE_INT)?;
                    }
                    /* Set max solution time */
                    task.put_dou_param(Dparam::MIO_MAX_TIME, 60.0)?;

                    /* A maximization problem */
                    task.put_obj_sense(Objsense::MAXIMIZE)?;
                    /* Solve the problem */

                    let _trm = task.optimize()?;

                    // Print a summary containing information
                    //   about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITG, xx.as_mut_slice())?;

                    /* Get status information about the solution */

                    match task.get_sol_sta(Soltype::ITG)? {
                        Solsta::INTEGER_OPTIMAL => {
                            println!("Optimal solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::PRIM_FEAS => {
                            println!("Feasible solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::UNKNOWN => {
                          match task.get_pro_sta(Soltype::ITG)? {
                              Prosta::PRIM_INFEAS_OR_UNBOUNDED => {
                                  println!("Problem status Infeasible or unbounded");
                              }
                              Prosta::PRIM_INFEAS => {
                                  println!("Problem status Infeasible.");
                              }
                              Prosta::UNKNOWN => {
                                  println!("Problem status unknown.");
                              }
                              _ => {
                                  println!("Other problem status.");
                              }
                          }
                        }
                        _ => {
                            println!("Other solution status");
                        }
                    }
                    Ok(())
                }))
}
source

pub fn put_a_col_list( &mut self, sub_: &[i32], ptrb_: &[i64], ptre_: &[i64], asub_: &[i32], aval_: &[f64] ) -> Result<(), String>

Replaces all elements in several columns the linear constraint matrix.

§Arguments
  • sub_ Indexes of columns that should be replaced.
  • ptrb_ Array of pointers to the first element in the columns.
  • ptre_ Array of pointers to the last element plus one in the columns.
  • asub_ Row indexes
  • aval_ Coefficient values.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putacollist64

source

pub fn put_a_col_slice( &mut self, first_: i32, last_: i32, ptrb_: &[i64], ptre_: &[i64], asub_: &[i32], aval_: &[f64] ) -> Result<(), String>

Replaces all elements in a sequence of columns the linear constraint matrix.

§Arguments
  • first_ First column in the slice.
  • last_ Last column plus one in the slice.
  • ptrb_ Array of pointers to the first element in the columns.
  • ptre_ Array of pointers to the last element plus one in the columns.
  • asub_ Row indexes
  • aval_ Coefficient values.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putacolslice64

Examples found in repository?
examples/solvelinear.rs (line 44)
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
fn setup(task : & mut mosek::Task,
         aval : &[f64],
         asub : &[i32],
         ptrb : &[i64],
         ptre : &[i64],
         numvar : i32) -> Result<Vec<i32>,String> {

    // mosek.stakey[] skx = new mosek.stakey [numvar];
    // mosek.stakey[] skc = new mosek.stakey [numvar];

    // for (int i = 0; i < numvar ; ++i) {
    //   skx[i] = mosek.stakey.bas;
    //   skc[i] = mosek.stakey.fix;
    // }

    task.append_vars(numvar)?;
    task.append_cons(numvar)?;

    task.put_a_col_slice(0,numvar,ptrb,ptre,asub,aval)?;

    task.put_con_bound_slice_const(0,numvar,Boundkey::FX,0.0,0.0)?;
    task.put_var_bound_slice_const(0,numvar,Boundkey::FR,-INF,INF)?;

    /* Define a basic solution by specifying
       status keys for variables & constraints. */
    task.delete_solution(Soltype::BAS)?;

    task.put_skc_slice(Soltype::BAS, 0, numvar, vec![Stakey::FIX; numvar as usize].as_slice())?;
    task.put_skx_slice(Soltype::BAS, 0, numvar, vec![Stakey::BAS; numvar as usize].as_slice())?;

    let mut basis = vec![0; numvar as usize];
    task.init_basis_solve(basis.as_mut_slice())?;
    Ok(basis)
  }
source

pub fn put_afe_barf_block_triplet( &mut self, afeidx_: &[i64], barvaridx_: &[i32], subk_: &[i32], subl_: &[i32], valkl_: &[f64] ) -> Result<(), String>

Inputs barF in block triplet form.

§Arguments
  • afeidx_ Constraint index.
  • barvaridx_ Symmetric matrix variable index.
  • subk_ Block row index.
  • subl_ Block column index.
  • valkl_ The numerical value associated with each block triplet.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putafebarfblocktriplet

source

pub fn put_afe_barf_entry( &mut self, afeidx_: i64, barvaridx_: i32, termidx_: &[i64], termweight_: &[f64] ) -> Result<(), String>

Inputs one entry in barF.

§Arguments
  • afeidx_ Row index of barF.
  • barvaridx_ Semidefinite variable index.
  • termidx_ Element indices in matrix storage.
  • termweight_ Weights in the weighted sum.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putafebarfentry

source

pub fn put_afe_barf_entry_list( &mut self, afeidx_: &[i64], barvaridx_: &[i32], numterm_: &[i64], ptrterm_: &[i64], termidx_: &[i64], termweight_: &[f64] ) -> Result<(), String>

Inputs a list of entries in barF.

§Arguments
  • afeidx_ Row indexes of barF.
  • barvaridx_ Semidefinite variable indexes.
  • numterm_ Number of terms in the weighted sums.
  • ptrterm_ Pointer to the terms forming each entry.
  • termidx_ Concatenated element indexes in matrix storage.
  • termweight_ Concatenated weights in the weighted sum.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putafebarfentrylist

source

pub fn put_afe_barf_row( &mut self, afeidx_: i64, barvaridx_: &[i32], numterm_: &[i64], ptrterm_: &[i64], termidx_: &[i64], termweight_: &[f64] ) -> Result<(), String>

Inputs a row of barF.

§Arguments
  • afeidx_ Row index of barF.
  • barvaridx_ Semidefinite variable indexes.
  • numterm_ Number of terms in the weighted sums.
  • ptrterm_ Pointer to the terms forming each entry.
  • termidx_ Concatenated element indexes in matrix storage.
  • termweight_ Concatenated weights in the weighted sum.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putafebarfrow

source

pub fn put_afe_f_col( &mut self, varidx_: i32, afeidx_: &[i64], val_: &[f64] ) -> Result<(), String>

Replaces all elements in one column of the F matrix in the affine expressions.

§Arguments
  • varidx_ Column index.
  • afeidx_ Row indexes of non-zero values in the column.
  • val_ New non-zero values in the column.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putafefcol

source

pub fn put_afe_f_entry( &mut self, afeidx_: i64, varidx_: i32, value_: f64 ) -> Result<(), String>

Replaces one entry in F.

§Arguments
  • afeidx_ Row index in F.
  • varidx_ Column index in F.
  • value_ Value of the entry.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putafefentry

Examples found in repository?
examples/portfolio_2_frontier.rs (line 89)
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
fn portfolio(n : i32,
             mu : &[f64],
             GT : &[f64],
             x0  : &[f64],
             alphas : &[f64],
             w : f64) -> Result<Vec<(f64,f64)>,String> {
    let k = (GT.len() / n as usize) as i32;
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(t) => t,
        None => return Err("Failed to create task".to_string()),
    };
    //task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    task.append_vars(n+1)?;
    task.append_cons(1)?;

    /* Objective */
    task.put_obj_sense(Objsense::MAXIMIZE)?;

    let x : Vec<i32> = (0i32..n).collect();
    let s = n;

    /* Total budget */
    let total_budget = w + x0.iter().sum::<f64>();

    /* Total budget constraint - set bounds l^c = u^c */
    task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
    task.put_con_name(0i32,"budget")?;
    task.put_c_slice(0,n,mu)?;

    /* x variables. */
    for (j,xj) in x.iter().enumerate() {
        /* Coefficients in the first row of A */
        task.put_aij(0, *xj, 1.0)?;
        /* No short-selling - x^l = 0, x^u = inf */
        task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
        task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
    }
    task.put_var_name(s, "s")?;
    task.put_var_bound(s, mosek::Boundkey::FR, 0.0, 0.0)?;

    // risk bound
    // (s,0.5,GT * x) in Q_r
    {
        let acci = task.get_num_acc()?;
        let afei = task.get_num_afe()?;

        task.append_afes(k as i64 + 2)?;
        let dom = task.append_r_quadratic_cone_domain(k as i64+2)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 2].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_f_entry(afei,s,1.0)?;
        task.put_afe_g(afei+1,0.5)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 2, j as i32, *v)?;
        }
    }

    let frontier : Vec<(f64,f64)> = alphas.iter().filter_map(|alpha| {
        /* Sets the objective function coefficient for s. */
        if      let Err(_) = task.put_c_j(s, - *alpha) { None }
        else if let Err(_) = task.optimize() { None }
        else if let Err(_) = task.write_data(format!("portfolio_2_frontier-{}.ptf",alpha).as_str()) { None }
        else if let Ok(solsta) = task.get_sol_sta(Soltype::ITR) {
            // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
            match solsta {
                Solsta::OPTIMAL => {
                    let mut xx = vec![0.0; n as usize+1];
                    if let Err(_) = task.get_xx(Soltype::ITR,xx.as_mut_slice()) { None }
                    else {
                        Some((*alpha,mu.iter().zip(xx.iter()).map(|(m,x)| m * x).sum::<f64>()))
                    }
                }
                _ => None
            }
        }
        else {
            None
        }
    }).collect();

    Ok(frontier)
}
More examples
Hide additional examples
examples/portfolio_5_card.rs (line 145)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
source

pub fn put_afe_f_entry_list( &mut self, afeidx_: &[i64], varidx_: &[i32], val_: &[f64] ) -> Result<(), String>

Replaces a list of entries in F.

§Arguments
  • afeidx_ Row indices in F.
  • varidx_ Column indices in F.
  • val_ Values of the entries in F.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putafefentrylist

source

pub fn put_afe_f_row( &mut self, afeidx_: i64, varidx_: &[i32], val_: &[f64] ) -> Result<(), String>

Replaces all elements in one row of the F matrix in the affine expressions.

§Arguments
  • afeidx_ Row index.
  • varidx_ Column indexes of non-zero values in the row.
  • val_ New non-zero values in the row.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putafefrow

source

pub fn put_afe_f_row_list( &mut self, afeidx_: &[i64], numnzrow_: &[i32], ptrrow_: &[i64], varidx_: &[i32], val_: &[f64] ) -> Result<(), String>

Replaces all elements in a number of rows of the F matrix in the affine expressions.

§Arguments
  • afeidx_ Row indices.
  • numnzrow_ Number of non-zeros in each row.
  • ptrrow_ Pointer to the first nonzero in each row.
  • varidx_ Column indexes of non-zero values.
  • val_ New non-zero values in the rows.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putafefrowlist

Examples found in repository?
examples/ceo1.rs (lines 70-74)
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
fn main() -> Result<(),String> {
    let numcon = 1;
    let numvar = 3;

    let bkc = mosek::Boundkey::FX;
    let blc = 1.0;
    let buc = 1.0;

    let bkx = vec![ Boundkey::FR,
                    Boundkey::FR,
                    Boundkey::FR ];
    let blx = vec![ -INF, -INF, -INF ];
    let bux = vec![ INF, INF, INF ];
    let c   = vec![ 1.0, 1.0, 0.0 ];
    let a   = vec![ 1.0, 1.0, 1.0 ];
    let asub = vec![0, 1, 2];
    //let csub = new int[numvar];
    //double[] xx  = new double[numvar];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG, 
            &mut|msg| print!("{}",msg),
            |task| task.with_callback(
                &mut |caller| { println!("caller = {}",caller); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                       The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                      /* Append 'numvar' variables.
                         The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    /* Define the linear part of the problem */
                    task.put_c_slice(0, numvar, c.as_slice())?;
                    task.put_a_row(0, asub.as_slice(), a.as_slice())?;
                    task.put_con_bound(0, bkc, blc, buc)?;
                    task.put_var_bound_slice(0, numvar, bkx.as_slice(), blx.as_slice(), bux.as_slice())?;

                    /* Add a conic constraint */
                    task.append_afes(3)?;
                    let afeidxs = vec![0,  1,  2  ];
                    let b       = vec![0.0,0.0,0.0];
                    let domidx  = task.append_primal_exp_cone_domain()?;
                    task.put_afe_f_row_list(afeidxs.as_slice(),
                                            vec![1,1,1].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![1.0,1.0,1.0].as_slice())?;
                    task.append_acc(domidx,afeidxs.as_slice(),b.as_slice())?;

                    task.put_obj_sense(Objsense::MINIMIZE)?;

                    println!("optimize");
                    /* Solve the problem */
                    task.optimize()?;
                    // Print a summary containing information
                    // about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    /* Get status information about the solution */
                    let solsta = task.get_sol_sta(Soltype::ITR)?;

                    assert!(solsta == Solsta::OPTIMAL);
                    
                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITR, & mut xx[..])?;
                    
                    println!("Optimal primal solution");
                    for j in 0..numvar as usize {
                        println!("x[{}]: {:.4}",j,xx[j]);
                    }
                    Ok(())
                }))
}
source

pub fn put_afe_g(&mut self, afeidx_: i64, g_: f64) -> Result<(), String>

Replaces one element in the g vector in the affine expressions.

§Arguments
  • afeidx_ Row index.
  • g_ New value for the element of g.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putafeg

Examples found in repository?
examples/portfolio_2_frontier.rs (line 90)
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
fn portfolio(n : i32,
             mu : &[f64],
             GT : &[f64],
             x0  : &[f64],
             alphas : &[f64],
             w : f64) -> Result<Vec<(f64,f64)>,String> {
    let k = (GT.len() / n as usize) as i32;
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(t) => t,
        None => return Err("Failed to create task".to_string()),
    };
    //task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    task.append_vars(n+1)?;
    task.append_cons(1)?;

    /* Objective */
    task.put_obj_sense(Objsense::MAXIMIZE)?;

    let x : Vec<i32> = (0i32..n).collect();
    let s = n;

    /* Total budget */
    let total_budget = w + x0.iter().sum::<f64>();

    /* Total budget constraint - set bounds l^c = u^c */
    task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
    task.put_con_name(0i32,"budget")?;
    task.put_c_slice(0,n,mu)?;

    /* x variables. */
    for (j,xj) in x.iter().enumerate() {
        /* Coefficients in the first row of A */
        task.put_aij(0, *xj, 1.0)?;
        /* No short-selling - x^l = 0, x^u = inf */
        task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
        task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
    }
    task.put_var_name(s, "s")?;
    task.put_var_bound(s, mosek::Boundkey::FR, 0.0, 0.0)?;

    // risk bound
    // (s,0.5,GT * x) in Q_r
    {
        let acci = task.get_num_acc()?;
        let afei = task.get_num_afe()?;

        task.append_afes(k as i64 + 2)?;
        let dom = task.append_r_quadratic_cone_domain(k as i64+2)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 2].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_f_entry(afei,s,1.0)?;
        task.put_afe_g(afei+1,0.5)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 2, j as i32, *v)?;
        }
    }

    let frontier : Vec<(f64,f64)> = alphas.iter().filter_map(|alpha| {
        /* Sets the objective function coefficient for s. */
        if      let Err(_) = task.put_c_j(s, - *alpha) { None }
        else if let Err(_) = task.optimize() { None }
        else if let Err(_) = task.write_data(format!("portfolio_2_frontier-{}.ptf",alpha).as_str()) { None }
        else if let Ok(solsta) = task.get_sol_sta(Soltype::ITR) {
            // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
            match solsta {
                Solsta::OPTIMAL => {
                    let mut xx = vec![0.0; n as usize+1];
                    if let Err(_) = task.get_xx(Soltype::ITR,xx.as_mut_slice()) { None }
                    else {
                        Some((*alpha,mu.iter().zip(xx.iter()).map(|(m,x)| m * x).sum::<f64>()))
                    }
                }
                _ => None
            }
        }
        else {
            None
        }
    }).collect();

    Ok(frontier)
}
More examples
Hide additional examples
examples/portfolio_5_card.rs (line 142)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
source

pub fn put_afe_g_list( &mut self, afeidx_: &[i64], g_: &[f64] ) -> Result<(), String>

Replaces a list of elements in the g vector in the affine expressions.

§Arguments
  • afeidx_ Indices of entries in g.
  • g_ New values for the elements of g.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putafeglist

source

pub fn put_afe_g_slice( &mut self, first_: i64, last_: i64, slice_: &[f64] ) -> Result<(), String>

Modifies a slice of the vector g.

§Arguments
  • first_ First index in the sequence.
  • last_ Last index plus 1 in the sequence.
  • slice_ The slice of g as a dense vector.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putafegslice

source

pub fn put_aij(&mut self, i_: i32, j_: i32, aij_: f64) -> Result<(), String>

Changes a single value in the linear coefficient matrix.

§Arguments
  • i_ Constraint (row) index.
  • j_ Variable (column) index.
  • aij_ New coefficient.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putaij

Examples found in repository?
examples/portfolio_2_frontier.rs (line 69)
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
fn portfolio(n : i32,
             mu : &[f64],
             GT : &[f64],
             x0  : &[f64],
             alphas : &[f64],
             w : f64) -> Result<Vec<(f64,f64)>,String> {
    let k = (GT.len() / n as usize) as i32;
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(t) => t,
        None => return Err("Failed to create task".to_string()),
    };
    //task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    task.append_vars(n+1)?;
    task.append_cons(1)?;

    /* Objective */
    task.put_obj_sense(Objsense::MAXIMIZE)?;

    let x : Vec<i32> = (0i32..n).collect();
    let s = n;

    /* Total budget */
    let total_budget = w + x0.iter().sum::<f64>();

    /* Total budget constraint - set bounds l^c = u^c */
    task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
    task.put_con_name(0i32,"budget")?;
    task.put_c_slice(0,n,mu)?;

    /* x variables. */
    for (j,xj) in x.iter().enumerate() {
        /* Coefficients in the first row of A */
        task.put_aij(0, *xj, 1.0)?;
        /* No short-selling - x^l = 0, x^u = inf */
        task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
        task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
    }
    task.put_var_name(s, "s")?;
    task.put_var_bound(s, mosek::Boundkey::FR, 0.0, 0.0)?;

    // risk bound
    // (s,0.5,GT * x) in Q_r
    {
        let acci = task.get_num_acc()?;
        let afei = task.get_num_afe()?;

        task.append_afes(k as i64 + 2)?;
        let dom = task.append_r_quadratic_cone_domain(k as i64+2)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 2].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_f_entry(afei,s,1.0)?;
        task.put_afe_g(afei+1,0.5)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 2, j as i32, *v)?;
        }
    }

    let frontier : Vec<(f64,f64)> = alphas.iter().filter_map(|alpha| {
        /* Sets the objective function coefficient for s. */
        if      let Err(_) = task.put_c_j(s, - *alpha) { None }
        else if let Err(_) = task.optimize() { None }
        else if let Err(_) = task.write_data(format!("portfolio_2_frontier-{}.ptf",alpha).as_str()) { None }
        else if let Ok(solsta) = task.get_sol_sta(Soltype::ITR) {
            // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
            match solsta {
                Solsta::OPTIMAL => {
                    let mut xx = vec![0.0; n as usize+1];
                    if let Err(_) = task.get_xx(Soltype::ITR,xx.as_mut_slice()) { None }
                    else {
                        Some((*alpha,mu.iter().zip(xx.iter()).map(|(m,x)| m * x).sum::<f64>()))
                    }
                }
                _ => None
            }
        }
        else {
            None
        }
    }).collect();

    Ok(frontier)
}
More examples
Hide additional examples
examples/reoptimization.rs (line 93)
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
fn main() -> Result<(),String> {

    let numcon = 3;
    let numvar = 3;
    let c = &[1.5, 2.5, 3.0 ];
    let bkc = &[ Boundkey::UP,
                 Boundkey::UP,
                 Boundkey::UP ];
    let blc = &[ -INF,
                 -INF,
                 -INF ];
    let buc = &[ 100000.0,
                 50000.0,
                 60000.0 ];
    let bkx = &[ Boundkey::LO,
                 Boundkey::LO,
                 Boundkey::LO
                             ];
    let blx = &[ 0.0, 0.0, 0.0 ];
    let bux = &[ INF,
                 INF,
                 INF ];

    let asub = &[
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ] ];

    let aval = &[
        &[ 2.0, 3.0, 2.0 ],
        &[ 4.0, 2.0, 3.0 ],
        &[ 3.0, 3.0, 2.0 ] ];


    let mut task = Task::new().unwrap();
    /* Append the constraints. */
    task.append_cons(numcon)?;

    /* Append the variables. */
    task.append_vars(numvar)?;

    /* Put C. */
    for (j,&cj) in (0..numvar).zip(c.iter()) {
        task.put_c_j(j,cj)?;
    }
    /* Put constraint bounds. */
    for (i,&bki,&bli,&bui) in izip!(0..numcon,bkc,blc,buc) {
        task.put_con_bound(i, bki, bli, bui)?;
    }

    /* Put variable bounds. */
    for (j,&bki,&bli,&bui) in izip!(0..numvar,bkx,blx,bux) {
        task.put_var_bound(j, bki, bli, bui)?;
    }

    /* Put A. */
    if numcon > 0 {
        for (j,&asubj,&avalj) in izip!(0..numvar,asub,aval) {
            task.put_a_col(j,
                           asubj,
                           avalj)?;
        }
    }

    /* A maximization problem */
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    /* Solve the problem */
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /****************** Make a change to the A matrix ******************/
    task.put_aij(0, 0, 3.0)?;
    let _trm = task.optimize()?;
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /***************** Add a new variable ******************************/
    /* Get index of new variable. */

    let varidx = task.get_num_var()?;

    /* Append a new variable x_3 to the problem */
    task.append_vars(1)?;
    let numvar = numvar + 1;

    /* Set bounds on new varaible */
    task.put_var_bound(varidx, Boundkey::LO, 0.0, INF)?;

    /* Change objective */
    task.put_c_j(varidx, 1.0)?;

    /* Put new values in the A matrix */
    let acolsub = &[0i32, 2];
    let acolval = &[4.0, 1.0];

    task.put_a_col(varidx, /* column index */
                   acolsub,
                   acolval)?;

    /* Change optimizer to simplex free and reoptimize */
    task.put_int_param(mosek::Iparam::OPTIMIZER, mosek::Optimizertype::FREE_SIMPLEX)?;
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Add a new constraint ***************************/
    /* Get index of new constraint. */
    let conidx = task.get_num_con()?;

    /* Append a new constraint */
    task.append_cons(1)?;
    let numcon = numcon + 1;

    /* Set bounds on new constraint */
    task.put_con_bound(conidx,
                       Boundkey::UP,
                       -INF,
                       30000.0)?;

    /* Put new values in the A matrix */
    let arowsub = &[0i32,   1,   2,   3  ];
    let arowval = &[1.0, 2.0, 1.0, 1.0 ];

    task.put_a_row(conidx, /* row index */
                   arowsub,
                   arowval)?;

    let _trm = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Change constraint bounds ********************/
    let newbkc = &[Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP];
    let newblc = &[-INF,
                   -INF,
                   -INF,
                   -INF];
    let newbuc = &[ 80000.0, 40000.0, 50000.0, 22000.0 ];

    task.put_con_bound_slice(0, numcon, newbkc, newblc, newbuc)?;

    let _ = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    Ok(())
}
source

pub fn put_aij_list( &mut self, subi_: &[i32], subj_: &[i32], valij_: &[f64] ) -> Result<(), String>

Changes one or more coefficients in the linear constraint matrix.

§Arguments
  • subi_ Constraint (row) indices.
  • subj_ Variable (column) indices.
  • valij_ New coefficient values.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putaijlist64

Examples found in repository?
examples/pinfeas.rs (lines 21-23)
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
fn test_problem() -> Result<mosek::Task,String> {
    let mut task = mosek::Task::new().unwrap();
    task.append_vars(7)?;
    task.append_cons(7)?;
    task.put_c_list(&[0,1,2,3,4,5,6],
                    &[1.0,2.0,5.0,2.0,1.0,2.0,1.0])?;
    task.put_aij_list(&[0,0,1,1,2,2,2,3,3,4,5,5,6,6],
                      &[0,1,2,3,4,5,6,0,4,1,2,5,3,6],
                      &[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0])?;
    task.put_con_bound_slice(0, 7,
                             &[Boundkey::UP,Boundkey::UP,Boundkey::UP,Boundkey::FX,Boundkey::FX,Boundkey::FX,Boundkey::FX],
                             &[-INF, -INF, -INF, 1100.0, 200.0, 500.0, 500.0],
                             &[200.0, 1000.0, 1000.0, 1100.0, 200.0, 500.0, 500.0])?;
    task.put_var_bound_slice_const(0, 7, Boundkey::UP, 0.0, INF)?;
    Ok(task)
}
More examples
Hide additional examples
examples/portfolio_5_card.rs (line 114)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
source

pub fn put_a_row( &mut self, i_: i32, subi_: &[i32], vali_: &[f64] ) -> Result<(), String>

Replaces all elements in one row of the linear constraint matrix.

§Arguments
  • i_ Row index.
  • subi_ Column indexes of non-zero values in row.
  • vali_ New non-zero values of row.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putarow

Examples found in repository?
examples/ceo1.rs (line 61)
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
fn main() -> Result<(),String> {
    let numcon = 1;
    let numvar = 3;

    let bkc = mosek::Boundkey::FX;
    let blc = 1.0;
    let buc = 1.0;

    let bkx = vec![ Boundkey::FR,
                    Boundkey::FR,
                    Boundkey::FR ];
    let blx = vec![ -INF, -INF, -INF ];
    let bux = vec![ INF, INF, INF ];
    let c   = vec![ 1.0, 1.0, 0.0 ];
    let a   = vec![ 1.0, 1.0, 1.0 ];
    let asub = vec![0, 1, 2];
    //let csub = new int[numvar];
    //double[] xx  = new double[numvar];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG, 
            &mut|msg| print!("{}",msg),
            |task| task.with_callback(
                &mut |caller| { println!("caller = {}",caller); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                       The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                      /* Append 'numvar' variables.
                         The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    /* Define the linear part of the problem */
                    task.put_c_slice(0, numvar, c.as_slice())?;
                    task.put_a_row(0, asub.as_slice(), a.as_slice())?;
                    task.put_con_bound(0, bkc, blc, buc)?;
                    task.put_var_bound_slice(0, numvar, bkx.as_slice(), blx.as_slice(), bux.as_slice())?;

                    /* Add a conic constraint */
                    task.append_afes(3)?;
                    let afeidxs = vec![0,  1,  2  ];
                    let b       = vec![0.0,0.0,0.0];
                    let domidx  = task.append_primal_exp_cone_domain()?;
                    task.put_afe_f_row_list(afeidxs.as_slice(),
                                            vec![1,1,1].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![1.0,1.0,1.0].as_slice())?;
                    task.append_acc(domidx,afeidxs.as_slice(),b.as_slice())?;

                    task.put_obj_sense(Objsense::MINIMIZE)?;

                    println!("optimize");
                    /* Solve the problem */
                    task.optimize()?;
                    // Print a summary containing information
                    // about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    /* Get status information about the solution */
                    let solsta = task.get_sol_sta(Soltype::ITR)?;

                    assert!(solsta == Solsta::OPTIMAL);
                    
                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITR, & mut xx[..])?;
                    
                    println!("Optimal primal solution");
                    for j in 0..numvar as usize {
                        println!("x[{}]: {:.4}",j,xx[j]);
                    }
                    Ok(())
                }))
}
More examples
Hide additional examples
examples/reoptimization.rs (lines 154-156)
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
fn main() -> Result<(),String> {

    let numcon = 3;
    let numvar = 3;
    let c = &[1.5, 2.5, 3.0 ];
    let bkc = &[ Boundkey::UP,
                 Boundkey::UP,
                 Boundkey::UP ];
    let blc = &[ -INF,
                 -INF,
                 -INF ];
    let buc = &[ 100000.0,
                 50000.0,
                 60000.0 ];
    let bkx = &[ Boundkey::LO,
                 Boundkey::LO,
                 Boundkey::LO
                             ];
    let blx = &[ 0.0, 0.0, 0.0 ];
    let bux = &[ INF,
                 INF,
                 INF ];

    let asub = &[
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ] ];

    let aval = &[
        &[ 2.0, 3.0, 2.0 ],
        &[ 4.0, 2.0, 3.0 ],
        &[ 3.0, 3.0, 2.0 ] ];


    let mut task = Task::new().unwrap();
    /* Append the constraints. */
    task.append_cons(numcon)?;

    /* Append the variables. */
    task.append_vars(numvar)?;

    /* Put C. */
    for (j,&cj) in (0..numvar).zip(c.iter()) {
        task.put_c_j(j,cj)?;
    }
    /* Put constraint bounds. */
    for (i,&bki,&bli,&bui) in izip!(0..numcon,bkc,blc,buc) {
        task.put_con_bound(i, bki, bli, bui)?;
    }

    /* Put variable bounds. */
    for (j,&bki,&bli,&bui) in izip!(0..numvar,bkx,blx,bux) {
        task.put_var_bound(j, bki, bli, bui)?;
    }

    /* Put A. */
    if numcon > 0 {
        for (j,&asubj,&avalj) in izip!(0..numvar,asub,aval) {
            task.put_a_col(j,
                           asubj,
                           avalj)?;
        }
    }

    /* A maximization problem */
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    /* Solve the problem */
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /****************** Make a change to the A matrix ******************/
    task.put_aij(0, 0, 3.0)?;
    let _trm = task.optimize()?;
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /***************** Add a new variable ******************************/
    /* Get index of new variable. */

    let varidx = task.get_num_var()?;

    /* Append a new variable x_3 to the problem */
    task.append_vars(1)?;
    let numvar = numvar + 1;

    /* Set bounds on new varaible */
    task.put_var_bound(varidx, Boundkey::LO, 0.0, INF)?;

    /* Change objective */
    task.put_c_j(varidx, 1.0)?;

    /* Put new values in the A matrix */
    let acolsub = &[0i32, 2];
    let acolval = &[4.0, 1.0];

    task.put_a_col(varidx, /* column index */
                   acolsub,
                   acolval)?;

    /* Change optimizer to simplex free and reoptimize */
    task.put_int_param(mosek::Iparam::OPTIMIZER, mosek::Optimizertype::FREE_SIMPLEX)?;
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Add a new constraint ***************************/
    /* Get index of new constraint. */
    let conidx = task.get_num_con()?;

    /* Append a new constraint */
    task.append_cons(1)?;
    let numcon = numcon + 1;

    /* Set bounds on new constraint */
    task.put_con_bound(conidx,
                       Boundkey::UP,
                       -INF,
                       30000.0)?;

    /* Put new values in the A matrix */
    let arowsub = &[0i32,   1,   2,   3  ];
    let arowval = &[1.0, 2.0, 1.0, 1.0 ];

    task.put_a_row(conidx, /* row index */
                   arowsub,
                   arowval)?;

    let _trm = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Change constraint bounds ********************/
    let newbkc = &[Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP];
    let newblc = &[-INF,
                   -INF,
                   -INF,
                   -INF];
    let newbuc = &[ 80000.0, 40000.0, 50000.0, 22000.0 ];

    task.put_con_bound_slice(0, numcon, newbkc, newblc, newbuc)?;

    let _ = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    Ok(())
}
examples/portfolio_5_card.rs (lines 96-98)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
source

pub fn put_a_row_list( &mut self, sub_: &[i32], ptrb_: &[i64], ptre_: &[i64], asub_: &[i32], aval_: &[f64] ) -> Result<(), String>

Replaces all elements in several rows of the linear constraint matrix.

§Arguments
  • sub_ Indexes of rows or columns that should be replaced.
  • ptrb_ Array of pointers to the first element in the rows.
  • ptre_ Array of pointers to the last element plus one in the rows.
  • asub_ Variable indexes.
  • aval_ Coefficient values.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putarowlist64

source

pub fn put_a_row_slice( &mut self, first_: i32, last_: i32, ptrb_: &[i64], ptre_: &[i64], asub_: &[i32], aval_: &[f64] ) -> Result<(), String>

Replaces all elements in several rows the linear constraint matrix.

§Arguments
  • first_ First row in the slice.
  • last_ Last row plus one in the slice.
  • ptrb_ Array of pointers to the first element in the rows.
  • ptre_ Array of pointers to the last element plus one in the rows.
  • asub_ Column indexes of new elements.
  • aval_ Coefficient values.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putarowslice64

source

pub fn put_a_truncate_tol(&mut self, tolzero_: f64) -> Result<(), String>

Truncates all elements in A below a certain tolerance to zero.

§Arguments
  • tolzero_ Truncation tolerance.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putatruncatetol

source

pub fn put_bara_block_triplet( &mut self, subi_: &[i32], subj_: &[i32], subk_: &[i32], subl_: &[i32], valijkl_: &[f64] ) -> Result<(), String>

Inputs barA in block triplet form.

§Arguments
  • subi_ Constraint index.
  • subj_ Symmetric matrix variable index.
  • subk_ Block row index.
  • subl_ Block column index.
  • valijkl_ The numerical value associated with each block triplet.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putbarablocktriplet

source

pub fn put_bara_ij( &mut self, i_: i32, j_: i32, sub_: &[i64], weights_: &[f64] ) -> Result<(), String>

Inputs an element of barA.

§Arguments
  • i_ Row index of barA.
  • j_ Column index of barA.
  • sub_ Element indexes in matrix storage.
  • weights_ Weights in the weighted sum.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putbaraij

source

pub fn put_bara_ij_list( &mut self, subi_: &[i32], subj_: &[i32], alphaptrb_: &[i64], alphaptre_: &[i64], matidx_: &[i64], weights_: &[f64] ) -> Result<(), String>

Inputs list of elements of barA.

§Arguments
  • subi_ Row index of barA.
  • subj_ Column index of barA.
  • alphaptrb_ Start entries for terms in the weighted sum.
  • alphaptre_ End entries for terms in the weighted sum.
  • matidx_ Element indexes in matrix storage.
  • weights_ Weights in the weighted sum.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putbaraijlist

source

pub fn put_bara_row_list( &mut self, subi_: &[i32], ptrb_: &[i64], ptre_: &[i64], subj_: &[i32], nummat_: &[i64], matidx_: &[i64], weights_: &[f64] ) -> Result<(), String>

Replace a set of rows of barA

§Arguments
  • subi_ Row indexes of barA.
  • ptrb_ Start of rows in barA.
  • ptre_ End of rows in barA.
  • subj_ Column index of barA.
  • nummat_ Number of entries in weighted sum of matrixes.
  • matidx_ Matrix indexes for weighted sum of matrixes.
  • weights_ Weights for weighted sum of matrixes.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putbararowlist

source

pub fn put_barc_block_triplet( &mut self, subj_: &[i32], subk_: &[i32], subl_: &[i32], valjkl_: &[f64] ) -> Result<(), String>

Inputs barC in block triplet form.

§Arguments
  • subj_ Symmetric matrix variable index.
  • subk_ Block row index.
  • subl_ Block column index.
  • valjkl_ The numerical value associated with each block triplet.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putbarcblocktriplet

source

pub fn put_barc_j( &mut self, j_: i32, sub_: &[i64], weights_: &[f64] ) -> Result<(), String>

Changes one element in barc.

§Arguments
  • j_ Index of the element in barc` that should be changed.
  • sub_ sub is list of indexes of those symmetric matrices appearing in sum.
  • weights_ The weights of the terms in the weighted sum.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putbarcj

source

pub fn put_bars_j( &mut self, whichsol_: i32, j_: i32, barsj_: &[f64] ) -> Result<(), String>

Sets the dual solution for a semidefinite variable.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • j_ Index of the semidefinite variable.

  • barsj_ Value of the j’th variable of barx.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putbarsj

source

pub fn put_barvar_name(&mut self, j_: i32, name_: &str) -> Result<(), String>

Sets the name of a semidefinite variable.

§Arguments
  • j_ Index of the variable.
  • name_ The variable name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putbarvarname

source

pub fn put_barx_j( &mut self, whichsol_: i32, j_: i32, barxj_: &[f64] ) -> Result<(), String>

Sets the primal solution for a semidefinite variable.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • j_ Index of the semidefinite variable.

  • barxj_ Value of the j’th variable of barx.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putbarxj

source

pub fn put_cfix(&mut self, cfix_: f64) -> Result<(), String>

Replaces the fixed term in the objective.

§Arguments
  • cfix_ Fixed term in the objective.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putcfix

source

pub fn put_c_j(&mut self, j_: i32, cj_: f64) -> Result<(), String>

Modifies one linear coefficient in the objective.

§Arguments
  • j_ Index of the variable whose objective coefficient should be changed.
  • cj_ New coefficient value.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putcj

Examples found in repository?
examples/helloworld.rs (line 21)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
fn main() -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
        };

    task.append_vars(1)?;                           // 1 variable x
    task.put_c_j(0, 1.0)?;                          // c_0 = 1.0
    task.put_var_bound(0, Boundkey::RA, 2.0, 3.0)?; // 2.0 <= x <= 3.0
    task.put_obj_sense(Objsense::MINIMIZE)?;        // minimize

    task.optimize()?;                               // Optimize

    let mut x = vec![0.0; 1];
    task.get_xx(Soltype::ITR, x.as_mut_slice())?;   // Get solution
    println!("Solution x = {}", x[0]);              // Print solution
    return Result::Ok(());
}
More examples
Hide additional examples
examples/portfolio_2_frontier.rs (line 99)
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
fn portfolio(n : i32,
             mu : &[f64],
             GT : &[f64],
             x0  : &[f64],
             alphas : &[f64],
             w : f64) -> Result<Vec<(f64,f64)>,String> {
    let k = (GT.len() / n as usize) as i32;
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(t) => t,
        None => return Err("Failed to create task".to_string()),
    };
    //task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    task.append_vars(n+1)?;
    task.append_cons(1)?;

    /* Objective */
    task.put_obj_sense(Objsense::MAXIMIZE)?;

    let x : Vec<i32> = (0i32..n).collect();
    let s = n;

    /* Total budget */
    let total_budget = w + x0.iter().sum::<f64>();

    /* Total budget constraint - set bounds l^c = u^c */
    task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
    task.put_con_name(0i32,"budget")?;
    task.put_c_slice(0,n,mu)?;

    /* x variables. */
    for (j,xj) in x.iter().enumerate() {
        /* Coefficients in the first row of A */
        task.put_aij(0, *xj, 1.0)?;
        /* No short-selling - x^l = 0, x^u = inf */
        task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
        task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
    }
    task.put_var_name(s, "s")?;
    task.put_var_bound(s, mosek::Boundkey::FR, 0.0, 0.0)?;

    // risk bound
    // (s,0.5,GT * x) in Q_r
    {
        let acci = task.get_num_acc()?;
        let afei = task.get_num_afe()?;

        task.append_afes(k as i64 + 2)?;
        let dom = task.append_r_quadratic_cone_domain(k as i64+2)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 2].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_f_entry(afei,s,1.0)?;
        task.put_afe_g(afei+1,0.5)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 2, j as i32, *v)?;
        }
    }

    let frontier : Vec<(f64,f64)> = alphas.iter().filter_map(|alpha| {
        /* Sets the objective function coefficient for s. */
        if      let Err(_) = task.put_c_j(s, - *alpha) { None }
        else if let Err(_) = task.optimize() { None }
        else if let Err(_) = task.write_data(format!("portfolio_2_frontier-{}.ptf",alpha).as_str()) { None }
        else if let Ok(solsta) = task.get_sol_sta(Soltype::ITR) {
            // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
            match solsta {
                Solsta::OPTIMAL => {
                    let mut xx = vec![0.0; n as usize+1];
                    if let Err(_) = task.get_xx(Soltype::ITR,xx.as_mut_slice()) { None }
                    else {
                        Some((*alpha,mu.iter().zip(xx.iter()).map(|(m,x)| m * x).sum::<f64>()))
                    }
                }
                _ => None
            }
        }
        else {
            None
        }
    }).collect();

    Ok(frontier)
}
examples/reoptimization.rs (line 58)
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
fn main() -> Result<(),String> {

    let numcon = 3;
    let numvar = 3;
    let c = &[1.5, 2.5, 3.0 ];
    let bkc = &[ Boundkey::UP,
                 Boundkey::UP,
                 Boundkey::UP ];
    let blc = &[ -INF,
                 -INF,
                 -INF ];
    let buc = &[ 100000.0,
                 50000.0,
                 60000.0 ];
    let bkx = &[ Boundkey::LO,
                 Boundkey::LO,
                 Boundkey::LO
                             ];
    let blx = &[ 0.0, 0.0, 0.0 ];
    let bux = &[ INF,
                 INF,
                 INF ];

    let asub = &[
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ] ];

    let aval = &[
        &[ 2.0, 3.0, 2.0 ],
        &[ 4.0, 2.0, 3.0 ],
        &[ 3.0, 3.0, 2.0 ] ];


    let mut task = Task::new().unwrap();
    /* Append the constraints. */
    task.append_cons(numcon)?;

    /* Append the variables. */
    task.append_vars(numvar)?;

    /* Put C. */
    for (j,&cj) in (0..numvar).zip(c.iter()) {
        task.put_c_j(j,cj)?;
    }
    /* Put constraint bounds. */
    for (i,&bki,&bli,&bui) in izip!(0..numcon,bkc,blc,buc) {
        task.put_con_bound(i, bki, bli, bui)?;
    }

    /* Put variable bounds. */
    for (j,&bki,&bli,&bui) in izip!(0..numvar,bkx,blx,bux) {
        task.put_var_bound(j, bki, bli, bui)?;
    }

    /* Put A. */
    if numcon > 0 {
        for (j,&asubj,&avalj) in izip!(0..numvar,asub,aval) {
            task.put_a_col(j,
                           asubj,
                           avalj)?;
        }
    }

    /* A maximization problem */
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    /* Solve the problem */
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /****************** Make a change to the A matrix ******************/
    task.put_aij(0, 0, 3.0)?;
    let _trm = task.optimize()?;
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /***************** Add a new variable ******************************/
    /* Get index of new variable. */

    let varidx = task.get_num_var()?;

    /* Append a new variable x_3 to the problem */
    task.append_vars(1)?;
    let numvar = numvar + 1;

    /* Set bounds on new varaible */
    task.put_var_bound(varidx, Boundkey::LO, 0.0, INF)?;

    /* Change objective */
    task.put_c_j(varidx, 1.0)?;

    /* Put new values in the A matrix */
    let acolsub = &[0i32, 2];
    let acolval = &[4.0, 1.0];

    task.put_a_col(varidx, /* column index */
                   acolsub,
                   acolval)?;

    /* Change optimizer to simplex free and reoptimize */
    task.put_int_param(mosek::Iparam::OPTIMIZER, mosek::Optimizertype::FREE_SIMPLEX)?;
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Add a new constraint ***************************/
    /* Get index of new constraint. */
    let conidx = task.get_num_con()?;

    /* Append a new constraint */
    task.append_cons(1)?;
    let numcon = numcon + 1;

    /* Set bounds on new constraint */
    task.put_con_bound(conidx,
                       Boundkey::UP,
                       -INF,
                       30000.0)?;

    /* Put new values in the A matrix */
    let arowsub = &[0i32,   1,   2,   3  ];
    let arowval = &[1.0, 2.0, 1.0, 1.0 ];

    task.put_a_row(conidx, /* row index */
                   arowsub,
                   arowval)?;

    let _trm = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Change constraint bounds ********************/
    let newbkc = &[Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP];
    let newblc = &[-INF,
                   -INF,
                   -INF,
                   -INF];
    let newbuc = &[ 80000.0, 40000.0, 50000.0, 22000.0 ];

    task.put_con_bound_slice(0, numcon, newbkc, newblc, newbuc)?;

    let _ = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    Ok(())
}
examples/portfolio_5_card.rs (line 87)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
examples/milo1.rs (line 54)
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
fn main() -> Result<(),String> {
    let numcon : i32 = 2;
    let numvar : i32 = 2;

    let infinity = 0.0; // only for symbolic purposes, value never used

    let bkc = vec![Boundkey::UP, Boundkey::LO];
    let blc = vec![ -infinity,         -4.0 ];
    let buc = vec![ 250.0,             infinity ];

    let bkx = vec![ Boundkey::LO, Boundkey::LO  ];
    let blx = vec![ 0.0,               0.0 ];
    let bux = vec![ infinity,          infinity ];

    let c   = vec![1.0, 0.64];

    let asub = vec![0,   1,
                    0,    1];
    let aval = vec![50.0, 3.0, 31.0, -2.0];

    let ptrb : Vec<usize> = vec![ 0, 2 ];
    let ptre : Vec<usize> = vec![ 2, 4 ];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG,
            &mut |msg| print!("{}",msg),
            |task| task.with_itg_sol_callback(
                &mut |xx| { println!("Found a new solution = {:?}",xx); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                    The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                    /* Append 'numvar' variables.
                    The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    for ((((j,cj),bk),bl),bu) in (0..numvar).zip(c.iter()).zip(bkx.iter()).zip(blx.iter()).zip(bux.iter()) {
                        /* Set the linear term c_j in the objective.*/
                        task.put_c_j(j, *cj)?;
                        /* Set the bounds on variable j.
                           blx[j] <= x_j <= bux[j] */
                        task.put_var_bound(j, *bk, *bl, *bu)?;
                        /* Input column j of A */
                        task.put_a_col(j,                     /* Variable (column) index.*/
                                       &asub[ptrb[j as usize]..ptre[j as usize]],               /* Row index of non-zeros in column j.*/
                                       &aval[ptrb[j as usize]..ptre[j as usize]])?;              /* Non-zero Values of column j. */
                    }
                    // Set the bounds on constraints.
                    // for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] 
                    for (((i,bk),bl),bu) in (0..numcon).zip(bkc.iter()).zip(blc.iter()).zip(buc.iter()) {
                        task.put_con_bound(i, *bk, *bl, *bu)?;
                    }

                    /* Specify integer variables. */
                    for j in 0..numvar {
                        task.put_var_type(j, Variabletype::TYPE_INT)?;
                    }
                    /* Set max solution time */
                    task.put_dou_param(Dparam::MIO_MAX_TIME, 60.0)?;

                    /* A maximization problem */
                    task.put_obj_sense(Objsense::MAXIMIZE)?;
                    /* Solve the problem */

                    let _trm = task.optimize()?;

                    // Print a summary containing information
                    //   about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITG, xx.as_mut_slice())?;

                    /* Get status information about the solution */

                    match task.get_sol_sta(Soltype::ITG)? {
                        Solsta::INTEGER_OPTIMAL => {
                            println!("Optimal solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::PRIM_FEAS => {
                            println!("Feasible solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::UNKNOWN => {
                          match task.get_pro_sta(Soltype::ITG)? {
                              Prosta::PRIM_INFEAS_OR_UNBOUNDED => {
                                  println!("Problem status Infeasible or unbounded");
                              }
                              Prosta::PRIM_INFEAS => {
                                  println!("Problem status Infeasible.");
                              }
                              Prosta::UNKNOWN => {
                                  println!("Problem status unknown.");
                              }
                              _ => {
                                  println!("Other problem status.");
                              }
                          }
                        }
                        _ => {
                            println!("Other solution status");
                        }
                    }
                    Ok(())
                }))
}
source

pub fn put_c_list(&mut self, subj_: &[i32], val_: &[f64]) -> Result<(), String>

Modifies a part of the linear objective coefficients.

§Arguments
  • subj_ Indices of variables for which objective coefficients should be changed.
  • val_ New numerical values for the objective coefficients that should be modified.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putclist

Examples found in repository?
examples/pinfeas.rs (lines 19-20)
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
fn test_problem() -> Result<mosek::Task,String> {
    let mut task = mosek::Task::new().unwrap();
    task.append_vars(7)?;
    task.append_cons(7)?;
    task.put_c_list(&[0,1,2,3,4,5,6],
                    &[1.0,2.0,5.0,2.0,1.0,2.0,1.0])?;
    task.put_aij_list(&[0,0,1,1,2,2,2,3,3,4,5,5,6,6],
                      &[0,1,2,3,4,5,6,0,4,1,2,5,3,6],
                      &[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0])?;
    task.put_con_bound_slice(0, 7,
                             &[Boundkey::UP,Boundkey::UP,Boundkey::UP,Boundkey::FX,Boundkey::FX,Boundkey::FX,Boundkey::FX],
                             &[-INF, -INF, -INF, 1100.0, 200.0, 500.0, 500.0],
                             &[200.0, 1000.0, 1000.0, 1100.0, 200.0, 500.0, 500.0])?;
    task.put_var_bound_slice_const(0, 7, Boundkey::UP, 0.0, INF)?;
    Ok(task)
}
source

pub fn put_con_bound( &mut self, i_: i32, bkc_: i32, blc_: f64, buc_: f64 ) -> Result<(), String>

Changes the bound for one constraint.

§Arguments
  • i_ Index of the constraint.

  • bkc_ New bound key.

    See Boundkey

  • blc_ New lower bound.

  • buc_ New upper bound.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putconbound

Examples found in repository?
examples/portfolio_2_frontier.rs (line 62)
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
fn portfolio(n : i32,
             mu : &[f64],
             GT : &[f64],
             x0  : &[f64],
             alphas : &[f64],
             w : f64) -> Result<Vec<(f64,f64)>,String> {
    let k = (GT.len() / n as usize) as i32;
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(t) => t,
        None => return Err("Failed to create task".to_string()),
    };
    //task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    task.append_vars(n+1)?;
    task.append_cons(1)?;

    /* Objective */
    task.put_obj_sense(Objsense::MAXIMIZE)?;

    let x : Vec<i32> = (0i32..n).collect();
    let s = n;

    /* Total budget */
    let total_budget = w + x0.iter().sum::<f64>();

    /* Total budget constraint - set bounds l^c = u^c */
    task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
    task.put_con_name(0i32,"budget")?;
    task.put_c_slice(0,n,mu)?;

    /* x variables. */
    for (j,xj) in x.iter().enumerate() {
        /* Coefficients in the first row of A */
        task.put_aij(0, *xj, 1.0)?;
        /* No short-selling - x^l = 0, x^u = inf */
        task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
        task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
    }
    task.put_var_name(s, "s")?;
    task.put_var_bound(s, mosek::Boundkey::FR, 0.0, 0.0)?;

    // risk bound
    // (s,0.5,GT * x) in Q_r
    {
        let acci = task.get_num_acc()?;
        let afei = task.get_num_afe()?;

        task.append_afes(k as i64 + 2)?;
        let dom = task.append_r_quadratic_cone_domain(k as i64+2)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 2].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_f_entry(afei,s,1.0)?;
        task.put_afe_g(afei+1,0.5)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 2, j as i32, *v)?;
        }
    }

    let frontier : Vec<(f64,f64)> = alphas.iter().filter_map(|alpha| {
        /* Sets the objective function coefficient for s. */
        if      let Err(_) = task.put_c_j(s, - *alpha) { None }
        else if let Err(_) = task.optimize() { None }
        else if let Err(_) = task.write_data(format!("portfolio_2_frontier-{}.ptf",alpha).as_str()) { None }
        else if let Ok(solsta) = task.get_sol_sta(Soltype::ITR) {
            // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
            match solsta {
                Solsta::OPTIMAL => {
                    let mut xx = vec![0.0; n as usize+1];
                    if let Err(_) = task.get_xx(Soltype::ITR,xx.as_mut_slice()) { None }
                    else {
                        Some((*alpha,mu.iter().zip(xx.iter()).map(|(m,x)| m * x).sum::<f64>()))
                    }
                }
                _ => None
            }
        }
        else {
            None
        }
    }).collect();

    Ok(frontier)
}
More examples
Hide additional examples
examples/ceo1.rs (line 62)
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
fn main() -> Result<(),String> {
    let numcon = 1;
    let numvar = 3;

    let bkc = mosek::Boundkey::FX;
    let blc = 1.0;
    let buc = 1.0;

    let bkx = vec![ Boundkey::FR,
                    Boundkey::FR,
                    Boundkey::FR ];
    let blx = vec![ -INF, -INF, -INF ];
    let bux = vec![ INF, INF, INF ];
    let c   = vec![ 1.0, 1.0, 0.0 ];
    let a   = vec![ 1.0, 1.0, 1.0 ];
    let asub = vec![0, 1, 2];
    //let csub = new int[numvar];
    //double[] xx  = new double[numvar];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG, 
            &mut|msg| print!("{}",msg),
            |task| task.with_callback(
                &mut |caller| { println!("caller = {}",caller); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                       The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                      /* Append 'numvar' variables.
                         The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    /* Define the linear part of the problem */
                    task.put_c_slice(0, numvar, c.as_slice())?;
                    task.put_a_row(0, asub.as_slice(), a.as_slice())?;
                    task.put_con_bound(0, bkc, blc, buc)?;
                    task.put_var_bound_slice(0, numvar, bkx.as_slice(), blx.as_slice(), bux.as_slice())?;

                    /* Add a conic constraint */
                    task.append_afes(3)?;
                    let afeidxs = vec![0,  1,  2  ];
                    let b       = vec![0.0,0.0,0.0];
                    let domidx  = task.append_primal_exp_cone_domain()?;
                    task.put_afe_f_row_list(afeidxs.as_slice(),
                                            vec![1,1,1].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![1.0,1.0,1.0].as_slice())?;
                    task.append_acc(domidx,afeidxs.as_slice(),b.as_slice())?;

                    task.put_obj_sense(Objsense::MINIMIZE)?;

                    println!("optimize");
                    /* Solve the problem */
                    task.optimize()?;
                    // Print a summary containing information
                    // about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    /* Get status information about the solution */
                    let solsta = task.get_sol_sta(Soltype::ITR)?;

                    assert!(solsta == Solsta::OPTIMAL);
                    
                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITR, & mut xx[..])?;
                    
                    println!("Optimal primal solution");
                    for j in 0..numvar as usize {
                        println!("x[{}]: {:.4}",j,xx[j]);
                    }
                    Ok(())
                }))
}
examples/reoptimization.rs (line 62)
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
fn main() -> Result<(),String> {

    let numcon = 3;
    let numvar = 3;
    let c = &[1.5, 2.5, 3.0 ];
    let bkc = &[ Boundkey::UP,
                 Boundkey::UP,
                 Boundkey::UP ];
    let blc = &[ -INF,
                 -INF,
                 -INF ];
    let buc = &[ 100000.0,
                 50000.0,
                 60000.0 ];
    let bkx = &[ Boundkey::LO,
                 Boundkey::LO,
                 Boundkey::LO
                             ];
    let blx = &[ 0.0, 0.0, 0.0 ];
    let bux = &[ INF,
                 INF,
                 INF ];

    let asub = &[
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ] ];

    let aval = &[
        &[ 2.0, 3.0, 2.0 ],
        &[ 4.0, 2.0, 3.0 ],
        &[ 3.0, 3.0, 2.0 ] ];


    let mut task = Task::new().unwrap();
    /* Append the constraints. */
    task.append_cons(numcon)?;

    /* Append the variables. */
    task.append_vars(numvar)?;

    /* Put C. */
    for (j,&cj) in (0..numvar).zip(c.iter()) {
        task.put_c_j(j,cj)?;
    }
    /* Put constraint bounds. */
    for (i,&bki,&bli,&bui) in izip!(0..numcon,bkc,blc,buc) {
        task.put_con_bound(i, bki, bli, bui)?;
    }

    /* Put variable bounds. */
    for (j,&bki,&bli,&bui) in izip!(0..numvar,bkx,blx,bux) {
        task.put_var_bound(j, bki, bli, bui)?;
    }

    /* Put A. */
    if numcon > 0 {
        for (j,&asubj,&avalj) in izip!(0..numvar,asub,aval) {
            task.put_a_col(j,
                           asubj,
                           avalj)?;
        }
    }

    /* A maximization problem */
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    /* Solve the problem */
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /****************** Make a change to the A matrix ******************/
    task.put_aij(0, 0, 3.0)?;
    let _trm = task.optimize()?;
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /***************** Add a new variable ******************************/
    /* Get index of new variable. */

    let varidx = task.get_num_var()?;

    /* Append a new variable x_3 to the problem */
    task.append_vars(1)?;
    let numvar = numvar + 1;

    /* Set bounds on new varaible */
    task.put_var_bound(varidx, Boundkey::LO, 0.0, INF)?;

    /* Change objective */
    task.put_c_j(varidx, 1.0)?;

    /* Put new values in the A matrix */
    let acolsub = &[0i32, 2];
    let acolval = &[4.0, 1.0];

    task.put_a_col(varidx, /* column index */
                   acolsub,
                   acolval)?;

    /* Change optimizer to simplex free and reoptimize */
    task.put_int_param(mosek::Iparam::OPTIMIZER, mosek::Optimizertype::FREE_SIMPLEX)?;
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Add a new constraint ***************************/
    /* Get index of new constraint. */
    let conidx = task.get_num_con()?;

    /* Append a new constraint */
    task.append_cons(1)?;
    let numcon = numcon + 1;

    /* Set bounds on new constraint */
    task.put_con_bound(conidx,
                       Boundkey::UP,
                       -INF,
                       30000.0)?;

    /* Put new values in the A matrix */
    let arowsub = &[0i32,   1,   2,   3  ];
    let arowval = &[1.0, 2.0, 1.0, 1.0 ];

    task.put_a_row(conidx, /* row index */
                   arowsub,
                   arowval)?;

    let _trm = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Change constraint bounds ********************/
    let newbkc = &[Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP];
    let newblc = &[-INF,
                   -INF,
                   -INF,
                   -INF];
    let newbuc = &[ 80000.0, 40000.0, 50000.0, 22000.0 ];

    task.put_con_bound_slice(0, numcon, newbkc, newblc, newbuc)?;

    let _ = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    Ok(())
}
examples/portfolio_5_card.rs (line 99)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
examples/milo1.rs (line 66)
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
fn main() -> Result<(),String> {
    let numcon : i32 = 2;
    let numvar : i32 = 2;

    let infinity = 0.0; // only for symbolic purposes, value never used

    let bkc = vec![Boundkey::UP, Boundkey::LO];
    let blc = vec![ -infinity,         -4.0 ];
    let buc = vec![ 250.0,             infinity ];

    let bkx = vec![ Boundkey::LO, Boundkey::LO  ];
    let blx = vec![ 0.0,               0.0 ];
    let bux = vec![ infinity,          infinity ];

    let c   = vec![1.0, 0.64];

    let asub = vec![0,   1,
                    0,    1];
    let aval = vec![50.0, 3.0, 31.0, -2.0];

    let ptrb : Vec<usize> = vec![ 0, 2 ];
    let ptre : Vec<usize> = vec![ 2, 4 ];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG,
            &mut |msg| print!("{}",msg),
            |task| task.with_itg_sol_callback(
                &mut |xx| { println!("Found a new solution = {:?}",xx); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                    The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                    /* Append 'numvar' variables.
                    The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    for ((((j,cj),bk),bl),bu) in (0..numvar).zip(c.iter()).zip(bkx.iter()).zip(blx.iter()).zip(bux.iter()) {
                        /* Set the linear term c_j in the objective.*/
                        task.put_c_j(j, *cj)?;
                        /* Set the bounds on variable j.
                           blx[j] <= x_j <= bux[j] */
                        task.put_var_bound(j, *bk, *bl, *bu)?;
                        /* Input column j of A */
                        task.put_a_col(j,                     /* Variable (column) index.*/
                                       &asub[ptrb[j as usize]..ptre[j as usize]],               /* Row index of non-zeros in column j.*/
                                       &aval[ptrb[j as usize]..ptre[j as usize]])?;              /* Non-zero Values of column j. */
                    }
                    // Set the bounds on constraints.
                    // for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] 
                    for (((i,bk),bl),bu) in (0..numcon).zip(bkc.iter()).zip(blc.iter()).zip(buc.iter()) {
                        task.put_con_bound(i, *bk, *bl, *bu)?;
                    }

                    /* Specify integer variables. */
                    for j in 0..numvar {
                        task.put_var_type(j, Variabletype::TYPE_INT)?;
                    }
                    /* Set max solution time */
                    task.put_dou_param(Dparam::MIO_MAX_TIME, 60.0)?;

                    /* A maximization problem */
                    task.put_obj_sense(Objsense::MAXIMIZE)?;
                    /* Solve the problem */

                    let _trm = task.optimize()?;

                    // Print a summary containing information
                    //   about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITG, xx.as_mut_slice())?;

                    /* Get status information about the solution */

                    match task.get_sol_sta(Soltype::ITG)? {
                        Solsta::INTEGER_OPTIMAL => {
                            println!("Optimal solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::PRIM_FEAS => {
                            println!("Feasible solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::UNKNOWN => {
                          match task.get_pro_sta(Soltype::ITG)? {
                              Prosta::PRIM_INFEAS_OR_UNBOUNDED => {
                                  println!("Problem status Infeasible or unbounded");
                              }
                              Prosta::PRIM_INFEAS => {
                                  println!("Problem status Infeasible.");
                              }
                              Prosta::UNKNOWN => {
                                  println!("Problem status unknown.");
                              }
                              _ => {
                                  println!("Other problem status.");
                              }
                          }
                        }
                        _ => {
                            println!("Other solution status");
                        }
                    }
                    Ok(())
                }))
}
source

pub fn put_con_bound_list( &mut self, sub_: &[i32], bkc_: &[i32], blc_: &[f64], buc_: &[f64] ) -> Result<(), String>

Changes the bounds of a list of constraints.

§Arguments
  • sub_ List of constraint indexes.

  • bkc_ Bound keys for the constraints.

    See Boundkey

  • blc_ Lower bounds for the constraints.

  • buc_ Upper bounds for the constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putconboundlist

source

pub fn put_con_bound_list_const( &mut self, sub_: &[i32], bkc_: i32, blc_: f64, buc_: f64 ) -> Result<(), String>

Changes the bounds of a list of constraints.

§Arguments
  • sub_ List of constraint indexes.

  • bkc_ New bound key for all constraints in the list.

    See Boundkey

  • blc_ New lower bound for all constraints in the list.

  • buc_ New upper bound for all constraints in the list.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putconboundlistconst

source

pub fn put_con_bound_slice( &mut self, first_: i32, last_: i32, bkc_: &[i32], blc_: &[f64], buc_: &[f64] ) -> Result<(), String>

Changes the bounds for a slice of the constraints.

§Arguments
  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • bkc_ Bound keys for the constraints.

    See Boundkey

  • blc_ Lower bounds for the constraints.

  • buc_ Upper bounds for the constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putconboundslice

Examples found in repository?
examples/pinfeas.rs (lines 24-27)
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
fn test_problem() -> Result<mosek::Task,String> {
    let mut task = mosek::Task::new().unwrap();
    task.append_vars(7)?;
    task.append_cons(7)?;
    task.put_c_list(&[0,1,2,3,4,5,6],
                    &[1.0,2.0,5.0,2.0,1.0,2.0,1.0])?;
    task.put_aij_list(&[0,0,1,1,2,2,2,3,3,4,5,5,6,6],
                      &[0,1,2,3,4,5,6,0,4,1,2,5,3,6],
                      &[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0])?;
    task.put_con_bound_slice(0, 7,
                             &[Boundkey::UP,Boundkey::UP,Boundkey::UP,Boundkey::FX,Boundkey::FX,Boundkey::FX,Boundkey::FX],
                             &[-INF, -INF, -INF, 1100.0, 200.0, 500.0, 500.0],
                             &[200.0, 1000.0, 1000.0, 1100.0, 200.0, 500.0, 500.0])?;
    task.put_var_bound_slice_const(0, 7, Boundkey::UP, 0.0, INF)?;
    Ok(task)
}
More examples
Hide additional examples
examples/reoptimization.rs (line 178)
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
fn main() -> Result<(),String> {

    let numcon = 3;
    let numvar = 3;
    let c = &[1.5, 2.5, 3.0 ];
    let bkc = &[ Boundkey::UP,
                 Boundkey::UP,
                 Boundkey::UP ];
    let blc = &[ -INF,
                 -INF,
                 -INF ];
    let buc = &[ 100000.0,
                 50000.0,
                 60000.0 ];
    let bkx = &[ Boundkey::LO,
                 Boundkey::LO,
                 Boundkey::LO
                             ];
    let blx = &[ 0.0, 0.0, 0.0 ];
    let bux = &[ INF,
                 INF,
                 INF ];

    let asub = &[
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ] ];

    let aval = &[
        &[ 2.0, 3.0, 2.0 ],
        &[ 4.0, 2.0, 3.0 ],
        &[ 3.0, 3.0, 2.0 ] ];


    let mut task = Task::new().unwrap();
    /* Append the constraints. */
    task.append_cons(numcon)?;

    /* Append the variables. */
    task.append_vars(numvar)?;

    /* Put C. */
    for (j,&cj) in (0..numvar).zip(c.iter()) {
        task.put_c_j(j,cj)?;
    }
    /* Put constraint bounds. */
    for (i,&bki,&bli,&bui) in izip!(0..numcon,bkc,blc,buc) {
        task.put_con_bound(i, bki, bli, bui)?;
    }

    /* Put variable bounds. */
    for (j,&bki,&bli,&bui) in izip!(0..numvar,bkx,blx,bux) {
        task.put_var_bound(j, bki, bli, bui)?;
    }

    /* Put A. */
    if numcon > 0 {
        for (j,&asubj,&avalj) in izip!(0..numvar,asub,aval) {
            task.put_a_col(j,
                           asubj,
                           avalj)?;
        }
    }

    /* A maximization problem */
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    /* Solve the problem */
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /****************** Make a change to the A matrix ******************/
    task.put_aij(0, 0, 3.0)?;
    let _trm = task.optimize()?;
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /***************** Add a new variable ******************************/
    /* Get index of new variable. */

    let varidx = task.get_num_var()?;

    /* Append a new variable x_3 to the problem */
    task.append_vars(1)?;
    let numvar = numvar + 1;

    /* Set bounds on new varaible */
    task.put_var_bound(varidx, Boundkey::LO, 0.0, INF)?;

    /* Change objective */
    task.put_c_j(varidx, 1.0)?;

    /* Put new values in the A matrix */
    let acolsub = &[0i32, 2];
    let acolval = &[4.0, 1.0];

    task.put_a_col(varidx, /* column index */
                   acolsub,
                   acolval)?;

    /* Change optimizer to simplex free and reoptimize */
    task.put_int_param(mosek::Iparam::OPTIMIZER, mosek::Optimizertype::FREE_SIMPLEX)?;
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Add a new constraint ***************************/
    /* Get index of new constraint. */
    let conidx = task.get_num_con()?;

    /* Append a new constraint */
    task.append_cons(1)?;
    let numcon = numcon + 1;

    /* Set bounds on new constraint */
    task.put_con_bound(conidx,
                       Boundkey::UP,
                       -INF,
                       30000.0)?;

    /* Put new values in the A matrix */
    let arowsub = &[0i32,   1,   2,   3  ];
    let arowval = &[1.0, 2.0, 1.0, 1.0 ];

    task.put_a_row(conidx, /* row index */
                   arowsub,
                   arowval)?;

    let _trm = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Change constraint bounds ********************/
    let newbkc = &[Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP];
    let newblc = &[-INF,
                   -INF,
                   -INF,
                   -INF];
    let newbuc = &[ 80000.0, 40000.0, 50000.0, 22000.0 ];

    task.put_con_bound_slice(0, numcon, newbkc, newblc, newbuc)?;

    let _ = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    Ok(())
}
examples/portfolio_5_card.rs (line 116)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
source

pub fn put_con_bound_slice_const( &mut self, first_: i32, last_: i32, bkc_: i32, blc_: f64, buc_: f64 ) -> Result<(), String>

Changes the bounds for a slice of the constraints.

§Arguments
  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • bkc_ New bound key for all constraints in the slice.

    See Boundkey

  • blc_ New lower bound for all constraints in the slice.

  • buc_ New upper bound for all constraints in the slice.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putconboundsliceconst

Examples found in repository?
examples/solvelinear.rs (line 46)
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
fn setup(task : & mut mosek::Task,
         aval : &[f64],
         asub : &[i32],
         ptrb : &[i64],
         ptre : &[i64],
         numvar : i32) -> Result<Vec<i32>,String> {

    // mosek.stakey[] skx = new mosek.stakey [numvar];
    // mosek.stakey[] skc = new mosek.stakey [numvar];

    // for (int i = 0; i < numvar ; ++i) {
    //   skx[i] = mosek.stakey.bas;
    //   skc[i] = mosek.stakey.fix;
    // }

    task.append_vars(numvar)?;
    task.append_cons(numvar)?;

    task.put_a_col_slice(0,numvar,ptrb,ptre,asub,aval)?;

    task.put_con_bound_slice_const(0,numvar,Boundkey::FX,0.0,0.0)?;
    task.put_var_bound_slice_const(0,numvar,Boundkey::FR,-INF,INF)?;

    /* Define a basic solution by specifying
       status keys for variables & constraints. */
    task.delete_solution(Soltype::BAS)?;

    task.put_skc_slice(Soltype::BAS, 0, numvar, vec![Stakey::FIX; numvar as usize].as_slice())?;
    task.put_skx_slice(Soltype::BAS, 0, numvar, vec![Stakey::BAS; numvar as usize].as_slice())?;

    let mut basis = vec![0; numvar as usize];
    task.init_basis_solve(basis.as_mut_slice())?;
    Ok(basis)
  }
More examples
Hide additional examples
examples/portfolio_5_card.rs (line 161)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
source

pub fn put_cone( &mut self, k_: i32, ct_: i32, conepar_: f64, submem_: &[i32] ) -> Result<(), String>

Replaces a conic constraint.

§Arguments
  • k_ Index of the cone.

  • ct_ Specifies the type of the cone.

    See Conetype

  • conepar_ For the power cone it denotes the exponent alpha. For other cone types it is unused and can be set to 0.

  • submem_ Variable subscripts of the members in the cone.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putcone

source

pub fn put_cone_name(&mut self, j_: i32, name_: &str) -> Result<(), String>

Sets the name of a cone.

§Arguments
  • j_ Index of the cone.
  • name_ The name of the cone.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putconename

source

pub fn put_con_name(&mut self, i_: i32, name_: &str) -> Result<(), String>

Sets the name of a constraint.

§Arguments
  • i_ Index of the constraint.
  • name_ The name of the constraint.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putconname

Examples found in repository?
examples/portfolio_2_frontier.rs (line 63)
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
fn portfolio(n : i32,
             mu : &[f64],
             GT : &[f64],
             x0  : &[f64],
             alphas : &[f64],
             w : f64) -> Result<Vec<(f64,f64)>,String> {
    let k = (GT.len() / n as usize) as i32;
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(t) => t,
        None => return Err("Failed to create task".to_string()),
    };
    //task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    task.append_vars(n+1)?;
    task.append_cons(1)?;

    /* Objective */
    task.put_obj_sense(Objsense::MAXIMIZE)?;

    let x : Vec<i32> = (0i32..n).collect();
    let s = n;

    /* Total budget */
    let total_budget = w + x0.iter().sum::<f64>();

    /* Total budget constraint - set bounds l^c = u^c */
    task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
    task.put_con_name(0i32,"budget")?;
    task.put_c_slice(0,n,mu)?;

    /* x variables. */
    for (j,xj) in x.iter().enumerate() {
        /* Coefficients in the first row of A */
        task.put_aij(0, *xj, 1.0)?;
        /* No short-selling - x^l = 0, x^u = inf */
        task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
        task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
    }
    task.put_var_name(s, "s")?;
    task.put_var_bound(s, mosek::Boundkey::FR, 0.0, 0.0)?;

    // risk bound
    // (s,0.5,GT * x) in Q_r
    {
        let acci = task.get_num_acc()?;
        let afei = task.get_num_afe()?;

        task.append_afes(k as i64 + 2)?;
        let dom = task.append_r_quadratic_cone_domain(k as i64+2)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 2].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_f_entry(afei,s,1.0)?;
        task.put_afe_g(afei+1,0.5)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 2, j as i32, *v)?;
        }
    }

    let frontier : Vec<(f64,f64)> = alphas.iter().filter_map(|alpha| {
        /* Sets the objective function coefficient for s. */
        if      let Err(_) = task.put_c_j(s, - *alpha) { None }
        else if let Err(_) = task.optimize() { None }
        else if let Err(_) = task.write_data(format!("portfolio_2_frontier-{}.ptf",alpha).as_str()) { None }
        else if let Ok(solsta) = task.get_sol_sta(Soltype::ITR) {
            // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
            match solsta {
                Solsta::OPTIMAL => {
                    let mut xx = vec![0.0; n as usize+1];
                    if let Err(_) = task.get_xx(Soltype::ITR,xx.as_mut_slice()) { None }
                    else {
                        Some((*alpha,mu.iter().zip(xx.iter()).map(|(m,x)| m * x).sum::<f64>()))
                    }
                }
                _ => None
            }
        }
        else {
            None
        }
    }).collect();

    Ok(frontier)
}
More examples
Hide additional examples
examples/portfolio_5_card.rs (line 95)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
source

pub fn put_con_solution_i( &mut self, i_: i32, whichsol_: i32, sk_: i32, x_: f64, sl_: f64, su_: f64 ) -> Result<(), String>

Sets the primal and dual solution information for a single constraint.

§Arguments
  • i_ Index of the constraint.

  • whichsol_ Selects a solution.

    See Soltype

  • sk_ Status key of the constraint.

    See Stakey

  • x_ Primal solution value of the constraint.

  • sl_ Solution value of the dual variable associated with the lower bound.

  • su_ Solution value of the dual variable associated with the upper bound.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putconsolutioni

source

pub fn put_c_slice( &mut self, first_: i32, last_: i32, slice_: &[f64] ) -> Result<(), String>

Modifies a slice of the linear objective coefficients.

§Arguments
  • first_ First element in the slice of c.
  • last_ Last element plus 1 of the slice in c to be changed.
  • slice_ New numerical values for the objective coefficients that should be modified.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putcslice

Examples found in repository?
examples/portfolio_2_frontier.rs (line 64)
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
fn portfolio(n : i32,
             mu : &[f64],
             GT : &[f64],
             x0  : &[f64],
             alphas : &[f64],
             w : f64) -> Result<Vec<(f64,f64)>,String> {
    let k = (GT.len() / n as usize) as i32;
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(t) => t,
        None => return Err("Failed to create task".to_string()),
    };
    //task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    task.append_vars(n+1)?;
    task.append_cons(1)?;

    /* Objective */
    task.put_obj_sense(Objsense::MAXIMIZE)?;

    let x : Vec<i32> = (0i32..n).collect();
    let s = n;

    /* Total budget */
    let total_budget = w + x0.iter().sum::<f64>();

    /* Total budget constraint - set bounds l^c = u^c */
    task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
    task.put_con_name(0i32,"budget")?;
    task.put_c_slice(0,n,mu)?;

    /* x variables. */
    for (j,xj) in x.iter().enumerate() {
        /* Coefficients in the first row of A */
        task.put_aij(0, *xj, 1.0)?;
        /* No short-selling - x^l = 0, x^u = inf */
        task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
        task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
    }
    task.put_var_name(s, "s")?;
    task.put_var_bound(s, mosek::Boundkey::FR, 0.0, 0.0)?;

    // risk bound
    // (s,0.5,GT * x) in Q_r
    {
        let acci = task.get_num_acc()?;
        let afei = task.get_num_afe()?;

        task.append_afes(k as i64 + 2)?;
        let dom = task.append_r_quadratic_cone_domain(k as i64+2)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 2].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_f_entry(afei,s,1.0)?;
        task.put_afe_g(afei+1,0.5)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 2, j as i32, *v)?;
        }
    }

    let frontier : Vec<(f64,f64)> = alphas.iter().filter_map(|alpha| {
        /* Sets the objective function coefficient for s. */
        if      let Err(_) = task.put_c_j(s, - *alpha) { None }
        else if let Err(_) = task.optimize() { None }
        else if let Err(_) = task.write_data(format!("portfolio_2_frontier-{}.ptf",alpha).as_str()) { None }
        else if let Ok(solsta) = task.get_sol_sta(Soltype::ITR) {
            // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
            match solsta {
                Solsta::OPTIMAL => {
                    let mut xx = vec![0.0; n as usize+1];
                    if let Err(_) = task.get_xx(Soltype::ITR,xx.as_mut_slice()) { None }
                    else {
                        Some((*alpha,mu.iter().zip(xx.iter()).map(|(m,x)| m * x).sum::<f64>()))
                    }
                }
                _ => None
            }
        }
        else {
            None
        }
    }).collect();

    Ok(frontier)
}
More examples
Hide additional examples
examples/ceo1.rs (line 60)
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
fn main() -> Result<(),String> {
    let numcon = 1;
    let numvar = 3;

    let bkc = mosek::Boundkey::FX;
    let blc = 1.0;
    let buc = 1.0;

    let bkx = vec![ Boundkey::FR,
                    Boundkey::FR,
                    Boundkey::FR ];
    let blx = vec![ -INF, -INF, -INF ];
    let bux = vec![ INF, INF, INF ];
    let c   = vec![ 1.0, 1.0, 0.0 ];
    let a   = vec![ 1.0, 1.0, 1.0 ];
    let asub = vec![0, 1, 2];
    //let csub = new int[numvar];
    //double[] xx  = new double[numvar];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG, 
            &mut|msg| print!("{}",msg),
            |task| task.with_callback(
                &mut |caller| { println!("caller = {}",caller); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                       The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                      /* Append 'numvar' variables.
                         The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    /* Define the linear part of the problem */
                    task.put_c_slice(0, numvar, c.as_slice())?;
                    task.put_a_row(0, asub.as_slice(), a.as_slice())?;
                    task.put_con_bound(0, bkc, blc, buc)?;
                    task.put_var_bound_slice(0, numvar, bkx.as_slice(), blx.as_slice(), bux.as_slice())?;

                    /* Add a conic constraint */
                    task.append_afes(3)?;
                    let afeidxs = vec![0,  1,  2  ];
                    let b       = vec![0.0,0.0,0.0];
                    let domidx  = task.append_primal_exp_cone_domain()?;
                    task.put_afe_f_row_list(afeidxs.as_slice(),
                                            vec![1,1,1].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![1.0,1.0,1.0].as_slice())?;
                    task.append_acc(domidx,afeidxs.as_slice(),b.as_slice())?;

                    task.put_obj_sense(Objsense::MINIMIZE)?;

                    println!("optimize");
                    /* Solve the problem */
                    task.optimize()?;
                    // Print a summary containing information
                    // about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    /* Get status information about the solution */
                    let solsta = task.get_sol_sta(Soltype::ITR)?;

                    assert!(solsta == Solsta::OPTIMAL);
                    
                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITR, & mut xx[..])?;
                    
                    println!("Optimal primal solution");
                    for j in 0..numvar as usize {
                        println!("x[{}]: {:.4}",j,xx[j]);
                    }
                    Ok(())
                }))
}
source

pub fn put_djc( &mut self, djcidx_: i64, domidxlist_: &[i64], afeidxlist_: &[i64], b_: &[f64], termsizelist_: &[i64] ) -> Result<(), String>

Inputs a disjunctive constraint.

§Arguments
  • djcidx_ Index of the disjunctive constraint.
  • domidxlist_ List of domain indexes.
  • afeidxlist_ List of affine expression indexes.
  • b_ The vector of constant terms modifying affine expressions.
  • termsizelist_ List of term sizes.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putdjc

source

pub fn put_djc_name(&mut self, djcidx_: i64, name_: &str) -> Result<(), String>

Sets the name of a disjunctive constraint.

§Arguments
  • djcidx_ Index of the disjunctive constraint.
  • name_ The name of the disjunctive constraint.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putdjcname

source

pub fn put_djc_slice( &mut self, idxfirst_: i64, idxlast_: i64, domidxlist_: &[i64], afeidxlist_: &[i64], b_: &[f64], termsizelist_: &[i64], termsindjc_: &[i64] ) -> Result<(), String>

Inputs a slice of disjunctive constraints.

§Arguments
  • idxfirst_ Index of the first disjunctive constraint in the slice.
  • idxlast_ Index of the last disjunctive constraint in the slice plus 1.
  • domidxlist_ List of domain indexes.
  • afeidxlist_ List of affine expression indexes.
  • b_ The vector of constant terms modifying affine expressions. Optional.
  • termsizelist_ List of term sizes.
  • termsindjc_ Number of terms in each of the disjunctive constraints in the slice.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putdjcslice

source

pub fn put_domain_name( &mut self, domidx_: i64, name_: &str ) -> Result<(), String>

Sets the name of a domain.

§Arguments
  • domidx_ Index of the domain.
  • name_ The name of the domain.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putdomainname

source

pub fn put_dou_param( &mut self, param_: i32, parvalue_: f64 ) -> Result<(), String>

Sets a double parameter.

§Arguments
  • param_ Which parameter.

    See Dparam

  • parvalue_ Parameter value.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putdouparam

Examples found in repository?
examples/parameters.rs (line 25)
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
fn main() -> Result<(),String> {
    let mut task = Task::new().unwrap();
    println!("Test MOSEK parameter get/set functions");

    // Set log level (integer parameter)
    task.put_int_param(Iparam::LOG, 1)?;
    // Select interior-point optimizer... (integer parameter)
    task.put_int_param(Iparam::OPTIMIZER, Optimizertype::INTPNT)?;
    // ... without basis identification (integer parameter)
    task.put_int_param(Iparam::INTPNT_BASIS,Basindtype::NEVER)?;
    // Set relative gap tolerance (double parameter)
    task.put_dou_param(Dparam::INTPNT_CO_TOL_REL_GAP, 1.0e-7)?;

    // The same using explicit string names
    task.put_param("MSK_DPAR_INTPNT_CO_TOL_REL_GAP", "1.0e-7")?;
    task.put_na_dou_param("MSK_DPAR_INTPNT_CO_TOL_REL_GAP",  1.0e-7 )?;

    // Incorrect value

    if let Err(_) = task.put_dou_param(Dparam::INTPNT_CO_TOL_REL_GAP, -1.0) {
        println!("Wrong parameter value");
    }


    let param = task.get_dou_param(Dparam::INTPNT_CO_TOL_REL_GAP)?;
    println!("Current value for parameter intpnt_co_tol_rel_gap = $param");

    // Define and solve an optimization problem here
    // optimize(task,)
    // After optimization:

    println!("Get MOSEK information items");

    let tm = task.get_dou_inf(Dinfitem::OPTIMIZER_TIME)?;
    let iter = task.get_int_inf(Iinfitem::INTPNT_ITER)?;

    println!("Time: {}",tm);
    println!("Iterations: {}",iter);
    Ok(())
}
More examples
Hide additional examples
examples/concurrent1.rs (line 112)
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
fn concurrent1(data : FileOrText, timelimit : Option<String>) -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
        };

    match data {
        FileOrText::File(fname) => task.read_data(fname.as_str())?,
        FileOrText::Text(text)  => task.read_ptf_string(text.as_str())?
    }
    if let Some(timelimit) = timelimit {
        task.put_dou_param(mosek::Dparam::OPTIMIZER_MAX_TIME, timelimit.parse().unwrap())?;
    }

    let numintvar = task.get_num_int_var()?;

    let r = if numintvar == 0 {
        let optimizers = &[mosek::Optimizertype::CONIC,
                           mosek::Optimizertype::DUAL_SIMPLEX,
                           mosek::Optimizertype::PRIMAL_SIMPLEX];
        optimize_concurrent(& mut task, optimizers)
    }
    else {
        let seeds = &[ 42, 13, 71749373 ];
        optimize_concurrent_mio(& mut task, seeds)
    };


    let sense = task.get_obj_sense()?;
    // Pick the feasible result. For non-integer problems all
    // solutions should be the same if more than one is returned, but
    // for integer problems tasks may have hit the time limit and
    // returned non-optimal solutions.

    let n = r.len();

    if n == 0 {
        println!("All optimizers failed.");
    }
    else if numintvar > 0 {
        let (ii,_,tasks) = split3vec(r);

        let pobjs : Vec<(usize,f64)> =
            ii.iter().zip(tasks.iter()).enumerate()
            .filter_map(|(k,(_i,t))|
                match (*t).solution_def(Soltype::ITG) {
                    Ok(true) => match t.get_sol_sta(Soltype::ITG).unwrap() {
                        Solsta::PRIM_FEAS|Solsta::INTEGER_OPTIMAL => Some((k,t.get_primal_obj(Soltype::ITG).unwrap())),
                        _ => None
                    },
                    _ => None
                })
            .collect();

        let &(besti,bestobj) = pobjs.iter()
            .max_by(|(_,o1),(_,o2)|
                    match sense {
                        Objsense::MAXIMIZE => if o1 < o2 {Ordering::Less} else if o2 < o1 {Ordering::Greater} else {Ordering::Equal},
                        _ => if o1 > o2 {Ordering::Less} else if o2 > o1 {Ordering::Greater} else {Ordering::Equal}
                    }).unwrap();

        drop_except(tasks,besti).unwrap()
            .with_stream_callback(
                Streamtype::LOG, 
                &mut |msg| print!("{}",msg),
                |t| { 
                    t.optimizer_summary(mosek::Streamtype::LOG)?;
                    t.solution_summary(mosek::Streamtype::LOG)?;
                    Ok::<(),String>(())
                })?;

        println!("{} optimizers succeeded:",pobjs.len());
        for &(k,v) in pobjs.iter() {
            println!("Optimizer with seed #{} produced result : {:.5e}",ii[k],v);
        }

        println!("\tBest solution is #{}: {:.5e}",ii[besti],bestobj);
    }
    else {
        let (ii,_,tasks) = split3vec(r);

        let pobjs : Vec<(usize,f64)> =
            tasks.iter().enumerate()
            .filter_map(|(k,t)|
                        match t.get_sol_sta(Soltype::BAS) {
                            Ok(Solsta::PRIM_FEAS)|Ok(Solsta::OPTIMAL) => Some((k,t.get_primal_obj(Soltype::BAS).unwrap())),
                            _ => None
                        }.or_else(|| match t.get_sol_sta(Soltype::ITR) {
                            Ok(Solsta::PRIM_FEAS)|Ok(Solsta::OPTIMAL) => Some((k,t.get_primal_obj(Soltype::ITR).unwrap())),
                            _ => None
                        }))
            .collect();

        let &(besti,bestobj) = pobjs.iter()
            .max_by(|(_,o1),(_,o2)|
                    match sense {
                        Objsense::MAXIMIZE => if o1 < o2 {Ordering::Less} else if o2 < o1 {Ordering::Greater} else {Ordering::Equal},
                        _ => if o1 > o2 {Ordering::Less} else if o2 > o1 {Ordering::Greater} else {Ordering::Equal}
                    }).unwrap();

        drop_except(tasks,besti).unwrap()
            .with_stream_callback(
                Streamtype::LOG, 
                &mut|msg| print!("{}",msg),
                |t| {
                    t.optimizer_summary(mosek::Streamtype::LOG)?;
                    t.solution_summary(mosek::Streamtype::LOG)?;
                    Ok::<(),String>(())
                })?;

        println!("{} optimizers succeeded:",pobjs.len());
        for &(k,v) in pobjs.iter() {
            println!("Optimizer with seed #{} produced result : {:.5e}",ii[k],v);
        }

        println!("\tBest solution is #{}: {:.5e}",ii[besti],bestobj);
    }


    Result::Ok(())
}
examples/milo1.rs (line 74)
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
fn main() -> Result<(),String> {
    let numcon : i32 = 2;
    let numvar : i32 = 2;

    let infinity = 0.0; // only for symbolic purposes, value never used

    let bkc = vec![Boundkey::UP, Boundkey::LO];
    let blc = vec![ -infinity,         -4.0 ];
    let buc = vec![ 250.0,             infinity ];

    let bkx = vec![ Boundkey::LO, Boundkey::LO  ];
    let blx = vec![ 0.0,               0.0 ];
    let bux = vec![ infinity,          infinity ];

    let c   = vec![1.0, 0.64];

    let asub = vec![0,   1,
                    0,    1];
    let aval = vec![50.0, 3.0, 31.0, -2.0];

    let ptrb : Vec<usize> = vec![ 0, 2 ];
    let ptre : Vec<usize> = vec![ 2, 4 ];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG,
            &mut |msg| print!("{}",msg),
            |task| task.with_itg_sol_callback(
                &mut |xx| { println!("Found a new solution = {:?}",xx); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                    The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                    /* Append 'numvar' variables.
                    The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    for ((((j,cj),bk),bl),bu) in (0..numvar).zip(c.iter()).zip(bkx.iter()).zip(blx.iter()).zip(bux.iter()) {
                        /* Set the linear term c_j in the objective.*/
                        task.put_c_j(j, *cj)?;
                        /* Set the bounds on variable j.
                           blx[j] <= x_j <= bux[j] */
                        task.put_var_bound(j, *bk, *bl, *bu)?;
                        /* Input column j of A */
                        task.put_a_col(j,                     /* Variable (column) index.*/
                                       &asub[ptrb[j as usize]..ptre[j as usize]],               /* Row index of non-zeros in column j.*/
                                       &aval[ptrb[j as usize]..ptre[j as usize]])?;              /* Non-zero Values of column j. */
                    }
                    // Set the bounds on constraints.
                    // for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] 
                    for (((i,bk),bl),bu) in (0..numcon).zip(bkc.iter()).zip(blc.iter()).zip(buc.iter()) {
                        task.put_con_bound(i, *bk, *bl, *bu)?;
                    }

                    /* Specify integer variables. */
                    for j in 0..numvar {
                        task.put_var_type(j, Variabletype::TYPE_INT)?;
                    }
                    /* Set max solution time */
                    task.put_dou_param(Dparam::MIO_MAX_TIME, 60.0)?;

                    /* A maximization problem */
                    task.put_obj_sense(Objsense::MAXIMIZE)?;
                    /* Solve the problem */

                    let _trm = task.optimize()?;

                    // Print a summary containing information
                    //   about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITG, xx.as_mut_slice())?;

                    /* Get status information about the solution */

                    match task.get_sol_sta(Soltype::ITG)? {
                        Solsta::INTEGER_OPTIMAL => {
                            println!("Optimal solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::PRIM_FEAS => {
                            println!("Feasible solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::UNKNOWN => {
                          match task.get_pro_sta(Soltype::ITG)? {
                              Prosta::PRIM_INFEAS_OR_UNBOUNDED => {
                                  println!("Problem status Infeasible or unbounded");
                              }
                              Prosta::PRIM_INFEAS => {
                                  println!("Problem status Infeasible.");
                              }
                              Prosta::UNKNOWN => {
                                  println!("Problem status unknown.");
                              }
                              _ => {
                                  println!("Other problem status.");
                              }
                          }
                        }
                        _ => {
                            println!("Other solution status");
                        }
                    }
                    Ok(())
                }))
}
source

pub fn put_int_param( &mut self, param_: i32, parvalue_: i32 ) -> Result<(), String>

Sets an integer parameter.

§Arguments
  • param_ Which parameter.

    See Iparam

  • parvalue_ Parameter value.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putintparam

Examples found in repository?
examples/concurrent1.rs (line 48)
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
fn optimize_concurrent(task       : &mut mosek::Task,
                       optimizers : &[i32]) -> Vec<(usize,i32,mosek::Task)> {
    let stop = Arc::new(Mutex::new(false));
    optimizers.iter().enumerate()
        .filter_map(|(i,&ot)|
                    if let Some(mut t) = task.clone() {
                        if let Err(_) = t.put_int_param(mosek::Iparam::OPTIMIZER, ot as i32) { None }
                        else {
                            let stopopt = Arc::clone(&stop);
                            Some((i,thread::spawn(move || optimize(t,stopopt))))
                        }
                    }
                    else { None })
        .filter_map(|(i,th)|
                    match th.join().unwrap() {
                        None => None,
                        Some((r,t)) => Some((i,r,t)) } )
        .collect()
}

fn optimize_concurrent_mio(task  : & mut mosek::Task,
                           seeds : &[i32]) -> Vec<(usize,i32,mosek::Task)> {
    let stop = Arc::new(Mutex::new(false));

    seeds.iter().enumerate()
        .filter_map(|(i,&seed)| {
            if let Some(mut t) = task.clone() {
                if let Err(_) = t.put_int_param(mosek::Iparam::MIO_SEED, seed) { None }
                else {
                    let stopopt = Arc::clone(&stop);
                    Some((i,thread::spawn(move || optimize(t,stopopt))))
                }
            }
            else { None }})
        .filter_map(|(i,th)|
                    match th.join().unwrap() {
                        None => None,
                        Some((r,t)) => Some((i,r,t)) } )
        .collect()
}
More examples
Hide additional examples
examples/callback.rs (line 118)
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
fn callbackmain(which : &str, data : FileOrText) -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = Task::new().unwrap();
    match data {
        FileOrText::Text(data)  => { task.read_ptf_string(data)? },
        FileOrText::File(fname) => { task.read_data(fname)? }
    }

    task.write_data("callback.ptf")?;

    match which {
        "psim"   => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::PRIMAL_SIMPLEX)?,
        "dsim"   => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::DUAL_SIMPLEX)?,
        "intpnt" => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::INTPNT)?,
        s => return Err(format!("Invalid argument '{}'",s))
    }

    /* Directs the log task stream to the 'printstr' function. */
    task.with_stream_callback(
        Streamtype::LOG,
        & mut |msg| print!("{}",msg),
        |task|
            task.with_info_callback(
                & mut callback,
                |task|
                    task.optimize()
            )
    )?;

    Result::Ok(())
}
examples/parameters.rs (line 19)
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
fn main() -> Result<(),String> {
    let mut task = Task::new().unwrap();
    println!("Test MOSEK parameter get/set functions");

    // Set log level (integer parameter)
    task.put_int_param(Iparam::LOG, 1)?;
    // Select interior-point optimizer... (integer parameter)
    task.put_int_param(Iparam::OPTIMIZER, Optimizertype::INTPNT)?;
    // ... without basis identification (integer parameter)
    task.put_int_param(Iparam::INTPNT_BASIS,Basindtype::NEVER)?;
    // Set relative gap tolerance (double parameter)
    task.put_dou_param(Dparam::INTPNT_CO_TOL_REL_GAP, 1.0e-7)?;

    // The same using explicit string names
    task.put_param("MSK_DPAR_INTPNT_CO_TOL_REL_GAP", "1.0e-7")?;
    task.put_na_dou_param("MSK_DPAR_INTPNT_CO_TOL_REL_GAP",  1.0e-7 )?;

    // Incorrect value

    if let Err(_) = task.put_dou_param(Dparam::INTPNT_CO_TOL_REL_GAP, -1.0) {
        println!("Wrong parameter value");
    }


    let param = task.get_dou_param(Dparam::INTPNT_CO_TOL_REL_GAP)?;
    println!("Current value for parameter intpnt_co_tol_rel_gap = $param");

    // Define and solve an optimization problem here
    // optimize(task,)
    // After optimization:

    println!("Get MOSEK information items");

    let tm = task.get_dou_inf(Dinfitem::OPTIMIZER_TIME)?;
    let iter = task.get_int_inf(Iinfitem::INTPNT_ITER)?;

    println!("Time: {}",tm);
    println!("Iterations: {}",iter);
    Ok(())
}
examples/parallel.rs (line 40)
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
fn parallel(files : Vec<FileOrText>) -> Result<(),String> {
    // Create an example list of tasks to optimize
    let mut tasks : Vec<(String,Task)> = files.iter().filter_map(|fname| {
        let mut t = Task::new().unwrap();
        match fname {
            FileOrText::File(fname) => {
                if let Err(_) = t.read_data(fname.as_str()) { None }
                else {
                    t.put_int_param(mosek::Iparam::NUM_THREADS, 2).unwrap();
                    Some((fname.as_str().to_string(),t))
                }
            },
            FileOrText::Text(data) => {
                if let Err(_) = t.read_ptf_string(data.as_str()) { None }
                else {
                    t.put_int_param(mosek::Iparam::NUM_THREADS, 2).unwrap();
                    Some(("-".to_string(),t))
                }
            }
        }
    }).collect();

    let mut res = vec![0i32; tasks.len()];
    let mut trm = vec![0i32; tasks.len()];
    {
        let taskrs : Vec<& mut Task> = tasks.iter_mut().map(|(_a,b)| b).collect();

        // Size of thread pool available for all tasks
        let threadpoolsize : i32 = 6;

        // Optimize all the given tasks in parallel
        mosek::optimize_batch(false,          // No race
                              -1.0,           // No time limit
                              threadpoolsize,
                              taskrs.as_slice(),          // Array of tasks to optimize
                              trm.as_mut_slice(),
                              res.as_mut_slice())?;
    }

    for (resi,trmi,(fname,ti)) in izip!(res,trm,tasks.iter()) {
        println!("Task  {}  res {}   trm {}   obj_val  {}  time {}",
                 fname,
                 resi,
                 trmi,
                 ti.get_dou_inf(mosek::Dinfitem::INTPNT_PRIMAL_OBJ)?,
                 ti.get_dou_inf(mosek::Dinfitem::OPTIMIZER_TIME)?);
    }
    Ok(())
}
examples/reoptimization.rs (line 126)
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
fn main() -> Result<(),String> {

    let numcon = 3;
    let numvar = 3;
    let c = &[1.5, 2.5, 3.0 ];
    let bkc = &[ Boundkey::UP,
                 Boundkey::UP,
                 Boundkey::UP ];
    let blc = &[ -INF,
                 -INF,
                 -INF ];
    let buc = &[ 100000.0,
                 50000.0,
                 60000.0 ];
    let bkx = &[ Boundkey::LO,
                 Boundkey::LO,
                 Boundkey::LO
                             ];
    let blx = &[ 0.0, 0.0, 0.0 ];
    let bux = &[ INF,
                 INF,
                 INF ];

    let asub = &[
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ] ];

    let aval = &[
        &[ 2.0, 3.0, 2.0 ],
        &[ 4.0, 2.0, 3.0 ],
        &[ 3.0, 3.0, 2.0 ] ];


    let mut task = Task::new().unwrap();
    /* Append the constraints. */
    task.append_cons(numcon)?;

    /* Append the variables. */
    task.append_vars(numvar)?;

    /* Put C. */
    for (j,&cj) in (0..numvar).zip(c.iter()) {
        task.put_c_j(j,cj)?;
    }
    /* Put constraint bounds. */
    for (i,&bki,&bli,&bui) in izip!(0..numcon,bkc,blc,buc) {
        task.put_con_bound(i, bki, bli, bui)?;
    }

    /* Put variable bounds. */
    for (j,&bki,&bli,&bui) in izip!(0..numvar,bkx,blx,bux) {
        task.put_var_bound(j, bki, bli, bui)?;
    }

    /* Put A. */
    if numcon > 0 {
        for (j,&asubj,&avalj) in izip!(0..numvar,asub,aval) {
            task.put_a_col(j,
                           asubj,
                           avalj)?;
        }
    }

    /* A maximization problem */
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    /* Solve the problem */
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /****************** Make a change to the A matrix ******************/
    task.put_aij(0, 0, 3.0)?;
    let _trm = task.optimize()?;
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /***************** Add a new variable ******************************/
    /* Get index of new variable. */

    let varidx = task.get_num_var()?;

    /* Append a new variable x_3 to the problem */
    task.append_vars(1)?;
    let numvar = numvar + 1;

    /* Set bounds on new varaible */
    task.put_var_bound(varidx, Boundkey::LO, 0.0, INF)?;

    /* Change objective */
    task.put_c_j(varidx, 1.0)?;

    /* Put new values in the A matrix */
    let acolsub = &[0i32, 2];
    let acolval = &[4.0, 1.0];

    task.put_a_col(varidx, /* column index */
                   acolsub,
                   acolval)?;

    /* Change optimizer to simplex free and reoptimize */
    task.put_int_param(mosek::Iparam::OPTIMIZER, mosek::Optimizertype::FREE_SIMPLEX)?;
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Add a new constraint ***************************/
    /* Get index of new constraint. */
    let conidx = task.get_num_con()?;

    /* Append a new constraint */
    task.append_cons(1)?;
    let numcon = numcon + 1;

    /* Set bounds on new constraint */
    task.put_con_bound(conidx,
                       Boundkey::UP,
                       -INF,
                       30000.0)?;

    /* Put new values in the A matrix */
    let arowsub = &[0i32,   1,   2,   3  ];
    let arowval = &[1.0, 2.0, 1.0, 1.0 ];

    task.put_a_row(conidx, /* row index */
                   arowsub,
                   arowval)?;

    let _trm = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Change constraint bounds ********************/
    let newbkc = &[Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP];
    let newblc = &[-INF,
                   -INF,
                   -INF,
                   -INF];
    let newbuc = &[ 80000.0, 40000.0, 50000.0, 22000.0 ];

    task.put_con_bound_slice(0, numcon, newbkc, newblc, newbuc)?;

    let _ = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    Ok(())
}
source

pub fn put_max_num_acc(&mut self, maxnumacc_: i64) -> Result<(), String>

Sets the number of preallocated affine conic constraints.

§Arguments
  • maxnumacc_ Number of preallocated affine conic constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putmaxnumacc

source

pub fn put_max_num_afe(&mut self, maxnumafe_: i64) -> Result<(), String>

Sets the number of preallocated affine expressions in the optimization task.

§Arguments
  • maxnumafe_ Number of preallocated affine expressions.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putmaxnumafe

source

pub fn put_max_num_a_nz(&mut self, maxnumanz_: i64) -> Result<(), String>

Sets the number of preallocated non-zero entries in the linear coefficient matrix.

§Arguments
  • maxnumanz_ New size of the storage reserved for storing the linear coefficient matrix.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putmaxnumanz

source

pub fn put_max_num_barvar(&mut self, maxnumbarvar_: i32) -> Result<(), String>

Sets the number of preallocated symmetric matrix variables.

§Arguments
  • maxnumbarvar_ Number of preallocated symmetric matrix variables.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putmaxnumbarvar

source

pub fn put_max_num_con(&mut self, maxnumcon_: i32) -> Result<(), String>

Sets the number of preallocated constraints in the optimization task.

§Arguments
  • maxnumcon_ Number of preallocated constraints in the optimization task.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putmaxnumcon

source

pub fn put_max_num_cone(&mut self, maxnumcone_: i32) -> Result<(), String>

Sets the number of preallocated conic constraints in the optimization task.

§Arguments
  • maxnumcone_ Number of preallocated conic constraints in the optimization task.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putmaxnumcone

source

pub fn put_max_num_djc(&mut self, maxnumdjc_: i64) -> Result<(), String>

Sets the number of preallocated disjunctive constraints.

§Arguments
  • maxnumdjc_ Number of preallocated disjunctive constraints in the task.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putmaxnumdjc

source

pub fn put_max_num_domain(&mut self, maxnumdomain_: i64) -> Result<(), String>

Sets the number of preallocated domains in the optimization task.

§Arguments
  • maxnumdomain_ Number of preallocated domains.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putmaxnumdomain

source

pub fn put_max_num_q_nz(&mut self, maxnumqnz_: i64) -> Result<(), String>

Sets the number of preallocated non-zero entries in quadratic terms.

§Arguments
  • maxnumqnz_ Number of non-zero elements preallocated in quadratic coefficient matrices.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putmaxnumqnz

source

pub fn put_max_num_var(&mut self, maxnumvar_: i32) -> Result<(), String>

Sets the number of preallocated variables in the optimization task.

§Arguments
  • maxnumvar_ Number of preallocated variables in the optimization task.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putmaxnumvar

source

pub fn put_na_dou_param( &mut self, paramname_: &str, parvalue_: f64 ) -> Result<(), String>

Sets a double parameter.

§Arguments
  • paramname_ Name of a parameter.
  • parvalue_ Parameter value.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putnadouparam

Examples found in repository?
examples/parameters.rs (line 29)
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
fn main() -> Result<(),String> {
    let mut task = Task::new().unwrap();
    println!("Test MOSEK parameter get/set functions");

    // Set log level (integer parameter)
    task.put_int_param(Iparam::LOG, 1)?;
    // Select interior-point optimizer... (integer parameter)
    task.put_int_param(Iparam::OPTIMIZER, Optimizertype::INTPNT)?;
    // ... without basis identification (integer parameter)
    task.put_int_param(Iparam::INTPNT_BASIS,Basindtype::NEVER)?;
    // Set relative gap tolerance (double parameter)
    task.put_dou_param(Dparam::INTPNT_CO_TOL_REL_GAP, 1.0e-7)?;

    // The same using explicit string names
    task.put_param("MSK_DPAR_INTPNT_CO_TOL_REL_GAP", "1.0e-7")?;
    task.put_na_dou_param("MSK_DPAR_INTPNT_CO_TOL_REL_GAP",  1.0e-7 )?;

    // Incorrect value

    if let Err(_) = task.put_dou_param(Dparam::INTPNT_CO_TOL_REL_GAP, -1.0) {
        println!("Wrong parameter value");
    }


    let param = task.get_dou_param(Dparam::INTPNT_CO_TOL_REL_GAP)?;
    println!("Current value for parameter intpnt_co_tol_rel_gap = $param");

    // Define and solve an optimization problem here
    // optimize(task,)
    // After optimization:

    println!("Get MOSEK information items");

    let tm = task.get_dou_inf(Dinfitem::OPTIMIZER_TIME)?;
    let iter = task.get_int_inf(Iinfitem::INTPNT_ITER)?;

    println!("Time: {}",tm);
    println!("Iterations: {}",iter);
    Ok(())
}
source

pub fn put_na_int_param( &mut self, paramname_: &str, parvalue_: i32 ) -> Result<(), String>

Sets an integer parameter.

§Arguments
  • paramname_ Name of a parameter.
  • parvalue_ Parameter value.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putnaintparam

source

pub fn put_na_str_param( &mut self, paramname_: &str, parvalue_: &str ) -> Result<(), String>

Sets a string parameter.

§Arguments
  • paramname_ Name of a parameter.
  • parvalue_ Parameter value.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putnastrparam

source

pub fn put_obj_name(&mut self, objname_: &str) -> Result<(), String>

Assigns a new name to the objective.

§Arguments
  • objname_ Name of the objective.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putobjname

source

pub fn put_obj_sense(&mut self, sense_: i32) -> Result<(), String>

Sets the objective sense.

§Arguments
  • sense_ The objective sense of the task

    See Objsense

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putobjsense

Examples found in repository?
examples/helloworld.rs (line 23)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
fn main() -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
        };

    task.append_vars(1)?;                           // 1 variable x
    task.put_c_j(0, 1.0)?;                          // c_0 = 1.0
    task.put_var_bound(0, Boundkey::RA, 2.0, 3.0)?; // 2.0 <= x <= 3.0
    task.put_obj_sense(Objsense::MINIMIZE)?;        // minimize

    task.optimize()?;                               // Optimize

    let mut x = vec![0.0; 1];
    task.get_xx(Soltype::ITR, x.as_mut_slice())?;   // Get solution
    println!("Solution x = {}", x[0]);              // Print solution
    return Result::Ok(());
}
More examples
Hide additional examples
examples/portfolio_2_frontier.rs (line 53)
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
fn portfolio(n : i32,
             mu : &[f64],
             GT : &[f64],
             x0  : &[f64],
             alphas : &[f64],
             w : f64) -> Result<Vec<(f64,f64)>,String> {
    let k = (GT.len() / n as usize) as i32;
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(t) => t,
        None => return Err("Failed to create task".to_string()),
    };
    //task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    task.append_vars(n+1)?;
    task.append_cons(1)?;

    /* Objective */
    task.put_obj_sense(Objsense::MAXIMIZE)?;

    let x : Vec<i32> = (0i32..n).collect();
    let s = n;

    /* Total budget */
    let total_budget = w + x0.iter().sum::<f64>();

    /* Total budget constraint - set bounds l^c = u^c */
    task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
    task.put_con_name(0i32,"budget")?;
    task.put_c_slice(0,n,mu)?;

    /* x variables. */
    for (j,xj) in x.iter().enumerate() {
        /* Coefficients in the first row of A */
        task.put_aij(0, *xj, 1.0)?;
        /* No short-selling - x^l = 0, x^u = inf */
        task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
        task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
    }
    task.put_var_name(s, "s")?;
    task.put_var_bound(s, mosek::Boundkey::FR, 0.0, 0.0)?;

    // risk bound
    // (s,0.5,GT * x) in Q_r
    {
        let acci = task.get_num_acc()?;
        let afei = task.get_num_afe()?;

        task.append_afes(k as i64 + 2)?;
        let dom = task.append_r_quadratic_cone_domain(k as i64+2)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 2].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_f_entry(afei,s,1.0)?;
        task.put_afe_g(afei+1,0.5)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 2, j as i32, *v)?;
        }
    }

    let frontier : Vec<(f64,f64)> = alphas.iter().filter_map(|alpha| {
        /* Sets the objective function coefficient for s. */
        if      let Err(_) = task.put_c_j(s, - *alpha) { None }
        else if let Err(_) = task.optimize() { None }
        else if let Err(_) = task.write_data(format!("portfolio_2_frontier-{}.ptf",alpha).as_str()) { None }
        else if let Ok(solsta) = task.get_sol_sta(Soltype::ITR) {
            // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
            match solsta {
                Solsta::OPTIMAL => {
                    let mut xx = vec![0.0; n as usize+1];
                    if let Err(_) = task.get_xx(Soltype::ITR,xx.as_mut_slice()) { None }
                    else {
                        Some((*alpha,mu.iter().zip(xx.iter()).map(|(m,x)| m * x).sum::<f64>()))
                    }
                }
                _ => None
            }
        }
        else {
            None
        }
    }).collect();

    Ok(frontier)
}
examples/ceo1.rs (line 77)
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
fn main() -> Result<(),String> {
    let numcon = 1;
    let numvar = 3;

    let bkc = mosek::Boundkey::FX;
    let blc = 1.0;
    let buc = 1.0;

    let bkx = vec![ Boundkey::FR,
                    Boundkey::FR,
                    Boundkey::FR ];
    let blx = vec![ -INF, -INF, -INF ];
    let bux = vec![ INF, INF, INF ];
    let c   = vec![ 1.0, 1.0, 0.0 ];
    let a   = vec![ 1.0, 1.0, 1.0 ];
    let asub = vec![0, 1, 2];
    //let csub = new int[numvar];
    //double[] xx  = new double[numvar];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG, 
            &mut|msg| print!("{}",msg),
            |task| task.with_callback(
                &mut |caller| { println!("caller = {}",caller); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                       The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                      /* Append 'numvar' variables.
                         The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    /* Define the linear part of the problem */
                    task.put_c_slice(0, numvar, c.as_slice())?;
                    task.put_a_row(0, asub.as_slice(), a.as_slice())?;
                    task.put_con_bound(0, bkc, blc, buc)?;
                    task.put_var_bound_slice(0, numvar, bkx.as_slice(), blx.as_slice(), bux.as_slice())?;

                    /* Add a conic constraint */
                    task.append_afes(3)?;
                    let afeidxs = vec![0,  1,  2  ];
                    let b       = vec![0.0,0.0,0.0];
                    let domidx  = task.append_primal_exp_cone_domain()?;
                    task.put_afe_f_row_list(afeidxs.as_slice(),
                                            vec![1,1,1].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![1.0,1.0,1.0].as_slice())?;
                    task.append_acc(domidx,afeidxs.as_slice(),b.as_slice())?;

                    task.put_obj_sense(Objsense::MINIMIZE)?;

                    println!("optimize");
                    /* Solve the problem */
                    task.optimize()?;
                    // Print a summary containing information
                    // about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    /* Get status information about the solution */
                    let solsta = task.get_sol_sta(Soltype::ITR)?;

                    assert!(solsta == Solsta::OPTIMAL);
                    
                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITR, & mut xx[..])?;
                    
                    println!("Optimal primal solution");
                    for j in 0..numvar as usize {
                        println!("x[{}]: {:.4}",j,xx[j]);
                    }
                    Ok(())
                }))
}
examples/reoptimization.rs (line 80)
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
fn main() -> Result<(),String> {

    let numcon = 3;
    let numvar = 3;
    let c = &[1.5, 2.5, 3.0 ];
    let bkc = &[ Boundkey::UP,
                 Boundkey::UP,
                 Boundkey::UP ];
    let blc = &[ -INF,
                 -INF,
                 -INF ];
    let buc = &[ 100000.0,
                 50000.0,
                 60000.0 ];
    let bkx = &[ Boundkey::LO,
                 Boundkey::LO,
                 Boundkey::LO
                             ];
    let blx = &[ 0.0, 0.0, 0.0 ];
    let bux = &[ INF,
                 INF,
                 INF ];

    let asub = &[
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ] ];

    let aval = &[
        &[ 2.0, 3.0, 2.0 ],
        &[ 4.0, 2.0, 3.0 ],
        &[ 3.0, 3.0, 2.0 ] ];


    let mut task = Task::new().unwrap();
    /* Append the constraints. */
    task.append_cons(numcon)?;

    /* Append the variables. */
    task.append_vars(numvar)?;

    /* Put C. */
    for (j,&cj) in (0..numvar).zip(c.iter()) {
        task.put_c_j(j,cj)?;
    }
    /* Put constraint bounds. */
    for (i,&bki,&bli,&bui) in izip!(0..numcon,bkc,blc,buc) {
        task.put_con_bound(i, bki, bli, bui)?;
    }

    /* Put variable bounds. */
    for (j,&bki,&bli,&bui) in izip!(0..numvar,bkx,blx,bux) {
        task.put_var_bound(j, bki, bli, bui)?;
    }

    /* Put A. */
    if numcon > 0 {
        for (j,&asubj,&avalj) in izip!(0..numvar,asub,aval) {
            task.put_a_col(j,
                           asubj,
                           avalj)?;
        }
    }

    /* A maximization problem */
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    /* Solve the problem */
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /****************** Make a change to the A matrix ******************/
    task.put_aij(0, 0, 3.0)?;
    let _trm = task.optimize()?;
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /***************** Add a new variable ******************************/
    /* Get index of new variable. */

    let varidx = task.get_num_var()?;

    /* Append a new variable x_3 to the problem */
    task.append_vars(1)?;
    let numvar = numvar + 1;

    /* Set bounds on new varaible */
    task.put_var_bound(varidx, Boundkey::LO, 0.0, INF)?;

    /* Change objective */
    task.put_c_j(varidx, 1.0)?;

    /* Put new values in the A matrix */
    let acolsub = &[0i32, 2];
    let acolval = &[4.0, 1.0];

    task.put_a_col(varidx, /* column index */
                   acolsub,
                   acolval)?;

    /* Change optimizer to simplex free and reoptimize */
    task.put_int_param(mosek::Iparam::OPTIMIZER, mosek::Optimizertype::FREE_SIMPLEX)?;
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Add a new constraint ***************************/
    /* Get index of new constraint. */
    let conidx = task.get_num_con()?;

    /* Append a new constraint */
    task.append_cons(1)?;
    let numcon = numcon + 1;

    /* Set bounds on new constraint */
    task.put_con_bound(conidx,
                       Boundkey::UP,
                       -INF,
                       30000.0)?;

    /* Put new values in the A matrix */
    let arowsub = &[0i32,   1,   2,   3  ];
    let arowval = &[1.0, 2.0, 1.0, 1.0 ];

    task.put_a_row(conidx, /* row index */
                   arowsub,
                   arowval)?;

    let _trm = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Change constraint bounds ********************/
    let newbkc = &[Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP];
    let newblc = &[-INF,
                   -INF,
                   -INF,
                   -INF];
    let newbuc = &[ 80000.0, 40000.0, 50000.0, 22000.0 ];

    task.put_con_bound_slice(0, numcon, newbkc, newblc, newbuc)?;

    let _ = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    Ok(())
}
examples/portfolio_5_card.rs (line 85)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
examples/milo1.rs (line 77)
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
fn main() -> Result<(),String> {
    let numcon : i32 = 2;
    let numvar : i32 = 2;

    let infinity = 0.0; // only for symbolic purposes, value never used

    let bkc = vec![Boundkey::UP, Boundkey::LO];
    let blc = vec![ -infinity,         -4.0 ];
    let buc = vec![ 250.0,             infinity ];

    let bkx = vec![ Boundkey::LO, Boundkey::LO  ];
    let blx = vec![ 0.0,               0.0 ];
    let bux = vec![ infinity,          infinity ];

    let c   = vec![1.0, 0.64];

    let asub = vec![0,   1,
                    0,    1];
    let aval = vec![50.0, 3.0, 31.0, -2.0];

    let ptrb : Vec<usize> = vec![ 0, 2 ];
    let ptre : Vec<usize> = vec![ 2, 4 ];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG,
            &mut |msg| print!("{}",msg),
            |task| task.with_itg_sol_callback(
                &mut |xx| { println!("Found a new solution = {:?}",xx); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                    The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                    /* Append 'numvar' variables.
                    The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    for ((((j,cj),bk),bl),bu) in (0..numvar).zip(c.iter()).zip(bkx.iter()).zip(blx.iter()).zip(bux.iter()) {
                        /* Set the linear term c_j in the objective.*/
                        task.put_c_j(j, *cj)?;
                        /* Set the bounds on variable j.
                           blx[j] <= x_j <= bux[j] */
                        task.put_var_bound(j, *bk, *bl, *bu)?;
                        /* Input column j of A */
                        task.put_a_col(j,                     /* Variable (column) index.*/
                                       &asub[ptrb[j as usize]..ptre[j as usize]],               /* Row index of non-zeros in column j.*/
                                       &aval[ptrb[j as usize]..ptre[j as usize]])?;              /* Non-zero Values of column j. */
                    }
                    // Set the bounds on constraints.
                    // for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] 
                    for (((i,bk),bl),bu) in (0..numcon).zip(bkc.iter()).zip(blc.iter()).zip(buc.iter()) {
                        task.put_con_bound(i, *bk, *bl, *bu)?;
                    }

                    /* Specify integer variables. */
                    for j in 0..numvar {
                        task.put_var_type(j, Variabletype::TYPE_INT)?;
                    }
                    /* Set max solution time */
                    task.put_dou_param(Dparam::MIO_MAX_TIME, 60.0)?;

                    /* A maximization problem */
                    task.put_obj_sense(Objsense::MAXIMIZE)?;
                    /* Solve the problem */

                    let _trm = task.optimize()?;

                    // Print a summary containing information
                    //   about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITG, xx.as_mut_slice())?;

                    /* Get status information about the solution */

                    match task.get_sol_sta(Soltype::ITG)? {
                        Solsta::INTEGER_OPTIMAL => {
                            println!("Optimal solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::PRIM_FEAS => {
                            println!("Feasible solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::UNKNOWN => {
                          match task.get_pro_sta(Soltype::ITG)? {
                              Prosta::PRIM_INFEAS_OR_UNBOUNDED => {
                                  println!("Problem status Infeasible or unbounded");
                              }
                              Prosta::PRIM_INFEAS => {
                                  println!("Problem status Infeasible.");
                              }
                              Prosta::UNKNOWN => {
                                  println!("Problem status unknown.");
                              }
                              _ => {
                                  println!("Other problem status.");
                              }
                          }
                        }
                        _ => {
                            println!("Other solution status");
                        }
                    }
                    Ok(())
                }))
}
source

pub fn put_optserver_host(&mut self, host_: &str) -> Result<(), String>

Specify an OptServer for remote calls.

§Arguments
  • host_ A URL specifying the optimization server to be used.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putoptserverhost

source

pub fn put_param( &mut self, parname_: &str, parvalue_: &str ) -> Result<(), String>

Modifies the value of parameter.

§Arguments
  • parname_ Parameter name.
  • parvalue_ Parameter value.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putparam

Examples found in repository?
examples/parameters.rs (line 28)
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
fn main() -> Result<(),String> {
    let mut task = Task::new().unwrap();
    println!("Test MOSEK parameter get/set functions");

    // Set log level (integer parameter)
    task.put_int_param(Iparam::LOG, 1)?;
    // Select interior-point optimizer... (integer parameter)
    task.put_int_param(Iparam::OPTIMIZER, Optimizertype::INTPNT)?;
    // ... without basis identification (integer parameter)
    task.put_int_param(Iparam::INTPNT_BASIS,Basindtype::NEVER)?;
    // Set relative gap tolerance (double parameter)
    task.put_dou_param(Dparam::INTPNT_CO_TOL_REL_GAP, 1.0e-7)?;

    // The same using explicit string names
    task.put_param("MSK_DPAR_INTPNT_CO_TOL_REL_GAP", "1.0e-7")?;
    task.put_na_dou_param("MSK_DPAR_INTPNT_CO_TOL_REL_GAP",  1.0e-7 )?;

    // Incorrect value

    if let Err(_) = task.put_dou_param(Dparam::INTPNT_CO_TOL_REL_GAP, -1.0) {
        println!("Wrong parameter value");
    }


    let param = task.get_dou_param(Dparam::INTPNT_CO_TOL_REL_GAP)?;
    println!("Current value for parameter intpnt_co_tol_rel_gap = $param");

    // Define and solve an optimization problem here
    // optimize(task,)
    // After optimization:

    println!("Get MOSEK information items");

    let tm = task.get_dou_inf(Dinfitem::OPTIMIZER_TIME)?;
    let iter = task.get_int_inf(Iinfitem::INTPNT_ITER)?;

    println!("Time: {}",tm);
    println!("Iterations: {}",iter);
    Ok(())
}
source

pub fn put_q_con( &mut self, qcsubk_: &[i32], qcsubi_: &[i32], qcsubj_: &[i32], qcval_: &[f64] ) -> Result<(), String>

Replaces all quadratic terms in constraints.

§Arguments
  • qcsubk_ Constraint subscripts for quadratic coefficients.
  • qcsubi_ Row subscripts for quadratic constraint matrix.
  • qcsubj_ Column subscripts for quadratic constraint matrix.
  • qcval_ Quadratic constraint coefficient values.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putqcon

source

pub fn put_q_con_k( &mut self, k_: i32, qcsubi_: &[i32], qcsubj_: &[i32], qcval_: &[f64] ) -> Result<(), String>

Replaces all quadratic terms in a single constraint.

§Arguments
  • k_ The constraint in which the new quadratic elements are inserted.
  • qcsubi_ Row subscripts for quadratic constraint matrix.
  • qcsubj_ Column subscripts for quadratic constraint matrix.
  • qcval_ Quadratic constraint coefficient values.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putqconk

source

pub fn put_q_obj( &mut self, qosubi_: &[i32], qosubj_: &[i32], qoval_: &[f64] ) -> Result<(), String>

Replaces all quadratic terms in the objective.

§Arguments
  • qosubi_ Row subscripts for quadratic objective coefficients.
  • qosubj_ Column subscripts for quadratic objective coefficients.
  • qoval_ Quadratic objective coefficient values.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putqobj

source

pub fn put_q_obj_i_j( &mut self, i_: i32, j_: i32, qoij_: f64 ) -> Result<(), String>

Replaces one coefficient in the quadratic term in the objective.

§Arguments
  • i_ Row index for the coefficient to be replaced.
  • j_ Column index for the coefficient to be replaced.
  • qoij_ The new coefficient value.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putqobjij

source

pub fn put_skc(&mut self, whichsol_: i32, skc_: &[i32]) -> Result<(), String>

Sets the status keys for the constraints.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • skc_ Status keys for the constraints.

    See Stakey

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putskc

source

pub fn put_skc_slice( &mut self, whichsol_: i32, first_: i32, last_: i32, skc_: &[i32] ) -> Result<(), String>

Sets the status keys for a slice of the constraints.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • skc_ Status keys for the constraints.

    See Stakey

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putskcslice

Examples found in repository?
examples/solvelinear.rs (line 53)
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
fn setup(task : & mut mosek::Task,
         aval : &[f64],
         asub : &[i32],
         ptrb : &[i64],
         ptre : &[i64],
         numvar : i32) -> Result<Vec<i32>,String> {

    // mosek.stakey[] skx = new mosek.stakey [numvar];
    // mosek.stakey[] skc = new mosek.stakey [numvar];

    // for (int i = 0; i < numvar ; ++i) {
    //   skx[i] = mosek.stakey.bas;
    //   skc[i] = mosek.stakey.fix;
    // }

    task.append_vars(numvar)?;
    task.append_cons(numvar)?;

    task.put_a_col_slice(0,numvar,ptrb,ptre,asub,aval)?;

    task.put_con_bound_slice_const(0,numvar,Boundkey::FX,0.0,0.0)?;
    task.put_var_bound_slice_const(0,numvar,Boundkey::FR,-INF,INF)?;

    /* Define a basic solution by specifying
       status keys for variables & constraints. */
    task.delete_solution(Soltype::BAS)?;

    task.put_skc_slice(Soltype::BAS, 0, numvar, vec![Stakey::FIX; numvar as usize].as_slice())?;
    task.put_skx_slice(Soltype::BAS, 0, numvar, vec![Stakey::BAS; numvar as usize].as_slice())?;

    let mut basis = vec![0; numvar as usize];
    task.init_basis_solve(basis.as_mut_slice())?;
    Ok(basis)
  }
source

pub fn put_skx(&mut self, whichsol_: i32, skx_: &[i32]) -> Result<(), String>

Sets the status keys for the scalar variables.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • skx_ Status keys for the variables.

    See Stakey

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putskx

source

pub fn put_skx_slice( &mut self, whichsol_: i32, first_: i32, last_: i32, skx_: &[i32] ) -> Result<(), String>

Sets the status keys for a slice of the variables.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • skx_ Status keys for the variables.

    See Stakey

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putskxslice

Examples found in repository?
examples/solvelinear.rs (line 54)
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
fn setup(task : & mut mosek::Task,
         aval : &[f64],
         asub : &[i32],
         ptrb : &[i64],
         ptre : &[i64],
         numvar : i32) -> Result<Vec<i32>,String> {

    // mosek.stakey[] skx = new mosek.stakey [numvar];
    // mosek.stakey[] skc = new mosek.stakey [numvar];

    // for (int i = 0; i < numvar ; ++i) {
    //   skx[i] = mosek.stakey.bas;
    //   skc[i] = mosek.stakey.fix;
    // }

    task.append_vars(numvar)?;
    task.append_cons(numvar)?;

    task.put_a_col_slice(0,numvar,ptrb,ptre,asub,aval)?;

    task.put_con_bound_slice_const(0,numvar,Boundkey::FX,0.0,0.0)?;
    task.put_var_bound_slice_const(0,numvar,Boundkey::FR,-INF,INF)?;

    /* Define a basic solution by specifying
       status keys for variables & constraints. */
    task.delete_solution(Soltype::BAS)?;

    task.put_skc_slice(Soltype::BAS, 0, numvar, vec![Stakey::FIX; numvar as usize].as_slice())?;
    task.put_skx_slice(Soltype::BAS, 0, numvar, vec![Stakey::BAS; numvar as usize].as_slice())?;

    let mut basis = vec![0; numvar as usize];
    task.init_basis_solve(basis.as_mut_slice())?;
    Ok(basis)
  }
source

pub fn put_slc(&mut self, whichsol_: i32, slc_: &[f64]) -> Result<(), String>

Sets the slc vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • slc_ Dual variables corresponding to the lower bounds on the constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putslc

source

pub fn put_slc_slice( &mut self, whichsol_: i32, first_: i32, last_: i32, slc_: &[f64] ) -> Result<(), String>

Sets a slice of the slc vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • slc_ Dual variables corresponding to the lower bounds on the constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putslcslice

source

pub fn put_slx(&mut self, whichsol_: i32, slx_: &[f64]) -> Result<(), String>

Sets the slx vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • slx_ Dual variables corresponding to the lower bounds on the variables.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putslx

source

pub fn put_slx_slice( &mut self, whichsol_: i32, first_: i32, last_: i32, slx_: &[f64] ) -> Result<(), String>

Sets a slice of the slx vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • slx_ Dual variables corresponding to the lower bounds on the variables.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putslxslice

source

pub fn put_snx(&mut self, whichsol_: i32, sux_: &[f64]) -> Result<(), String>

Sets the snx vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • sux_ Dual variables corresponding to the upper bounds on the variables.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putsnx

source

pub fn put_snx_slice( &mut self, whichsol_: i32, first_: i32, last_: i32, snx_: &[f64] ) -> Result<(), String>

Sets a slice of the snx vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • snx_ Dual variables corresponding to the conic constraints on the variables.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putsnxslice

source

pub fn put_solution( &mut self, whichsol_: i32, skc_: &[i32], skx_: &[i32], skn_: &[i32], xc_: &[f64], xx_: &[f64], y_: &[f64], slc_: &[f64], suc_: &[f64], slx_: &[f64], sux_: &[f64], snx_: &[f64] ) -> Result<(), String>

Inserts a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • skc_ Status keys for the constraints.

    See Stakey

  • skx_ Status keys for the variables.

    See Stakey

  • skn_ Status keys for the conic constraints.

    See Stakey

  • xc_ Primal constraint solution.

  • xx_ Primal variable solution.

  • y_ Vector of dual variables corresponding to the constraints.

  • slc_ Dual variables corresponding to the lower bounds on the constraints.

  • suc_ Dual variables corresponding to the upper bounds on the constraints.

  • slx_ Dual variables corresponding to the lower bounds on the variables.

  • sux_ Dual variables corresponding to the upper bounds on the variables.

  • snx_ Dual variables corresponding to the conic constraints on the variables.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putsolution

source

pub fn put_solution_new( &mut self, whichsol_: i32, skc_: &[i32], skx_: &[i32], skn_: &[i32], xc_: &[f64], xx_: &[f64], y_: &[f64], slc_: &[f64], suc_: &[f64], slx_: &[f64], sux_: &[f64], snx_: &[f64], doty_: &[f64] ) -> Result<(), String>

Inserts a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • skc_ Status keys for the constraints.

    See Stakey

  • skx_ Status keys for the variables.

    See Stakey

  • skn_ Status keys for the conic constraints.

    See Stakey

  • xc_ Primal constraint solution.

  • xx_ Primal variable solution.

  • y_ Vector of dual variables corresponding to the constraints.

  • slc_ Dual variables corresponding to the lower bounds on the constraints.

  • suc_ Dual variables corresponding to the upper bounds on the constraints.

  • slx_ Dual variables corresponding to the lower bounds on the variables.

  • sux_ Dual variables corresponding to the upper bounds on the variables.

  • snx_ Dual variables corresponding to the conic constraints on the variables.

  • doty_ Dual variables corresponding to affine conic constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putsolutionnew

source

pub fn put_solution_y_i( &mut self, i_: i32, whichsol_: i32, y_: f64 ) -> Result<(), String>

Inputs the dual variable of a solution.

§Arguments
  • i_ Index of the dual variable.

  • whichsol_ Selects a solution.

    See Soltype

  • y_ Solution value of the dual variable.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putsolutionyi

source

pub fn put_str_param( &mut self, param_: i32, parvalue_: &str ) -> Result<(), String>

Sets a string parameter.

§Arguments
  • param_ Which parameter.

    See Sparam

  • parvalue_ Parameter value.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putstrparam

Examples found in repository?
examples/opt_server_async.rs (line 48)
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
fn opt_server_async(inputfile : FileOrText, addr : String, numpolls : usize, cert : Option<String>) -> Result<(),String> {
    // Path to certificate, if any

    let token = {
        Task::new().unwrap()
            .with_stream_callback(
                Streamtype::LOG,
                &mut |msg| print!("{}",msg),
                |task| {
                    match inputfile {
                        FileOrText::File(ref filename) => task.read_data(filename.as_str()).unwrap(),
                        FileOrText::Text(ref data)     => task.read_ptf_string(data.as_str()).unwrap()
                    }
                    if let Some(ref cert) = cert {
                        task.put_str_param(Sparam::REMOTE_TLS_CERT_PATH,cert.as_str())?;
                    }
                    task.async_optimize(addr.as_str(),"")
                }).expect("Failed to submit async optimization")
    };

    println!("Task token = '{}'", token);

    println!("Setting log stream...");
    Task::new().unwrap().with_stream_callback(
        Streamtype::LOG,
        & mut |msg| print!("{}",msg),
        |task| task.with_callback(
            &mut|caller| { println!("caller = {}",caller); false },
            |task| {
                println!("Reading input file '{:?}'...",inputfile);
                match inputfile {
                    FileOrText::File(ref filename) => task.read_data(filename.as_str()).unwrap(),
                    FileOrText::Text(ref data)     => task.read_ptf_string(data.as_str()).unwrap()
                }
                if let Some(ref cert) = cert {
                    task.put_str_param(Sparam::REMOTE_TLS_CERT_PATH,cert.as_str())?;
                }

                println!("Starting polling loop...");
                for i in 0..numpolls {
                    sleep(Duration::new(1,0));

                    println!("\tpoll {}...", i);

                    let mut trm  : i32 = 0;
                    let mut resp : i32 = 0;

                    let respavailable = task.async_poll(addr.as_str(),
                                                        "",
                                                        token.as_str(),
                                                        & mut resp,
                                                        & mut trm)?;

                    if respavailable {
                        println!("solution available!");

                        task.async_get_result(addr.as_str(),
                                              "",
                                              token.as_str(),
                                              & mut resp,
                                              & mut trm)?;

                        task.solution_summary (Streamtype::LOG)?;
                        return Ok(());
                    }
                }

                println!("max num polls reached, stopping host.");
                task.async_stop (addr.as_str(), "", token.as_str())?;
                Err("Max num polls".to_string())
            }))
}
source

pub fn put_suc(&mut self, whichsol_: i32, suc_: &[f64]) -> Result<(), String>

Sets the suc vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • suc_ Dual variables corresponding to the upper bounds on the constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putsuc

source

pub fn put_suc_slice( &mut self, whichsol_: i32, first_: i32, last_: i32, suc_: &[f64] ) -> Result<(), String>

Sets a slice of the suc vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • suc_ Dual variables corresponding to the upper bounds on the constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putsucslice

source

pub fn put_sux(&mut self, whichsol_: i32, sux_: &[f64]) -> Result<(), String>

Sets the sux vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • sux_ Dual variables corresponding to the upper bounds on the variables.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putsux

source

pub fn put_sux_slice( &mut self, whichsol_: i32, first_: i32, last_: i32, sux_: &[f64] ) -> Result<(), String>

Sets a slice of the sux vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • sux_ Dual variables corresponding to the upper bounds on the variables.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putsuxslice

source

pub fn put_task_name(&mut self, taskname_: &str) -> Result<(), String>

Assigns a new name to the task.

§Arguments
  • taskname_ Name assigned to the task.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.puttaskname

source

pub fn put_var_bound( &mut self, j_: i32, bkx_: i32, blx_: f64, bux_: f64 ) -> Result<(), String>

Changes the bounds for one variable.

§Arguments
  • j_ Index of the variable.

  • bkx_ New bound key.

    See Boundkey

  • blx_ New lower bound.

  • bux_ New upper bound.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putvarbound

Examples found in repository?
examples/helloworld.rs (line 22)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
fn main() -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
        };

    task.append_vars(1)?;                           // 1 variable x
    task.put_c_j(0, 1.0)?;                          // c_0 = 1.0
    task.put_var_bound(0, Boundkey::RA, 2.0, 3.0)?; // 2.0 <= x <= 3.0
    task.put_obj_sense(Objsense::MINIMIZE)?;        // minimize

    task.optimize()?;                               // Optimize

    let mut x = vec![0.0; 1];
    task.get_xx(Soltype::ITR, x.as_mut_slice())?;   // Get solution
    println!("Solution x = {}", x[0]);              // Print solution
    return Result::Ok(());
}
More examples
Hide additional examples
examples/portfolio_2_frontier.rs (line 71)
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
fn portfolio(n : i32,
             mu : &[f64],
             GT : &[f64],
             x0  : &[f64],
             alphas : &[f64],
             w : f64) -> Result<Vec<(f64,f64)>,String> {
    let k = (GT.len() / n as usize) as i32;
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(t) => t,
        None => return Err("Failed to create task".to_string()),
    };
    //task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    task.append_vars(n+1)?;
    task.append_cons(1)?;

    /* Objective */
    task.put_obj_sense(Objsense::MAXIMIZE)?;

    let x : Vec<i32> = (0i32..n).collect();
    let s = n;

    /* Total budget */
    let total_budget = w + x0.iter().sum::<f64>();

    /* Total budget constraint - set bounds l^c = u^c */
    task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
    task.put_con_name(0i32,"budget")?;
    task.put_c_slice(0,n,mu)?;

    /* x variables. */
    for (j,xj) in x.iter().enumerate() {
        /* Coefficients in the first row of A */
        task.put_aij(0, *xj, 1.0)?;
        /* No short-selling - x^l = 0, x^u = inf */
        task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
        task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
    }
    task.put_var_name(s, "s")?;
    task.put_var_bound(s, mosek::Boundkey::FR, 0.0, 0.0)?;

    // risk bound
    // (s,0.5,GT * x) in Q_r
    {
        let acci = task.get_num_acc()?;
        let afei = task.get_num_afe()?;

        task.append_afes(k as i64 + 2)?;
        let dom = task.append_r_quadratic_cone_domain(k as i64+2)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 2].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_f_entry(afei,s,1.0)?;
        task.put_afe_g(afei+1,0.5)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 2, j as i32, *v)?;
        }
    }

    let frontier : Vec<(f64,f64)> = alphas.iter().filter_map(|alpha| {
        /* Sets the objective function coefficient for s. */
        if      let Err(_) = task.put_c_j(s, - *alpha) { None }
        else if let Err(_) = task.optimize() { None }
        else if let Err(_) = task.write_data(format!("portfolio_2_frontier-{}.ptf",alpha).as_str()) { None }
        else if let Ok(solsta) = task.get_sol_sta(Soltype::ITR) {
            // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
            match solsta {
                Solsta::OPTIMAL => {
                    let mut xx = vec![0.0; n as usize+1];
                    if let Err(_) = task.get_xx(Soltype::ITR,xx.as_mut_slice()) { None }
                    else {
                        Some((*alpha,mu.iter().zip(xx.iter()).map(|(m,x)| m * x).sum::<f64>()))
                    }
                }
                _ => None
            }
        }
        else {
            None
        }
    }).collect();

    Ok(frontier)
}
examples/reoptimization.rs (line 67)
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
fn main() -> Result<(),String> {

    let numcon = 3;
    let numvar = 3;
    let c = &[1.5, 2.5, 3.0 ];
    let bkc = &[ Boundkey::UP,
                 Boundkey::UP,
                 Boundkey::UP ];
    let blc = &[ -INF,
                 -INF,
                 -INF ];
    let buc = &[ 100000.0,
                 50000.0,
                 60000.0 ];
    let bkx = &[ Boundkey::LO,
                 Boundkey::LO,
                 Boundkey::LO
                             ];
    let blx = &[ 0.0, 0.0, 0.0 ];
    let bux = &[ INF,
                 INF,
                 INF ];

    let asub = &[
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ],
        &[ 0i32, 1, 2 ] ];

    let aval = &[
        &[ 2.0, 3.0, 2.0 ],
        &[ 4.0, 2.0, 3.0 ],
        &[ 3.0, 3.0, 2.0 ] ];


    let mut task = Task::new().unwrap();
    /* Append the constraints. */
    task.append_cons(numcon)?;

    /* Append the variables. */
    task.append_vars(numvar)?;

    /* Put C. */
    for (j,&cj) in (0..numvar).zip(c.iter()) {
        task.put_c_j(j,cj)?;
    }
    /* Put constraint bounds. */
    for (i,&bki,&bli,&bui) in izip!(0..numcon,bkc,blc,buc) {
        task.put_con_bound(i, bki, bli, bui)?;
    }

    /* Put variable bounds. */
    for (j,&bki,&bli,&bui) in izip!(0..numvar,bkx,blx,bux) {
        task.put_var_bound(j, bki, bli, bui)?;
    }

    /* Put A. */
    if numcon > 0 {
        for (j,&asubj,&avalj) in izip!(0..numvar,asub,aval) {
            task.put_a_col(j,
                           asubj,
                           avalj)?;
        }
    }

    /* A maximization problem */
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    /* Solve the problem */
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /****************** Make a change to the A matrix ******************/
    task.put_aij(0, 0, 3.0)?;
    let _trm = task.optimize()?;
    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in xx.iter().enumerate() {
        println!("x[{}]: {}",j,xj);
    }

    /***************** Add a new variable ******************************/
    /* Get index of new variable. */

    let varidx = task.get_num_var()?;

    /* Append a new variable x_3 to the problem */
    task.append_vars(1)?;
    let numvar = numvar + 1;

    /* Set bounds on new varaible */
    task.put_var_bound(varidx, Boundkey::LO, 0.0, INF)?;

    /* Change objective */
    task.put_c_j(varidx, 1.0)?;

    /* Put new values in the A matrix */
    let acolsub = &[0i32, 2];
    let acolval = &[4.0, 1.0];

    task.put_a_col(varidx, /* column index */
                   acolsub,
                   acolval)?;

    /* Change optimizer to simplex free and reoptimize */
    task.put_int_param(mosek::Iparam::OPTIMIZER, mosek::Optimizertype::FREE_SIMPLEX)?;
    let _trm = task.optimize()?;

    let mut xx = vec![0.0; task.get_num_var()? as usize];
    task.get_xx(Soltype::BAS, xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Add a new constraint ***************************/
    /* Get index of new constraint. */
    let conidx = task.get_num_con()?;

    /* Append a new constraint */
    task.append_cons(1)?;
    let numcon = numcon + 1;

    /* Set bounds on new constraint */
    task.put_con_bound(conidx,
                       Boundkey::UP,
                       -INF,
                       30000.0)?;

    /* Put new values in the A matrix */
    let arowsub = &[0i32,   1,   2,   3  ];
    let arowval = &[1.0, 2.0, 1.0, 1.0 ];

    task.put_a_row(conidx, /* row index */
                   arowsub,
                   arowval)?;

    let _trm = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    /********************** Change constraint bounds ********************/
    let newbkc = &[Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP,
                   Boundkey::UP];
    let newblc = &[-INF,
                   -INF,
                   -INF,
                   -INF];
    let newbuc = &[ 80000.0, 40000.0, 50000.0, 22000.0 ];

    task.put_con_bound_slice(0, numcon, newbkc, newblc, newbuc)?;

    let _ = task.optimize()?;

    task.get_xx(Soltype::BAS, // Request the basic solution.
                xx.as_mut_slice())?;

    for (j,xj) in (0..numvar).zip(xx.iter()) {
        println!("x[{}]: {}",j,xj);
    }

    Ok(())
}
examples/milo1.rs (line 57)
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
fn main() -> Result<(),String> {
    let numcon : i32 = 2;
    let numvar : i32 = 2;

    let infinity = 0.0; // only for symbolic purposes, value never used

    let bkc = vec![Boundkey::UP, Boundkey::LO];
    let blc = vec![ -infinity,         -4.0 ];
    let buc = vec![ 250.0,             infinity ];

    let bkx = vec![ Boundkey::LO, Boundkey::LO  ];
    let blx = vec![ 0.0,               0.0 ];
    let bux = vec![ infinity,          infinity ];

    let c   = vec![1.0, 0.64];

    let asub = vec![0,   1,
                    0,    1];
    let aval = vec![50.0, 3.0, 31.0, -2.0];

    let ptrb : Vec<usize> = vec![ 0, 2 ];
    let ptre : Vec<usize> = vec![ 2, 4 ];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG,
            &mut |msg| print!("{}",msg),
            |task| task.with_itg_sol_callback(
                &mut |xx| { println!("Found a new solution = {:?}",xx); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                    The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                    /* Append 'numvar' variables.
                    The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    for ((((j,cj),bk),bl),bu) in (0..numvar).zip(c.iter()).zip(bkx.iter()).zip(blx.iter()).zip(bux.iter()) {
                        /* Set the linear term c_j in the objective.*/
                        task.put_c_j(j, *cj)?;
                        /* Set the bounds on variable j.
                           blx[j] <= x_j <= bux[j] */
                        task.put_var_bound(j, *bk, *bl, *bu)?;
                        /* Input column j of A */
                        task.put_a_col(j,                     /* Variable (column) index.*/
                                       &asub[ptrb[j as usize]..ptre[j as usize]],               /* Row index of non-zeros in column j.*/
                                       &aval[ptrb[j as usize]..ptre[j as usize]])?;              /* Non-zero Values of column j. */
                    }
                    // Set the bounds on constraints.
                    // for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] 
                    for (((i,bk),bl),bu) in (0..numcon).zip(bkc.iter()).zip(blc.iter()).zip(buc.iter()) {
                        task.put_con_bound(i, *bk, *bl, *bu)?;
                    }

                    /* Specify integer variables. */
                    for j in 0..numvar {
                        task.put_var_type(j, Variabletype::TYPE_INT)?;
                    }
                    /* Set max solution time */
                    task.put_dou_param(Dparam::MIO_MAX_TIME, 60.0)?;

                    /* A maximization problem */
                    task.put_obj_sense(Objsense::MAXIMIZE)?;
                    /* Solve the problem */

                    let _trm = task.optimize()?;

                    // Print a summary containing information
                    //   about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITG, xx.as_mut_slice())?;

                    /* Get status information about the solution */

                    match task.get_sol_sta(Soltype::ITG)? {
                        Solsta::INTEGER_OPTIMAL => {
                            println!("Optimal solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::PRIM_FEAS => {
                            println!("Feasible solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::UNKNOWN => {
                          match task.get_pro_sta(Soltype::ITG)? {
                              Prosta::PRIM_INFEAS_OR_UNBOUNDED => {
                                  println!("Problem status Infeasible or unbounded");
                              }
                              Prosta::PRIM_INFEAS => {
                                  println!("Problem status Infeasible.");
                              }
                              Prosta::UNKNOWN => {
                                  println!("Problem status unknown.");
                              }
                              _ => {
                                  println!("Other problem status.");
                              }
                          }
                        }
                        _ => {
                            println!("Other solution status");
                        }
                    }
                    Ok(())
                }))
}
source

pub fn put_var_bound_list( &mut self, sub_: &[i32], bkx_: &[i32], blx_: &[f64], bux_: &[f64] ) -> Result<(), String>

Changes the bounds of a list of variables.

§Arguments
  • sub_ List of variable indexes.

  • bkx_ Bound keys for the variables.

    See Boundkey

  • blx_ Lower bounds for the variables.

  • bux_ Upper bounds for the variables.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putvarboundlist

source

pub fn put_var_bound_list_const( &mut self, sub_: &[i32], bkx_: i32, blx_: f64, bux_: f64 ) -> Result<(), String>

Changes the bounds of a list of variables.

§Arguments
  • sub_ List of variable indexes.

  • bkx_ New bound key for all variables in the list.

    See Boundkey

  • blx_ New lower bound for all variables in the list.

  • bux_ New upper bound for all variables in the list.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putvarboundlistconst

source

pub fn put_var_bound_slice( &mut self, first_: i32, last_: i32, bkx_: &[i32], blx_: &[f64], bux_: &[f64] ) -> Result<(), String>

Changes the bounds for a slice of the variables.

§Arguments
  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • bkx_ Bound keys for the variables.

    See Boundkey

  • blx_ Lower bounds for the variables.

  • bux_ Upper bounds for the variables.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putvarboundslice

Examples found in repository?
examples/ceo1.rs (line 63)
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
fn main() -> Result<(),String> {
    let numcon = 1;
    let numvar = 3;

    let bkc = mosek::Boundkey::FX;
    let blc = 1.0;
    let buc = 1.0;

    let bkx = vec![ Boundkey::FR,
                    Boundkey::FR,
                    Boundkey::FR ];
    let blx = vec![ -INF, -INF, -INF ];
    let bux = vec![ INF, INF, INF ];
    let c   = vec![ 1.0, 1.0, 0.0 ];
    let a   = vec![ 1.0, 1.0, 1.0 ];
    let asub = vec![0, 1, 2];
    //let csub = new int[numvar];
    //double[] xx  = new double[numvar];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG, 
            &mut|msg| print!("{}",msg),
            |task| task.with_callback(
                &mut |caller| { println!("caller = {}",caller); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                       The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                      /* Append 'numvar' variables.
                         The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    /* Define the linear part of the problem */
                    task.put_c_slice(0, numvar, c.as_slice())?;
                    task.put_a_row(0, asub.as_slice(), a.as_slice())?;
                    task.put_con_bound(0, bkc, blc, buc)?;
                    task.put_var_bound_slice(0, numvar, bkx.as_slice(), blx.as_slice(), bux.as_slice())?;

                    /* Add a conic constraint */
                    task.append_afes(3)?;
                    let afeidxs = vec![0,  1,  2  ];
                    let b       = vec![0.0,0.0,0.0];
                    let domidx  = task.append_primal_exp_cone_domain()?;
                    task.put_afe_f_row_list(afeidxs.as_slice(),
                                            vec![1,1,1].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![1.0,1.0,1.0].as_slice())?;
                    task.append_acc(domidx,afeidxs.as_slice(),b.as_slice())?;

                    task.put_obj_sense(Objsense::MINIMIZE)?;

                    println!("optimize");
                    /* Solve the problem */
                    task.optimize()?;
                    // Print a summary containing information
                    // about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    /* Get status information about the solution */
                    let solsta = task.get_sol_sta(Soltype::ITR)?;

                    assert!(solsta == Solsta::OPTIMAL);
                    
                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITR, & mut xx[..])?;
                    
                    println!("Optimal primal solution");
                    for j in 0..numvar as usize {
                        println!("x[{}]: {:.4}",j,xx[j]);
                    }
                    Ok(())
                }))
}
source

pub fn put_var_bound_slice_const( &mut self, first_: i32, last_: i32, bkx_: i32, blx_: f64, bux_: f64 ) -> Result<(), String>

Changes the bounds for a slice of the variables.

§Arguments
  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • bkx_ New bound key for all variables in the slice.

    See Boundkey

  • blx_ New lower bound for all variables in the slice.

  • bux_ New upper bound for all variables in the slice.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putvarboundsliceconst

Examples found in repository?
examples/pinfeas.rs (line 28)
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
fn test_problem() -> Result<mosek::Task,String> {
    let mut task = mosek::Task::new().unwrap();
    task.append_vars(7)?;
    task.append_cons(7)?;
    task.put_c_list(&[0,1,2,3,4,5,6],
                    &[1.0,2.0,5.0,2.0,1.0,2.0,1.0])?;
    task.put_aij_list(&[0,0,1,1,2,2,2,3,3,4,5,5,6,6],
                      &[0,1,2,3,4,5,6,0,4,1,2,5,3,6],
                      &[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0])?;
    task.put_con_bound_slice(0, 7,
                             &[Boundkey::UP,Boundkey::UP,Boundkey::UP,Boundkey::FX,Boundkey::FX,Boundkey::FX,Boundkey::FX],
                             &[-INF, -INF, -INF, 1100.0, 200.0, 500.0, 500.0],
                             &[200.0, 1000.0, 1000.0, 1100.0, 200.0, 500.0, 500.0])?;
    task.put_var_bound_slice_const(0, 7, Boundkey::UP, 0.0, INF)?;
    Ok(task)
}
More examples
Hide additional examples
examples/solvelinear.rs (line 47)
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
fn setup(task : & mut mosek::Task,
         aval : &[f64],
         asub : &[i32],
         ptrb : &[i64],
         ptre : &[i64],
         numvar : i32) -> Result<Vec<i32>,String> {

    // mosek.stakey[] skx = new mosek.stakey [numvar];
    // mosek.stakey[] skc = new mosek.stakey [numvar];

    // for (int i = 0; i < numvar ; ++i) {
    //   skx[i] = mosek.stakey.bas;
    //   skc[i] = mosek.stakey.fix;
    // }

    task.append_vars(numvar)?;
    task.append_cons(numvar)?;

    task.put_a_col_slice(0,numvar,ptrb,ptre,asub,aval)?;

    task.put_con_bound_slice_const(0,numvar,Boundkey::FX,0.0,0.0)?;
    task.put_var_bound_slice_const(0,numvar,Boundkey::FR,-INF,INF)?;

    /* Define a basic solution by specifying
       status keys for variables & constraints. */
    task.delete_solution(Soltype::BAS)?;

    task.put_skc_slice(Soltype::BAS, 0, numvar, vec![Stakey::FIX; numvar as usize].as_slice())?;
    task.put_skx_slice(Soltype::BAS, 0, numvar, vec![Stakey::BAS; numvar as usize].as_slice())?;

    let mut basis = vec![0; numvar as usize];
    task.init_basis_solve(basis.as_mut_slice())?;
    Ok(basis)
  }
examples/portfolio_5_card.rs (line 73)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
source

pub fn put_var_name(&mut self, j_: i32, name_: &str) -> Result<(), String>

Sets the name of a variable.

§Arguments
  • j_ Index of the variable.
  • name_ The variable name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putvarname

Examples found in repository?
examples/portfolio_2_frontier.rs (line 72)
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
fn portfolio(n : i32,
             mu : &[f64],
             GT : &[f64],
             x0  : &[f64],
             alphas : &[f64],
             w : f64) -> Result<Vec<(f64,f64)>,String> {
    let k = (GT.len() / n as usize) as i32;
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(t) => t,
        None => return Err("Failed to create task".to_string()),
    };
    //task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    task.append_vars(n+1)?;
    task.append_cons(1)?;

    /* Objective */
    task.put_obj_sense(Objsense::MAXIMIZE)?;

    let x : Vec<i32> = (0i32..n).collect();
    let s = n;

    /* Total budget */
    let total_budget = w + x0.iter().sum::<f64>();

    /* Total budget constraint - set bounds l^c = u^c */
    task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
    task.put_con_name(0i32,"budget")?;
    task.put_c_slice(0,n,mu)?;

    /* x variables. */
    for (j,xj) in x.iter().enumerate() {
        /* Coefficients in the first row of A */
        task.put_aij(0, *xj, 1.0)?;
        /* No short-selling - x^l = 0, x^u = inf */
        task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
        task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
    }
    task.put_var_name(s, "s")?;
    task.put_var_bound(s, mosek::Boundkey::FR, 0.0, 0.0)?;

    // risk bound
    // (s,0.5,GT * x) in Q_r
    {
        let acci = task.get_num_acc()?;
        let afei = task.get_num_afe()?;

        task.append_afes(k as i64 + 2)?;
        let dom = task.append_r_quadratic_cone_domain(k as i64+2)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 2].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_f_entry(afei,s,1.0)?;
        task.put_afe_g(afei+1,0.5)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 2, j as i32, *v)?;
        }
    }

    let frontier : Vec<(f64,f64)> = alphas.iter().filter_map(|alpha| {
        /* Sets the objective function coefficient for s. */
        if      let Err(_) = task.put_c_j(s, - *alpha) { None }
        else if let Err(_) = task.optimize() { None }
        else if let Err(_) = task.write_data(format!("portfolio_2_frontier-{}.ptf",alpha).as_str()) { None }
        else if let Ok(solsta) = task.get_sol_sta(Soltype::ITR) {
            // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
            match solsta {
                Solsta::OPTIMAL => {
                    let mut xx = vec![0.0; n as usize+1];
                    if let Err(_) = task.get_xx(Soltype::ITR,xx.as_mut_slice()) { None }
                    else {
                        Some((*alpha,mu.iter().zip(xx.iter()).map(|(m,x)| m * x).sum::<f64>()))
                    }
                }
                _ => None
            }
        }
        else {
            None
        }
    }).collect();

    Ok(frontier)
}
More examples
Hide additional examples
examples/portfolio_5_card.rs (line 78)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
source

pub fn put_var_solution_j( &mut self, j_: i32, whichsol_: i32, sk_: i32, x_: f64, sl_: f64, su_: f64, sn_: f64 ) -> Result<(), String>

Sets the primal and dual solution information for a single variable.

§Arguments
  • j_ Index of the variable.

  • whichsol_ Selects a solution.

    See Soltype

  • sk_ Status key of the variable.

    See Stakey

  • x_ Primal solution value of the variable.

  • sl_ Solution value of the dual variable associated with the lower bound.

  • su_ Solution value of the dual variable associated with the upper bound.

  • sn_ Solution value of the dual variable associated with the conic constraint.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putvarsolutionj

source

pub fn put_var_type(&mut self, j_: i32, vartype_: i32) -> Result<(), String>

Sets the variable type of one variable.

§Arguments
  • j_ Index of the variable.

  • vartype_ The new variable type.

    See Variabletype

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putvartype

Examples found in repository?
examples/portfolio_5_card.rs (line 81)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
More examples
Hide additional examples
examples/milo1.rs (line 71)
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
fn main() -> Result<(),String> {
    let numcon : i32 = 2;
    let numvar : i32 = 2;

    let infinity = 0.0; // only for symbolic purposes, value never used

    let bkc = vec![Boundkey::UP, Boundkey::LO];
    let blc = vec![ -infinity,         -4.0 ];
    let buc = vec![ 250.0,             infinity ];

    let bkx = vec![ Boundkey::LO, Boundkey::LO  ];
    let blx = vec![ 0.0,               0.0 ];
    let bux = vec![ infinity,          infinity ];

    let c   = vec![1.0, 0.64];

    let asub = vec![0,   1,
                    0,    1];
    let aval = vec![50.0, 3.0, 31.0, -2.0];

    let ptrb : Vec<usize> = vec![ 0, 2 ];
    let ptre : Vec<usize> = vec![ 2, 4 ];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG,
            &mut |msg| print!("{}",msg),
            |task| task.with_itg_sol_callback(
                &mut |xx| { println!("Found a new solution = {:?}",xx); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                    The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                    /* Append 'numvar' variables.
                    The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    for ((((j,cj),bk),bl),bu) in (0..numvar).zip(c.iter()).zip(bkx.iter()).zip(blx.iter()).zip(bux.iter()) {
                        /* Set the linear term c_j in the objective.*/
                        task.put_c_j(j, *cj)?;
                        /* Set the bounds on variable j.
                           blx[j] <= x_j <= bux[j] */
                        task.put_var_bound(j, *bk, *bl, *bu)?;
                        /* Input column j of A */
                        task.put_a_col(j,                     /* Variable (column) index.*/
                                       &asub[ptrb[j as usize]..ptre[j as usize]],               /* Row index of non-zeros in column j.*/
                                       &aval[ptrb[j as usize]..ptre[j as usize]])?;              /* Non-zero Values of column j. */
                    }
                    // Set the bounds on constraints.
                    // for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] 
                    for (((i,bk),bl),bu) in (0..numcon).zip(bkc.iter()).zip(blc.iter()).zip(buc.iter()) {
                        task.put_con_bound(i, *bk, *bl, *bu)?;
                    }

                    /* Specify integer variables. */
                    for j in 0..numvar {
                        task.put_var_type(j, Variabletype::TYPE_INT)?;
                    }
                    /* Set max solution time */
                    task.put_dou_param(Dparam::MIO_MAX_TIME, 60.0)?;

                    /* A maximization problem */
                    task.put_obj_sense(Objsense::MAXIMIZE)?;
                    /* Solve the problem */

                    let _trm = task.optimize()?;

                    // Print a summary containing information
                    //   about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITG, xx.as_mut_slice())?;

                    /* Get status information about the solution */

                    match task.get_sol_sta(Soltype::ITG)? {
                        Solsta::INTEGER_OPTIMAL => {
                            println!("Optimal solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::PRIM_FEAS => {
                            println!("Feasible solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::UNKNOWN => {
                          match task.get_pro_sta(Soltype::ITG)? {
                              Prosta::PRIM_INFEAS_OR_UNBOUNDED => {
                                  println!("Problem status Infeasible or unbounded");
                              }
                              Prosta::PRIM_INFEAS => {
                                  println!("Problem status Infeasible.");
                              }
                              Prosta::UNKNOWN => {
                                  println!("Problem status unknown.");
                              }
                              _ => {
                                  println!("Other problem status.");
                              }
                          }
                        }
                        _ => {
                            println!("Other solution status");
                        }
                    }
                    Ok(())
                }))
}
source

pub fn put_var_type_list( &mut self, subj_: &[i32], vartype_: &[i32] ) -> Result<(), String>

Sets the variable type for one or more variables.

§Arguments
  • subj_ A list of variable indexes for which the variable type should be changed.

  • vartype_ A list of variable types.

    See Variabletype

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putvartypelist

source

pub fn put_xc(&mut self, whichsol_: i32, xc_: &mut [f64]) -> Result<(), String>

Sets the xc vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • xc_ Primal constraint solution.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putxc

source

pub fn put_xc_slice( &mut self, whichsol_: i32, first_: i32, last_: i32, xc_: &[f64] ) -> Result<(), String>

Sets a slice of the xc vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • xc_ Primal constraint solution.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putxcslice

source

pub fn put_xx(&mut self, whichsol_: i32, xx_: &[f64]) -> Result<(), String>

Sets the xx vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • xx_ Primal variable solution.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putxx

source

pub fn put_xx_slice( &mut self, whichsol_: i32, first_: i32, last_: i32, xx_: &[f64] ) -> Result<(), String>

Sets a slice of the xx vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • xx_ Primal variable solution.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putxxslice

source

pub fn put_y(&mut self, whichsol_: i32, y_: &[f64]) -> Result<(), String>

Sets the y vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • y_ Vector of dual variables corresponding to the constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.puty

source

pub fn put_y_slice( &mut self, whichsol_: i32, first_: i32, last_: i32, y_: &[f64] ) -> Result<(), String>

Sets a slice of the y vector for a solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • first_ First index in the sequence.

  • last_ Last index plus 1 in the sequence.

  • y_ Vector of dual variables corresponding to the constraints.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.putyslice

source

pub fn read_b_solution( &self, filename_: &str, compress_: i32 ) -> Result<(), String>

Read a binary dump of the task solution and information items.

§Arguments
  • filename_ A valid file name.

  • compress_ Data compression type.

    See Compresstype

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.readbsolution

source

pub fn read_data(&mut self, filename_: &str) -> Result<(), String>

Reads problem data from a file.

§Arguments
  • filename_ A valid file name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.readdataautoformat

Examples found in repository?
examples/callback.rs (line 112)
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
fn callbackmain(which : &str, data : FileOrText) -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = Task::new().unwrap();
    match data {
        FileOrText::Text(data)  => { task.read_ptf_string(data)? },
        FileOrText::File(fname) => { task.read_data(fname)? }
    }

    task.write_data("callback.ptf")?;

    match which {
        "psim"   => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::PRIMAL_SIMPLEX)?,
        "dsim"   => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::DUAL_SIMPLEX)?,
        "intpnt" => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::INTPNT)?,
        s => return Err(format!("Invalid argument '{}'",s))
    }

    /* Directs the log task stream to the 'printstr' function. */
    task.with_stream_callback(
        Streamtype::LOG,
        & mut |msg| print!("{}",msg),
        |task|
            task.with_info_callback(
                & mut callback,
                |task|
                    task.optimize()
            )
    )?;

    Result::Ok(())
}
More examples
Hide additional examples
examples/parallel.rs (line 38)
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
fn parallel(files : Vec<FileOrText>) -> Result<(),String> {
    // Create an example list of tasks to optimize
    let mut tasks : Vec<(String,Task)> = files.iter().filter_map(|fname| {
        let mut t = Task::new().unwrap();
        match fname {
            FileOrText::File(fname) => {
                if let Err(_) = t.read_data(fname.as_str()) { None }
                else {
                    t.put_int_param(mosek::Iparam::NUM_THREADS, 2).unwrap();
                    Some((fname.as_str().to_string(),t))
                }
            },
            FileOrText::Text(data) => {
                if let Err(_) = t.read_ptf_string(data.as_str()) { None }
                else {
                    t.put_int_param(mosek::Iparam::NUM_THREADS, 2).unwrap();
                    Some(("-".to_string(),t))
                }
            }
        }
    }).collect();

    let mut res = vec![0i32; tasks.len()];
    let mut trm = vec![0i32; tasks.len()];
    {
        let taskrs : Vec<& mut Task> = tasks.iter_mut().map(|(_a,b)| b).collect();

        // Size of thread pool available for all tasks
        let threadpoolsize : i32 = 6;

        // Optimize all the given tasks in parallel
        mosek::optimize_batch(false,          // No race
                              -1.0,           // No time limit
                              threadpoolsize,
                              taskrs.as_slice(),          // Array of tasks to optimize
                              trm.as_mut_slice(),
                              res.as_mut_slice())?;
    }

    for (resi,trmi,(fname,ti)) in izip!(res,trm,tasks.iter()) {
        println!("Task  {}  res {}   trm {}   obj_val  {}  time {}",
                 fname,
                 resi,
                 trmi,
                 ti.get_dou_inf(mosek::Dinfitem::INTPNT_PRIMAL_OBJ)?,
                 ti.get_dou_inf(mosek::Dinfitem::OPTIMIZER_TIME)?);
    }
    Ok(())
}
examples/opt_server_async.rs (line 44)
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
fn opt_server_async(inputfile : FileOrText, addr : String, numpolls : usize, cert : Option<String>) -> Result<(),String> {
    // Path to certificate, if any

    let token = {
        Task::new().unwrap()
            .with_stream_callback(
                Streamtype::LOG,
                &mut |msg| print!("{}",msg),
                |task| {
                    match inputfile {
                        FileOrText::File(ref filename) => task.read_data(filename.as_str()).unwrap(),
                        FileOrText::Text(ref data)     => task.read_ptf_string(data.as_str()).unwrap()
                    }
                    if let Some(ref cert) = cert {
                        task.put_str_param(Sparam::REMOTE_TLS_CERT_PATH,cert.as_str())?;
                    }
                    task.async_optimize(addr.as_str(),"")
                }).expect("Failed to submit async optimization")
    };

    println!("Task token = '{}'", token);

    println!("Setting log stream...");
    Task::new().unwrap().with_stream_callback(
        Streamtype::LOG,
        & mut |msg| print!("{}",msg),
        |task| task.with_callback(
            &mut|caller| { println!("caller = {}",caller); false },
            |task| {
                println!("Reading input file '{:?}'...",inputfile);
                match inputfile {
                    FileOrText::File(ref filename) => task.read_data(filename.as_str()).unwrap(),
                    FileOrText::Text(ref data)     => task.read_ptf_string(data.as_str()).unwrap()
                }
                if let Some(ref cert) = cert {
                    task.put_str_param(Sparam::REMOTE_TLS_CERT_PATH,cert.as_str())?;
                }

                println!("Starting polling loop...");
                for i in 0..numpolls {
                    sleep(Duration::new(1,0));

                    println!("\tpoll {}...", i);

                    let mut trm  : i32 = 0;
                    let mut resp : i32 = 0;

                    let respavailable = task.async_poll(addr.as_str(),
                                                        "",
                                                        token.as_str(),
                                                        & mut resp,
                                                        & mut trm)?;

                    if respavailable {
                        println!("solution available!");

                        task.async_get_result(addr.as_str(),
                                              "",
                                              token.as_str(),
                                              & mut resp,
                                              & mut trm)?;

                        task.solution_summary (Streamtype::LOG)?;
                        return Ok(());
                    }
                }

                println!("max num polls reached, stopping host.");
                task.async_stop (addr.as_str(), "", token.as_str())?;
                Err("Max num polls".to_string())
            }))
}
examples/concurrent1.rs (line 108)
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
fn concurrent1(data : FileOrText, timelimit : Option<String>) -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
        };

    match data {
        FileOrText::File(fname) => task.read_data(fname.as_str())?,
        FileOrText::Text(text)  => task.read_ptf_string(text.as_str())?
    }
    if let Some(timelimit) = timelimit {
        task.put_dou_param(mosek::Dparam::OPTIMIZER_MAX_TIME, timelimit.parse().unwrap())?;
    }

    let numintvar = task.get_num_int_var()?;

    let r = if numintvar == 0 {
        let optimizers = &[mosek::Optimizertype::CONIC,
                           mosek::Optimizertype::DUAL_SIMPLEX,
                           mosek::Optimizertype::PRIMAL_SIMPLEX];
        optimize_concurrent(& mut task, optimizers)
    }
    else {
        let seeds = &[ 42, 13, 71749373 ];
        optimize_concurrent_mio(& mut task, seeds)
    };


    let sense = task.get_obj_sense()?;
    // Pick the feasible result. For non-integer problems all
    // solutions should be the same if more than one is returned, but
    // for integer problems tasks may have hit the time limit and
    // returned non-optimal solutions.

    let n = r.len();

    if n == 0 {
        println!("All optimizers failed.");
    }
    else if numintvar > 0 {
        let (ii,_,tasks) = split3vec(r);

        let pobjs : Vec<(usize,f64)> =
            ii.iter().zip(tasks.iter()).enumerate()
            .filter_map(|(k,(_i,t))|
                match (*t).solution_def(Soltype::ITG) {
                    Ok(true) => match t.get_sol_sta(Soltype::ITG).unwrap() {
                        Solsta::PRIM_FEAS|Solsta::INTEGER_OPTIMAL => Some((k,t.get_primal_obj(Soltype::ITG).unwrap())),
                        _ => None
                    },
                    _ => None
                })
            .collect();

        let &(besti,bestobj) = pobjs.iter()
            .max_by(|(_,o1),(_,o2)|
                    match sense {
                        Objsense::MAXIMIZE => if o1 < o2 {Ordering::Less} else if o2 < o1 {Ordering::Greater} else {Ordering::Equal},
                        _ => if o1 > o2 {Ordering::Less} else if o2 > o1 {Ordering::Greater} else {Ordering::Equal}
                    }).unwrap();

        drop_except(tasks,besti).unwrap()
            .with_stream_callback(
                Streamtype::LOG, 
                &mut |msg| print!("{}",msg),
                |t| { 
                    t.optimizer_summary(mosek::Streamtype::LOG)?;
                    t.solution_summary(mosek::Streamtype::LOG)?;
                    Ok::<(),String>(())
                })?;

        println!("{} optimizers succeeded:",pobjs.len());
        for &(k,v) in pobjs.iter() {
            println!("Optimizer with seed #{} produced result : {:.5e}",ii[k],v);
        }

        println!("\tBest solution is #{}: {:.5e}",ii[besti],bestobj);
    }
    else {
        let (ii,_,tasks) = split3vec(r);

        let pobjs : Vec<(usize,f64)> =
            tasks.iter().enumerate()
            .filter_map(|(k,t)|
                        match t.get_sol_sta(Soltype::BAS) {
                            Ok(Solsta::PRIM_FEAS)|Ok(Solsta::OPTIMAL) => Some((k,t.get_primal_obj(Soltype::BAS).unwrap())),
                            _ => None
                        }.or_else(|| match t.get_sol_sta(Soltype::ITR) {
                            Ok(Solsta::PRIM_FEAS)|Ok(Solsta::OPTIMAL) => Some((k,t.get_primal_obj(Soltype::ITR).unwrap())),
                            _ => None
                        }))
            .collect();

        let &(besti,bestobj) = pobjs.iter()
            .max_by(|(_,o1),(_,o2)|
                    match sense {
                        Objsense::MAXIMIZE => if o1 < o2 {Ordering::Less} else if o2 < o1 {Ordering::Greater} else {Ordering::Equal},
                        _ => if o1 > o2 {Ordering::Less} else if o2 > o1 {Ordering::Greater} else {Ordering::Equal}
                    }).unwrap();

        drop_except(tasks,besti).unwrap()
            .with_stream_callback(
                Streamtype::LOG, 
                &mut|msg| print!("{}",msg),
                |t| {
                    t.optimizer_summary(mosek::Streamtype::LOG)?;
                    t.solution_summary(mosek::Streamtype::LOG)?;
                    Ok::<(),String>(())
                })?;

        println!("{} optimizers succeeded:",pobjs.len());
        for &(k,v) in pobjs.iter() {
            println!("Optimizer with seed #{} produced result : {:.5e}",ii[k],v);
        }

        println!("\tBest solution is #{}: {:.5e}",ii[besti],bestobj);
    }


    Result::Ok(())
}
source

pub fn read_data_format( &mut self, filename_: &str, format_: i32, compress_: i32 ) -> Result<(), String>

Reads problem data from a file.

§Arguments
  • filename_ A valid file name.

  • format_ File data format.

    See Dataformat

  • compress_ File compression type.

    See Compresstype

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.readdataformat

source

pub fn read_json_sol(&mut self, filename_: &str) -> Result<(), String>

Reads a solution from a JSOL file.

§Arguments
  • filename_ A valid file name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.readjsonsol

source

pub fn read_json_string(&mut self, data_: &str) -> Result<(), String>

Load task data from a string in JSON format.

§Arguments
  • data_ Problem data in text format.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.readjsonstring

source

pub fn read_lp_string(&mut self, data_: &str) -> Result<(), String>

Load task data from a string in LP format.

§Arguments
  • data_ Problem data in text format.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.readlpstring

source

pub fn read_opf_string(&mut self, data_: &str) -> Result<(), String>

Load task data from a string in OPF format.

§Arguments
  • data_ Problem data in text format.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.readopfstring

source

pub fn read_param_file(&mut self, filename_: &str) -> Result<(), String>

Reads a parameter file.

§Arguments
  • filename_ A valid file name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.readparamfile

source

pub fn read_ptf_string(&mut self, data_: &str) -> Result<(), String>

Load task data from a string in PTF format.

§Arguments
  • data_ Problem data in text format.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.readptfstring

Examples found in repository?
examples/writecallback.rs (line 29)
27
28
29
30
31
32
33
34
35
fn main() -> Result<(),String> {
    let mut task = Task::new().unwrap();
    task.read_ptf_string(DFLT_FILE).unwrap();

    task.write_data_stream(|s| if let Err(_) = stdout().write_all(s) { 0 } else { s.len() },
                           Dataformat::PTF,
                           Compresstype::NONE)?;
    Ok(())
}
More examples
Hide additional examples
examples/callback.rs (line 111)
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
fn callbackmain(which : &str, data : FileOrText) -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = Task::new().unwrap();
    match data {
        FileOrText::Text(data)  => { task.read_ptf_string(data)? },
        FileOrText::File(fname) => { task.read_data(fname)? }
    }

    task.write_data("callback.ptf")?;

    match which {
        "psim"   => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::PRIMAL_SIMPLEX)?,
        "dsim"   => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::DUAL_SIMPLEX)?,
        "intpnt" => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::INTPNT)?,
        s => return Err(format!("Invalid argument '{}'",s))
    }

    /* Directs the log task stream to the 'printstr' function. */
    task.with_stream_callback(
        Streamtype::LOG,
        & mut |msg| print!("{}",msg),
        |task|
            task.with_info_callback(
                & mut callback,
                |task|
                    task.optimize()
            )
    )?;

    Result::Ok(())
}
examples/parallel.rs (line 45)
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
fn parallel(files : Vec<FileOrText>) -> Result<(),String> {
    // Create an example list of tasks to optimize
    let mut tasks : Vec<(String,Task)> = files.iter().filter_map(|fname| {
        let mut t = Task::new().unwrap();
        match fname {
            FileOrText::File(fname) => {
                if let Err(_) = t.read_data(fname.as_str()) { None }
                else {
                    t.put_int_param(mosek::Iparam::NUM_THREADS, 2).unwrap();
                    Some((fname.as_str().to_string(),t))
                }
            },
            FileOrText::Text(data) => {
                if let Err(_) = t.read_ptf_string(data.as_str()) { None }
                else {
                    t.put_int_param(mosek::Iparam::NUM_THREADS, 2).unwrap();
                    Some(("-".to_string(),t))
                }
            }
        }
    }).collect();

    let mut res = vec![0i32; tasks.len()];
    let mut trm = vec![0i32; tasks.len()];
    {
        let taskrs : Vec<& mut Task> = tasks.iter_mut().map(|(_a,b)| b).collect();

        // Size of thread pool available for all tasks
        let threadpoolsize : i32 = 6;

        // Optimize all the given tasks in parallel
        mosek::optimize_batch(false,          // No race
                              -1.0,           // No time limit
                              threadpoolsize,
                              taskrs.as_slice(),          // Array of tasks to optimize
                              trm.as_mut_slice(),
                              res.as_mut_slice())?;
    }

    for (resi,trmi,(fname,ti)) in izip!(res,trm,tasks.iter()) {
        println!("Task  {}  res {}   trm {}   obj_val  {}  time {}",
                 fname,
                 resi,
                 trmi,
                 ti.get_dou_inf(mosek::Dinfitem::INTPNT_PRIMAL_OBJ)?,
                 ti.get_dou_inf(mosek::Dinfitem::OPTIMIZER_TIME)?);
    }
    Ok(())
}
examples/opt_server_async.rs (line 45)
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
fn opt_server_async(inputfile : FileOrText, addr : String, numpolls : usize, cert : Option<String>) -> Result<(),String> {
    // Path to certificate, if any

    let token = {
        Task::new().unwrap()
            .with_stream_callback(
                Streamtype::LOG,
                &mut |msg| print!("{}",msg),
                |task| {
                    match inputfile {
                        FileOrText::File(ref filename) => task.read_data(filename.as_str()).unwrap(),
                        FileOrText::Text(ref data)     => task.read_ptf_string(data.as_str()).unwrap()
                    }
                    if let Some(ref cert) = cert {
                        task.put_str_param(Sparam::REMOTE_TLS_CERT_PATH,cert.as_str())?;
                    }
                    task.async_optimize(addr.as_str(),"")
                }).expect("Failed to submit async optimization")
    };

    println!("Task token = '{}'", token);

    println!("Setting log stream...");
    Task::new().unwrap().with_stream_callback(
        Streamtype::LOG,
        & mut |msg| print!("{}",msg),
        |task| task.with_callback(
            &mut|caller| { println!("caller = {}",caller); false },
            |task| {
                println!("Reading input file '{:?}'...",inputfile);
                match inputfile {
                    FileOrText::File(ref filename) => task.read_data(filename.as_str()).unwrap(),
                    FileOrText::Text(ref data)     => task.read_ptf_string(data.as_str()).unwrap()
                }
                if let Some(ref cert) = cert {
                    task.put_str_param(Sparam::REMOTE_TLS_CERT_PATH,cert.as_str())?;
                }

                println!("Starting polling loop...");
                for i in 0..numpolls {
                    sleep(Duration::new(1,0));

                    println!("\tpoll {}...", i);

                    let mut trm  : i32 = 0;
                    let mut resp : i32 = 0;

                    let respavailable = task.async_poll(addr.as_str(),
                                                        "",
                                                        token.as_str(),
                                                        & mut resp,
                                                        & mut trm)?;

                    if respavailable {
                        println!("solution available!");

                        task.async_get_result(addr.as_str(),
                                              "",
                                              token.as_str(),
                                              & mut resp,
                                              & mut trm)?;

                        task.solution_summary (Streamtype::LOG)?;
                        return Ok(());
                    }
                }

                println!("max num polls reached, stopping host.");
                task.async_stop (addr.as_str(), "", token.as_str())?;
                Err("Max num polls".to_string())
            }))
}
examples/concurrent1.rs (line 109)
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
fn concurrent1(data : FileOrText, timelimit : Option<String>) -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
        };

    match data {
        FileOrText::File(fname) => task.read_data(fname.as_str())?,
        FileOrText::Text(text)  => task.read_ptf_string(text.as_str())?
    }
    if let Some(timelimit) = timelimit {
        task.put_dou_param(mosek::Dparam::OPTIMIZER_MAX_TIME, timelimit.parse().unwrap())?;
    }

    let numintvar = task.get_num_int_var()?;

    let r = if numintvar == 0 {
        let optimizers = &[mosek::Optimizertype::CONIC,
                           mosek::Optimizertype::DUAL_SIMPLEX,
                           mosek::Optimizertype::PRIMAL_SIMPLEX];
        optimize_concurrent(& mut task, optimizers)
    }
    else {
        let seeds = &[ 42, 13, 71749373 ];
        optimize_concurrent_mio(& mut task, seeds)
    };


    let sense = task.get_obj_sense()?;
    // Pick the feasible result. For non-integer problems all
    // solutions should be the same if more than one is returned, but
    // for integer problems tasks may have hit the time limit and
    // returned non-optimal solutions.

    let n = r.len();

    if n == 0 {
        println!("All optimizers failed.");
    }
    else if numintvar > 0 {
        let (ii,_,tasks) = split3vec(r);

        let pobjs : Vec<(usize,f64)> =
            ii.iter().zip(tasks.iter()).enumerate()
            .filter_map(|(k,(_i,t))|
                match (*t).solution_def(Soltype::ITG) {
                    Ok(true) => match t.get_sol_sta(Soltype::ITG).unwrap() {
                        Solsta::PRIM_FEAS|Solsta::INTEGER_OPTIMAL => Some((k,t.get_primal_obj(Soltype::ITG).unwrap())),
                        _ => None
                    },
                    _ => None
                })
            .collect();

        let &(besti,bestobj) = pobjs.iter()
            .max_by(|(_,o1),(_,o2)|
                    match sense {
                        Objsense::MAXIMIZE => if o1 < o2 {Ordering::Less} else if o2 < o1 {Ordering::Greater} else {Ordering::Equal},
                        _ => if o1 > o2 {Ordering::Less} else if o2 > o1 {Ordering::Greater} else {Ordering::Equal}
                    }).unwrap();

        drop_except(tasks,besti).unwrap()
            .with_stream_callback(
                Streamtype::LOG, 
                &mut |msg| print!("{}",msg),
                |t| { 
                    t.optimizer_summary(mosek::Streamtype::LOG)?;
                    t.solution_summary(mosek::Streamtype::LOG)?;
                    Ok::<(),String>(())
                })?;

        println!("{} optimizers succeeded:",pobjs.len());
        for &(k,v) in pobjs.iter() {
            println!("Optimizer with seed #{} produced result : {:.5e}",ii[k],v);
        }

        println!("\tBest solution is #{}: {:.5e}",ii[besti],bestobj);
    }
    else {
        let (ii,_,tasks) = split3vec(r);

        let pobjs : Vec<(usize,f64)> =
            tasks.iter().enumerate()
            .filter_map(|(k,t)|
                        match t.get_sol_sta(Soltype::BAS) {
                            Ok(Solsta::PRIM_FEAS)|Ok(Solsta::OPTIMAL) => Some((k,t.get_primal_obj(Soltype::BAS).unwrap())),
                            _ => None
                        }.or_else(|| match t.get_sol_sta(Soltype::ITR) {
                            Ok(Solsta::PRIM_FEAS)|Ok(Solsta::OPTIMAL) => Some((k,t.get_primal_obj(Soltype::ITR).unwrap())),
                            _ => None
                        }))
            .collect();

        let &(besti,bestobj) = pobjs.iter()
            .max_by(|(_,o1),(_,o2)|
                    match sense {
                        Objsense::MAXIMIZE => if o1 < o2 {Ordering::Less} else if o2 < o1 {Ordering::Greater} else {Ordering::Equal},
                        _ => if o1 > o2 {Ordering::Less} else if o2 > o1 {Ordering::Greater} else {Ordering::Equal}
                    }).unwrap();

        drop_except(tasks,besti).unwrap()
            .with_stream_callback(
                Streamtype::LOG, 
                &mut|msg| print!("{}",msg),
                |t| {
                    t.optimizer_summary(mosek::Streamtype::LOG)?;
                    t.solution_summary(mosek::Streamtype::LOG)?;
                    Ok::<(),String>(())
                })?;

        println!("{} optimizers succeeded:",pobjs.len());
        for &(k,v) in pobjs.iter() {
            println!("Optimizer with seed #{} produced result : {:.5e}",ii[k],v);
        }

        println!("\tBest solution is #{}: {:.5e}",ii[besti],bestobj);
    }


    Result::Ok(())
}
source

pub fn read_solution( &mut self, whichsol_: i32, filename_: &str ) -> Result<(), String>

Reads a solution from a file.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • filename_ A valid file name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.readsolution

source

pub fn read_solution_file(&self, filename_: &str) -> Result<(), String>

Read solution file in format determined by the filename

§Arguments
  • filename_ A valid file name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.readsolutionfile

source

pub fn read_summary(&mut self, whichstream_: i32) -> Result<(), String>

Prints information about last file read.

§Arguments
  • whichstream_ Index of the stream.

    See Streamtype

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.readsummary

source

pub fn read_task(&mut self, filename_: &str) -> Result<(), String>

Load task data from a file.

§Arguments
  • filename_ A valid file name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.readtask

source

pub fn remove_barvars(&mut self, subset_: &[i32]) -> Result<(), String>

Removes a number of symmetric matrices.

§Arguments
  • subset_ Indexes of symmetric matrices which should be removed.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.removebarvars

source

pub fn remove_cones(&mut self, subset_: &[i32]) -> Result<(), String>

Removes a number of conic constraints from the problem.

§Arguments
  • subset_ Indexes of cones which should be removed.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.removecones

source

pub fn remove_cons(&mut self, subset_: &[i32]) -> Result<(), String>

Removes a number of constraints.

§Arguments
  • subset_ Indexes of constraints which should be removed.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.removecons

source

pub fn remove_vars(&mut self, subset_: &[i32]) -> Result<(), String>

Removes a number of variables.

§Arguments
  • subset_ Indexes of variables which should be removed.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.removevars

source

pub fn resize_task( &mut self, maxnumcon_: i32, maxnumvar_: i32, maxnumcone_: i32, maxnumanz_: i64, maxnumqnz_: i64 ) -> Result<(), String>

Resizes an optimization task.

§Arguments
  • maxnumcon_ New maximum number of constraints.
  • maxnumvar_ New maximum number of variables.
  • maxnumcone_ New maximum number of cones.
  • maxnumanz_ New maximum number of linear non-zero elements.
  • maxnumqnz_ New maximum number of quadratic non-zeros elements.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.resizetask

source

pub fn sensitivity_report(&self, whichstream_: i32) -> Result<(), String>

Creates a sensitivity report.

§Arguments
  • whichstream_ Index of the stream.

    See Streamtype

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.sensitivityreport

source

pub fn set_defaults(&mut self) -> Result<(), String>

source

pub fn solution_def(&self, whichsol_: i32) -> Result<bool, String>

Checks whether a solution is defined.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

§Returns
  • isdef Is non-zero if the requested solution is defined.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.solutiondef

Examples found in repository?
examples/concurrent1.rs (line 146)
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
fn concurrent1(data : FileOrText, timelimit : Option<String>) -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
        };

    match data {
        FileOrText::File(fname) => task.read_data(fname.as_str())?,
        FileOrText::Text(text)  => task.read_ptf_string(text.as_str())?
    }
    if let Some(timelimit) = timelimit {
        task.put_dou_param(mosek::Dparam::OPTIMIZER_MAX_TIME, timelimit.parse().unwrap())?;
    }

    let numintvar = task.get_num_int_var()?;

    let r = if numintvar == 0 {
        let optimizers = &[mosek::Optimizertype::CONIC,
                           mosek::Optimizertype::DUAL_SIMPLEX,
                           mosek::Optimizertype::PRIMAL_SIMPLEX];
        optimize_concurrent(& mut task, optimizers)
    }
    else {
        let seeds = &[ 42, 13, 71749373 ];
        optimize_concurrent_mio(& mut task, seeds)
    };


    let sense = task.get_obj_sense()?;
    // Pick the feasible result. For non-integer problems all
    // solutions should be the same if more than one is returned, but
    // for integer problems tasks may have hit the time limit and
    // returned non-optimal solutions.

    let n = r.len();

    if n == 0 {
        println!("All optimizers failed.");
    }
    else if numintvar > 0 {
        let (ii,_,tasks) = split3vec(r);

        let pobjs : Vec<(usize,f64)> =
            ii.iter().zip(tasks.iter()).enumerate()
            .filter_map(|(k,(_i,t))|
                match (*t).solution_def(Soltype::ITG) {
                    Ok(true) => match t.get_sol_sta(Soltype::ITG).unwrap() {
                        Solsta::PRIM_FEAS|Solsta::INTEGER_OPTIMAL => Some((k,t.get_primal_obj(Soltype::ITG).unwrap())),
                        _ => None
                    },
                    _ => None
                })
            .collect();

        let &(besti,bestobj) = pobjs.iter()
            .max_by(|(_,o1),(_,o2)|
                    match sense {
                        Objsense::MAXIMIZE => if o1 < o2 {Ordering::Less} else if o2 < o1 {Ordering::Greater} else {Ordering::Equal},
                        _ => if o1 > o2 {Ordering::Less} else if o2 > o1 {Ordering::Greater} else {Ordering::Equal}
                    }).unwrap();

        drop_except(tasks,besti).unwrap()
            .with_stream_callback(
                Streamtype::LOG, 
                &mut |msg| print!("{}",msg),
                |t| { 
                    t.optimizer_summary(mosek::Streamtype::LOG)?;
                    t.solution_summary(mosek::Streamtype::LOG)?;
                    Ok::<(),String>(())
                })?;

        println!("{} optimizers succeeded:",pobjs.len());
        for &(k,v) in pobjs.iter() {
            println!("Optimizer with seed #{} produced result : {:.5e}",ii[k],v);
        }

        println!("\tBest solution is #{}: {:.5e}",ii[besti],bestobj);
    }
    else {
        let (ii,_,tasks) = split3vec(r);

        let pobjs : Vec<(usize,f64)> =
            tasks.iter().enumerate()
            .filter_map(|(k,t)|
                        match t.get_sol_sta(Soltype::BAS) {
                            Ok(Solsta::PRIM_FEAS)|Ok(Solsta::OPTIMAL) => Some((k,t.get_primal_obj(Soltype::BAS).unwrap())),
                            _ => None
                        }.or_else(|| match t.get_sol_sta(Soltype::ITR) {
                            Ok(Solsta::PRIM_FEAS)|Ok(Solsta::OPTIMAL) => Some((k,t.get_primal_obj(Soltype::ITR).unwrap())),
                            _ => None
                        }))
            .collect();

        let &(besti,bestobj) = pobjs.iter()
            .max_by(|(_,o1),(_,o2)|
                    match sense {
                        Objsense::MAXIMIZE => if o1 < o2 {Ordering::Less} else if o2 < o1 {Ordering::Greater} else {Ordering::Equal},
                        _ => if o1 > o2 {Ordering::Less} else if o2 > o1 {Ordering::Greater} else {Ordering::Equal}
                    }).unwrap();

        drop_except(tasks,besti).unwrap()
            .with_stream_callback(
                Streamtype::LOG, 
                &mut|msg| print!("{}",msg),
                |t| {
                    t.optimizer_summary(mosek::Streamtype::LOG)?;
                    t.solution_summary(mosek::Streamtype::LOG)?;
                    Ok::<(),String>(())
                })?;

        println!("{} optimizers succeeded:",pobjs.len());
        for &(k,v) in pobjs.iter() {
            println!("Optimizer with seed #{} produced result : {:.5e}",ii[k],v);
        }

        println!("\tBest solution is #{}: {:.5e}",ii[besti],bestobj);
    }


    Result::Ok(())
}
source

pub fn solution_summary(&self, whichstream_: i32) -> Result<(), String>

Prints a short summary of the current solutions.

§Arguments
  • whichstream_ Index of the stream.

    See Streamtype

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.solutionsummary

Examples found in repository?
examples/opt_server_async.rs (line 96)
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
fn opt_server_async(inputfile : FileOrText, addr : String, numpolls : usize, cert : Option<String>) -> Result<(),String> {
    // Path to certificate, if any

    let token = {
        Task::new().unwrap()
            .with_stream_callback(
                Streamtype::LOG,
                &mut |msg| print!("{}",msg),
                |task| {
                    match inputfile {
                        FileOrText::File(ref filename) => task.read_data(filename.as_str()).unwrap(),
                        FileOrText::Text(ref data)     => task.read_ptf_string(data.as_str()).unwrap()
                    }
                    if let Some(ref cert) = cert {
                        task.put_str_param(Sparam::REMOTE_TLS_CERT_PATH,cert.as_str())?;
                    }
                    task.async_optimize(addr.as_str(),"")
                }).expect("Failed to submit async optimization")
    };

    println!("Task token = '{}'", token);

    println!("Setting log stream...");
    Task::new().unwrap().with_stream_callback(
        Streamtype::LOG,
        & mut |msg| print!("{}",msg),
        |task| task.with_callback(
            &mut|caller| { println!("caller = {}",caller); false },
            |task| {
                println!("Reading input file '{:?}'...",inputfile);
                match inputfile {
                    FileOrText::File(ref filename) => task.read_data(filename.as_str()).unwrap(),
                    FileOrText::Text(ref data)     => task.read_ptf_string(data.as_str()).unwrap()
                }
                if let Some(ref cert) = cert {
                    task.put_str_param(Sparam::REMOTE_TLS_CERT_PATH,cert.as_str())?;
                }

                println!("Starting polling loop...");
                for i in 0..numpolls {
                    sleep(Duration::new(1,0));

                    println!("\tpoll {}...", i);

                    let mut trm  : i32 = 0;
                    let mut resp : i32 = 0;

                    let respavailable = task.async_poll(addr.as_str(),
                                                        "",
                                                        token.as_str(),
                                                        & mut resp,
                                                        & mut trm)?;

                    if respavailable {
                        println!("solution available!");

                        task.async_get_result(addr.as_str(),
                                              "",
                                              token.as_str(),
                                              & mut resp,
                                              & mut trm)?;

                        task.solution_summary (Streamtype::LOG)?;
                        return Ok(());
                    }
                }

                println!("max num polls reached, stopping host.");
                task.async_stop (addr.as_str(), "", token.as_str())?;
                Err("Max num polls".to_string())
            }))
}
More examples
Hide additional examples
examples/ceo1.rs (line 84)
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
fn main() -> Result<(),String> {
    let numcon = 1;
    let numvar = 3;

    let bkc = mosek::Boundkey::FX;
    let blc = 1.0;
    let buc = 1.0;

    let bkx = vec![ Boundkey::FR,
                    Boundkey::FR,
                    Boundkey::FR ];
    let blx = vec![ -INF, -INF, -INF ];
    let bux = vec![ INF, INF, INF ];
    let c   = vec![ 1.0, 1.0, 0.0 ];
    let a   = vec![ 1.0, 1.0, 1.0 ];
    let asub = vec![0, 1, 2];
    //let csub = new int[numvar];
    //double[] xx  = new double[numvar];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG, 
            &mut|msg| print!("{}",msg),
            |task| task.with_callback(
                &mut |caller| { println!("caller = {}",caller); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                       The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                      /* Append 'numvar' variables.
                         The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    /* Define the linear part of the problem */
                    task.put_c_slice(0, numvar, c.as_slice())?;
                    task.put_a_row(0, asub.as_slice(), a.as_slice())?;
                    task.put_con_bound(0, bkc, blc, buc)?;
                    task.put_var_bound_slice(0, numvar, bkx.as_slice(), blx.as_slice(), bux.as_slice())?;

                    /* Add a conic constraint */
                    task.append_afes(3)?;
                    let afeidxs = vec![0,  1,  2  ];
                    let b       = vec![0.0,0.0,0.0];
                    let domidx  = task.append_primal_exp_cone_domain()?;
                    task.put_afe_f_row_list(afeidxs.as_slice(),
                                            vec![1,1,1].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![0,1,2].as_slice(),
                                            vec![1.0,1.0,1.0].as_slice())?;
                    task.append_acc(domidx,afeidxs.as_slice(),b.as_slice())?;

                    task.put_obj_sense(Objsense::MINIMIZE)?;

                    println!("optimize");
                    /* Solve the problem */
                    task.optimize()?;
                    // Print a summary containing information
                    // about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    /* Get status information about the solution */
                    let solsta = task.get_sol_sta(Soltype::ITR)?;

                    assert!(solsta == Solsta::OPTIMAL);
                    
                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITR, & mut xx[..])?;
                    
                    println!("Optimal primal solution");
                    for j in 0..numvar as usize {
                        println!("x[{}]: {:.4}",j,xx[j]);
                    }
                    Ok(())
                }))
}
examples/concurrent1.rs (line 168)
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
fn concurrent1(data : FileOrText, timelimit : Option<String>) -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
        };

    match data {
        FileOrText::File(fname) => task.read_data(fname.as_str())?,
        FileOrText::Text(text)  => task.read_ptf_string(text.as_str())?
    }
    if let Some(timelimit) = timelimit {
        task.put_dou_param(mosek::Dparam::OPTIMIZER_MAX_TIME, timelimit.parse().unwrap())?;
    }

    let numintvar = task.get_num_int_var()?;

    let r = if numintvar == 0 {
        let optimizers = &[mosek::Optimizertype::CONIC,
                           mosek::Optimizertype::DUAL_SIMPLEX,
                           mosek::Optimizertype::PRIMAL_SIMPLEX];
        optimize_concurrent(& mut task, optimizers)
    }
    else {
        let seeds = &[ 42, 13, 71749373 ];
        optimize_concurrent_mio(& mut task, seeds)
    };


    let sense = task.get_obj_sense()?;
    // Pick the feasible result. For non-integer problems all
    // solutions should be the same if more than one is returned, but
    // for integer problems tasks may have hit the time limit and
    // returned non-optimal solutions.

    let n = r.len();

    if n == 0 {
        println!("All optimizers failed.");
    }
    else if numintvar > 0 {
        let (ii,_,tasks) = split3vec(r);

        let pobjs : Vec<(usize,f64)> =
            ii.iter().zip(tasks.iter()).enumerate()
            .filter_map(|(k,(_i,t))|
                match (*t).solution_def(Soltype::ITG) {
                    Ok(true) => match t.get_sol_sta(Soltype::ITG).unwrap() {
                        Solsta::PRIM_FEAS|Solsta::INTEGER_OPTIMAL => Some((k,t.get_primal_obj(Soltype::ITG).unwrap())),
                        _ => None
                    },
                    _ => None
                })
            .collect();

        let &(besti,bestobj) = pobjs.iter()
            .max_by(|(_,o1),(_,o2)|
                    match sense {
                        Objsense::MAXIMIZE => if o1 < o2 {Ordering::Less} else if o2 < o1 {Ordering::Greater} else {Ordering::Equal},
                        _ => if o1 > o2 {Ordering::Less} else if o2 > o1 {Ordering::Greater} else {Ordering::Equal}
                    }).unwrap();

        drop_except(tasks,besti).unwrap()
            .with_stream_callback(
                Streamtype::LOG, 
                &mut |msg| print!("{}",msg),
                |t| { 
                    t.optimizer_summary(mosek::Streamtype::LOG)?;
                    t.solution_summary(mosek::Streamtype::LOG)?;
                    Ok::<(),String>(())
                })?;

        println!("{} optimizers succeeded:",pobjs.len());
        for &(k,v) in pobjs.iter() {
            println!("Optimizer with seed #{} produced result : {:.5e}",ii[k],v);
        }

        println!("\tBest solution is #{}: {:.5e}",ii[besti],bestobj);
    }
    else {
        let (ii,_,tasks) = split3vec(r);

        let pobjs : Vec<(usize,f64)> =
            tasks.iter().enumerate()
            .filter_map(|(k,t)|
                        match t.get_sol_sta(Soltype::BAS) {
                            Ok(Solsta::PRIM_FEAS)|Ok(Solsta::OPTIMAL) => Some((k,t.get_primal_obj(Soltype::BAS).unwrap())),
                            _ => None
                        }.or_else(|| match t.get_sol_sta(Soltype::ITR) {
                            Ok(Solsta::PRIM_FEAS)|Ok(Solsta::OPTIMAL) => Some((k,t.get_primal_obj(Soltype::ITR).unwrap())),
                            _ => None
                        }))
            .collect();

        let &(besti,bestobj) = pobjs.iter()
            .max_by(|(_,o1),(_,o2)|
                    match sense {
                        Objsense::MAXIMIZE => if o1 < o2 {Ordering::Less} else if o2 < o1 {Ordering::Greater} else {Ordering::Equal},
                        _ => if o1 > o2 {Ordering::Less} else if o2 > o1 {Ordering::Greater} else {Ordering::Equal}
                    }).unwrap();

        drop_except(tasks,besti).unwrap()
            .with_stream_callback(
                Streamtype::LOG, 
                &mut|msg| print!("{}",msg),
                |t| {
                    t.optimizer_summary(mosek::Streamtype::LOG)?;
                    t.solution_summary(mosek::Streamtype::LOG)?;
                    Ok::<(),String>(())
                })?;

        println!("{} optimizers succeeded:",pobjs.len());
        for &(k,v) in pobjs.iter() {
            println!("Optimizer with seed #{} produced result : {:.5e}",ii[k],v);
        }

        println!("\tBest solution is #{}: {:.5e}",ii[besti],bestobj);
    }


    Result::Ok(())
}
examples/milo1.rs (line 84)
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
fn main() -> Result<(),String> {
    let numcon : i32 = 2;
    let numvar : i32 = 2;

    let infinity = 0.0; // only for symbolic purposes, value never used

    let bkc = vec![Boundkey::UP, Boundkey::LO];
    let blc = vec![ -infinity,         -4.0 ];
    let buc = vec![ 250.0,             infinity ];

    let bkx = vec![ Boundkey::LO, Boundkey::LO  ];
    let blx = vec![ 0.0,               0.0 ];
    let bux = vec![ infinity,          infinity ];

    let c   = vec![1.0, 0.64];

    let asub = vec![0,   1,
                    0,    1];
    let aval = vec![50.0, 3.0, 31.0, -2.0];

    let ptrb : Vec<usize> = vec![ 0, 2 ];
    let ptre : Vec<usize> = vec![ 2, 4 ];

    /* Create the optimization task. */
    Task::new().expect("Failed to create task")
        .with_stream_callback(
            Streamtype::LOG,
            &mut |msg| print!("{}",msg),
            |task| task.with_itg_sol_callback(
                &mut |xx| { println!("Found a new solution = {:?}",xx); false },
                |task| {
                    /* Append 'numcon' empty constraints.
                    The constraints will initially have no bounds. */
                    task.append_cons(numcon)?;

                    /* Append 'numvar' variables.
                    The variables will initially be fixed at zero (x=0). */
                    task.append_vars(numvar)?;

                    for ((((j,cj),bk),bl),bu) in (0..numvar).zip(c.iter()).zip(bkx.iter()).zip(blx.iter()).zip(bux.iter()) {
                        /* Set the linear term c_j in the objective.*/
                        task.put_c_j(j, *cj)?;
                        /* Set the bounds on variable j.
                           blx[j] <= x_j <= bux[j] */
                        task.put_var_bound(j, *bk, *bl, *bu)?;
                        /* Input column j of A */
                        task.put_a_col(j,                     /* Variable (column) index.*/
                                       &asub[ptrb[j as usize]..ptre[j as usize]],               /* Row index of non-zeros in column j.*/
                                       &aval[ptrb[j as usize]..ptre[j as usize]])?;              /* Non-zero Values of column j. */
                    }
                    // Set the bounds on constraints.
                    // for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] 
                    for (((i,bk),bl),bu) in (0..numcon).zip(bkc.iter()).zip(blc.iter()).zip(buc.iter()) {
                        task.put_con_bound(i, *bk, *bl, *bu)?;
                    }

                    /* Specify integer variables. */
                    for j in 0..numvar {
                        task.put_var_type(j, Variabletype::TYPE_INT)?;
                    }
                    /* Set max solution time */
                    task.put_dou_param(Dparam::MIO_MAX_TIME, 60.0)?;

                    /* A maximization problem */
                    task.put_obj_sense(Objsense::MAXIMIZE)?;
                    /* Solve the problem */

                    let _trm = task.optimize()?;

                    // Print a summary containing information
                    //   about the solution for debugging purposes
                    task.solution_summary(Streamtype::MSG)?;

                    let mut xx = vec![0.0; numvar as usize];
                    task.get_xx(Soltype::ITG, xx.as_mut_slice())?;

                    /* Get status information about the solution */

                    match task.get_sol_sta(Soltype::ITG)? {
                        Solsta::INTEGER_OPTIMAL => {
                            println!("Optimal solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::PRIM_FEAS => {
                            println!("Feasible solution");
                            for (j,xj) in (0..numvar).zip(xx.iter()) {
                                println!("x[{}]: {}", j,xj);
                            }
                        }
                        Solsta::UNKNOWN => {
                          match task.get_pro_sta(Soltype::ITG)? {
                              Prosta::PRIM_INFEAS_OR_UNBOUNDED => {
                                  println!("Problem status Infeasible or unbounded");
                              }
                              Prosta::PRIM_INFEAS => {
                                  println!("Problem status Infeasible.");
                              }
                              Prosta::UNKNOWN => {
                                  println!("Problem status unknown.");
                              }
                              _ => {
                                  println!("Other problem status.");
                              }
                          }
                        }
                        _ => {
                            println!("Other solution status");
                        }
                    }
                    Ok(())
                }))
}
source

pub fn solve_with_basis( &mut self, transp_: bool, numnz_: i32, sub_: &mut [i32], val_: &mut [f64] ) -> Result<i32, String>

Solve a linear equation system involving a basis matrix.

§Arguments
  • transp_ Controls which problem formulation is solved.
  • numnz_ Input (number of non-zeros in right-hand side).
  • sub_ Input (indexes of non-zeros in right-hand side) and output (indexes of non-zeros in solution vector).
  • val_ Input (right-hand side values) and output (solution vector values).
§Returns
  • numnzout Output (number of non-zeros in solution vector).

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.solvewithbasis

source

pub fn str_to_cone_type( &self, str_: &str, conetype_: &mut i32 ) -> Result<(), String>

Obtains a cone type code.

§Arguments
  • str_ String corresponding to the cone type code.

  • conetype_ The cone type corresponding to str.

    See Conetype

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.strtoconetype

source

pub fn str_to_sk(&self, str_: &str, sk_: &mut i32) -> Result<(), String>

Obtains a status key.

§Arguments
  • str_ A status key abbreviation string.

  • sk_ Status key corresponding to the string.

    See Stakey

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.strtosk

source

pub fn toconic(&mut self) -> Result<(), String>

In-place reformulation of a QCQO to a conic quadratic problem.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.toconic

Disconnects a user-defined function from a task stream.

§Arguments
  • whichstream_ Index of the stream.

    See Streamtype

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.unlinkfuncfromtaskstream

source

pub fn update_solution_info(&mut self, whichsol_: i32) -> Result<(), String>

Update the information items related to the solution.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.updatesolutioninfo

source

pub fn which_param( &self, parname_: &str, partype_: &mut i32, param_: &mut i32 ) -> Result<(), String>

Checks a parameter name.

§Arguments
  • parname_ Parameter name.

  • partype_ Parameter type.

    See Parametertype

  • param_ Which parameter.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.whichparam

source

pub fn write_b_solution( &self, filename_: &str, compress_: i32 ) -> Result<(), String>

Write a binary dump of the task solution and information items.

§Arguments
  • filename_ A valid file name.

  • compress_ Data compression type.

    See Compresstype

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.writebsolution

source

pub fn write_data(&self, filename_: &str) -> Result<(), String>

Writes problem data to a file.

§Arguments
  • filename_ A valid file name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.writedata

Examples found in repository?
examples/callback.rs (line 115)
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
fn callbackmain(which : &str, data : FileOrText) -> Result<(),String> {
    /* Create the optimization task. */
    let mut task = Task::new().unwrap();
    match data {
        FileOrText::Text(data)  => { task.read_ptf_string(data)? },
        FileOrText::File(fname) => { task.read_data(fname)? }
    }

    task.write_data("callback.ptf")?;

    match which {
        "psim"   => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::PRIMAL_SIMPLEX)?,
        "dsim"   => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::DUAL_SIMPLEX)?,
        "intpnt" => task.put_int_param(Iparam::OPTIMIZER,Optimizertype::INTPNT)?,
        s => return Err(format!("Invalid argument '{}'",s))
    }

    /* Directs the log task stream to the 'printstr' function. */
    task.with_stream_callback(
        Streamtype::LOG,
        & mut |msg| print!("{}",msg),
        |task|
            task.with_info_callback(
                & mut callback,
                |task|
                    task.optimize()
            )
    )?;

    Result::Ok(())
}
More examples
Hide additional examples
examples/portfolio_2_frontier.rs (line 101)
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
fn portfolio(n : i32,
             mu : &[f64],
             GT : &[f64],
             x0  : &[f64],
             alphas : &[f64],
             w : f64) -> Result<Vec<(f64,f64)>,String> {
    let k = (GT.len() / n as usize) as i32;
    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(t) => t,
        None => return Err("Failed to create task".to_string()),
    };
    //task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    task.append_vars(n+1)?;
    task.append_cons(1)?;

    /* Objective */
    task.put_obj_sense(Objsense::MAXIMIZE)?;

    let x : Vec<i32> = (0i32..n).collect();
    let s = n;

    /* Total budget */
    let total_budget = w + x0.iter().sum::<f64>();

    /* Total budget constraint - set bounds l^c = u^c */
    task.put_con_bound(0i32, mosek::Boundkey::FX, total_budget, total_budget)?;
    task.put_con_name(0i32,"budget")?;
    task.put_c_slice(0,n,mu)?;

    /* x variables. */
    for (j,xj) in x.iter().enumerate() {
        /* Coefficients in the first row of A */
        task.put_aij(0, *xj, 1.0)?;
        /* No short-selling - x^l = 0, x^u = inf */
        task.put_var_bound(*xj, mosek::Boundkey::LO, 0.0, 0.0)?;
        task.put_var_name(*xj, format!("x[{}]",j+1).as_str())?;
    }
    task.put_var_name(s, "s")?;
    task.put_var_bound(s, mosek::Boundkey::FR, 0.0, 0.0)?;

    // risk bound
    // (s,0.5,GT * x) in Q_r
    {
        let acci = task.get_num_acc()?;
        let afei = task.get_num_afe()?;

        task.append_afes(k as i64 + 2)?;
        let dom = task.append_r_quadratic_cone_domain(k as i64+2)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 2].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_f_entry(afei,s,1.0)?;
        task.put_afe_g(afei+1,0.5)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 2, j as i32, *v)?;
        }
    }

    let frontier : Vec<(f64,f64)> = alphas.iter().filter_map(|alpha| {
        /* Sets the objective function coefficient for s. */
        if      let Err(_) = task.put_c_j(s, - *alpha) { None }
        else if let Err(_) = task.optimize() { None }
        else if let Err(_) = task.write_data(format!("portfolio_2_frontier-{}.ptf",alpha).as_str()) { None }
        else if let Ok(solsta) = task.get_sol_sta(Soltype::ITR) {
            // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
            match solsta {
                Solsta::OPTIMAL => {
                    let mut xx = vec![0.0; n as usize+1];
                    if let Err(_) = task.get_xx(Soltype::ITR,xx.as_mut_slice()) { None }
                    else {
                        Some((*alpha,mu.iter().zip(xx.iter()).map(|(m,x)| m * x).sum::<f64>()))
                    }
                }
                _ => None
            }
        }
        else {
            None
        }
    }).collect();

    Ok(frontier)
}
examples/portfolio_5_card.rs (line 165)
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
fn portfolio(n     : i32,
             mu    : &[f64],
             GT    : &[f64],
             x0    : &[f64],
             gamma : f64,
             p     : i32,
             w     : f64) -> Result<(Vec<f64>,f64),String> {

    /* Create the optimization task. */
    let mut task = match Task::new() {
        Some(e) => e,
        None => return Err("Failed to create task".to_string()),
    };

    let k = (GT.len() / n as usize) as i32;
    // task.put_stream_callback(Streamtype::LOG, |msg| print!("{}",msg))?;

    /* Compute total wealth */
    let w0 = w + x0.iter().sum::<f64>();

    task.append_vars(3*n)?;

    let all_vars : Vec<i32> = (0..3*n).collect();
    let x = &all_vars[0..n as usize];
    let y = &all_vars[n as usize..2*n as usize];
    let z = &all_vars[2*n as usize..3*n as usize];

    task.put_var_bound_slice_const(0,n,mosek::Boundkey::LO,0.0,INF)?;
    task.put_var_bound_slice_const(n,2*n,mosek::Boundkey::RA,0.0,1.0)?;
    task.put_var_bound_slice_const(2*n,3*n, mosek::Boundkey::FR, -INF,INF)?;

    for (i,xj,yj,zj) in izip!(0..n,x,y,z) {
        task.put_var_name(*xj,format!("x[{}]",i+1).as_str())?;
        task.put_var_name(*yj,format!("y[{}]",i+1).as_str())?;
        task.put_var_name(*zj,format!("z[{}]",i+1).as_str())?;
        task.put_var_type(*yj, Variabletype::TYPE_INT)?;
    }

    // objective
    task.put_obj_sense(Objsense::MAXIMIZE)?;
    for (j,mui) in x.iter().zip(mu.iter()) {
        task.put_c_j(*j, *mui)?;
    }

    let n_ones = vec![1.0; n as usize];
    // budget constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"budget")?;
        task.put_a_row(coni,
                       x,
                       n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::FX,w0,w0)?;
    }

    // |x-x0| <= z
    {
        let coni = task.get_num_con()?;
        task.append_cons(2 * n)?;
        for i in 0..n {
            task.put_con_name(coni+i,   format!("zabs1[{}]",1 + i).as_str())?;
            task.put_con_name(coni+n+i, format!("zabs2[{}]",1 + i).as_str())?;
        }
        let ones      = vec![1.0; n as usize];
        let minusones = vec![-1.0; n as usize];
        let con_abs1 : Vec<i32> = (coni..coni+n).collect();
        let con_abs2 : Vec<i32> = (coni+n..coni+2*n).collect();
        task.put_aij_list(con_abs1.as_slice(), x, minusones.as_slice())?;
        task.put_aij_list(con_abs1.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni,coni+n, vec![Boundkey::LO; n as usize].as_slice(), x0.iter().map(|&v| -v).collect::<Vec<f64>>().as_slice(), vec![INF; n as usize].as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), x, ones.as_slice())?;
        task.put_aij_list(con_abs2.as_slice(), z, ones.as_slice())?;
        task.put_con_bound_slice(coni+n,coni+n*2, vec![Boundkey::LO; n as usize].as_slice(), x0, vec![INF; n as usize].as_slice())?;
    }

    // cardinality constraint
    {
        let coni = task.get_num_con()?;
        task.append_cons(1)?;
        task.put_con_name(coni,"cardinality")?;
        task.put_a_row(coni, y, n_ones.as_slice())?;
        task.put_con_bound(coni,mosek::Boundkey::UP,p as f64,p as f64)?;
    }

    // (gamma,G'x) in Q
    {
        let afei = task.get_num_afe()?;
        let acci = task.get_num_acc()?;

        task.append_afes(k as i64+1)?;
        let dom = task.append_quadratic_cone_domain(k as i64+1)?;
        task.append_acc_seq(dom,
                            afei,
                            vec![0.0; k as usize + 1].as_slice())?;
        task.put_acc_name(acci,"risk")?;
        task.put_afe_g(afei,gamma)?;

        for ((i,j),v) in iproduct!(0..n,0..n).zip(GT).filter(|(_,v)| **v != 0.0) {
            task.put_afe_f_entry(afei + i as i64 + 1, j as i32, *v)?;
        }
    }

    // Switch
    {
        let coni = task.get_num_con()?;
        task.append_cons(n)?;
        for i in 0..n {
            task.put_con_name(coni + i, format!("switch[{}]",i+1).as_str())?;
        }

        let conlist : Vec<i32> = (coni..coni+n).collect();
        task.put_aij_list(conlist.as_slice(), z, vec![1.0; n as usize].as_slice())?;
        task.put_aij_list(conlist.as_slice(), y, vec![-w0; n as usize].as_slice())?;

        task.put_con_bound_slice_const(coni,coni+n, Boundkey::UP, 0.0,0.0)?;
    }

    let _ = task.optimize()?;
    task.write_data(format!("portfolio_5_card-{}.ptf",p).as_str())?;

    // Check if the integer solution is an optimal point
    if task.get_sol_sta(Soltype::ITG)? != Solsta::INTEGER_OPTIMAL {
        // See https://docs.mosek.com/latest/rustapi/accessing-solution.html about handling solution statuses.
        eprintln!("Solution not optimal!");
        std::process::exit(1);
    }

    let mut xx = vec![0.0;n as usize];
    task.get_xx_slice(Soltype::ITG, 0,n,xx.as_mut_slice())?;
    Ok((xx[0..n as usize].to_vec(),task.get_primal_obj(Soltype::ITG)?))
}
source

pub fn write_json_sol(&self, filename_: &str) -> Result<(), String>

Writes a solution to a JSON file.

§Arguments
  • filename_ A valid file name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.writejsonsol

source

pub fn write_param_file(&self, filename_: &str) -> Result<(), String>

Writes all the parameters to a parameter file.

§Arguments
  • filename_ A valid file name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.writeparamfile

source

pub fn write_solution( &self, whichsol_: i32, filename_: &str ) -> Result<(), String>

Write a solution to a file.

§Arguments
  • whichsol_ Selects a solution.

    See Soltype

  • filename_ A valid file name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.writesolution

source

pub fn write_solution_file(&self, filename_: &str) -> Result<(), String>

Write solution file in format determined by the filename

§Arguments
  • filename_ A valid file name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.writesolutionfile

source

pub fn write_stat(&mut self, filename_: &str) -> Result<(), String>

Appends a record to the statistics file.

§Arguments
  • filename_ A valid file name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.writestat

source

pub fn write_task(&self, filename_: &str) -> Result<(), String>

Write a complete binary dump of the task data.

§Arguments
  • filename_ A valid file name.

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.writetask

source

pub fn write_task_solver_result_file( &self, filename_: &str, compress_: i32 ) -> Result<(), String>

Internal

§Arguments
  • filename_ A valid file name.

  • compress_ Data compression type.

    See Compresstype

Full documentation: https://docs.mosek.com/latest/capi/alphabetic-functionalities.html#mosek.env.writetasksolverresult_file

Trait Implementations§

source§

impl Drop for Task

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl Send for Task

Auto Trait Implementations§

§

impl RefUnwindSafe for Task

§

impl !Sync for Task

§

impl Unpin for Task

§

impl UnwindSafe for Task

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.