ipopt 0.2.0

Rust language bindings for the Ipopt non-linear constrained optimization library.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
//   Copyright 2018 Egor Larionov
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

#![warn(missing_docs)]

/*!
 * # Ipopt-rs
 *
 * This crate provides a safe Rust interface to the [Ipopt](https://projects.coin-or.org/Ipopt)
 * non-linear optimization library. From the Ipopt webpage:
 *
 * > Ipopt (**I**nterior **P**oint **OPT**imizer, pronounced eye-pea-Opt) is a software package
 * > for large-scale nonlinear optimization. It is designed to find (local) solutions of
 * > mathematical optimization problems of the from
 * >
 * >```verbatim
 * >    min     f(x)
 * >    x in R^n
 * >
 * >    s.t.       g_L <= g(x) <= g_U
 * >               x_L <=  x   <= x_U
 * >```
 * >
 * > where `f(x): R^n --> R` is the objective function, and `g(x): R^n --> R^m` are the
 * > constraint functions. The vectors `g_L` and `g_U` denote the lower and upper bounds
 * > on the constraints, and the vectors `x_L` and `x_U` are the bounds on the variables
 * > `x`. The functions `f(x)` and `g(x)` can be nonlinear and nonconvex, but should be
 * > twice continuously differentiable. Note that equality constraints can be
 * > formulated in the above formulation by setting the corresponding components of
 * > `g_L` and `g_U` to the same value.
 *
 * This crate somewhat simplifies the C-interface exposed by Ipopt. Notably it handles the
 * boilerplate code required to solve simple unconstrained problems.
 *
 * # Examples
 *
 * Solve a simple unconstrained problem using L-BFGS: minimize `(x - 1)^2 + (y -1)^2`
 *
 *
 * ```
 * extern crate ipopt;
 * #[macro_use] extern crate approx; // for floating point equality tests
 *
 * use ipopt::*;
 *
 * struct NLP {
 * }
 *
 * impl BasicProblem for NLP {
 *     // There are two independent variables: x and y.
 *     fn num_variables(&self) -> usize {
 *         2
 *     }    
 *     // The variables are unbounded. Any lower bound lower than -10^9 and upper bound higher
 *     // than 10^9 is treated effectively as infinity. These absolute infinity limits can be
 *     // changed via the `nlp_lower_bound_inf` and `nlp_upper_bound_inf` Ipopt options.
 *     fn bounds(&self, x_l: &mut [Number], x_u: &mut [Number]) -> bool {
 *         x_l.swap_with_slice(vec![-1e20; 2].as_mut_slice());
 *         x_u.swap_with_slice(vec![1e20; 2].as_mut_slice());
 *         true
 *     }
 *
 *     // Set the initial conditions for the solver.
 *     fn initial_point(&self) -> Vec<Number> {
 *         vec![0.0, 0.0]
 *     }
 *
 *     // The objective to be minimized.
 *     fn objective(&self, x: &[Number], obj: &mut Number) -> bool {
 *         *obj = (x[0] - 1.0)*(x[0] - 1.0) + (x[1] - 1.0)*(x[1] - 1.0);
 *         true
 *     }
 *
 *     // Objective gradient is used to find a new search direction to find the critical point.
 *     fn objective_grad(&self, x: &[Number], grad_f: &mut [Number]) -> bool {
 *         grad_f[0] = 2.0*(x[0] - 1.0);
 *         grad_f[1] = 2.0*(x[1] - 1.0);
 *         true
 *     }
 * }
 *
 * fn main() {
 *     let nlp = NLP { };
 *     let mut ipopt = Ipopt::new_unconstrained(nlp).unwrap();
 *
 *     // Set Ipopt specific options here a list of all options is available at
 *     // https://www.coin-or.org/Ipopt/documentation/node40.html
 *     ipopt.set_option("tol", 1e-9); // set error tolerance
 *     ipopt.set_option("print_level", 5); // set the print level (5 is the default)
 *
 *     let solve_result = ipopt.solve();
 *
 *     assert_eq!(solve_result.status, SolveStatus::SolveSucceeded);
 *     assert_relative_eq!(solve_result.solver_data.primal_variables[0], 1.0, epsilon = 1e-10);
 *     assert_relative_eq!(solve_result.solver_data.primal_variables[1], 1.0, epsilon = 1e-10);
 *     assert_relative_eq!(solve_result.objective_value, 0.0, epsilon = 1e-10);
 * }
 * ```
 *
 * See the tests for more examples including constrained optimization.
 *
 */

extern crate ipopt_sys as ffi;

use crate::ffi::{Bool, Int};
use std::ffi::CString;
use std::slice;

/// Uniform floating point number type.
pub type Number = f64; // Same as ffi::Number
/// Index type used to access internal buffers.
pub type Index = i32; // Same as ffi::Index

/// The non-linear problem to be solved by Ipopt. This trait specifies all the
/// information needed to construct the unconstrained optimization problem (although the
/// variables are allowed to be bounded).
/// In the callbacks within, `x` is the independent variable and must be the same size
/// as returned by `num_variables`.
/// Each of the callbacks required during interior point iterations are allowed to fail.
/// In case of failure to produce values, simply return `false` where applicable.
/// This feature could be used to tell Ipopt to try smaller perturbations for `x` for
/// instance.
pub trait BasicProblem {
    /// Specify the indexing style used for arrays in this problem.
    /// (Default is zero-based)
    fn indexing_style(&self) -> IndexingStyle {
        IndexingStyle::CStyle
    }
    /// Total number of variables of the non-linear problem.
    fn num_variables(&self) -> usize;

    /// Specify lower and upper variable bounds given by `x_l` and `x_u` respectively.
    /// Both slices will have the same size as what `num_variables` returns.
    fn bounds(&self, x_l: &mut [Number], x_u: &mut [Number]) -> bool;

    /// Construct the initial guess for Ipopt to start with.
    /// The returned `Vec` must have the same size as `num_variables`.
    fn initial_point(&self) -> Vec<Number>;

    /// Objective function. This is the function being minimized.
    /// This function is internally called by Ipopt callback `eval_f`.
    fn objective(&self, x: &[Number], obj: &mut Number) -> bool;
    /// Gradient of the objective function.
    /// This function is internally called by Ipopt callback `eval_grad_f`.
    fn objective_grad(&self, x: &[Number], grad_f: &mut [Number]) -> bool;
}

/// An extension to the `BasicProblem` trait that enables full Newton iterations in
/// Ipopt. If this trait is NOT implemented by your problem, Ipopt will be set to perform
/// [Quasi-Newton Approximation](https://www.coin-or.org/Ipopt/documentation/node31.html)
/// for second derivatives.
/// This interface asks for the Hessian matrix in sparse triplet form.
pub trait NewtonProblem: BasicProblem {
    /// Number of non-zeros in the Hessian matrix. This includes the constraint hessian
    /// if one is provided.
    fn num_hessian_non_zeros(&self) -> usize;
    /// Hessian indices. These are the row and column indices of the non-zeros
    /// in the sparse representation of the matrix.
    /// This is a symmetric matrix, fill the lower left triangular half only.
    /// If your problem is constrained (i.e. you are ultimately implementing
    /// `ConstrainedProblem`), ensure that you provide coordinates for non-zeros of the
    /// constraint hessian as well.
    /// This function is internally called by Ipopt callback `eval_h`.
    fn hessian_indices(&self, rows: &mut [Index], cols: &mut [Index]) -> bool;
    /// Objective Hessian values. Each value must correspond to the `row` and `column` as
    /// specified in `hessian_indices`.
    /// This function is internally called by Ipopt callback `eval_h` and each value is
    /// premultiplied by `Ipopt`'s `obj_factor` as necessary.
    fn hessian_values(&self, x: &[Number], vals: &mut [Number]) -> bool;
}

