ADMB Documentation  -a65f1c97
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
qfc_sim.cpp
Go to the documentation of this file.
1 
31  #include "qfclib.h"
32 
33 
40  int numRows4VarFromFile(adstring filename,adstring varName)
41  {
42  const int MAXCHARS=1000; // constant value for max number of character readin for each line
43  const char *delim=" ,#:="; //change the delimiters as you need," ,#:="
44 
45  ifstream infile(filename); // open file for read in
46  char readin[MAXCHARS];
47  int cnt=0;
48  while(!infile.eof()){
49  infile.getline(readin,MAXCHARS);
50  char *pch;
51  pch = strtok(readin,delim); //first string or char[] being separated
52  while(pch != NULL)
53  {
54  //printf ("%s\n",pch);
55  if(strcmp(pch,(char*)varName)== 0) {cnt++; break;} //find the matched variable name
56  pch = strtok(NULL,delim);
57  } //end inner while()
58  }
59  infile.close();
60  //cout<<cnt<<endl;
61  return cnt;
62  }
63 
64 
65 
74  dmatrix findValFromFile(adstring filename,adstring varName,int numVals)
75  {
76  int repeat=numRows4VarFromFile(filename,varName);
77  if (repeat<=0) {cerr<<"Can not found that variable name in this file"<<endl; exit(1);}
78  const int MAXCHARS=1000; //constant value for max number of character readin for each line
79  const char *delim=" ,#:="; //change the delimiters as you need," ,#:="
80 
81  ifstream infile(filename); //open file for read in
82  dmatrix results(1,repeat,1,numVals); //output
83  char readin[MAXCHARS];
84  int cnt=0; //how many values needed after found that variable
85  int lines=0; //track of num rows for repeat
86  int start=0; //find the matched variable name
87 
88  while(!infile.eof()){
89  infile.getline(readin,MAXCHARS);
90  char *pch;
91  pch = strtok(readin,delim); //first string or char[] being separated
92  while(pch != NULL)
93  {
94  //printf ("%s\n",pch);
95  if(start==1) { //if founded the variable we needed
96  cnt++;
97  results(lines,cnt)=atof(pch); //change to double
98  //cout<<results(linecnt)<<" "<<readin<<endl;
99  if(cnt==numVals) start=0; //exit after readin in all we need # of values
100  }
101  if(strcmp(pch,(char*)varName)== 0) {//find the matched variable name
102  start=1; //find the matched variable name
103  cnt=0; //reset numVals counter as 0
104  lines++; //update line index
105  if(lines>repeat) break; //exit after reading num of repeat rows
106  }
107 
108  pch = strtok(NULL,delim);
109  } //end inner while()
110  }//end first while()
111  infile.close();
112 
113  return results;
114  }
115 
116 
117 
118 
119 
120 
127  dvector unique(const dvector& in)
128  {
129  dvector lookup(1,in.size()); //track of duplicate index
130  lookup=1; //initial 1 as no duplicate, duplicate mark as 0
131 
132  dvector all=sort(in);
133 
134  //find duplicates
135  for(int i=all.indexmin();i<all.indexmax();i++)
136  {
137  if(lookup(i)!=0) //0 means already marked as duplicate, so skip it, initial as all 1
138  {
139  for(int j=i+1;j<=all.size();j++)
140  {
141  if(all(i) == all(j))
142  lookup(j)=0; //mark same duplicate as 0
143  }
144  }
145  }
146 
147  //output the unique by removing the duplicates
148  int tot=int(sum(lookup)); //total unique value
149  dvector out(1,tot);
150  int idx=1;
151  for(int i=all.indexmin();i<=all.indexmax();i++)
152  if(lookup(i)==1) //only output unique value, duplicate mark as 0
153  out(idx++) = all(i);
154 
155  return out;
156  }
157 
158 
159 
160 
171  ivector sample(const dvector& source,int nSample,int withReplace,const random_number_generator& rng)
172  {
173  int totN=source.size();
174  dvector lookup(source.indexmin(),source.indexmax());
175  lookup=source;
176  ivector out(1,nSample);
177 
178  if(withReplace==0){ //sampling without replacement, all unique site index
179  out(1)=source.indexmin()+int(totN*randu(rng));
180  lookup(out(1))=0;//if selected, then mark lookup as 0
181 
182  for(int i=2;i<=nSample;i++){
183  out(i)=source.indexmin()+int(totN*randu(rng));
184  while(lookup(out(i))==0){ //which means already being selected
185  out(i)=source.indexmin()+int(totN*randu(rng));
186  }
187  lookup(out(i))=0;//if selected, then mark lookup as 0
188  }
189  }else{ //with replacement,allow repeat sampling
190  for(int i=1;i<=nSample;i++)
191  out(i)=source.indexmin()+int(totN*randu(rng));
192  }
193 
194  return out; //you can use source(out) to access the sample
195  }
196 
197 
198 
199 
200 
201 
208  dvector matrix2vector(const dmatrix& input, int byrow=1)
209  {
210  dvector out(1,size_count(input)); //input.rowsize()*input.colsize()
211  long idx=1;
212  if(byrow==1){ //by row
213  for(int i=input.indexmin();i<=input.indexmax();i++) //row
214  for(int j=input(i).indexmin();j<=input(i).indexmax();j++) //col
215  out(idx++)=input(i,j);
216  }
217  else{ //by column
218  for(int i=input.colmin();i<=input.colmax();i++) //col
219  for(int j=input.rowmin();j<=input.rowmax();j++) //row
220  out(idx++)=input(j,i);
221  }
222  return out;
223  }
224 
232  dvar_vector matrix2vector(const dvar_matrix& input, int byrow=1)
233  {
234  dvar_vector out(1,size_count(input)); //input.rowsize()*input.colsize()
235  long idx=1;
236  if(byrow==1){ //by row
237  for(int i=input.indexmin();i<=input.indexmax();i++) //row
238  for(int j=input(i).indexmin();j<=input(i).indexmax();j++) //col
239  out(idx++)=input(i,j);
240  }
241  else{ //by column
242  for(int i=input.colmin();i<=input.colmax();i++) //col
243  for(int j=input.rowmin();j<=input.rowmax();j++) //row
244  out(idx++)=input(j,i);
245  }
246  return out;
247  }
248 
256  df1b2vector matrix2vector(const df1b2matrix& input, int byrow=1)
257  {
258  df1b2vector out(1,size_count(input)); //input.rowsize()*input.colsize()
259  long idx=1;
260  if(byrow==1){ //by row
261  for(int i=input.indexmin();i<=input.indexmax();i++) //row
262  for(int j=input(i).indexmin();j<=input(i).indexmax();j++) //col
263  out(idx++)=input(i,j);
264  }
265  else{ //by column
266  for(int i=input.colmin();i<=input.colmax();i++) //col
267  for(int j=input.rowmin();j<=input.rowmax();j++) //row
268  out(idx++)=input(j,i);
269  }
270  return out;
271  }
272 
273 
274 
275 
276 
286  dmatrix vector2matrix(dvector& input, int nrow, int ncol, int byrow=1)
287  {
288  if(nrow*ncol != input.size()){
289  cerr<<"In vector2matrix(): Defined matrix dimension not fit the input vector size"<<endl;
290  exit(1);
291  }
292  dmatrix out(1,nrow,1,ncol);
293  long idx=input.indexmin();
294  if(byrow==1){ //by row
295  for(int i=1;i<=nrow;i++) //row
296  for(int j=1;j<=ncol;j++) //col
297  out(i,j)=input(idx++);
298  }
299  else{ //by column
300  for(int i=1;i<=ncol;i++) //col
301  for(int j=1;j<=nrow;j++) //row
302  out(j,i)=input(idx++);
303  }
304  return out;
305  }
306 
317  df1b2matrix vector2matrix(df1b2vector& input, int nrow, int ncol, int byrow=1)
318  {
319  if(nrow*ncol != input.size()){
320  cerr<<"In vector2matrix(): Defined matrix dimension not fit the input vector size"<<endl;
321  exit(1);
322  }
323  df1b2matrix out(1,nrow,1,ncol);
324  long idx=input.indexmin();
325  if(byrow==1){ //by row
326  for(int i=1;i<=nrow;i++) //row
327  for(int j=1;j<=ncol;j++) //col
328  out(i,j)=input(idx++);
329  }
330  else{ //by column
331  for(int i=1;i<=ncol;i++) //col
332  for(int j=1;j<=nrow;j++) //row
333  out(j,i)=input(idx++);
334  }
335  return out;
336  }
337 
348  dvar_matrix vector2matrix(const dvar_vector& input, int nrow, int ncol, int byrow=1)
349  {
350  if(nrow*ncol != input.size()){
351  cerr<<"In vector2matrix(): Defined matrix dimension not fit the input vector size"<<endl;
352  exit(1);
353  }
354  dvar_matrix out(1,nrow,1,ncol);
355  long idx=input.indexmin();
356  if(byrow==1){ //by row
357  for(int i=1;i<=nrow;i++) //row
358  for(int j=1;j<=ncol;j++) //col
359  out(i,j)=input(idx++);
360  }
361  else{ //by column
362  for(int i=1;i<=ncol;i++) //col
363  for(int j=1;j<=nrow;j++) //row
364  out(j,i)=input(idx++);
365  }
366  return out;
367  }
368 
369 
370 
371 
372 
373 
374 
375 
383  bool doubleEqual(double nVal1, double nVal2, int nPrecision)
384  {
385  const double base = 10;
386  // if want equal, you can define an arrange like
387  bool bRet = (((nVal2 - pow(base,-nPrecision)) < nVal1) && (nVal1 < (nVal2 + pow(base,-nPrecision))));
388  return bRet;
389  }
390 
391 
392 
393 
394 
395 
403  double runif(double low, double upper, random_number_generator & rng)
404  {
405  return low+ randu(rng)*(upper-low); //randu() get (0,1)
406  }
407 
408 
409 
410 
418  double rnorm(double mu, double sigma, random_number_generator & rng)
419  {
420  return mu + randn(rng)*sigma;
421  }
422 
423 
424 
425 
433  double rlnorm(double mu, double sigma, random_number_generator & rng)
434  {
435  return mfexp(mu + randn(rng)*sigma);
436  }
437 
438 namespace qfclib
439 {
447  double rgamma(double alpha, random_number_generator& rng)
448  {
449  double v0, v1, v2, fract, em, qm, tmp, gam_n1;
450  int i;
451 
452  //calculate Gamma(n,1) integer part first
453  tmp = 1.;
454  if (int(alpha) == 0) //which means 0<alpha <1
455  gam_n1 = 0;
456  else{
457  for( i = 1;i<=int(alpha);i++)
458  tmp *= randu(rng); //using modified rnd()
459 
460  gam_n1 = -1. * log(tmp);
461  }
462 
463  fract = alpha - int(alpha) + EPS; //fractional part of alpha
464  v0 = QFC_M_E / (QFC_M_E + fract);
465 
466  //calculate the fractional gamma(fract,1)
467  while(1){
468  v1 = randu(rng);
469  v2 = randu(rng);
470  if (v1 <= v0){
471  em = pow(v1 / (v0 + EPS), 1. / fract);
472  qm = v2 * pow(em, fract - 1.);
473  }else{
474  em = 1. - log((v1 - v0) / (1. - v0 + EPS));
475  qm = v2 * mfexp(-em);
476  }
477  if (qm <= (pow(em, fract - 1.) * mfexp(-em))) break;
478  }
479 
480  return (em + gam_n1);
481  }
482 }
483 
484  double rgamma(double alpha, random_number_generator& rng);
485 
494  double rgamma(double alpha, double beta, random_number_generator& rng)
495  {return rgamma(alpha,rng)/beta; }
496 
497 
498 
499 
500 
508  double rbeta(double alpha, double beta, random_number_generator& rng)
509  {return rgamma(alpha,rng)/(rgamma(alpha,rng)+rgamma(beta,rng)); }
510 
511 
512 
513 
514 
522  {
523  double tot=0;
524  int ncat=shape.size();
525  dvector gam(shape.indexmin(),ncat);
526  dvector results(shape.indexmin(),ncat);
527  int i;
528 
529  //generate gamma random number first
530  for (i=shape.indexmin(); i<=shape.indexmax(); i++) {
531  gam[i]=rgamma(shape[i],rng);
532  }
533 
534  tot=sum(gam);
535  //normalize them by its sum
536  for (i=shape.indexmin(); i<=shape.indexmax(); i++) {
537  results[i] = gam[i]/tot;
538 
539  if (results[i]< EPS)
540  results[i]= EPS; // not put zero
541  //cout<<results(i)<<endl;
542  }
543  return results;
544  }
545 
double rgamma(double alpha, random_number_generator &rng)
generate random gamma number, pseudo code see http://en.wikipedia.org/wiki/Gamma_distribution ...
Definition: qfc_sim.cpp:447
int rowmax(void) const
Definition: fvar.hpp:2564
dvector unique(const dvector &in)
find the unique values from input vector and only return the unique (by remove the duplicate) values ...
Definition: qfc_sim.cpp:127
double runif(double low, double upper, random_number_generator &rng)
generate one random uniform from (low,upper)
Definition: qfc_sim.cpp:403
dmatrix findValFromFile(adstring filename, adstring varName, int numVals)
find the number of values(numVals) for one specific variable(varName) from an admb output file ...
Definition: qfc_sim.cpp:74
int colmin(void) const
Definition: fvar.hpp:2552
Vector of double precision numbers.
Definition: dvector.h:50
int indexmin(void) const
Definition: df1b2fun.h:1054
int indexmin() const
Get minimum valid index.
Definition: dvector.h:199
int indexmin() const
Definition: fvar.hpp:2917
double sum(const d3_array &darray)
Author: David Fournier Copyright (c) 2008-2012 Regents of the University of California.
Definition: d3arr.cpp:21
Description not yet available.
Definition: df1b2fun.h:953
int indexmin(void) const
Definition: df1b2fun.h:969
ADMB variable vector.
Definition: fvar.hpp:2172
int rowmin(void) const
Definition: df1b2fun.h:1053
unsigned int size() const
Definition: fvar.hpp:2297
const double EPS
Definition: qfclib.h:42
ivector sample(const dvector &source, int nSample, int withReplace, const random_number_generator &rng)
generate a random sample index(size is nSample) based on the input samples(source) with or without re...
Definition: qfc_sim.cpp:171
d3_array mfexp(const d3_array &m)
Author: David Fournier Copyright (c) 2008-2012 Regents of the University of California.
Definition: d3arr7.cpp:10
double randu(const random_number_generator &rng)
Uniform random number generator.
Definition: rngen.cpp:198
Description not yet available.
Definition: fvar.hpp:7951
dmatrix sort(const dmatrix &m, int column, int NSTACK)
Description not yet available.
Definition: dmsort.cpp:17
prnstream & endl(prnstream &)
Array of integers(int) with indexes from index_min to indexmax.
Definition: ivector.h:50
int rowmax() const
Definition: fvar.hpp:2929
double rbeta(double alpha, double beta, random_number_generator &rng)
generate random beta(alpha, beta) number,
Definition: qfc_sim.cpp:508
double rnorm(double mu, double sigma, random_number_generator &rng)
generate one random normal number N(mu,sigma)
Definition: qfc_sim.cpp:418
int indexmax() const
Get maximum valid index.
Definition: dvector.h:204
const double QFC_M_E
Definition: qfclib.h:43
double rlnorm(double mu, double sigma, random_number_generator &rng)
generate one random lognormal number LN(mu,sigma)
Definition: qfc_sim.cpp:433
dvariable beta(const prevariable &a, const prevariable &b)
Beta density function.
Definition: vbeta.cpp:18
int colmin(void) const
Definition: fvar.hpp:2939
int rowmin(void) const
Definition: fvar.hpp:2560
Description not yet available.
Definition: fvar.hpp:2819
bool doubleEqual(double nVal1, double nVal2, int nPrecision)
determine if two double values are equal within some precision
Definition: qfc_sim.cpp:383
unsigned int size() const
Get number of elements in array.
Definition: dvector.h:209
int indexmax() const
Definition: fvar.hpp:2921
int indexmin() const
Definition: fvar.hpp:2287
int indexmax(void) const
Definition: fvar.hpp:2572
Description not yet available.
Definition: df1b2fun.h:1042
dvector matrix2vector(const dmatrix &input, int byrow=1)
convert the matrix as a vector eithter by row=1(default) or by column=0,
Definition: qfc_sim.cpp:208
double randn(const random_number_generator &rng)
Normal number generator.
Definition: rngen.cpp:183
Class definition of matrix with derivitive information .
Definition: fvar.hpp:2480
int indexmax(void) const
Definition: df1b2fun.h:1055
unsigned int size_count(const dvector &x)
Returns total size of elements in vector x.
Definition: dsize.cpp:17
int numRows4VarFromFile(adstring filename, adstring varName)
get how many rows for one specific variable(varName) in admb output file(filename) ...
Definition: qfc_sim.cpp:40
int colmin(void) const
Definition: df1b2fun.h:1089
int colmax(void) const
Definition: df1b2fun.h:1090
int rowmax(void) const
Definition: df1b2fun.h:1056
int indexmin(void) const
Definition: fvar.hpp:2568
dmatrix vector2matrix(dvector &input, int nrow, int ncol, int byrow=1)
convert the Vector as a Matrix eithter by row=1(default) or by column=0,
Definition: qfc_sim.cpp:286
int rowmin() const
Definition: fvar.hpp:2925
d3_array log(const d3_array &arr3)
Author: David Fournier Copyright (c) 2008-2012 Regents of the University of California.
Definition: d3arr2a.cpp:13
int size()
Definition: df1b2fun.h:971
d3_array pow(const d3_array &m, int e)
Description not yet available.
Definition: d3arr6.cpp:17
int colmax(void) const
Definition: fvar.hpp:2943
double rgamma(double alpha, random_number_generator &rng)
Copyright (c) 2016 ADMB Foundation.
dvector rdirichlet(const dvector &shape, random_number_generator &rng)
generate random dirichlet number
Definition: qfc_sim.cpp:521
int colmax(void) const
Definition: fvar.hpp:2556