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
// Copyright (C) 2004, 2009 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 "AmplTNLP.hpp"
#include "IpDenseVector.hpp"
#include "IpGenTMatrix.hpp"
#include "IpSymTMatrix.hpp"
#include "IpBlas.hpp"

#include <cstring>

/* AMPL includes */
#include "asl.h"
#include "asl_pfgh.h"
#include "getstub.h"

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

void AmplTNLP::gutsOfConstructor(
   const SmartPtr<RegisteredOptions> regoptions,
   const SmartPtr<OptionsList>       options,
   const char* const*                argv,
   bool                              allow_discrete /* = false */,
   SmartPtr<AmplOptionsList>         ampl_options_list /* = NULL */,
   const char*                       ampl_option_string /* = NULL */,
   const char*                       ampl_invokation_string /* = NULL */,
   const char*                       ampl_banner_string /* = NULL */,
   std::string*                      nl_file_content /* = NULL */
)
{
   // The ASL include files #define certain
   // variables that they expect you to work with.
   // These variables then appear as though they are
   // global variables when, in fact, they are not
   // Most of them are data members of an asl object

   // Create the ASL structure
   ASL_pfgh* asl = reinterpret_cast<ASL_pfgh*>(ASL_alloc(ASL_read_pfgh));
   DBG_ASSERT(asl);
   asl_ = asl; // keep the pointer for ourselves to use later...

   // First assume that we don't want to halt on error (default)
   nerror_ = (void*) new fint;
   *(fint*)nerror_ = 0;

   // Read the options and stub
   char* stub = get_options(regoptions, options, ampl_options_list, ampl_option_string, ampl_invokation_string, ampl_banner_string,
                            argv);
   FILE* nl = NULL;
   if( nl_file_content )
   {
      nl = jac0dim(const_cast<char*>(nl_file_content->c_str()), -(ftnlen )nl_file_content->length());
   }
   else
   {
      if( !stub )
      {
         jnlst_->Printf(J_ERROR, J_MAIN, "No .nl file given!\n");
         THROW_EXCEPTION(INVALID_TNLP, "No .nl file given!\n");
      }
      nl = jac0dim(stub, (ftnlen)strlen(stub));
      DBG_ASSERT(nl);
   }
   jnlst_->Printf(J_SUMMARY, J_MAIN, "\n");

   // check the problem statistics (see Table 1 in AMPL doc)
   DBG_ASSERT(n_var > 0); // need some continuous variables
   if( !allow_discrete && (nbv > 0 || niv > 0 || nlvbi > 0 || nlvci > 0 || nlvoi > 0) )
   {
      jnlst_->Printf(J_WARNING, J_MAIN, "==> Warning: Treating %d binary and %d integer variables as continuous.\n\n",
                     nbv, niv + nlvbi + nlvci + nlvoi);
      // never used: allow_discrete = true;
   }
   allow_discrete = true;
   ASSERT_EXCEPTION(allow_discrete || (nbv == 0 && niv == 0 && nlvbi == 0 && nlvci == 0 && nlvoi == 0), IpoptException,
                    "Discrete variables not allowed when the allow_discrete flag is false, "
                    "Either remove the integer variables, or change the flag in the constructor of AmplTNLP");

   if( n_cc != 0 )
   {
      jnlst_->Printf(J_ERROR, J_MAIN,
                     "\n\n***** Ipopt does not support complementarity constraints.  Aborting. *****\n\n");
      ASSERT_EXCEPTION(n_cc == 0, IpoptException,
                       "Ipopt does not support complementarity constraints.");
   }

   DBG_ASSERT(nlo == 0 || nlo == 1); // Can handle nonlinear obj.
   DBG_ASSERT(nwv == 0); // Don't know what "linear arc" variables are
   DBG_ASSERT(nlnc == 0); // Don't know what "nonlinear network"constraints are
   DBG_ASSERT(lnc == 0); // Don't know what "linear network" constraints are

   // Set options in the asl structure
   want_xpi0 = 1 | 2;  // allocate initial values for primal and dual if available
   obj_no = 0;
   DBG_ASSERT((want_xpi0 & 1) == 1 && (want_xpi0 & 2) == 2);

   // allocate space for initial values
   X0 = new real[n_var];
   havex0 = new char[n_var];
   pi0 = new real[n_con];
   havepi0 = new char[n_con];

   // prepare for suffixes
   if( IsValid(suffix_handler_) )
   {
      suffix_handler_->PrepareAmplForSuffixes(asl);
   }

   // read the rest of the nl file
#ifdef IPOPT_INT64
   int retcode = pfgh_read(nl, ASL_return_read_err | ASL_findgroups | ASL_allow_Z | ASL_use_Z);
#else
   int retcode = pfgh_read(nl, ASL_return_read_err | ASL_findgroups);
#endif
   switch( retcode )
   {
      case ASL_readerr_none:
      {
         break;
      }
      case ASL_readerr_nofile:
      {
         jnlst_->Printf(J_ERROR, J_MAIN, "Cannot open .nl file\n");
         THROW_EXCEPTION(INVALID_TNLP, "Cannot open .nl file");
      }
      case ASL_readerr_nonlin:
      {
         DBG_ASSERT(false); // this better not be an error!
         jnlst_->Printf(J_ERROR, J_MAIN, "model involves nonlinearities (ed0read)\n");
         THROW_EXCEPTION(INVALID_TNLP, "model involves nonlinearities (ed0read)");
      }
      case ASL_readerr_argerr:
      {
         jnlst_->Printf(J_ERROR, J_MAIN, "user-defined function with bad args\n");
         THROW_EXCEPTION(INVALID_TNLP, "user-defined function with bad args");
      }
      case ASL_readerr_unavail:
      {
         jnlst_->Printf(J_ERROR, J_MAIN, "user-defined function not available\n");
         THROW_EXCEPTION(INVALID_TNLP, "user-defined function not available");
      }
      case ASL_readerr_corrupt:
      {
         jnlst_->Printf(J_ERROR, J_MAIN, "corrupt .nl file\n");
         THROW_EXCEPTION(INVALID_TNLP, "corrupt .nl file");
      }
      case ASL_readerr_bug:
      {
         jnlst_->Printf(J_ERROR, J_MAIN, "bug in .nl reader\n");
         THROW_EXCEPTION(INVALID_TNLP, "bug in .nl reader");
      }
      case ASL_readerr_CLP:
      {
         jnlst_->Printf(J_ERROR, J_MAIN, "Ampl model contains a constraint without \"=\", \">=\", or \"<=\".\n");
         THROW_EXCEPTION(INVALID_TNLP, "Ampl model contains a constraint without \"=\", \">=\", or \"<=\".");
      }
      default:
      {
         jnlst_->Printf(J_ERROR, J_MAIN, "Unknown error in stub file read. retcode = %d\n", retcode);
         THROW_EXCEPTION(INVALID_TNLP, "Unknown error in stub file read");
      }
   }
}

AmplTNLP::AmplTNLP(
   const SmartPtr<const Journalist>& jnlst,
   const SmartPtr<RegisteredOptions> regoptions,
   const SmartPtr<OptionsList>       options,
   const char* const*                argv,
   SmartPtr<AmplSuffixHandler>       suffix_handler /* = NULL */,
   bool                              allow_discrete /* = false */,
   SmartPtr<AmplOptionsList>         ampl_options_list /* = NULL */,
   const char*                       ampl_option_string /* = NULL */,
   const char*                       ampl_invokation_string /* = NULL */,
   const char*                       ampl_banner_string /* = NULL */,
   std::string*                      nl_file_content /* = NULL */
)
   : TNLP(),
     jnlst_(jnlst),
     asl_(NULL),
     obj_sign_(1),
     nz_h_full_(-1),
     x_sol_(NULL),
     z_L_sol_(NULL),
     z_U_sol_(NULL),
     g_sol_(NULL),
     lambda_sol_(NULL),
     obj_sol_(0.0),
     objval_called_with_current_x_(false),
     conval_called_with_current_x_(false),
     hesset_called_(false),
     set_active_objective_called_(false),
     Oinfo_ptr_(NULL),
     suffix_handler_(suffix_handler)
{
   DBG_START_METH("AmplTNLP::AmplTNLP", dbg_verbosity);

   gutsOfConstructor(regoptions, options, argv, allow_discrete, ampl_options_list, ampl_option_string, ampl_invokation_string, ampl_banner_string, nl_file_content);
}

