Exemplo n.º 1
0
// Matrix-Vector algorithm for multiplying matrices
void mat_vec(float* A, float* B, int m, int p, int n, float* C)
{
  float* x = (float*) calloc(p,sizeof(float));
  float* y = (float*) calloc(m,sizeof(float));
  
  // If memory allocation fails then exit with error
  if(x == NULL || y == NULL) { exit(1); }
  
  int j;
  
  // Loop through columns of B
  for(j=0; j < n; j++)
  {
    // Get column j of B and load into x
    get_col(B,p,n,j,x);
      
    // Get column j of C and load into y
    get_col(C,m,n,j,y);
      
    // Saxpy level 2 operation y <- alpha*A*x + y
    cblas_sgemv(CblasRowMajor,CblasNoTrans,m,p,1.0,A,p,x,1,1.0,y,1);
      
    // Set column j of C to y
    set_col(C,m,n,j,y);
  }

  // Free intermediate values
  free(x);
  free(y);
}
Exemplo n.º 2
0
Arquivo: svd.c Projeto: Rainwin2015/C
MAT	*bifactor(MAT *A, MAT *U, MAT *V)
#endif
{
	int	k;
	STATIC VEC	*tmp1=VNULL, *tmp2=VNULL, *w=VNULL;
	Real	beta;

	if ( ! A )
		error(E_NULL,"bifactor");
	if ( ( U && ( U->m != U->n ) ) || ( V && ( V->m != V->n ) ) )
		error(E_SQUARE,"bifactor");
	if ( ( U && U->m != A->m ) || ( V && V->m != A->n ) )
		error(E_SIZES,"bifactor");
	tmp1 = v_resize(tmp1,A->m);
	tmp2 = v_resize(tmp2,A->n);
	w    = v_resize(w,   max(A->m,A->n));
	MEM_STAT_REG(tmp1,TYPE_VEC);
	MEM_STAT_REG(tmp2,TYPE_VEC);
	MEM_STAT_REG(w,   TYPE_VEC);

	if ( A->m >= A->n )
	    for ( k = 0; k < A->n; k++ )
	    {
		get_col(A,k,tmp1);
		hhvec(tmp1,k,&beta,tmp1,&(A->me[k][k]));
		_hhtrcols(A,k,k+1,tmp1,beta,w);
		if ( U )
		    _hhtrcols(U,k,0,tmp1,beta,w);
		if ( k+1 >= A->n )
		    continue;
		get_row(A,k,tmp2);
		hhvec(tmp2,k+1,&beta,tmp2,&(A->me[k][k+1]));
		hhtrrows(A,k+1,k+1,tmp2,beta);
		if ( V )
		    _hhtrcols(V,k+1,0,tmp2,beta,w);
	    }
	else
	    for ( k = 0; k < A->m; k++ )
	    {
		get_row(A,k,tmp2);
		hhvec(tmp2,k,&beta,tmp2,&(A->me[k][k]));
		hhtrrows(A,k+1,k,tmp2,beta);
		if ( V )
		    _hhtrcols(V,k,0,tmp2,beta,w);
		if ( k+1 >= A->m )
		    continue;
		get_col(A,k,tmp1);
		hhvec(tmp1,k+1,&beta,tmp1,&(A->me[k+1][k]));
		_hhtrcols(A,k+1,k+1,tmp1,beta,w);
		if ( U )
		    _hhtrcols(U,k+1,0,tmp1,beta,w);
	    }

#ifdef	THREADSAFE
	V_FREE(tmp1);	V_FREE(tmp2);
#endif

	return A;
}
Exemplo n.º 3
0
Arquivo: tetris.c Projeto: seL4/refos
/*! @brief Update game state forward a frame. */
void
game_frame(int c)
{
    int j;
    int *backup;

    if (c == 0) {
        if (fits_in (shape, pos + B_COLS)) {
            pos += B_COLS;
        } else {
            place(shape, pos, get_col(shape));
            ++points;
            for (j = 0; j < 252; j = B_COLS * (j / B_COLS + 1)) {
                for (; board[++j];) {
                    if (j % B_COLS == 10) {
                        linesCleared++;

                        for (; j % B_COLS; board[j--] = 0);
                        update();
                        for (; --j; board[j + B_COLS] = board[j]);
                        update();
                    }
                }
            }
            shape = next_shape();
            if (!fits_in (shape, pos = 17)) c = keys[KEY_QUIT];
        }
    }

    if (c == keys[KEY_LEFT]) {
        if (!fits_in (shape, --pos)) ++pos;
    }
    if (c == keys[KEY_ROTATE]) {
        backup = shape;
        shape = &shapes[4 * *shape]; /* Rotate */
        /* Check if it fits, if not restore shape from backup. */
        if (!fits_in (shape, pos)) shape = backup;
    }

    if (c == keys[KEY_RIGHT]) {
        if (!fits_in (shape, ++pos)) --pos;
    }
    if (c == keys[KEY_DROP]) {
        for (; fits_in (shape, pos + B_COLS); ++points) pos += B_COLS;
    }
    if (c == keys[KEY_PAUSE] || c == keys[KEY_QUIT]) {
        exitGame = 1;
        return;
    }

    place(shape, pos, get_col(shape));
    update();
    place(shape, pos, RESETATTR);
}
void print_distribution (Triplet min, Triplet max, Triplet data, int width, char limit, char sensor)
{
  mvaddch(3, get_col (width, min.x), limit);
  mvaddch(3, get_col (width, data.x), sensor);
  mvaddch(3, get_col (width, max.x), limit);
  mvaddch(4, get_col (width, min.y), limit);
  mvaddch(4, get_col (width, data.y), sensor);
  mvaddch(4, get_col (width, max.y), limit);
  mvaddch(5, get_col (width, min.z), limit);
  mvaddch(5, get_col (width, data.z), sensor);
  mvaddch(5, get_col (width, max.z), limit);
}
Exemplo n.º 5
0
 sf::IntRect Spritesheet::_get_rect(int frame)
 {
     return sf::IntRect(
         get_col(frame, _cols) * _tile_width,
         get_row(frame, _cols) * _tile_height,
         _tile_width, _tile_height);
 }
Exemplo n.º 6
0
/** @brief Swaps the OpenGL buffer.
 */