/// Extends the `BasicProblem` trait to enable equality and inequality constraints.
/// Equality constraints are enforce by setting the lower and upper bounds for the
/// constraint to the same value.
/// This type of problem is the target use case for Ipopt.
/// NOTE: Although its possible to run Quasi-Newton iterations on a constrained problem,
/// it doesn't perform well in general, which is the reason why you must also provide the
/// Hessian callbacks.  However, you may still enable L-BFGS explicitly by setting the
/// "hessian_approximation" Ipopt option to "limited-memory", in which case you should
/// simply return `false` in `hessian_indices` and `hessian_values`.
pub trait ConstrainedProblem: BasicProblem {
    /// Number of equality and inequality constraints.
    fn num_constraints(&self) -> usize;
    /// Number of non-zeros in the constraint Jacobian.
    fn num_constraint_jac_non_zeros(&self) -> usize;
    /// Constraint function. This gives the value of each constraint.
    /// The output slice `g` is guaranteed to be the same size as `num_constraints`.
    /// This function is internally called by Ipopt callback `eval_g`.
    fn constraint(&self, x: &[Number], g: &mut [Number]) -> bool;
    /// Specify lower and upper bounds, `g_l` and `g_u` respectively, on the constraint function.
    /// Both slices will have the same size as what `num_constraints` returns.
    fn constraint_bounds(&self, g_l: &mut [Number], g_u: &mut [Number]) -> bool;
    /// Constraint Jacobian indices. These are the row and column indices of the
    /// non-zeros in the sparse representation of the matrix.
    /// This function is internally called by Ipopt callback `eval_jac_g`.
    fn constraint_jac_indices(&self, rows: &mut [Index], cols: &mut [Index]) -> bool;
    /// Constraint Jacobian values. Each value must correspond to the `row` and
    /// `column` as specified in `constraint_jac_indices`.
    /// This function is internally called by Ipopt callback `eval_jac_g`.
    fn constraint_jac_values(&self, x: &[Number], vals: &mut [Number]) -> bool;
    /// Number of non-zeros in the Hessian matrix. This includes the constraint hessian.
    fn num_hessian_non_zeros(&self) -> usize;
    /// Hessian indices. These are the row and column indices of the non-zeros
    /// in the sparse representation of the matrix.
    /// This should be a symmetric matrix, fill the lower left triangular half only.
    /// Ensure that you provide coordinates for non-zeros of the
    /// objective and constraint hessians.
    /// This function is internally called by Ipopt callback `eval_h`.
    fn hessian_indices(&self, rows: &mut [Index], cols: &mut [Index]) -> bool;
    /// Hessian values. Each value must correspond to the `row` and `column` as
    /// specified in `hessian_indices`.
    /// Write the objective hessian values multiplied by `obj_factor` and constraint
    /// hessian values multipled by the corresponding values in `lambda` (the Lagrange
    /// multiplier).
    /// This function is internally called by Ipopt callback `eval_h`.
    fn hessian_values(
        &self,
        x: &[Number],
        obj_factor: Number,
        lambda: &[Number],
        vals: &mut [Number],
    ) -> bool;
}

/// Type of option you can specify to Ipopt.
/// This is used internally for conversion.
pub enum IpoptOption<'a> {
    /// Numeric option.
    Num(f64),
    /// String option.
    Str(&'a str),
    /// Integer option.
    Int(i32),
}

/// Convert a floating point value to an `IpoptOption`.
impl<'a> From<f64> for IpoptOption<'a> {
    fn from(opt: f64) -> Self {
        IpoptOption::Num(opt)
    }
}

/// Convert a string to an `IpoptOption`.
impl<'a> From<&'a str> for IpoptOption<'a> {
    fn from(opt: &'a str) -> Self {
        IpoptOption::Str(opt)
    }
}

/// Convert an integer value to an `IpoptOption`.
impl<'a> From<i32> for IpoptOption<'a> {
    fn from(opt: i32) -> Self {
        IpoptOption::Int(opt)
    }
}

/// An interface to mutably access internal solver data including the input problem
/// which Ipopt owns.
#[derive(Debug, PartialEq)]
pub struct SolverDataMut<'a, P: 'a> {
    /// A mutable reference to the original input problem.
    pub problem: &'a mut P,
    /// This is the solution after the solve.
    pub primal_variables: &'a mut [Number],
    /// Lower bound multipliers.
    pub lower_bound_multipliers: &'a mut [Number],
    /// Upper bound multipliers.
    pub upper_bound_multipliers: &'a mut [Number],
    /// Constraint multipliers, which are available only from contrained problems.
    pub constraint_multipliers: &'a mut [Number],
}

/// An interface to access internal solver data including the input problem immutably.
#[derive(Clone, Debug, PartialEq)]
pub struct SolverData<'a, P: 'a> {
    /// A mutable reference to the original input problem.
    pub problem: &'a P,
    /// This is the solution after the solve.
    pub primal_variables: &'a [Number],
    /// Lower bound multipliers.
    pub lower_bound_multipliers: &'a [Number],
    /// Upper bound multipliers.
    pub upper_bound_multipliers: &'a [Number],
    /// Constraint multipliers, which are available only from contrained problems.
    pub constraint_multipliers: &'a [Number],
}

/// Enum that indicates in which mode the algorithm is at some point in time.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum AlgorithmMode {
    /// Ipopt is in regular mode.
    Regular,
    /// Ipopt is in restoration phase. See Ipopt documentation for details.
    RestorationPhase,
}

