Exemple #1
0
/* lambda/mlambda integer least-square estimation ------------------------------
* integer least-square estimation. reduction is performed by lambda (ref.[1]),
* and search by mlambda (ref.[2]).
* args : int n I number of float parameters
* int m I number of fixed solutions
* double *a I float parameters (n x 1)
* double *Q I covariance matrix of float parameters (n x n)
* double *F O fixed solutions (n x m)
* double *s O sum of squared residulas of fixed solutions (1 x m)
* return : status (0:ok,other:error)
* notes : matrix stored by column-major order (fortran convension)
*-----------------------------------------------------------------------------*/
int lambda_solution(int n, int m, const double *a, const double *Q, double *F,
                  double *s)
{
    int info;

    if (n<=0||m<=0) return -1;
    double L[n*n];
    double D[n];
    double Z[n*n];
    double z[n];
    double E[n*m];

    /* L = zeros(n,n) */
    memset(L, 0, sizeof(double)*n*n);

    /* Z = eye(n) */
    memset(Z, 0, sizeof(double)*n*n);
    for (int i=0; i<n; i++)
      Z[i+n*i] = 1;

    /* LD factorization */
    if (!(info=LD(n,Q,L,D))) {

        /* lambda reduction */
        reduction(n,L,D,Z);
        matmul("TN",n,1,n,1.0,Z,a,0.0,z); /* z=Z'*a */

        /* mlambda search */
        if (!(info=search(n,m,L,D,z,E,s))) {

            info=solve("T",Z,E,n,m,F); /* F=Z'\E */
        }
    }
    return info;
}
Exemple #2
0
/* lambda/mlambda integer least-square estimation ------------------------------
* integer least-square estimation. reduction is performed by lambda (ref.[1]),
* and search by mlambda (ref.[2]).
* args   : int    n      I  number of float parameters
*          int    m      I  number of fixed solutions
*          double *a     I  float parameters (n x 1)
*          double *Q     I  covariance matrix of float parameters (n x n)
*          double *F     O  fixed solutions (n x m)
*          double *s     O  sum of squared residulas of fixed solutions (1 x m)
* return : status (0:ok,other:error)
* notes  : matrix stored by column-major order (fortran convension)
*-----------------------------------------------------------------------------*/
extern int lambda(int n, int m, const double *a, const double *Q, double *F,
                  double *s)
{
    int info;
    double *L,*D,*Z,*z,*E;
    
    if (n<=0||m<=0) return -1;
    L=zeros(n,n); D=mat(n,1); Z=eye(n); z=mat(n,1),E=mat(n,m);
    
    /* LD factorization */
    if (!(info=LD(n,Q,L,D))) {
        
        /* lambda reduction */
        reduction(n,L,D,Z);
        matmul("TN",n,1,n,1.0,Z,a,0.0,z); /* z=Z'*a */
        
        /* mlambda search */
        if (!(info=search(n,m,L,D,z,E,s))) {
            
            info=solve("T",Z,E,n,m,F); /* F=Z'\E */
        }
    }
    free(L); free(D); free(Z); free(z); free(E);
    return info;
}
Exemple #3
0
/* lambda reduction transformation ------------------------------
* integer least-square estimation. reduction is performed by lambda (ref.[1]),
* and search by mlambda (ref.[2]).
* args   : int    n      I  number of float parameters
*          double *a     I  float parameters (n x 1)
*          double *Q     I  covariance matrix of float parameters (n x n)
* return : status (0:ok,other:error)
* notes  : matrix stored by column-major order (fortran convension)
*-----------------------------------------------------------------------------*/
int lambda_reduction(int n, const double *Q, double *Z)
{
    int info;

    if (n<=0) return -1;

    double L[n*n];
    double D[n];

    /* L = zeros(n,n) */
    memset(L, 0, sizeof(double)*n*n);

    /* Z = eye(n) */
    memset(Z, 0, sizeof(double)*n*n);
    for (int i=0; i<n; i++)
      Z[i+n*i] = 1;

    /* LD factorization */
    if (!(info=LD(n,Q,L,D))) {
        /* lambda reduction */
        reduction(n,L,D,Z);
    }

    return info;
}
Exemple #4
0
void	put_quadri(t_mlx *p, int a, int **tab)
{
  t_point	quad;
  int	i;
  int	xbase;
  int	ybase;
  int	count;
  int	j;

  i = 0;
  quad.x = 175;
  quad.y = 500;
  quad.segm = 325 / a;
  count = 0;
  xbase = quad.x;
  ybase = quad.y;
  while (i < a)
    {
      quad.x = xbase + (count * quad.segm);
      quad.y = ybase + (count * quad.segm);
      quad.tmp = quad.y;
      j = 0;
      reduction(p, tab, i, &quad);
      i++;
      count++;
    }
}
int precedenceParser() {				// hlavni funkce precedencni analyzy

	tStack stack1;
	stackInit(&stack1);

	tStack stack2;
	stackInit(&stack2);

	tOpData temp;

	infix2post(&stack1, &stack2);		// prevedeni vyrazu na postfixovou notaci

	while(stackEmpty(&stack2) != true) {		// prechozeni na druhy zasobnik + kontrolni vypsani

		stackPop(&stack2, &temp);
		stackPush(&stack1, temp);
	}

	int x = reduction(&stack1, &stack2);		// provedeni redukce
	printf("Navratovy typ vyrazu: %d\n", x);

	stackDispose(&stack1);
	stackDispose(&stack2);


	return x;
}
Exemple #6
0
   int ARLambda::lambda( const Vector<double>& a, 
                         const Matrix<double>& Q, 
                         Matrix<double>& F,
                         Vector<double>& s,
                         const int& m )
   {
      if( (a.size()!=Q.rows()) || (Q.rows()!=Q.cols()) ) return -1;
      if( m < 1) return -1;

      const int n = static_cast<int>(a.size());

      Matrix<double> L(n,n,0.0),E(n,m,0.0);
      Vector<double> D(n,0.0),z(n,0.0);
      Matrix<double> Z = ident<double>(n);

      if (factorize(Q,L,D)==0) 
      {      
         reduction(L,D,Z);
         z = transpose(Z)*a;

         if (search(L,D,z,E,s,m)==0) 
         {
            try
            {  // F=Z'\E - Z nxn  E nxm F nxm
               F = transpose( inverseLUD(Z) ) * E;
            }
            catch(...) 
            { return -1; }
         }
      }

      return 0;

   }  // End of method 'ARLambda::lambda()'
Exemple #7
0
	void mul(mpz_class& z, const mpz_class& x, const mpz_class& y) const
	{
		z = x * y;
		reduction(z);
		if (z >= p_) {
			z -= p_;
		}
	}
Exemple #8
0
void NelderMead::process()
{
    int count = 0;
    
    int maxCount = FileParser::getKey("NELDER_MEAD_CYCLES", 100);
    
    while ((!converged() && count < maxCount) || unlimited)
    {
        sendLog(LogLevelDebug);
        std::vector<double> centroid = calculateCentroid();
        count++;

        logged << "Evaluation of best point: " << testPoints[0].second << std::endl;
        sendLog(LogLevelDebug);

        TestPoint reflected = reflectedPoint(centroid);
        
        if (reflected.second < testPoints[1].second)
        {
            logged << "Reflecting" << std::endl;
            setWorstTestPoint(reflected);
            continue;
        }
        
        if (reflected.second < testPoints[0].second)
        {
            TestPoint expanded = expandedPoint(centroid);
            bool expandedBetter = (expanded.second < reflected.second);
            setWorstTestPoint(expandedBetter ? expanded : reflected);
            
            logged << (expandedBetter ? "Expanding" : "Reflecting") << std::endl;
            
            continue;
        }
        
        TestPoint contracted = contractedPoint(centroid);
        TestPoint *worstPoint = worstTestPoint();
        
        if (contracted.second < worstPoint->second)
        {
            logged << "Contracting" << std::endl;
            setWorstTestPoint(contracted);
            continue;
        }
        else
        {
            logged << "Reducing" << std::endl;
            reduction();
        }
    }
    
    orderTestPoints();
    setTestPointParameters(&testPoints[0]);
    
    logged << "Evaluation of best point: " << testPoints[0].second << std::endl;
    sendLog(LogLevelDetailed);

}
Exemple #9
0
static float
f14_maxcorr (float **     const p,
             unsigned int const ng) {
    /*----------------------------------------------------------------------------
      The Maximal Correlation Coefficient
    -----------------------------------------------------------------------------*/
    unsigned int i;
    float *px, *py;
    float ** q;
    float * x;
    float * iy;
    float tmp;

    px = vector(0, ng);
    py = vector(0, ng);
    q = matrix(1, ng + 1, 1, ng + 1);
    x = vector(1, ng);
    iy = vector(1, ng);

    /*
     * px[i] is the (i-1)th entry in the marginal probability matrix obtained
     * by summing the rows of p[i][j]
     */
    for (i = 0; i < ng; ++i) {
        unsigned int j;
        for (j = 0; j < ng; ++j) {
            px[i] += p[i][j];
            py[j] += p[i][j];
        }
    }

    /* Compute the Q matrix */
    for (i = 0; i < ng; ++i) {
        unsigned int j;
        for (j = 0; j < ng; ++j) {
            unsigned int k;
            q[i + 1][j + 1] = 0;
            for (k = 0; k < ng; ++k)
                q[i + 1][j + 1] += p[i][k] * p[j][k] / px[i] / py[k];
        }
    }

    /* Balance the matrix */
    mkbalanced(q, ng);
    /* Reduction to Hessenberg Form */
    reduction(q, ng);
    /* Finding eigenvalue for nonsymetric matrix using QR algorithm */
    hessenberg(q, ng, x, iy);
    if (sortit)
        simplesrt(ng, x);

    /* Return the sqrt of the second largest eigenvalue of q */
    for (i = 2, tmp = x[1]; i <= ng; ++i)
        tmp = (tmp > x[i]) ? tmp : x[i];

    return sqrt(x[ng - 1]);
}
Exemple #10
0
/**
 * Principle Variation Search (root node)
 * Difference with normal (non-root) search:
 * - Sending new PVs asap to the interface
 * - Sort order based on pv and amount of nodes of the subtrees
 * - No pruning and hash table lookup/store
 * - Compatible with all supported wild variants
 */