void gl_swap(void) {
	static Uint32 last = 0;
	Uint32 now;

	if (fps_enabled) {
		char fps_s[16];

		snprintf(fps_s, 16, "FPS: %.2f", fps);
		text_draw_string(10, 10, fps_s, 1, get_col(COL_RED));
	}

	blit_fbo();

	now = SDL_GetTicks();
	if (now - last < 1000 / FPS)
		SDL_Delay(1000 / FPS - (now - last));
	last = SDL_GetTicks();

	frames++;
	if (frames == 10) {
		fps = 10000 / (float)(now - fps_time);
		frames = 0;
		fps_time = now;
	}
}
Exemplo n.º 7
0
int null_spielen(Player *p, Game *g) {
	//Null (selbst):
	//-zwingend: auf jeder farbe die 7 (oder blank, notfalls auch eine blanke 8/9) (wenn nur eine farbe nicht passt -> auf skat reizen?)
	//-wenn auf jeder farbe 7,9,B,K (oder besser, oder blank): dann null hand/ouvert
	//-7,9,D,K,A auf einer Farbe auch okay (also wenn farbe sehr lang, dann können auch tiefe karten fehlen)
	int ret = 47;
	int risk = 0;
	for(int i = 0; i < 4; i++) {
		if(!player_has_card(p, get_card(i, SIEBEN)) && !blank(p, i) && !(length_of_color(p, i) == 1 && (player_has_card(p, get_card(i, NEUN)) || player_has_card(p, get_card(i, ACHT)))))
			risk += length_of_color(p, i);
		int val = 0;
		for(int j = 0; j < p->hcardcount; j++)
			if(get_col(p->hand[j]) == i)
				val += get_val(p->hand[j]);
		int min_val[] = {0, 7, 12, 15, 16, 15, 18, 22, 0};
		if(val < min_val[length_of_color(p,i)])
			ret = 23;
	}
	
	if(risk == 0) { //keine unsicheren Karten -> Hand
		ret += 12;
	}
	if(risk < 3) return ret; //max 2 unsichere Karten
	return 0;
}
Exemplo n.º 8
0
// returns 0 if solved > 0 otherwise
int unsolved(oku_sod* sod){
	int i,j,size = sod->size, score=0;
	//occurance counters
	int row[size+1][size+1],col[size+1][size+1],blk[size+1][size+1];
	//initialize counters
	for(i=0;i<size+1;i++)
		for(j=1;j<size+1;j++){
			row[i][j] = 0;
			col[i][j] = 0;
			blk[i][j] = 0;
		}
	// count occurances
	for(i=0;i<size;i++)
		for(j=0;j<size;j++){
			row[i][get_row(sod,i,j)]++;
			col[i][get_col(sod,i,j)]++;
			blk[i][get_blk(sod,i,j)]++;
		}
	for(i=0;i<size;i++)
		for(j=1;j<size+1;j++){
			score += row[i][j] > 1 ? 1 : 0;
			score += col[i][j] > 1 ? 1 : 0;
			score += blk[i][j] > 1 ? 1 : 0;
		 }
	return score;
}
bool
AsciiProcessor::background_color_cmd( const char * buf,
                                      BuilderBase * build,
                                      const char* & next )
{
    RGBcolor col;

    if ( ! get_col( buf, col, next ) )
    {
        P_ERROR( "wrong color [" << buf << "]" );
        return false;
    }

    buf = next;

    if ( ! strskip( buf, DELIMITER_CHAR, next ) )
    {
        P_ERROR( "wrong delimiter char" );
        return CMD_ERR;
    }

    build->set_cmd_set_background_color( col );

    return CMD_OK;
}
Exemplo n.º 10
0
int get_cols(uchar **row,uchar *fmt,...) {
    int cnt=0;
    va_list va;
    void *p;
    va_start(va,fmt);
    while(*fmt) {
        uchar *col;
        p = va_arg(va,void*);
        //if (*row[0]==0) return cnt; // eof ???
        col = get_col(row);
        //printf("EX:%c,COL:%s\n",*fmt,col);
        switch(*fmt) {
        case 'i':
            if (sscanf(col,"%d",(int*)p)!=1) return -2;
            break;
        case 's':
            c_decode(col,col,-1); // decode C constructs
            *(uchar**)p=col; // remember it here
            break;
        default:
            return -1; // unknown format
        }
        fmt++;
        cnt++;
    }
    va_end(va);
    return cnt;
}
Exemplo n.º 11
0
 void set_cols(int start_col, int end_col, const mat& pmat){
   assert(start_col >= 0);
   assert(end_col <= end_offset - start_offset);
   assert(pmat.rows() == end-start);
   assert(pmat.cols() >= end_col - start_col);
   for (int i=start_col; i< end_col; i++)
     this->operator[](i) = get_col(pmat, i-start_col);
 }