AmplTNLP::AmplTNLP(
   const SmartPtr<const Journalist>& jnlst,
   const SmartPtr<OptionsList>       options,
   // cppcheck-suppress constParameter
   char**&                           argv,
   SmartPtr<AmplSuffixHandler>       suffix_handler /* = NULL */,
   bool                              allow_discrete /* = false */,
   SmartPtr<AmplOptionsList>         ampl_options_list /* = NULL */,
   const char*                       ampl_option_string /* = NULL */,
   const char*                       ampl_invokation_string /* = NULL */,
   const char*                       ampl_banner_string /* = NULL */,
   std::string*                      nl_file_content /* = NULL */
)
   : TNLP(),
     jnlst_(jnlst),
     asl_(NULL),
     obj_sign_(1),
     nz_h_full_(-1),
     x_sol_(NULL),
     z_L_sol_(NULL),
     z_U_sol_(NULL),
     g_sol_(NULL),
     lambda_sol_(NULL),
     obj_sol_(0.0),
     objval_called_with_current_x_(false),
     conval_called_with_current_x_(false),
     hesset_called_(false),
     set_active_objective_called_(false),
     Oinfo_ptr_(NULL),
     suffix_handler_(suffix_handler)
{
   DBG_START_METH("AmplTNLP::AmplTNLP", dbg_verbosity);

   gutsOfConstructor(NULL, options, argv, allow_discrete, ampl_options_list, ampl_option_string, ampl_invokation_string, ampl_banner_string, nl_file_content);
}

void AmplTNLP::set_active_objective(
   Index in_obj_no
)
{
   if( hesset_called_ )
   {
      jnlst_->Printf(J_ERROR, J_MAIN,
                     "Internal error: AmplTNLP::set_active_objective called after AmplTNLP::call_hesset.\n");
      THROW_EXCEPTION(INVALID_TNLP,
                      "Internal error: AmplTNLP::set_active_objective called after AmplTNLP::call_hesset.");
   }
   ASL_pfgh* asl = asl_;
   DBG_ASSERT(asl);
   obj_no = in_obj_no;
   set_active_objective_called_ = true;
}

void AmplTNLP::call_hesset()
{
   if( hesset_called_ )
   {
      jnlst_->Printf(J_ERROR, J_MAIN, "Internal error: AmplTNLP::call_hesset is called twice.\n");
      THROW_EXCEPTION(INVALID_TNLP, "Internal error: AmplTNLP::call_hesset is called twice.");
   }

   ASL_pfgh* asl = asl_;
   DBG_ASSERT(asl);

   if( n_obj == 0 )
   {
      hesset(1, 0, 0, 0, nlc);
   }
   else
   {
      if( n_obj > 1 && !set_active_objective_called_ )
      {
         jnlst_->Printf(J_ERROR, J_MAIN,
                        "There is more than one objective function in the AMPL model, but AmplTNLP::set_active_objective has not been called.\n");
         THROW_EXCEPTION(INVALID_TNLP,
                         "There is more than one objective function in the AMPL model, but AmplTNLP::set_active_objective has not been called");
      }
      // see "changes" in solvers directory of ampl code...
      hesset(1, obj_no, 1, 0, nlc);
   }

   obj_sign_ = 1; // minimization
   if( n_obj > 0 && objtype[obj_no] != 0 )
   {
      obj_sign_ = -1;
   }

   // find the nonzero structure for the hessian parameters to
   // sphsetup:
   int coeff_obj = 1;
   int mult_supplied = 1; // multipliers will be supplied
   int uptri = 1; // only need the upper triangular part
   nz_h_full_ = sphsetup(-1, coeff_obj, mult_supplied, uptri);

   hesset_called_ = true;
}

AmplTNLP::~AmplTNLP()
{
   ASL_pfgh* asl = asl_;

   if( asl )
   {
      if( X0 )
      {
         delete[] X0;
         X0 = NULL;
      }
      if( havex0 )
      {
         delete[] havex0;
         havex0 = NULL;
      }
      if( pi0 )
      {
         delete[] pi0;
         pi0 = NULL;
      }
      if( havepi0 )
      {
         delete[] havepi0;
         havepi0 = NULL;
      }
      ASL* asl_to_free = (ASL*) asl_;
      ASL_free(&asl_to_free);
      asl_ = NULL;
   }

   delete[] x_sol_;
   x_sol_ = NULL;
   delete[] z_L_sol_;
   z_L_sol_ = NULL;
   delete[] z_U_sol_;
   z_U_sol_ = NULL;
   delete[] g_sol_;
   g_sol_ = NULL;
   delete[] lambda_sol_;
   lambda_sol_ = NULL;

   if( Oinfo_ptr_ )
   {
      Option_Info* Oinfo = (Option_Info*) Oinfo_ptr_;
      delete[] Oinfo->sname;
      delete[] Oinfo->bsname;
      delete[] Oinfo->opname;
      delete Oinfo;
   }

   delete (fint*) nerror_;
}

bool AmplTNLP::get_nlp_info(
   Index&          n,
   Index&          m,
   Index&          nnz_jac_g,
   Index&          nnz_h_lag,
   IndexStyleEnum& index_style
)
{
   ASL_pfgh* asl = asl_;
   DBG_ASSERT(asl);

   if( !hesset_called_ )
   {
      call_hesset();
   }

   n = n_var; // # of variables (variable types have been asserted in the constructor
   m = n_con; // # of constraints
#ifdef IPOPT_INT64
   nnz_jac_g = nZc; // # of non-zeros in the jacobian
#else
   nnz_jac_g = nzc; // # of non-zeros in the jacobian
#endif
   nnz_h_lag = nz_h_full_; // # of non-zeros in the hessian

   index_style = TNLP::FORTRAN_STYLE;

   return true;
}

bool AmplTNLP::get_var_con_metadata(
   Index                   n,
   StringMetaDataMapType&  var_string_md,
   IntegerMetaDataMapType& var_integer_md,
   NumericMetaDataMapType& var_numeric_md,
   Index                   m,
   StringMetaDataMapType&  con_string_md,
   IntegerMetaDataMapType& con_integer_md,
   NumericMetaDataMapType& con_numeric_md
)
{
   ASL_pfgh* asl = asl_;
   DBG_ASSERT(asl);

   // pick up the variable and constraints names if available
   Index rlen = maxrownamelen;
   Index clen = maxcolnamelen;

   if( clen > 0 )
   {
      std::vector<std::string> var_names(n);
      for( Index i = 0; i < n; i++ )
      {
         var_names[i] = var_name(i);
      }
      var_string_md_["idx_names"] = var_names;
   }

   if( rlen > 0 )
   {
      std::vector<std::string> con_names(m);
      for( Index i = 0; i < m; i++ )
      {
         con_names[i] = con_name(i);
      }
      con_string_md_["idx_names"] = con_names;
   }

   if( var_string_md_.size() > 0 || var_integer_md_.size() > 0 || var_numeric_md_.size() > 0
       || con_string_md_.size() > 0 || con_integer_md_.size() > 0 || con_numeric_md_.size() > 0 )
   {
      var_string_md = var_string_md_;
      var_integer_md = var_integer_md_;
      var_numeric_md = var_numeric_md_;
      con_string_md = con_string_md_;
      con_integer_md = con_integer_md_;
      con_numeric_md = con_numeric_md_;
      return true;
   }

   return false;
}