int search_t::pvs_root(int alpha, int beta, int depth) {

    assert(root.move_count > 0);
    int best = -score::INF;
    const bool is_pv = true;
    root.sort_moves(&stack->best_move);

    /*
     * Moves loop
     */

    for (int i = 0; i < root.move_count; i++) {
        root_move_t * rmove = &root.moves[i];
        move_t * move = &rmove->move;
        int nodes_before = nodes;

        //extensions and reductions
        int extend = extension(move, depth, is_pv, rmove->gives_check);
        int reduce = reduction(depth, i, rmove->is_dangerous);
        int score = 0;

        //go forward and search one level deeper
        forward(move, rmove->gives_check);
        if (i == 0) {
            score = -pvs(-beta, -alpha, depth - 1 + extend);
        } else {
            score = -pvs(-alpha - 1, -alpha, depth - 1 - reduce + extend);
            if (score > alpha) { //open window research w/o reductions
                score = -pvs(-beta, -alpha, depth - 1 + extend);
            }
        }
        backward(move);

        //handle results
        rmove->nodes += nodes - nodes_before;
        if (stop_all) {
            return alpha;
        } else if (score > best) {
            best = score;
            result_score = score;
            rmove->nodes += i;
            stack->best_move.set(move);
            bool exact = score::flags(score, alpha, beta) == score::EXACT;
            if (exact || false == move->equals(&stack->pv_moves[0])) {
                update_pv(&rmove->move);
            }
            uci::send_pv(best, depth, sel_depth, nodes + pruned_nodes, game->tm.elapsed(),
                    pv_to_string().c_str(), score::flags(best, alpha, beta));
            if (!exact) { //adjust asp. window
                return score;
            }
            assert(alpha < best);
            alpha = best;
        }
    }
    return best;
}
Exemple #11
0
int main(int argc, char const *argv[])
{
    tokenadt *array, *stack;
    numdict *dict;
    valuepool *vpool;
    
    array = token_adt_new(MAXADTLEN);
    stack = token_adt_new(MAXADTLEN);
    dict = numdict_new();
    vpool = value_pool_new();

    char b[MAXINPUT];
    int l;
    const char *info = GAKIO_REPL_INFO;
    fputs(info, stdout);
    fflush(stdout);

    const char *prmt = ">> ";
    while (1) {
        fputs(prmt, stdout);
        fflush(stdout);

        if (fgets(b, MAXINPUT, stdin) == NULL)
                return 0; 
        l = strlen(b);

        /* 如果输入字符长度大于 MAXINPUT,将截取 MAXINPUT 长的字符串;
         * 并清空标准输入中剩余的字符
         */
        if (l > 0 && b[l-1] != '\n') {
            b[l-1] = '\n';
            while (getchar() != '\n');
        }

        if (l > 0 && b[l-1] == '\n')  
            b[l-1] = '\0'; 

        if (strcmp(b, ":q") != 0) {
            
            l = akio_lex(array, vpool, b);
            if (!l) {
                reduction(array, stack, dict, vpool);
            }
            token_adt_reset(array);
            token_adt_reset(stack);
        } else {
            break;
        }
    }

    token_adt_delete(array);
    token_adt_delete(stack);
    numdict_delete(dict);
    value_pool_delete(vpool);
    return 0;
}
Exemple #12
0
expresion* stx::parse()
{
    Func f_reducida = reduction(my_func);/*quitamos espacios de la funcion*/
    starting_vector();/*inicializar el vector de atomos*/
    atomizer(f_reducida);/*Separamos los atomos al vector*/
    //armar el arbol de acuerdo a la precedencia
            //comenzar a poblar
    //return new operator(new constante(5),&sumab,new constante(10));

}
Exemple #13
0
struct rational div_rational(struct rational a, struct rational b) {
	struct rational c;
	
	c.x = a.x * b.y;
	c.y = a.y * b.x;
	
	c = reduction(c);

	return c;
}
Exemple #14
0
struct rational sub_rational(struct rational a, struct rational b) {
	struct rational c;
	if (a.y == b.y) {
		c.x = a.x - b.x;
		c.y = a.y;
	} else {
		c.x = a.x * b.y - b.x *a.y;
		c.y = a.y * b.y;
	}
	c = reduction(c);

	return c;
}
Exemple #15
0
	void reduction(mpz_class& z) const
	{
#if 0
		const size_t N = 72 / sizeof(BlockType);
		BlockType buf[N];
		const size_t zn = mie::Gmp::getBlockSize(z);
		assert(zn  <= pn_ * 2 && pn_ * 2 <= N);
		memcpy(buf, mie::Gmp::getBlock(p), zn * sizeof(BlockType));
		memset(buf[zn], 0, (pn_ - zn) * sizeof(BlockType));
		reduction(buf);
#else
		for (size_t i = 0; i < pn_; i++) {
			BlockType q = mie::Gmp::getBlock(z, 0) * pp_;
			z += p_ * q;
			z >>= sizeof(BlockType) * 8;
		}
#endif
	}