Exemplo n.º 12
0
int choose_card_null(Player *p, Game *g) {
	int c = 0;
	//Wenn Vorhand, spiele niedrigste Karte
	if(g->p[g->vorhand] == p) {
		for(int i = 0; i < p->hcardcount; i++) {
			if(get_val(p->hand[c]) < get_val(p->hand[i]))
				c = i;
		}
		return c;
	}
	
	//Wenn Farbe bekannt werden muss, wähle größtmögliche Karte ohne den Stich zu bekommen oder niedrigste Karte
	c = -1;
	for(int i = 0; i < p->hcardcount; i++) {
		if(get_col(p->hand[i]) == get_col(g->card[g->vorhand])) {
			if(c == -1) c = i;
			else {
				switch(higher(g, p->hand[i], p->hand[c])) {
					case 1:
					if(higher(g, p->hand[i], g->card[g->vorhand]) != 1 || (p != g->p[(g->vorhand+1)%3] && higher(g, p->hand[i], g->card[(g->vorhand+1)%3]) != 1))
						c = i;
					break;
					
					case -1:
					if(higher(g, p->hand[c], g->card[g->vorhand]) == 1 && (p == g->p[(g->vorhand+1)%3] || higher(g, p->hand[c], g->card[(g->vorhand+1)%3]) == 1))
						c = i;
					break;
				}
			}
		}
	}
	if(c >= 0) return c;
	
	//Sonst: wähle höchste farbfremde Karte
	c = 0;
	for(int i = 1; i < p->hcardcount; i++) {
		if(get_val(p->hand[i]) < get_val(p->hand[c]))
			c = i;
	}
	
	return c;
}
Exemplo n.º 13
0
void Sheet::get_cols (const int start_col, const int end_col, char***& cols)
{
    int nc = end_col - start_col + 1;
    cols = (char***)malloc ((nc+1)*sizeof(char**));

    for (int i = 1;  i <= nc;  i++)
    {
	int nr;
	get_col (i+start_col-1, cols[i], nr);
    }
}
Exemplo n.º 14
0
Arquivo: excel.c Projeto: rajul/POJ
int main(int argc, char *argv[])
{
	int i, l;
	char input[50];
	char col_name[30];
	long row, col;

	fill_alphabets();
	fill_permutation_sizes();
	fill_permutation_range_limits();


	for(i=0; i<26; i++)
		printf("%c ", alphabets[i]);

	printf("\n");

	for(i=0; i<6; i++)
		printf("%ld\n", permutation_sizes[i]);

	printf("\n");

	for(i=0; i<6; i++)
		printf("%ld\n", permutation_ranges_limits[i]);

	while(1)
	{
		scanf("%s", input);

		if(strcmp(input, "R0C0") == 0)
			break;

		printf("Input String: %s\n", input);

		row = get_row(input);
		col = get_col(input);

		get_col_name(col, col_name);

		printf("Row: %ld\n", row);
		printf("Col: %ld\n", col);

		int l = strlen(col_name);

		for(i=(l-1); i>=0; i--)
			printf("%c", col_name[i]);
		
		printf("%ld\n", row);
	}

	return 0;
}
Exemplo n.º 15
0
void exchange_cards_null(Player *p, Game *g) {
	//skat aufnehmen
	p->hand[10] = g->skat[0];
	p->hand[11] = g->skat[1];
	p->hcardcount = 12;
	for(; p->hcardcount > 10; --p->hcardcount) {
		int c = -1;

		//Risikofarbe suchen
		//dabei wird der wert jeder Karte (ass = 0 … sieben = 7) quadriert
		//und durch die anzahl der Karten der Farbe +1 geteilt
		//die Farbe mit dem geringsten Wert ist ein Risiko
		int col_risk = 0;
		float val_risk = 100.0;
		for(int col = 0; col < 4; ++col) {
			int val = 0;
			for(int j = 0; j < p->hcardcount; j++)
				if(get_col(p->hand[j]) == col)
					val += get_val(p->hand[j]);
			float risk = (float)(val*val+1)/((float)length_of_color(p, col)+1.0);
			if(val_risk > risk && risk != 0) {
				val_risk = risk;
				col_risk = col;
			}
		}
		
		//höchste Karte der Risikofarbe in den Skat
		for(int i = 0; i < p->hcardcount; ++i) {
			if(get_col(p->hand[i]) == col_risk) {
				if(c == -1) c = i;
				else if(get_val(p->hand[i]) < get_val(p->hand[c]))
					c = i;
			}
		}
		
		g->skat[p->hcardcount-10] = p->hand[c];
		p->hand[c] = p->hand[p->hcardcount-1];
	}
}
Exemplo n.º 16
0
static MAT *calc_VinvIminAw(MAT *Vw, MAT *X, MAT *VinvIminAw, int calc_Aw) {
/*
 * calculate V_w^-1(I-A_w) (==VinvIminAw),
 * A = X(X'X)^-1 X' (AY = XBeta; Beta = (X'X)^-1 X'Y)
 *
 * on second thought (Nov 1998 -- more than 4 years later :-))
 * calc (I-Aw) only once and keep this constant during iteration.
 */
 	MAT *tmp = MNULL, *V = MNULL;
 	VEC *b = VNULL, *rhs = VNULL;
 	int i, j;

	if (X->m != Vw->n || VinvIminAw->m != X->m)
		ErrMsg(ER_IMPOSVAL, "calc_VinvIminAw: sizes don't match");
	
	if (calc_Aw) {
		IminAw = m_resize(IminAw, X->m, X->m);
		tmp = m_resize(tmp, X->n, X->n);
		tmp = mtrm_mlt(X, X, tmp); /* X'X */
		m_inverse(tmp, tmp); /* (X'X)-1 */
		/* X(X'X)-1 -> X(X'X)-1 X') */
		IminAw = XVXt_mlt(X, tmp, IminAw);
		for (i = 0; i < IminAw->m; i++) /* I - Aw */
			for (j = 0; j <= i; j++)
				if (i == j)
					IminAw->me[i][j] = 1.0 - IminAw->me[i][j];
				else
					IminAw->me[i][j] = IminAw->me[j][i] = -IminAw->me[i][j];
	}

	V = m_copy(Vw, V);
	LDLfactor(V);

	rhs = v_resize(rhs, X->m);
	b = v_resize(b, X->m);

	for (i = 0; i < X->m; i++) { /* solve Vw X = (I-A) for X -> V-1(I-A) */
		rhs = get_col(IminAw, i, rhs);
		LDLsolve(V, rhs, b);
		set_col(VinvIminAw, i, b);
	}
	v_free(rhs);
	v_free(b);
	m_free(V);

	if (tmp) 
		m_free(tmp);

	return VinvIminAw;
}
Exemplo n.º 17
0
MAT	*makeQ(const MAT *QR,const VEC *diag, MAT *Qout)
#endif
{
    STATIC	VEC	*tmp1=VNULL,*tmp2=VNULL;
    unsigned int	i, limit;
    Real	beta, r_ii, tmp_val;
    int	j;
    
    limit = min(QR->m,QR->n);
    if ( ! QR || ! diag )
	error(E_NULL,"makeQ");
    if ( diag->dim < limit )
	error(E_SIZES,"makeQ");
    if ( Qout==(MAT *)NULL || Qout->m < QR->m || Qout->n < QR->m )
	Qout = m_get(QR->m,QR->m);
    
    tmp1 = v_resize(tmp1,QR->m);	/* contains basis vec & columns of Q */
    tmp2 = v_resize(tmp2,QR->m);	/* contains H/holder vectors */
    MEM_STAT_REG(tmp1,TYPE_VEC);
    MEM_STAT_REG(tmp2,TYPE_VEC);
    
    for ( i=0; i<QR->m ; i++ )
    {	/* get i-th column of Q */
	/* set up tmp1 as i-th basis vector */
	for ( j=0; j<QR->m ; j++ )
	    tmp1->ve[j] = 0.0;
	tmp1->ve[i] = 1.0;
	
	/* apply H/h transforms in reverse order */
	for ( j=limit-1; j>=0; j-- )
	{
	    get_col(QR,j,tmp2);
	    r_ii = fabs(tmp2->ve[j]);
	    tmp2->ve[j] = diag->ve[j];
	    tmp_val = (r_ii*fabs(diag->ve[j]));
	    beta = ( tmp_val == 0.0 ) ? 0.0 : 1.0/tmp_val;
	    /* hhtrvec(tmp2,beta->ve[j],j,tmp1,tmp1); */
	    hhtrvec(tmp2,beta,j,tmp1,tmp1);
	}
	
	/* insert into Q */
	set_col(Qout,i,tmp1);
    }

#ifdef	THREADSAFE
    V_FREE(tmp1);	V_FREE(tmp2);
#endif

    return (Qout);
}
Exemplo n.º 18
0
// Saxpy operations for multiplying matrices
void mat_saxpy(float* A, float* B, int m, int p, int n, float* C)
{
  float* x = (float*) calloc(m,sizeof(float));
  float* y = (float*) calloc(m,sizeof(float));
  
  // If memory allocation fails then exit with error
  if(x == NULL || y == NULL) { exit(1); }
  
  int j,k;
  
  // Loop through columns of B
  for(j=0; j < n; j++)
  {
    // Loop through columns of A
    for(k=0; k < p; k++)
    {
      // Get column k of A and load into x
      get_col(A,m,p,k,x);
      
      // Get column j of C and load into y
      get_col(C,m,n,j,y);
      
      // Get alpha
      float alpha = B[k*n+j];
      
      // Saxpy level 1 operation y <- alpha*x + y
      cblas_saxpy(m,alpha,x,1,y,1);
      
      // Set column j of C to y
      set_col(C,m,n,j,y);
    }
  }

  // Free intermediate values
  free(x);
  free(y);
}
Exemplo n.º 19
0
MAT	*makeHQ(MAT *H, VEC *diag, VEC *beta, MAT *Qout)
#endif
{
	int	i, j, limit;
	STATIC	VEC	*tmp1 = VNULL, *tmp2 = VNULL;

	if ( H==(MAT *)NULL || diag==(VEC *)NULL || beta==(VEC *)NULL )
		error(E_NULL,"makeHQ");
	limit = H->m - 1;
	if ( diag->dim < limit || beta->dim < limit )
		error(E_SIZES,"makeHQ");
	if ( H->m != H->n )
		error(E_SQUARE,"makeHQ");
	Qout = m_resize(Qout,H->m,H->m);

	tmp1 = v_resize(tmp1,H->m);
	tmp2 = v_resize(tmp2,H->m);
	MEM_STAT_REG(tmp1,TYPE_VEC);
	MEM_STAT_REG(tmp2,TYPE_VEC);

	for ( i = 0; i < H->m; i++ )
	{
		/* tmp1 = i'th basis vector */
		for ( j = 0; j < H->m; j++ )
			/* tmp1->ve[j] = 0.0; */
		    v_set_val(tmp1,j,0.0);
		/* tmp1->ve[i] = 1.0; */
		v_set_val(tmp1,i,1.0);

		/* apply H/h transforms in reverse order */
		for ( j = limit-1; j >= 0; j-- )
		{
			get_col(H,(unsigned int)j,tmp2);
			/* tmp2->ve[j+1] = diag->ve[j]; */
			v_set_val(tmp2,j+1,v_entry(diag,j));
			hhtrvec(tmp2,beta->ve[j],j+1,tmp1,tmp1);
		}

		/* insert into Qout */
		set_col(Qout,(unsigned int)i,tmp1);
	}

#ifdef THREADSAFE
	V_FREE(tmp1);	V_FREE(tmp2);
#endif

	return (Qout);
}
Exemplo n.º 20
0
Arquivo: score.c Projeto: stig/pac
/* Check all locations pacman occupies at the moment whether they
 * contain any cherries */