/// Pieces of solver data available from Ipopt after each iteration inside the intermediate
/// callback.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct IntermediateCallbackData {
    /// Algorithm mode indicates which mode the algorithm is currently in.
    pub alg_mod: AlgorithmMode,
    /// The current iteration count. This includes regular iterations and iterations during the
    /// restoration phase.
    pub iter_count: Index,
    /// The unscaled objective value at the current point. During the restoration phase, this value
    /// remains the unscaled objective value for the original problem.
    pub obj_value: Number,
    /// The unscaled constraint violation at the current point. This quantity is the infinity-norm
    /// (max) of the (unscaled) constraints. During the restoration phase, this value remains
    /// the constraint violation of the original problem at the current point. The option
    /// inf_pr_output can be used to switch to the printing of a different quantity.
    pub inf_pr: Number,
    /// The scaled dual infeasibility at the current point. This quantity measure the infinity-norm
    /// (max) of the internal dual infeasibility, Eq. (4a) in the [implementation
    /// paper](https://www.coin-or.org/Ipopt/documentation/node64.html#WaecBieg06:mp),
    /// including inequality constraints reformulated using slack variables and problem scaling.
    /// During the restoration phase, this is the value of the dual infeasibility for the
    /// restoration phase problem.
    pub inf_du: Number,
    /// The value of the barrier parameter $ \mu$.
    pub mu: Number,
    /// The infinity norm (max) of the primal step (for the original variables $ x$ and the
    /// internal slack variables $ s$). During the restoration phase, this value includes the
    /// values of additional variables, $ p$ and $ n$ (see Eq. (30) in [the implementation
    /// paper](https://www.coin-or.org/Ipopt/documentation/node64.html#WaecBieg06:mp))
    pub d_norm: Number,
    /// The value of the regularization term for the Hessian of the Lagrangian in
    /// the augmented system ($ \delta_w$ in Eq. (26) and Section 3.1 in [the implementation
    /// paper](https://www.coin-or.org/Ipopt/documentation/node64.html#WaecBieg06:mp)). A zero
    /// value indicates that no regularization was done.
    pub regularization_size: Number,
    /// The stepsize for the dual variables ( $ \alpha^z_k$ in Eq. (14c) in [the implementation
    /// paper](https://www.coin-or.org/Ipopt/documentation/node64.html#WaecBieg06:mp)).
    pub alpha_du: Number,
    /// The stepsize for the primal variables ($ \alpha_k$ in Eq. (14a) in [the implementation
    /// paper](https://www.coin-or.org/Ipopt/documentation/node64.html#WaecBieg06:mp)).
    pub alpha_pr: Number,
    /// The number of backtracking line search steps (does not include second-order correction steps).
    pub ls_trials: Index,
}

/// A data structure to store data returned by the solver.
#[derive(Debug, PartialEq)]
pub struct SolveResult<'a, P: 'a> {
    /// Data available from the solver, that can be updated by the user.
    pub solver_data: SolverDataMut<'a, P>,
    /// These are the values of each constraint at the end of the time step.
    pub constraint_values: &'a [Number],
    /// Objective value.
    pub objective_value: Number,
    /// Solve status. This enum reports the status of the last solve.
    pub status: SolveStatus,
}

/// Type defining the callback function for giving intermediate execution control to
/// the user. If set, it is called once per iteration, providing the user with some
/// information on the state of the optimization. This can be used to print some user-
/// defined output. It also gives the user a way to terminate the optimization
/// prematurely. If this method returns false, Ipopt will terminate the optimization.
pub type IntermediateCallback<P> = fn(&mut P, IntermediateCallbackData) -> bool;

/// Ipopt non-linear optimization problem solver. This structure is used to store data
/// needed to solve these problems using first and second order methods.
pub struct Ipopt<P: BasicProblem> {
    /// Internal (opaque) Ipopt problem representation.
    nlp_internal: ffi::IpoptProblem,
    /// User specified interface defining the problem to be solved.
    nlp_interface: P,
    /// Intermediate callback.
    intermediate_callback: Option<IntermediateCallback<P>>,
    /// Number of primal variables.
    num_primal_variables: usize,
    /// Number of dual variables.
    num_dual_variables: usize,
}

/// Implement debug for Ipopt.
impl<P: BasicProblem + std::fmt::Debug> std::fmt::Debug for Ipopt<P> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f,
               "Ipopt {{ nlp_internal: {:?}, nlp_interface: {:?}, intermediate_callback: {:?}, num_primal_variables: {:?}, num_dual_variables: {:?} }}",
               self.nlp_internal,
               self.nlp_interface,
               if self.intermediate_callback.is_some() { "Some" } else { "None" },
               self.num_primal_variables,
               self.num_dual_variables)
    }
}

/// The only non-`Send` type in `Ipopt` is `nlp_internal`, which is a mutable raw pointer to an
/// underlying C struct. It is safe to implement `Send` for `Ipopt` here because it cannot be
/// copied or cloned.
unsafe impl<P: BasicProblem> Send for Ipopt<P> {}

impl<P: BasicProblem> Ipopt<P> {
    /// Create a new unconstrained non-linear problem.
    pub fn new_unconstrained(nlp: P) -> Result<Self, CreateError> {
        let num_vars = nlp.num_variables();

        let x = nlp.initial_point();

        // Validate all inputs before attempting to use the unsafe wrapper.
        if num_vars < 1 {
            return Err(CreateError::NoOptimizationVariablesSpecified);
        }
        if x.len() != num_vars {
            return Err(CreateError::InvalidInitialPoint);
        }

        let mut mult_x_l = Vec::with_capacity(num_vars);
        mult_x_l.resize(num_vars, 0.0);
        let mut mult_x_u = Vec::with_capacity(num_vars);
        mult_x_u.resize(num_vars, 0.0);

        let mut nlp_internal: ffi::IpoptProblem = ::std::ptr::null_mut();

        let create_error = CreateProblemStatus::new(unsafe {
            ffi::CreateIpoptProblem(
                &mut nlp_internal as *mut ffi::IpoptProblem,
                num_vars as Index,
                x.as_ptr(),
                mult_x_l.as_ptr(),
                mult_x_u.as_ptr(),
                0, // no constraints
                ::std::ptr::null(),
                0, // no non-zeros in constraint Jacobian
                0, // no hessian
                nlp.indexing_style() as Index,
                Some(Self::variable_only_bounds),
                Some(Self::eval_f),
                Some(Self::eval_g_none),
                Some(Self::eval_grad_f),
                Some(Self::eval_jac_g_none),
                Some(Self::eval_h_none),
            )
        });

        if CreateProblemStatus::Success != create_error {
            return Err(create_error.into());
        }

        assert!(Self::set_ipopt_option(
            nlp_internal,
            "hessian_approximation",
            "limited-memory"
        ));
        Ok(Ipopt {
            nlp_internal,
            nlp_interface: nlp,
            intermediate_callback: None,
            num_primal_variables: num_vars,
            num_dual_variables: 0,
        })
    }

    /// Helper static function that can be used in the constructor.
    fn set_ipopt_option<'a, O>(nlp: ffi::IpoptProblem, name: &str, option: O) -> bool
    where
        O: Into<IpoptOption<'a>>,
    {
        (unsafe {
            // Convert the input name string to a `char *` C type
            let name_cstr = CString::new(name).unwrap();
            let name_cstr = (&name_cstr).as_ptr() as *mut i8; // this is `char *`
                                                              // Match option to one of the three types of options Ipopt can receive.
            match option.into() {
                IpoptOption::Num(opt) => ffi::AddIpoptNumOption(nlp, name_cstr, opt as Number),
                IpoptOption::Str(opt) => {
                    // Convert option string to `char *`
                    let opt_cstr = CString::new(opt).unwrap();
                    let opt_cstr = (&opt_cstr).as_ptr() as *mut i8;
                    ffi::AddIpoptStrOption(nlp, name_cstr, opt_cstr)
                }
                IpoptOption::Int(opt) => ffi::AddIpoptIntOption(nlp, name_cstr, opt as Int),
            }
        } != 0) // converts Ipopt Bool to Rust bool
    }

    /// Set an Ipopt option.
    pub fn set_option<'a, O>(&mut self, name: &str, option: O) -> Option<&mut Self>
    where
        O: Into<IpoptOption<'a>>,
    {
        let success = Self::set_ipopt_option(self.nlp_internal, name, option);
        if success {
            Some(self)
        } else {
            None
        }
    }

