void print_matrix(const real_2d_array& m, int row1, int row2, int col1, int col2) {
	row1 = min(row1, m.rows());
	row2 = min(row2, m.rows());
	col1 = min(col1, m.cols());
	col2 = min(col2, m.cols());
	for (int r=row1; r<row2; ++r) {
		for (int c=col1; c<col2; ++c) {
			cout<<m[r][c]<<"\t";
		}
		cout<<endl;
	}
}
void store_idata(const char* fpath, const real_2d_array& data) {
	FILE* f = fopen(fpath, "w");
	if (!f) throw "[store_data] Failed opening file!";
	for (int row=0; row<data.rows(); ++row) {
        for (int col=0; col<data.cols()-1; ++col) {
        	fprintf(f, "%i\t",(int)data[row][col]);
        }
        fprintf(f, "%i", (int)data[row][data.cols()-1]);
        //if (row != data.rows()-1)
		fprintf(f, "\n");
	}
	fclose(f);
}
Пример #3
0
// Opposite of slice --URI	
void insert(real_2d_array &matrix, int i, real_1d_array &output){
  int j;
  int c = matrix.cols();
  for(j=0; j<c; j++)
    matrix[i][j] = output[j];

}
void load_data(const char* fpath, real_2d_array& data, int readrows=-1) {
    int numrows = (readrows < 0)? get_file_numlines(fpath): readrows;
    int numcols = get_file_numcols(fpath);
    if (numrows <= 0 || numcols <= 0) {
    	throw "Failed to read data!";
    }
    data.setlength(numrows, numcols);

    char line[1000000];
    double rowvals[100000];
    FILE* f = fopen(fpath, "r");
    if (!f) throw "[load_data] Failed opening file!";
    for (int row=0; row<numrows; ++row) {
    	fgets (line, 1000000, f);

        int numvals = parse_row(line, rowvals);
        if (numcols != numvals) {
        	cerr<<"[load_data] numcols != numvals in row="<<row<<endl;
        	cerr<<"[load_data] numcols = "<<numcols<<endl;
        	cerr<<"[load_data] numvals = "<<numvals<<endl;
        	cerr<<"[load_data] line =["<<line<<"]"<<endl;
        	throw "Inconsistent data in input file!";
        }
        for (int col=0; col<numcols; ++col) {
        	data[row][col] = rowvals[col];
        }
    }
    fclose(f);
}
void fill_matrix(real_2d_array& dstm, int size) {
	dstm.setlength(size,size);
	for (int i=0; i<size; ++i) {
		//cout<<"[fill_matrix] row = "<<i<<endl;
		for (int j=i; j<size; ++j) {
			//cout<<"[fill_matrix] col = "<<j<<endl;
			dstm[i][j] = i*j+j;
			dstm[j][i] = dstm[i][j];
		}
	}
}
void move_to_alglib_matrix(DataMatrix<T>& datam, real_2d_array& dstm) {
	cout<<"Setting dimensions to:"<<datam.numrows<<"x"<<datam.numcols<<endl;
	dstm.setlength(datam.numrows,datam.numcols);
	cout<<"Moving..."<<endl;
	for (int r=0; r<datam.numrows; ++r) {
		if (r%100==0) {	cout<<(r*100/datam.numrows)<<"% moved..."<<endl; }
		for (int c=0; c<datam.numcols; ++c) {
			dstm[r][c] = datam.data[r][c];
		}
		delete[] datam.data[r]; //freeing src data!
	}
	delete[] datam.data; //freeing src data!
	cout<<"Done..."<<endl;
}
Пример #7
0
CostCalculator_eigen::CostCalculator_eigen(const real_1d_array expectReturn,
                                           const real_2d_array &varMatrix,
                                           const real_1d_array &tradingCost,
                                           const real_1d_array &currentWeight) {
    assert(expectReturn.length() == varMatrix.rows());
    assert(varMatrix.rows() == varMatrix.cols());
    assert(tradingCost.length() == varMatrix.rows());
    assert(currentWeight.length() == varMatrix.rows());
    variableNumber_ = expectReturn.length();

    xReal_.resize(variableNumber_, 1);
    varMatrix_.resize(variableNumber_, variableNumber_);
    expectReturn_.resize(variableNumber_);
    tradingCost_.resize(variableNumber_);
    currentWeight_.resize(variableNumber_);

    for (int i = 0; i != variableNumber_; ++i) {
        expectReturn_(i) = expectReturn[i];
        tradingCost_(i) = tradingCost[i];
        currentWeight_(i) = currentWeight[i];
        for (int j = 0; j != variableNumber_; ++j)
            varMatrix_(i, j) = varMatrix[i][j];
    }
}
Пример #8
0
// slices i^th row of matrix, into output
void slice(real_2d_array &matrix, int i, real_1d_array &output){
	int j;
	int c = matrix.cols();
	for(j=0;j<c;j++)
		output[j] = matrix[i][j];
}
Пример #9
0
int main(int argc, char **argv)
{
  printf("HELLO!");
       // Set measured indices --URI
       for(int i=0; i<NMEA; i++)
	 measIdx[i] = 2*i;

    //
    // using LBFGS method.
    //
	Ydata.setlength(NT,NX);
	real_1d_array X0,grad_a;
	X0.setlength(NT*NX);
	grad_a.setlength(NT*NX);
	real_2d_array result;
	result.setlength(NBETA,(3+NT*NX));
	double act;
    	int i,j;
	int beta = 1, ipath;

	void *ptr;

    	double epsg = 1e-8;
    	double epsf = 1e-8;
    	double epsx = 1e-8;
	FILE *fp_output;
	char filename[50];

   	ae_int_t maxits = 10000;

	readdata(Ydata);
	
	minlbfgsstate state;
	minlbfgsreport rep;

	// Make Initial paths - Load Later. URI
	if(generate_paths == true){
	  
	  ofstream initpaths("initpaths.txt");
	  for(ipath=0;ipath<NPATH;ipath++){
	    for(i=0;i<NX*NT;i++) 
	      X0[i]=20*randomreal()-10;

	    if(initpaths.is_open()){
	      for(i=0;i<NX*NT;i++) 
		initpaths << X0[i] << " ";
	      initpaths << endl;	      
	    }
	    else{
	      printf("ERROR FILE WAS NOT OPENED");
	    }
	  }	  
	  initpaths.close();
	  cout << "Last entry in initpaths.txt: " << X0[NT*NX-1];
	}


	//load init paths file --Needed for all loop iterations
	// either loadpaths or lastpath will be used depending on BETASTART	

	//loadpaths must be declared before ipath loop, because all
	//paths are contained in the loadpaths file, so it has to
	//persist through each iteration.
	ifstream loadpaths("initpaths.txt");

	int nans = 0;       

	for(ipath=0;ipath<NPATH;ipath++){
	     string taustr("Ntd%d_");

	     for(i=0; i<NTD;i++)
		  taustr = taustr + std::to_string(taus[i]) + "-";

	     string temp("pathNoise/D%d_M%d_PATH%d_"+taustr+"dt%e.dat");
	     sprintf(filename, temp.c_str(), NX,NMEA,ipath,NTD,DT);

		//lastpath is the filename used to continue from a
		//non-zero BETASTART. It must occur within ipath loop,
		//because each path is contained in different file
		ifstream lastpath(filename);

		//Make BETASTART variable to continue old thing
		//load in initial paths --URI
		if(BETASTART ==0){
		  fp_output = fopen(filename,"w"); 		
		  if(loadpaths.is_open()){
		    for(i=0;i<NX*NT;i++)
		      loadpaths >> X0[i];			  
		    cout << "Last entry loaded from initpaths.txt: " << X0[NT*NX-1];
		  }
		  else{
		    printf("ERROR INIT PATHS NOT FOUND!");
		  }
		}
Пример #10
0
// Construction of a kmean Trea for the neighborhoods stored in xy.
void kmeanTree(Node* node, real_2d_array xy, int min_size){
  if(xy.rows()>min_size){ //Stop if we have less than min_size neighborhoods.

    // K_mean (K=4) :
    clusterizerstate s;
    kmeansreport rep;

    clusterizercreate(s);
    clusterizersetpoints(s, xy, 2);
    clusterizersetkmeanslimits(s, 5, 0);
    clusterizerrunkmeans(s, 4, rep);

    if(int(rep.terminationtype)==1){ // Check if the K_mean step finished correctly.

      // Count the number of neighborhoods in each cluster.
      vector<int> count(4);
      for(int c=0;c<4;c++){
        for(int i=0;i<rep.npoints;++i){
          if(rep.cidx[i] == c){
            count[c]++;
          }
        }
      }

      if(count[0] && count[1] && count[2] && count[3]){ // Check that each cluster is non-empty.

        // Create new nodes
        for(int c=0;c<4;c++){
          Node*  nodeSon = new Node;
          node->addSon(nodeSon);
        }

        vector<real_2d_array> clusters(4);

        for(int c=0;c<4;c++){
          // Add the center element of each cluster in its related node.
          for(int f=0;f<rep.nfeatures;++f){
            node->getSon(c)->addCenterCoord((double)rep.c[c][f]);
          }

          // Separate the neighborhoods into the new nodes.
          int id = 0;
          clusters[c].setlength(count[c],rep.nfeatures);
          for(int i=0;i<rep.npoints;++i){
            if(rep.cidx[i] == c){
              for(int f=0;f<rep.nfeatures;++f){
                clusters[c][id][f] = xy[i][f];
              }
              id++;
            }
          }
        }

        // Iterate the construction on the new nodes.
        for(int c=0;c<4;c++){
          kmeanTree(node->getSon(c),clusters[c],min_size);
        }
      }
    }
  }
}
Пример #11
0
/*************************************************************************
ODE solver results

Called after OdeSolverIteration returned False.

INPUT PARAMETERS:
    State   -   algorithm state (used by OdeSolverIteration).

OUTPUT PARAMETERS:
    M       -   number of tabulated values, M>=1
    XTbl    -   array[0..M-1], values of X
    YTbl    -   array[0..M-1,0..N-1], values of Y in X[i]
    Rep     -   solver report:
                * Rep.TerminationType completetion code:
                    * -2    X is not ordered  by  ascending/descending  or
                            there are non-distinct X[],  i.e.  X[i]=X[i+1]
                    * -1    incorrect parameters were specified
                    *  1    task has been solved
                * Rep.NFEV contains number of function calculations

  -- ALGLIB --
     Copyright 01.09.2009 by Bochkanov Sergey
*************************************************************************/
void odesolverresults(const odesolverstate &state, ae_int_t &m, real_1d_array &xtbl, real_2d_array &ytbl, odesolverreport &rep)
{
    alglib_impl::ae_state _alglib_env_state;
    alglib_impl::ae_state_init(&_alglib_env_state);
    try
    {
        alglib_impl::odesolverresults(const_cast<alglib_impl::odesolverstate*>(state.c_ptr()), &m, const_cast<alglib_impl::ae_vector*>(xtbl.c_ptr()), const_cast<alglib_impl::ae_matrix*>(ytbl.c_ptr()), const_cast<alglib_impl::odesolverreport*>(rep.c_ptr()), &_alglib_env_state);
        alglib_impl::ae_state_clear(&_alglib_env_state);
        return;
    }
    catch(alglib_impl::ae_error_type)
    {
        throw ap_error(_alglib_env_state.error_msg);
    }
}