void pick_up_cherries(struct env *board, struct creature *ct)
{
        int i, j, k = 1;
        int score = 0;
	int r, c;

	r = board->rows;
	c = board->cols;
        for (i=-k; i<=k; i++) {
                for (j=-k; j<=k; j++) {
                        score += pick_cherry(board, 
					(board->pos[(r+get_row(ct)+i)%r][(c+get_col(ct)+j)%c]));
                }
        }

	/* give a higher score the more lives we have left */
        up_score(board, score * lives_left(board));
}
Exemplo n.º 21
0
MAT	*Hfactor(MAT *A, VEC *diag, VEC *beta)
#endif
{
	STATIC	VEC	*hh = VNULL, *w = VNULL;
	int	k, limit;

	if ( ! A || ! diag || ! beta )
		error(E_NULL,"Hfactor");
	if ( diag->dim < A->m - 1 || beta->dim < A->m - 1 )
		error(E_SIZES,"Hfactor");
	if ( A->m != A->n )
		error(E_SQUARE,"Hfactor");
	limit = A->m - 1;

	hh = v_resize(hh,A->m);
	w  = v_resize(w,A->n);
	MEM_STAT_REG(hh,TYPE_VEC);
	MEM_STAT_REG(w, TYPE_VEC);

	for ( k = 0; k < limit; k++ )
	  {
	    /* compute the Householder vector hh */
	    get_col(A,(unsigned int)k,hh);
	    /* printf("the %d'th column = ");	v_output(hh); */
	    hhvec(hh,k+1,&beta->ve[k],hh,&A->me[k+1][k]);
	    /* diag->ve[k] = hh->ve[k+1]; */
	    v_set_val(diag,k,v_entry(hh,k+1));
	    /* printf("H/h vector = ");	v_output(hh); */
	    /* printf("from the %d'th entry\n",k+1); */
	    /* printf("beta = %g\n",beta->ve[k]); */

	    /* apply Householder operation symmetrically to A */
	    _hhtrcols(A,k+1,k+1,hh,v_entry(beta,k),w);
	    hhtrrows(A,0  ,k+1,hh,v_entry(beta,k));
	    /* printf("A = ");		m_output(A); */
	  }

#ifdef THREADSAFE
	V_FREE(hh);	V_FREE(w);
#endif

	return (A);
}
Exemplo n.º 22
0
SEXP top_cumprop_internal(Rcpp::RObject incoming, Rcpp::IntegerVector topset) {
    auto mat=beachmat::create_matrix<M>(incoming);
    const size_t ncells=mat->get_ncol();
    const size_t ngenes=mat->get_nrow();

    check_topset(topset);
    Rcpp::NumericMatrix percentages(topset.size(), ncells);
    typename M::vector holder(ngenes); 

    for (size_t c=0; c<ncells; ++c) {
        mat->get_col(c, holder.begin()); // need to copy as cumsum will change ordering.
        double totals=std::accumulate(holder.begin(), holder.end(), static_cast<typename M::type>(0));

        auto cur_col=percentages.column(c);
        compute_cumsum<typename M::type, typename M::vector>(holder.begin(), ngenes, topset, cur_col.begin());
        for (auto& p : cur_col) { p/=totals; }
    }

    return percentages;
}
Exemplo n.º 23
0
void solve(){
    char ch;
    int row, col=0, start=0;
    
    scanf("%s%d",font,&row);
    row--;
    if(strcmp(op,".P")==0){
        scanf("%d",&col);
        col--;
    }
    
    while((ch=getchar())!='|');
    gets(str);
    int len = strlen(str)-1;
    while(str[len]!='|')len--;
    if(strcmp(op,".P")!=0){
        col=get_col(len, start);
    }
    //printf("%d %d %s\n",len,start,str);
    if(strcmp(font,"C1")==0){
        for(int i=start; i<len&&col<60; i++, col++){
            if(str[i]!=' '){
                ans[row][col]=str[i];
            }
        }
    }
    else{
        for(int i=start; i<len&&col<60; i++, col+=6){
            if(str[i]==' ')continue;
            int x=str[i]-'A';
            for(int k=0; k<6;k++){
                for(int j=0;j<5;j++){
                    if(map[x][j][k]=='*'){
                        ans[row+j][col+k]='*';
                    }
                }
            }
        }
    }
}
Exemplo n.º 24
0
MAT	*QRfactor(MAT *A, VEC *diag)
#endif
{
    unsigned int	k,limit;
    Real	beta;
    STATIC	VEC	*hh=VNULL, *w=VNULL;
    
    if ( ! A || ! diag )
	error(E_NULL,"QRfactor");
    limit = min(A->m,A->n);
    if ( diag->dim < limit )
	error(E_SIZES,"QRfactor");
    
    hh = v_resize(hh,A->m);
    w  = v_resize(w, A->n);
    MEM_STAT_REG(hh,TYPE_VEC);
    MEM_STAT_REG(w, TYPE_VEC);
    
    for ( k=0; k<limit; k++ )
    {
	/* get H/holder vector for the k-th column */
	get_col(A,k,hh);
	/* hhvec(hh,k,&beta->ve[k],hh,&A->me[k][k]); */
	hhvec(hh,k,&beta,hh,&A->me[k][k]);
	diag->ve[k] = hh->ve[k];
	
	/* apply H/holder vector to remaining columns */
	/* hhtrcols(A,k,k+1,hh,beta->ve[k]); */
	_hhtrcols(A,k,k+1,hh,beta,w);
    }

#ifdef	THREADSAFE
    V_FREE(hh);	V_FREE(w);
#endif

    return (A);
}
Exemplo n.º 25
0
VEC	*_Qsolve(const MAT *QR, const VEC *diag, const VEC *b, 
		 VEC *x, VEC *tmp)