bool AmplTNLP::get_bounds_info(
   Index   n,
   Number* x_l,
   Number* x_u,
   Index   m,
   Number* g_l,
   Number* g_u
)
{
   ASL_pfgh* asl = asl_;
   DBG_ASSERT(asl);

   DBG_ASSERT(n == n_var);
   DBG_ASSERT(m == n_con);

   for( Index i = 0; i < n; i++ )
   {
      x_l[i] = LUv[2 * i];
      x_u[i] = LUv[2 * i + 1];
   }

   for( Index i = 0; i < m; i++ )
   {
      g_l[i] = LUrhs[2 * i];
      g_u[i] = LUrhs[2 * i + 1];
   }

   return true;
}

bool AmplTNLP::get_constraints_linearity(
   Index          n,
   LinearityType* const_types
)
{
   ASL_pfgh* asl = AmplSolverObject();
   DBG_ASSERT(asl);
   //check that n is good
   DBG_ASSERT(n == n_con);
   (void) n;
   // check that there are no network constraints
   DBG_ASSERT(nlnc == 0 && lnc == 0);
   //the first nlc constraints are non linear the rest is linear
   for( Index i = 0; i < nlc; i++ )
   {
      const_types[i] = NON_LINEAR;
   }
   // the rest is linear
   for( Index i = nlc; i < n_con; i++ )
   {
      const_types[i] = LINEAR;
   }
   return true;
}

bool AmplTNLP::get_starting_point(
   Index   n,
   bool    init_x,
   Number* x,
   bool    init_z,
   Number* z_L,
   Number* z_U,
   Index   m,
   bool    init_lambda,
   Number* lambda
)
{
   ASL_pfgh* asl = asl_;
   DBG_ASSERT(asl);
   DBG_ASSERT(n == n_var);
   DBG_ASSERT(m == n_con);

   if( init_x )
      for( Index i = 0; i < n; i++ )
      {
         x[i] = havex0[i] ? X0[i] : Max(LUv[2 * i], Min(LUv[2 * i + 1], 0.0));
      }

   if( init_z )
   {
      // Modified for warm-start from AMPL
      DBG_ASSERT(IsValid(suffix_handler_));
      const Number* zL_init = suffix_handler_->GetNumberSuffixValues("ipopt_zL_in", AmplSuffixHandler::Variable_Source);
      const Number* zU_init = suffix_handler_->GetNumberSuffixValues("ipopt_zU_in", AmplSuffixHandler::Variable_Source);
      for( Index i = 0; i < n; i++ )
      {
         z_L[i] = zL_init != NULL ? obj_sign_ * zL_init[i] : 1.0;
         z_U[i] = zU_init != NULL ? -obj_sign_ * zU_init[i] : 1.0;
      }
   }

   if( init_lambda )
      for( Index i = 0; i < m; i++ )
      {
         lambda[i] = havepi0[i] ? -obj_sign_ * pi0[i] : 0.0;
      }

   return true;
}

bool AmplTNLP::eval_f(
   Index         n,
   const Number* x,
   bool          new_x,
   Number&       obj_value
)
{
   DBG_START_METH("AmplTNLP::eval_f",
                  dbg_verbosity);
   if( !apply_new_x(new_x, n, x) )
   {
      return false;
   }

   return internal_objval(x, obj_value);
}

bool AmplTNLP::eval_grad_f(
   Index         n,
   const Number* x,
   bool          new_x,
   Number*       grad_f
)
{
   DBG_START_METH("AmplTNLP::eval_grad_f",
                  dbg_verbosity);
   ASL_pfgh* asl = asl_;
   DBG_ASSERT(asl);

   if( !apply_new_x(new_x, n, x) )
   {
      return false;
   }

   if( n_obj == 0 )
   {
      for( Index i = 0; i < n; i++ )
      {
         grad_f[i] = 0.;
      }
   }
   else
   {
      objgrd(obj_no, const_cast<Number*>(x), grad_f, (fint* )nerror_);
      if( !nerror_ok(nerror_) )
      {
         return false;
      }

      if( obj_sign_ == -1 )
      {
         for( Index i = 0; i < n; i++ )
         {
            grad_f[i] *= -1.;
         }
      }
   }
   return true;
}

bool AmplTNLP::eval_g(
   Index         n,
   const Number* x,
   bool          new_x,
   Index         m,
   Number*       g
)
{
   DBG_START_METH("AmplTNLP::eval_g", dbg_verbosity);

   DBG_DO(ASL_pfgh* asl = asl_);
   DBG_ASSERT(asl);
   DBG_ASSERT(n == n_var);
   DBG_ASSERT(m == n_con);

   if( !apply_new_x(new_x, n, x) )
   {
      return false;
   }

   return internal_conval(x, m, g);
}

bool AmplTNLP::eval_jac_g(
   Index         n,
   const Number* x,
   bool          new_x,
   Index         m,
   Index         nele_jac,
   Index*        iRow,
   Index*        jCol,
   Number*       values
)
{
   DBG_START_METH("AmplTNLP::eval_jac_g",
                  dbg_verbosity);
   ASL_pfgh* asl = asl_;
   DBG_ASSERT(asl);
   DBG_ASSERT(n == n_var);
   DBG_ASSERT(m == n_con);
   (void) m;

   if( iRow && jCol && !values )
   {
      // setup the structure
      Index current_nz = 0;
      for( Index i = 0; i < n_con; i++ )
      {
         for( cgrad* cg = Cgrad[i]; cg; cg = cg->next )
         {
            iRow[cg->goff] = i + 1;
            jCol[cg->goff] = cg->varno + 1;
            //    iRow[current_nz] = i + 1;
            //    jCol[current_nz] = cg->varno+1;
            current_nz++;
         }
      }
      DBG_ASSERT(current_nz == nele_jac);
      (void) nele_jac;
      return true;
   }
   else if( !iRow && !jCol && values )
   {
      if( !apply_new_x(new_x, n, x) )
      {
         return false;
      }

      jacval(const_cast<Number*>(x), values, (fint* )nerror_);
      if( nerror_ok(nerror_) )
      {
         return true;
      }
   }
   else
   {
      DBG_ASSERT(false && "Invalid combination of iRow, jCol, and values pointers");
   }

   return false;
}

bool AmplTNLP::eval_h(
   Index         n,
   const Number* x,
   bool          new_x,
   Number        obj_factor,
   Index         m,
   const Number* lambda,
   bool          /*new_lambda*/,
   Index         nele_hess,
   Index*        iRow,
   Index*        jCol,
   Number*       values
)
{
   DBG_START_METH("AmplTNLP::eval_h",
                  dbg_verbosity);
   ASL_pfgh* asl = asl_;
   DBG_ASSERT(asl);
   DBG_ASSERT(n == n_var);
   DBG_ASSERT(m == n_con);

   if( iRow && jCol && !values )
   {
      // setup the structure
      Index k = 0;
      for( Index i = 0; i < n; i++ )
      {
#ifdef IPOPT_INT64
         for( size_t j = sputinfo->hcolstartsZ[i]; j < sputinfo->hcolstartsZ[i + 1]; j++ )
#else
         for( Index j = sputinfo->hcolstarts[i]; j < sputinfo->hcolstarts[i + 1]; j++ )
#endif
         {
            iRow[k] = i + 1;
            jCol[k] = sputinfo->hrownos[j] + 1;
            k++;
         }
      }
      DBG_ASSERT(k == nele_hess);
      (void) nele_hess;
      return true;
   }
   else if( !iRow && !jCol && values )
   {
      if( !apply_new_x(new_x, n, x) )
      {
         return false;
      }
      if( !objval_called_with_current_x_ )
      {
         Number dummy;
         internal_objval(x, dummy);
         internal_conval(x, m);
      }
      if( !conval_called_with_current_x_ )
      {
         internal_conval(x, m);
      }

      real* OW = new real[Max(1, n_obj)];
      if( n_obj > 0 )
      {
         for( Index i = 0; i < n_obj; i++ )
         {
            OW[i] = 0.;
         }
         OW[obj_no] = obj_sign_ * obj_factor;
      }
      sphes(values, -1, OW, const_cast<Number*>(lambda));
      delete[] OW;
      return true;
   }
   else
   {
      DBG_ASSERT(false && "Invalid combination of iRow, jCol, and values pointers");
   }

   return false;
}

