ipopt-src 0.2.3+3.14.16

Redistribution of Coin-OR Ipopt as a crate
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
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
// Copyright (C) 2004, 2010 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// Authors:  Carl Laird, Andreas Waechter     IBM    2004-08-13

#include "IpoptConfig.h"
#include "IpTNLPAdapter.hpp"
#include "IpBlas.hpp"
#include "IpIpoptData.hpp"
#include "IpIpoptCalculatedQuantities.hpp"
#include "IpDenseVector.hpp"
#include "IpExpansionMatrix.hpp"
#include "IpGenTMatrix.hpp"
#include "IpSymTMatrix.hpp"
#include "IpTDependencyDetector.hpp"
#include "IpTSymDependencyDetector.hpp"
#include "IpTripletToCSRConverter.hpp"

#ifdef IPOPT_HAS_HSL
#include "CoinHslConfig.h"
#include "IpMa28TDependencyDetector.hpp"
#endif

#ifdef IPOPT_HAS_MUMPS
# include "IpMumpsSolverInterface.hpp"
#endif
#ifdef IPOPT_HAS_WSMP
# include "IpWsmpSolverInterface.hpp"
#endif

#include <cmath>
#include <cstdio>
#include <cstring>

namespace Ipopt
{
#if IPOPT_VERBOSITY > 0
static const Index dbg_verbosity = 0;
#endif

TNLPAdapter::TNLPAdapter(
   const SmartPtr<TNLP>             tnlp,
   const SmartPtr<const Journalist> jnlst /* = NULL */
)
   : tnlp_(tnlp),
     jnlst_(jnlst),
     full_x_(NULL),
     full_lambda_(NULL),
     full_g_(NULL),
     jac_g_(NULL),
     c_rhs_(NULL),
     x_tag_for_iterates_(0),
     y_c_tag_for_iterates_(0),
     y_d_tag_for_iterates_(0),
     x_tag_for_g_(0),
     x_tag_for_jac_g_(0),
     jac_idx_map_(NULL),
     h_idx_map_(NULL),
     x_fixed_map_(NULL),
     findiff_jac_ia_(NULL),
     findiff_jac_ja_(NULL),
     findiff_jac_postriplet_(NULL),
     findiff_x_l_(NULL),
     findiff_x_u_(NULL)
{
   ASSERT_EXCEPTION(IsValid(tnlp_), INVALID_TNLP, "The TNLP passed to TNLPAdapter is NULL. This MUST be a valid TNLP!");
}

TNLPAdapter::~TNLPAdapter()
{
   delete[] full_x_;
   delete[] full_lambda_;
   delete[] full_g_;
   delete[] jac_g_;
   delete[] c_rhs_;
   delete[] jac_idx_map_;
   delete[] h_idx_map_;
   delete[] x_fixed_map_;
   delete[] findiff_jac_ia_;
   delete[] findiff_jac_ja_;
   delete[] findiff_jac_postriplet_;
   delete[] findiff_x_l_;
   delete[] findiff_x_u_;
}

void TNLPAdapter::RegisterOptions(
   SmartPtr<RegisteredOptions> roptions
)
{
   roptions->SetRegisteringCategory("NLP");
   roptions->AddNumberOption(
      "nlp_lower_bound_inf",
      "any bound less or equal this value will be considered -inf (i.e. not lower bounded).",
      -1e19);
   roptions->AddNumberOption(
      "nlp_upper_bound_inf",
      "any bound greater or this value will be considered +inf (i.e. not upper bounded).",
      1e19);
   roptions->AddStringOption4(
      "fixed_variable_treatment",
      "Determines how fixed variables should be handled.",
      "make_parameter",
      "make_parameter", "Remove fixed variable from optimization variables",
      "make_parameter_nodual", "Remove fixed variable from optimization variables and do not compute bound multipliers for fixed variables",
      "make_constraint", "Add equality constraints fixing variables",
      "relax_bounds", "Relax fixing bound constraints",
      "The main difference between those options is that the starting point in the \"make_constraint\" case still "
      "has the fixed variables at their given values, whereas in the case \"make_parameter(_nodual)\" the functions are always "
      "evaluated with the fixed values for those variables.  "
      "Also, for \"relax_bounds\", the fixing bound constraints are relaxed (according to\" bound_relax_factor\"). "
      "For all but \"make_parameter_nodual\", bound multipliers are computed for the fixed variables.");

   std::vector<std::string> options;
   std::vector<std::string> descrs;
   options.push_back("none");
   descrs.push_back("don't check; no extra work at beginning");
#ifdef IPOPT_HAS_MUMPS
   options.push_back("mumps");
   descrs.push_back("use MUMPS");
#endif
#ifdef IPOPT_HAS_WSMP
   options.push_back("wsmp");
   descrs.push_back("use WSMP");
#endif
#if ((defined(COINHSL_HAS_MA28) && !defined(IPOPT_SINGLE)) || (defined(COINHSL_HAS_MA28S) && defined(IPOPT_SINGLE))) && defined(F77_FUNC) && !defined(IPOPT_INT64)
   options.push_back("ma28");
   descrs.push_back("use MA28");
#endif
   roptions->AddStringOption(
      "dependency_detector",
      "Indicates which linear solver should be used to detect linearly dependent equality constraints.",
      "none",
      options,
      descrs,
      "This is experimental and does not work well.",
      true);
   roptions->AddBoolOption(
      "dependency_detection_with_rhs",
      "Indicates if the right hand sides of the constraints should be considered in addition to gradients during dependency detection",
      false,
      "",
      true);
   roptions->AddLowerBoundedIntegerOption(
      "num_linear_variables",
      "Number of linear variables",
      0,
      0,
      "When the Hessian is approximated, it is assumed that the first num_linear_variables variables are linear. "
      "The Hessian is then not approximated in this space. "
      "If the get_number_of_nonlinear_variables method in the TNLP is implemented, this option is ignored.",
      true);
   roptions->AddStringOption2(
      "jacobian_approximation",
      "Specifies technique to compute constraint Jacobian",
      "exact",
      "exact", "user-provided derivatives",
      "finite-difference-values", "user-provided structure, values by finite differences",
      "",
      true);
   roptions->AddStringOption2(
      "gradient_approximation",
      "Specifies technique to compute objective Gradient",
      "exact",
      "exact", "user-provided gradient",
      "finite-difference-values", "values by finite differences",
      "",
      true);
   roptions->AddLowerBoundedNumberOption(
      "findiff_perturbation",
      "Size of the finite difference perturbation for derivative approximation.",
      0., true,
      1e-7,
      "This determines the relative perturbation of the variable entries.",
      true);

   roptions->SetRegisteringCategory("Derivative Checker");
   roptions->AddStringOption4(
      "derivative_test",
      "Enable derivative checker",
      "none",
      "none", "do not perform derivative test",
      "first-order", "perform test of first derivatives at starting point",
      "second-order", "perform test of first and second derivatives at starting point",
      "only-second-order", "perform test of second derivatives at starting point",
      "If this option is enabled, a (slow!) derivative test will be performed before the optimization. "
      "The test is performed at the user provided starting point and marks derivative values that seem suspicious");
   roptions->AddLowerBoundedIntegerOption(
      "derivative_test_first_index",
      "Index of first quantity to be checked by derivative checker",
      -2,
      -2,
      "If this is set to -2, then all derivatives are checked. "
      "Otherwise, for the first derivative test it specifies the first variable for which the test is done (counting starts at 0). "
      "For second derivatives, it specifies the first constraint for which the test is done; "
      "counting of constraint indices starts at 0, and -1 refers to the objective function Hessian.");
   roptions->AddLowerBoundedNumberOption(
      "derivative_test_perturbation",
      "Size of the finite difference perturbation in derivative test.",
      0., true,
      1e-8,
      "This determines the relative perturbation of the variable entries.");
   roptions->AddLowerBoundedNumberOption(
      "derivative_test_tol",
      "Threshold for indicating wrong derivative.",
      0., true,
      1e-4,
      "If the relative deviation of the estimated derivative from the given one is larger than this value, "
      "the corresponding derivative is marked as wrong.");
   roptions->AddBoolOption(
      "derivative_test_print_all",
      "Indicates whether information for all estimated derivatives should be printed.",
      false,
      "Determines verbosity of derivative checker.");
   roptions->AddLowerBoundedNumberOption(
      "point_perturbation_radius",
      "Maximal perturbation of an evaluation point.",
      0., false,
      10.,
      "If a random perturbation of a points is required, this number indicates the maximal perturbation. "
      "This is for example used when determining the center point at which the finite difference derivative test is executed.");
}

bool TNLPAdapter::ProcessOptions(
   const OptionsList& options,
   const std::string& prefix
)
{
   DBG_START_METH("TNLPAdapter::ProcessOptions", dbg_verbosity);
   options.GetNumericValue("nlp_lower_bound_inf", nlp_lower_bound_inf_, prefix);
   options.GetNumericValue("nlp_upper_bound_inf", nlp_upper_bound_inf_, prefix);

   ASSERT_EXCEPTION(nlp_lower_bound_inf_ < nlp_upper_bound_inf_, OPTION_INVALID,
                    "Option \"nlp_lower_bound_inf\" must be smaller than \"nlp_upper_bound_inf\".");

   // Registered in IpOrigIpoptNLP
   options.GetNumericValue("bound_relax_factor", bound_relax_factor_, prefix);

   Index enum_int;
   options.GetEnumValue("fixed_variable_treatment", enum_int, prefix);
   fixed_variable_treatment_ = FixedVariableTreatmentEnum(enum_int);
   options.GetEnumValue("derivative_test", enum_int, prefix);
   derivative_test_ = DerivativeTestEnum(enum_int);
   options.GetNumericValue("derivative_test_perturbation", derivative_test_perturbation_, prefix);
   options.GetNumericValue("derivative_test_tol", derivative_test_tol_, prefix);
   options.GetBoolValue("derivative_test_print_all", derivative_test_print_all_, prefix);
   options.GetIntegerValue("derivative_test_first_index", derivative_test_first_index_, prefix);

   // The option warm_start_same_structure is registered by OrigIpoptNLP
   options.GetBoolValue("warm_start_same_structure", warm_start_same_structure_, prefix);
   // The following is registered in OrigIpoptNLP
   options.GetEnumValue("hessian_approximation", enum_int, prefix);
   hessian_approximation_ = HessianApproximationType(enum_int);
   options.GetIntegerValue("num_linear_variables", num_linear_variables_, prefix);

   options.GetEnumValue("jacobian_approximation", enum_int, prefix);
   jacobian_approximation_ = JacobianApproxEnum(enum_int);
   options.GetEnumValue("gradient_approximation", enum_int, prefix);
   gradient_approximation_ = GradientApproxEnum(enum_int);
   options.GetNumericValue("findiff_perturbation", findiff_perturbation_, prefix);

   options.GetNumericValue("point_perturbation_radius", point_perturbation_radius_, prefix);

   options.GetNumericValue("tol", tol_, prefix);

   options.GetBoolValue("dependency_detection_with_rhs", dependency_detection_with_rhs_, prefix);
   std::string dependency_detector;
   options.GetStringValue("dependency_detector", dependency_detector, prefix);
#ifdef IPOPT_HAS_MUMPS
   if( dependency_detector == "mumps" )
   {
      SmartPtr<SparseSymLinearSolverInterface> SolverInterface;
      SolverInterface = new MumpsSolverInterface();
      SmartPtr<TSymLinearSolver> ScaledSolver =
         new TSymLinearSolver(SolverInterface, NULL);
      dependency_detector_ = new TSymDependencyDetector(*ScaledSolver);
   }
#endif

#ifdef IPOPT_HAS_WSMP
   if( dependency_detector == "wsmp" )
   {
      SmartPtr<SparseSymLinearSolverInterface> SolverInterface;
#ifdef PARDISO_MATCHING_PREPROCESS
      std::string libname;
      options.GetStringValue("pardisolib", libname, prefix);
      SolverInterface = new WsmpSolverInterface(new LibraryLoader(libname));
#else
      SolverInterface = new WsmpSolverInterface();
#endif
      SmartPtr<TSymLinearSolver> ScaledSolver =
         new TSymLinearSolver(SolverInterface, NULL);
      dependency_detector_ = new TSymDependencyDetector(*ScaledSolver);
   }
#endif

#if ((defined(COINHSL_HAS_MA28) && !defined(IPOPT_SINGLE)) || (defined(COINHSL_HAS_MA28S) && defined(IPOPT_SINGLE))) && defined(F77_FUNC) && !defined(IPOPT_INT64)
   if( dependency_detector == "ma28" )
   {
      dependency_detector_ = new Ma28TDependencyDetector();
   }
#endif

   if( IsValid(dependency_detector_) )
      if( !dependency_detector_->ReducedInitialize(*jnlst_, options, prefix) )
      {
         return false;
      }

   return true;
}

bool TNLPAdapter::GetSpaces(
   SmartPtr<const VectorSpace>&    x_space,
   SmartPtr<const VectorSpace>&    c_space,
   SmartPtr<const VectorSpace>&    d_space,
   SmartPtr<const VectorSpace>&    x_l_space,
   SmartPtr<const MatrixSpace>&    px_l_space,
   SmartPtr<const VectorSpace>&    x_u_space,
   SmartPtr<const MatrixSpace>&    px_u_space,
   SmartPtr<const VectorSpace>&    d_l_space,
   SmartPtr<const MatrixSpace>&    pd_l_space,
   SmartPtr<const VectorSpace>&    d_u_space,
   SmartPtr<const MatrixSpace>&    pd_u_space,
   SmartPtr<const MatrixSpace>&    Jac_c_space,
   SmartPtr<const MatrixSpace>&    Jac_d_space,
   SmartPtr<const SymMatrixSpace>& Hess_lagrangian_space
)
{
   DBG_START_METH("TNLPAdapter::GetSpaces", dbg_verbosity);

   // First, if required, perform derivative test
   if( derivative_test_ != NO_TEST )
   {
      bool retval = CheckDerivatives(derivative_test_, derivative_test_first_index_);
      if( !retval )
      {
         return retval;
      }
   }

   if( warm_start_same_structure_ )
   {
      ASSERT_EXCEPTION(full_x_, INVALID_WARMSTART,
                       "warm_start_same_structure chosen, but TNLPAdapter is called for the first time.");
      if( IsValid(jnlst_) )
      {
         jnlst_->Printf(J_DETAILED, J_INITIALIZATION, "Reusing previous information for warm start in TNLPAdapter.\n");
      }
   }
   else
   {
      // In case the Adapter has been used before, but this is not a
      // warm start, make sure we delete all previously allocated
      // memory
      delete[] full_x_;
      full_x_ = NULL;
      delete[] full_lambda_;
      full_lambda_ = NULL;
      delete[] full_g_;
      full_g_ = NULL;
      delete[] jac_g_;
      jac_g_ = NULL;
      delete[] c_rhs_;
      c_rhs_ = NULL;
      delete[] jac_idx_map_;
      jac_idx_map_ = NULL;
      delete[] h_idx_map_;
      h_idx_map_ = NULL;
      delete[] x_fixed_map_;
      x_fixed_map_ = NULL;
      jac_fixed_idx_map_.clear();
      jac_fixed_iRow_.clear();
      jac_fixed_jCol_.clear();
#if __cplusplus >= 201103L
      jac_fixed_idx_map_.shrink_to_fit();
      jac_fixed_iRow_.shrink_to_fit();
      jac_fixed_jCol_.shrink_to_fit();
#endif
   }

   // Get the full dimensions of the problem
   Index n_full_x, n_full_g, nz_full_jac_g, nz_full_h;
   bool retval = tnlp_->get_nlp_info(n_full_x, n_full_g, nz_full_jac_g, nz_full_h, index_style_);
   ASSERT_EXCEPTION(retval, INVALID_TNLP, "get_nlp_info returned false");
   ASSERT_EXCEPTION(n_full_x >= 0, INVALID_TNLP, "number of variables negative");
   ASSERT_EXCEPTION(n_full_g >= 0, INVALID_TNLP, "number of constraints negative");
   ASSERT_EXCEPTION(nz_full_jac_g >= 0, INVALID_TNLP, "number of nonzeros in Jacobian negative");
   ASSERT_EXCEPTION(nz_full_h >= 0, INVALID_TNLP, "number of nonzeros in Hessian negative");
   ASSERT_EXCEPTION(
      !warm_start_same_structure_
      || (n_full_x == n_full_x_ && n_full_g == n_full_g_ && nz_full_jac_g == nz_full_jac_g_
          && nz_full_h == nz_full_h_), INVALID_WARMSTART,
      "warm_start_same_structure chosen, but problem dimensions are different.");
   n_full_x_ = n_full_x;
   n_full_g_ = n_full_g;
   nz_full_jac_g_ = nz_full_jac_g;
   nz_full_h_ = nz_full_h;

   if( !warm_start_same_structure_ )
   {
      // create space to store vectors that are the full length of x
      full_x_ = new Number[n_full_x_];

      // create space to store vectors that area the full length of lambda
      full_lambda_ = new Number[n_full_g_];

      // create space to store vectors that are the full length of g
      full_g_ = new Number[n_full_g_];
      // check if there is any meta data for the variables and constraints
      StringMetaDataMapType var_string_md;
      IntegerMetaDataMapType var_integer_md;
      NumericMetaDataMapType var_numeric_md;
      StringMetaDataMapType con_string_md;
      IntegerMetaDataMapType con_integer_md;
      NumericMetaDataMapType con_numeric_md;
      if( !tnlp_->get_var_con_metadata(n_full_x_, var_string_md, var_integer_md, var_numeric_md, n_full_g_,
                                       con_string_md, con_integer_md, con_numeric_md) )
      {
         var_string_md.clear();
         var_integer_md.clear();
         var_numeric_md.clear();
         con_string_md.clear();
         con_integer_md.clear();
         con_numeric_md.clear();
      }

      // allocate internal space to store the full jacobian
      jac_g_ = new Number[nz_full_jac_g_];

      /* Spaces for bounds. We need to remove the fixed variables
       * and find out which bounds do not exist. */
      Number* x_l = new Number[n_full_x_];
      Number* x_u = new Number[n_full_x_];
      Number* g_l = new Number[n_full_g_];
      Number* g_u = new Number[n_full_g_];
      retval = tnlp_->get_bounds_info(n_full_x_, x_l, x_u, n_full_g_, g_l, g_u);
      ASSERT_EXCEPTION(retval, INVALID_TNLP, "get_bounds_info returned false in GetSpaces");

      //*********************************************************
      // Create the spaces and permutation spaces
      //*********************************************************

      Index n_x_var;
      Index n_x_l;
      Index n_x_u;
      Index* x_not_fixed_map = new Index[n_full_x_];
      Index* x_l_map = new Index[n_full_x_];
      Index* x_u_map = new Index[n_full_x_];

      Index n_c;
      Index n_d;
      Index n_d_l;
      Index n_d_u;
      Index* c_map = new Index[n_full_g_]; // we do not know n_c yet!
      Index* d_map = new Index[n_full_g_]; // we do not know n_d yet!
      Index* d_l_map = new Index[n_full_g_]; // "
      Index* d_u_map = new Index[n_full_g_]; // "

      bool done = false;
      // We might have to do the following twice: If we detect that we
      // don't have enough degrees of freedom, we simply redo
      // everything with fixed_variable_treatment to set RELAX_BOUNDS
      while( !done )
      {
         n_x_var = 0;
         n_x_l = 0;
         n_x_u = 0;
         n_x_fixed_ = 0;
         Index* x_fixed_map_tmp = new Index[n_full_x_];

         for( Index i = 0; i < n_full_x_; i++ )
         {
            Number lower_bound = x_l[i];
            Number upper_bound = x_u[i];
            if( lower_bound == upper_bound )
            {
               switch( fixed_variable_treatment_ )
               {
                  case MAKE_PARAMETER:
                  case MAKE_PARAMETER_NODUAL:
                     // Variable is fixed, remove it from the problem
                     full_x_[i] = lower_bound;
                     x_fixed_map_tmp[n_x_fixed_] = i;
                     n_x_fixed_++;
                     break;
                  case MAKE_CONSTRAINT:
                     x_fixed_map_tmp[n_x_fixed_] = i; // don't really need this
                     // array then
                     n_x_fixed_++;
                     x_not_fixed_map[n_x_var] = i;
                     n_x_var++;
                     break;
                  case RELAX_BOUNDS:
                     x_l_map[n_x_l] = n_x_var;
                     n_x_l++;
                     x_u_map[n_x_u] = n_x_var;
                     n_x_u++;
                     n_x_var++;
                     break;
                  default:
                     DBG_ASSERT(false && "invalid fixed_variable_treatment_");
               }
            }
            else if( lower_bound > upper_bound )
            {
               char string[128];
               Snprintf(string, 127,
                        "There are inconsistent bounds on variable %" IPOPT_INDEX_FORMAT ": lower = %25.16e and upper = %25.16e.", i, lower_bound,
                        upper_bound);
               delete[] x_l;
               delete[] x_u;
               delete[] g_l;
               delete[] g_u;
               delete[] x_not_fixed_map;
               delete[] x_fixed_map_tmp;
               delete[] x_l_map;
               delete[] x_u_map;
               delete[] c_map;
               delete[] d_map;
               delete[] d_l_map;
               delete[] d_u_map;
               THROW_EXCEPTION(INCONSISTENT_BOUNDS, string);
            }
            else
            {
               x_not_fixed_map[n_x_var] = i;
               if( lower_bound > nlp_lower_bound_inf_ )
               {
                  x_l_map[n_x_l] = n_x_var;
                  n_x_l++;
               }

               if( upper_bound < nlp_upper_bound_inf_ )
               {
                  x_u_map[n_x_u] = n_x_var;
                  n_x_u++;
               }
               n_x_var++;
            }
         }

         // If there are fixed variables, we keep their position around
         // for a possible warm start later or if fixed variables are
         // treated by added equality constraints
         if( n_x_fixed_ > 0 )
         {
            delete[] x_fixed_map_;
            x_fixed_map_ = NULL;
            x_fixed_map_ = new Index[n_x_fixed_];
            for( Index i = 0; i < n_x_fixed_; i++ )
            {
               x_fixed_map_[i] = x_fixed_map_tmp[i];
            }
         }
         else
         {
            delete[] x_fixed_map_;
            x_fixed_map_ = NULL;
         }
         delete[] x_fixed_map_tmp;

         // Create the spaces for c and d
         // - includes the internal permutation matrices for
         //  full_g to c and d
         // - includes the permutation matrices for d_l and d_u
         // c(x) = (P_c)T * g(x)
         // d(x) = (P_d)T * g(x)
         // d_L = (P_d_L)T * (P_d)T * g_l
         // d_U = (P_d_U)T * (P_d)T * g_u
         n_c = 0;
         n_d = 0;
         n_d_l = 0;
         n_d_u = 0;

         for( Index i = 0; i < n_full_g_; i++ )
         {
            Number lower_bound = g_l[i];
            Number upper_bound = g_u[i];
            if( lower_bound == upper_bound )
            {
               // equality constraint
               c_map[n_c] = i;
               n_c++;
            }
            else if( lower_bound > upper_bound )
            {
               delete[] x_l;
               delete[] x_u;
               delete[] g_l;
               delete[] g_u;
               delete[] x_not_fixed_map;
               delete[] x_l_map;
               delete[] x_u_map;
               delete[] c_map;
               delete[] d_map;
               delete[] d_l_map;
               delete[] d_u_map;
               char string[128];
               Snprintf(string, 127,
                        "There are inconsistent bounds on constraint function %" IPOPT_INDEX_FORMAT ": lower = %25.16e and upper = %25.16e.", i,
                        lower_bound, upper_bound);
               THROW_EXCEPTION(INCONSISTENT_BOUNDS, string);
            }
            else
            {
               // inequality constraint
               d_map[n_d] = i;
               if( lower_bound > nlp_lower_bound_inf_ )
               {
                  d_l_map[n_d_l] = n_d;
                  n_d_l++;
               }
               if( upper_bound < nlp_upper_bound_inf_ )
               {
                  d_u_map[n_d_u] = n_d;
                  n_d_u++;
               }
               n_d++;
            }
         }

         if( fixed_variable_treatment_ == RELAX_BOUNDS || n_x_fixed_ == 0 || n_x_var >= n_c || n_x_var == 0 )
         {
            done = true;
         }
         else
         {
            fixed_variable_treatment_ = RELAX_BOUNDS;
            jnlst_->Printf(J_WARNING, J_INITIALIZATION,
                           "Too few degrees of freedom (n_x = %" IPOPT_INDEX_FORMAT ", n_c = %" IPOPT_INDEX_FORMAT ").\n  Trying fixed_variable_treatment = RELAX_BOUNDS\n\n",
                           n_x_var, n_c);
         }
      } // while (!done)

      // If requested, check if there are linearly dependent equality
      // constraints
      if( n_c > 0 && IsValid(dependency_detector_) )
      {
         std::list<Index> c_deps;
         if( !DetermineDependentConstraints(n_x_var, x_not_fixed_map, x_l, x_u, g_l, g_u, n_c, c_map, c_deps) )
         {
            jnlst_->Printf(J_WARNING, J_INITIALIZATION,
                           "Dependent constraint detector had a problem, assume full rank.\n");
         }
         c_deps.sort();
         if( !c_deps.empty() )
         {
            jnlst_->Printf(J_WARNING, J_INITIALIZATION,
                           "\nDetected %zd linearly dependent equality constraints; taking those out.\n\n", c_deps.size());
         }
         else
         {
            jnlst_->Printf(J_DETAILED, J_INITIALIZATION, "\nNo dependent constraints detected.\n\n");
         }
         if( jnlst_->ProduceOutput(J_DETAILED, J_INITIALIZATION) )
         {
            jnlst_->Printf(J_DETAILED, J_INITIALIZATION, "\nList of indices of dependent constraints:\n");
            Index count = 0;
            for( std::list<Index>::iterator i = c_deps.begin(); i != c_deps.end(); ++i )
            {
               jnlst_->Printf(J_DETAILED, J_INITIALIZATION, "c_dep[%" IPOPT_INDEX_FORMAT "] = %" IPOPT_INDEX_FORMAT "\n", count++, *i);
            }
            jnlst_->Printf(J_DETAILED, J_INITIALIZATION, "\n");
         }
         if( !c_deps.empty() )
         {
            // Take the dependent constraints out.
            // We assume that the list in c_dep is sorted
            std::list<Index>::iterator idep = c_deps.begin();
            Index new_n_c = *idep;
            for( Index i = *idep; i < n_c; i++ )
            {
               if( i == *idep )
               {
                  ++idep;
               }
               else
               {
                  c_map[new_n_c] = c_map[i];
                  new_n_c++;
               }
               if( idep == c_deps.end() )
               {
                  // just copy the rest and done
                  for( Index j = i + 1; j < n_c; j++ )
                  {
                     c_map[new_n_c++] = c_map[j];
                  }
                  break;
               }
            }
            n_c = new_n_c;
            // We also need to set the multipliers for the constraints
            // to zero (could do only for dependent ones... was too lazy
            // right now)
            const Number zero = 0.;
            IpBlasCopy(n_full_g_, &zero, 0, full_lambda_, 1);
         }
      }
      delete[] x_l;
      x_l = NULL;
      delete[] x_u;
      x_u = NULL;

      // create x spaces
      SmartPtr<DenseVectorSpace> dv_x_space = new DenseVectorSpace(n_x_var);
      x_space_ = GetRawPtr(dv_x_space);
      SmartPtr<DenseVectorSpace> dv_x_l_space = new DenseVectorSpace(n_x_l);
      x_l_space_ = GetRawPtr(dv_x_l_space);
      SmartPtr<DenseVectorSpace> dv_x_u_space = new DenseVectorSpace(n_x_u);
      x_u_space_ = GetRawPtr(dv_x_u_space);

      if( n_x_fixed_ > 0 && (fixed_variable_treatment_ == MAKE_PARAMETER || fixed_variable_treatment_ == MAKE_PARAMETER_NODUAL) )
      {
         P_x_full_x_space_ = new ExpansionMatrixSpace(n_full_x_, n_x_var, x_not_fixed_map);
         P_x_full_x_ = P_x_full_x_space_->MakeNewExpansionMatrix();
      }
      else
      {
         P_x_full_x_space_ = NULL;
         P_x_full_x_ = NULL;
      }

      P_x_x_L_space_ = new ExpansionMatrixSpace(n_x_var, n_x_l, x_l_map);
      px_l_space_ = GetRawPtr(P_x_x_L_space_);
      P_x_x_L_ = P_x_x_L_space_->MakeNewExpansionMatrix();
      P_x_x_U_space_ = new ExpansionMatrixSpace(n_x_var, n_x_u, x_u_map);
      px_u_space_ = GetRawPtr(P_x_x_U_space_);
      P_x_x_U_ = P_x_x_U_space_->MakeNewExpansionMatrix();

      // setup the variable meta data if present
      if( var_string_md.size() > 0 )
      {
         for( StringMetaDataMapType::iterator iter = var_string_md.begin(); iter != var_string_md.end(); ++iter )
         {
            std::vector<std::string> string_md(n_x_var);
            const Index* pos_idx = NULL;
            if( IsValid(P_x_full_x_space_) )
            {
               pos_idx = P_x_full_x_->ExpandedPosIndices();
               for( Index i = 0; i < n_x_var; i++ )
               {
                  string_md[i] = iter->second[pos_idx[i]];
               }
            }
            else
            {
               for( Index i = 0; i < n_x_var; i++ )
               {
                  string_md[i] = iter->second[i];
               }
            }
            dv_x_space->SetStringMetaData(iter->first, string_md);

            string_md.clear();
            string_md.resize(n_x_l);
            const Index* pos_idxL = P_x_x_L_space_->ExpandedPosIndices();
            for( Index i = 0; i < n_x_l; i++ )
            {
               if( pos_idx != NULL )
               {
                  string_md[i] = iter->second[pos_idx[pos_idxL[i]]];
               }
               else
               {
                  string_md[i] = iter->second[pos_idxL[i]];
               }
            }
            dv_x_l_space->SetStringMetaData(iter->first, string_md);

            string_md.clear();
            string_md.resize(n_x_u);
            const Index* pos_idxU = P_x_x_U_space_->ExpandedPosIndices();
            for( Index i = 0; i < n_x_u; i++ )
            {
               if( pos_idx != NULL )
               {
                  string_md[i] = iter->second[pos_idx[pos_idxU[i]]];
               }
               else
               {
                  string_md[i] = iter->second[pos_idxU[i]];
               }
            }
            dv_x_u_space->SetStringMetaData(iter->first, string_md);
         }
      }

      if( var_integer_md.size() > 0 )
      {
         for( IntegerMetaDataMapType::iterator iter = var_integer_md.begin(); iter != var_integer_md.end(); ++iter )
         {
            std::vector<Index> integer_md(n_x_var);
            const Index* pos_idx = NULL;
            if( IsValid(P_x_full_x_space_) )
            {
               pos_idx = P_x_full_x_->ExpandedPosIndices();
               for( Index i = 0; i < n_x_var; i++ )
               {
                  integer_md[i] = iter->second[pos_idx[i]];
               }
            }
            else
            {
               for( Index i = 0; i < n_x_var; i++ )
               {
                  integer_md[i] = iter->second[i];
               }
            }
            dv_x_space->SetIntegerMetaData(iter->first, integer_md);

            integer_md.clear();
            integer_md.resize(n_x_l);
            const Index* pos_idxL = P_x_x_L_space_->ExpandedPosIndices();
            for( Index i = 0; i < n_x_l; i++ )
            {
               if( pos_idx != NULL )
               {
                  integer_md[i] = iter->second[pos_idx[pos_idxL[i]]];
               }
               else
               {
                  integer_md[i] = iter->second[pos_idxL[i]];
               }
            }
            dv_x_l_space->SetIntegerMetaData(iter->first, integer_md);

            integer_md.clear();
            integer_md.resize(n_x_u);
            const Index* pos_idxU = P_x_x_U_space_->ExpandedPosIndices();
            for( Index i = 0; i < n_x_u; i++ )
            {
               if( pos_idx != NULL )
               {
                  integer_md[i] = iter->second[pos_idx[pos_idxU[i]]];
               }
               else
               {
                  integer_md[i] = iter->second[pos_idxU[i]];
               }
            }
            dv_x_u_space->SetIntegerMetaData(iter->first, integer_md);
         }
      }

      if( var_numeric_md.size() > 0 )
      {
         for( NumericMetaDataMapType::iterator iter = var_numeric_md.begin(); iter != var_numeric_md.end(); ++iter )
         {
            std::vector<Number> numeric_md(n_x_var);
            const Index* pos_idx = NULL;
            if( IsValid(P_x_full_x_space_) )
            {
               pos_idx = P_x_full_x_->ExpandedPosIndices();
               for( Index i = 0; i < n_x_var; i++ )
               {
                  numeric_md[i] = iter->second[pos_idx[i]];
               }
            }
            else
            {
               for( Index i = 0; i < n_x_var; i++ )
               {
                  numeric_md[i] = iter->second[i];
               }
            }
            dv_x_space->SetNumericMetaData(iter->first, numeric_md);

            numeric_md.clear();
            numeric_md.resize(n_x_l);
            const Index* pos_idxL = P_x_x_L_space_->ExpandedPosIndices();
            for( Index i = 0; i < n_x_l; i++ )
            {
               if( pos_idx != NULL )
               {
                  numeric_md[i] = iter->second[pos_idx[pos_idxL[i]]];
               }
               else
               {
                  numeric_md[i] = iter->second[pos_idxL[i]];
               }
            }
            dv_x_l_space->SetNumericMetaData(iter->first, numeric_md);

            numeric_md.clear();
            numeric_md.resize(n_x_u);
            const Index* pos_idxU = P_x_x_U_space_->ExpandedPosIndices();
            for( Index i = 0; i < n_x_u; i++ )
            {
               if( pos_idx != NULL )
               {
                  numeric_md[i] = iter->second[pos_idx[pos_idxU[i]]];
               }
               else
               {
                  numeric_md[i] = iter->second[pos_idxU[i]];
               }
            }
            dv_x_u_space->SetNumericMetaData(iter->first, numeric_md);
         }
      }

      delete[] x_not_fixed_map;
      x_not_fixed_map = NULL;
      delete[] x_l_map;
      x_l_map = NULL;
      delete[] x_u_map;
      x_u_map = NULL;

      // create the required c_space

      SmartPtr<DenseVectorSpace> dc_space;
      if( n_x_fixed_ == 0 || fixed_variable_treatment_ == MAKE_PARAMETER || fixed_variable_treatment_ == MAKE_PARAMETER_NODUAL )
      {
         dc_space = new DenseVectorSpace(n_c);
      }
      else
      {
         dc_space = new DenseVectorSpace(n_c + n_x_fixed_);
      }
      c_space_ = GetRawPtr(dc_space);
      c_rhs_ = new Number[dc_space->Dim()];

      // create the internal expansion matrix for c to g
      P_c_g_space_ = new ExpansionMatrixSpace(n_full_g_, n_c, c_map);
      P_c_g_ = P_c_g_space_->MakeNewExpansionMatrix();
      delete[] c_map;
      c_map = NULL;

      // create the required d_space
      SmartPtr<DenseVectorSpace> dv_d_space = new DenseVectorSpace(n_d);
      d_space_ = GetRawPtr(dv_d_space);
      // create the internal expansion matrix for d to g
      P_d_g_space_ = new ExpansionMatrixSpace(n_full_g_, n_d, d_map);
      P_d_g_ = P_d_g_space_->MakeNewExpansionMatrix();
      delete[] d_map;
      d_map = NULL;

      // create the required d_l space
      SmartPtr<DenseVectorSpace> dv_d_l_space = new DenseVectorSpace(n_d_l);
      d_l_space_ = GetRawPtr(dv_d_l_space);
      // create the required expansion matrix for d_L to d_L_exp
      SmartPtr<ExpansionMatrixSpace> P_d_l_space = new ExpansionMatrixSpace(n_d, n_d_l, d_l_map);
      pd_l_space_ = GetRawPtr(P_d_l_space);
      delete[] d_l_map;
      d_l_map = NULL;

      // create the required d_u space
      SmartPtr<DenseVectorSpace> dv_d_u_space = new DenseVectorSpace(n_d_u);
      d_u_space_ = GetRawPtr(dv_d_u_space);
      // create the required expansion matrix for d_U to d_U_exp
      SmartPtr<ExpansionMatrixSpace> P_d_u_space = new ExpansionMatrixSpace(n_d, n_d_u, d_u_map);
      pd_u_space_ = GetRawPtr(P_d_u_space);
      delete[] d_u_map;
      d_u_map = NULL;

      delete[] g_l;
      g_l = NULL;
      delete[] g_u;
      g_u = NULL;

      // set the constraint meta data if present
      if( con_string_md.size() > 0 )
      {
         for( StringMetaDataMapType::iterator iter = con_string_md.begin(); iter != con_string_md.end(); ++iter )
         {
            std::vector<std::string> string_md(n_c);
            const Index* pos_idx = P_c_g_space_->ExpandedPosIndices();
            for( Index i = 0; i < n_c; i++ )
            {
               string_md[i] = iter->second[pos_idx[i]];
            }
            dc_space->SetStringMetaData(iter->first, string_md);

            string_md.clear();
            string_md.resize(n_d);
            pos_idx = P_d_g_space_->ExpandedPosIndices();
            for( Index i = 0; i < n_d; i++ )
            {
               string_md[i] = iter->second[pos_idx[i]];
            }
            dv_d_space->SetStringMetaData(iter->first, string_md);

            string_md.clear();
            string_md.resize(n_d_l);
            const Index* d_pos_idx = P_d_l_space->ExpandedPosIndices();
            for( Index i = 0; i < n_d_l; i++ )
            {
               string_md[i] = iter->second[pos_idx[d_pos_idx[i]]];
            }
            dv_d_l_space->SetStringMetaData(iter->first, string_md);

            string_md.clear();
            string_md.resize(n_d_u);
            d_pos_idx = P_d_u_space->ExpandedPosIndices();
            for( Index i = 0; i < n_d_u; i++ )
            {
               string_md[i] = iter->second[pos_idx[d_pos_idx[i]]];
            }
            dv_d_u_space->SetStringMetaData(iter->first, string_md);
         }
      }

      if( con_integer_md.size() > 0 )
      {
         for( IntegerMetaDataMapType::iterator iter = con_integer_md.begin(); iter != con_integer_md.end(); ++iter )
         {
            std::vector<Index> integer_md(n_c);
            const Index* pos_idx = P_c_g_space_->ExpandedPosIndices();
            for( Index i = 0; i < n_c; i++ )
            {
               integer_md[i] = iter->second[pos_idx[i]];
            }
            dc_space->SetIntegerMetaData(iter->first, integer_md);

            integer_md.clear();
            integer_md.resize(n_d);
            pos_idx = P_d_g_space_->ExpandedPosIndices();
            for( Index i = 0; i < n_d; i++ )
            {
               integer_md[i] = iter->second[pos_idx[i]];
            }
            dv_d_space->SetIntegerMetaData(iter->first, integer_md);

            integer_md.clear();
            integer_md.resize(n_d_l);
            const Index* d_pos_idx = P_d_l_space->ExpandedPosIndices();
            for( Index i = 0; i < n_d_l; i++ )
            {
               integer_md[i] = iter->second[pos_idx[d_pos_idx[i]]];
            }
            dv_d_l_space->SetIntegerMetaData(iter->first, integer_md);

            integer_md.clear();
            integer_md.resize(n_d_u);
            d_pos_idx = P_d_u_space->ExpandedPosIndices();
            for( Index i = 0; i < n_d_u; i++ )
            {
               integer_md[i] = iter->second[pos_idx[d_pos_idx[i]]];
            }
            dv_d_u_space->SetIntegerMetaData(iter->first, integer_md);
         }
      }

      if( con_numeric_md.size() > 0 )
      {
         for( NumericMetaDataMapType::iterator iter = con_numeric_md.begin(); iter != con_numeric_md.end(); ++iter )
         {
            std::vector<Number> numeric_md(n_c);
            const Index* pos_idx = P_c_g_space_->ExpandedPosIndices();
            for( Index i = 0; i < n_c; i++ )
            {
               numeric_md[i] = iter->second[pos_idx[i]];
            }
            dc_space->SetNumericMetaData(iter->first, numeric_md);

            numeric_md.clear();
            numeric_md.resize(n_d);
            pos_idx = P_d_g_space_->ExpandedPosIndices();
            for( Index i = 0; i < n_d; i++ )
            {
               numeric_md[i] = iter->second[pos_idx[i]];
            }
            dv_d_space->SetNumericMetaData(iter->first, numeric_md);

            numeric_md.clear();
            numeric_md.resize(n_d_l);
            const Index* d_pos_idx = P_d_l_space->ExpandedPosIndices();
            for( Index i = 0; i < n_d_l; i++ )
            {
               numeric_md[i] = iter->second[pos_idx[d_pos_idx[i]]];
            }
            dv_d_l_space->SetNumericMetaData(iter->first, numeric_md);

            numeric_md.clear();
            numeric_md.resize(n_d_u);
            d_pos_idx = P_d_u_space->ExpandedPosIndices();
            for( Index i = 0; i < n_d_u; i++ )
            {
               numeric_md[i] = iter->second[pos_idx[d_pos_idx[i]]];
            }
            dv_d_u_space->SetNumericMetaData(iter->first, numeric_md);
         }
      }

      /** Create the matrix space for the jacobians
       */
      // Get the non zero structure
      Index* g_iRow = new Index[nz_full_jac_g_];
      Index* g_jCol = new Index[nz_full_jac_g_];

      bool retval = tnlp_->eval_jac_g(n_full_x_, NULL, false, n_full_g_, nz_full_jac_g_, g_iRow, g_jCol, NULL);

      if( !retval )
      {
         delete[] g_iRow;
         delete[] g_jCol;

         THROW_EXCEPTION(INVALID_TNLP, "eval_jac_g returned false in GetSpaces");
      }

      if( index_style_ != TNLP::FORTRAN_STYLE )
      {
         for( Index i = 0; i < nz_full_jac_g_; i++ )
         {
            DBG_ASSERT(g_iRow[i] >= 0);
            DBG_ASSERT(g_iRow[i] < n_full_g_);
            DBG_ASSERT(g_jCol[i] >= 0);
            DBG_ASSERT(g_jCol[i] < n_full_x_);
            g_iRow[i] += 1;
            g_jCol[i] += 1;
         }
      }
#if IPOPT_CHECKLEVEL > 0
      else
      {
         for( Index i = 0; i < nz_full_jac_g_; i++ )
         {
            DBG_ASSERT(g_iRow[i] > 0);
            DBG_ASSERT(g_iRow[i] <= n_full_g_);
            DBG_ASSERT(g_jCol[i] > 0);
            DBG_ASSERT(g_jCol[i] <= n_full_x_);
         }
      }
#endif

      if( jacobian_approximation_ == JAC_FINDIFF_VALUES )
      {
         initialize_findiff_jac(g_iRow, g_jCol);
      }

      // ... build the non-zero structure for jac_c
      // ... (the permutation from rows in jac_g to jac_c is
      // ...  the same as P_c_g_)
      Index nz_jac_all;
      if( fixed_variable_treatment_ == MAKE_PARAMETER || fixed_variable_treatment_ == MAKE_PARAMETER_NODUAL )
      {
         nz_jac_all = nz_full_jac_g_;
      }
      else
      {
         nz_jac_all = nz_full_jac_g_ + n_x_fixed_;
      }
      jac_idx_map_ = new Index[nz_jac_all];
      Index* jac_c_iRow = new Index[nz_jac_all];
      Index* jac_c_jCol = new Index[nz_jac_all];
      Index current_nz = 0;

      const Index* c_row_pos = P_c_g_->CompressedPosIndices();
      if( IsValid(P_x_full_x_) )
      {
         // there are missing variables x
         const Index* c_col_pos = P_x_full_x_->CompressedPosIndices();
         for( Index i = 0; i < nz_full_jac_g_; i++ )
         {
            const Index& c_row = c_row_pos[g_iRow[i] - 1];
            const Index& c_col = c_col_pos[g_jCol[i] - 1];
            if( c_col != -1 && c_row != -1 )
            {
               jac_idx_map_[current_nz] = i;
               jac_c_iRow[current_nz] = c_row + 1;
               jac_c_jCol[current_nz] = c_col + 1;
               current_nz++;
            }
            else if( c_col == -1 && fixed_variable_treatment_ == MAKE_PARAMETER )
            {
               // c_col == -1 should mean a fixed variables
               // c_row == -1 should mean a row in d(x)  (but the distinction into c(x) and d(x) isn't relevant for us here)
               jac_fixed_idx_map_.push_back(i);
               jac_fixed_iRow_.push_back(g_iRow[i]);
               jac_fixed_jCol_.push_back(g_jCol[i]);
            }
         }
      }
      else
      {
         for( Index i = 0; i < nz_full_jac_g_; i++ )
         {
            const Index& c_row = c_row_pos[g_iRow[i] - 1];
            const Index& c_col = g_jCol[i] - 1;
            if( c_row != -1 )
            {
               jac_idx_map_[current_nz] = i;
               jac_c_iRow[current_nz] = c_row + 1;
               jac_c_jCol[current_nz] = c_col + 1;
               current_nz++;
            }
         }
      }
      nz_jac_c_no_extra_ = current_nz;
      Index n_added_constr;
      if( fixed_variable_treatment_ == MAKE_PARAMETER || fixed_variable_treatment_ == MAKE_PARAMETER_NODUAL )
      {
         nz_jac_c_ = nz_jac_c_no_extra_;
         n_added_constr = 0;
      }
      else
      {
         nz_jac_c_ = nz_jac_c_no_extra_ + n_x_fixed_;
         for( Index i = 0; i < n_x_fixed_; i++ )
         {
            jac_c_iRow[current_nz] = n_c + i + 1;
            jac_c_jCol[current_nz] = x_fixed_map_[i] + 1;
            current_nz++;
         }
         n_added_constr = n_x_fixed_;
      }

      Jac_c_space_ = new GenTMatrixSpace(n_c + n_added_constr, n_x_var, nz_jac_c_, jac_c_iRow, jac_c_jCol);
      delete[] jac_c_iRow;
      jac_c_iRow = NULL;
      delete[] jac_c_jCol;
      jac_c_jCol = NULL;

      // ... build the nonzero structure for jac_d
      // ... (the permutation from rows in jac_g to jac_c is the
      // ...  the same as P_d_g_)
      Index* jac_d_iRow = new Index[nz_full_jac_g_];
      Index* jac_d_jCol = new Index[nz_full_jac_g_];
      current_nz = 0;
      const Index* d_row_pos = P_d_g_->CompressedPosIndices();
      if( IsValid(P_x_full_x_) )
      {
         const Index* d_col_pos = P_x_full_x_->CompressedPosIndices();
         for( Index i = 0; i < nz_full_jac_g_; i++ )
         {
            const Index& d_row = d_row_pos[g_iRow[i] - 1];
            const Index& d_col = d_col_pos[g_jCol[i] - 1];
            if( d_col != -1 && d_row != -1 )
            {
               jac_idx_map_[current_nz + nz_jac_c_no_extra_] = i;
               jac_d_iRow[current_nz] = d_row + 1;
               jac_d_jCol[current_nz] = d_col + 1;
               current_nz++;
            }
         }
      }
      else
      {
         for( Index i = 0; i < nz_full_jac_g_; i++ )
         {
            const Index& d_row = d_row_pos[g_iRow[i] - 1];
            const Index& d_col = g_jCol[i] - 1;
            if( d_row != -1 )
            {
               jac_idx_map_[current_nz + nz_jac_c_no_extra_] = i;
               jac_d_iRow[current_nz] = d_row + 1;
               jac_d_jCol[current_nz] = d_col + 1;
               current_nz++;
            }
         }
      }
      nz_jac_d_ = current_nz;
      Jac_d_space_ = new GenTMatrixSpace(n_d, n_x_var, nz_jac_d_, jac_d_iRow, jac_d_jCol);
      delete[] jac_d_iRow;
      jac_d_iRow = NULL;
      delete[] jac_d_jCol;
      jac_d_jCol = NULL;

      delete[] g_iRow;
      g_iRow = NULL;
      delete[] g_jCol;
      g_jCol = NULL;

      if( hessian_approximation_ == EXACT )
      {
         /** Create the matrix space for the hessian of the lagrangian */
         Index* full_h_iRow = new Index[nz_full_h_];
         Index* full_h_jCol = new Index[nz_full_h_];
         Index* h_iRow = new Index[nz_full_h_];
         Index* h_jCol = new Index[nz_full_h_];
         retval = tnlp_->eval_h(n_full_x_, NULL, false, 0, n_full_g_,
                                NULL, false, nz_full_h_, full_h_iRow, full_h_jCol, NULL);
         if( !retval )
         {
            delete[] full_h_iRow;
            delete[] full_h_jCol;
            delete[] h_iRow;
            delete[] h_jCol;
            jnlst_->Printf(J_ERROR, J_INITIALIZATION,
                           "Option \"hessian_approximation\" is not chosen as \"limited-memory\", but eval_h returns false.\n");
            THROW_EXCEPTION(OPTION_INVALID, "eval_h is called but has not been implemented");
         }

         if( index_style_ != TNLP::FORTRAN_STYLE )
         {
            for( Index i = 0; i < nz_full_h_; i++ )
            {
               DBG_ASSERT(full_h_iRow[i] >= 0);
               DBG_ASSERT(full_h_iRow[i] < n_full_x);
               DBG_ASSERT(full_h_jCol[i] >= 0);
               DBG_ASSERT(full_h_jCol[i] < n_full_x);
               full_h_iRow[i] += 1;
               full_h_jCol[i] += 1;
            }
         }
#if IPOPT_CHECKLEVEL > 0
         else
         {
            for( Index i = 0; i < nz_full_h_; i++ )
            {
               DBG_ASSERT(full_h_iRow[i] > 0);
               DBG_ASSERT(full_h_iRow[i] <= n_full_x);
               DBG_ASSERT(full_h_jCol[i] > 0);
               DBG_ASSERT(full_h_jCol[i] <= n_full_x);
            }
         }
#endif

         current_nz = 0;
         if( IsValid(P_x_full_x_) )
         {
            h_idx_map_ = new Index[nz_full_h_];
            const Index* h_pos = P_x_full_x_->CompressedPosIndices();
            for( Index i = 0; i < nz_full_h_; i++ )
            {
               const Index& h_row = h_pos[full_h_iRow[i] - 1];
               const Index& h_col = h_pos[full_h_jCol[i] - 1];
               if( h_row != -1 && h_col != -1 )
               {
                  h_idx_map_[current_nz] = i;
                  h_iRow[current_nz] = h_row + 1;
                  h_jCol[current_nz] = h_col + 1;
                  current_nz++;
               }
            }
         }
         else
         {
            h_idx_map_ = NULL;
            for( Index i = 0; i < nz_full_h_; i++ )
            {
               const Index& h_row = full_h_iRow[i] - 1;
               const Index& h_col = full_h_jCol[i] - 1;
               h_iRow[i] = h_row + 1;
               h_jCol[i] = h_col + 1;
               current_nz++;
            }
            current_nz = nz_full_h_;
         }
         nz_h_ = current_nz;
         Hess_lagrangian_space_ = new SymTMatrixSpace(n_x_var, nz_h_, h_iRow, h_jCol);
         delete[] full_h_iRow;
         full_h_iRow = NULL;
         delete[] full_h_jCol;
         full_h_jCol = NULL;
         delete[] h_iRow;
         h_iRow = NULL;
         delete[] h_jCol;
         h_jCol = NULL;
      }
      else
      {
         nz_h_ = 0;
         Hess_lagrangian_space_ = NULL;
      }
   } /* if (warm_start_same_structure_) { */

   // Assign the spaces to the returned pointers
   x_space = x_space_;
   c_space = c_space_;
   d_space = d_space_;
   x_l_space = x_l_space_;
   px_l_space = px_l_space_;
   x_u_space = x_u_space_;
   px_u_space = px_u_space_;
   d_l_space = d_l_space_;
   pd_l_space = pd_l_space_;
   d_u_space = d_u_space_;
   pd_u_space = pd_u_space_;
   Jac_c_space = Jac_c_space_;
   Jac_d_space = Jac_d_space_;
   Hess_lagrangian_space = Hess_lagrangian_space_;

   if( IsValid(jnlst_) )
   {
      jnlst_->Printf(J_ITERSUMMARY, J_STATISTICS, "Number of nonzeros in equality constraint Jacobian...:%9" IPOPT_INDEX_FORMAT "\n",
                     nz_jac_c_);
      jnlst_->Printf(J_ITERSUMMARY, J_STATISTICS, "Number of nonzeros in inequality constraint Jacobian.:%9" IPOPT_INDEX_FORMAT "\n",
                     nz_jac_d_);
      jnlst_->Printf(J_ITERSUMMARY, J_STATISTICS, "Number of nonzeros in Lagrangian Hessian.............:%9" IPOPT_INDEX_FORMAT "\n\n",
                     nz_h_);
   }

   return true;
}

bool TNLPAdapter::GetBoundsInformation(
   const Matrix& Px_L,
   Vector&       x_L,
   const Matrix& Px_U,
   Vector&       x_U,
   const Matrix& Pd_L,
   Vector&       d_L,
   const Matrix& Pd_U,
   Vector&       d_U
)
{
   // This could be done more efficiently, I have already called this method
   // once to setup the structure for the problem, I could store the values
   // and use them here ?
   // Actually, this is better for a warm start
   Number* x_l = new Number[n_full_x_];
   Number* x_u = new Number[n_full_x_];
   Number* g_l = new Number[n_full_g_];
   Number* g_u = new Number[n_full_g_];
   bool retval = tnlp_->get_bounds_info(n_full_x_, x_l, x_u, n_full_g_, g_l, g_u);
   ASSERT_EXCEPTION(retval, INVALID_TNLP, "get_bounds_info returned false in GetBoundsInformation");

   if( fixed_variable_treatment_ == MAKE_PARAMETER || fixed_variable_treatment_ == MAKE_PARAMETER_NODUAL )
   {
      // Set the values of fixed variables
      for( Index i = 0; i < n_x_fixed_; i++ )
      {
         DBG_ASSERT(x_l[x_fixed_map_[i]] == x_u[x_fixed_map_[i]]);
         full_x_[x_fixed_map_[i]] = x_l[x_fixed_map_[i]];
      }
   }
   else if( fixed_variable_treatment_ == RELAX_BOUNDS )
   {
      // Relax the bounds for fixed variables
      const Number bound_relax = Max(Number(1e-8), bound_relax_factor_);
      for( Index i = 0; i < n_x_fixed_; i++ )
      {
         if( x_l[i] == x_u[i] )
         {
            x_l[i] -= bound_relax * Max(Number(1.), std::abs(x_l[i]));
            x_u[i] += bound_relax * Max(Number(1.), std::abs(x_u[i]));
         }
      }
   }

   // Set the bounds values for x
   DenseVector* dx_L = static_cast<DenseVector*>(&x_L);
   DBG_ASSERT(dynamic_cast<DenseVector*>(&x_L));
   Number* values = dx_L->Values();
   const ExpansionMatrix* em_Px_L = static_cast<const ExpansionMatrix*>(&Px_L);
   DBG_ASSERT(dynamic_cast<const ExpansionMatrix*>(&Px_L));
   if( IsValid(P_x_full_x_) )
   {
      for( Index i = 0; i < Px_L.NCols(); i++ )
      {
         const Index& ipopt_idx = em_Px_L->ExpandedPosIndices()[i];
         const Index& full_idx = P_x_full_x_->ExpandedPosIndices()[ipopt_idx];
         const Number& lower_bound = x_l[full_idx];
         values[i] = lower_bound;
      }
   }
   else
   {
      for( Index i = 0; i < Px_L.NCols(); i++ )
      {
         const Index& ipopt_idx = em_Px_L->ExpandedPosIndices()[i];
         const Number& lower_bound = x_l[ipopt_idx];
         values[i] = lower_bound;
      }
   }

   DenseVector* dx_U = static_cast<DenseVector*>(&x_U);
   DBG_ASSERT(dynamic_cast<DenseVector*>(&x_U));
   values = dx_U->Values();
   const ExpansionMatrix* em_Px_U = static_cast<const ExpansionMatrix*>(&Px_U);
   DBG_ASSERT(dynamic_cast<const ExpansionMatrix*>(&Px_U));
   if( IsValid(P_x_full_x_) )
   {
      for( Index i = 0; i < Px_U.NCols(); i++ )
      {
         const Index& ipopt_idx = em_Px_U->ExpandedPosIndices()[i];
         const Index& full_idx = P_x_full_x_->ExpandedPosIndices()[ipopt_idx];
         const Number& upper_bound = x_u[full_idx];
         values[i] = upper_bound;
      }
   }
   else
   {
      for( Index i = 0; i < Px_U.NCols(); i++ )
      {
         const Index& ipopt_idx = em_Px_U->ExpandedPosIndices()[i];
         const Number& upper_bound = x_u[ipopt_idx];
         values[i] = upper_bound;
      }
   }

   // get the bounds values (rhs values to subtract) for c
   // i.e. if gL == gU, then we actually have g(x) = gL = gU,
   // since we solve c(x) = 0, we actually need c(x) - gL = 0
   for( Index i = 0; i < P_c_g_->NCols(); i++ )
   {
      Index full_idx = P_c_g_->ExpandedPosIndices()[i];
      Number rhs = g_l[full_idx];
      c_rhs_[i] = rhs;
   }
   // similarly, if we have fixed variables, consider them here
   if( fixed_variable_treatment_ == MAKE_CONSTRAINT )
   {
      Index n_c_no_fixed = P_c_g_->NCols();
      for( Index i = 0; i < n_x_fixed_; i++ )
      {
         DBG_ASSERT(x_l[x_fixed_map_[i]] == x_u[x_fixed_map_[i]]);
         c_rhs_[n_c_no_fixed + i] = x_l[x_fixed_map_[i]];
      }
   }

   // get the bounds values for d
   DenseVector* dd_L = static_cast<DenseVector*>(&d_L);
   DBG_ASSERT(dynamic_cast<DenseVector*>(&d_L));
   values = dd_L->Values();
   const ExpansionMatrix* em_Pd_L = static_cast<const ExpansionMatrix*>(&Pd_L);
   DBG_ASSERT(dynamic_cast<const ExpansionMatrix*>(&Pd_L));
   for( Index i = 0; i < Pd_L.NCols(); i++ )
   {
      Index d_exp_idx = em_Pd_L->ExpandedPosIndices()[i];
      Index full_idx = P_d_g_->ExpandedPosIndices()[d_exp_idx];
      Number lower_bound = g_l[full_idx];
      values[i] = lower_bound;
   }

   DenseVector* dd_U = static_cast<DenseVector*>(&d_U);
   DBG_ASSERT(dynamic_cast<DenseVector*>(&d_U));
   values = dd_U->Values();
   const ExpansionMatrix* em_Pd_U = static_cast<const ExpansionMatrix*>(&Pd_U);
   DBG_ASSERT(dynamic_cast<const ExpansionMatrix*>(&Pd_U));
   for( Index i = 0; i < Pd_U.NCols(); i++ )
   {
      Index d_exp_idx = em_Pd_U->ExpandedPosIndices()[i];
      Index full_idx = P_d_g_->ExpandedPosIndices()[d_exp_idx];
      Number upper_bound = g_u[full_idx];
      values[i] = upper_bound;
   }

   // In case we are doing finite differences, keep a copy of the bounds
   if( jacobian_approximation_ != JAC_EXACT || gradient_approximation_ != OBJGRAD_EXACT )
   {
      delete[] findiff_x_l_;
      delete[] findiff_x_u_;
      findiff_x_l_ = x_l;
      findiff_x_u_ = x_u;
      x_l = NULL;
      x_u = NULL;
   }

   delete[] x_l;
   x_l = NULL;
   delete[] x_u;
   x_u = NULL;
   delete[] g_l;
   g_l = NULL;
   delete[] g_u;
   g_u = NULL;

   return true;
}

bool TNLPAdapter::GetStartingPoint(
   SmartPtr<Vector> x,
   bool             need_x,
   SmartPtr<Vector> y_c,
   bool             need_y_c,
   SmartPtr<Vector> y_d,
   bool             need_y_d,
   SmartPtr<Vector> z_L,
   bool             need_z_L,
   SmartPtr<Vector> z_U,
   bool             need_z_U
)
{
   Number* full_x = new Number[n_full_x_];
   Number* full_z_l = new Number[n_full_x_];
   Number* full_z_u = new Number[n_full_x_];
   Number* full_lambda = new Number[n_full_g_];
   bool init_x = need_x;
   bool init_z = need_z_L || need_z_U || (fixed_variable_treatment_ == MAKE_CONSTRAINT && n_x_fixed_ > 0 && need_y_c);
   bool init_lambda = need_y_c || need_y_d;

   bool retvalue = tnlp_->get_starting_point(n_full_x_, init_x, full_x, init_z, full_z_l, full_z_u, n_full_g_,
                   init_lambda, full_lambda);

   if( !retvalue )
   {
      delete[] full_x;
      delete[] full_z_l;
      delete[] full_z_u;
      delete[] full_lambda;
      return false;
   }

   if( need_x )
   {
      DenseVector* dx = static_cast<DenseVector*>(GetRawPtr(x));
      DBG_ASSERT(dynamic_cast<DenseVector*>(GetRawPtr(x)));
      Number* values = dx->Values();
      const Index& n_x_var = x->Dim();
      if( IsValid(P_x_full_x_) )
      {
         const Index* x_pos = P_x_full_x_->ExpandedPosIndices();
         for( Index i = 0; i < n_x_var; i++ )
         {
            values[i] = full_x[x_pos[i]];
         }
      }
      else
      {
         IpBlasCopy(n_x_var, full_x, 1, values, 1);
      }
   }

   if( need_y_c )
   {
      DenseVector* dy_c = static_cast<DenseVector*>(GetRawPtr(y_c));
      DBG_ASSERT(dynamic_cast<DenseVector*>(GetRawPtr(y_c)));
      Number* values = dy_c->Values();
      const Index* y_c_pos = P_c_g_->ExpandedPosIndices();
      for( Index i = 0; i < P_c_g_->NCols(); i++ )
      {
         values[i] = full_lambda[y_c_pos[i]];
      }
      if( fixed_variable_treatment_ == MAKE_CONSTRAINT )
      {
         for( Index i = 0; i < n_x_fixed_; i++ )
         {
            values[P_c_g_->NCols() + i] = full_z_u[x_fixed_map_[i]] - full_z_l[x_fixed_map_[i]];
         }
      }
   }

   if( need_y_d )
   {
      DenseVector* dy_d = static_cast<DenseVector*>(GetRawPtr(y_d));
      DBG_ASSERT(dynamic_cast<DenseVector*>(GetRawPtr(y_d)));
      Number* values = dy_d->Values();
      const Index* y_d_pos = P_d_g_->ExpandedPosIndices();
      for( Index i = 0; i < y_d->Dim(); i++ )
      {
         values[i] = full_lambda[y_d_pos[i]];
      }
   }

   if( need_z_L )
   {
      DenseVector* dz_l = static_cast<DenseVector*>(GetRawPtr(z_L));
      DBG_ASSERT(dynamic_cast<DenseVector*>(GetRawPtr(z_L)));
      Number* values = dz_l->Values();
      const Index& n_z_l = z_L->Dim();
      const Index* z_l_pos = P_x_x_L_->ExpandedPosIndices();
      if( IsValid(P_x_full_x_) )
      {
         const Index* x_pos = P_x_full_x_->ExpandedPosIndices();
         for( Index i = 0; i < n_z_l; i++ )
         {
            Index idx = z_l_pos[i]; // convert from x_L to x (ipopt)
            idx = x_pos[idx]; // convert from x (ipopt) to x_full
            values[i] = full_z_l[idx];
         }
      }
      else
      {
         for( Index i = 0; i < n_z_l; i++ )
         {
            Index idx = z_l_pos[i]; // convert from x_L to x (ipopt)
            values[i] = full_z_l[idx];
         }
      }
   }

   if( need_z_U )
   {
      DenseVector* dz_u = static_cast<DenseVector*>(GetRawPtr(z_U));
      DBG_ASSERT(dynamic_cast<DenseVector*>(GetRawPtr(z_U)));
      Number* values = dz_u->Values();
      const Index* z_u_pos = P_x_x_U_->ExpandedPosIndices();
      if( IsValid(P_x_full_x_) )
      {
         const Index* x_pos = P_x_full_x_->ExpandedPosIndices();
         for( Index i = 0; i < z_U->Dim(); i++ )
         {
            Index idx = z_u_pos[i]; // convert from x_u to x (ipopt)
            idx = x_pos[idx]; // convert from x (ipopt) to x_full
            values[i] = full_z_u[idx];
         }
      }
      else
      {
         for( Index i = 0; i < z_U->Dim(); i++ )
         {
            Index idx = z_u_pos[i]; // convert from x_u to x (ipopt)
            values[i] = full_z_u[idx];
         }
      }
   }

   delete[] full_x;
   full_x = NULL;
   delete[] full_z_l;
   full_z_l = NULL;
   delete[] full_z_u;
   full_z_u = NULL;
   delete[] full_lambda;
   full_lambda = NULL;

   return true;
}

bool TNLPAdapter::GetWarmStartIterate(
   IteratesVector& warm_start_iterate
)
{
   return tnlp_->get_warm_start_iterate(warm_start_iterate);
}

bool TNLPAdapter::Eval_f(
   const Vector& x,
   Number&       f
)
{
   bool new_x = false;
   if( update_local_x(x) )
   {
      new_x = true;
   }
   return tnlp_->eval_f(n_full_x_, full_x_, new_x, f);
}

bool TNLPAdapter::Eval_grad_f(
   const Vector& x,
   Vector&       g_f
)
{
   bool retvalue = false;
   bool new_x = false;
   if( update_local_x(x) )
   {
      new_x = true;
   }

   DenseVector* dg_f = static_cast<DenseVector*>(&g_f);
   DBG_ASSERT(dynamic_cast<DenseVector*>(&g_f));
   Number* values = dg_f->Values();

   if( gradient_approximation_ == OBJGRAD_EXACT )
   {
      if( IsValid(P_x_full_x_) )
      {
         Number* full_grad_f = new Number[n_full_x_];
         if( tnlp_->eval_grad_f(n_full_x_, full_x_, new_x, full_grad_f) )
         {
            const Index* x_pos = P_x_full_x_->ExpandedPosIndices();
            for( Index i = 0; i < g_f.Dim(); i++ )
            {
               values[i] = full_grad_f[x_pos[i]];
            }
            retvalue = true;
         }
         delete[] full_grad_f;
      }
      else
      {
         retvalue = tnlp_->eval_grad_f(n_full_x_, full_x_, new_x, values);
      }
   }
   else
   {
      // make sure we have the value of the objective at the point
      Number f;
      retvalue = tnlp_->eval_f(n_full_x_, full_x_, new_x, f);
      if( retvalue )
      {
         Number* full_x_pert = new Number[n_full_x_];
         IpBlasCopy(n_full_x_, full_x_, 1, full_x_pert, 1);
         const Index* x_pos = NULL;
         if( IsValid(P_x_full_x_) )
         {
            x_pos = P_x_full_x_->ExpandedPosIndices();
         }

         // Compute the finite difference objective
         for( Index i = 0; i < g_f.Dim(); i++ )
         {
            Index ivar = x_pos != NULL ? x_pos[i] : i;
            if( findiff_x_l_[ivar] < findiff_x_u_[ivar] )
            {
               const Number xorig = full_x_pert[ivar];
               Number this_perturbation = findiff_perturbation_ * Max(Number(1.), std::abs(full_x_[ivar]));
               full_x_pert[ivar] += this_perturbation;
               if( full_x_pert[ivar] > findiff_x_u_[ivar] )
               {
                  // if at upper bound, then change direction towards lower bound
                  this_perturbation = -this_perturbation;
                  full_x_pert[ivar] = xorig + this_perturbation;
               }
               Number f_pert;
               retvalue = tnlp_->eval_f(n_full_x_, full_x_pert, true, f_pert);
               if( !retvalue )
               {
                  break;
               }

               values[i] = (f_pert - f) / this_perturbation;

               full_x_pert[ivar] = xorig;
            }
         }

         delete[] full_x_pert;
      }
   }

   return retvalue;
}

bool TNLPAdapter::Eval_c(
   const Vector& x,
   Vector&       c
)
{
   bool new_x = false;
   if( update_local_x(x) )
   {
      new_x = true;
   }

   if( internal_eval_g(new_x) )
   {
      DenseVector* dc = static_cast<DenseVector*>(&c);
      DBG_ASSERT(dynamic_cast<DenseVector*>(&c));
      Number* values = dc->Values();
      const Index* c_pos = P_c_g_->ExpandedPosIndices();
      Index n_c_no_fixed = P_c_g_->NCols();
      for( Index i = 0; i < n_c_no_fixed; i++ )
      {
         values[i] = full_g_[c_pos[i]];
         values[i] -= c_rhs_[i];
      }
      if( fixed_variable_treatment_ == MAKE_CONSTRAINT )
      {
         for( Index i = 0; i < n_x_fixed_; i++ )
         {
            values[n_c_no_fixed + i] = full_x_[x_fixed_map_[i]] - c_rhs_[n_c_no_fixed + i];
         }
      }
      return true;
   }

   return false;
}

bool TNLPAdapter::Eval_jac_c(
   const Vector& x,
   Matrix&       jac_c
)
{
   bool new_x = false;
   if( update_local_x(x) )
   {
      new_x = true;
   }

   if( internal_eval_jac_g(new_x) )
   {
      GenTMatrix* gt_jac_c = static_cast<GenTMatrix*>(&jac_c);
      DBG_ASSERT(dynamic_cast<GenTMatrix*>(&jac_c));
      Number* values = gt_jac_c->Values();

      for( Index i = 0; i < nz_jac_c_no_extra_; i++ )
      {
         // Assume the same structure as initially given
         values[i] = jac_g_[jac_idx_map_[i]];
      }
      if( fixed_variable_treatment_ == MAKE_CONSTRAINT )
      {
         const Number one = 1.;
         IpBlasCopy(n_x_fixed_, &one, 0, &values[nz_jac_c_no_extra_], 1);
      }
      return true;
   }
   return false;
}

bool TNLPAdapter::Eval_d(
   const Vector& x,
   Vector&       d
)
{
   bool new_x = false;
   if( update_local_x(x) )
   {
      new_x = true;
   }

   DenseVector* dd = static_cast<DenseVector*>(&d);
   DBG_ASSERT(dynamic_cast<DenseVector*>(&d));
   Number* values = dd->Values();
   if( internal_eval_g(new_x) )
   {
      const Index* d_pos = P_d_g_->ExpandedPosIndices();
      for( Index i = 0; i < d.Dim(); i++ )
      {
         values[i] = full_g_[d_pos[i]];
      }
      return true;
   }

   return false;
}

bool TNLPAdapter::Eval_jac_d(
   const Vector& x,
   Matrix&       jac_d
)
{
   bool new_x = false;
   if( update_local_x(x) )
   {
      new_x = true;
   }

   if( internal_eval_jac_g(new_x) )
   {
      GenTMatrix* gt_jac_d = static_cast<GenTMatrix*>(&jac_d);
      DBG_ASSERT(dynamic_cast<GenTMatrix*>(&jac_d));
      Number* values = gt_jac_d->Values();

      for( Index i = 0; i < nz_jac_d_; i++ )
      {
         // Assume the same structure as initially given
         values[i] = jac_g_[jac_idx_map_[nz_jac_c_no_extra_ + i]];
      }
      return true;
   }
   return false;
}

bool TNLPAdapter::Eval_h(
   const Vector& x,
   Number        obj_factor,
   const Vector& yc,
   const Vector& yd,
   SymMatrix&    h
)
{
   // First see if all weights are set to zero (for example, when
   // computing the least square multiplier estimates, this is what
   // we do).  In that case, there is no need to compute values, just
   // set them to zero.
   if( obj_factor == 0. && yc.Asum() == 0. && yd.Asum() == 0. )
   {
      SymTMatrix* st_h = static_cast<SymTMatrix*>(&h);
      DBG_ASSERT(dynamic_cast<SymTMatrix*>(&h));
      Number* values = st_h->Values();
      for( Index i = 0; i < nz_h_; i++ )
      {
         values[i] = 0.;
      }
      return true;
   }

   bool retval = false;
   bool new_x = false;
   if( update_local_x(x) )
   {
      new_x = true;
   }
   bool new_y = false;
   if( update_local_lambda(yc, yd) )
   {
      new_y = true;
   }

   SymTMatrix* st_h = static_cast<SymTMatrix*>(&h);
   DBG_ASSERT(dynamic_cast<SymTMatrix*>(&h));
   Number* values = st_h->Values();

   if( h_idx_map_ )
   {
      Number* full_h = new Number[nz_full_h_];

      if( tnlp_->eval_h(n_full_x_, full_x_, new_x, obj_factor, n_full_g_, full_lambda_, new_y, nz_full_h_, NULL, NULL,
                        full_h) )
      {
         for( Index i = 0; i < nz_h_; i++ )
         {
            values[i] = full_h[h_idx_map_[i]];
         }
         retval = true;
      }
      delete[] full_h;
   }
   else
   {
      retval = tnlp_->eval_h(n_full_x_, full_x_, new_x, obj_factor, n_full_g_, full_lambda_, new_y, nz_full_h_, NULL,
                             NULL, values);
   }

   return retval;
}

void TNLPAdapter::GetScalingParameters(
   const SmartPtr<const VectorSpace> x_space,
   const SmartPtr<const VectorSpace> c_space,
   const SmartPtr<const VectorSpace> d_space,
   Number&                           obj_scaling,
   SmartPtr<Vector>&                 x_scaling,
   SmartPtr<Vector>&                 c_scaling,
   SmartPtr<Vector>&                 d_scaling
) const
{
   x_scaling = x_space->MakeNew();
   c_scaling = c_space->MakeNew();
   d_scaling = d_space->MakeNew();
   DBG_ASSERT(c_scaling->Dim() + d_scaling->Dim() == n_full_g_ + (fixed_variable_treatment_ == MAKE_CONSTRAINT ? n_x_fixed_ : 0));

   DenseVector* dx = static_cast<DenseVector*>(GetRawPtr(x_scaling));
   DBG_ASSERT(dynamic_cast<DenseVector*>(GetRawPtr(x_scaling)));
   DenseVector* dc = static_cast<DenseVector*>(GetRawPtr(c_scaling));
   DBG_ASSERT(dynamic_cast<DenseVector*>(GetRawPtr(c_scaling)));
   DenseVector* dd = static_cast<DenseVector*>(GetRawPtr(d_scaling));
   DBG_ASSERT(dynamic_cast<DenseVector*>(GetRawPtr(d_scaling)));
   Number* dx_values = dx->Values();
   Number* dc_values = dc->Values();
   Number* dd_values = dd->Values();

   Number* full_g_scaling = new Number[n_full_g_];
   bool use_x_scaling = true;
   bool use_g_scaling = true;

   if( IsValid(P_x_full_x_) )
   {
      Number* full_x_scaling = new Number[n_full_x_];
      bool retval = tnlp_->get_scaling_parameters(obj_scaling, use_x_scaling, n_full_x_, full_x_scaling, use_g_scaling,
                    n_full_g_, full_g_scaling);
      if( !retval )
      {
         delete[] full_x_scaling;
         jnlst_->Printf(J_ERROR, J_INITIALIZATION,
                        "Option nlp_scaling_method selected as user-scaling, but no user-scaling available, or it cannot be computed.\n");
         THROW_EXCEPTION(OPTION_INVALID, "User scaling chosen, but get_scaling_parameters returned false.");
      }

      if( use_x_scaling )
      {
         const Index* x_pos = P_x_full_x_->ExpandedPosIndices();
         for( Index i = 0; i < dx->Dim(); i++ )
         {
            dx_values[i] = full_x_scaling[x_pos[i]];
         }
      }
      delete[] full_x_scaling;
   }
   else
   {
      bool retval = tnlp_->get_scaling_parameters(obj_scaling, use_x_scaling, n_full_x_, dx_values, use_g_scaling,
                    n_full_g_, full_g_scaling);
      if( !retval )
      {
         jnlst_->Printf(J_ERROR, J_INITIALIZATION,
                        "Option nlp_scaling_method selected as user-scaling, but no user-scaling available, or it cannot be computed.\n");
         THROW_EXCEPTION(OPTION_INVALID, "User scaling chosen, but get_scaling_parameters returned false.");
      }
   }

   if( !use_x_scaling )
   {
      x_scaling = NULL;
   }

   if( use_g_scaling )
   {
      const Index* c_pos = P_c_g_->ExpandedPosIndices();
      for( Index i = 0; i < P_c_g_->NCols(); i++ )
      {
         dc_values[i] = full_g_scaling[c_pos[i]];
      }
      if( fixed_variable_treatment_ == MAKE_CONSTRAINT )
      {
         const Number one = 1.;
         IpBlasCopy(n_x_fixed_, &one, 0, &dc_values[P_c_g_->NCols()], 1);
      }

      const Index* d_pos = P_d_g_->ExpandedPosIndices();
      for( Index i = 0; i < dd->Dim(); i++ )
      {
         dd_values[i] = full_g_scaling[d_pos[i]];
      }
   }
   else
   {
      c_scaling = NULL;
      d_scaling = NULL;
   }

   delete[] full_g_scaling;
}

void TNLPAdapter::FinalizeSolution(
   SolverReturn               status,
   const Vector&              x,
   const Vector&              z_L,
   const Vector&              z_U,
   const Vector&              c,
   const Vector&              d,
   const Vector&              y_c,
   const Vector&              y_d,
   Number                     obj_value,
   const IpoptData*           ip_data,
   IpoptCalculatedQuantities* ip_cq
)
{
   DBG_START_METH("TNLPAdapter::FinalizeSolution", dbg_verbosity);

   update_local_x(x);
   update_local_lambda(y_c, y_d);

   ResortX(x, full_x_);

   StringMetaDataMapType var_string_md;
   IntegerMetaDataMapType var_integer_md;
   NumericMetaDataMapType var_numeric_md;
   StringMetaDataMapType con_string_md;
   IntegerMetaDataMapType con_integer_md;
   NumericMetaDataMapType con_numeric_md;

   SmartPtr<const DenseVectorSpace> x_space = dynamic_cast<const DenseVectorSpace*>(GetRawPtr(x.OwnerSpace()));
   const NumericMetaDataMapType x_meta = x_space->GetNumericMetaData();
   NumericMetaDataMapType::const_iterator x_meta_iter;
   for( x_meta_iter = x_meta.begin(); x_meta_iter != x_meta.end(); ++x_meta_iter )
   {
      if( (Index) x_meta_iter->second.size() == x.Dim() )
      {
         std::vector<Number> new_meta_data;
         new_meta_data.resize(n_full_x_);
         SmartPtr<DenseVector> x_meta_vector = x_space->MakeNewDenseVector();
         x_meta_vector->SetValues(&(x_meta_iter->second)[0]);
         ResortX(*x_meta_vector, &new_meta_data[0]);
         var_numeric_md[x_meta_iter->first] = new_meta_data;
      }
   }

   ResortG(y_c, y_d, full_lambda_);

   SmartPtr<const DenseVectorSpace> y_c_space = dynamic_cast<const DenseVectorSpace*>(GetRawPtr(y_c.OwnerSpace()));
   SmartPtr<const DenseVectorSpace> y_d_space = dynamic_cast<const DenseVectorSpace*>(GetRawPtr(y_d.OwnerSpace()));
   const NumericMetaDataMapType y_c_meta = y_c_space->GetNumericMetaData();
   const NumericMetaDataMapType y_d_meta = y_d_space->GetNumericMetaData();
   NumericMetaDataMapType::const_iterator y_c_meta_iter;
   for( y_c_meta_iter = y_c_meta.begin(); y_c_meta_iter != y_c_meta.end(); ++y_c_meta_iter )
   {
      if( (Index) y_c_meta_iter->second.size() == y_c.Dim() )
      {
         if( y_d_space->HasNumericMetaData(y_c_meta_iter->first.c_str())    // There exists a corresponding y_d metadata
             && ((Index) (y_d_meta.find(y_c_meta_iter->first)->second).size()) == y_d.Dim() ) // and y_d metadata vector has size y_d.Dim()
         {
            std::vector<Number> y_d_second = y_d_space->GetNumericMetaData(y_c_meta_iter->first);
            std::vector<Number> new_g_meta_data;
            new_g_meta_data.resize(n_full_g_);
            SmartPtr<DenseVector> y_c_meta_vector = y_c_space->MakeNewDenseVector();
            SmartPtr<DenseVector> y_d_meta_vector = y_d_space->MakeNewDenseVector();
            y_c_meta_vector->SetValues(&(y_c_meta_iter->second)[0]);
            if( y_d_second.size() > 0 )
            {
               y_d_meta_vector->SetValues(&y_d_second[0]);
            }
            ResortG(*y_c_meta_vector, *y_d_meta_vector, &new_g_meta_data[0]);
            con_numeric_md[y_c_meta_iter->first] = new_g_meta_data;
         }
      }
   }

   Number* full_g = new Number[n_full_g_];
   // TODO:
   if( c.Dim() + d.Dim() < n_full_g_ )
   {
      const Number zero = 0.;
      IpBlasCopy(n_full_g_, &zero, 0, full_g, 1);
   }
   ResortG(c, d, full_g, true);

   Number* full_z_L = new Number[n_full_x_];
   Number* full_z_U = new Number[n_full_x_];
   switch( status )
   {
      case SUCCESS:
      case MAXITER_EXCEEDED:
      case STOP_AT_TINY_STEP:
      case STOP_AT_ACCEPTABLE_POINT:
      case LOCAL_INFEASIBILITY:
      case USER_REQUESTED_STOP:
      case FEASIBLE_POINT_FOUND:
      case DIVERGING_ITERATES:
      case RESTORATION_FAILURE:
      case ERROR_IN_STEP_COMPUTATION:
         // only for these status codes, IpoptApplication calls without all vectors 0
         if( !ResortBoundMultipliers(x, y_c, y_d, z_L, full_z_L, z_U, full_z_U) )
         {
            jnlst_->Printf(J_WARNING, J_INITIALIZATION, "Failed to evaluate gradient of objective or constraints when computing bound multipliers for fixed variables.\n");
         }
         break;
      default:
         // if IpoptApplication doesn't provide an actual solution, do not bother to setup good multipliers for fixed variables
         ResortBounds(z_L, full_z_L, z_U, full_z_U);
         break;
   }

   SmartPtr<const DenseVectorSpace> z_L_space = dynamic_cast<const DenseVectorSpace*>(GetRawPtr(z_L.OwnerSpace()));
   SmartPtr<const DenseVectorSpace> z_U_space = dynamic_cast<const DenseVectorSpace*>(GetRawPtr(z_U.OwnerSpace()));
   const NumericMetaDataMapType z_L_meta = z_L_space->GetNumericMetaData();
   const NumericMetaDataMapType z_U_meta = z_U_space->GetNumericMetaData();
   NumericMetaDataMapType::const_iterator z_L_meta_iter;
   for( z_L_meta_iter = z_L_meta.begin(); z_L_meta_iter != z_L_meta.end(); ++z_L_meta_iter )
   {
      if( (Index) z_L_meta_iter->second.size() == z_L.Dim() )
      {
         if( z_U_space->HasNumericMetaData(z_L_meta_iter->first.c_str())
             && (Index) z_U_meta.find(z_L_meta_iter->first.c_str())->second.size() == z_U.Dim() )
         {
            std::vector<Number> z_U_second = z_U_space->GetNumericMetaData(z_L_meta_iter->first);
            SmartPtr<DenseVector> z_L_meta_vector = z_L_space->MakeNewDenseVector();
            SmartPtr<DenseVector> z_U_meta_vector = z_U_space->MakeNewDenseVector();
            z_L_meta_vector->SetValues(&(z_L_meta_iter->second)[0]);
            if( z_U_second.size() > 0 )
            {
               z_U_meta_vector->SetValues(&z_U_second[0]);
            }
            std::vector<Number> new_z_L_meta_data(n_full_x_, 0.0);
            std::vector<Number> new_z_U_meta_data(n_full_x_, 0.0);
            ResortBounds(*z_L_meta_vector, &new_z_L_meta_data[0], *z_U_meta_vector, &new_z_U_meta_data[0]);
            std::string z_L_meta_data_tag = z_L_meta_iter->first;
            std::string z_U_meta_data_tag = z_L_meta_iter->first;
            z_L_meta_data_tag += "_z_L";
            z_U_meta_data_tag += "_z_U";
            var_numeric_md[z_L_meta_data_tag] = new_z_L_meta_data;
            var_numeric_md[z_U_meta_data_tag] = new_z_U_meta_data;
         }
      }
   }

   tnlp_->finalize_metadata(n_full_x_, var_string_md, var_integer_md, var_numeric_md, n_full_g_, con_string_md,
                            con_integer_md, con_numeric_md);

   tnlp_->finalize_solution(status, n_full_x_, full_x_, full_z_L, full_z_U, n_full_g_, full_g, full_lambda_, obj_value,
                            ip_data, ip_cq);

   delete[] full_z_L;
   full_z_L = NULL;
   delete[] full_z_U;
   full_z_U = NULL;
   delete[] full_g;
   full_g = NULL;

   if( c.Dim() + d.Dim() < n_full_g_ )
   {
      // Temporary: Check if we really have a feasible point:
      Number max_viol = 0.;
      Number* x_l = new Number[n_full_x_];
      Number* x_u = new Number[n_full_x_];
      Number* g_l = new Number[n_full_g_];
      Number* g_u = new Number[n_full_g_];
      bool retval = tnlp_->get_bounds_info(n_full_x_, x_l, x_u, n_full_g_, g_l, g_u);
      ASSERT_EXCEPTION(retval, INVALID_TNLP, "get_bounds_info returned false in FinalizeSolution");
      for( Index i = 0; i < n_full_g_; i++ )
      {
         max_viol = Max(max_viol, full_g_[i] - g_u[i], g_l[i] - full_g_[i]);
      }
      jnlst_->Printf(J_ITERSUMMARY, J_INITIALIZATION, "Constraint violation for ALL constraints is %e.\n", max_viol);
      delete[] x_l;
      delete[] x_u;
      delete[] g_l;
      delete[] g_u;
   }
}

bool TNLPAdapter::IntermediateCallBack(
   AlgorithmMode              mode,
   Index                      iter,
   Number                     obj_value,
   Number                     inf_pr,
   Number                     inf_du,
   Number                     mu,
   Number                     d_norm,
   Number                     regularization_size,
   Number                     alpha_du,
   Number                     alpha_pr,
   Index                      ls_trials,
   const IpoptData*           ip_data,
   IpoptCalculatedQuantities* ip_cq
)
{
   return tnlp_->intermediate_callback(mode, iter, obj_value, inf_pr, inf_du, mu, d_norm, regularization_size, alpha_du,
                                       alpha_pr, ls_trials, ip_data, ip_cq);
}

void TNLPAdapter::GetQuasiNewtonApproximationSpaces(
   SmartPtr<VectorSpace>& approx_space,
   SmartPtr<Matrix>&      P_approx
)
{
   Index num_nonlin_vars = tnlp_->get_number_of_nonlinear_variables();

   if( num_nonlin_vars < 0 && num_linear_variables_ == 0 )
   {
      approx_space = NULL;
      P_approx = NULL;
      return;
   }

   Index* pos_nonlin_vars = NULL;
   if( num_nonlin_vars < 0 )
   {
      num_nonlin_vars = n_full_x_ - num_linear_variables_;
      pos_nonlin_vars = new Index[num_nonlin_vars];
      Index ii = 0;
      for( Index i = num_linear_variables_; i < n_full_x_; i++ )
      {
         pos_nonlin_vars[ii++] = i;
      }
   }
   else if( num_nonlin_vars > 0 )
   {
      pos_nonlin_vars = new Index[num_nonlin_vars];
      bool retval = tnlp_->get_list_of_nonlinear_variables(num_nonlin_vars, pos_nonlin_vars);
      if( !retval )
      {
         delete[] pos_nonlin_vars;
         jnlst_->Printf(J_ERROR, J_INITIALIZATION,
                        "TNLP's get_number_of_nonlinear_variables returns non-negative number, but get_list_of_nonlinear_variables returns false.\n");
         THROW_EXCEPTION(INVALID_TNLP, "get_list_of_nonlinear_variables has not been overwritten");
      }
      // Correct indices in case user starts counting variables at 1
      // and not 0
      if( index_style_ == TNLP::FORTRAN_STYLE )
      {
         for( Index i = 0; i < num_nonlin_vars; i++ )
         {
            DBG_ASSERT(pos_nonlin_vars[i] > 0);
            DBG_ASSERT(pos_nonlin_vars[i] <= n_full_x_);
            pos_nonlin_vars[i]--;
         }
      }
#if IPOPT_CHECKLEVEL > 0
      else
      {
         for( Index i = 0; i < num_nonlin_vars; i++ )
         {
            DBG_ASSERT(pos_nonlin_vars[i] >= 0);
            DBG_ASSERT(pos_nonlin_vars[i] < n_full_x_);
         }
      }
#endif
   }

   if( IsNull(P_x_full_x_) )
   {
      if( num_nonlin_vars == n_full_x_ )
      {
         approx_space = NULL;
         P_approx = NULL;
      }
      else
      {
         SmartPtr<ExpansionMatrixSpace> ex_sp = new ExpansionMatrixSpace(n_full_x_, num_nonlin_vars, pos_nonlin_vars);
         P_approx = ex_sp->MakeNew();
         approx_space = new DenseVectorSpace(num_nonlin_vars);
      }
   }
   else
   {
      const Index* compr_pos = P_x_full_x_->CompressedPosIndices();
      Index* nonfixed_pos_nonlin_vars = new Index[num_nonlin_vars];

      Index nonfixed_nonlin_vars = 0;
      for( Index i = 0; i < num_nonlin_vars; i++ )
      {
         Index full_pos = pos_nonlin_vars[i];
         Index nonfixed_pos = compr_pos[full_pos];
         if( nonfixed_pos >= 0 )
         {
            nonfixed_pos_nonlin_vars[nonfixed_nonlin_vars] = nonfixed_pos;
            nonfixed_nonlin_vars++;
         }
      }

      const Index n_x_free = n_full_x_ - n_x_fixed_;
      if( nonfixed_nonlin_vars == n_x_free )
      {
         approx_space = NULL;
         P_approx = NULL;
      }
      else
      {
         SmartPtr<ExpansionMatrixSpace> ex_sp = new ExpansionMatrixSpace(n_x_free, nonfixed_nonlin_vars,
            nonfixed_pos_nonlin_vars);
         P_approx = ex_sp->MakeNew();
         approx_space = new DenseVectorSpace(nonfixed_nonlin_vars);
      }

      delete[] nonfixed_pos_nonlin_vars;
   }
   delete[] pos_nonlin_vars;
}

void TNLPAdapter::ResortX(
   const Vector& x,
   Number*       x_orig,
   bool          usefixedvals
)
{
   const DenseVector* dx = static_cast<const DenseVector*>(&x);
   DBG_ASSERT(dynamic_cast<const DenseVector*>(&x));

   if( IsValid(P_x_full_x_) )
   {
      const Index* x_pos = P_x_full_x_->CompressedPosIndices();

      if( dx->IsHomogeneous() )
      {
         const Number& scalar = dx->Scalar();
         for( Index i = 0; i < n_full_x_; i++ )
         {
            Index idx = x_pos[i];
            if( idx != -1 )
            {
               x_orig[i] = scalar;
            }
            else if( usefixedvals )
            {
               x_orig[i] = full_x_[i];
            }
            else
            {
               x_orig[i] = 0.0;
            }
         }
      }
      else
      {
         const Number* x_values = dx->Values();
         for( Index i = 0; i < n_full_x_; i++ )
         {
            Index idx = x_pos[i];
            if( idx != -1 )
            {
               x_orig[i] = x_values[idx];
            }
            else if( usefixedvals )
            {
               x_orig[i] = full_x_[i];
            }
            else
            {
               x_orig[i] = 0.0;
            }
         }
      }
   }
   else
   {
      if( dx->IsHomogeneous() )
      {
         const Number& scalar = dx->Scalar();
         IpBlasCopy(n_full_x_, &scalar, 0, x_orig, 1);
      }
      else
      {
         IpBlasCopy(n_full_x_, dx->Values(), 1, x_orig, 1);
      }
   }
}

void TNLPAdapter::ResortG(
   const Vector& c,
   const Vector& d,
   Number*       g_orig,
   bool          correctrhs
)
{
   const DenseVector* dc = static_cast<const DenseVector*>(&c);
   DBG_ASSERT(dynamic_cast<const DenseVector*>(&c));

   const Index* c_pos = P_c_g_->ExpandedPosIndices();
   if( dc->IsHomogeneous() )
   {
      Number scalar = dc->Scalar();
      for( Index i = 0; i < P_c_g_->NCols(); i++ )
      {
         g_orig[c_pos[i]] = scalar;
         if( correctrhs )
         {
            g_orig[c_pos[i]] += c_rhs_[i];
         }
      }
   }
   else
   {
      const Number* c_values = dc->Values();
      for( Index i = 0; i < P_c_g_->NCols(); i++ )
      {
         g_orig[c_pos[i]] = c_values[i];
         if( correctrhs )
         {
            g_orig[c_pos[i]] += c_rhs_[i];
         }
      }
   }

   const DenseVector* dd = static_cast<const DenseVector*>(&d);
   DBG_ASSERT(dynamic_cast<const DenseVector*>(&d));

   const Index* d_pos = P_d_g_->ExpandedPosIndices();
   if( dd->IsHomogeneous() )
   {
      Number scalar = dd->Scalar();
      for( Index i = 0; i < d.Dim(); i++ )
      {
         g_orig[d_pos[i]] = scalar;
      }
   }
   else
   {
      const Number* d_values = dd->Values();
      for( Index i = 0; i < d.Dim(); i++ )
      {
         g_orig[d_pos[i]] = d_values[i];
      }
   }
}

void TNLPAdapter::ResortBounds(
   const Vector& x_L,
   Number*       x_L_orig,
   const Vector& x_U,
   Number*       x_U_orig
)
{
   if( x_L_orig )
   {
      const DenseVector* dx_L = static_cast<const DenseVector*>(&x_L);
      DBG_ASSERT(dynamic_cast<const DenseVector*>(&x_L));

      const Index* bnds_pos_not_fixed = P_x_x_L_->ExpandedPosIndices();
      const Index& n_xL = x_L.Dim();

      if( n_xL < n_full_x_ )
      {
         memset(x_L_orig, 0, n_full_x_ * sizeof(Number));
      }

      if( IsValid(P_x_full_x_) )
      {
         const Index* bnds_pos_full = P_x_full_x_->ExpandedPosIndices();
         if( dx_L->IsHomogeneous() )
         {
            Number scalar = dx_L->Scalar();
            for( Index i = 0; i < n_xL; i++ )
            {
               Index idx = bnds_pos_not_fixed[i];
               idx = bnds_pos_full[idx];
               x_L_orig[idx] = scalar;
            }
         }
         else
         {
            const Number* x_L_values = dx_L->Values();
            for( Index i = 0; i < n_xL; i++ )
            {
               Index idx = bnds_pos_not_fixed[i];
               idx = bnds_pos_full[idx];
               x_L_orig[idx] = x_L_values[i];
            }
         }
      }
      else
      {
         if( dx_L->IsHomogeneous() )
         {
            Number scalar = dx_L->Scalar();
            for( Index i = 0; i < n_xL; i++ )
            {
               Index idx = bnds_pos_not_fixed[i];
               x_L_orig[idx] = scalar;
            }
         }
         else
         {
            const Number* x_L_values = dx_L->Values();
            for( Index i = 0; i < n_xL; i++ )
            {
               Index idx = bnds_pos_not_fixed[i];
               x_L_orig[idx] = x_L_values[i];
            }
         }
      }
   }

   if( x_U_orig )
   {
      const DenseVector* dx_U = static_cast<const DenseVector*>(&x_U);
      DBG_ASSERT(dynamic_cast<const DenseVector*>(&x_U));

      if( x_U.Dim() < n_full_x_ )
      {
         memset(x_U_orig, 0, n_full_x_ * sizeof(Number));
      }

      const Index* bnds_pos_not_fixed = P_x_x_U_->ExpandedPosIndices();

      if( IsValid(P_x_full_x_) )
      {
         const Index* bnds_pos_full = P_x_full_x_->ExpandedPosIndices();
         if( dx_U->IsHomogeneous() )
         {
            Number scalar = dx_U->Scalar();
            for( Index i = 0; i < x_U.Dim(); i++ )
            {
               Index idx = bnds_pos_not_fixed[i];
               idx = bnds_pos_full[idx];
               x_U_orig[idx] = scalar;
            }
         }
         else
         {
            const Number* x_U_values = dx_U->Values();
            for( Index i = 0; i < x_U.Dim(); i++ )
            {
               Index idx = bnds_pos_not_fixed[i];
               idx = bnds_pos_full[idx];
               x_U_orig[idx] = x_U_values[i];
            }
         }
      }
      else
      {
         if( dx_U->IsHomogeneous() )
         {
            Number scalar = dx_U->Scalar();
            for( Index i = 0; i < x_U.Dim(); i++ )
            {
               Index idx = bnds_pos_not_fixed[i];
               x_U_orig[idx] = scalar;
            }
         }
         else
         {
            const Number* x_U_values = dx_U->Values();
            for( Index i = 0; i < x_U.Dim(); i++ )
            {
               Index idx = bnds_pos_not_fixed[i];
               x_U_orig[idx] = x_U_values[i];
            }
         }
      }
   }
}

bool TNLPAdapter::ResortBoundMultipliers(
   const Vector& x,
   const Vector& y_c,
   const Vector& y_d,
   const Vector& z_L,
   Number*       z_L_orig,
   const Vector& z_U,
   Number*       z_U_orig
)
{
   ResortBounds(z_L, z_L_orig, z_U, z_U_orig);

   if( n_x_fixed_ == 0 )
   {
      return true;
   }

   // recover the bound multipliers for fixed variables
   if( fixed_variable_treatment_ == MAKE_CONSTRAINT )
   {
      const DenseVector* dy_c = static_cast<const DenseVector*>(&y_c);
      DBG_ASSERT(dynamic_cast<const DenseVector*>(&y_c));
      Index n_c_no_fixed = y_c.Dim() - n_x_fixed_;
      if( !dy_c->IsHomogeneous() )
      {
         const Number* values = dy_c->Values();
         for( Index i = 0; i < n_x_fixed_; i++ )
         {
            if( z_L_orig != NULL )
            {
               z_L_orig[x_fixed_map_[i]] = Max(Number(0.), -values[n_c_no_fixed + i]);
            }
            if( z_U_orig != NULL )
            {
               z_U_orig[x_fixed_map_[i]] = Max(Number(0.), values[n_c_no_fixed + i]);
            }
         }
      }
      else
      {
         Number value = dy_c->Scalar();
         for( Index i = 0; i < n_x_fixed_; i++ )
         {
            if( z_L_orig != NULL )
            {
               z_L_orig[x_fixed_map_[i]] = Max(Number(0.), -value);
            }
            if( z_U_orig != NULL )
            {
               z_U_orig[x_fixed_map_[i]] = Max(Number(0.), value);
            }
         }
      }
   }

   if( fixed_variable_treatment_ == MAKE_PARAMETER )
   {
      // Lagrangian should be grad_f + lambda jac - z_L + z_U  == 0
      // so fixed variables get z_L - z_U = grad_f + lambda_jac
      Number* mult = new Number[n_full_x_];
      memset(mult, 0, sizeof(Number) * n_full_x_);

      bool new_x = update_local_x(x);
      if( !tnlp_->eval_grad_f(n_full_x_, full_x_, new_x, mult) )
      {
         delete[] mult;
         return false;
      }

      if( !jac_fixed_idx_map_.empty() )
      {
         if( !internal_eval_jac_g(false) )
         {
            delete[] mult;
            return false;
         }
         DBG_ASSERT(dynamic_cast<const DenseVector*>(&y_c));
         DBG_ASSERT(dynamic_cast<const DenseVector*>(&y_d));
         const DenseVector* dy_c = static_cast<const DenseVector*>(&y_c);
         const DenseVector* dy_d = static_cast<const DenseVector*>(&y_d);
         // mappings from full g() indices to index in c() and d()
         const Index* c_row_pos = P_c_g_->CompressedPosIndices();
         const Index* d_row_pos = P_d_g_->CompressedPosIndices();
         for( size_t i = 0; i < jac_fixed_idx_map_.size(); i++ )
         {
            // Assume the same structure as initially given
            // correct for 1-based indexing in jac_fixed_iRow_ and jac_fixed_jCol_
            Index row = jac_fixed_iRow_[i] - 1;
            Index col = jac_fixed_jCol_[i] - 1;
            Number val = jac_g_[jac_fixed_idx_map_[i]];
            DBG_ASSERT(row >= 0);
            DBG_ASSERT(row < n_full_g_);
            DBG_ASSERT(col >= 0);
            DBG_ASSERT(col < n_full_x_);

            Number lambda = 0.0;
            if( c_row_pos[row] != -1 )
            {
               if( dy_c->IsHomogeneous() )
               {
                  lambda = dy_c->Scalar();
               }
               else
               {
                  lambda = dy_c->Values()[c_row_pos[row]];
               }
            }
            else if( d_row_pos[row] != -1 )
            {
               if( dy_d->IsHomogeneous() )
               {
                  lambda = dy_d->Scalar();
               }
               else
               {
                  lambda = dy_d->Values()[d_row_pos[row]];
               }
            }
            // else: a constraint that is neither in c() nor d(), so assuming lambda=0 seems ok

            // add lambda*jac part
            mult[col] += lambda * val;
         }
      }

      // set z_L = max(0,mult), z_U = max(0,-mult)
      for( Index i = 0; i < n_x_fixed_; ++i )
      {
         Index xidx = x_fixed_map_[i];
         if( z_L_orig != NULL )
         {
            z_L_orig[xidx] = Max(Number(0.0),  mult[xidx]);
         }
         if( z_U_orig != NULL )
         {
            z_U_orig[xidx] = Max(Number(0.0), -mult[xidx]);
         }
      }

      delete[] mult;
   }

   return true;
}

bool TNLPAdapter::update_local_x(
   const Vector& x
)
{
   if( x.GetTag() == x_tag_for_iterates_ )
   {
      return false;
   }

   ResortX(x, full_x_);

   x_tag_for_iterates_ = x.GetTag();

   return true;
}

bool TNLPAdapter::update_local_lambda(
   const Vector& y_c,
   const Vector& y_d
)
{
   if( y_c.GetTag() == y_c_tag_for_iterates_ && y_d.GetTag() == y_d_tag_for_iterates_ )
   {
      return false;
   }

   ResortG(y_c, y_d, full_lambda_);

   y_c_tag_for_iterates_ = y_c.GetTag();
   y_d_tag_for_iterates_ = y_d.GetTag();

   return true;
}

bool TNLPAdapter::internal_eval_g(
   bool new_x
)
{
   if( x_tag_for_g_ == x_tag_for_iterates_ )
   {
      // already calculated!
      return true;
   }

   x_tag_for_g_ = x_tag_for_iterates_;

   bool retval = tnlp_->eval_g(n_full_x_, full_x_, new_x, n_full_g_, full_g_);

   if( !retval )
   {
      x_tag_for_jac_g_ = 0;
   }

   return retval;
}

bool TNLPAdapter::internal_eval_jac_g(
   bool new_x
)
{
   if( x_tag_for_jac_g_ == x_tag_for_iterates_ )
   {
      // already calculated!
      return true;
   }

   x_tag_for_jac_g_ = x_tag_for_iterates_;

   bool retval;
   if( jacobian_approximation_ == JAC_EXACT )
   {
      retval = tnlp_->eval_jac_g(n_full_x_, full_x_, new_x, n_full_g_, nz_full_jac_g_, NULL, NULL, jac_g_);
   }
   else
   {
      // make sure we have the value of the constraints at the point
      retval = internal_eval_g(new_x);
      if( retval )
      {
         Number* full_g_pert = new Number[n_full_g_];
         Number* full_x_pert = new Number[n_full_x_];
         IpBlasCopy(n_full_x_, full_x_, 1, full_x_pert, 1);
         // Compute the finite difference Jacobian
         for( Index ivar = 0; ivar < n_full_x_; ivar++ )
         {
            if( findiff_x_l_[ivar] < findiff_x_u_[ivar] )
            {
               const Number xorig = full_x_pert[ivar];
               Number this_perturbation = findiff_perturbation_ * Max(Number(1.), std::abs(full_x_[ivar]));
               full_x_pert[ivar] += this_perturbation;
               if( full_x_pert[ivar] > findiff_x_u_[ivar] )
               {
                  // if at upper bound, then change direction towards lower bound
                  this_perturbation = -this_perturbation;
                  full_x_pert[ivar] = xorig + this_perturbation;
               }
               retval = tnlp_->eval_g(n_full_x_, full_x_pert, true, n_full_g_, full_g_pert);
               if( !retval )
               {
                  break;
               }
               for( Index i = findiff_jac_ia_[ivar]; i < findiff_jac_ia_[ivar + 1]; i++ )
               {
                  const Index& icon = findiff_jac_ja_[i];
                  const Index& ipos = findiff_jac_postriplet_[i];
                  jac_g_[ipos] = (full_g_pert[icon] - full_g_[icon]) / this_perturbation;
               }
               full_x_pert[ivar] = xorig;
            }
         }
         delete[] full_g_pert;
         delete[] full_x_pert;
      }
   }

   if( !retval )
   {
      x_tag_for_jac_g_ = 0;
   }

   return retval;
}

void TNLPAdapter::initialize_findiff_jac(
   const Index* iRow,
   const Index* jCol
)
{

   SmartPtr<TripletToCSRConverter> findiff_jac_converter = new TripletToCSRConverter(0);
   // construct structure of a sparse matrix with only Jacobian in it
   // TODO: This could be done more efficiently without detour via
   // symmetric matrix
   Index* airn = new Index[nz_full_jac_g_];
   Index* ajcn = new Index[nz_full_jac_g_];
   for( Index i = 0; i < nz_full_jac_g_; i++ )
   {
      airn[i] = jCol[i];
      ajcn[i] = iRow[i] + n_full_x_;
   }
   // Get the column ordered sparse representation
   findiff_jac_nnz_ = findiff_jac_converter->InitializeConverter(n_full_g_ + n_full_x_, nz_full_jac_g_, airn, ajcn);
   delete[] airn;
   delete[] ajcn;
   if( findiff_jac_nnz_ != nz_full_jac_g_ )
   {
      THROW_EXCEPTION(INVALID_TNLP,
                      "Sparsity structure of Jacobian has multiple occurrences of the same position.  This is not allowed for finite differences.");
   }

   // Finally, get the right numbers out of the converter object
   delete[] findiff_jac_ia_;
   delete[] findiff_jac_ja_;
   delete[] findiff_jac_postriplet_;
   findiff_jac_ia_ = NULL;
   findiff_jac_ja_ = NULL;
   findiff_jac_postriplet_ = NULL;
   findiff_jac_ia_ = new Index[n_full_x_ + 1];
   findiff_jac_ja_ = new Index[findiff_jac_nnz_];
   findiff_jac_postriplet_ = new Index[findiff_jac_nnz_];
   const Index* ia = findiff_jac_converter->IA();
   if( ia != NULL )
   {
      for( Index i = 0; i < n_full_x_ + 1; i++ )
      {
         findiff_jac_ia_[i] = ia[i];
      }
   }
   else
   {
      memset(findiff_jac_ia_, 0, n_full_x_ * sizeof(Index));
   }
   const Index* ja = findiff_jac_converter->JA();
   for( Index i = 0; i < findiff_jac_nnz_; i++ )
   {
      findiff_jac_ja_[i] = ja[i] - n_full_x_;
   }
   const Index* postrip = findiff_jac_converter->iPosFirst();
   for( Index i = 0; i < findiff_jac_nnz_; i++ )
   {
      findiff_jac_postriplet_[i] = postrip[i];
   }

}

bool TNLPAdapter::CheckDerivatives(
   TNLPAdapter::DerivativeTestEnum deriv_test,
   Index                           deriv_test_start_index
)
{
   if( deriv_test == NO_TEST )
   {
      return true;
   }

   Index nerrors = 0;

   ASSERT_EXCEPTION(IsValid(jnlst_), ERROR_IN_TNLP_DERIVATIVE_TEST,
                    "No Journalist given to TNLPAdapter.  Need Journalist, otherwise can't produce any output in DerivativeChecker!");

   bool retval = true;
   // Since this method should be independent of all other internal
   // data (so that it can be called indpenendent of GetSpace etc),
   // we are not using any internal fields

   // Obtain the problem size
   Index nx; // number of variables
   Index ng; // number of constriants
   Index nz_jac_g; // number of nonzeros in constraint Jacobian
   Index nz_hess_lag; // number of nonzeros in Lagrangian Hessian
   TNLP::IndexStyleEnum index_style;
   retval = tnlp_->get_nlp_info(nx, ng, nz_jac_g, nz_hess_lag, index_style);
   ASSERT_EXCEPTION(retval, INVALID_TNLP, "get_nlp_info returned false for derivative checker");
   ASSERT_EXCEPTION(nx >= 0, INVALID_TNLP, "number of variables negative");
   ASSERT_EXCEPTION(ng >= 0, INVALID_TNLP, "number of constraints negative");
   ASSERT_EXCEPTION(nz_jac_g >= 0, INVALID_TNLP, "number of nonzeros in Jacobian negative");
   ASSERT_EXCEPTION(nz_hess_lag >= 0, INVALID_TNLP, "number of nonzeros in Hessian negative");

   // Obtain starting point as reference point at which derivative
   // test should be performed
   Number* xref = new Number[nx];
   tnlp_->get_starting_point(nx, true, xref, false, NULL, NULL, ng, false, NULL);

   // Perform a random perturbation.  We need the bounds to make sure
   // they are not violated
   Number* x_l = new Number[nx];
   Number* x_u = new Number[nx];
   Number* g_l = new Number[ng];
   Number* g_u = new Number[ng];
   retval = tnlp_->get_bounds_info(nx, x_l, x_u, ng, g_l, g_u);
   ASSERT_EXCEPTION(retval, INVALID_TNLP, "get_bounds_info returned false in derivative checker");
   IpResetRandom01();
   for( Index i = 0; i < nx; i++ )
   {
      const Number lower = Max(x_l[i], xref[i] - point_perturbation_radius_);
      const Number upper = Min(x_u[i], xref[i] + point_perturbation_radius_);
      const Number interval = upper - lower;
      const Number random_number = IpRandom01();
      xref[i] = lower + random_number * interval;
   }
   delete[] x_l;
   delete[] x_u;
   delete[] g_l;
   delete[] g_u;

   // Obtain value of objective and constraints at reference point
   bool new_x = true;
   Number fref;
   Number* gref = NULL;
   if( ng > 0 )
   {
      gref = new Number[ng];
   }
   retval = tnlp_->eval_f(nx, xref, new_x, fref);
   ASSERT_EXCEPTION(retval, ERROR_IN_TNLP_DERIVATIVE_TEST,
                    "In TNLP derivative test: f could not be evaluated at reference point.");
   new_x = false;
   if( ng > 0 )
   {
      retval = tnlp_->eval_g(nx, xref, new_x, ng, gref);
      ASSERT_EXCEPTION(retval, ERROR_IN_TNLP_DERIVATIVE_TEST,
                       "In TNLP derivative test: g could not be evaluated at reference point.");
   }

   // Obtain gradient of objective function at reference point
   Number* grad_f = new Number[nx];
   retval = tnlp_->eval_grad_f(nx, xref, true, grad_f);
   ASSERT_EXCEPTION(retval, ERROR_IN_TNLP_DERIVATIVE_TEST,
                    "In TNLP derivative test: grad_f could not be evaluated at reference point.");

   Index* g_iRow = NULL;
   Index* g_jCol = NULL;
   Number* jac_g = NULL;
   if( ng > 0 )
   {
      // Obtain constraint Jacobian at reference point (including structure)
      g_iRow = new Index[nz_jac_g];
      g_jCol = new Index[nz_jac_g];
      retval = tnlp_->eval_jac_g(nx, NULL, false, ng, nz_jac_g, g_iRow, g_jCol, NULL);
      ASSERT_EXCEPTION(retval, ERROR_IN_TNLP_DERIVATIVE_TEST,
                       "In TNLP derivative test: Jacobian structure could not be evaluated.");
      // Correct counting if required to C-style
      if( index_style == TNLP::FORTRAN_STYLE )
      {
         for( Index i = 0; i < nz_jac_g; i++ )
         {
            DBG_ASSERT(g_iRow[i] > 0);
            DBG_ASSERT(g_iRow[i] <= ng);
            DBG_ASSERT(g_jCol[i] > 0);
            DBG_ASSERT(g_jCol[i] <= nx);
            g_iRow[i] -= 1;
            g_jCol[i] -= 1;
         }
      }
#if IPOPT_CHECKLEVEL > 0
      else
      {
         for( Index i = 0; i < nz_jac_g; i++ )
         {
            DBG_ASSERT(g_iRow[i] >= 0);
            DBG_ASSERT(g_iRow[i] < ng);
            DBG_ASSERT(g_jCol[i] >= 0);
            DBG_ASSERT(g_jCol[i] < nx);
         }
      }
#endif
      // Obtain values at reference point
      jac_g = new Number[nz_jac_g];
      retval = tnlp_->eval_jac_g(nx, xref, new_x, ng, nz_jac_g, NULL, NULL, jac_g);
      ASSERT_EXCEPTION(retval, ERROR_IN_TNLP_DERIVATIVE_TEST,
                       "In TNLP derivative test: Jacobian values could not be evaluated at reference point.");
   }

   // Space for the perturbed point
   Number* xpert = new Number[nx];
   IpBlasCopy(nx, xref, 1, xpert, 1);

   // Space for constraints at perturbed point
   Number* gpert = NULL;
   if( ng > 0 )
   {
      gpert = new Number[ng];
   }

   Index index_correction = 0;
   if( index_style == TNLP::FORTRAN_STYLE )
   {
      index_correction = 1;
   }

   if( deriv_test == FIRST_ORDER_TEST || deriv_test == SECOND_ORDER_TEST )
   {
      jnlst_->Printf(J_SUMMARY, J_NLP, "Starting derivative checker for first derivatives.\n\n");

      // Now go through all variables and check the partial derivatives
      const Index ivar_first = Max(Index(0), deriv_test_start_index);
      for( Index ivar = ivar_first; ivar < nx; ivar++ )
      {
         Number this_perturbation = derivative_test_perturbation_ * Max(Number(1.), std::abs(xref[ivar]));
         xpert[ivar] = xref[ivar] + this_perturbation;

         Number fpert;
         new_x = true;
         retval = tnlp_->eval_f(nx, xpert, new_x, fpert);
         ASSERT_EXCEPTION(retval, ERROR_IN_TNLP_DERIVATIVE_TEST,
                          "In TNLP derivative test: f could not be evaluated at perturbed point.");
         new_x = false;

         Number deriv_approx = (fpert - fref) / this_perturbation;
         Number deriv_exact = grad_f[ivar];
         Number rel_error = std::abs(deriv_approx - deriv_exact) / Max(std::abs(deriv_approx), derivative_test_tol_);
         char cflag = ' ';
         if( rel_error >= derivative_test_tol_ )
         {
            cflag = '*';
            nerrors++;
         }
         if( cflag != ' ' || derivative_test_print_all_ )
         {
            jnlst_->Printf(J_WARNING, J_NLP, "%c grad_f[      %5" IPOPT_INDEX_FORMAT "] = %23.16e    ~ %23.16e  [%10.3e]\n", cflag,
                           ivar + index_correction, deriv_exact, deriv_approx, rel_error);
         }

         if( ng > 0 )
         {
            retval = tnlp_->eval_g(nx, xpert, new_x, ng, gpert);
            ASSERT_EXCEPTION(retval, ERROR_IN_TNLP_DERIVATIVE_TEST,
                             "In TNLP derivative test: g could not be evaluated at reference point.");
            for( Index icon = 0; icon < ng; icon++ )
            {
               deriv_approx = (gpert[icon] - gref[icon]) / this_perturbation;
               deriv_exact = 0.;
               bool found = false;
               for( Index i = 0; i < nz_jac_g; i++ )
               {
                  if( g_iRow[i] == icon && g_jCol[i] == ivar )
                  {
                     found = true;
                     deriv_exact += jac_g[i];
                  }
               }
               rel_error = std::abs(deriv_approx - deriv_exact) / Max(std::abs(deriv_approx), derivative_test_tol_);
               cflag = ' ';
               if( rel_error >= derivative_test_tol_ )
               {
                  cflag = '*';
                  nerrors++;
               }
               char sflag = ' ';
               if( found )
               {
                  sflag = 'v';
               }
               if( cflag != ' ' || derivative_test_print_all_ )
               {
                  jnlst_->Printf(J_WARNING, J_NLP, "%c jac_g [%5" IPOPT_INDEX_FORMAT ",%5" IPOPT_INDEX_FORMAT "] = %23.16e %c  ~ %23.16e  [%10.3e]\n", cflag,
                                 icon + index_correction, ivar + index_correction, deriv_exact, sflag, deriv_approx, rel_error);
               }
            }
         }

         xpert[ivar] = xref[ivar];
      }

   }
   const Number zero = 0.;
   if( deriv_test == SECOND_ORDER_TEST || deriv_test == ONLY_SECOND_ORDER_TEST )
   {
      jnlst_->Printf(J_SUMMARY, J_NLP, "Starting derivative checker for second derivatives with obj_factor or lambda[i] set to 1.5.\n\n");

      // Get sparsity structure of Hessian
      Index* h_iRow = new Index[nz_hess_lag];
      Index* h_jCol = new Index[nz_hess_lag];
      retval = tnlp_->eval_h(nx, NULL, false, 0., ng, NULL, false, nz_hess_lag, h_iRow, h_jCol, NULL);
      ASSERT_EXCEPTION(retval, ERROR_IN_TNLP_DERIVATIVE_TEST,
                       "In TNLP derivative test: Hessian structure could not be evaluated.");

      if( index_style == TNLP::FORTRAN_STYLE )
      {
         for( Index i = 0; i < nz_hess_lag; i++ )
         {
            DBG_ASSERT(h_iRow[i] > 0);
            DBG_ASSERT(h_iRow[i] <= nx);
            DBG_ASSERT(h_jCol[i] > 0);
            DBG_ASSERT(h_jCol[i] <= nx);
            h_iRow[i] -= 1;
            h_jCol[i] -= 1;
         }
      }
#if IPOPT_CHECKLEVEL > 0
      else
      {
         for( Index i = 0; i < nz_hess_lag; i++ )
         {
            DBG_ASSERT(h_iRow[i] >= 0);
            DBG_ASSERT(h_iRow[i] < nx);
            DBG_ASSERT(h_jCol[i] >= 0);
            DBG_ASSERT(h_jCol[i] < nx);
         }
      }
#endif
      Number* h_values = new Number[nz_hess_lag];

      Number* lambda = NULL;
      if( ng > 0 )
      {
         lambda = new Number[ng];
         IpBlasCopy(ng, &zero, 0, lambda, 1);
      }
      Number* gradref = new Number[nx]; // gradient of objective or constraint at reference point
      Number* gradpert = new Number[nx]; // gradient of objective or constraint at perturbed point
      Number* jacpert = new Number[nz_jac_g];

      // Check all Hessians
      const Index icon_first = Max(Index(-1), deriv_test_start_index);
      for( Index icon = icon_first; icon < ng; icon++ )
      {
         Number objfact = 0.;
         if( icon == -1 )
         {
            objfact = 1.5;
            IpBlasCopy(nx, grad_f, 1, gradref, 1);
         }
         else
         {
            DBG_ASSERT(lambda != NULL);
            lambda[icon] = 1.5;
            IpBlasCopy(nx, &zero, 0, gradref, 1);
            for( Index i = 0; i < nz_jac_g; i++ )
            {
               if( g_iRow[i] == icon )
               {
                  gradref[g_jCol[i]] += jac_g[i];
               }
            }
         }
         // Hessian at reference point
         new_x = true;
         bool new_y = true;
         retval = tnlp_->eval_h(nx, xref, new_x, objfact, ng, lambda, new_y, nz_hess_lag, NULL, NULL, h_values);
         ASSERT_EXCEPTION(retval, ERROR_IN_TNLP_DERIVATIVE_TEST,
                          "In TNLP derivative test: Hessian could not be evaluated at reference point.");

         for( Index ivar = 0; ivar < nx; ivar++ )
         {
            Number this_perturbation = derivative_test_perturbation_ * Max(Number(1.), std::abs(xref[ivar]));
            xpert[ivar] = xref[ivar] + this_perturbation;

            new_x = true;
            if( icon == -1 )
            {
               // we are looking at the objective function
               retval = tnlp_->eval_grad_f(nx, xpert, new_x, gradpert);
               ASSERT_EXCEPTION(retval, ERROR_IN_TNLP_DERIVATIVE_TEST,
                                "In TNLP derivative test: grad_f could not be evaluated at perturbed point.");
            }
            else
            {
               // this is the icon-th constraint
               retval = tnlp_->eval_jac_g(nx, xpert, new_x, ng, nz_jac_g, NULL, NULL, jacpert);
               ASSERT_EXCEPTION(retval, ERROR_IN_TNLP_DERIVATIVE_TEST,
                                "In TNLP derivative test: Jacobian values could not be evaluated at reference point.");
               // ok, now we need to filter the gradient of the icon-th constraint
               IpBlasCopy(nx, &zero, 0, gradpert, 1);
               IpBlasCopy(nx, &zero, 0, gradref, 1);
               for( Index i = 0; i < nz_jac_g; i++ )
               {
                  if( g_iRow[i] == icon )
                  {
                     gradpert[g_jCol[i]] += jacpert[i];
                     gradref[g_jCol[i]] += jac_g[i];
                  }
               }
            }

            for( Index ivar2 = 0; ivar2 < nx; ivar2++ )
            {
               Number deriv_approx = 1.5 * (gradpert[ivar2] - gradref[ivar2]) / this_perturbation;
               Number deriv_exact = 0.;
               bool found = false;
               for( Index i = 0; i < nz_hess_lag; i++ )
               {
                  if( (h_iRow[i] == ivar && h_jCol[i] == ivar2) || (h_jCol[i] == ivar && h_iRow[i] == ivar2) )
                  {
                     deriv_exact += h_values[i];
                     found = true;
                  }
               }
               Number rel_error = std::abs(deriv_approx - deriv_exact) / Max(std::abs(deriv_approx), derivative_test_tol_);
               char cflag = ' ';
               if( rel_error >= derivative_test_tol_ )
               {
                  cflag = '*';
                  nerrors++;
               }
               char sflag = ' ';
               if( found )
               {
                  sflag = 'v';
               }
               if( cflag != ' ' || derivative_test_print_all_ )
               {
                  if( icon == -1 )
                  {
                     jnlst_->Printf(J_WARNING, J_NLP,
                                    "%c             obj_hess[%5" IPOPT_INDEX_FORMAT ",%5" IPOPT_INDEX_FORMAT "] = %23.16e %c  ~ %23.16e  [%10.3e]\n", cflag,
                                    ivar + index_correction, ivar2 + index_correction, deriv_exact, sflag, deriv_approx, rel_error);
                  }
                  else
                  {
                     jnlst_->Printf(J_WARNING, J_NLP,
                                    "%c %5" IPOPT_INDEX_FORMAT "-th constr_hess[%5" IPOPT_INDEX_FORMAT ",%5" IPOPT_INDEX_FORMAT "] = %23.16e %c  ~ %23.16e  [%10.3e]\n", cflag,
                                    icon + index_correction, ivar + index_correction, ivar2 + index_correction, deriv_exact, sflag,
                                    deriv_approx, rel_error);
                  }
               }

            }

            xpert[ivar] = xref[ivar];
         }

         if( icon >= 0 )
         {
            lambda[icon] = 0.;
         }
      }

      delete[] h_iRow;
      delete[] h_jCol;
      delete[] h_values;
      delete[] lambda;
      delete[] gradref;
      delete[] gradpert;
      delete[] jacpert;
   }

   delete[] xref;
   delete[] gref;
   delete[] grad_f;
   delete[] xpert;
   delete[] g_iRow;
   delete[] g_jCol;
   delete[] jac_g;
   delete[] gpert;

   if( nerrors == 0 )
   {
      jnlst_->Printf(J_SUMMARY, J_NLP, "\nNo errors detected by derivative checker.\n\n");
   }
   else
   {
      jnlst_->Printf(J_WARNING, J_NLP, "\nDerivative checker detected %" IPOPT_INDEX_FORMAT " error(s).\n\n", nerrors);
   }

   return retval;
}

bool TNLPAdapter::DetermineDependentConstraints(
   Index             n_x_var,
   const Index*      x_not_fixed_map,
   const Number*     x_l,
   const Number*     x_u,
   const Number*     g_l,
   const Number*     /*g_u*/,
   Index             n_c,
   const Index*      c_map,
   std::list<Index>& c_deps
)
{
   // First get a temporary expansion matrix for getting the equality
   // constraints
   SmartPtr<ExpansionMatrixSpace> P_c_g_space = new ExpansionMatrixSpace(n_full_g_, n_c, c_map);
   SmartPtr<ExpansionMatrix> P_c_g = P_c_g_space->MakeNewExpansionMatrix();

   // Get the structure of the big Jacobian of g and get the map for
   // the equality constraints entries
   Index* g_iRow = new Index[nz_full_jac_g_];
   Index* g_jCol = new Index[nz_full_jac_g_];
   if( !tnlp_->eval_jac_g(n_full_x_, NULL, false, n_full_g_, nz_full_jac_g_, g_iRow, g_jCol, NULL) )
   {
      delete[] g_iRow;
      delete[] g_jCol;
      return false;
   }
   if( index_style_ == TNLP::FORTRAN_STYLE )
   {
      for( Index i = 0; i < nz_full_jac_g_; i++ )
      {
         DBG_ASSERT(g_iRow[i] > 0);
         DBG_ASSERT(g_iRow[i] <= n_full_g_);
         DBG_ASSERT(g_jCol[i] > 0);
         DBG_ASSERT(g_jCol[i] <= n_full_x_);
         g_iRow[i] -= 1;
         g_jCol[i] -= 1;
      }
   }
#if IPOPT_CHECKLEVEL > 0
   else
   {
      for( Index i = 0; i < nz_full_jac_g_; i++ )
      {
         DBG_ASSERT(g_iRow[i] >= 0);
         DBG_ASSERT(g_iRow[i] < n_full_g_);
         DBG_ASSERT(g_jCol[i] >= 0);
         DBG_ASSERT(g_jCol[i] < n_full_x_);
      }
   }
#endif
   // TODO: Here we don't handle
   // fixed_variable_treatment_==MAKE_PARAMETER correctly (yet?)
   // Include space for the RHS
   Index* jac_c_map = new Index[nz_full_jac_g_];
   Index* jac_c_iRow = new Index[nz_full_jac_g_ + n_c];
   Index* jac_c_jCol = new Index[nz_full_jac_g_ + n_c];
   Index nz_jac_c = 0;
   const Index* c_row_pos = P_c_g->CompressedPosIndices();
   Index n_fixed = n_full_x_ - n_x_var;
   if( n_fixed > 0 )
   {
      // Get the reverse map for the fixed variables
      Index* c_col_pos = new Index[n_full_x_];
      for( Index i = 0; i < n_full_x_; i++ )
      {
         c_col_pos[i] = -1;
      }
      for( Index i = 0; i < n_x_var; i++ )
      {
         c_col_pos[x_not_fixed_map[i]] = i;
      }
      for( Index i = 0; i < nz_full_jac_g_; i++ )
      {
         const Index& c_row = c_row_pos[g_iRow[i]];
         const Index& c_col = c_col_pos[g_jCol[i]];
         if( c_col != -1 && c_row != -1 )
         {
            jac_c_map[nz_jac_c] = i;
            jac_c_iRow[nz_jac_c] = c_row + 1;
            jac_c_jCol[nz_jac_c] = c_col + 1;
            nz_jac_c++;
         }
      }
      delete[] c_col_pos;
   }
   else
   {
      for( Index i = 0; i < nz_full_jac_g_; i++ )
      {
         const Index& c_row = c_row_pos[g_iRow[i]];
         const Index& c_col = g_jCol[i];
         if( c_row != -1 )
         {
            jac_c_map[nz_jac_c] = i;
            jac_c_iRow[nz_jac_c] = c_row + 1;
            jac_c_jCol[nz_jac_c] = c_col + 1;
            nz_jac_c++;
         }
      }
   }
   delete[] g_iRow;
   delete[] g_jCol;

   // First we evaluate the equality constraint Jacobian at the
   // starting point with some random perturbation (projected into bounds)
   if( !tnlp_->get_starting_point(n_full_x_, true, full_x_, false, NULL,
                                  NULL, n_full_g_, false, NULL) )
   {
      delete[] jac_c_iRow;
      delete[] jac_c_jCol;
      delete[] jac_c_map;
      return false;
   }
   // Here we reset the random number generator
   IpResetRandom01();
   for( Index i = 0; i < n_full_x_; i++ )
   {
      const Number lower = Max(x_l[i], full_x_[i] - point_perturbation_radius_);
      const Number upper = Min(x_u[i], full_x_[i] + point_perturbation_radius_);
      const Number interval = upper - lower;
      const Number random_number = IpRandom01();
      full_x_[i] = lower + random_number * interval;
   }
   Number* g_vals = NULL;
   if( dependency_detection_with_rhs_ )
   {
      g_vals = new Number[n_full_g_];
      if( !tnlp_->eval_g(n_full_x_, full_x_, true, n_full_g_, g_vals) )
      {
         delete[] jac_c_iRow;
         delete[] jac_c_jCol;
         delete[] jac_c_map;
         delete[] g_vals;
         return false;
      }
   }
   if( !tnlp_->eval_jac_g(n_full_x_, full_x_, !dependency_detection_with_rhs_, n_full_g_, nz_full_jac_g_, NULL, NULL,
                          jac_g_) )
   {
      delete[] jac_c_iRow;
      delete[] jac_c_jCol;
      delete[] jac_c_map;
      delete[] g_vals;
      return false;
   }

   // Get the equality constraint Jacobian out
   Number* jac_c_vals = new Number[nz_jac_c + n_c];
   for( Index i = 0; i < nz_jac_c; i++ )
   {
      jac_c_vals[i] = jac_g_[jac_c_map[i]];
   }
   if( dependency_detection_with_rhs_ )
   {
      // Add the right hand side column
      const Index* c_row_pos2 = P_c_g->ExpandedPosIndices();
      for( Index i = 0; i < n_c; i++ )
      {
         jac_c_iRow[nz_jac_c + i] = i + 1;
         jac_c_jCol[nz_jac_c + i] = n_x_var + 1;
         jac_c_vals[nz_jac_c + i] = g_vals[c_row_pos2[i]] - g_l[c_row_pos2[i]];
      }
      n_x_var += 1;
      nz_jac_c += n_c;
   }

   ASSERT_EXCEPTION(IsValid(dependency_detector_), OPTION_INVALID,
                    "No dependency_detector_ object available in TNLPAdapter::DetermineDependentConstraints");

   bool retval = dependency_detector_->DetermineDependentRows(n_c, n_x_var, nz_jac_c, jac_c_vals, jac_c_iRow,
                 jac_c_jCol, c_deps);

   // For now, we just get rid of the dependency_detector_ object, in
   // order to save memory.  Maybe we need to add a clean method at
   // some point if we think that this is actually used more than
   // once...
   dependency_detector_ = NULL;

   delete[] jac_c_iRow;
   delete[] jac_c_jCol;
   delete[] jac_c_map;
   delete[] jac_c_vals;
   delete[] g_vals;

   return retval;
}

} // namespace Ipopt