    /// Set intermediate callback.
    pub fn set_intermediate_callback(&mut self, mb_cb: Option<IntermediateCallback<P>>)
    where
        P: BasicProblem,
    {
        self.intermediate_callback = mb_cb;

        unsafe {
            if mb_cb.is_some() {
                ffi::SetIntermediateCallback(self.nlp_internal, Some(Self::intermediate_cb));
            } else {
                ffi::SetIntermediateCallback(self.nlp_internal, None);
            }
        }
    }

    /// Solve non-linear problem.
    /// Return the solve status and the final value of the objective function.
    pub fn solve(&mut self) -> SolveResult<P> {
        let res = {
            let udata_ptr = self as *mut Ipopt<P>;
            unsafe { ffi::IpoptSolve(self.nlp_internal, udata_ptr as ffi::UserDataPtr) }
        };

        let Ipopt {
            nlp_interface: ref mut problem,
            num_primal_variables,
            num_dual_variables,
            ..
        } = *self;

        SolveResult {
            solver_data: SolverDataMut {
                problem,
                primal_variables: unsafe {
                    slice::from_raw_parts_mut(res.data.x, num_primal_variables)
                },
                lower_bound_multipliers: unsafe {
                    slice::from_raw_parts_mut(res.data.mult_x_L, num_primal_variables)
                },
                upper_bound_multipliers: unsafe {
                    slice::from_raw_parts_mut(res.data.mult_x_U, num_primal_variables)
                },
                constraint_multipliers: unsafe {
                    slice::from_raw_parts_mut(res.data.mult_g, num_dual_variables)
                },
            },
            constraint_values: unsafe { slice::from_raw_parts(res.g, num_dual_variables) },
            objective_value: res.obj_val,
            status: SolveStatus::new(res.status),
        }
    }

    /// Get data for inspection and updating from the internal solver. This is useful for updating
    /// initial guesses between solves for instance.
    #[allow(non_snake_case)]
    pub fn solver_data_mut(&mut self) -> SolverDataMut<P> {
        let Ipopt {
            nlp_interface: ref mut problem,
            nlp_internal,
            num_primal_variables,
            num_dual_variables,
            ..
        } = *self;

        let ffi::SolverData {
            x,
            mult_g,
            mult_x_L,
            mult_x_U,
        } = unsafe { ffi::GetSolverData(nlp_internal) };

        SolverDataMut {
            problem,
            primal_variables: unsafe { slice::from_raw_parts_mut(x, num_primal_variables) },
            lower_bound_multipliers: unsafe {
                slice::from_raw_parts_mut(mult_x_L, num_primal_variables)
            },
            upper_bound_multipliers: unsafe {
                slice::from_raw_parts_mut(mult_x_U, num_primal_variables)
            },
            constraint_multipliers: unsafe {
                slice::from_raw_parts_mut(mult_g, num_dual_variables)
            },
        }
    }

    /// Get data for inspection from the internal solver.
    #[allow(non_snake_case)]
    pub fn solver_data(&self) -> SolverData<P> {
        let Ipopt {
            nlp_interface: ref problem,
            nlp_internal,
            num_primal_variables,
            num_dual_variables,
            ..
        } = *self;

        let ffi::SolverData {
            x,
            mult_g,
            mult_x_L,
            mult_x_U,
        } = unsafe { ffi::GetSolverData(nlp_internal) };

        SolverData {
            problem,
            primal_variables: unsafe { slice::from_raw_parts(x, num_primal_variables) },
            lower_bound_multipliers: unsafe {
                slice::from_raw_parts(mult_x_L, num_primal_variables)
            },
            upper_bound_multipliers: unsafe {
                slice::from_raw_parts(mult_x_U, num_primal_variables)
            },
            constraint_multipliers: unsafe { slice::from_raw_parts(mult_g, num_dual_variables) },
        }
    }

    /**
     * Ipopt C API
     */

    /// Specify lower and upper bounds for variables. No constraints on basic problems.
    unsafe extern "C" fn variable_only_bounds(
        n: Index,
        x_l: *mut Number,
        x_u: *mut Number,
        m: Index,
        _g_l: *mut Number,
        _g_u: *mut Number,
        user_data: ffi::UserDataPtr,
    ) -> Bool {
        assert_eq!(m, 0);
        let nlp = &mut (*(user_data as *mut Ipopt<P>)).nlp_interface;
        nlp.bounds(
            slice::from_raw_parts_mut(x_l, n as usize),
            slice::from_raw_parts_mut(x_u, n as usize),
        ) as Bool
    }

    /// Evaluate the objective function.
    unsafe extern "C" fn eval_f(
        n: Index,
        x: *mut Number,
        _new_x: Bool,
        obj_value: *mut Number,
        user_data: ffi::UserDataPtr,
    ) -> Bool {
        let nlp = &mut (*(user_data as *mut Ipopt<P>)).nlp_interface;
        nlp.objective(slice::from_raw_parts(x, n as usize), &mut *obj_value) as Bool
    }

    /// Evaluate the objective gradient.
    unsafe extern "C" fn eval_grad_f(
        n: Index,
        x: *mut Number,
        _new_x: Bool,
        grad_f: *mut Number,
        user_data: ffi::UserDataPtr,
    ) -> Bool {
        let nlp = &mut (*(user_data as *mut Ipopt<P>)).nlp_interface;
        nlp.objective_grad(
            slice::from_raw_parts(x, n as usize),
            slice::from_raw_parts_mut(grad_f, n as usize),
        ) as Bool
    }

    /// Placeholder constraint function with no constraints.
    unsafe extern "C" fn eval_g_none(
        _n: Index,
        _x: *mut Number,
        _new_x: Bool,
        _m: Index,
        _g: *mut Number,
        _user_data: ffi::UserDataPtr,
    ) -> Bool {
        true as Bool
    }

    /// Placeholder constraint derivative function with no constraints.
    unsafe extern "C" fn eval_jac_g_none(
        _n: Index,
        _x: *mut Number,
        _new_x: Bool,
        _m: Index,
        _nele_jac: Index,
        _irow: *mut Index,
        _jcol: *mut Index,
        _values: *mut Number,
        _user_data: ffi::UserDataPtr,
    ) -> Bool {
        true as Bool
    }

    /// Placeholder hessian evaluation function.
    unsafe extern "C" fn eval_h_none(
        _n: Index,
        _x: *mut Number,
        _new_x: Bool,
        _obj_factor: Number,
        _m: Index,
        _lambda: *mut Number,
        _new_lambda: Bool,
        _nele_hess: Index,
        _irow: *mut Index,
        _jcol: *mut Index,
        _values: *mut Number,
        _user_data: ffi::UserDataPtr,
    ) -> Bool {
        // From "Quasi-Newton Approximation of Second-Derivatives" in Ipopt docs:
        //  "If you are using the C or Fortran interface, you still need to implement [eval_h],
        //  but [it] should return false or IERR=1, respectively, and don't need to do
        //  anything else."
        false as Bool
    }