void AmplTNLP::finalize_solution(
   SolverReturn               status,
   Index                      n,
   const Number*              x,
   const Number*              z_L,
   const Number*              z_U,
   Index                      m,
   const Number*              g,
   const Number*              lambda,
   Number                     obj_value,
   const IpoptData*           /*ip_data*/,
   IpoptCalculatedQuantities* /*ip_cq*/
)
{
   ASL_pfgh* asl = asl_;
   DBG_ASSERT(asl);

   if( !x_sol_ )
   {
      x_sol_ = new Number[n];
   }
   if( !z_L_sol_ )
   {
      z_L_sol_ = new Number[n];
   }
   if( !z_U_sol_ )
   {
      z_U_sol_ = new Number[n];
   }
   if( !g_sol_ )
   {
      g_sol_ = new Number[m];
   }
   if( !lambda_sol_ )
   {
      lambda_sol_ = new Number[m];
   }

   IpBlasCopy(n, x, 1, x_sol_, 1);
   IpBlasCopy(m, g, 1, g_sol_, 1);
   if( obj_sign_ == -1.0 ) // maximization
   {
      for( Index i = 0; i < n; ++i )
      {
         z_L_sol_[i] = -z_L[i];
      }
      IpBlasCopy(n, z_U, 1, z_U_sol_, 1);
      IpBlasCopy(m, lambda, 1, lambda_sol_, 1);
   }
   else
   {
      IpBlasCopy(n, z_L, 1, z_L_sol_, 1);
      for( Index i = 0; i < n; ++i )
      {
         z_U_sol_[i] = -z_U[i];
      }
      for( Index i = 0; i < m; ++i )
      {
         lambda_sol_[i] = -lambda[i];
      }
   }
   obj_sol_ = obj_value;

   std::string message = " \nIpopt " IPOPT_VERSION ": ";
   switch( status )
   {
      case SUCCESS:
         message += "Optimal Solution Found";
         solve_result_num = 0;
         break;

      case STOP_AT_ACCEPTABLE_POINT:
         message += "Solved To Acceptable Level.";
         solve_result_num = 1;
         break;

      case FEASIBLE_POINT_FOUND:
         message += "Found feasible point for square problem.";
         solve_result_num = 2;
         break;

      case LOCAL_INFEASIBILITY:
         message += "Converged to a locally infeasible point. Problem may be infeasible.";
         solve_result_num = 200;
         break;

      case DIVERGING_ITERATES:
         message += "Iterates diverging; problem might be unbounded.";
         solve_result_num = 300;
         break;

      case MAXITER_EXCEEDED:
         message += "Maximum Number of Iterations Exceeded.";
         solve_result_num = 400;
         break;

      case CPUTIME_EXCEEDED:
         message += "Maximum CPU Time Exceeded.";
         solve_result_num = 401;
         break;

      case WALLTIME_EXCEEDED:
         message += "Maximum Wallclock Time Exceeded.";
         solve_result_num = 402;
         break;

      case USER_REQUESTED_STOP:
         message += "User requested stop.";
         solve_result_num = 403;
         break;

      case STOP_AT_TINY_STEP:
         message += "Search Direction becomes Too Small.";
         solve_result_num = 500;
         break;

      case RESTORATION_FAILURE:
         message += "Restoration Phase Failed.";
         solve_result_num = 501;
         break;

      case ERROR_IN_STEP_COMPUTATION:
         message += "Error in step computation.";
         solve_result_num = 502;
         break;

      // the following should be dead code, i.e., finalize_solution isn't called in these cases
      case INVALID_NUMBER_DETECTED:
         message += "Invalid number in NLP function or derivative detected.";
         solve_result_num = 550;
         break;

      case TOO_FEW_DEGREES_OF_FREEDOM:
         message += "NLP has too few degrees of freedom.";
         solve_result_num = 551;
         break;

      case INVALID_OPTION:
         message += "Invalid option setting.";
         solve_result_num = 552;
         break;

      case OUT_OF_MEMORY:
         message += "Out of memory.";
         solve_result_num = 553;
         break;

      case INTERNAL_ERROR:
         message += "Internal error.";
         solve_result_num = 554;
         break;

      case UNASSIGNED:
         message += "Unknown Error";
         solve_result_num = 599;
         break;
   }

   if( IsValid(suffix_handler_) )
   {
      // Modified for warm-start from AMPL. Assign Bound Multipliers as Suffixes
      suf_rput("ipopt_zL_out", ASL_Sufkind_var, z_L_sol_);
      suf_rput("ipopt_zU_out", ASL_Sufkind_var, z_U_sol_);
   }

   // Write the .sol file
   write_solution_file(message);
}

bool AmplTNLP::internal_objval(
   const Number* x,
   Number&       obj_val
)
{
   DBG_START_METH("AmplTNLP::internal_objval",
                  dbg_verbosity);
   ASL_pfgh* asl = asl_;
   DBG_ASSERT(asl);
   objval_called_with_current_x_ = false; // in case the call below fails

   if( n_obj == 0 )
   {
      obj_val = 0;
      objval_called_with_current_x_ = true;
      return true;
   }
   else
   {
      Number retval = objval(obj_no, const_cast<Number*>(x), (fint* )nerror_);
      if( nerror_ok(nerror_) )
      {
         obj_val = obj_sign_ * retval;
         objval_called_with_current_x_ = true;
         return true;
      }
   }

   return false;
}

bool AmplTNLP::internal_conval(
   const Number* x,
   Index         m,
   Number*       g
)
{
   DBG_START_METH("AmplTNLP::internal_conval",
                  dbg_verbosity);
   ASL_pfgh* asl = asl_;
   DBG_ASSERT(asl);
   DBG_ASSERT(m == n_con);
   conval_called_with_current_x_ = false; // in case the call below fails

   bool allocated = false;
   if( !g )
   {
      g = new Number[m];
      allocated = true;
   }
   conval(const_cast<Number*>(x), g, (fint* )nerror_);

   if( allocated )
   {
      delete[] g;
   }

   if( nerror_ok(nerror_) )
   {
      conval_called_with_current_x_ = true;
      return true;
   }
   return false;
}

bool AmplTNLP::apply_new_x(
   bool          new_x,
   Index         /*n*/,
   const Number* x
)
{
   DBG_START_METH("AmplTNLP::apply_new_x",
                  dbg_verbosity);

   ASL_pfgh* asl = asl_;
   DBG_ASSERT(asl);

   if( new_x )
   {
      if( !hesset_called_ )
      {
         call_hesset();
      }

      DBG_PRINT((1, "Set new x.\n"));
      // update the flags so these methods are called
      // before evaluating the hessian
      conval_called_with_current_x_ = false;
      objval_called_with_current_x_ = false;

      // tell ampl that we have a new x
      xknowne(const_cast<Number*>(x), (fint* )nerror_);
      return nerror_ok(nerror_);
   }

   return true;
}

void AmplTNLP::write_solution_file(
   const std::string& message
) const
{
   ASL_pfgh* asl = asl_;
   DBG_ASSERT(asl);
   DBG_ASSERT(x_sol_ && lambda_sol_);

   // We need to copy the message into a non-const char array to make
   // it work with the AMPL C function.
   char* cmessage = new char[message.length() + 1];
   strcpy(cmessage, message.c_str());

   write_sol(cmessage, x_sol_, lambda_sol_, (Option_Info* )Oinfo_ptr_);

   delete[] cmessage;
}