#endif
{
    unsigned int	dynamic;
    int		k, limit;
    Real	beta, r_ii, tmp_val;
    
    limit = min(QR->m,QR->n);
    dynamic = FALSE;
    if ( ! QR || ! diag || ! b )
	error(E_NULL,"_Qsolve");
    if ( diag->dim < limit || b->dim != QR->m )
	error(E_SIZES,"_Qsolve");
    x = v_resize(x,QR->m);
    if ( tmp == VNULL )
	dynamic = TRUE;
    tmp = v_resize(tmp,QR->m);
    
    /* apply H/holder transforms in normal order */
    x = v_copy(b,x);
    for ( k = 0 ; k < limit ; k++ )
    {
	get_col(QR,k,tmp);
	r_ii = fabs(tmp->ve[k]);
	tmp->ve[k] = diag->ve[k];
	tmp_val = (r_ii*fabs(diag->ve[k]));
	beta = ( tmp_val == 0.0 ) ? 0.0 : 1.0/tmp_val;
	/* hhtrvec(tmp,beta->ve[k],k,x,x); */
	hhtrvec(tmp,beta,k,x,x);
    }
    
    if ( dynamic )
	V_FREE(tmp);
    
    return (x);
}
Exemplo n.º 26
0
/* --------------------------------------------------------------
 QPC solver based on MDM algorithm.

 Usage: exitflag = gnpp_mdm( &get_col, diag_H, vector_c, vector_y,
       dim, tmax, tolabs, tolrel, th, &alpha, &t, &aHa11, &aHa22, &History );
-------------------------------------------------------------- */
int gnpp_mdm(const void* (*get_col)(long,long),
            double *diag_H,
            double *vector_c,
            double *vector_y,
            long dim,
            long tmax,
            double tolabs,
            double tolrel,
            double th,
            double *alpha,
            long  *ptr_t,
            double *ptr_aHa11,
            double *ptr_aHa22,
            double **ptr_History,
            long verb)
{
  double LB;
  double UB;
  double aHa11, aHa12, aHa22, ac1, ac2;
  double tmp;
  double Huu, Huv, Hvv;
  double min_beta1, max_beta1, min_beta2, max_beta2, beta;
  double lambda;
  double delta1, delta2;
  double *History;
  double *Ha1;
  double *Ha2;
  double *tmp_ptr;
  double *col_u, *col_v;
  double *col_v1, *col_v2;
  long u1, u2;
  long v1, v2;
  long i;
  long t;
  long History_size;
  int exitflag;

  /* ------------------------------------------------------------ */
  /* Initialization                                               */
  /* ------------------------------------------------------------ */

  Ha1 = mxCalloc(dim, sizeof(double));
  if( Ha1 == NULL ) mexErrMsgTxt("Not enough memory.");
  Ha2 = mxCalloc(dim, sizeof(double));
  if( Ha2 == NULL ) mexErrMsgTxt("Not enough memory.");

  History_size = (tmax < HISTORY_BUF ) ? tmax+1 : HISTORY_BUF;
  History = mxCalloc(History_size*2,sizeof(double));
  if( History == NULL ) mexErrMsgTxt("Not enough memory.");

  /* inx1 = firts of find( y ==1 ), inx2 = firts of find( y ==2 ) */
  v1 = -1; v2 = -1; i = 0;
  while( (v1 == -1 || v2 == -1) && i < dim ) {
    if( v1 == -1 && vector_y[i] == 1 ) { v1 = i; }
    if( v2 == -1 && vector_y[i] == 2 ) { v2 = i; }
    i++;
  }

  col_v1 = (double*)get_col(v1,-1);
  col_v2 = (double*)get_col(v2,v1);

  aHa12 = col_v1[v2];
  aHa11 = diag_H[v1];
  aHa22 = diag_H[v2];
  ac1 = vector_c[v1];
  ac2 = vector_c[v2];

  min_beta1 = PLUS_INF; min_beta2 = PLUS_INF;
  for( i = 0; i < dim; i++ )
  {
    alpha[i] = 0;
    Ha1[i] = col_v1[i];
    Ha2[i] = col_v2[i];

    beta = Ha1[i] + Ha2[i] + vector_c[i];

    if( vector_y[i] == 1 && min_beta1 > beta ) {
      u1 = i;
      min_beta1 = beta;
    }

    if( vector_y[i] == 2 && min_beta2 > beta ) {
      u2 = i;
      min_beta2 = beta;
    }
  }

  alpha[v1] = 1;
  alpha[v2] = 1;

  UB = 0.5*(aHa11 + 2*aHa12 + aHa22) + ac1 + ac2;
  LB = min_beta1 + min_beta2 - 0.5*(aHa11 + 2*aHa12 + aHa22);

  delta1 = Ha1[v1] + Ha2[v1] + vector_c[v1] - min_beta1;
  delta2 = Ha1[v2] + Ha2[v2] + vector_c[v2] - min_beta2;

  t = 0;
  History[INDEX(0,0,2)] = LB;
  History[INDEX(1,0,2)] = UB;

  if( verb ) {
    mexPrintf("Init: UB=%f, LB=%f, UB-LB=%f, (UB-LB)/|UB|=%f \n",
      UB, LB, UB-LB,(UB-LB)/UB);
  }

  /* Stopping conditions */
  if( UB-LB <= tolabs ) exitflag = 1;
  else if(UB-LB <= ABS(UB)*tolrel ) exitflag = 2;
  else if(LB > th) exitflag = 3;
  else exitflag = -1;

  /* ------------------------------------------------------------ */
  /* Main optimization loop                                       */
  /* ------------------------------------------------------------ */

  while( exitflag == -1 )
  {
    t++;

    if( delta1 > delta2 )
    {
      col_u = (double*)get_col(u1,-1);
      col_v = (double*)get_col(v1,u1);

      Huu = diag_H[u1];
      Hvv = diag_H[v1];
      Huv = col_u[v1];

      lambda = delta1/(alpha[v1]*(Huu - 2*Huv + Hvv ));
      lambda = MIN(1,lambda);

      tmp = lambda*alpha[v1];

      aHa11 = aHa11 + 2*tmp*(Ha1[u1]-Ha1[v1])+tmp*tmp*( Huu - 2*Huv + Hvv );
      aHa12 = aHa12 + tmp*(Ha2[u1]-Ha2[v1]);
      ac1 = ac1 + tmp*(vector_c[u1]-vector_c[v1]);

      alpha[u1] = alpha[u1] + tmp;
      alpha[v1] = alpha[v1] - tmp;

      min_beta1 = PLUS_INF; min_beta2 = PLUS_INF;
      max_beta1 = MINUS_INF; max_beta2 = MINUS_INF;
      for( i = 0; i < dim; i ++ )
      {
         Ha1[i] = Ha1[i] + tmp*(col_u[i] - col_v[i]);

         beta = Ha1[i] + Ha2[i] + vector_c[i];
         if( vector_y[i] == 1 )
           {
             if( min_beta1 > beta ) { u1 = i; min_beta1 = beta; }
             if( max_beta1 < beta && alpha[i] > 0 ) { v1 = i; max_beta1 = beta; }
           }
         else
           {
             if( min_beta2 > beta ) { u2 = i; min_beta2 = beta; }
             if( max_beta2 < beta && alpha[i] > 0) { v2 = i; max_beta2 = beta; }
           }
      }
    }
    else
    {
      col_u = (double*)get_col(u2,-1);
      col_v = (double*)get_col(v2,u2);

      Huu = diag_H[u2];
      Hvv = diag_H[v2];
      Huv = col_u[v2];

      lambda = delta2/(alpha[v2]*( Huu - 2*Huv + Hvv ));
      lambda = MIN(1,lambda);

      tmp = lambda*alpha[v2];
      aHa22 = aHa22 + 2*tmp*( Ha2[u2]-Ha2[v2]) + tmp*tmp*( Huu - 2*Huv + Hvv);
      aHa12 = aHa12 + tmp*(Ha1[u2]-Ha1[v2]);
      ac2 = ac2 + tmp*( vector_c[u2]-vector_c[v2] );

      alpha[u2] = alpha[u2] + tmp;
      alpha[v2] = alpha[v2] - tmp;

      min_beta1 = PLUS_INF; min_beta2 = PLUS_INF;
      max_beta1 = MINUS_INF; max_beta2 = MINUS_INF;
      for(i = 0; i < dim; i++ )
      {
         Ha2[i] = Ha2[i] + tmp*( col_u[i] - col_v[i] );

         beta = Ha1[i] + Ha2[i] + vector_c[i];

         if( vector_y[i] == 1 )
         {
           if( min_beta1 > beta ) { u1 = i; min_beta1 = beta; }
           if( max_beta1 < beta && alpha[i] > 0 ) { v1 = i; max_beta1 = beta; }
         }
         else
         {
           if( min_beta2 > beta ) { u2 = i; min_beta2 = beta; }
           if( max_beta2 < beta && alpha[i] > 0) { v2 = i; max_beta2 = beta; }
         }
      }
    }

    UB = 0.5*(aHa11 + 2*aHa12 + aHa22) + ac1 + ac2;
    LB = min_beta1 + min_beta2 - 0.5*(aHa11 + 2*aHa12 + aHa22);

    delta1 = Ha1[v1] + Ha2[v1] + vector_c[v1] - min_beta1;
    delta2 = Ha1[v2] + Ha2[v2] + vector_c[v2] - min_beta2;

    /* Stopping conditions */
    if( UB-LB <= tolabs ) exitflag = 1;
    else if( UB-LB <= ABS(UB)*tolrel ) exitflag = 2;
    else if(LB > th) exitflag = 3;
    else if(t >= tmax) exitflag = 0;

    if( verb && (t % verb) == 0) {
     mexPrintf("%d: UB=%f,LB=%f,UB-LB=%f,(UB-LB)/|UB|=%f\n",
        t, UB, LB, UB-LB,(UB-LB)/UB);
    }

    /* Store selected values */
    if( t < History_size ) {
      History[INDEX(0,t,2)] = LB;
      History[INDEX(1,t,2)] = UB;
    }
    else {
      tmp_ptr = mxCalloc((History_size+HISTORY_BUF)*2,sizeof(double));
      if( tmp_ptr == NULL ) mexErrMsgTxt("Not enough memory.");
      for( i = 0; i < History_size; i++ ) {
        tmp_ptr[INDEX(0,i,2)] = History[INDEX(0,i,2)];
        tmp_ptr[INDEX(1,i,2)] = History[INDEX(1,i,2)];
      }
      tmp_ptr[INDEX(0,t,2)] = LB;
      tmp_ptr[INDEX(1,t,2)] = UB;

      History_size += HISTORY_BUF;
      mxFree( History );
      History = tmp_ptr;
    }
  }

  /* print info about last iteration*/
  if(verb && (t % verb) ) {
    mexPrintf("Exit: UB=%f, LB=%f, UB-LB=%f, (UB-LB)/|UB|=%f \n",
      UB, LB, UB-LB,(UB-LB)/UB);
  }

  /*------------------------------------------------------- */
  /* Set outputs                                            */
  /*------------------------------------------------------- */
  (*ptr_t) = t;
  (*ptr_aHa11) = aHa11;
  (*ptr_aHa22) = aHa22;
  (*ptr_History) = History;

  /* Free memory */
  mxFree( Ha1 );
  mxFree( Ha2 );

  return( exitflag );
}
Exemplo n.º 27
0
libqp_state_T libqp_splx_solver(const double* (*get_col)(uint32_t),
                  double *diag_H,
                  double *f,
                  double *b,
                  uint32_t *I,
                  uint8_t *S,
                  double *x,
                  uint32_t n,
                  uint32_t MaxIter,
                  double TolAbs,
                  double TolRel,
                  double QP_TH,
				  void (*print_state)(libqp_state_T state))
{
  double *d;
  double *col_u, *col_v;
  double *x_neq;
  double tmp;
  double improv;
  double tmp_num;
  double tmp_den=0;
  double tau=0;
  double delta;
  uint32_t *inx;
  uint32_t *nk;
  uint32_t m;
  uint32_t u=0;
  uint32_t v=0;
  uint32_t k;
  uint32_t i, j;
  libqp_state_T state;

  
  /* ------------------------------------------------------------ 
    Initialization                                               
  ------------------------------------------------------------ */
  state.nIter = 0;
  state.QP = LIBQP_PLUS_INF;
  state.QD = -LIBQP_PLUS_INF;
  state.exitflag = 100;

  inx=NULL;
  nk=NULL;
  d=NULL;
  x_neq = NULL;

  /* count number of constraints */
  for( i=0, m=0; i < n; i++ ) 
    m = LIBQP_MAX(m,I[i]);

  /* auxciliary variables for tranforming equalities to inequalities */
  x_neq = (double*) LIBQP_CALLOC(m, sizeof(double));
  if( x_neq == NULL )
  {
	  state.exitflag=-1;
	  goto cleanup;
  }

  /* inx is translation table between variable index i and its contraint */
  inx = (uint32_t*) LIBQP_CALLOC(m*n, sizeof(uint32_t));
  if( inx == NULL )
  {
	  state.exitflag=-1;
	  goto cleanup;
  }

  /* nk is the number of variables coupled by i-th linear constraint */
  nk = (uint32_t*) LIBQP_CALLOC(m, sizeof(uint32_t));
  if( nk == NULL )
  {
	  state.exitflag=-1;
	  goto cleanup;
  }

  /* setup auxciliary variables */
  for( i=0; i < m; i++ ) 
    x_neq[i] = b[i];


  /* create inx and nk */
  for( i=0; i < n; i++ ) {
     k = I[i]-1;
     inx[LIBQP_INDEX(nk[k],k,n)] = i;
     nk[k]++;     

     if(S[k] != 0) 
       x_neq[k] -= x[i];
  }
    
  /* d = H*x + f is gradient*/
  d = (double*) LIBQP_CALLOC(n, sizeof(double));
  if( d == NULL )
  {
	  state.exitflag=-1;
	  goto cleanup;
  }
 
  /* compute gradient */
  for( i=0; i < n; i++ ) 
  {
    d[i] += f[i];
    if( x[i] > 0 ) {
      col_u = (double*)get_col(i);      
      for( j=0; j < n; j++ ) {
          d[j] += col_u[j]*x[i];
      }
    }
  }
  
  /* compute state.QP = 0.5*x'*(f+d);
             state.QD = 0.5*x'*(f-d); */
  for( i=0, state.QP = 0, state.QD=0; i < n; i++) 
  {
    state.QP += x[i]*(f[i]+d[i]);
    state.QD += x[i]*(f[i]-d[i]);
  }
  state.QP = 0.5*state.QP;
  state.QD = 0.5*state.QD;
  
  for( i=0; i < m; i++ ) 
  {
    for( j=0, tmp = LIBQP_PLUS_INF; j < nk[i]; j++ ) 
      tmp = LIBQP_MIN(tmp, d[inx[LIBQP_INDEX(j,i,n)]]);

    if(S[i] == 0) 
      state.QD += b[i]*tmp;
    else
      state.QD += b[i]*LIBQP_MIN(tmp,0);
  }
  
  /* print initial state */
  if( print_state != NULL) 
    print_state( state );

  /* ------------------------------------------------------------ 
    Main optimization loop 
  ------------------------------------------------------------ */
  while( state.exitflag == 100 ) 
  {
    state.nIter ++;

    /* go over blocks of variables coupled by lin. constraint */
    for( k=0; k < m; k++ ) 
    {       
        
      /* compute u = argmin_{i in I_k} d[i] 
             delta =  sum_{i in I_k} x[i]*d[i] - b*min_{i in I_k} */
      for( j=0, tmp = LIBQP_PLUS_INF, delta = 0; j < nk[k]; j++ ) 
      {
        i = inx[LIBQP_INDEX(j,k,n)];
        delta += x[i]*d[i];
        if( tmp > d[i] ) {
          tmp = d[i];
          u = i;
        }
      }

      if(S[k] != 0 && d[u] > 0) 
        u = -1;
      else
        delta -= b[k]*d[u];
            
      /* if satisfied then k-th block of variables needs update */
      if( delta > TolAbs/m && delta > TolRel*LIBQP_ABS(state.QP)/m) 
      {         
        /* for fixed u select v = argmax_{i in I_k} Improvement(i) */
        if( u != -1 ) 
        {
          col_u = (double*)get_col(u);
          improv = -LIBQP_PLUS_INF;
          for( j=0; j < nk[k]; j++ ) 
          {
            i = inx[LIBQP_INDEX(j,k,n)];
           
            if(x[i] > 0 && i != u) 
            {
              tmp_num = x[i]*(d[i] - d[u]); 
              tmp_den = x[i]*x[i]*(diag_H[u] - 2*col_u[i] + diag_H[i]);
              if( tmp_den > 0 ) 
              {
                if( tmp_num < tmp_den ) 
                  tmp = tmp_num*tmp_num / tmp_den;
                else 
                  tmp = tmp_num - 0.5 * tmp_den;
                 
                if( tmp > improv ) 
                { 
                  improv = tmp;
                  tau = LIBQP_MIN(1,tmp_num/tmp_den);
                  v = i;
                } 
              }
            }
          }

          /* check if virtual variable can be for updated */
          if(x_neq[k] > 0 && S[k] != 0) 
          {
            tmp_num = -x_neq[k]*d[u]; 
            tmp_den = x_neq[k]*x_neq[k]*diag_H[u];
            if( tmp_den > 0 ) 
            {
              if( tmp_num < tmp_den ) 
                tmp = tmp_num*tmp_num / tmp_den;
              else 
                tmp = tmp_num - 0.5 * tmp_den;
                 
              if( tmp > improv ) 
              { 
                improv = tmp;
                tau = LIBQP_MIN(1,tmp_num/tmp_den);
                v = -1;
              } 
            }
          }

          /* minimize objective w.r.t variable u and v */
          if(v != -1)
          {
            tmp = x[v]*tau;
            x[u] += tmp;
            x[v] -= tmp;

            /* update d = H*x + f */
            col_v = (double*)get_col(v);
            for(i = 0; i < n; i++ )              
              d[i] += tmp*(col_u[i]-col_v[i]);
          }
          else
          {
            tmp = x_neq[k]*tau;
            x[u] += tmp;
            x_neq[k] -= tmp;

            /* update d = H*x + f */
            for(i = 0; i < n; i++ )              
              d[i] += tmp*col_u[i];
          }
        }
        else
        {
          improv = -LIBQP_PLUS_INF;
          for( j=0; j < nk[k]; j++ ) 
          {
            i = inx[LIBQP_INDEX(j,k,n)];
           
            if(x[i] > 0) 
            {
              tmp_num = x[i]*d[i]; 
              tmp_den = x[i]*x[i]*diag_H[i];
              if( tmp_den > 0 ) 
              {
                if( tmp_num < tmp_den ) 
                  tmp = tmp_num*tmp_num / tmp_den;
                else 
                  tmp = tmp_num - 0.5 * tmp_den;
                 
                if( tmp > improv ) 
                { 
                  improv = tmp;
                  tau = LIBQP_MIN(1,tmp_num/tmp_den);
                  v = i;
                } 
              }
            }
          }

          tmp = x[v]*tau;
          x_neq[k] += tmp;
          x[v] -= tmp;

          /* update d = H*x + f */
          col_v = (double*)get_col(v);
          for(i = 0; i < n; i++ )              
            d[i] -= tmp*col_v[i];
        }

        /* update objective value */
        state.QP = state.QP - improv;
      }
    }
    
    /* Compute primal and dual objectives */
    for( i=0, state.QP = 0, state.QD=0; i < n; i++) 
    {
       state.QP += x[i]*(f[i]+d[i]);
       state.QD += x[i]*(f[i]-d[i]);
    }
    state.QP = 0.5*state.QP;
    state.QD = 0.5*state.QD;

    for( k=0; k < m; k++ ) 
    { 
      for( j=0,tmp = LIBQP_PLUS_INF; j < nk[k]; j++ ) {
        i = inx[LIBQP_INDEX(j,k,n)];
        tmp = LIBQP_MIN(tmp, d[i]);
      }
      
      if(S[k] == 0) 
        state.QD += b[k]*tmp;
      else
        state.QD += b[k]*LIBQP_MIN(tmp,0);
    }

    /* print state */
    if( print_state != NULL) 
      print_state( state );

    /* check stopping conditions */
    if(state.QP-state.QD <= LIBQP_ABS(state.QP)*TolRel ) state.exitflag = 1;
    else if( state.QP-state.QD <= TolAbs ) state.exitflag = 2;
    else if( state.QP <= QP_TH ) state.exitflag = 3;
    else if( state.nIter >= MaxIter) state.exitflag = 0;
  }

  /*----------------------------------------------------------
    Clean up
  ---------------------------------------------------------- */
cleanup:
  LIBQP_FREE( d );
  LIBQP_FREE( inx );
  LIBQP_FREE( nk );
  LIBQP_FREE( x_neq );
  
  return( state ); 
}
Exemplo n.º 28
0
/* --------------------------------------------------------------

Usage: exitflag = qpbsvm_sca( &get_col, diag_H, f, UB, dim, tmax, 
               tolabs, tolrel, tolKKT, x, Nabla, &t, &History, verb )

-------------------------------------------------------------- */
int qpbsvm_sca(const void* (*get_col)(long,long),
            double *diag_H,
            double *f,
            double UB,
            long   dim,
            long   tmax,
            double tolabs,
            double tolrel,
            double tolKKT,
            double *x,
	        double *Nabla,
            long   *ptr_t,
            double **ptr_History,
            long   verb)
{
  double *History;
  double *col_H;
  double *tmp_ptr;
  double x_old;
  double delta_x;
  double xHx;
  double Q_P;
  double Q_D;
  double xf;
  double xi_sum;
  long History_size;
  long t;
  long i, j;
  int exitflag;
  int KKTsatisf;

  /* ------------------------------------------------------------ */
  /* Initialization                                               */
  /* ------------------------------------------------------------ */

  t = 0;

  History_size = (tmax < HISTORY_BUF ) ? tmax+1 : HISTORY_BUF;
  History = mxCalloc(History_size*2,sizeof(double));
  if( History == NULL ) mexErrMsgTxt("Not enough memory.");

  /* compute Q_P and Q_D */
  xHx = 0;
  xf = 0;
  xi_sum = 0;
  for(i = 0; i < dim; i++ ) {
    xHx += x[i]*(Nabla[i] - f[i]);
    xf += x[i]*f[i];
    xi_sum += MAX(0,-Nabla[i]);
  }

  Q_P = 0.5*xHx + xf;
  Q_D = -0.5*xHx - UB*xi_sum;
  History[INDEX(0,t,2)] = Q_P;
  History[INDEX(1,t,2)] = Q_D;

  if( verb > 0 ) {
    mexPrintf("%d: Q_P=%f, Q_D=%f, Q_P-Q_D=%f, (Q_P-Q_D)/|Q_P|=%f \n",
     t, Q_P, Q_D, Q_P-Q_D,(Q_P-Q_D)/ABS(Q_P));
  }

  exitflag = -1;
  while( exitflag == -1 ) 
  {
    t++;     
 
    for(i = 0; i < dim; i++ ) {
      if( diag_H[i] > 0 ) {
        /* variable update */
        x_old = x[i];
        x[i] = MIN(UB,MAX(0, x[i] - Nabla[i]/diag_H[i]));
        
        /* update Nabla */
        delta_x = x[i] - x_old;
        if( delta_x != 0 ) {
          col_H = (double*)get_col(i,-1);
          for(j = 0; j < dim; j++ ) {
            Nabla[j] += col_H[j]*delta_x;
          }
        }   

      }
    }

    /* compute Q_P and Q_D */
    xHx = 0;
    xf = 0;
    xi_sum = 0;
    KKTsatisf = 1;
    for(i = 0; i < dim; i++ ) {
      xHx += x[i]*(Nabla[i] - f[i]);
      xf += x[i]*f[i];
      xi_sum += MAX(0,-Nabla[i]);

      if((x[i] > 0 && x[i] < UB && ABS(Nabla[i]) > tolKKT) || 
         (x[i] == 0 && Nabla[i] < -tolKKT) ||
         (x[i] == UB && Nabla[i] > tolKKT)) KKTsatisf = 0;
    }

    Q_P = 0.5*xHx + xf;
    Q_D = -0.5*xHx - UB*xi_sum;

    /* stopping conditions */
    if(t >= tmax) exitflag = 0;
    else if(Q_P-Q_D <= tolabs) exitflag = 1;
    else if(Q_P-Q_D <= ABS(Q_P)*tolrel) exitflag = 2;
    else if(KKTsatisf == 1) exitflag = 3;

    if( verb > 0 && (t % verb == 0 || t==1)) {
      mexPrintf("%d: Q_P=%f, Q_D=%f, Q_P-Q_D=%f, (Q_P-Q_D)/|Q_P|=%f \n",
        t, Q_P, Q_D, Q_P-Q_D,(Q_P-Q_D)/ABS(Q_P));
    }

    /* Store UB LB to History buffer */
    if( t < History_size ) {
      History[INDEX(0,t,2)] = Q_P;
      History[INDEX(1,t,2)] = Q_D;
    }
    else {
      tmp_ptr = mxCalloc((History_size+HISTORY_BUF)*2,sizeof(double));
      if( tmp_ptr == NULL ) mexErrMsgTxt("Not enough memory.");
      for( i = 0; i < History_size; i++ ) {
        tmp_ptr[INDEX(0,i,2)] = History[INDEX(0,i,2)];
        tmp_ptr[INDEX(1,i,2)] = History[INDEX(1,i,2)];
      }
      tmp_ptr[INDEX(0,t,2)] = Q_P;
      tmp_ptr[INDEX(1,t,2)] = Q_D;
      
      History_size += HISTORY_BUF;
      mxFree( History );
      History = tmp_ptr;
    }
  }

  (*ptr_t) = t;
  (*ptr_History) = History;

  return( exitflag ); 
}
Exemplo n.º 29
0
/* --------------------------------------------------------------

Usage: exitflag = qpbsvm_scamv( &get_col, diag_H, f, UB, dim, tmax, 
               tolabs, tolrel, tolKKT, x, Nabla, &t, &History, verb )

-------------------------------------------------------------- */
int qpbsvm_scamv(const void* (*get_col)(long,long),
            double *diag_H,
            double *f,
            double UB,
            long   dim,
            long   tmax,
            double tolabs,
            double tolrel,
            double tolKKT,
            double *x,
	        double *Nabla,
            long   *ptr_t,
            double **ptr_History,
            long   verb)
{
  double *History;
  double *col_H;
  double delta_x;
  double x_new;
  double max_viol;
  double fval;
  long t;
  long i;
  long u;
  int exitflag;

  /* ------------------------------------------------------------ */
  /* Initialization                                               */
  /* ------------------------------------------------------------ */

  t = 0;
  exitflag = -1;
  while( exitflag == -1 && t <= tmax) 
  {
    t++;     

    max_viol = 0;
    for(i = 0; i < dim; i++ ) 
    {      
      if( x[i] == 0 )
      {
        if( max_viol < -Nabla[i]) { u = i; max_viol = -Nabla[i]; }
      }
      else if( x[i] > 0 && x[i] < UB )
      {
        if( max_viol < ABS(Nabla[i]) ) { u = i; max_viol = ABS(Nabla[i]); } 
      }
      else if( max_viol < Nabla[i]) { u = i; max_viol = Nabla[i]; }
    }

/*    mexPrintf("%d: max_viol=%f, u=%d\n", t, max_viol, u);*/

    if( max_viol <= tolKKT ) 
    {
      exitflag = 1;
    } 
    else
    {
      /* update */
      x_new = MIN(UB,MAX(0, x[u] - Nabla[u]/diag_H[u]));

      delta_x = x_new - x[u];
      x[u] = x_new;

      col_H = (double*)get_col(u,-1);
      for(i = 0; i < dim; i++ ) {
        Nabla[i] += col_H[i]*delta_x;
      }
    }
  }

  History = mxCalloc((t+1)*2,sizeof(double));
  if( History == NULL ) mexErrMsgTxt("Not enough memory.");

  fval = 0;
  for(fval = 0, i = 0; i < dim; i++ ) {
    fval += 0.5*x[i]*(Nabla[i]+f[i]);
  }

  History[INDEX(0,t,2)] = fval;
  History[INDEX(1,t,2)] = 0;

  (*ptr_t) = t;
  (*ptr_History) = History;



  return( exitflag ); 
}
Exemplo n.º 30
0
/** @brief Main in-game rendering routine.
 *
 *  @param b Board configuration to render.
 */