    /// Intermediate callback.
    unsafe extern "C" fn intermediate_cb(
        alg_mod: Index,
        iter_count: Index,
        obj_value: Number,
        inf_pr: Number,
        inf_du: Number,
        mu: Number,
        d_norm: Number,
        regularization_size: Number,
        alpha_du: Number,
        alpha_pr: Number,
        ls_trials: Index,
        user_data: ffi::UserDataPtr,
    ) -> Bool {
        let ip = &mut (*(user_data as *mut Ipopt<P>));
        if let Some(callback) = ip.intermediate_callback {
            (callback)(
                &mut ip.nlp_interface,
                IntermediateCallbackData {
                    alg_mod: match alg_mod {
                        0 => AlgorithmMode::Regular,
                        _ => AlgorithmMode::RestorationPhase,
                    },
                    iter_count,
                    obj_value,
                    inf_pr,
                    inf_du,
                    mu,
                    d_norm,
                    regularization_size,
                    alpha_du,
                    alpha_pr,
                    ls_trials,
                },
            ) as Bool
        } else {
            true as Bool
        }
    }
}

impl<P: NewtonProblem> Ipopt<P> {
    /// Create a new newton problem.
    pub fn new_newton(nlp: P) -> Result<Self, CreateError> {
        let num_vars = nlp.num_variables();

        let x = nlp.initial_point();

        // Validate all inputs before attempting to use the unsafe wrapper.
        if num_vars < 1 {
            return Err(CreateError::NoOptimizationVariablesSpecified);
        }
        if x.len() != num_vars {
            return Err(CreateError::InvalidInitialPoint);
        }

        let mut mult_x_l = Vec::with_capacity(num_vars);
        mult_x_l.resize(num_vars, 0.0);
        let mut mult_x_u = Vec::with_capacity(num_vars);
        mult_x_u.resize(num_vars, 0.0);

        let mut nlp_internal: ffi::IpoptProblem = ::std::ptr::null_mut();

        let create_error = CreateProblemStatus::new(unsafe {
            ffi::CreateIpoptProblem(
                &mut nlp_internal as *mut ffi::IpoptProblem,
                num_vars as Index,
                x.as_ptr(),
                mult_x_l.as_ptr(),
                mult_x_u.as_ptr(),
                0, // no constraints
                ::std::ptr::null(),
                0, // no non-zeros in constraint Jacobian
                nlp.num_hessian_non_zeros() as Index,
                nlp.indexing_style() as Index,
                Some(Self::variable_only_bounds),
                Some(Self::eval_f),
                Some(Self::eval_g_none),
                Some(Self::eval_grad_f),
                Some(Self::eval_jac_g_none),
                Some(Self::eval_h),
            )
        });

        if create_error != CreateProblemStatus::Success {
            return Err(create_error.into());
        }

        Ok(Ipopt {
            nlp_internal,
            nlp_interface: nlp,
            intermediate_callback: None,
            num_primal_variables: num_vars,
            num_dual_variables: 0,
        })
    }

    /**
     * Ipopt C API
     */

    /// Evaluate the hessian matrix.
    unsafe extern "C" fn eval_h(
        n: Index,
        x: *mut Number,
        _new_x: Bool,
        obj_factor: Number,
        _m: Index,
        _lambda: *mut Number,
        _new_lambda: Bool,
        nele_hess: Index,
        irow: *mut Index,
        jcol: *mut Index,
        values: *mut Number,
        user_data: ffi::UserDataPtr,
    ) -> Bool {
        let nlp = &mut (*(user_data as *mut Ipopt<P>)).nlp_interface;
        if values.is_null() {
            /* return the structure. */
            nlp.hessian_indices(
                slice::from_raw_parts_mut(irow, nele_hess as usize),
                slice::from_raw_parts_mut(jcol, nele_hess as usize),
            ) as Bool
        } else {
            /* return the values. */
            let result = nlp.hessian_values(
                slice::from_raw_parts(x, n as usize),
                slice::from_raw_parts_mut(values, nele_hess as usize),
            ) as Bool;
            // This problem has no constraints so we can multiply each entry by the
            // objective factor.
            let start_idx = nlp.indexing_style() as isize;
            for i in start_idx..nele_hess as isize {
                *values.offset(i) *= obj_factor;
            }
            result
        }
    }
}

impl<P: ConstrainedProblem> Ipopt<P> {
    /// Create a new constrained non-linear problem.
    pub fn new(nlp: P) -> Result<Self, CreateError> {
        let num_constraints = nlp.num_constraints();
        let num_vars = nlp.num_variables();
        let num_hess_nnz = nlp.num_hessian_non_zeros();
        let num_constraint_jac_nnz = nlp.num_constraint_jac_non_zeros();

        let x = nlp.initial_point();

        // Validate all inputs before attempting to use the unsafe wrapper.
        if num_vars < 1 {
            return Err(CreateError::NoOptimizationVariablesSpecified);
        }
        if x.len() != num_vars {
            return Err(CreateError::InvalidInitialPoint);
        }
        if (num_constraints > 0 && num_constraint_jac_nnz == 0)
            || (num_constraints == 0 && num_constraint_jac_nnz > 0)
        {
            return Err(CreateError::InvalidConstraintJacobian);
        }

        let mut mult_g = Vec::with_capacity(num_constraints);
        mult_g.resize(num_constraints, 0.0);
        let mut mult_x_l = Vec::with_capacity(num_vars);
        mult_x_l.resize(num_vars, 0.0);
        let mut mult_x_u = Vec::with_capacity(num_vars);
        mult_x_u.resize(num_vars, 0.0);

        let mut nlp_internal: ffi::IpoptProblem = ::std::ptr::null_mut();

        let create_error = CreateProblemStatus::new(unsafe {
            ffi::CreateIpoptProblem(
                &mut nlp_internal as *mut ffi::IpoptProblem,
                num_vars as Index,
                x.as_ptr(),
                mult_x_l.as_ptr(),
                mult_x_u.as_ptr(),
                num_constraints as Index,
                mult_g.as_ptr(),
                num_constraint_jac_nnz as Index,
                num_hess_nnz as Index,
                nlp.indexing_style() as Index,
                Some(Self::bounds),
                Some(Self::eval_f),
                Some(Self::eval_g),
                Some(Self::eval_grad_f),
                Some(Self::eval_jac_g),
                Some(Self::eval_full_h),
            )
        });

        if create_error != CreateProblemStatus::Success {
            return Err(create_error.into());
        }

        Ok(Ipopt {
            nlp_internal,
            nlp_interface: nlp,
            intermediate_callback: None,
            num_primal_variables: num_vars,
            num_dual_variables: num_constraints,
        })
    }

    /**
     * Ipopt C API
     */

    /// Specify lower and upper bounds for variables and the constraint function.
    unsafe extern "C" fn bounds(
        n: Index,
        x_l: *mut Number,
        x_u: *mut Number,
        m: Index,
        g_l: *mut Number,
        g_u: *mut Number,
        user_data: ffi::UserDataPtr,
    ) -> Bool {
        let nlp = &mut (*(user_data as *mut Ipopt<P>)).nlp_interface;
        (nlp.bounds(
            slice::from_raw_parts_mut(x_l, n as usize),
            slice::from_raw_parts_mut(x_u, n as usize),
        ) && nlp.constraint_bounds(
            slice::from_raw_parts_mut(g_l, m as usize),
            slice::from_raw_parts_mut(g_u, m as usize),
        )) as Bool
    }