Exemple #16
0
int main(int argc, char * argv[])
{
	if (argc != 2) {printf("Please provide a matrix");}

	int ierr = MPI_Init(&argc, &argv);
	MPI_Comm_rank(MPI_COMM_WORLD, &rank); //sets rank
	MPI_Comm_size(MPI_COMM_WORLD, &size); //gets number of processes
	current_pivot = 0;

	if (rank == 0) { //master process
		get_number_of_rows(argv[1], &numrows);
		numcols = numrows + 1; //specified by assignment
		int i;
		for (i = 1; i < size; i++) { //sending out information to slaves about what rows they are reading.
			MPI_Isend(&numrows, 1, MPI_INT, i, MASTER_TO_SLAVE_TAG, MPI_COMM_WORLD, &request);
		}
	}
	else {
		MPI_Recv(&numrows, 1, MPI_INT, 0, MASTER_TO_SLAVE_TAG, MPI_COMM_WORLD, &status);
		numcols = numrows + 1;
	}
	if (rank >= numrows) {
		ierr = MPI_Finalize();
		return 0;
	} else if (rank < (numrows % size)) {
		numrows = (numrows / size) + 1;
	} else {
		numrows = (numrows / size);
	}
	matrix = allocate_matrix(numrows, numcols);
	read_rows(argv[1], matrix);
	RREF(matrix);
	absolute(matrix, &numrows, &numcols);
	reduction(matrix, &numrows, &numcols);
	get_best_threshold();
	collect(matrix);
	// print_matrix(matrix, numrows, numcols);
	print_matrix(final_matrix, numcols - 1, numcols);
	if (rank == 0) {
		// output_to_file(final_matrix);
	}
	free_matrix(matrix, &numrows);
	ierr = MPI_Finalize();
}
Exemple #17
0
int main(void)
{
  hypergraph * H = loadHyperGraph("data/test.dat");
  displayHyperGraph(H, "H");
  
  //Initialize G with no edges and the same vertices as H
  hypergraph * G = newHyperGraph();
  vertexSet *tmp = H->vertexSets;
  while(tmp != NULL)
  {
    appendUniqueVertexSet(&G->vertexSets, tmp->id);
    tmp = tmp->nextVertex;
  }
  
  G = reduction(copyHyperGraph(H), G);
  
  //printf("\nReduction complete...\n\n");
  displayHyperGraph(G, "G'");
  return 0;
}
Exemple #18
0
void divide(int now, int n, int l, int r, int connect)
{
	for(int i = 0; i != n; ++i)
	{
		d[i] = edge[now][i];
		map[d[i].id] = i;
	}

	for(int i = l; i <= r; ++i)
	{
		for(int j = 0; j != ques[i].num; ++j)
			d[map[ques[i].d[j]]].mark = 1;
	}

	if(l == r)
	{
		for(int i = 0; i != n; ++i)
		{
			int u = ms.find(d[i].u), v = ms.find(d[i].v);
			if(u != v && !d[i].mark) 
			{
				ms.fa[u] = ms.fa[v];
				--connect;
			}
		}

		ms.reset(n, d);
		ques[l].ans = connect;
		return;
	} 

	connect -= contraction(n);
	reduction(n, l, r);

	for(int i = 0; i != n; ++i)
		edge[now + 1][i] = d[i];

	int m = (l + r) >> 1;
	divide(now + 1, n, l, m, connect);
	divide(now + 1, n, m + 1, r, connect);
}
int main(void)
{
  //pentagon graph generation
  //number = # of poles
  hypergraph * H = generatePentagonGraph(7);
  H = sortHyperGraph(H);
  
  displayHyperGraph(H, "H");
  
  //Initialize G with no edges and the same vertices as H
  hypergraph * G = newHyperGraph();
  vertexSet *tmp = H->vertexSets;
  while(tmp != NULL)
  {
    appendUniqueVertexSet(&G->vertexSets, tmp->id);
    tmp = tmp->nextVertex;
  }
  
  printf("\nWorking on reduction...\n\n");
  G = reduction(H, G);
  
  printf("\nReduction complete...\n\n");
  displayHyperGraph(G, "G'");
  
  H = generatePoleGraph(7);
  
  if(isInterConnectionGraphOf(H, G))
    printf("SOLUTION CORRECT\n");
  else
    printf("SOLUTION INCORRECT\n");
  
  //Free Memory
  freeHyperGraph(H);
  freeHyperGraph(G);
  
  return 0;
}
Exemple #20
0
int main()
{
  int *in;
  in = (int *) malloc (sizeof(int) * NUM );

  int i;
  int max = 2147483646;
  int min = 0;
  srand(8650341L);
  for (i = 0; i < NUM; i++)
  {
    in[i] = (int)(min + rand() * 1.0 * (max - min) / (RAND_MAX ));
  }

#ifdef GEM5
  resetGem5Stats();
#endif
  int sum = reduction(&in[0]);
#ifdef GEM5
  dumpGem5Stats("reduction");
#endif
  printf("sum: %d\n", sum);
  return 0;
}
Exemple #21
0
/* Returns the Maximal Correlation Coefficient */
double f14_maxcorr (double **P, int Ng) {
	int i, j, k;
	double *px, *py, **Q;
	double *x, *iy, tmp;
	double f;
	
	px = allocate_vector (0, Ng);
	py = allocate_vector (0, Ng);
	Q = allocate_matrix (1, Ng + 1, 1, Ng + 1);
	x = allocate_vector (1, Ng);
	iy = allocate_vector (1, Ng);
	
	/*
	* px[i] is the (i-1)th entry in the marginal probability matrix obtained
	* by summing the rows of p[i][j]
	*/
	for (i = 0; i < Ng; ++i) {
		for (j = 0; j < Ng; ++j) {
			px[i] += P[i][j];
			py[j] += P[i][j];
		}
	}
	
	/* Find the Q matrix */
	for (i = 0; i < Ng; ++i) {
		for (j = 0; j < Ng; ++j) {
			Q[i + 1][j + 1] = 0;
			for (k = 0; k < Ng; ++k)
				Q[i + 1][j + 1] += P[i][k] * P[j][k] / px[i] / py[k];
		}
	}
	
	/* Balance the matrix */
	mkbalanced (Q, Ng);
	/* Reduction to Hessenberg Form */
	reduction (Q, Ng);
	/* Finding eigenvalue for nonsymetric matrix using QR algorithm */
	if (!hessenberg (Q, Ng, x, iy)) { 
		/* Memmory cleanup */
		for (i=1; i<=Ng+1; i++) free(Q[i]+1);
		free(Q+1);
		free((char *)px);
		free((char *)py);
		free((x+1));
		free((iy+1));
		
		/* computation failed ! */
		return 0.0;
	}
	
	/* simplesrt(Ng,x); */
	/* Returns the sqrt of the second largest eigenvalue of Q */
	for (i = 2, tmp = x[1]; i <= Ng; ++i)
		tmp = (tmp > x[i]) ? tmp : x[i];
	
	f = sqrt(x[Ng - 1]);
	
	for (i=1; i<=Ng+1; i++) free(Q[i]+1);
	free(Q+1);
	free((char *)px); 
	free((char *)py); 
	free((x+1)); 
	free((iy+1)); 
	
	return f;
}
Exemple #22
0
// revised from RTKLIB by T.TAKASU, Japan 
int CLAMBDA::lambda(int n, int m,  std::vector<double> a, std::vector< std::vector<double> > Q, std::vector< std::vector<double> >& F,	 std::vector<double>& s)
{
	//
	//SYNTAX:
	//            ======================================
	//            | [zn,  s]=search( n, m, L, D, zs) |
	//            ======================================
	//      Search m best integer vectors zn and correspondent quadratic residual error was given by s
	//INPUTS:
	//      n: dimension of ambiguity vectors
	//      m: how many ambiguity vectors one want to output, when m=2, zn could given the best and the second best solution  
	//      Q: (co)variance matrices of float ambiguities
	//      a: float  ambiguities
	//OUTPUT:
	//      F: m integer ambiguity vectors
	//      s:   quadratic residual error of m sets ambiguity vectors
	//	revised by D. Xiang on 2014/05/06 in Tongji Univ
	//	email: [email protected]
	//	School.of Surveying and Geoinformatics Engineering,Tongji Univ.,China
	//	Originally written by D. Xiang on 2012 in CASM, Beijing 
	//////////////////////////////////////////////////////////////////////////
	if (n<=0||m<=0) return -1;
	if(F.size()==0)
	{
		F.resize(n);
		for(int i=0;i<n;i++)
			F[i].resize(m);
	}
	if(s.size()==0)
		s.resize(m);

	int info;
	CMatrix mymat;
	std::vector< std::vector<double> > L(n),Z,E(m),ET(n),ZT,Q1;
	std::vector< double > D(n),z(n);
	mymat.zeros(L,n,n); mymat.zeros(Z,n,n);
	mymat.zeros(L,n,n); mymat.eye(Z,n,n);ZT=Z; Q1=Z;
	for(int i=0; i<n; i++) { ET[i].resize(m);} for(int i=0;i<m;i++)E[i].resize(n);
	/* LD factorization 下*对*上*/
	if ((info=LTDLFactorization(n,Q,L,D))) {

		/* lambda reduction */
		reduction(n,L,D,Z);
		//matmul("TN",n,1,n,1.0,Z,a,0.0,z); /* z=Z*a */
		mymat.multip(Z,a,z,n,n);
		/* mlambda search */
		if (!(info=search(n,m,L,D,z,E,s))) 
		{

			//info=solve("T",Z,E,n,m,F); /* F=Z'\E */
			mymat.MatT(E,ET,m,n);
			if(mymat.MatrixSovleDong(Z,ET,F,n,m)==false)
			{
//				AfxMessageBox("Error");
				return -1;
			}

		}
	}
	return info;
}
Exemple #23
0
int main(int argc, char **argv){
  int entries = 10000; // Not divisible
  int p_Nred = 256;
  int reducedEntries = (entries + p_Nred - 1)/p_Nred;

  float *a    = new float[entries];
  float *aRed = new float[reducedEntries];

  float trueRed = 0;

  for(int i = 0; i < entries; ++i){
    a[i]     = 1;
    trueRed += a[i];
  }

  for(int i = 0; i < reducedEntries; ++i)
    aRed[i] = 0;

  occa::device device;
  occa::kernel reduction;
  occa::memory o_a, o_aRed;

  occa::kernelInfo reductionInfo;

  device.setup("mode = Serial");

  o_a  = device.malloc(entries*sizeof(float));
  o_aRed = device.malloc(reducedEntries*sizeof(float));

  reductionInfo.addDefine("p_Nred", p_Nred);

#if 1
  reduction = device.buildKernelFromSource("reduction.okl",
                                           "reduction",
                                           reductionInfo);
#else
  reduction = device.buildKernelFromSource("reduction.cu",
                                           "reduction",
                                           reductionInfo);

  size_t dims     = 1;
  occa::dim inner(p_Nred);
  occa::dim outer((entries + p_Nred - 1) / p_Nred);

  reduction.setWorkingDims(dims, inner, outer);
#endif

  o_a.copyFrom(a);

  occa::initTimer(device);

  occa::tic("reduction");

  reduction(entries, o_a, o_aRed);

  double elapsedTime = occa::toc("reduction", reduction);

  o_aRed.copyTo(aRed);

  std::cout << "Elapsed time = " << elapsedTime << " s" << std::endl;

  occa::printTimer();

  for(int i = 1; i < reducedEntries; ++i)
    aRed[0] += aRed[i];

  if(aRed[0] != trueRed){
    std::cout << "aRed[0] = " << aRed[0] << '\n'
              << "trueRed = " << trueRed << '\n';

    std::cout << "Reduction failed\n";
    throw 1;
  }
  else
    std::cout << "Reduction(a) = " << aRed[0] << '\n';

  delete [] a;
  delete [] aRed;

  reduction.free();
  o_a.free();
  o_aRed.free();

  device.free();

  return 0;
}
Exemple #24
0
bool pinpal(char* dataFile, char* initFile, char* outFile,
	    char* paraFile, bool isInitFile, bool isInitSparse,
	    bool isDataSparse, bool isParameter,
	    rParameter::parameterType parameterType,
	    FILE* Display)
{

  rTimeStart(TOTAL_TIME_START1);
  rTimeStart(FILE_READ_START1);
  rComputeTime com;
  
  FILE* fpData      = NULL;
  FILE* fpOut       = NULL;

  if ((fpOut=fopen(outFile,"w"))==NULL) {
    rError("Cannot open out file " << outFile);
  }
  rParameter param;
  param.setDefaultParameter(parameterType);
  if (isParameter) {
    FILE* fpParameter = NULL;
    if ((fpParameter=fopen(paraFile,"r"))==NULL) {
      fprintf(Display,"Cannot open parameter file %s \n",
	      paraFile);
      exit(0);
    } else {
      param.readFile(fpParameter);
      fclose(fpParameter);
    }
  }
  // param.display(Display);

  if ((fpData=fopen(dataFile,"r"))==NULL) {
    rError("Cannot open data file " << dataFile);
  }
  char titleAndComment[LengthOfBuffer];
  int m;
  time_t ltime;
  time( &ltime );
  fprintf(fpOut,"SDPA start at %s",ctime(&ltime));
  rIO::read(fpData,fpOut,m,titleAndComment);
  fprintf(fpOut,"data      is %s\n",dataFile);
  if (paraFile) {
    fprintf(fpOut,"parameter is %s\n",paraFile);
  }
  if (initFile) {
    fprintf(fpOut,"initial   is %s\n",initFile);
  }
  fprintf(fpOut,"out       is %s\n",outFile);

  int nBlock;
  rIO::read(fpData,nBlock);
  int* blockStruct = NULL;
  blockStruct = new int[nBlock];
  if (blockStruct==NULL) {
    rError("Memory exhausted about blockStruct");
  }
  rIO::read(fpData,nBlock,blockStruct);
  int nDim = 0;
  for (int l=0; l<nBlock; ++l) {
    nDim += abs(blockStruct[l]);
  }
  
  // rMessage("b has not been read yet , m = " << m);
  rVector b(m);
  rIO::read(fpData,b);
  // rMessage("b has been read");
  
  rBlockSparseMatrix C;
  rBlockSparseMatrix* A = NULL;
  A = new rBlockSparseMatrix[m];
  if (A==NULL) {
    rError("Memory exhausted about blockStruct");
  }

  long position = ftell(fpData);
  // C,A must be accessed "twice".

  // count numbers of elements of C and A
  int* CNonZeroCount = NULL;
  CNonZeroCount = new int[nBlock];
  if (CNonZeroCount==NULL) {
    rError("Memory exhausted about blockStruct");
  }
  int* ANonZeroCount = NULL;
  ANonZeroCount = new int[nBlock*m];
  if (ANonZeroCount==NULL) {
    rError("Memory exhausted about blockStruct");
  }
  // initialize C and A
  rIO::read(fpData,m,nBlock,blockStruct,
	    CNonZeroCount,ANonZeroCount,isDataSparse);
  // rMessage(" C and A count over");
    
  C.initialize(nBlock,blockStruct);
  for (int l=0; l<nBlock; ++l) {
    int size = blockStruct[l];
    if (size > 0) {
      C.ele[l].initialize(size,size,rSparseMatrix::SPARSE,
			  CNonZeroCount[l]);
    } else {
      C.ele[l].initialize(-size,-size,rSparseMatrix::DIAGONAL,
			  -size);
    }
  }
  for (int k=0; k<m; ++k) {
    A[k].initialize(nBlock,blockStruct);
    for (int l=0; l<nBlock; ++l) {
      int size = blockStruct[l];
      if (size > 0) {
	A[k].ele[l].initialize(size,size,rSparseMatrix::SPARSE,
			       ANonZeroCount[k*nBlock+l]);
      } else {
	A[k].ele[l].initialize(-size,-size,rSparseMatrix::DIAGONAL,
			       -size);
      }
    }
  }
  delete[] CNonZeroCount;
  CNonZeroCount = NULL;
  delete[] ANonZeroCount;
  ANonZeroCount = NULL;
    
  // rMessage(" C and A initialize over");
  rIO::read(fpData, C, A, m, nBlock, blockStruct, position, isDataSparse);
  // rMessage(" C and A have been read");
  fclose(fpData);

#if 0
  fprintf(Display,"C = \n");
  C.display(Display);
  for (int k=0; k<m; ++k) {
    fprintf(Display,"A[%d] = \n",k);
    A[k].display(Display);
  }
#endif

#if 0
  // write  C and A in SDPA sparse data format to file
  ofstream output;
  output.open("dumped.rsdpa.dat-s");
  if (output.fail()) {
    rError("Cannot Open dumped.rsdpa.dat-s");
  }
  output << m << endl;
  output << nBlock << endl;
  for (l = 0; l<nBlock ; ++l) {
    output << blockStruct[l] << " " ;
  }
  output << endl;
  for (k=0; k<m; ++k) {
	output << b.ele[k] << " ";
  }
  output << endl;
  int index=0;
  for (l=0; l<nBlock; ++l) {
    switch (C.ele[l].Sp_De_Di) {
    case rSparseMatrix::SPARSE:
      for (index = 0; index < C.ele[l].NonZeroCount; ++index) {
	int i = C.ele[l].row_index[index];
	int j = C.ele[l].column_index[index];
	double value = C.ele[l].sp_ele[index];
	if (value!=0.0) {
	  output << "0 " << l+1 << " "
		 << i+1 << " " << j+1 << " "
		 << -value << endl;
	}
      }
      break;
    case rSparseMatrix::DENSE:
      break;
    case rSparseMatrix::DIAGONAL:
      for (int index = 0; index < C.ele[l].nRow; ++index) {
	double value = C.ele[l].di_ele[index];
	if (value!=0.0) {
	  output << "0 " << l+1 << " "
		 << index+1 << " " << index+1 << " "
		 << -value << endl;
	}
      }
	break;
    } // end of switch
  }// end of 'for (int l)'

  for (k=0; k<m; ++k) {
    for (int l=0; l<nBlock; ++l) {
      switch (A[k].ele[l].Sp_De_Di) {
      case rSparseMatrix::SPARSE:
	for (index = 0; index < A[k].ele[l].NonZeroCount; ++index) {
	  int i = A[k].ele[l].row_index[index];
	  int j = A[k].ele[l].column_index[index];
	  double value = A[k].ele[l].sp_ele[index];
	  if (value!=0.0) {
	    output << k+1 << " "  << l+1 << " "
		   << i+1 << " " << j+1 << " "
		   << value << endl;
	  }
	}
	break;
      case rSparseMatrix::DENSE:
	break;
      case rSparseMatrix::DIAGONAL:
	for (int index = 0; index < A[k].ele[l].nRow; ++index) {
	  double value = A[k].ele[l].di_ele[index];
	  if (value!=0.0) {
	    output << k+1 << " " << l+1 << " "
		   << index+1 << " " << index+1 << " "
		   << value << endl;
	  }
	}
	break;
      } // end of switch
    } // end of 'for (int l)'
  } // end of 'for (int k)'
  output.close();
#endif
  
#if 0
  rTimeStart(FILE_CHECK_START1);
  // check whether C,A are symmetric or not.
  int lin,iin,jin;
  if (C.sortSparseIndex(lin,iin,jin)==FAILURE) {
    fprintf(Display,"C is not symmetric, block %d,"
	    "(%d,%d) ", lin+1,iin+1,jin+1);
    exit(0);
  }
  for (int k=0; k<m; ++k) {
    if (A[k].sortSparseIndex(lin,iin,jin)==FAILURE) {
      fprintf(Display,"A[%d] is not symmetric, block %d,"
	      "(%d,%d) ", k+1,lin+1,iin+1,jin+1);
      exit(0);
    }
  }
  rTimeEnd(FILE_CHECK_END1);
  com.FileCheck += rTimeCal(FILE_CHECK_START1,
			    FILE_CHECK_END1);
#endif
  
#if 1
  rTimeStart(FILE_CHANGE_START1);
  // if possible , change C and A to Dense
  C.changeToDense();
  for (int k=0; k<m; ++k) {
    A[k].changeToDense();
  }
  rTimeEnd(FILE_CHANGE_END1);
  com.FileChange += rTimeCal(FILE_CHANGE_START1,
			     FILE_CHANGE_END1);
#endif

  // rMessage("C = ");
  // C.display(Display);
  // for (int k=0; k<m; ++k) {
  //   rMessage("A["<<k<<"] = ");
  //   A[k].display(Display);
  //   }
  
  // the end of initialization of C and A

  // set initial solutions.
  rSolutions initPt;
  rSolutions currentPt;

  if (isInitFile) {
    initPt.initializeZero(m,nBlock,blockStruct,com);
    FILE* fpInit = NULL;
    if ((fpInit=fopen(initFile,"r"))==NULL) {
      rError("Cannot open init file " << initFile);
    }
    rIO::read(fpInit,initPt.xMat,initPt.yVec,initPt.zMat, nBlock,
	      blockStruct, isInitSparse);
    fclose(fpInit);
    initPt.initializeResetup(m,nBlock,blockStruct,com);
    currentPt.copyFrom(initPt);
  } else {
    initPt.initialize(m,nBlock,blockStruct,param.lambdaStar,com);
    currentPt.initialize(m,nBlock,blockStruct,param.lambdaStar,com);
  }
  // rMessage("initial pt = ");
  // initPt.display(Display);
  // rMessage("current pt = ");
  // currentPt.display(Display);
  
  
  rTimeEnd(FILE_READ_END1);
  com.FileRead += rTimeCal(FILE_READ_START1,
			   FILE_READ_END1);

  // -------------------------------------------------------------
  // the end of file read
  // -------------------------------------------------------------
  
  rResiduals initRes(m, nBlock, blockStruct, b, C, A, currentPt);
  rResiduals currentRes;
  currentRes.copyFrom(initRes);
  // rMessage("initial currentRes = ");
  // currentRes.display(Display);

  rNewton newton(m, nBlock, blockStruct);
  newton.computeFormula(m,A,0.0,KAPPA);

  rStepLength alpha(1.0,1.0,nBlock, blockStruct);
  rDirectionParameter beta(param.betaStar);
  rSwitch reduction(rSwitch::ON);
  rAverageComplementarity mu(param.lambdaStar);
  rLanczos lanczos(nBlock,blockStruct);
  
  // rMessage("init mu");
  // mu.display();
  if (isInitFile) {
    mu.initialize(nDim, initPt);
  }
  rRatioInitResCurrentRes theta(param, initRes);
  rSolveInfo solveInfo(nDim, b, C, A, initPt, mu.initial,
		       param.omegaStar);
  rPhase phase(initRes, solveInfo, param, nDim);

  int pIteration = 0;
  rIO::printHeader(fpOut, Display);
  // -----------------------------------------------------
  // Here is MAINLOOP
  // -----------------------------------------------------

  rTimeStart(MAIN_LOOP_START1);

  // explicit maxIteration
  // param.maxIteration = 2;
  while (phase.updateCheck(currentRes, solveInfo, param)
	 && pIteration < param.maxIteration) {
    // rMessage(" turn hajimari " << pIteration );
    // Mehrotra's Predictor
    rTimeStart(MEHROTRA_PREDICTOR_START1);

    // set variable of Mehrotra
    reduction.MehrotraPredictor(phase);
    beta.MehrotraPredictor(phase, reduction, param);
    // rMessage("reduction = ");
    // reduction.display();
    // rMessage("phase = ");
    // phase.display();
    // rMessage("beta.predictor.value = " << beta.value);
    
    // rMessage("xMat = ");
    // currentPt.xMat.display();
    // rMessage("zMat = ");
    // currentPt.zMat.display();
    // rMessage(" mu = " << mu.current);

    bool isSuccessCholesky;
    isSuccessCholesky = newton.Mehrotra(rNewton::PREDICTOR,
					m, A, C, mu,
					beta, reduction,
					phase, currentPt,
					currentRes, com);
    if (isSuccessCholesky == false) {
      break;
    }
      
    // rMessage("newton predictor = ");
    // newton.display();
    // rMessage("newton Dy predictor = ");
    // newton.DyVec.display();
    // newton.bMat.display();
    rTimeEnd(MEHROTRA_PREDICTOR_END1);
    com.Predictor += rTimeCal(MEHROTRA_PREDICTOR_START1,
			      MEHROTRA_PREDICTOR_END1);
    
    rTimeStart(STEP_PRE_START1);
    alpha.MehrotraPredictor(b,C,A, currentPt, phase, newton,
			    lanczos, com);
    // rMessage("xMat = ");
    // currentPt.xMat.display();
    // rMessage("zMat = ");
    // currentPt.zMat.display();
    // rMessage("alpha predictor = ");
    // alpha.display();
    // phase.display();
    // rMessage("newton predictor = ");
    // newton.display();
    // rMessage("currentPt = ");
    // currentPt.display();
    rTimeStart(STEP_PRE_END1);
    com.StepPredictor += rTimeCal(STEP_PRE_START1,STEP_PRE_END1);

    // rMessage("alphaStar = " << param.alphaStar);
    // Mehrotra's Corrector
    // rMessage(" Corrector ");
    rTimeStart(CORRECTOR_START1);
    beta.MehrotraCorrector(nDim,phase,alpha,currentPt,
			   newton,mu,param);
    // rMessage("beta corrector = " << beta.value);
    newton.Mehrotra(rNewton::CORRECTOR,m,A,C,mu,beta,reduction,
		    phase, currentPt, currentRes, com);
    // rMessage("currentPt = ");
    // currentPt.display();
    // rMessage("newton corrector = ");
    // newton.display();
    // rMessage("newton Dy corrector = ");
    // newton.DyVec.display();

    rTimeEnd(CORRECTOR_END1);
    com.Corrector += rTimeCal(CORRECTOR_START1,
			      CORRECTOR_END1);
      
    rTimeStart(CORRECTOR_STEP_START1);
    alpha.MehrotraCorrector(nDim, b, C, A, currentPt, phase,
			    reduction, newton, mu, theta,
			    lanczos, param, com);
    // rMessage("alpha corrector = ");
    // alpha.display();
    rTimeEnd(CORRECTOR_STEP_END1);
    com.StepCorrector += rTimeCal(CORRECTOR_STEP_START1,
				  CORRECTOR_STEP_END1);
    // the end of Corrector
    
    rIO::printOneIteration(pIteration, mu, theta, solveInfo,
			   alpha, beta, currentRes, fpOut, Display);

    if (currentPt.update(alpha,newton,com)==false) {
      // if step length is too short,
      // we finish algorithm
      rMessage("cannot move");
      pIteration++;
      break;
    }

    // rMessage("currentPt = ");
    // currentPt.display();
    // rMessage("newton = ");
    // newton.display();

    // rMessage("updated");
    theta.update(reduction,alpha);
    mu.update(nDim,currentPt);
    currentRes.update(m,nBlock,blockStruct,b,C,A,
		      initRes, theta, currentPt, phase, mu,com);
    
    theta.update_exact(initRes,currentRes);
    solveInfo.update(nDim, b, C, initPt, currentPt,
		     currentRes, mu, theta, param);
    pIteration++;

  } // end of MAIN_LOOP

  rTimeEnd(MAIN_LOOP_END1);

  com.MainLoop = rTimeCal(MAIN_LOOP_START1,
			  MAIN_LOOP_END1);
  currentPt.update_last(com);
  currentRes.compute(m,nBlock,blockStruct,b,C,A,currentPt,mu);
  
  rTimeEnd(TOTAL_TIME_END1);
  
  com.TotalTime = rTimeCal(TOTAL_TIME_START1,
			   TOTAL_TIME_END1);

  #if REVERSE_PRIMAL_DUAL
  phase.reverse();
  #endif
#if 1
  rIO::printLastInfo(pIteration, mu, theta, solveInfo, alpha, beta,
		     currentRes, phase, currentPt, com.TotalTime,
		     nDim, b, C, A, com, param, fpOut, Display);
#endif
  // com.display(fpOut);

  if (blockStruct) {
    delete[] blockStruct;
    blockStruct = NULL;
  }

  C.~rBlockSparseMatrix();
  for (int k=0; k<m; ++k) {
    A[k].~rBlockSparseMatrix();
  }
  delete[] A;
  A = NULL;

  
  fprintf(Display,   "  main loop time = %.6f\n",com.MainLoop);
  fprintf(fpOut,   "    main loop time = %.6f\n",com.MainLoop);
  fprintf(Display,   "      total time = %.6f\n",com.TotalTime);
  fprintf(fpOut,   "        total time = %.6f\n",com.TotalTime);
  #if 0
  fprintf(Display,   "file  check time = %.6f\n",com.FileCheck);
  fprintf(fpOut,   "  file  check time = %.6f\n",com.FileCheck);
  fprintf(Display,   "file change time = %.6f\n",com.FileChange);
  fprintf(fpOut,   "  file change time = %.6f\n",com.FileChange);
  #endif
  fprintf(Display,   "file   read time = %.6f\n",com.FileRead);
  fprintf(fpOut,   "  file   read time = %.6f\n",com.FileRead);
  fclose(fpOut);
  
  return true;
}
Exemple #25
0
// simplex routine
// f is n dimensional function to be minimised, lower and upper are bounds of coordinates for initial vertices
// simplex_goal_size is tolerance for convergene and W is workspace for simplex routine of dimension n
// out termination the vector W->ce will contain coordinates for lowest vertex
int simplex(double f(gsl_vector* x),double lower, double upper, double simplex_goal_size, simplex_workspace* W)
{
	int steps = 0;
	double fp1, fp2, flo, fhi;
	// initialize system by generating vertices and
	// finding their function values
	simplex_generate(lower,upper,W);
	simplex_initialize(f,W);
	do
	{
		// make an update for higher, lower and centroid
		simplex_update(W);
		fhi = gsl_vector_get(W->fp,W->hi);
		flo = gsl_vector_get(W->fp,W->lo);
		// make reflection
		reflection(W);
		fp1 = f(W->p1);
		if (fp1 < flo)
		{
			// if f(reflected) < f(lower) attempt expansion
			expansion(W);
			fp2 = f(W->p2);
			if (fp2 < fp1)
			{
				// if f(expanded) < f(reflecred) accept expansion
				gsl_matrix_set_row(W->simplex,W->hi,W->p2);
				gsl_vector_set(W->fp,W->hi,fp2);
			}
			else
			{
				// if not, accept reflection
				gsl_matrix_set_row(W->simplex,W->hi,W->p1);
				gsl_vector_set(W->fp,W->hi,fp1);
			}
		}
		else
		{
			if (fp1 < fhi)
			{
				// if f(reflected) < f(higher) accept reflection
				gsl_matrix_set_row(W->simplex,W->hi,W->p1);
				gsl_vector_set(W->fp,W->hi,fp1);			
			}
			else
			{
				// if not, attempt contraction
				contraction(W);
				fp2 = f(W->p2);
				if (fp2 < fhi)
				{
					// if f(contracted) < f(higher), accept contraction
					gsl_matrix_set_row(W->simplex,W->hi,W->p2);
					gsl_vector_set(W->fp,W->hi,fp2);
				}
				else
				{
					// if not, we must be in a valley, perform reduction
					reduction(f,W);
				}
			}
		}
	steps++;
	// if simplex has reduced sufficiently, that is size(simplex) < simplex_goal_size
	// convergence is achieved. Return number of steps before convergence.
	} while (simplex_size(W) > simplex_goal_size);
	// copy lowest vertex to centroid vector
	gsl_matrix_get_row(W->ce,W->simplex,W->lo);
	return steps;
}
Exemple #26
0
/**
 * Principle Variation Search (fail-soft)
 * @param alpha lowerbound value
 * @param beta upperbound value
 * @param depth remaining search depth
 * @return score for the current node
 */