void AmplTNLP::get_discrete_info(
   Index& nlvb_,
   Index& nlvbi_,
   Index& nlvc_,
   Index& nlvci_,
   Index& nlvo_,
   Index& nlvoi_,
   Index& nbv_,
   Index& niv_
) const
{
   ASL_pfgh* asl = asl_;
   DBG_ASSERT(asl);

   nlvb_ = nlvb;
   nlvbi_ = nlvbi;
   nlvc_ = nlvc;
   nlvci_ = nlvci;
   nlvo_ = nlvo;
   nlvoi_ = nlvoi;
   nbv_ = nbv;
   niv_ = niv;
}

bool AmplTNLP::get_scaling_parameters(
   Number& obj_scaling,
   bool&   use_x_scaling,
   Index   n,
   Number* x_scaling,
   bool&   use_g_scaling,
   Index   m,
   Number* g_scaling
)
{
   DBG_ASSERT(IsValid(suffix_handler_));
   const Number* obj = suffix_handler_->GetNumberSuffixValues("scaling_factor", AmplSuffixHandler::Objective_Source);
   obj_scaling = (obj) ? obj[0] : 1.0;

   const Number* x = suffix_handler_->GetNumberSuffixValues("scaling_factor", AmplSuffixHandler::Variable_Source);
   if( x )
   {
      use_x_scaling = true;
      for( Index i = 0; i < n; i++ )
      {
         if( x[i] > 0.0 )
         {
            x_scaling[i] = x[i];
         }
         else
         {
            x_scaling[i] = 1.0;
         }
      }
   }
   else
   {
      use_x_scaling = false;
   }

   const Number* g = suffix_handler_->GetNumberSuffixValues("scaling_factor", AmplSuffixHandler::Constraint_Source);
   if( g )
   {
      use_g_scaling = true;
      for( Index i = 0; i < m; i++ )
      {
         if( g[i] > 0 )
         {
            g_scaling[i] = g[i];
         }
         else
         {
            g_scaling[i] = 1.0;
         }
      }
   }
   else
   {
      use_g_scaling = false;
   }

   return true;
}

Index AmplTNLP::get_number_of_nonlinear_variables()
{
   ASL_pfgh* asl = asl_;
   DBG_ASSERT(asl);
   return Max(nlvo, nlvc);
}

bool AmplTNLP::get_list_of_nonlinear_variables(
   Index  num_nonlin_vars,
   Index* pos_nonlin_vars
)
{
   DBG_DO(ASL_pfgh* asl = asl_);
   DBG_ASSERT(asl);
   DBG_ASSERT(num_nonlin_vars == Max(nlvo, nlvc));

   // The first variables are the nonlinear ones (using Fortran
   // numbering)
   for( Index i = 0; i < num_nonlin_vars; i++ )
   {
      pos_nonlin_vars[i] = i + 1;
   }
   return true;
}

extern "C"
{
   static char* get_num_opt(
      Option_Info* oi,
      keyword*     kw,
      char*        value
   )
   {
      AmplOptionsList::PrivatInfo* pinfo = (AmplOptionsList::PrivatInfo*) kw->info;

      real real_val;
      // cppcheck-suppress autoVariables
      // cppcheck-suppress unmatchedSuppression
      kw->info = &real_val;
      char* retval = D_val(oi, kw, value);
      kw->info = (void*) pinfo;

      if( !pinfo->Options()->SetNumericValue(pinfo->IpoptName().c_str(), real_val) )
      {
         pinfo->Jnlst()->Printf(J_ERROR, J_MAIN, "\nInvalid value \"%s\" for option %s.\n", value, kw->name);
         THROW_EXCEPTION(OPTION_INVALID, "Invalid numeric option");
      }

      return retval;
   }

   static char* get_int_opt(
      Option_Info* oi,
      keyword*     kw,
      char*        value
   )
   {
      AmplOptionsList::PrivatInfo* pinfo = (AmplOptionsList::PrivatInfo*) kw->info;

      int int_val;
      // cppcheck-suppress autoVariables
      // cppcheck-suppress unmatchedSuppression
      kw->info = &int_val;
      char* retval = I_val(oi, kw, value);
      kw->info = (void*) pinfo;

      if( !pinfo->Options()->SetIntegerValue(pinfo->IpoptName().c_str(), int_val) )
      {
         pinfo->Jnlst()->Printf(J_ERROR, J_MAIN, "\nInvalid value \"%s\" for option %s.\n", value, kw->name);
         THROW_EXCEPTION(OPTION_INVALID, "Invalid integer option");
      }

      return retval;
   }

   static char* get_str_opt(
      Option_Info* oi,
      keyword*     kw,
      char*        value
   )
   {
      AmplOptionsList::PrivatInfo* pinfo = (AmplOptionsList::PrivatInfo*) kw->info;

      char* str_val;
      // cppcheck-suppress autoVariables
      // cppcheck-suppress unmatchedSuppression
      kw->info = &str_val;
      char* retval = C_val(oi, kw, value);
      kw->info = (void*) pinfo;

      if( !pinfo->Options()->SetStringValue(pinfo->IpoptName().c_str(), str_val) )
      {
         pinfo->Jnlst()->Printf(J_ERROR, J_MAIN, "\nInvalid value \"%s\" for option %s.\n", value, kw->name);
         THROW_EXCEPTION(OPTION_INVALID, "Invalid string option");
      }

      return retval;
   }

   static char* get_haltonerror_opt(
      Option_Info* oi,
      keyword*     kw,
      char*        value
   )
   {
      AmplOptionsList::PrivatInfo* pinfo = (AmplOptionsList::PrivatInfo*) kw->info;

      char* str_val;
      // cppcheck-suppress autoVariables
      // cppcheck-suppress unmatchedSuppression
      kw->info = &str_val;
      char* retval = C_val(oi, kw, value);
      kw->info = (void*) pinfo;

      fint** nerror = (fint**) pinfo->NError();

      // cppcheck-suppress uninitvar
      if( strcmp(str_val, "yes") == 0 )
      {
         delete *nerror;
         *nerror = NULL;
      }
      // cppcheck-suppress uninitvar
      else if( strcmp(str_val, "no") == 0 )
      {
         delete *nerror;
         *nerror = new fint;
         ** nerror = 0;
      }
      else
      {
         pinfo->Jnlst()->Printf(J_ERROR, J_MAIN, "\nInvalid value \"%s\" for option %s.\n", value, kw->name);
         THROW_EXCEPTION(OPTION_INVALID, "Invalid option");
      }

      return retval;
   }
}

AmplOptionsList::AmplOption::AmplOption(
   const std::string& ipopt_option_name,
   AmplOptionType     type,
   const std::string& description
)
   : ipopt_option_name_(ipopt_option_name),
     type_(type)
{
   description_ = new char[description.size() + 1];
   strcpy(description_, description.c_str());
}

AmplOptionsList::~AmplOptionsList()
{
   if( keywds_ )
   {
      DBG_ASSERT(nkeywds_ > 0);
      keyword* keywords = (keyword*) keywds_;
      for( Index i = 0; i < nkeywds_; i++ )
      {
         PrivatInfo* pinfo = static_cast<PrivatInfo*>(keywords[i].info);
         delete pinfo;
         delete[] keywords[i].name;
      }
      delete[] keywords;
   }
}