void draw_scene(board_t *b, GLuint fb, int reflections) {
	char temp[80];
	int clock_seconds = 0;
	int clock_minutes = 0;

	glBindFramebuffer(GL_FRAMEBUFFER, fb);

	transition_update();

	gg_dialog_cleanup();

	glDisable(GL_BLEND);
	glDepthFunc(GL_ALWAYS);

	draw_backdrop();

	glEnable(GL_BLEND);
	glDepthFunc(GL_LEQUAL);

	go_3d(get_screen_width(), get_screen_height());

	render_scene_3d(b, fb, reflections);
	mouse_square = find_square(get_true_mouse_x(), get_true_mouse_y());

	glBindFramebuffer(GL_FRAMEBUFFER, fb);
	resize_window(get_screen_width(), get_screen_height());

	glPushMatrix();

	draw_ui_elements();

	// draw_move_list(get_col(COL_WHITE), get_col(COL_YELLOW));
	// draw_capture_list(get_col(COL_WHITE));

	clock_minutes = (((SDL_GetTicks() - get_turn_counter()) / 1000) / 60);
	clock_seconds = ((SDL_GetTicks() - get_turn_counter()) / 1000) - (clock_minutes * 60);
	snprintf(temp, sizeof(temp), "%i:%02i", clock_minutes, clock_seconds);
	/*text_draw_string( 303, 440, temp, 1, &col_black);*/
	glPopMatrix();

	/*if ( get_white_in_check() == TRUE )
		text_draw_string_bouncy( 180, 420, "White is in check!", 1, get_col(COL_WHITE));
	else if ( get_black_in_check() == TRUE )
		text_draw_string_bouncy( 180, 420, "Black is in check!", 1, get_col(COL_WHITE));*/

	gg_dialog_render_all();

	if (get_fading_out()) {
		if (!draw_fade(FADE_OUT))
			set_switch_to_menu(TRUE);
	} else {
		if (get_show_egg())
			draw_sonic_fade(FADE_IN);
		else
			draw_fade(FADE_IN);
	}

	/* Draw mouse cursor.. */
	draw_texture(get_mouse_cursor(), get_mouse_x(), (479 - get_mouse_y() - 32), 32, 32, 1.0f, get_col(COL_WHITE));
}