int search_t::pvs(int alpha, int beta, int depth) {

    assert(alpha < beta);
    assert(alpha >= -score::INF);
    assert(beta <= score::INF);

    stack->pv_count = 0;
    sel_depth = MAX(brd.ply, sel_depth);
    stack->best_move.clear();

    /*
     * If no more depth remaining, return quiescence value
     */

    if (depth < 1) {
        const int score = qsearch(alpha, beta, 0);
        return score;
    }

    /*
     * Stop conditions
     */

    //time 
    nodes++;
    if (abort()) {
        return alpha;
    }

    //ceiling
    if (brd.ply >= (MAX_PLY - 1)) {
        return evaluate(this);
    }

    assert(depth > 0 && depth <= MAX_PLY);
    int alpha1 = alpha;

    //mate distance pruning: if mate(d) in n don't search deeper
    if ((score::MATE - brd.ply) < beta) {
        beta = score::MATE - brd.ply;
        if (alpha >= beta) {
            return beta;
        }
    }
    if ((-score::MATE + brd.ply) > alpha) {
        alpha = -score::MATE + brd.ply;
        if (beta <= alpha) {
            return alpha;
        }
    }

    //draw by lack of material or fifty quiet moves
    if (is_draw()) {
        return draw_score();
    }

    /*
     * Transposition table lookup
     */

    const bool pv = alpha + 1 < beta;
    stack->tt_key = brd.stack->tt_key; //needed for testing repetitions
    int tt_move = 0, tt_flag = 0, tt_score;
    if (trans_table::retrieve(stack->tt_key, brd.ply, depth, tt_score, tt_move, tt_flag)) {
        if (pv && tt_flag == score::EXACT) {
            return tt_score;
        } else if (!pv && tt_score >= beta && tt_flag == score::LOWERBOUND) {
            return tt_score;
        } else if (!pv && tt_score <= alpha && tt_flag == score::UPPERBOUND) {
            return tt_score;
        }
    }
    stack->tt_move.set(tt_move);

    /*
     * Node pruning
     */

    const bool in_check = stack->in_check;
    const int eval = evaluate(this);
    const bool do_prune_node = eval >= beta && !in_check && !pv && !score::is_mate(beta) && brd.has_pieces(brd.us());

    // beta pruning
    if (do_prune_node && depth < 4 && beta_pruning) {
        int bp_score = eval - 50 * depth;
        if (bp_score >= beta) {
            return bp_score;
        }
    }

    //null move pruning
    if (do_prune_node && null_enabled) {
        int R = 3;
        forward();
        int null_score = -pvs(-beta, -alpha, depth - 1 - R);
        backward();
        if (stop_all) {
            return alpha;
        } else if (null_score >= beta) {
            const int RV = 5;
            if (null_verify && depth > RV && material::is_eg(this)) {
                //verification
                int verified_score = pvs(alpha, beta, depth - 1 - RV);
                if (verified_score >= beta) {
                    return verified_score;
                }
            } else {
                //no verification
                return null_score;
            }
        }
    }

    /*
     * Internal iterative deepening (IID)
     */

    if (pv && depth > 2 && tt_move == 0) {
        int iid_score = pvs(alpha, beta, depth - 2);
        if (score::is_mate(iid_score)) {
            return iid_score;
        } else if (stack->best_move.piece) {
            stack->tt_move.set(&stack->best_move);
        }
    }

    /*
     * Moves loop
     */

    //if there is no first move, it's checkmate or stalemate
    move_t * move = move::first(this, depth);
    if (!move) {
        return in_check ? -score::MATE + brd.ply : draw_score();
    }

    //set futility pruning delta value
    bool do_ffp = false;
    int delta = score::INVALID;
    if (depth <= 8 && !in_check && !score::is_mate(alpha) && !material::is_eg(this) && ffp_enabled) {
        int ffp_score = eval + 40 * depth;
        if (ffp_score <= alpha) {
            do_ffp = true;
            delta = ffp_score + 50;
        }
    }

    //prepare and do the loop
    int best = -score::INF;
    int searched_moves = 0;
    const int score_max = score::MATE - brd.ply - 1;
    stack->best_move.clear();
    do {

        assert(brd.valid(move) && brd.legal(move));
        assert(stack->best_move.equals(move) == false);
        assert(in_searched(move, searched_moves) == false);

        const int gives_check = brd.gives_check(move);
        assert(gives_check == 0 || gives_check == 1 || gives_check == 2);

        /*
         * Move pruning: skip all futile moves
         */

        const bool is_dangerous = in_check || gives_check || move->capture || move->promotion || move->castle || is_advanced_passed_pawn(move);

        bool pruned = false;
        if (do_ffp && searched_moves > 0) {
            pruned = !is_dangerous;
            pruned |= gives_check == 0 && (move->capture || move->promotion) && brd.max_gain(move) + delta <= alpha;
            if (pruned) {
                pruned_nodes++;
                continue;
            }
        }


        /*
         * Move extensions
         */

        int extend = extension(move, depth, pv, gives_check);

        /*
         * Move Reductions (Late Move Reductions, LMR) 
         */

        int reduce = reduction(depth, searched_moves, is_dangerous);

        /*
         * Go forward and search next node
         */

        forward(move, gives_check);
        int score;
        if (searched_moves == 0) {
            score = -pvs(-beta, -alpha, depth - 1 + extend);
        } else {
            score = -pvs(-alpha - 1, -alpha, depth - 1 - reduce + extend);
            if (score > alpha && (pv || reduce > 0)) { //open window research without reductions
                score = -pvs(-beta, -alpha, depth - 1 + extend);
            }
        }
        backward(move);

        /*
         * Handle results: update the best value / do a beta cutoff
         */

        if (stop_all) {
            return alpha;
        } else if (score > best) {
            stack->best_move.set(move);
            if (score >= beta) {
                trans_table::store(stack->tt_key, brd.root_ply, brd.ply, depth, score, move->to_int(), score::LOWERBOUND);
                if (!move->capture && !move->promotion && !move->castle) {
                    update_killers(move);
                    update_history(move);
                    for (int i = 0; i < searched_moves; i++) {
                        move_t * m = &stack->searched[i];
                        if (!m->capture && !m->promotion && !m->castle) {
                            history[m->piece][m->tsq] >>= searched_moves;
                        }
                    }
                }
Exemple #27
0
bool pinpal(char* dataFile, char* initFile, char* outFile,
	    char* paraFile, bool isInitFile, bool isInitSparse,
	    bool isDataSparse, bool isParameter,
	    Parameter::parameterType parameterType,
	    FILE* Display)
{
  TimeStart(TOTAL_TIME_START1);
  TimeStart(FILE_READ_START1);
  ComputeTime com;

  FILE* fpData      = NULL;
  FILE* fpOut       = NULL;

  if ((fpOut=fopen(outFile,"w"))==NULL) {
    rError("Cannot open out file " << outFile);
  }
  Parameter param;
  param.setDefaultParameter(parameterType);
  if (isParameter) {
    FILE* fpParameter = NULL;
    if ((fpParameter=fopen(paraFile,"r"))==NULL) {
      fprintf(Display,"Cannot open parameter file %s \n",
	      paraFile);
      exit(0);
    } else {
      param.readFile(fpParameter);
      fclose(fpParameter);
    }
  }
  
  // param.display(Display,param.infPrint);

  if ((fpData=fopen(dataFile,"r"))==NULL) {
    rError("Cannot open data file " << dataFile);
  }
  char titleAndComment[LengthOfBuffer];
  int m;
  time_t ltime;
  time( &ltime );
  fprintf(fpOut,"SDPA start at %s",ctime(&ltime));
  IO::read(fpData,fpOut,m,titleAndComment);
  fprintf(fpOut,"data      is %s\n",dataFile);
  if (paraFile) {
    fprintf(fpOut,"parameter is %s\n",paraFile);
  }
  if (initFile) {
    fprintf(fpOut,"initial   is %s\n",initFile);
  }
  fprintf(fpOut,"out       is %s\n",outFile);


#if 1 // 2007/11/28 nakata    for multi LP block

  int SDP_nBlock, SOCP_nBlock,LP_nBlock, nBlock;
  IO::read(fpData,nBlock);

  int* blockStruct          = NULL;
  IO::BlockType* blockType  = NULL;
  int* blockNumber          = NULL;
  int* SDP_blockStruct      = NULL;
  int* SOCP_blockStruct     = NULL;
  NewArray(blockStruct,int,nBlock);
  NewArray(blockType,  IO::BlockType, nBlock);
  NewArray(blockNumber,int,nBlock);
  IO::read(fpData,nBlock,blockStruct);

  SDP_nBlock  = 0;
  SOCP_nBlock = 0;
  LP_nBlock   = 0;
  for (int l=0; l<nBlock; l++){
	if (blockStruct[l] >= 2) {
	  blockType[l] = IO::btSDP;
	  blockNumber[l] = SDP_nBlock;
	  SDP_nBlock++;
	} else if (blockStruct[l] < 0) {
	  blockType[l] = IO::btLP;
	  blockStruct[l] = - blockStruct[l];
	  blockNumber[l] = LP_nBlock;
	  LP_nBlock += blockStruct[l];
	} else if (blockStruct[l] == 1) {
	  blockType[l] = IO::btLP;
	  blockNumber[l] = LP_nBlock;
	  LP_nBlock += blockStruct[l];
	} else {
	  rError("block struct");
	}
  }

  NewArray(SDP_blockStruct, int,SDP_nBlock);
  NewArray(SOCP_blockStruct,int,SOCP_nBlock);
  
  SDP_nBlock = 0;
  for (int l=0; l<nBlock; l++){
	if (blockType[l] == IO::btSDP) {
	  SDP_blockStruct[SDP_nBlock] = blockStruct[l];
	  SDP_nBlock++;
	} 
  }

  InputData inputData;
  //  rMessage("read input data: start");
  IO::read(fpData, m, SDP_nBlock, SDP_blockStruct,
	   SOCP_nBlock, SOCP_blockStruct, LP_nBlock,
	   nBlock, blockStruct, blockType, blockNumber,
	   inputData,isDataSparse);
  //  rMessage("read input data: end");
  inputData.initialize_index(SDP_nBlock,SOCP_nBlock,LP_nBlock,com);
#else 

  int SDP_nBlock, SOCP_nBlock,LP_nBlock;
  IO::read(fpData,SDP_nBlock,SOCP_nBlock,LP_nBlock);
  int* SDP_blockStruct;
  int* SOCP_blockStruct;
  NewArray(SDP_blockStruct ,int,SDP_nBlock);
  NewArray(SOCP_blockStruct,int,SOCP_nBlock);
  IO::read(fpData,SDP_nBlock,SDP_blockStruct,
	   SOCP_nBlock,SOCP_blockStruct, LP_nBlock);

  for (int l=0; l<SDP_nBlock-1; l++){
    if (SDP_blockStruct[l] < 0){
      rError("LP block must be in the last block");
    }
  }
  // muriyari nyuuryoku saseru
  if (SDP_blockStruct[SDP_nBlock-1] < 0){
    LP_nBlock = - SDP_blockStruct[SDP_nBlock-1];
    SDP_nBlock--;
  }

  InputData inputData;
  IO::read(fpData, m, SDP_nBlock, SDP_blockStruct,
	   SOCP_nBlock, SOCP_blockStruct, LP_nBlock,
	   inputData,isDataSparse);
  inputData.initialize_index(SDP_nBlock,SOCP_nBlock,LP_nBlock,com);

#endif
  fclose(fpData);
  
  // inputData.display();


#if 1
  TimeStart(FILE_CHANGE_START1);
  // if possible , change C and A to Dense
  inputData.C.changeToDense();
  for (int k=0; k<m; ++k) {
    inputData.A[k].changeToDense();
  }
  TimeEnd(FILE_CHANGE_END1);
  com.FileChange += TimeCal(FILE_CHANGE_START1,
			     FILE_CHANGE_END1);
#endif

  // rMessage("C = ");
  // inputData.C.display(Display);
  // for (int k=0; k<m; ++k) {
  //   rMessage("A["<<k<<"] = ");
  //   inputData.A[k].display(Display);
  //   }
  
  // the end of initialization of C and A

  Newton newton(m, SDP_nBlock, SDP_blockStruct,
		SOCP_nBlock, SOCP_blockStruct,	LP_nBlock);
  int nBlock2 = SDP_nBlock+SOCP_nBlock+LP_nBlock;
  // 2008/03/12 kazuhide nakata
  Chordal chordal;
  // rMessage("ordering bMat: start");
  chordal.ordering_bMat(m, nBlock2, inputData, fpOut);
  // rMessage("ordering bMat: end");
  newton.initialize_bMat(m, chordal,inputData, fpOut);
  chordal.terminate();

  //  rMessage("newton.computeFormula_SDP: start");
  newton.computeFormula_SDP(inputData,0.0,KAPPA);
  //  rMessage("newton.computeFormula_SDP: end");

  // set initial solutions.
  Solutions currentPt;
  WorkVariables work;
  DenseLinearSpace initPt_xMat;
  DenseLinearSpace initPt_zMat;

  currentPt.initialize(m, SDP_nBlock, SDP_blockStruct,
		       SOCP_nBlock, SOCP_blockStruct, LP_nBlock,
		       param.lambdaStar,com);
  work.initialize(m, SDP_nBlock, SDP_blockStruct,
		  SOCP_nBlock, SOCP_blockStruct, LP_nBlock);

  if (isInitFile) {
    FILE* fpInit = NULL;
    if ((fpInit=fopen(initFile,"r"))==NULL) {
      rError("Cannot open init file " << initFile);
    }
    IO::read(fpInit,currentPt.xMat,currentPt.yVec,currentPt.zMat,
	     SDP_nBlock,SDP_blockStruct,
	     SOCP_nBlock,SOCP_blockStruct,
	     LP_nBlock, nBlock, blockStruct,
	     blockType, blockNumber,
	     isInitSparse);
    #if 0
    rMessage("intial X = ");
    currentPt.xMat.display();
    rMessage("intial Z = ");
    currentPt.zMat.display();
    #endif
    fclose(fpInit);
    currentPt.computeInverse(work,com);

    initPt_xMat.initialize(SDP_nBlock, SDP_blockStruct,
			   SOCP_nBlock, SOCP_blockStruct, 
			   LP_nBlock);
    
    initPt_zMat.initialize(SDP_nBlock, SDP_blockStruct,
			   SOCP_nBlock, SOCP_blockStruct, 
			   LP_nBlock);
    initPt_xMat.copyFrom(currentPt.xMat);
    initPt_zMat.copyFrom(currentPt.zMat);

  }
  //  rMessage("initial xMat = "); initPt_xMat.display(Display);
  //  rMessage("initial yVec = "); currentPt.yVec.display(Display);
  //  rMessage("initial zMat = "); initPt_zMat.display(Display);
  //  rMessage("current pt = "); currentPt.display(Display);
  
  TimeEnd(FILE_READ_END1);
  com.FileRead += TimeCal(FILE_READ_START1,
			   FILE_READ_END1);
  // -------------------------------------------------------------
  // the end of file read
  // -------------------------------------------------------------
  
  Residuals initRes(m, SDP_nBlock, SDP_blockStruct,
		    SOCP_nBlock, SOCP_blockStruct,
		    LP_nBlock, inputData, currentPt);
  Residuals currentRes;
  currentRes.copyFrom(initRes);
  // rMessage("initial currentRes = ");
  // currentRes.display(Display);


  StepLength alpha;
  DirectionParameter beta(param.betaStar);
  Switch reduction(Switch::ON);
  AverageComplementarity mu(param.lambdaStar);

  // rMessage("init mu"); mu.display();

  if (isInitFile) {
    mu.initialize(currentPt);
  }

  RatioInitResCurrentRes theta(param, initRes);
  SolveInfo solveInfo(inputData, currentPt, 
			mu.initial, param.omegaStar);
  Phase phase(initRes, solveInfo, param, currentPt.nDim);

  int pIteration = 0;
  IO::printHeader(fpOut, Display);
  // -----------------------------------------------------
  // Here is MAINLOOP
  // -----------------------------------------------------

  TimeStart(MAIN_LOOP_START1);
  // explicit maxIteration for debug
  // param.maxIteration = 2;
  while (phase.updateCheck(currentRes, solveInfo, param)
	 && pIteration < param.maxIteration) {
    // rMessage(" turn hajimari " << pIteration );
    // Mehrotra's Predictor
    TimeStart(MEHROTRA_PREDICTOR_START1);
    // set variable of Mehrotra
    reduction.MehrotraPredictor(phase);
    beta.MehrotraPredictor(phase, reduction, param);

    // rMessage("reduction = "); reduction.display();
    // rMessage("phase = "); phase.display();
    // rMessage("beta.predictor.value = " << beta.value);
    // rMessage(" mu = " << mu.current);
    // rMessage("currentPt = "); currentPt.display();

    bool isSuccessCholesky;
    isSuccessCholesky = newton.Mehrotra(Newton::PREDICTOR,
					inputData, currentPt,
					currentRes,
					mu, beta, reduction,
					phase,work,com);
    if (isSuccessCholesky == false) {
      break;
    }
    // rMessage("newton predictor = "); newton.display();

    TimeEnd(MEHROTRA_PREDICTOR_END1);
    com.Predictor += TimeCal(MEHROTRA_PREDICTOR_START1,
			      MEHROTRA_PREDICTOR_END1);

    TimeStart(STEP_PRE_START1);
    alpha.MehrotraPredictor(inputData, currentPt, phase, newton,
			      work, com);
    // rMessage("alpha predictor = "); alpha.display();

    TimeStart(STEP_PRE_END1);
    com.StepPredictor += TimeCal(STEP_PRE_START1,STEP_PRE_END1);

    // rMessage("alphaStar = " << param.alphaStar);
    // Mehrotra's Corrector
    // rMessage(" Corrector ");

    TimeStart(CORRECTOR_START1);
    beta.MehrotraCorrector(phase,alpha,currentPt, newton,mu,param);

    // rMessage("beta corrector = " << beta.value);

#if 1 // 2007/08/29 kazuhide nakata
    // add stopping criteria: objValPrimal < ObjValDual
    //	if ((pIteration > 10) &&
    if (phase.value == SolveInfo::pdFEAS
	&& ( beta.value> 5.0
	     || solveInfo.objValPrimal < solveInfo.objValDual)){
      break;
    }
#endif

    newton.Mehrotra(Newton::CORRECTOR,
		    inputData, currentPt, currentRes,
		    mu, beta, reduction, phase,work,com);

    // rMessage("currentPt = "); currentPt.display();
    // rMessage("newton corrector = "); newton.display();

    TimeEnd(CORRECTOR_END1);
    com.Corrector += TimeCal(CORRECTOR_START1,
			      CORRECTOR_END1);
    TimeStart(CORRECTOR_STEP_START1);
    alpha.MehrotraCorrector(inputData, currentPt, phase,
			    reduction, newton, mu, theta,
			    work, param, com);
    // rMessage("alpha corrector = "); alpha.display();
    TimeEnd(CORRECTOR_STEP_END1);
    com.StepCorrector += TimeCal(CORRECTOR_STEP_START1,
				  CORRECTOR_STEP_END1);
    // the end of Corrector
    
    IO::printOneIteration(pIteration, mu, theta, solveInfo,
			   alpha, beta, fpOut, Display);

    if (currentPt.update(alpha,newton,work,com)==false) {
      // if step length is too short,
      // we finish algorithm
      rMessage("cannot move: step length is too short");
      //   memo by kazuhide nakata
      //   StepLength::MehrotraCorrector
      //   thetaMax*mu.initial -> thetamax*thetaMax*mu.initial
      break;
    }

    // rMessage("currentPt = "); currentPt.display();
    // rMessage("updated");

    theta.update(reduction,alpha);
    mu.update(currentPt);
    currentRes.update(m,inputData, currentPt, com);
    theta.update_exact(initRes,currentRes);

    if (isInitFile) {
      solveInfo.update(inputData, initPt_xMat, initPt_zMat, currentPt,
		       currentRes, mu, theta, param);
    } else {
      solveInfo.update(param.lambdaStar,inputData, currentPt,
		       currentRes, mu, theta, param);
    }
    // 2007/09/18 kazuhide nakata
    // print information of ObjVal, residual, gap, complementarity
    // solveInfo.check(inputData, currentPt,
    //                 currentRes, mu, theta, param);
    pIteration++;
  } // end of MAIN_LOOP

  TimeEnd(MAIN_LOOP_END1);

  com.MainLoop = TimeCal(MAIN_LOOP_START1,
			  MAIN_LOOP_END1);
  currentRes.compute(m,inputData,currentPt);
  TimeEnd(TOTAL_TIME_END1);
  
  com.TotalTime = TimeCal(TOTAL_TIME_START1,
			   TOTAL_TIME_END1);
  #if REVERSE_PRIMAL_DUAL
  phase.reverse();
  #endif
#if 1
  IO::printLastInfo(pIteration, mu, theta, solveInfo, alpha, beta,
		    currentRes, phase, currentPt, com.TotalTime,
			nBlock, blockStruct, blockType, blockNumber,
		    inputData, work, com, param, fpOut, Display);
#else
  IO::printLastInfo(pIteration, mu, theta, solveInfo, alpha, beta,
		    currentRes, phase, currentPt, com.TotalTime,
		    inputData, work, com, param, fpOut, Display);
#endif
  // com.display(fpOut);

  DeleteArray(SDP_blockStruct);
  DeleteArray(blockStruct);
  DeleteArray(blockType);
  DeleteArray(blockNumber);
  
  fprintf(Display,   "  main loop time = %.6f\n",com.MainLoop);
  fprintf(fpOut,   "    main loop time = %.6f\n",com.MainLoop);
  fprintf(Display,   "      total time = %.6f\n",com.TotalTime);
  fprintf(fpOut,   "        total time = %.6f\n",com.TotalTime);
  #if 0
  fprintf(Display,   "file  check time = %.6f\n",com.FileCheck);
  fprintf(fpOut,   "  file  check time = %.6f\n",com.FileCheck);
  fprintf(Display,   "file change time = %.6f\n",com.FileChange);
  fprintf(fpOut,   "  file change time = %.6f\n",com.FileChange);
  #endif
  fprintf(Display,   "file   read time = %.6f\n",com.FileRead);
  fprintf(fpOut,   "  file   read time = %.6f\n",com.FileRead);
  fclose(fpOut);


#if 0
  rMessage("memory release");
  currentRes.terminate();
  initRes.terminate();
  currentPt.terminate();
  initPt_xMat.terminate();
  initPt_zMat.terminate();
  newton.terminate();
  work.terminate();
  inputData.terminate();
  com.~ComputeTime();
  param.~Parameter();
  alpha.~StepLength();
  beta.~DirectionParameter();
  reduction.~Switch();
  mu.~AverageComplementarity();
  theta.~RatioInitResCurrentRes();
  solveInfo.~SolveInfo();
  phase.~Phase();
#endif

  return true;
}
DiagramWidget::DiagramWidget(QWidget *parent) :
    QWidget(parent)
{
    tableWidget=new QTableWidget();
    QStringList list;
    list.append(tr("Type"));
    list.append(tr("Record Date"));
    list.append(tr("Time"));
    list.append(tr("Selected Value"));
    list.append(tr("Unit"));
    list.append(tr("Maximum Value"));
    list.append(tr("Minimum Value"));
    list.append(tr("Average Value"));
    list.append(tr("Upper Limit"));
    list.append(tr("Lower Limit"));
    list.append(tr("Number"));
    tableWidget->setColumnCount(11);
    tableWidget->setRowCount(2);
    tableWidget->setHorizontalHeaderLabels(list);
    tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);

    tableWidget->setItem(0,0,new QTableWidgetItem(tr("Temperature")));
    tableWidget->setItem(1,0,new QTableWidgetItem(tr("Humidity")));
    tableWidget->setItem(0,4,new QTableWidgetItem("°C"));
    tableWidget->setItem(1,4,new QTableWidgetItem("%RH"));

    bigAct=new QAction(QIcon(":/png/png/big"),"",0);
    smallAct=new QAction(QIcon(":/png/png/small"),"",0);
    reductionAct=new QAction(QIcon(":/png/png/back"),"",0);
    radioRB1=new QRadioButton(tr("Temperature+Humidity"));
    radioRB2=new QRadioButton(tr("Temperature"));
    radioRB3=new QRadioButton(tr("Humidity"));
    radioRB1->setChecked(true);
    bigAct->setToolTip(tr("curves zoom out"));
    smallAct->setToolTip(tr("curves zoom in"));
    reductionAct->setText(tr("Rstore"));

    QToolBar *toolBar=new QToolBar();
    toolBar->addSeparator();
    toolBar->addAction(bigAct);
    toolBar->addAction(smallAct);
    toolBar->addAction(reductionAct);
    toolBar->addSeparator();
    toolBar->addWidget(radioRB1);
    toolBar->addWidget(radioRB2);
    toolBar->addWidget(radioRB3);

    customPlot=new QCustomPlot();
    customPlot->legend->setVisible(true);
    customPlot->legend->setIconSize(10,5);
    customPlot->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignTop|Qt::AlignLeft);
    customPlot->setInteractions(QCP::iRangeDrag|QCP::iRangeZoom);
    customPlot->addGraph();
    customPlot->addGraph();
    customPlot->addGraph();
    customPlot->addGraph();
    customPlot->addGraph();
    customPlot->addGraph();
    customPlot->addGraph();
    customPlot->graph(0)->setName(tr("Temperature"));
    customPlot->graph(1)->setName(tr("Humidity"));
    QPen pen;
    pen.setWidth(2);
    pen.setColor(QColor(0,0,255));
    customPlot->graph(0)->setPen(pen);
    pen.setColor(QColor(0,128,0));
    customPlot->graph(1)->setPen(pen);
    pen.setColor(QColor(128,64,0));
    pen.setWidth(1);
    customPlot->graph(2)->setPen(pen);
    pen.setColor(QColor(255,0,0));
    pen.setStyle(Qt::DashLine);
    customPlot->graph(3)->setPen(pen);
    customPlot->graph(4)->setPen(pen);
    pen.setColor(QColor(255,0,255));
    customPlot->graph(5)->setPen(pen);
    customPlot->graph(6)->setPen(pen);
//    customPlot->graph(2)->setVisible(false);
    customPlot->xAxis->setTickLabelType(QCPAxis::ltDateTime);
    QString format=QString("%1\n%2").arg(_dateFormat).arg(_timeFormat);
    customPlot->xAxis->setDateTimeFormat(format);
    customPlot->xAxis->setAutoTickStep(false);
    customPlot->legend->removeAt(2);
    customPlot->legend->removeAt(3);
    customPlot->legend->removeAt(4);
    customPlot->legend->removeAt(5);
    customPlot->legend->removeAt(6);

    QVBoxLayout *hLayout=new QVBoxLayout(this);
    hLayout->addWidget(toolBar);
    hLayout->addWidget(customPlot,5);
    hLayout->addWidget(tableWidget,1);


    //信号/槽
    connect(reductionAct,SIGNAL(triggered()),this,SLOT(reduction()));
    connect(customPlot,SIGNAL(mouseMove(QMouseEvent*)),this,SLOT(mousemoved(QMouseEvent*)));
    connect(customPlot,SIGNAL(mousePress(QMouseEvent*)),this,SLOT(mousePress(QMouseEvent*)));
    connect(radioRB1,SIGNAL(clicked()),this,SLOT(showAll()));
    connect(radioRB2,SIGNAL(clicked()),this,SLOT(showTemperature()));
    connect(radioRB3,SIGNAL(clicked()),this,SLOT(showHumidity()));
    connect(bigAct,SIGNAL(triggered()),this,SLOT(bigAct_trogged()));
    connect(smallAct,SIGNAL(triggered()),this,SLOT(smallAct_trogged()));
}