    /// Evaluate the constraint function.
    unsafe extern "C" fn eval_g(
        n: Index,
        x: *mut Number,
        _new_x: Bool,
        m: Index,
        g: *mut Number,
        user_data: ffi::UserDataPtr,
    ) -> Bool {
        let nlp = &mut (*(user_data as *mut Ipopt<P>)).nlp_interface;
        nlp.constraint(
            slice::from_raw_parts(x, n as usize),
            slice::from_raw_parts_mut(g, m as usize),
        ) as Bool
    }

    /// Evaluate the constraint Jacobian.
    unsafe extern "C" fn eval_jac_g(
        n: Index,
        x: *mut Number,
        _new_x: Bool,
        _m: Index,
        nele_jac: Index,
        irow: *mut Index,
        jcol: *mut Index,
        values: *mut Number,
        user_data: ffi::UserDataPtr,
    ) -> Bool {
        let nlp = &mut (*(user_data as *mut Ipopt<P>)).nlp_interface;
        if values.is_null() {
            /* return the structure of the Jacobian */
            nlp.constraint_jac_indices(
                slice::from_raw_parts_mut(irow, nele_jac as usize),
                slice::from_raw_parts_mut(jcol, nele_jac as usize),
            ) as Bool
        } else {
            /* return the values of the Jacobian of the constraints */
            nlp.constraint_jac_values(
                slice::from_raw_parts(x, n as usize),
                slice::from_raw_parts_mut(values, nele_jac as usize),
            ) as Bool
        }
    }

    /// Evaluate the hessian matrix. Compared to `eval_h` from `NewtonProblem`,
    /// this version includes the constraint hessian.
    unsafe extern "C" fn eval_full_h(
        n: Index,
        x: *mut Number,
        _new_x: Bool,
        obj_factor: Number,
        m: Index,
        lambda: *mut Number,
        _new_lambda: Bool,
        nele_hess: Index,
        irow: *mut Index,
        jcol: *mut Index,
        values: *mut Number,
        user_data: ffi::UserDataPtr,
    ) -> Bool {
        let nlp = &mut (*(user_data as *mut Ipopt<P>)).nlp_interface;
        if values.is_null() {
            /* return the structure. */
            nlp.hessian_indices(
                slice::from_raw_parts_mut(irow, nele_hess as usize),
                slice::from_raw_parts_mut(jcol, nele_hess as usize),
            ) as Bool
        } else {
            /* return the values. */
            nlp.hessian_values(
                slice::from_raw_parts(x, n as usize),
                obj_factor,
                slice::from_raw_parts(lambda, m as usize),
                slice::from_raw_parts_mut(values, nele_hess as usize),
            ) as Bool
        }
    }
}

/// Free the memory allocated on the C side.
impl<P: BasicProblem> Drop for Ipopt<P> {
    fn drop(&mut self) {
        unsafe {
            ffi::FreeIpoptProblem(self.nlp_internal);
        }
    }
}

/// Zero-based indexing (C Style) or one-based indexing (Fortran style).
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum IndexingStyle {
    /// C-style array indexing starting from 0.
    CStyle = 0,
    /// Fortran-style array indexing starting from 1.
    FortranStyle = 1,
}

/// Program return status.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum SolveStatus {
    /// Console Message: `EXIT: Optimal Solution Found.`
    ///
    /// This message indicates that IPOPT found a (locally) optimal point within the desired tolerances.
    SolveSucceeded,
    /// Console Message: `EXIT: Solved To Acceptable Level.`
    ///
    /// This indicates that the algorithm did not converge to the "desired" tolerances, but that
    /// it was able to obtain a point satisfying the "acceptable" tolerance level as specified by
    /// the [`acceptable_*`
    /// ](https://www.coin-or.org/Ipopt/documentation/node42.html#opt:acceptable_tol) options. This
    /// may happen if the desired tolerances are too small for the current problem.
    SolvedToAcceptableLevel,
    /// Console Message: `EXIT: Feasible point for square problem found.`
    ///
    /// This message is printed if the problem is "square" (i.e., it has as many equality
    /// constraints as free variables) and IPOPT found a feasible point.
    FeasiblePointFound,
    /// Console Message: `EXIT: Converged to a point of local infeasibility. Problem may be
    /// infeasible.`
    ///
    /// The restoration phase converged to a point that is a minimizer for the constraint violation
    /// (in the l1-norm), but is not feasible for the original problem. This indicates that
    /// the problem may be infeasible (or at least that the algorithm is stuck at a locally
    /// infeasible point). The returned point (the minimizer of the constraint violation) might
    /// help you to find which constraint is causing the problem. If you believe that the NLP is
    /// feasible, it might help to start the optimization from a different point.
    InfeasibleProblemDetected,
    /// Console Message: `EXIT: Search Direction is becoming Too Small.`
    ///
    /// This indicates that IPOPT is calculating very small step sizes and is making very little
    /// progress. This could happen if the problem has been solved to the best numerical accuracy
    /// possible given the current scaling.
    SearchDirectionBecomesTooSmall,
    /// Console Message: `EXIT: Iterates diverging; problem might be unbounded.`
    ///
    /// This message is printed if the max-norm of the iterates becomes larger than the value of
    /// the option [`diverging_iterates_tol`
    /// ](https://www.coin-or.org/Ipopt/documentation/node42.html#opt:diverging_iterates_tol).
    /// This can happen if the problem is unbounded below and the iterates are diverging.
    DivergingIterates,
    /// Console Message: `EXIT: Stopping optimization at current point as requested by user.`
    ///
    /// This message is printed if the user call-back method intermediate_callback returned false
    /// (see Section [3.3.4](https://www.coin-or.org/Ipopt/documentation/node23.html#sec:add_meth)).
    UserRequestedStop,
    /// Console Message: `EXIT: Maximum Number of Iterations Exceeded.`
    ///
    /// This indicates that IPOPT has exceeded the maximum number of iterations as specified by the
    /// option [`max_iter`](https://www.coin-or.org/Ipopt/documentation/node42.html#opt:max_iter).
    MaximumIterationsExceeded,
    /// Console Message: `EXIT: Maximum CPU time exceeded.`
    ///
    /// This indicates that IPOPT has exceeded the maximum number of CPU seconds as specified by
    /// the option
    /// [`max_cpu_time`](https://www.coin-or.org/Ipopt/documentation/node42.html#opt:max_cpu_time).
    MaximumCpuTimeExceeded,
    /// Console Message: `EXIT: Restoration Failed!`
    ///
    /// This indicates that the restoration phase failed to find a feasible point that was
    /// acceptable to the filter line search for the original problem. This could happen if the
    /// problem is highly degenerate, does not satisfy the constraint qualification, or if your NLP
    /// code provides incorrect derivative information.
    RestorationFailed,
    /// Console Output: `EXIT: Error in step computation (regularization becomes too large?)!`
    ///
    /// This messages is printed if IPOPT is unable to compute a search direction, despite several
    /// attempts to modify the iteration matrix. Usually, the value of the regularization parameter
    /// then becomes too large. One situation where this can happen is when values in the Hessian
    /// are invalid (NaN or Inf). You can check whether this is true by using the
    /// [`check_derivatives_for_naninf`
    /// ](https://www.coin-or.org/Ipopt/documentation/node44.html#opt:check_derivatives_for_naninf)
    /// option.
    ErrorInStepComputation,
    /// Console Message: (details about the particular error will be output to the console)
    ///
    /// This indicates that there was some problem specifying the options. See the specific message
    /// for details.
    InvalidOption,
    /// Console Message: `EXIT: Problem has too few degrees of freedom.`
    ///
    /// This indicates that your problem, as specified, has too few degrees of freedom. This can
    /// happen if you have too many equality constraints, or if you fix too many variables (IPOPT
    /// removes fixed variables by default, see also the [`fixed_variable_treatment`
    /// ](https://www.coin-or.org/Ipopt/documentation/node44.html#opt:fixed_variable_treatment)
    /// option).
    NotEnoughDegreesOfFreedom,
    /// Console Message: (no console message, this is a return code for the C and Fortran
    /// interfaces only.)
    ///
    /// This indicates that there was an exception of some sort when building the IpoptProblem
    /// structure in the C or Fortran interface. Likely there is an error in your model or the main
    /// routine.
    InvalidProblemDefinition,
    /// An invalid number like `NaN` was detected.
    InvalidNumberDetected,
    /// Console Message: (details about the particular error will be output to the console)
    ///
    /// This indicates that IPOPT has thrown an exception that does not have an internal return
    /// code. See the specific message for details.
    UnrecoverableException,
    /// Console Message: `Unknown Exception caught in Ipopt`
    ///
    /// An unknown exception was caught in IPOPT. This exception could have originated from your
    /// model or any linked in third party code.
    NonIpoptExceptionThrown,
    /// Console Message: `EXIT: Not enough memory.`
    ///
    /// An error occurred while trying to allocate memory. The problem may be too large for your
    /// current memory and swap configuration.
    InsufficientMemory,
    /// Console: `EXIT: INTERNAL ERROR: Unknown SolverReturn value - Notify IPOPT Authors.`
    ///
    /// An unknown internal error has occurred. Please notify the authors of IPOPT via the mailing
    /// list.
    InternalError,
    /// Unclassified error.
    UnknownError,
}