void* AmplOptionsList::Keywords(
   const SmartPtr<OptionsList>& options,
   SmartPtr<const Journalist>   jnlst,
   void**                       nerror
)
{
   if( keywds_ )
   {
      DBG_ASSERT(nkeywds_ > 0);
      keyword* keywords = (keyword*) keywds_;
      for( Index i = 0; i < nkeywds_; i++ )
      {
         PrivatInfo* pinfo = static_cast<PrivatInfo*>(keywords[i].info);
         delete pinfo;
         delete[] keywords[i].name;
      }
      delete[] keywords;
      nkeywds_ = 0;
   }

   /* PrintLatex(jnlst); */
   /* PrintDoxygen(jnlst); */

   Index n_options = NumberOfAmplOptions();
   keyword* keywords = new keyword[n_options];

   Index ioption = 0;
   for( std::map<std::string, SmartPtr<const AmplOption> >::iterator iter = ampl_options_map_.begin();
        iter != ampl_options_map_.end(); ++iter )
   {
      keywords[ioption].name = new char[iter->first.size() + 1];
      strcpy(keywords[ioption].name, iter->first.c_str());
      keywords[ioption].desc = iter->second->Description();
      switch( iter->second->Type() )
      {
         case String_Option:
         {
            PrivatInfo* pinfo = new PrivatInfo(iter->second->IpoptOptionName(), options, jnlst);
            keywords[ioption].info = (void*) pinfo;
            keywords[ioption].kf = get_str_opt;
         }
         break;
         case Number_Option:
         {
            PrivatInfo* pinfo = new PrivatInfo(iter->second->IpoptOptionName(), options, jnlst);
            keywords[ioption].info = (void*) pinfo;
            keywords[ioption].kf = get_num_opt;
         }
         break;
         case Integer_Option:
         {
            PrivatInfo* pinfo = new PrivatInfo(iter->second->IpoptOptionName(), options, jnlst);
            keywords[ioption].info = (void*) pinfo;
            keywords[ioption].kf = get_int_opt;
         }
         break;
         case WS_Option:
            keywords[ioption].info = NULL;
            keywords[ioption].kf = WS_val;
            break;
         case HaltOnError_Option:
            PrivatInfo* pinfo = new PrivatInfo(iter->second->IpoptOptionName(), options, jnlst, nerror);
            keywords[ioption].info = (void*) pinfo;
            keywords[ioption].kf = get_haltonerror_opt;
            break;
      }
      ioption++;
   }

   DBG_ASSERT(ioption == n_options);
   nkeywds_ = n_options;
   keywds_ = (void*) keywords;
   return keywds_;
}

void AmplOptionsList::MakeValidLatexString(
   std::string  source,
   std::string& dest
) const
{
   for( std::string::iterator c = source.begin(); c != source.end(); ++c )
   {
      if( *c == '_' )
      {
         dest.append("\\_");
      }
      else if( *c == '^' )
      {
         dest.append("\\^");
      }
      else if( *c == '>' || *c == '<' )
      {
         ;
      }
      else if( *c == '\n' )
      {
         dest += ", ";
      }
      else
      {
         dest += *c;
      }
   }
}

void AmplOptionsList::PrintLatex(
   SmartPtr<const Journalist> jnlst
)
{
   jnlst->Printf(J_SUMMARY, J_DOCUMENTATION, "\\begin{description}\n");
   for( std::map<std::string, SmartPtr<const AmplOption> >::iterator iter = ampl_options_map_.begin();
        iter != ampl_options_map_.end(); ++iter )
   {
      std::string amplname;
      std::string ipoptname;
      std::string descr;

      MakeValidLatexString(iter->first.c_str(), amplname);
      MakeValidLatexString(iter->second->IpoptOptionName(), ipoptname);
      MakeValidLatexString(iter->second->Description(), descr);

      if( ipoptname.length() > 0 )
      {
         jnlst->Printf(J_SUMMARY, J_DOCUMENTATION, "\\item[{\\htmlref{%s}{opt:%s}}]", amplname.c_str(),
                       iter->second->IpoptOptionName().c_str());
         if( amplname != ipoptname )
            jnlst->Printf(J_SUMMARY, J_DOCUMENTATION, " (Ipopt name: \\htmlref{%s}{opt:%s})", ipoptname.c_str(),
                          iter->second->IpoptOptionName().c_str());
      }
      else
      {
         jnlst->Printf(J_SUMMARY, J_DOCUMENTATION, "\\item[%s]", amplname.c_str());
      }
      jnlst->Printf(J_SUMMARY, J_DOCUMENTATION, " %s\n", descr.c_str());
   }
   jnlst->Printf(J_SUMMARY, J_DOCUMENTATION, "\\end{description}\n");
}

void AmplOptionsList::PrintDoxygen(
   SmartPtr<const Journalist> jnlst
)
{
   jnlst->Printf(J_SUMMARY, J_DOCUMENTATION, "| Option | Description |\n");
   jnlst->Printf(J_SUMMARY, J_DOCUMENTATION, "|:-------|:------------|\n");
   for( std::map<std::string, SmartPtr<const AmplOption> >::iterator iter = ampl_options_map_.begin();
        iter != ampl_options_map_.end(); ++iter )
   {
      if( iter->second->IpoptOptionName().length() > 0 )
      {
         jnlst->Printf(J_SUMMARY, J_DOCUMENTATION, "| \\ref OPT_%s \"%s\"", iter->second->IpoptOptionName().c_str(), iter->first.c_str());

         if( iter->first != iter->second->IpoptOptionName() )
         {
            jnlst->Printf(J_SUMMARY, J_DOCUMENTATION, " (Ipopt name: %s)", iter->second->IpoptOptionName().c_str());
         }
      }
      else
      {
         jnlst->Printf(J_SUMMARY, J_DOCUMENTATION, "| %s", iter->first.c_str());
      }

      std::string descr = iter->second->Description();
      for( std::string::iterator it = descr.begin(); it != descr.end(); ++it )
         if( *it == '\n' )
         {
            *it = ';';
         }

      jnlst->Printf(J_SUMMARY, J_DOCUMENTATION, " | %s |\n", descr.c_str());
   }
}

static const char sname_default[] = "ipopt";
static const char bsname_default[] = "Ipopt " IPOPT_VERSION;
static const char opname_default[] = "ipopt_options";

