-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmb2r.cpp
More file actions
2050 lines (1724 loc) · 73.6 KB
/
Copy pathadmb2r.cpp
File metadata and controls
2050 lines (1724 loc) · 73.6 KB
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
/********************************************************************************
*
* ADMB2R
*
* Routines for writing data from AD Model Builder to a file read by R with "dget"
*
* Jennifer Martin, Mike Prager and Andi Stephens
* NOAA, National Marine Fisheries Service
*
* jlmartin@usgs.gov
* mike.prager@noaa.gov
*
* Original version: February 2006
*
* Many of these routines are implemented with templates and overloaded functions.
*
* In order to make them compiler-independent, overloaded functions are defined for
* all types anticipated for use. These functions are gathered together under a
* single comment block describing them as a group.
*
* Overloaded functions are often paired with a similarly named "do_" function or
* template. The overloaded function passes various combinations of options to the
* "do_" function for processing.
*
*********************************************************************************/
/* CHANGELOG
* Version 0.50 Andi May 2006 Revised for compatibility
* Version 0.85 MHP 8 Aug 2006 Changed names of ...info_vector to ...info_list
to agree with actual R structure. Changed
default of argument "writestamp" to true (as
documented). Moved documentation from Word to
LaTeX, as Word file has deteriorated.
* Version 0.99 Andi 11 Aug 2006 Commented out non-integer functs for
writing row/col names.
Added test_missing function.
* Version 1.00 MHP 16 Aug 2006 Added factor of 2 to missing test, changed
declaration of dum_matrix to four parameters for
compatibility with older versions of ADMB.
* Version 1.00 MHP 30 Aug 2006 Corrected missing-value test. Inserted some
vector routines that had been removed in error.
* Version 1.00 JLM 01 Sep 2006 Switch the default behavior of writing out missing
values to false. Edited do_wrt_r_namevector to
independently assign default vector min/max.
Add additional details to some comment sections
for clarity.
* Version 1.01 JLM 09 Mar 2007 Fixed bug that didn't write out default row.names
for a dataframe (close_r_df). Added function to
write out a vector using one statement
(wrt_r_complete_vector). Fixed a bug that didn't
write error messages in many cases. Removed
periods at end of first two comment lines for
clarity (do_open_r_file).
* Version 1.1 JLM 12 Oct 2007 Expanded compatibility on multiple compilers.
* Version 1.11 MHP 19 Dec 2008 No changes to ADMB2R - renamed some files for
Example 1 to avoid minor ADMB 9.x bug.
* Version 1.12 MHP 03 Sep 2009 Incorporated declarations fixes by J. Sibert.
This removed many compatibility errors.
* Version 1.13 MHP 14 Sep 2009 Changed na_vector declar from int* to bool*.
* Version 1.14 MHP 15 Sep 2009 Added "endl" after 25 values to limit line
lengths in wrt_r_complete_vector, wrt_r_matrix,
and wrt_r_df_col.
* Version 1.15 JLM 13 Oct 2009 Added a new function "print_wrap" to wrap row
and column names and .Names vectors after the
25th comma-delimited element. Functions that
needed mofication: close_r_matrix, close_r_df,
close_r_vector, do_wrt_r_complete_vector,
close_r_info_list, close_r_list, close_r_file,
do_df_col_wrt_num. Modified the checking for
no remainders method in wrt_r_complete_vector,
wrt_r_matrix, and wrt_r_df_col to a method that
increments a counter for better consistency.
*********************************************************************************/
#include <ctime> // needed for timestamp
#include <string> // string manipulation routines
#include <vector> // vectors -- no need to manage array allocation by hand
#include <iomanip> // needed to set precision
#include <iostream> // needed for converting between data types
#if (__GNUC__) && (__GNUC__ < 3)
// gcc 2.95 <strstream> header
#include <strstream>
typedef strstream my_sstream;
#else
// use <sstream> header
#include <sstream>
typedef std::stringstream my_sstream;
#endif
using namespace std;
// GLOBAL VARIABLES
const char* version = "1.15"; // Version number
int i; // For indices
// ** File I/O Variables
string outfile; // output file name
ofstream rfile; // ofstream for output file
ofstream errfile; // output stream for error message
string err_msg = "ADMB2R error messages: "; // error message
// ** General Housekeeping Variables
int level; // Current nesting level for object names
bool OKflag = true; // error flag
string mflag; // is open object a matrix or data frame
string vecflag; // is open vector a list or simple vector
vector<bool> ObjDoneFlag; // flag to track object completion
vector<string> prevObj; // ( names of previous object, used in keeping
// ( track of whether the object is complete
// ** Data Writing Variables
double missing = -99999.; // No data/missing data indicator
double epsilon = 1e-6; // A small number
bool writeNA = false; // Flag to turn on/off writing NA for missing data
bool naflag = false; // Flag to signal use of NA matrix or vector
imatrix dum_matrix; // Dummy variable in use of NA matrix
ivector dum_vector; // Dummy variable in use of NA vector
int dim1 = -1; // matrix dimensions or data frame min/max
int dim2 = -1; // matrix dimensions or data frame min/max
int digits = -1; // ( Digits of data precision; -1 will write data
// ( as it appears in ADMB; 0 writes integers
// ** R Names Variables
vector<string> Rnames; // vector of names to write when closing the R object
string colnames; // list of names to be used for R columns
string rownames; // list of names to be used for R rows
int rowflag = 0; // Flag to write matrix or data frame row names
int colflag = 0; // Flag to write matrix or data frame column names
const char* quote = "\""; // Double-quote character (")
const char* cquote = ",\""; // comma plus double quote (,")
//=====================================================================================
// convert
//
// Utility routine to convert one type to another, e.g., double to string
//
// Use:
// out_type - type desired
// in_value - type to convert from
//=====================================================================================
template <class out_type, class in_value>
out_type convert(const in_value & t) {
my_sstream stream;
stream << t; // insert value to stream
out_type result; // store conversion's result here
stream >> result; // write value to result
return result;
} // end convert
//=====================================================================================
// test_missing
//
// Utility routine to test for the missing value.
// Returns true if the input value is the missing value.
//
//=====================================================================================
bool test_missing(double num) {
return (fabs(num - missing) < epsilon);
}
//=====================================================================================
// write_errmsg
//
// Utility routine to write error message string (global) to screen and to logfile.
//
// No arguments.
//=====================================================================================
void write_errmsg() {
// write error message to screen and file
if ( err_msg != "ADMB2R error messages: " ) {
cout << "**** ADMB2R Error: Please check file admb2r.log for error messages." << endl;
}
errfile.open ("admb2r.log");
errfile << err_msg << endl;
errfile.close();
} // end write_errmsg
//=====================================================================================
// print_wrap
//
// Function to limit line lengths when printing to the rfile. Limits lines to 25 comma-
// delimited elements.
//
// ARGUMENTS:
// s - the string to parse
// a - (optional) any text to append to the string before writing a new line, for
// example, any closing punctuation
//=====================================================================================
void print_wrap(string s, string a = "") {
string::size_type pos = s.find_first_of(",");
string::size_type istart = 0;
string temp;
int counter = 0;
// first, append any additional text (such as closing punctuation)
s = s + a;
if (pos < s.length() ) { // check to see if there are some comma-delimited tokens
while (pos != string::npos) {
counter = counter + 1;
if (counter == 25 ) { // when the 25th token is
temp = s.substr(istart, pos - istart + 1); // found, extract the substring
rfile << temp << endl; // and print
istart = pos + 1;
counter = 0;
}
pos = s.find_first_of(",", pos + 1); // find the next comma delimeter
}
// print the last batch of token, if there are any
if (istart < s.length() ) {
temp = s.substr(istart, s.length() - istart);
// only print if there are more than spaces
pos = temp.find_first_not_of(" ");
if (pos < s.length()) {
rfile << temp << endl;
}
}
} else {
// no comma-delimited tokens found; print entire string
rfile << s << endl;
}
} // end print_wrap
//=====================================================================================
// do_open_r_file
//
// Open the output file and initialize the R data object.
//
// Arguments are passed to do_open_r_file by the overloaded open_r_file function.
//
// ARGUMENTS
// fname - name of output file
// numdigits - data precision
// digits = -1 (default) or digits = 0 writes data out with default precision
// of 6; digits > 0 will write ALL data out in scientific notation with the
// specified number of digits after the decimal place.
//=====================================================================================
void do_open_r_file(const char* fname, int numdigits) {
// initialize nesting level
level = 0;
// initialize dummy matrix
dum_matrix.allocate(1,1,1,1);
// initialize dummy vector
dum_vector.allocate(1,1);
// intialize object completion tracking variables
ObjDoneFlag.clear();
ObjDoneFlag.push_back(true);
prevObj.clear();
prevObj.push_back("");
// initialize list of all R objects
Rnames.clear();
Rnames.push_back("c(");
// initialize row/column names and vector of list objects
colnames.erase();
rownames.erase();
// Open the R output file
outfile = fname;
rfile.open (fname);
// check to make sure it opened OK
if ( ! rfile.is_open() ) {
err_msg = err_msg + "\n**** ADMB2R Error: Unable to open " + outfile;
OKflag = false;
write_errmsg();
return;
}
// write a brief file header
rfile <<"### This file written with ADMB2R version " << version << endl;
rfile <<"### Read into R or S with x=dget('";
rfile << fname << "')";
rfile << endl;
rfile << endl;
// begin overall R structure (list)
rfile << "structure(list(";
rfile << endl;
rfile << endl;
// set precision based on the digits value specified.
digits = numdigits;
if ( digits > 0 ) {
rfile << setiosflags (ios::scientific);
rfile.precision(digits);
}
} // End do_open_r_file
//=====================================================================================
// open_r_file
//
// Overloaded function to get the R file name, precision, and set the missing value
// indicator.
//
// Allows user to specify one of three combinations of open_r_file:
// open_r_file(fname)
// open_r_file(fname, numdigits)
// open_r_file(fname, numdigits, ismissing)
//
// ARGUMENTS:
// fname - name of output file.
// This argument is passed to do_open_rfile for further handling.
// numdigits - (optional) data precision
// This argument is passed to do_open_rfile for further handling.
// digits = -1 (default) or digits = 0 writes data out with default precision
// of 6; digits > 0 will write ALL data out in scientific notation with the
// specified number of digits after the decimal place.
// ismissing - (optional) indicates the value that is used to represent a missing datum.
// If ismissing is specified, data matching this value will be replaced by NA in
// the R file.
//======================================================================================
void open_r_file(const char* fname, int numdigits = -1) {
// no missing value supplied, so turn off flag to write NAs to file
writeNA = false;
// pass info to do_open_r_file for processing
do_open_r_file(fname, numdigits);
} // End open_r_file (numdigits)
//=====================================================================================
void open_r_file(const char* fname, int numdigits, double ismissing) {
// missing is value supplied, so turn on flag to write NAs to file
writeNA = true;
// asign missing value to global variable
missing = ismissing;
// pass info to do_open_r_file for processing
do_open_r_file(fname, numdigits);
} // End open_r_file (numdigits, ismissing)
//======================================================================================
// close_r_file
//
// Close R object and do housekeeping
//
// No arguments.
//======================================================================================
void close_r_file() {
if ( OKflag == false ) {
write_errmsg();
if ( rfile.is_open() ) rfile.close();
return; // exit if there was an earlier error
}
// check that there is at least one item in file
if ( Rnames[0] == "c(" ) {
if ( rfile.is_open() ) rfile.close();
err_msg = err_msg + "\n**** ADMB2R Error: No data written to " + outfile;
OKflag = false;
write_errmsg();
return;
}
// check level; if level not equal to zero, one of the list objects didn't close properly
if ( level != 0 ) {
if ( rfile.is_open() ) rfile.close();
err_msg = err_msg + "\n**** ADMB2R Error: Close list object with close_r_list().";
write_errmsg();
OKflag = false;
return;
}
// check that final object is complete
if ( ObjDoneFlag[0] = false ) {
if ( rfile.is_open() ) rfile.close();
err_msg = err_msg + "\n**** ADMB2R Error: " + prevObj[level] + " is not complete!";
OKflag = false;
write_errmsg();
return;
}
rfile << endl;
rfile << "### Calling close_r_file -- last call in program." << endl;
rfile << ")," << endl;
rfile << endl;
rfile << ".Names = ";
print_wrap(Rnames[0], "))");
rfile.close();
// clear global variables: Rnames, colnames, rownames, ListNames
Rnames.clear();
colnames.erase();
rownames.erase();
prevObj.clear();
prevObj.push_back("");
ObjDoneFlag.clear();
ObjDoneFlag.push_back(true);
// re-set nesting level
level = 0;
write_errmsg();
} // end close_r_file
//=====================================================================================
// wrt_r_comment
//
// Write a comment to the output file. Cannot be used before open_r_file.
//
// ARGUMENTS:
// text - text to write as comment
//=====================================================================================
void wrt_r_comment(const char* text) {
if ( ! rfile.is_open() ) { // exit if file hasn't been opened yet
OKflag = false;
err_msg = err_msg + "**** ADMB2R Error: No open file\n";
write_errmsg();
return;
}
// if something goes wrong
if ( rfile.bad() ) {
if ( rfile.is_open() ) rfile.close();
OKflag = false;
err_msg = err_msg + "**** ADMB2R Error: Unable to write to " + outfile + "\n";
write_errmsg();
return;
}
rfile << "### " << text << endl;
} // end wrt_r_comment
//=====================================================================================
// reg_Rnames
//
// Adds object names to Names list, checks that previous object is complete,
// and does other housekeeping chores
//
// Called by open_r_matrix, open_r_list, open_r_info_list, open_r_vector, and open_r_df.
//
// ARGUMENTS:
// name - name of object to write
// description - type of R object (used in error reporting if object is incomplete).
//======================================================================================
int reg_Rnames(const char* name, string description) {
// check for previous object completion
if ( OKflag == false ) return 0; // exit if there was an earlier error
if ( prevObj[level] != "" ) { // make sure there are previous objects to check
//previous object is incomplete
if ( ObjDoneFlag[level] == false ) {
if ( rfile.is_open() ) rfile.close();
err_msg = err_msg + "\n**** ADMB2R Error: " + prevObj[level] + " is still open";
OKflag = false;
write_errmsg();
return 0;
}
}
// add object name to list
// if item not first in list add comma separator
if ( Rnames[level] != "c(" ) {
Rnames[level] = Rnames[level] + ", ";
rfile << ", ";
}
Rnames[level] = Rnames[level] + quote + name + quote;
// intialize object completion variables
prevObj[level] = description + name;
ObjDoneFlag[level] = false;
if ( OKflag == true ) return 1;
else return 0;
} // end reg_Rnames
//======================================================================================
// add_colname
//
// Utility to add column name to list, with comma as necessary
//
// ARGUMENTS:
// name - string to output.
//======================================================================================
void add_colname(const char* name) {
if ( colnames != "c(" ) {
colnames = colnames + ", "; // Object is not first item; preceed with a comma
}
colnames = colnames + quote + name + quote; // Add name to list
} // end add_colname
//======================================================================================
// add_rowname
//
// Utility to add row name to list, with comma as necessary
//
// ARGUMENTS:
// name - string to output.
//======================================================================================
void add_rowname(const char* name) {
if ( rownames != "c(" ) {
rownames = rownames + ", "; // Object is not first item; preceed with a comma
}
rownames = rownames + quote + name + quote; // Add name to list
} // end add_rowname
//======================================================================================
// check_rownames
//
// In writing row or column names, determines whether the item to write is a row or a column.
// Performs bounds-checking.
//
// Called from do_wrt_r_namevector and do_wrt_r_numvector
//
// ARGUMENTS
// start - first value in the series, or index of the first element in the vector
// stop - last value in the series, or index of the last element in the vector
// inc - how much to increment the values in the series
//======================================================================================
template <class T>
string check_rownames (T start, T stop, T inc) {
string return_val = "error"; // return string indicating error, row or col
T nitems = ((stop - start)/inc) + 1; // number of items to write
T diff = dim2 - dim1 + 1; // number of values in matrix or data frame
int M_dim; // dimension of row or column
string cr_names; // variable to specify row or column names
// determine if object is matrix or data frame and whether item is row or column names
if ( mflag == "matrix" && rowflag == 2 && rownames == "" ) { // process rows first
cr_names = rownames; // item to write is row names for matrix
return_val = "row";
} else {
if ( mflag == "matrix" && colflag == 2 && colnames == "" ) {
cr_names = colnames; // item to write is column names for matrix
return_val = "col";
}
else {
if ( mflag == "data frame" ) {
cr_names = rownames; // item is row names for data frame
return_val = "row";
}
}
}
// validate number of items
if ( mflag == "matrix" ) { // this is a matrix object
if ( cr_names == rownames ) { // process rows first
M_dim = dim1;
} // get matrix row dimension
else {
if ( cr_names == colnames ) M_dim = dim2;
} // get matrix col dimension
// check to see if # elements OK
if ( nitems != M_dim ) {
if ( rfile.is_open() ) rfile.close();
err_msg = err_msg + "\n**** ADMB2R Error: Number of matrix indices in wrt_r_namevector for ";
err_msg = err_msg + prevObj[level] + " shoud be " + convert<string>(M_dim);
OKflag = false;
write_errmsg();
return "error";
}
}
// end of branch for matrix, begin branch for data frame
else {
// check that this is being called from a matrix or data frame
if ( mflag == "" ) {
if ( rfile.is_open() ) rfile.close();
err_msg = err_msg + "\n**** ADMB2R Error: Invalid use of wrt_r_namevector for " + prevObj[level];
OKflag = false;
write_errmsg();
return "error";
}
// check that number of items to print is the same as the data frame
if ( nitems != diff ) {
if ( rfile.is_open() ) rfile.close();
err_msg = err_msg + "\n**** ADMB2R Error: Number of items to write in wrt_r_namevector for " ;
err_msg = err_msg + prevObj[level] + " shoud be " + convert<string>(diff);
OKflag = false;
write_errmsg();
return "error";
}
}
return return_val;
}; // end check_rownames
//======================================================================================
// open_r_matrix
//
// Opens the matrix object and does housekeeping tasks
//
// ARGUMENTS:
// name - name of matrix to write to file.
//======================================================================================
void open_r_matrix (const char* name) {
// add info object name to list and check for object completion
int flag = reg_Rnames(name, "Matrix Object ");
if ( flag == 0 ) return;
// set matrix/data frame flag for wrt_r_namevector
mflag = "matrix";
rfile << name << " = structure(c(" << endl;
};
//======================================================================================
// close_r_matrix
//
// Closes the matrix object and does housekeeping tasks
//
// No arguments.
//======================================================================================
void close_r_matrix() {
if ( OKflag == false ) return; // exit if there was an earlier error
// check that row and column names are not empty
if (rownames.empty() ) {
if ( rfile.is_open() ) rfile.close();
err_msg = err_msg + "\n**** ADMB2R Error: Please add row names to ";
err_msg = err_msg + prevObj[level] + " using wrt_r_namevector";
OKflag = false;
write_errmsg();
return;
}
if (colnames.empty() ) {
if ( rfile.is_open() ) rfile.close();
err_msg = err_msg + "\n**** ADMB2R Error: Please add column names to ";
err_msg = err_msg + prevObj[level] + " using wrt_r_namevector";
OKflag = false;
write_errmsg();
return;
}
rfile << ".Dimnames = list(" << endl;
// Write row info
print_wrap(rownames, ", ");
// write out row/column names and rest of object
print_wrap(colnames, "))");
rfile << endl;
// re-set matrix/data frame flag for wrt_r_namevector
mflag.erase();
// set object complete flag
ObjDoneFlag[level] = true;
// clear row/col names and dimensions and write flags for next use
rownames.erase();
colnames.erase();
rowflag = 0;
colflag = 0;
dim1 = -1;
dim2 = -1;
// if something goes wrong
if ( rfile.bad() ) {
if ( rfile.is_open() ) rfile.close();
err_msg = err_msg + "\n**** ADMB2R Error: Unable to write to " + outfile;
OKflag = false;
write_errmsg();
return;
}
} // end close_r_matrix
//=====================================================================================
// do_wrt_r_matrix
//
// Write a matrix subobject to the R data object.
// Matrices differ from data frames in that columns need not have names,
// and they are of uniform type in all columns, e.g. double.
//
// After this function is used, the column names must be written separately
// to complete the matrix. That is done because the column names may or may
// not be the same as the column indices. (Row names are assumed to be the
// same as the row indices, generally years.)
//
// Arguments are passed to do_wrt_r_matrix by the overloaded wrt_r_matrix function.
//
// ARGUMENTS:
// xx - the matrix
// na_matrix - a boolean matrix indicating which positions in the xx matrix
// should be replaced with the NA missing value indicator. A value of 1 (true)
// indicates the spot to replace with NA.
//====================================================================================
template <class T>
void do_wrt_r_matrix (const T& xx, imatrix& na_matrix) {
int ir, ic; // row/column iterators in for statement
int ra, rz, ca, cz; // for matrix bounds
int counter; // counter to limit line lengths
ra = xx.rowmin(); // Get starting row index
rz = xx.rowmax(); // Get ending row index
ca = xx.colmin(); // Get starting column index
cz = xx.colmax(); // Get ending column index
// Write the matrix data
for ( ic=ca; ic<=cz; ic++ ) {
counter = 0;
for ( ir=ra; ir<=rz; ir++ ) {
counter++;
// if value is the missing value indicator, and we're
// using a missing value "value", write "NA" instead
if ( test_missing(convert<double>(xx(ir,ic))) && writeNA == true ) {
rfile << "NA";
}
// if instead we're using a matrix of booleans to
// indicate the position of missing values, check
// to see if this position is a missing value
else if (naflag && na_matrix[ir][ic]){
rfile << "NA";
}
// otherwise use the value we're given.
else {
rfile << xx(ir,ic);
}
// write proper punctuation
if ( ic==cz && ir==rz ) {
rfile << "),";
} else {
rfile << ", ";
if (counter == 25) {
rfile << endl; // Limit line lengths
counter = 0;
}
}
}
rfile << endl;
}
// Write dimensions of the matrix and save to dim1 and dim2
i = rz-ra+1; // # of row elements
dim1 = i;
rfile << ".Dim = c(" << i;
i = cz-ca+1; // # of column elements
dim2 = i;
rfile << "," << i << ")," << endl;
//set matrix row and column names
string temp;
if ( rowflag == 0 ) rownames = "NULL";
if ( rowflag == 1 ) { // write matrix row indices
rownames = "c(";
for ( ir=ra; ir<=rz; ir++ ) {
temp = convert <string> (ir); //convert index (integer) to string
rownames = rownames + quote + temp + quote; //add index to list
if ( ir==rz )
rownames = rownames + ")"; // add appropriate punctuation
else
rownames = rownames + ", ";
}
}
if ( rowflag == 2 ) rownames.erase(); // write row names with wrt_r_namevector
if ( colflag == 0 ) colnames = "NULL";
if ( colflag == 1 ) { // write matrix col indices
colnames = "c(";
for ( ic=ca; ic<=cz; ic++ ) {
temp = convert <string> (ic); //convert index (integer) to string
colnames = colnames + quote + temp + quote; //add index to list
if ( ic==cz )
colnames = colnames + ")"; // add appropriate punctuation
else
colnames = colnames + ", ";
}
}
if ( colflag == 2 ) colnames.erase(); // write column names with wrt_r_namevector
}; // end do_wrt_r_matrix
//======================================================================================
// wrt_r_matrix
//
// Overloaded function to write a matrix object.
// Defined here for types dvar_matrix, dmatrix, and imatrix.
//
// ARGUMENTS
// xx - the matrix
// This argument is passed to do_wrt_r_matrix for further handling.
// rowoption, coloption - flags for whether to write row names and column names. Optional.
// 0 = write NULL for row or column (Default).
// 1 = write names with same index as matrix.
// 2 = write names with a vector or sequence of numbers.
// isna - is an NA_matrix supplied. Optional.
// false = no matrix will be supplied (Default). true = a NA matrix will follow.
// na_matrix - (optional) a boolean matrix indicating which positions in the xx matrix
// should be replaced with the NA missing value indicator. A value of 1 (true)
// indicates the spot to replace with NA. This argument is passed to do_wrt_r_matrix
// for further handling.
//======================================================================================
void wrt_r_matrix(const dvar_matrix& xx, int rowoption = 0, int coloption = 0,
bool isna = false, imatrix& na_matrix = dum_matrix) {
// Set global flags
rowflag = rowoption;
colflag = coloption;
naflag = isna;
do_wrt_r_matrix<dvar_matrix> (xx, na_matrix);
} // wrt_r_matrix_wrt (dvar_matrix)
//======================================================================================
void wrt_r_matrix(const dmatrix& xx, int rowoption = 0, int coloption = 0,
bool isna = false, imatrix& na_matrix = dum_matrix) {
// Set global flags
rowflag = rowoption;
colflag = coloption;
naflag = isna;
do_wrt_r_matrix<dmatrix> (xx, na_matrix);
} // wrt_r_matrix_wrt (dmatrix)
//======================================================================================
void wrt_r_matrix(const imatrix& xx, int rowoption = 0, int coloption = 0,
bool isna = false, imatrix& na_matrix = dum_matrix) {
// Set global flags
rowflag = rowoption;
colflag = coloption;
naflag = isna;
do_wrt_r_matrix<imatrix> (xx, na_matrix);
} // end wrt_r_matrix (imatrix)
//======================================================================================
// do_wrt_r_namevector
//
// Function template for writing ADMB vector type row or column items
// Called from overloaded wrt_r_namevector functions.
//
// ARGUMENTS:
// rowvec = the vector to use
// start = position in vector at which to start writing
// stop = position in vector at which to end writing
//======================================================================================
template <class T>
void do_wrt_r_namevector (const T& rowvec, int start, int stop) {
string temp;
string cr_names; // temp name for row or column names list
// if using defaults (start=0, stop=0) then get vector bounds
if ( start == 0 && stop == 0 ) {
start = (rowvec).indexmin();
stop = (rowvec).indexmax();
} else if ( stop == 0 ) {
stop = (rowvec).indexmax();
}
// do error checking and get which item (row or column names) to write
string test = check_rownames<int> (start, stop, 1);
if ( test == "error" ) return;
if ( test == "row" ) cr_names = rownames;
else cr_names = colnames;
// now assign values to row or column names
cr_names = "c(";
for ( i=start; i<=stop; i++ ) {
temp = convert <string> (rowvec[i]); //convert vector to string
cr_names = cr_names + quote + temp + quote; //add index to list
if ( i==stop ) {
cr_names = cr_names + ")";
} else {
cr_names = cr_names + ", ";
}
}
if ( test == "col" ) colnames = cr_names; // re-assign back to row- or colnames
else rownames = cr_names;
}; // end do_wrt_r_namevector
//======================================================================================
// do_wrt_r_numvector
//
// Function template for writing row or column items using a series of numbers
// Called from wrt_r_namevector
//
// ARGUMENTS:
// start = value to start the series
// stop = value to end the series
// inc = the increment between series values
//======================================================================================
template <class T>
void do_wrt_r_numvector (const T& start, const T& stop, T inc) {
string temp;
string cr_names; // temp name for row or column names list
T iter; // iterator
// do error checking and get which item (row or column names) to write
string test = check_rownames<T> (start, stop, inc);
if ( test == "error" ) return;
if ( test == "row" ) cr_names = rownames;
else cr_names = colnames;
// now assign values to row or column names
cr_names = "c(";
temp = convert <string> (start);
cr_names = cr_names + quote + temp + quote;
iter = start + inc;
while ( iter<=stop ) {
temp = convert <string> (iter);
cr_names = cr_names + ", " + quote + temp + quote;
iter = iter + inc;
}
cr_names = cr_names + ")";
if ( test == "col" ) colnames = cr_names; // re-assign back to rownames or colnames
else rownames = cr_names;
}; // End do_wrt_r_numvector
//======================================================================================
// wrt_r_namevector
//
// Overloaded function to write matrix or data frame row/column names.
// Defined here for int and ivector.
// (The functions for ADMB dvector and dvar_vector types have been commented out to
// prevent possible rounding errors.)
//
// Arguments
// start - value to start row/column names with
// stop - value to end row/column names with
// inc - value to increment row/column names. Optional.
//====================================================================================
void wrt_r_namevector(const int& start, const int& stop, int inc = 1) {
if ( OKflag == false ) return; // exit if there was an earlier error
do_wrt_r_numvector<int> (start, stop, inc);
} // end wrt_r_namevector (int)
////====================================================================================
void wrt_r_namevector(const ivector& rowvec, int start = 0, int stop = 0) {
if ( OKflag == false ) return; // exit if there was an earlier error
do_wrt_r_namevector<ivector> (rowvec, start, stop);
} // end wrt_r_namevector (ivector)
////====================================================================================
//void wrt_r_namevector(const dvector& rowvec, int start = 0, int stop = 0) {
// if ( OKflag == false ) return; // exit if there was an earlier error
//
// do_wrt_r_namevector<dvector> (rowvec, start, stop);
//
//} // end wrt_r_namevector (dvector)
//
//====================================================================================
//void wrt_r_namevector(const dvar_vector& rowvec, int start = 0, int stop = 0) {
// if ( OKflag == false ) return; // exit if there was an earlier error
//
// do_wrt_r_namevector<dvar_vector> (rowvec, start, stop);
//
//} // end wrt_r_namevector (dvar_vector)
//======================================================================================
// open_r_list
//
// Initalize a LIST object: add object to list of R objects, increment level and
// initialize the level checking variables
//
// ARGUMENTS:
// name - name of object