#[allow(non_snake_case)]
impl SolveStatus {
    fn new(status: ffi::ApplicationReturnStatus) -> Self {
        use crate::SolveStatus as RS;
        match status {
            ffi::ApplicationReturnStatus_Solve_Succeeded => RS::SolveSucceeded,
            ffi::ApplicationReturnStatus_Solved_To_Acceptable_Level => RS::SolvedToAcceptableLevel,
            ffi::ApplicationReturnStatus_Infeasible_Problem_Detected => {
                RS::InfeasibleProblemDetected
            }
            ffi::ApplicationReturnStatus_Search_Direction_Becomes_Too_Small => {
                RS::SearchDirectionBecomesTooSmall
            }
            ffi::ApplicationReturnStatus_Diverging_Iterates => RS::DivergingIterates,
            ffi::ApplicationReturnStatus_User_Requested_Stop => RS::UserRequestedStop,
            ffi::ApplicationReturnStatus_Feasible_Point_Found => RS::FeasiblePointFound,
            ffi::ApplicationReturnStatus_Maximum_Iterations_Exceeded => {
                RS::MaximumIterationsExceeded
            }
            ffi::ApplicationReturnStatus_Restoration_Failed => RS::RestorationFailed,
            ffi::ApplicationReturnStatus_Error_In_Step_Computation => RS::ErrorInStepComputation,
            ffi::ApplicationReturnStatus_Maximum_CpuTime_Exceeded => RS::MaximumCpuTimeExceeded,
            ffi::ApplicationReturnStatus_Not_Enough_Degrees_Of_Freedom => {
                RS::NotEnoughDegreesOfFreedom
            }
            ffi::ApplicationReturnStatus_Invalid_Problem_Definition => RS::InvalidProblemDefinition,
            ffi::ApplicationReturnStatus_Invalid_Option => RS::InvalidOption,
            ffi::ApplicationReturnStatus_Invalid_Number_Detected => RS::InvalidNumberDetected,
            ffi::ApplicationReturnStatus_Unrecoverable_Exception => RS::UnrecoverableException,
            ffi::ApplicationReturnStatus_NonIpopt_Exception_Thrown => RS::NonIpoptExceptionThrown,
            ffi::ApplicationReturnStatus_Insufficient_Memory => RS::InsufficientMemory,
            ffi::ApplicationReturnStatus_Internal_Error => RS::InternalError,
            _ => RS::UnknownError,
        }
    }
}

/// Problem create error type. This type is higher level than `CreateProblemStatus` and it captures
/// inconsistencies with the input before even calling `CreateIpoptProblem` internally adding
/// safety to this wrapper.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum CreateError {
    /// No optimization variables were provided.
    NoOptimizationVariablesSpecified,
    /// Initial guess size doesn't match number of variables specified.
    InvalidInitialPoint,
    /// The number of Jacobian elements is non-zero, yet no constraints were provided or
    /// the number of constraints is non-zero, yet no Jacobian elements were provided.
    InvalidConstraintJacobian,
    /// Unexpected error occureed: None of the above. This is likely an internal bug.
    Unknown,
}

impl From<CreateProblemStatus> for CreateError {
    fn from(s: CreateProblemStatus) -> CreateError {
        match s {
            CreateProblemStatus::MissingInitialGuess => CreateError::InvalidInitialPoint,
            CreateProblemStatus::TooFewOptimizationVariables => {
                CreateError::NoOptimizationVariablesSpecified
            }
            CreateProblemStatus::HaveJacobianElementsButNoConstraints => {
                CreateError::InvalidConstraintJacobian
            }
            CreateProblemStatus::HaveConstraintsButNoJacobianElements => {
                CreateError::InvalidConstraintJacobian
            }
            _ => CreateError::Unknown,
        }
    }
}

/// Internal program create return status.
#[derive(Copy, Clone, Debug, PartialEq)]
enum CreateProblemStatus {
    /// Program creation was successful. This variant should never be returned, instead a
    /// successfully built instance is returned in a `Result` struct.
    Success,
    /// The initial variable vector is missing.
    MissingInitialGuess,
    /// No optimization variables were provided.
    TooFewOptimizationVariables,
    /// Number of constraints is a negative value.
    ConstraintSizeIsNegative,
    /// Number of Jacobian elements is non-zero, yet no constraints were provided.
    HaveJacobianElementsButNoConstraints,
    /// Number of constraints is non-zero, yet no Jacobian elements were provided.
    HaveConstraintsButNoJacobianElements,
    /// Number of hessian elements given is negative.
    InvalidNumHessianElements,
    /// Missing callback for evaluating variable and constraint bounds.
    MissingBounds,
    /// Missing callback for evaluating the objective: `eval_f`.
    MissingEvalF,
    /// Missing callback for evaluating the gradient of the objective: `eval_grad_f`.
    MissingEvalGradF,
    /// Number of constraints is non-zero, yet callback for evaluating the constraint function
    /// `eval_g` or its Jacobian `eval_jac_g` is missing.
    HaveConstraintsButNoEvalGOrEvalJacG,
    /// Unexpected error occureed: None of the above. This is likely an internal bug.
    UnknownError,
}