char*
AmplTNLP::get_options(
   const SmartPtr<RegisteredOptions> regoptions,
   const SmartPtr<OptionsList>& options,
   SmartPtr<AmplOptionsList>&   ampl_options_list,
   const char*                  ampl_option_string,
   const char*                  ampl_invokation_string,
   const char*                  ampl_banner_string,
   const char* const*           argv
)
{
   ASL_pfgh* asl = asl_;

   if( !IsValid(ampl_options_list) )
   {
      ampl_options_list = new AmplOptionsList();
   }

   if( IsValid(regoptions) )
   {
      for( RegisteredOptions::RegOptionsList::const_iterator it_opt(regoptions->RegisteredOptionsList().begin()); it_opt != regoptions->RegisteredOptionsList().end(); ++it_opt )
      {
         AmplOptionsList::AmplOptionType ampltype = AmplOptionsList::Number_Option;

         switch( it_opt->second->Type() )
         {
            case Ipopt::OT_Number:
               ampltype = AmplOptionsList::Number_Option;
               break;
            case Ipopt::OT_Integer:
               ampltype = AmplOptionsList::Integer_Option;
               break;
            case Ipopt::OT_String:
               ampltype = AmplOptionsList::String_Option;
               break;
            case Ipopt::OT_Unknown:
               continue;
         }
         ampl_options_list->AddAmplOption(it_opt->first, it_opt->first, ampltype, it_opt->second->ShortDescription());
      }
   }
   else
   {
      // old deprecated use of AmplTNLP: manually list some options
      // Output
      ampl_options_list->AddAmplOption("print_level", "print_level", AmplOptionsList::Integer_Option, "Verbosity level");
      ampl_options_list->AddAmplOption("print_user_options", "print_user_options", AmplOptionsList::String_Option,
                                       "Toggle printing of user options");
      ampl_options_list->AddAmplOption("print_options_documentation", "print_options_documentation",
                                       AmplOptionsList::String_Option, "Print all available options (for ipopt.opt)");
      ampl_options_list->AddAmplOption("output_file", "output_file", AmplOptionsList::String_Option,
                                       "File name of an output file (leave unset for no file output)");
      ampl_options_list->AddAmplOption("file_print_level", "file_print_level", AmplOptionsList::Integer_Option,
                                       "Verbosity level for output file");
      ampl_options_list->AddAmplOption("option_file_name", "option_file_name", AmplOptionsList::String_Option,
                                       "File name of options file (default: ipopt.opt)");

      // Termination
      ampl_options_list->AddAmplOption("tol", "tol", AmplOptionsList::Number_Option,
                                       "Desired convergence tolerance (relative)");
      ampl_options_list->AddAmplOption("max_iter", "max_iter", AmplOptionsList::Integer_Option,
                                       "Maximum number of iterations");
      ampl_options_list->AddAmplOption("max_wall_time", "max_wall_time", AmplOptionsList::Number_Option, "Wallclock time limit");
      ampl_options_list->AddAmplOption("max_cpu_time", "max_cpu_time", AmplOptionsList::Number_Option, "CPU time limit");
      ampl_options_list->AddAmplOption("compl_inf_tol", "compl_inf_tol", AmplOptionsList::Number_Option,
                                       "Acceptance threshold for the complementarity conditions");
      ampl_options_list->AddAmplOption("dual_inf_tol", "dual_inf_tol", AmplOptionsList::Number_Option,
                                       "Desired threshold for the dual infeasibility");
      ampl_options_list->AddAmplOption("constr_viol_tol", "constr_viol_tol", AmplOptionsList::Number_Option,
                                       "Desired threshold for the constraint violation");
      ampl_options_list->AddAmplOption("acceptable_tol", "acceptable_tol", AmplOptionsList::Number_Option,
                                       "Acceptable convergence tolerance (relative)");
      ampl_options_list->AddAmplOption("acceptable_compl_inf_tol", "acceptable_compl_inf_tol",
                                       AmplOptionsList::Number_Option, "Acceptance threshold for the complementarity conditions");
      ampl_options_list->AddAmplOption("acceptable_dual_inf_tol", "acceptable_dual_inf_tol",
                                       AmplOptionsList::Number_Option, "Acceptance threshold for the dual infeasibility");
      ampl_options_list->AddAmplOption("acceptable_constr_viol_tol", "acceptable_constr_viol_tol",
                                       AmplOptionsList::Number_Option, "Acceptance threshold for the constraint violation");

      ampl_options_list->AddAmplOption("diverging_iterates_tol", "diverging_iterates_tol", AmplOptionsList::Number_Option,
                                       "Threshold for maximal value of primal iterates");

      // NLP scaling
      ampl_options_list->AddAmplOption("obj_scaling_factor", "obj_scaling_factor", AmplOptionsList::Number_Option,
                                       "Scaling factor for the objective function");
      ampl_options_list->AddAmplOption("nlp_scaling_method", "nlp_scaling_method", AmplOptionsList::String_Option,
                                       "Select the technique used for scaling the NLP");
      ampl_options_list->AddAmplOption("nlp_scaling_max_gradient", "nlp_scaling_max_gradient",
                                       AmplOptionsList::Number_Option, "Maximum gradient after scaling");

      // NLP corrections
      ampl_options_list->AddAmplOption("bound_relax_factor", "bound_relax_factor", AmplOptionsList::Number_Option,
                                       "Factor for initial relaxation of the bounds");
      ampl_options_list->AddAmplOption("honor_original_bounds", "honor_original_bounds", AmplOptionsList::String_Option,
                                       "If no, solution might slightly violate bounds");

      // Barrier parameter
      ampl_options_list->AddAmplOption("mu_strategy", "mu_strategy", AmplOptionsList::String_Option,
                                       "Update strategy for barrier parameter");
      ampl_options_list->AddAmplOption("mu_oracle", "mu_oracle", AmplOptionsList::String_Option,
                                       "Oracle for a new barrier parameter in the adaptive strategy");
      // Barrier parameter
      ampl_options_list->AddAmplOption("mu_max", "mu_max", AmplOptionsList::Number_Option,
                                       "Maximal value for barrier parameter for adaptive strategy");
      ampl_options_list->AddAmplOption("mu_init", "mu_init", AmplOptionsList::Number_Option,
                                       "Initial value for the barrier parameter");

      // Initialization
      ampl_options_list->AddAmplOption("bound_frac", "bound_frac", AmplOptionsList::Number_Option,
                                       "Desired minimal relative distance of initial point to bound");
      ampl_options_list->AddAmplOption("bound_push", "bound_push", AmplOptionsList::Number_Option,
                                       "Desired minimal absolute distance of initial point to bound");
      ampl_options_list->AddAmplOption("slack_bound_frac", "slack_bound_frac", AmplOptionsList::Number_Option,
                                       "Desired minimal relative distance of initial slack to bound");
      ampl_options_list->AddAmplOption("slack_bound_push", "slack_bound_push", AmplOptionsList::Number_Option,
                                       "Desired minimal absolute distance of initial slack to bound");
      ampl_options_list->AddAmplOption("bound_mult_init_val", "bound_mult_init_val", AmplOptionsList::Number_Option,
                                       "Initial value for the bound multipliers");
      ampl_options_list->AddAmplOption("constr_mult_init_max", "constr_mult_init_max", AmplOptionsList::Number_Option,
                                       "Maximal allowed least-square guess of constraint multipliers");

      // Multiplier updates
      ampl_options_list->AddAmplOption("alpha_for_y", "alpha_for_y", AmplOptionsList::String_Option,
                                       "Step size for constraint multipliers");

      // Line search
      ampl_options_list->AddAmplOption("max_soc", "max_soc", AmplOptionsList::Integer_Option,
                                       "Maximal number of second order correction trial steps");
      ampl_options_list->AddAmplOption("watchdog_shortened_iter_trigger", "watchdog_shortened_iter_trigger",
                                       AmplOptionsList::Integer_Option, "Trigger counter for watchdog procedure");

      // Restoration phase
      ampl_options_list->AddAmplOption("expect_infeasible_problem", "expect_infeasible_problem",
                                       AmplOptionsList::String_Option, "Enable heuristics to quickly detect an infeasible problem");
      ampl_options_list->AddAmplOption("required_infeasibility_reduction", "required_infeasibility_reduction",
                                       AmplOptionsList::Number_Option, "Required infeasibility reduction in restoration phase");

      // Added for Warm-Start
      ampl_options_list->AddAmplOption("warm_start_init_point", "warm_start_init_point", AmplOptionsList::String_Option,
                                       "Enables to specify bound multiplier values");
      ampl_options_list->AddAmplOption("warm_start_bound_push", "warm_start_bound_push", AmplOptionsList::Number_Option,
                                       "Enables to specify how much should variables should be pushed inside the feasible region");
      ampl_options_list->AddAmplOption("warm_start_mult_bound_push", "warm_start_mult_bound_push",
                                       AmplOptionsList::Number_Option,
                                       "Enables to specify how much should bound multipliers should be pushed inside the feasible region");

      // Quasi-Newton
      ampl_options_list->AddAmplOption("hessian_approximation", "hessian_approximation", AmplOptionsList::String_Option,
                                       "Can enable Quasi-Newton approximation of hessian");
      // Linear solver
      ampl_options_list->AddAmplOption("linear_solver", "linear_solver", AmplOptionsList::String_Option,
                                       "Linear solver to be used for step calculation");
      ampl_options_list->AddAmplOption("linear_system_scaling", "linear_system_scaling", AmplOptionsList::String_Option,
                                       "Method for scaling the linear systems");
      ampl_options_list->AddAmplOption("linear_scaling_on_demand", "linear_scaling_on_demand",
                                       AmplOptionsList::String_Option, "Enables heuristic for scaling only when seems required");
      ampl_options_list->AddAmplOption("max_refinement_steps", "max_refinement_steps", AmplOptionsList::Integer_Option,
                                       "Maximal number of iterative refinement steps per linear system solve");
      ampl_options_list->AddAmplOption("min_refinement_steps", "min_refinement_steps", AmplOptionsList::Integer_Option,
                                       "Minimum number of iterative refinement steps per linear system solve");

      // Quasi-Newton
      ampl_options_list->AddAmplOption("hessian_approximation", "hessian_approximation", AmplOptionsList::String_Option,
                                       "Can enable Quasi-Newton approximation of hessian");
   }

   // Synonyms for AMPL interface only
   ampl_options_list->AddAmplOption("outlev", "print_level", AmplOptionsList::Integer_Option, "Verbosity level");
   ampl_options_list->AddAmplOption("maxit", "max_iter", AmplOptionsList::Integer_Option,
                                    "Maximum number of iterations");

   // AMPL's wantsol option
   // description was originally taken from WS_desc_ASL+5, but that didn't make it through DLL boundaries
   ampl_options_list->AddAmplOption("wantsol", "", AmplOptionsList::WS_Option,
                                    "solution report without -AMPL: sum of 1 (write .sol file), 2 (print primal variable values), 4 (print dual variable values), 8 (do not print solution message)");

   // special AMPL option to exit when there is in error in the
   // function evaluation
   ampl_options_list->AddAmplOption("halt_on_ampl_error", "", AmplOptionsList::HaltOnError_Option,
                                    "Exit with message on evaluation error");

   Index n_options = ampl_options_list->NumberOfAmplOptions();

   keyword* keywds = (keyword*) ampl_options_list->Keywords(options, jnlst_, (void**) &nerror_);

   const char* sname;
   const char* bsname;
   const char* opname;
   if( ampl_option_string )
   {
      opname = ampl_option_string;
   }
   else
   {
      opname = opname_default;
   }
   if( ampl_invokation_string )
   {
      sname = ampl_invokation_string;
   }
   else
   {
      sname = sname_default;
   }
   if( ampl_banner_string )
   {
      bsname = ampl_banner_string;
   }
   else
   {
      bsname = bsname_default;
   }

   DBG_ASSERT(!Oinfo_ptr_);
   Option_Info* Oinfo = new Option_Info;
   Oinfo->sname = new char[strlen(sname) + 1];
   strcpy(Oinfo->sname, sname);
   Oinfo->bsname = new char[strlen(bsname) + 1];
   strcpy(Oinfo->bsname, bsname);
   Oinfo->opname = new char[strlen(opname) + 1];
   strcpy(Oinfo->opname, opname);
   Oinfo->keywds = keywds;
   Oinfo->n_keywds = (int)n_options;
   // Set the default for the remaining entries
   Oinfo->flags = 0;
   Oinfo->version = NULL;
   Oinfo->usage = NULL;
   Oinfo->kwf = NULL;
   Oinfo->feq = NULL;
   Oinfo->options = NULL;
   Oinfo->n_options = 0;
   Oinfo->driver_date = 0;
   Oinfo->wantsol = 0;
   Oinfo->nS = 0;
   Oinfo->S = NULL;
   Oinfo->uinfo = NULL;
   Oinfo->asl = NULL;
   Oinfo->eqsign = NULL;
   Oinfo->n_badopts = 0;
   Oinfo->option_echo = 0;
   Oinfo->nnl = 0;

   Oinfo_ptr_ = Oinfo;

   char* stub = getstops(const_cast<char**>(argv), Oinfo);

   return stub;
}

bool AmplTNLP::nerror_ok(
   void* nerror
)
{
   DBG_START_METH("AmplTNLP::nerror_ok",
                  dbg_verbosity);

   if( nerror == NULL || *((fint*) nerror) == 0 )
   {
      return true;
   }
   jnlst_->Printf(J_ERROR, J_MAIN,
                  "Error in an AMPL evaluation. Run with \"halt_on_ampl_error yes\" to see details.\n");
   DBG_PRINT((1, "nerror = %d\n", *((fint*)nerror)));
   return false;
}

AmplSuffixHandler::AmplSuffixHandler()
   : asl_(NULL),
     suftab_(NULL)
{
}

AmplSuffixHandler::~AmplSuffixHandler()
{
   if( suftab_ )
   {
      Index n = (Index) suffix_ids_.size();
      for( Index i = 0; i < n; i++ )
      {
         free(suftab_[i].name);
         suftab_[i].name = NULL;
      }
   }
   delete[] suftab_;
   suftab_ = NULL;
}

void AmplSuffixHandler::PrepareAmplForSuffixes(
   ASL_pfgh* asl
)
{
   DBG_ASSERT(asl);
   asl_ = asl;

   Index n = (Index) suffix_ids_.size();
   suftab_ = new SufDecl[n];
   for( Index i = 0; i < n; i++ )
   {
      suftab_[i].name = strdup(suffix_ids_[i].c_str());
      suftab_[i].table = 0;

      if( suffix_sources_[i] == Variable_Source )
      {
         suftab_[i].kind = ASL_Sufkind_var;
      }
      else if( suffix_sources_[i] == Constraint_Source )
      {
         suftab_[i].kind = ASL_Sufkind_con;
      }
      else if( suffix_sources_[i] == Objective_Source )
      {
         suftab_[i].kind = ASL_Sufkind_obj;
      }
      else if( suffix_sources_[i] == Problem_Source )
      {
         suftab_[i].kind = ASL_Sufkind_prob;
      }
      else
      {
         DBG_ASSERT(false && "Unknown suffix source in PrepareAmplForSuffixes");
      }

      if( suffix_types_[i] == Number_Type )
      {
         suftab_[i].kind = suftab_[i].kind | ASL_Sufkind_real;
      }

      suftab_[i].nextra = 0;
   }

   suf_declare(suftab_, n);
}

const int*
AmplSuffixHandler::GetIntegerSuffixValues(
   const std::string& suffix_string,
   Suffix_Source      source
) const
{
   ASL_pfgh* asl = asl_;
   DBG_ASSERT(asl);

   int kind;
   if( source == Variable_Source )
   {
      kind = ASL_Sufkind_var;
   }
   else if( source == Constraint_Source )
   {
      kind = ASL_Sufkind_con;
   }
   else if( source == Objective_Source )
   {
      kind = ASL_Sufkind_obj;
   }
   else if( source == Problem_Source )
   {
      kind = ASL_Sufkind_prob;
   }
   else
   {
      THROW_EXCEPTION(IpoptException, "Unknown suffix source in GetIntegerSuffixValues");
   }
   SufDesc* dp = suf_get(suffix_string.c_str(), kind);
   return dp->u.i;
}

std::vector<int> AmplSuffixHandler::GetIntegerSuffixValues(
   Index              n,
   const std::string& suffix_string,
   Suffix_Source      source
) const
{
   std::vector<int> ret;
   const int* ptr = GetIntegerSuffixValues(suffix_string, source);
   if( ptr )
   {
      ret.reserve(n);
      for( Index i = 0; i < n; i++ )
      {
         ret.push_back(ptr[i]);
      }
   }
   return ret;
}

const Number* AmplSuffixHandler::GetNumberSuffixValues(
   const std::string& suffix_string,
   Suffix_Source      source
) const
{
   ASL_pfgh* asl = asl_;
   DBG_ASSERT(asl);

   int kind;
   if( source == Variable_Source )
   {
      kind = ASL_Sufkind_var;
   }
   else if( source == Constraint_Source )
   {
      kind = ASL_Sufkind_con;
   }
   else if( source == Objective_Source )
   {
      kind = ASL_Sufkind_obj;
   }
   else if( source == Problem_Source )
   {
      kind = ASL_Sufkind_prob;
   }
   else
   {
      THROW_EXCEPTION(IpoptException, "Unknown suffix source in GetNumberSuffixValues");
   }
   SufDesc* dp = suf_get(suffix_string.c_str(), kind);
   return dp->u.r;
}

std::vector<Number> AmplSuffixHandler::GetNumberSuffixValues(
   Index              n,
   const std::string& suffix_string,
   Suffix_Source      source
) const
{
   std::vector<Number> ret;
   const Number* ptr = GetNumberSuffixValues(suffix_string, source);
   if( ptr )
   {
      ret.reserve(n);
      for( Index i = 0; i < n; i++ )
      {
         ret.push_back(ptr[i]);
      }
   }
   return ret;
}

} // namespace Ipopt