#[allow(non_snake_case)]
impl CreateProblemStatus {
    fn new(status: ffi::CreateProblemStatus) -> Self {
        use crate::CreateProblemStatus as RS;
        match status {
            ffi::CreateProblemStatus_Success => RS::Success,
            ffi::CreateProblemStatus_MissingInitialGuess => RS::MissingInitialGuess,
            ffi::CreateProblemStatus_TooFewOptimizationVariables => RS::TooFewOptimizationVariables,
            ffi::CreateProblemStatus_ConstraintSizeIsNegative => RS::ConstraintSizeIsNegative,
            ffi::CreateProblemStatus_HaveJacobianElementsButNoConstraints => {
                RS::HaveJacobianElementsButNoConstraints
            }
            ffi::CreateProblemStatus_HaveConstraintsButNoJacobianElements => {
                RS::HaveConstraintsButNoJacobianElements
            }
            ffi::CreateProblemStatus_InvalidNumHessianElements => RS::InvalidNumHessianElements,
            ffi::CreateProblemStatus_MissingBounds => RS::MissingBounds,
            ffi::CreateProblemStatus_MissingEvalF => RS::MissingEvalF,
            ffi::CreateProblemStatus_MissingEvalGradF => RS::MissingEvalGradF,
            ffi::CreateProblemStatus_HaveConstraintsButNoEvalGOrEvalJacG => {
                RS::HaveConstraintsButNoEvalGOrEvalJacG
            }
            _ => RS::UnknownError,
        }
    }
}

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

    #[derive(Clone, Debug)]
    struct NlpUnconstrained {
        num_vars: usize,
        init_point: Vec<Number>,
        lower: Vec<Number>,
        upper: Vec<Number>,
    }

    impl BasicProblem for NlpUnconstrained {
        fn num_variables(&self) -> usize {
            self.num_vars
        }
        fn bounds(&self, x_l: &mut [Number], x_u: &mut [Number]) -> bool {
            x_l.copy_from_slice(&self.lower);
            x_u.copy_from_slice(&self.upper);
            true
        }
        fn initial_point(&self) -> Vec<Number> {
            self.init_point.clone()
        }
        fn objective(&self, _: &[Number], _: &mut Number) -> bool {
            true
        }
        fn objective_grad(&self, _: &[Number], _: &mut [Number]) -> bool {
            true
        }
    }

    /// Test validation of new unconstrained ipopt problems.
    #[test]
    fn invalid_construction_unconstrained_test() {
        // Initialize a valid nlp.
        let nlp = NlpUnconstrained {
            num_vars: 2,
            init_point: vec![0.0, 0.0],
            lower: vec![-1e20; 2],
            upper: vec![1e20; 2],
        };

        assert!(Ipopt::new_unconstrained(nlp.clone()).is_ok());

        // Invalid initial point
        let nlp1 = NlpUnconstrained {
            init_point: vec![0.0],
            ..nlp.clone()
        };
        assert_eq!(
            Ipopt::new_unconstrained(nlp1).unwrap_err(),
            CreateError::InvalidInitialPoint
        );

        // Invalid number of variables
        let nlp4 = NlpUnconstrained {
            num_vars: 0,
            ..nlp.clone()
        };
        assert_eq!(
            Ipopt::new_unconstrained(nlp4).unwrap_err(),
            CreateError::NoOptimizationVariablesSpecified
        );
    }

    #[derive(Debug, Clone)]
    struct NlpConstrained {
        num_vars: usize,
        num_constraints: usize,
        num_constraint_jac_nnz: usize,
        num_hess_nnz: usize,
        constraint_lower: Vec<Number>,
        constraint_upper: Vec<Number>,
        init_point: Vec<Number>,
        lower: Vec<Number>,
        upper: Vec<Number>,
    }

    impl BasicProblem for NlpConstrained {
        fn num_variables(&self) -> usize {
            self.num_vars
        }
        fn bounds(&self, x_l: &mut [Number], x_u: &mut [Number]) -> bool {
            x_l.copy_from_slice(&self.lower);
            x_u.copy_from_slice(&self.upper);
            true
        }
        fn initial_point(&self) -> Vec<Number> {
            self.init_point.clone()
        }
        fn objective(&self, _: &[Number], _: &mut Number) -> bool {
            true
        }
        fn objective_grad(&self, _: &[Number], _: &mut [Number]) -> bool {
            true
        }
    }

    impl ConstrainedProblem for NlpConstrained {
        fn num_constraints(&self) -> usize {
            self.num_constraints
        }
        fn num_constraint_jac_non_zeros(&self) -> usize {
            self.num_constraint_jac_nnz
        }

        fn constraint_bounds(&self, g_l: &mut [Number], g_u: &mut [Number]) -> bool {
            g_l.copy_from_slice(&self.constraint_lower);
            g_u.copy_from_slice(&self.constraint_upper);
            true
        }
        fn constraint(&self, _: &[Number], _: &mut [Number]) -> bool {
            true
        }
        fn constraint_jac_indices(&self, _: &mut [Index], _: &mut [Index]) -> bool {
            true
        }
        fn constraint_jac_values(&self, _: &[Number], _: &mut [Number]) -> bool {
            true
        }

        // Hessian Implementation
        fn num_hessian_non_zeros(&self) -> usize {
            self.num_hess_nnz
        }
        fn hessian_indices(&self, _: &mut [Index], _: &mut [Index]) -> bool {
            true
        }
        fn hessian_values(&self, _: &[Number], _: Number, _: &[Number], _: &mut [Number]) -> bool {
            true
        }
    }

    /// Test validation of new constrained ipopt problems.
    #[test]
    fn invalid_construction_constrained_test() {
        // Initialize a valid nlp.
        let nlp = NlpConstrained {
            num_vars: 4,
            num_constraints: 2,
            num_constraint_jac_nnz: 8,
            num_hess_nnz: 10,
            constraint_lower: vec![25.0, 40.0],
            constraint_upper: vec![2.0e19, 40.0],
            init_point: vec![1.0, 5.0, 5.0, 1.0],
            lower: vec![1.0; 4],
            upper: vec![5.0; 4],
        };

        assert!(Ipopt::new(nlp.clone()).is_ok());

        // Invalid initial point
        let nlp1 = NlpConstrained {
            init_point: vec![0.0],
            ..nlp.clone()
        };
        assert_eq!(
            Ipopt::new(nlp1).unwrap_err(),
            CreateError::InvalidInitialPoint
        );

        // Invalid number of variables
        let nlp2 = NlpConstrained {
            num_vars: 0,
            ..nlp.clone()
        };
        assert_eq!(
            Ipopt::new(nlp2).unwrap_err(),
            CreateError::NoOptimizationVariablesSpecified
        );

        // Invalid constraint jacobian
        let nlp3 = NlpConstrained {
            num_constraint_jac_nnz: 0,
            ..nlp.clone()
        };
        assert_eq!(
            Ipopt::new(nlp3).unwrap_err(),
            CreateError::InvalidConstraintJacobian
        );

        let nlp4 = NlpConstrained {
            num_constraints: 0,
            constraint_lower: vec![],
            constraint_upper: vec![],
            ..nlp.clone()
        };
        assert_eq!(
            Ipopt::new(nlp4).unwrap_err(),
            CreateError::InvalidConstraintJacobian
        );
    }
}