コード例 #1
0
ファイル: player.cpp プロジェクト: amitn7/2D-game
void Player::flipUp() { 
  if ( Y() > 0) {
    setFlipUp(1);
  }
} 
コード例 #2
0
ファイル: Filter.cpp プロジェクト: dezed/mantid
bool Filter::setDataFromTable(Table *t, const QString& xColName, const QString& yColName, int startRow, int endRow)
{
	d_init_err = true;

	if (!t)
		return false;

	int xcol = t->colIndex(xColName);
	int ycol = t->colIndex(yColName);
	if (xcol < 0 || ycol < 0)
		return false;

	if (t->columnType(xcol) != Table::Numeric || t->columnType(ycol) != Table::Numeric)
		return false;

    startRow--; endRow--;
	if (startRow < 0 || startRow >= t->numRows())
		startRow = 0;
	if (endRow < 0 || endRow >= t->numRows())
		endRow = t->numRows() - 1;

    int from = QMIN(startRow, endRow);
    int to = QMAX(startRow, endRow);

	int r = abs(to - from) + 1;
    QVector<double> X(r), Y(r);

	int size = 0;
	for (int i = from; i<=to; i++ ){
		QString xval = t->text(i, xcol);
		QString yval = t->text(i, ycol);
		if (!xval.isEmpty() && !yval.isEmpty()){
		    bool valid_data = true;
            X[size] = t->locale().toDouble(xval, &valid_data);
            Y[size] = t->locale().toDouble(yval, &valid_data);
            if (valid_data)
                size++;
		}
	}

	if (size < d_min_points){
	  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(this->parent());
    if (!app) {
      throw std::logic_error("Parent of Filter is not ApplicationWindow as expected.");
    }
		QMessageBox::critical(app, tr("MantidPlot") + " - " + tr("Error"),
				tr("You need at least %1 points in order to perform this operation!").arg(d_min_points));
        return false;
	}

	if (d_n > 0){//delete previousely allocated memory
		delete[] d_x;
		delete[] d_y;
	}

	d_graph = 0;
	d_curve = 0;
	d_n = size;
	d_init_err = false;
	d_table = t;
	d_y_col_name = t->colName(ycol);
	X.resize(d_n);
	Y.resize(d_n);
	d_from = X[0];
    d_to = X[d_n-1];

	d_x = new double[d_n];
    d_y = new double[d_n];

    for (int i = 0; i < d_n; i++){
        d_x[i] = X[i];
        d_y[i] = Y[i];
    }

	if (d_sort_data){
    	size_t *p = new size_t[d_n];
   		gsl_sort_index(p, X.data(), 1, d_n);
    	for (int i=0; i<d_n; i++){
        	d_x[i] = X[static_cast<int>(p[i])];
  	    	d_y[i] = Y[static_cast<int>(p[i])];
		}
		delete[] p;
    }
	return true;
}
コード例 #3
0
ファイル: Rayman.cpp プロジェクト: oliverhuangchao/Rayman
void Rayman::draw() const { 
  Uint32 x = static_cast<Uint32>(X());
  Uint32 y = static_cast<Uint32>(Y());
  frames[currentFrame]->draw(x, y);
}
コード例 #4
0
 K E c() {return C[X(0,(k)Y(C)-1)];%> Q struct x { E G[sizeof T];
コード例 #5
0
ファイル: dCA.c プロジェクト: ArtPoon/phydynR
//~ R version: 
	//~ dA <- function(h, A, parms, ...)
	//~ {
		//~ nsy <- not.sampled.yet(h) 
		//~ with(get.fgy(h), 
		//~ { 
			//~ A_Y 	<- (A-nsy) / .Y
			//~ csFpG 	<- colSums( .F + .G )
			//~ list( .G %*% A_Y - csFpG * A_Y + (.F %*% A_Y) * pmax(1-A_Y, 0) )
		//~ })
	//~ }
void dCA( int *neq, double *t, double *y, double *ydot, double *yout, int*ip)
{
	int i =  (int)min( (int)( hres * (*t) / treeT ), hres-1);
	//~ if ((*t) < 10)
	//~ {
		//~ printf( "Fs %f %f \n", F(i, 3, 0), F(i, 0, 3)); 
		//~ printf( "Ys %f %f \n", Y(i, 0), Y(i, 1)); 
		//~ printf( "NSY %f %f \n", notSampledYet(i, 0), notSampledYet(i, 3)); 
		//~ printf( "t %f  treeT %f hres %f \n", (*t), treeT, hres); 
	//~ }
	int k,l;
	
	
	double csFpG[m]; 
	for (k = 0; k < m; k++)
	{
		csFpG[k] = 0.;
	}
	double a[m]; //normalized nlft 
	for (k = 0; k < m; k++) { 
		dA(k) = 0.;
		if (Y(i,k) > 0) {
			a[k] =  max(0, (A(k)-notSampledYet(i,k))) / Y(i,k); //max(1, Y(i,k)) );
		} else{
			a[k] = 1.; //
		} 
		for ( l = 0; l < m; l++)
		{
			csFpG[l] += G(i, k, l) + F(i, k, l);
		}
	}
	
	//dA
	//~ list( .G %*% A_Y - csFpG * A_Y + (.F %*% A_Y) * pmax(1-A_Y, 0) )
	for (k = 0; k < m; k++){
		dA(k) -= a[k] * csFpG[k];
		for (l = 0; l < m; l++){
			dA(k) += a[l] * G(i,k,l);
			dA(k) += max(0,(1-a[k])) * F(i,k,l) * a[l];
			dLambda += F(i,k,l) * a[k] * a[l]; //note- would be a little more accurate to have (A-1)/(Y-1) if k==l
		}
	}
	
	
	
	/*for (k = 0; k < m; k++){
		for (l = 0; l < m; l++){
			if (k==l){
				dA(k) -= a[l] * (F(i,l,k)) * a[k];
			} else{
				dA(k) += ( F(i,k,l) + G(i,k,l)) * a[l] ; //(1 - a[k]) * ??
				dA(k) -= ( F(i,l,k) + G(i,l,k)) * a[k]; //TODO 
			}
		}
	}
	*/
	
	//~ if ((*t) < 10)
	//~ {
		//~ printf("TIME %f\n", (*t)); 
		//~ for (k = 0; k < m; k++)
		//~ {
			//~ printf("%f %f %f %f %f \n", Y(i, k), notSampledYet(i,k), A(k) , a[k], dA(k));
		//~ }
		//~ printf("~~~~~~~~~~~\n");
		//~ for (k = 0; k < m; k++)
		//~ {
			//~ for (l = 0; l < m; l++)
			//~ {
				//~ printf("%f ", F(i,k,l) );
			//~ }
			//~ printf("\n"); 
		//~ }
		//~ printf("~~~~~~~~~~~\n");
		//~ for (k = 0; k < m; k++)
		//~ {
			//~ for (l = 0; l < m; l++)
			//~ {
				//~ printf("%f ", G(i,k,l) );
			//~ }
			//~ printf("\n"); 
		//~ }
		//~ printf("~~~~~~~~~~~\n");
		//~ printf("~~~~~~~~~~~\n");
	//~ }
}
コード例 #6
0
ファイル: dsyr2.c プロジェクト: copies/superlu
/* Subroutine */ int dsyr2_(char *uplo, integer *n, doublereal *alpha, 
	doublereal *x, integer *incx, doublereal *y, integer *incy, 
	doublereal *a, integer *lda)
{


    /* System generated locals */
    integer a_dim1, a_offset, i__1, i__2;

    /* Local variables */
    static integer info;
    static doublereal temp1, temp2;
    static integer i, j;
    static integer ix, iy, jx, jy, kx, ky;
    extern int input_error(char *, int *);

/*  Purpose   
    =======   

    DSYR2  performs the symmetric rank 2 operation   

       A := alpha*x*y' + alpha*y*x' + A,   

    where alpha is a scalar, x and y are n element vectors and A is an n 
  
    by n symmetric matrix.   

    Parameters   
    ==========   

    UPLO   - CHARACTER*1.   
             On entry, UPLO specifies whether the upper or lower   
             triangular part of the array A is to be referenced as   
             follows:   

                UPLO = 'U' or 'u'   Only the upper triangular part of A   
                                    is to be referenced.   

                UPLO = 'L' or 'l'   Only the lower triangular part of A   
                                    is to be referenced.   

             Unchanged on exit.   

    N      - INTEGER.   
             On entry, N specifies the order of the matrix A.   
             N must be at least zero.   
             Unchanged on exit.   

    ALPHA  - DOUBLE PRECISION.   
             On entry, ALPHA specifies the scalar alpha.   
             Unchanged on exit.   

    X      - DOUBLE PRECISION array of dimension at least   
             ( 1 + ( n - 1 )*abs( INCX ) ).   
             Before entry, the incremented array X must contain the n   
             element vector x.   
             Unchanged on exit.   

    INCX   - INTEGER.   
             On entry, INCX specifies the increment for the elements of   
             X. INCX must not be zero.   
             Unchanged on exit.   

    Y      - DOUBLE PRECISION array of dimension at least   
             ( 1 + ( n - 1 )*abs( INCY ) ).   
             Before entry, the incremented array Y must contain the n   
             element vector y.   
             Unchanged on exit.   

    INCY   - INTEGER.   
             On entry, INCY specifies the increment for the elements of   
             Y. INCY must not be zero.   
             Unchanged on exit.   

    A      - DOUBLE PRECISION array of DIMENSION ( LDA, n ).   
             Before entry with  UPLO = 'U' or 'u', the leading n by n   
             upper triangular part of the array A must contain the upper 
  
             triangular part of the symmetric matrix and the strictly   
             lower triangular part of A is not referenced. On exit, the   
             upper triangular part of the array A is overwritten by the   
             upper triangular part of the updated matrix.   
             Before entry with UPLO = 'L' or 'l', the leading n by n   
             lower triangular part of the array A must contain the lower 
  
             triangular part of the symmetric matrix and the strictly   
             upper triangular part of A is not referenced. On exit, the   
             lower triangular part of the array A is overwritten by the   
             lower triangular part of the updated matrix.   

    LDA    - INTEGER.   
             On entry, LDA specifies the first dimension of A as declared 
  
             in the calling (sub) program. LDA must be at least   
             max( 1, n ).   
             Unchanged on exit.   


    Level 2 Blas routine.   

    -- Written on 22-October-1986.   
       Jack Dongarra, Argonne National Lab.   
       Jeremy Du Croz, Nag Central Office.   
       Sven Hammarling, Nag Central Office.   
       Richard Hanson, Sandia National Labs.   



       Test the input parameters.   

    
   Parameter adjustments   
       Function Body */
#define X(I) x[(I)-1]
#define Y(I) y[(I)-1]

#define A(I,J) a[(I)-1 + ((J)-1)* ( *lda)]

    info = 0;
    if ( strncmp(uplo, "U", 1)!=0 && strncmp(uplo, "L", 1)!=0 ) {
	info = 1;
    } else if (*n < 0) {
	info = 2;
    } else if (*incx == 0) {
	info = 5;
    } else if (*incy == 0) {
	info = 7;
    } else if (*lda < max(1,*n)) {
	info = 9;
    }
    if (info != 0) {
	input_error("DSYR2 ", &info);
	return 0;
    }

/*     Quick return if possible. */

    if (*n == 0 || *alpha == 0.) {
	return 0;
    }

/*     Set up the start points in X and Y if the increments are not both 
  
       unity. */

    if (*incx != 1 || *incy != 1) {
	if (*incx > 0) {
	    kx = 1;
	} else {
	    kx = 1 - (*n - 1) * *incx;
	}
	if (*incy > 0) {
	    ky = 1;
	} else {
	    ky = 1 - (*n - 1) * *incy;
	}
	jx = kx;
	jy = ky;
    }

/*     Start the operations. In this version the elements of A are   
       accessed sequentially with one pass through the triangular part   
       of A. */

    if (strncmp(uplo, "U", 1)==0) {

/*        Form  A  when A is stored in the upper triangle. */

	if (*incx == 1 && *incy == 1) {
	    i__1 = *n;
	    for (j = 1; j <= *n; ++j) {
		if (X(j) != 0. || Y(j) != 0.) {
		    temp1 = *alpha * Y(j);
		    temp2 = *alpha * X(j);
		    i__2 = j;
		    for (i = 1; i <= j; ++i) {
			A(i,j) = A(i,j) + X(i) * temp1 
				+ Y(i) * temp2;
/* L10: */
		    }
		}
/* L20: */
	    }
	} else {
	    i__1 = *n;
	    for (j = 1; j <= *n; ++j) {
		if (X(jx) != 0. || Y(jy) != 0.) {
		    temp1 = *alpha * Y(jy);
		    temp2 = *alpha * X(jx);
		    ix = kx;
		    iy = ky;
		    i__2 = j;
		    for (i = 1; i <= j; ++i) {
			A(i,j) = A(i,j) + X(ix) * temp1 
				+ Y(iy) * temp2;
			ix += *incx;
			iy += *incy;
/* L30: */
		    }
		}
		jx += *incx;
		jy += *incy;
/* L40: */
	    }
	}
    } else {

/*        Form  A  when A is stored in the lower triangle. */

	if (*incx == 1 && *incy == 1) {
	    i__1 = *n;
	    for (j = 1; j <= *n; ++j) {
		if (X(j) != 0. || Y(j) != 0.) {
		    temp1 = *alpha * Y(j);
		    temp2 = *alpha * X(j);
		    i__2 = *n;
		    for (i = j; i <= *n; ++i) {
			A(i,j) = A(i,j) + X(i) * temp1 
				+ Y(i) * temp2;
/* L50: */
		    }
		}
/* L60: */
	    }
	} else {
	    i__1 = *n;
	    for (j = 1; j <= *n; ++j) {
		if (X(jx) != 0. || Y(jy) != 0.) {
		    temp1 = *alpha * Y(jy);
		    temp2 = *alpha * X(jx);
		    ix = jx;
		    iy = jy;
		    i__2 = *n;
		    for (i = j; i <= *n; ++i) {
			A(i,j) = A(i,j) + X(ix) * temp1 
				+ Y(iy) * temp2;
			ix += *incx;
			iy += *incy;
/* L70: */
		    }
		}
		jx += *incx;
		jy += *incy;
/* L80: */
	    }
	}
    }

    return 0;

/*     End of DSYR2 . */

} /* dsyr2_ */
コード例 #7
0
 int f() { return Y().b; }
コード例 #8
0
ファイル: spline.hpp プロジェクト: codeplea/celtic_knots
 ST operator()(FT x) const {return Y(x);}
コード例 #9
0
ファイル: benchmark.cpp プロジェクト: odellus/vexcl
std::pair<double,double> benchmark_spmv(
        const vex::Context &ctx, vex::profiler<> &prof
        )
{
    // Construct matrix for 3D Poisson problem in cubic domain.
    const size_t n = 128;
    const size_t N = n * n * n;
    const size_t M = 1024;

    double time_elapsed;

    const real h2i = (n - 1) * (n - 1);

    std::vector<size_t> row;
    std::vector<uint>   col;
    std::vector<real>   val;
    std::vector<real>   X(n * n * n, static_cast<real>(1e-2));
    std::vector<real>   Y(n * n * n, 0);

    row.reserve(n * n * n + 1);
    col.reserve(6 * (n - 2) * (n - 2) * (n - 2) + n * n * n);
    val.reserve(6 * (n - 2) * (n - 2) * (n - 2) + n * n * n);

    row.push_back(0);
    for(size_t k = 0, idx = 0; k < n; k++) {
        for(size_t j = 0; j < n; j++) {
            for(size_t i = 0; i < n; i++, idx++) {
                if (
                        i == 0 || i == (n - 1) ||
                        j == 0 || j == (n - 1) ||
                        k == 0 || k == (n - 1)
                   )
                {
                    col.push_back(idx);
                    val.push_back(1);
                    row.push_back(row.back() + 1);
                } else {
                    col.push_back(idx - n * n);
                    val.push_back(-h2i);

                    col.push_back(idx - n);
                    val.push_back(-h2i);

                    col.push_back(idx - 1);
                    val.push_back(-h2i);

                    col.push_back(idx);
                    val.push_back(6 * h2i);

                    col.push_back(idx + 1);
                    val.push_back(-h2i);

                    col.push_back(idx + n);
                    val.push_back(-h2i);

                    col.push_back(idx + n * n);
                    val.push_back(-h2i);

                    row.push_back(row.back() + 7);
                }
            }
        }
    }

    size_t nnz = row.back();

    // Transfer data to compute devices.
    vex::SpMat<real,uint> A(ctx, n * n * n, n * n * n, row.data(), col.data(), val.data());

    vex::vector<real> x(ctx, X);
    vex::vector<real> y(ctx, Y);

    // Get timings.
    y += A * x;
    y = 0;

    prof.tic_cpu("OpenCL");
    for(size_t i = 0; i < M; i++)
        y += A * x;
    ctx.finish();
    time_elapsed = prof.toc("OpenCL");

    double gflops = (2.0 * nnz + N) * M / time_elapsed / 1e9;
    double bwidth = M * (nnz * (2 * sizeof(real) + sizeof(size_t)) + 4 * N * sizeof(real)) / time_elapsed / 1e9;

    std::cout
        << "SpMV (" << vex::type_name<real>() << ")\n"
        << "  OpenCL"
        << "\n    GFLOPS:    " << gflops
        << "\n    Bandwidth: " << bwidth
        << std::endl;

    if (options.bm_cpu) {
        prof.tic_cpu("C++");
        for(size_t k = 0; k < M; k++)
            for(size_t i = 0; i < N; i++) {
                real s = 0;
                for(size_t j = row[i]; j < row[i + 1]; j++)
                    s += val[j] * X[col[j]];
                Y[i] += s;
            }
        time_elapsed = prof.toc("C++");

        {
            double gflops = (2.0 * nnz + N) * M / time_elapsed / 1e9;
            double bwidth = M * (nnz * (2 * sizeof(real) + sizeof(size_t)) + 4 * N * sizeof(real)) / time_elapsed / 1e9;

            std::cout
                << "  C++"
                << "\n    GFLOPS:    " << gflops
                << "\n    Bandwidth: " << bwidth
                << std::endl;
        }

        copy(Y, x);

        y -= x;

        vex::Reductor<real, vex::SUM> sum(ctx);

        std::cout << "  res = " << sum(y * y) << std::endl << std::endl;
    }

    return std::make_pair(gflops, bwidth);
}
コード例 #10
0
ファイル: MADBayes.cpp プロジェクト: keleslab/mbasic
SEXP MADBayes( SEXP _b, SEXP _clusterLabels, SEXP _Theta, SEXP _Mu, SEXP _D,
	       SEXP _Gamma, SEXP _Y, SEXP _lambdap, SEXP _lambdaw, SEXP _lambda) {

	// The following values are 1updated in MCMC iterations
	IntegerVector b(_b); // length I
	IntegerVector clusterLabels(_clusterLabels); // length I
	IntegerMatrix Theta(_Theta); // K by I
	//NumericMatrix W(_W); // KS by I + 1
	//NumericMatrix P(_P); // I by S
	NumericMatrix Mu(_Mu); // N by S
	IntegerVector D(_D); // Length N, valued in {0, 1, ..., K-1}
	double lambda = as<double>(_lambda);

	// The following values are piror parameters and are fixed
	double lambdap = as<double>(_lambdap);
	double lambdaw = as<double>(_lambdaw);

	// The following is the external information.
	NumericMatrix Gamma(_Gamma); // N*S by I
	NumericMatrix Y(_Y); // N by I

	// extract the dimensions
	int I = b.size();
	int S = Mu.ncol();
	int K = Theta.nrow();
	int N = D.size();

	// The following will be computed
	NumericMatrix W(K * S, I + 1);
	NumericMatrix P(I, S);

	// iterators
	int i, j, k = 0, s = 0, n, i1;//, likid;
	double loss;

	double _LOW = 1e-10;

	int ClusterSize[I + 1];

	for(i = 0; i < I + 1; i ++) {
		ClusterSize[i] = 0;
	}

	// Compute J

	int J = 0;
	for(i = 0; i < I; i ++) {
		if(J < clusterLabels[i]) {
			J = clusterLabels[i];
		}
		ClusterSize[clusterLabels[i]] ++;
	}
	J ++;

	// Update W
	for(j = 0; j < J; j ++) {
		for(k = 0; k < K; k ++) {
			double tmp[S + 1];
			tmp[S] = 0;
			for(s = 0; s < S; s ++) {
				tmp[s] = _LOW;
				tmp[S] += tmp[s];
				W(s * K + k, j) = 0;
			}
			for(i = 0; i < I; i ++) {
				if(b[i] == 0 && clusterLabels[i] == j) {
					tmp[Theta(k, i)] ++;
					tmp[S] ++;
				}
			}
			for(s = 0; s < S; s ++) {
				W(s * K + k, j) = tmp[s] / tmp[S];
			}
		}
	}

	// update P
	for(i = 0; i < I; i ++) {
		double tmp[S + 1];
		tmp[S] = 0;
		for(s = 0; s < S; s++) {
			tmp[s] = _LOW;
			tmp[S] += _LOW;
			P(i, s) = 0;
		}
		for(k = 0; k < K; k ++) {
			tmp[Theta(k, i)] ++;
			tmp[S] ++;
		}
		for(s = 0; s < S; s ++) {
			P(i, s) = tmp[s] / tmp[S];
		}
	}

	// update b
	for(i = 0; i < I; i ++) {
		double tmp = 0;
		for(k = 0; k < K; k ++) {
			tmp += 2 * lambdap * (1 - P(i, Theta(k, i)));
		}

		for(k = 0; k < K; k ++) {
			tmp -= 2 * lambdaw * (1 - W(Theta(k, i) * K + k, clusterLabels[i]));
		}
		    
		if(tmp < 0)
			b[i] = 1;
		else
			b[i] = 0;
	}

	loss = 0;
	for(i = 0; i < I; i ++) {
		for(n = 0; n < N; n ++) {
			k = D[n];
			s = Theta(k, i);
			loss += (Y(n, i) - Mu(n, s) * Gamma(s * N + n, i)) *
				(Y(n, i) - Mu(n, s) * Gamma(s * N + n, i));
		}

		if(b[i] == 1) {
			for(k = 0; k < K; k ++) {
				loss += 2 * lambdap * (1 - P(i, Theta(k, i)));
			}
		} else {
			for(k = 0; k < K; k ++) {
				loss += 2 * (1 - W(Theta(k, i) * K + k, clusterLabels[i])) * lambdaw;
			}
		}
	}
	loss += lambda * (J - 1);

	//printf("b, Loss function = %3.3f, number of clusters = %d\n", loss, J);

	// update Theta
	for(i = 0; i < I; i ++) {
		for(k = 0; k < K; k ++) {
			double tmp[S];
			for(s = 0; s < S; s ++) {
				// initialize
				tmp[s] = 0;
				//
				for(n = 0; n < N; n ++) {
					if(D[n] == k) {
						tmp[s] += (Y(n, i) - Mu(n, s) * Gamma(s * N + n, i)) * (Y(n, i) - Mu(n, s) * Gamma(s * N + n, i));
					}
				}
				if(b[i] == 1) {
					tmp[s] += 2 * lambdap * (1 - P(i, s));
				} else {
					tmp[s] += 2 * lambdaw * (1 - W(s * K + k, clusterLabels[i]));
				}
			}
			// Assign new values
			Theta(k, i) = 0;
			for(s = 1; s < S; s ++) {
				if(tmp[s] < tmp[Theta(k, i)])
					Theta(k, i) = s;
			}
		}
	}

	loss = 0;
	for(i = 0; i < I; i ++) {
		for(n = 0; n < N; n ++) {
			k = D[n];
			s = Theta(k, i);
			loss += (Y(n, i) - Mu(n, s) * Gamma(s * N + n, i)) *
				(Y(n, i) - Mu(n, s) * Gamma(s * N + n, i));
		}

		if(b[i] == 1) {
			for(k = 0; k < K; k ++) {
				loss += 2 * lambdap * (1 - P(i, Theta(k, i)));
			}
		} else {
			for(k = 0; k < K; k ++) {
				loss += 2 * (1 - W(Theta(k, i) * K + k, clusterLabels[i])) * lambdaw;
			}
		}
	}
	loss += lambda * (J - 1);

	//printf("theta, Loss function = %3.3f, number of clusters = %d\n", loss, J);

	//update clusters
	for(i = 0; i < I; i ++) {
		// do not update cluster if this is a singleton
		if(b[i] == 1)
			continue;

		int oldState = clusterLabels[i];
		ClusterSize[clusterLabels[i]] --;
		double tmp[J];
		double mintmp = lambda;// cost of starting a new cluster
		int newState = J;
		for(j = 0; j < J; j ++) {
			tmp[j] = 0;
			for(k = 0; k < K; k ++) {
				tmp[j] += 2 * (1 - W(Theta(k, i) * K + k, j)) * lambdaw;
			}
			// assign the minimum cost
			if(tmp[j] < mintmp) {
				mintmp = tmp[j];
				newState = j;
			}
		}

		clusterLabels[i] = newState;
		ClusterSize[newState] ++;
		if(mintmp >= lambda) {
			// a new cluster is formed
			if(J != newState) {
				printf("Error: new state is not J = %d.", J);
				exit(1);
			}
			for(s = 0; s < S; s ++) {
				for(k = 0; k < K; k ++) {
					if(Theta(k, i) != s) {
						W(s * K + k, J) = _LOW;
					} else {
						W(s * K + k, J) = 1 - (S - 1) * _LOW;
					}
				}
			}
			J ++;
		}
		if(ClusterSize[oldState] == 0) {
			// an old cluster should be removed
			W(_, oldState) = W(_, J - 1);
			for(k = 0; k < K * S; k ++) {
				W(k, J - 1) = 0;
			}
			for(i1 = 0; i1 < I; i1 ++) {
				if(clusterLabels[i1] == J - 1)
					clusterLabels[i1] = oldState;
			}
			ClusterSize[oldState] = ClusterSize[J - 1];
			ClusterSize[J - 1] = 0;
			J --;
		}
	}

	loss = 0;
	for(i = 0; i < I; i ++) {
		for(n = 0; n < N; n ++) {
			k = D[n];
			s = Theta(k, i);
			loss += (Y(n, i) - Mu(n, s) * Gamma(s * N + n, i)) *
				(Y(n, i) - Mu(n, s) * Gamma(s * N + n, i));
		}

		if(b[i] == 1) {
			for(k = 0; k < K; k ++) {
				loss += 2 * lambdap * (1 - P(i, Theta(k, i)));
			}
		} else {
			for(k = 0; k < K; k ++) {
				loss += 2 * (1 - W(Theta(k, i) * K + k, clusterLabels[i])) * lambdaw;
			}
		}
	}
	loss += lambda * (J - 1);

	//printf("z, Loss function = %3.3f, number of clusters = %d\n", loss, J);

	// update mu
	for(n = 0; n < N; n ++) {
		double denom = 0, numer = 0;
		for(i = 0; i < I; i ++) {
			denom += Gamma(n + s * N, i);
			numer += Y(n, i);
		}
		for(s = 0; s < S; s ++) {
			Mu(n, s) = numer / denom;
		}
		for(s = 0; s < S; s ++) {
			denom = 0;
			numer = 0;
			for(i = 0; i < I; i ++) {
				if(Theta(D[n], i) == s) {
					numer += Y(n, i);
					denom += Gamma(n + s * N, i);
				}
			}
			if(denom > 0) {
				Mu(n, s) = numer / denom;
			}
		}
	}

	// calculate the loss function

	loss = 0;
	for(i = 0; i < I; i ++) {
		for(n = 0; n < N; n ++) {
			k = D[n];
			s = Theta(k, i);
			loss += (Y(n, i) - Mu(n, s) * Gamma(s * N + n, i)) *
				(Y(n, i) - Mu(n, s) * Gamma(s * N + n, i));
		}

		if(b[i] == 1) {
			for(k = 0; k < K; k ++) {
				loss += 2 * lambdap * (1 - P(i, Theta(k, i)));
			}
		} else {
			for(k = 0; k < K; k ++) {
				loss += 2 * (1 - W(Theta(k, i) * K + k, clusterLabels[i])) * lambdaw;
			}
		}
	}
	loss += lambda * (J - 1);

	//printf("Loss function = %3.3f, number of clusters = %d\n", loss, J);

	Rcpp::List ret = Rcpp::List::create(
					    Rcpp::Named("Theta") = Theta,
					    Rcpp::Named("clusterLabels") = clusterLabels,
					    Rcpp::Named("b") = b,
					    Rcpp::Named("W") = W,
					    Rcpp::Named("P") = P,
					    Rcpp::Named("Mu") = Mu,
					    Rcpp::Named("loss") = loss
					    //,Rcpp::Named("oldlik") = oldlik
					    );
	return( ret );

}
コード例 #11
0
ファイル: ode.cpp プロジェクト: barak/CppAD-1
bool link_ode(
	size_t                     size       ,
	size_t                     repeat     ,
	CppAD::vector<double>      &x         ,
	CppAD::vector<double>      &jacobian
)
{
	// speed test global option values
	if( global_atomic )
		return false;

	// --------------------------------------------------------------------
	// setup
	assert( x.size() == size );
	assert( jacobian.size() == size * size );

	typedef CppAD::AD<double>       ADScalar;
	typedef CppAD::vector<ADScalar> ADVector;

	size_t j;
	size_t p = 0;              // use ode to calculate function values
	size_t n = size;           // number of independent variables
	size_t m = n;              // number of dependent variables
	ADVector  X(n), Y(m);      // independent and dependent variables
	CppAD::ADFun<double>  f;   // AD function

	// -------------------------------------------------------------
	if( ! global_onetape ) while(repeat--)
	{	// choose next x value
		uniform_01(n, x);
		for(j = 0; j < n; j++)
			X[j] = x[j];

		// declare the independent variable vector
		Independent(X);

		// evaluate function
		CppAD::ode_evaluate(X, p, Y);

		// create function object f : X -> Y
		f.Dependent(X, Y);

		if( global_optimize )
			f.optimize();

		// skip comparison operators
		f.compare_change_count(0);

		jacobian = f.Jacobian(x);
	}
	else
	{	// an x value
		uniform_01(n, x);
		for(j = 0; j < n; j++)
			X[j] = x[j];

		// declare the independent variable vector
		Independent(X);

		// evaluate function
		CppAD::ode_evaluate(X, p, Y);

		// create function object f : X -> Y
		f.Dependent(X, Y);

		if( global_optimize )
			f.optimize();

		// skip comparison operators
		f.compare_change_count(0);

		while(repeat--)
		{	// get next argument value
			uniform_01(n, x);

			// evaluate jacobian
			jacobian = f.Jacobian(x);
		}
	}
	return true;
}
コード例 #12
0
ファイル: change.cpp プロジェクト: thenewguy/mkvtoolnix
void
change_c::validate_deletion_of_mandatory() {
  const EbmlSemantic *semantic = get_semantic();
  if (semantic && semantic->Mandatory)
    mxerror(boost::format(Y("This property is mandatory and cannot be deleted in '%1%'. %2%\n")) % get_spec() % FILE_NOT_MODIFIED);
}
コード例 #13
0
ファイル: change.cpp プロジェクト: thenewguy/mkvtoolnix
void
change_c::parse_floating_point_number() {
  if (!parse_number(m_value, m_fp_value))
    mxerror(boost::format(Y("The property value is not a valid floating point number in '%1%'. %2%\n")) % get_spec() % FILE_NOT_MODIFIED);
}
コード例 #14
0
ファイル: change.cpp プロジェクト: thenewguy/mkvtoolnix
void
change_c::parse_signed_integer() {
  if (!parse_number(m_value, m_si_value))
    mxerror(boost::format(Y("The property value is not a valid signed integer in '%1%'. %2%\n")) % get_spec() % FILE_NOT_MODIFIED);
}
コード例 #15
0
ファイル: Node_Data.cpp プロジェクト: kravitz/transims4
Node_Data::Node_Data (int node) : Class_Index (node)
{
	X (0);
	Y (0);
	Z (0);
}
コード例 #16
0
ファイル: benchmark.cpp プロジェクト: odellus/vexcl
std::pair<double,double> benchmark_spmv_ccsr(
        const vex::Context &ctx, vex::profiler<> &prof
        )
{
    // Construct matrix for 3D Poisson problem in cubic domain.
    const uint n = 128;
    const uint N = n * n * n;
    const uint M = 1024;

    double time_elapsed;

    const real h2i = (n - 1) * (n - 1);

    std::vector<size_t> idx;
    std::vector<size_t> row(3);
    std::vector<int>    col(8);
    std::vector<real>   val(8);

    std::vector<real>   X(n * n * n, static_cast<real>(1e-2));
    std::vector<real>   Y(n * n * n, 0);

    idx.reserve(n * n * n);

    row[0] = 0;
    row[1] = 1;
    row[2] = 8;

    col[0] = 0;
    val[0] = 1;

    col[1] = -static_cast<int>(n * n);
    col[2] = -static_cast<int>(n);
    col[3] =    -1;
    col[4] =     0;
    col[5] =     1;
    col[6] =     n;
    col[7] =  (n * n);

    val[1] = -h2i;
    val[2] = -h2i;
    val[3] = -h2i;
    val[4] =  h2i * 6;
    val[5] = -h2i;
    val[6] = -h2i;
    val[7] = -h2i;

    for(size_t k = 0; k < n; k++) {
        for(size_t j = 0; j < n; j++) {
            for(size_t i = 0; i < n; i++) {
                if (
                        i == 0 || i == (n - 1) ||
                        j == 0 || j == (n - 1) ||
                        k == 0 || k == (n - 1)
                   )
                {
                    idx.push_back(0);
                } else {
                    idx.push_back(1);
                }
            }
        }
    }

    size_t nnz = 6 * (n - 2) * (n - 2) * (n - 2) + n * n * n;

    // Transfer data to compute devices.
    vex::SpMatCCSR<real,int> A(ctx.queue(0), n * n * n, 2,
            idx.data(), row.data(), col.data(), val.data());

    std::vector<vex::command_queue> q1(1, ctx.queue(0));
    vex::vector<real> x(q1, X);
    vex::vector<real> y(q1, Y);

    // Get timings.
    y += A * x;
    y = 0;

    prof.tic_cpu("OpenCL");
    for(size_t i = 0; i < M; i++)
        y += A * x;
    ctx.finish();
    time_elapsed = prof.toc("OpenCL");

    double gflops = (2.0 * nnz + N) * M / time_elapsed / 1e9;
    double bwidth = M * (nnz * (2 * sizeof(real) + sizeof(int)) + 4 * N * sizeof(real)) / time_elapsed / 1e9;

    std::cout
        << "SpMV (CCSR) (" << vex::type_name<real>() << ")\n"
        << "  OpenCL"
        << "\n    GFLOPS:    " << gflops
        << "\n    Bandwidth: " << bwidth
        << std::endl;

    if (options.bm_cpu) {
        prof.tic_cpu("C++");
        for(size_t k = 0; k < M; k++)
            for(size_t i = 0; i < N; i++) {
                real s = 0;
                for(size_t j = row[idx[i]]; j < row[idx[i] + 1]; j++)
                    s += val[j] * X[i + col[j]];
                Y[i] += s;
            }
        time_elapsed = prof.toc("C++");

        {
            double gflops = (2.0 * nnz + N) * M / time_elapsed / 1e9;
            double bwidth = M * (nnz * (2 * sizeof(real) + sizeof(int)) + 4 * N * sizeof(real)) / time_elapsed / 1e9;

            std::cout
                << "  C++"
                << "\n    GFLOPS:    " << gflops
                << "\n    Bandwidth: " << bwidth
                << std::endl;
        }

        copy(Y, x);

        y -= x;

        vex::Reductor<real, vex::SUM> sum(q1);

        std::cout << "  res = " << sum(y * y) << std::endl << std::endl;
    }

    return std::make_pair(gflops, bwidth);
}
void BigBullet::fire(string& power,string& offset) {
    Bullets::getInstance().add(new Bullet(power,"",Vector2f(X()+Gamedata::getInstance()->getXmlInt(getName()+offset+"X"),
                                          Y()+Gamedata::getInstance()->getXmlInt(getName()+offset+"Y")),
                                          Vector2f(Gamedata::getInstance()->getXmlFloat("redorbXspeed")*bulletDirection[0],
                                                  Gamedata::getInstance()->getXmlFloat("redorbYspeed")*bulletDirection[1])));
}
コード例 #18
0
ファイル: dgemv.c プロジェクト: aceskpark/osfeo
/* Subroutine */ int dgemv_(char *trans, integer *m, integer *n, doublereal *
	alpha, doublereal *a, integer *lda, doublereal *x, integer *incx, 
	doublereal *beta, doublereal *y, integer *incy)
{


    /* System generated locals */
    integer a_dim1, a_offset, i__1, i__2;

    /* Local variables */
    static integer info;
    static doublereal temp;
    static integer lenx, leny, i, j;
    extern logical lsame_(char *, char *);
    static integer ix, iy, jx, jy, kx, ky;
    extern /* Subroutine */ int xerbla_(char *, integer *);


/*  Purpose   
    =======   

    DGEMV  performs one of the matrix-vector operations   

       y := alpha*A*x + beta*y,   or   y := alpha*A'*x + beta*y,   

    where alpha and beta are scalars, x and y are vectors and A is an   
    m by n matrix.   

    Parameters   
    ==========   

    TRANS  - CHARACTER*1.   
             On entry, TRANS specifies the operation to be performed as   
             follows:   

                TRANS = 'N' or 'n'   y := alpha*A*x + beta*y.   

                TRANS = 'T' or 't'   y := alpha*A'*x + beta*y.   

                TRANS = 'C' or 'c'   y := alpha*A'*x + beta*y.   

             Unchanged on exit.   

    M      - INTEGER.   
             On entry, M specifies the number of rows of the matrix A.   
             M must be at least zero.   
             Unchanged on exit.   

    N      - INTEGER.   
             On entry, N specifies the number of columns of the matrix A. 
  
             N must be at least zero.   
             Unchanged on exit.   

    ALPHA  - DOUBLE PRECISION.   
             On entry, ALPHA specifies the scalar alpha.   
             Unchanged on exit.   

    A      - DOUBLE PRECISION array of DIMENSION ( LDA, n ).   
             Before entry, the leading m by n part of the array A must   
             contain the matrix of coefficients.   
             Unchanged on exit.   

    LDA    - INTEGER.   
             On entry, LDA specifies the first dimension of A as declared 
  
             in the calling (sub) program. LDA must be at least   
             max( 1, m ).   
             Unchanged on exit.   

    X      - DOUBLE PRECISION array of DIMENSION at least   
             ( 1 + ( n - 1 )*abs( INCX ) ) when TRANS = 'N' or 'n'   
             and at least   
             ( 1 + ( m - 1 )*abs( INCX ) ) otherwise.   
             Before entry, the incremented array X must contain the   
             vector x.   
             Unchanged on exit.   

    INCX   - INTEGER.   
             On entry, INCX specifies the increment for the elements of   
             X. INCX must not be zero.   
             Unchanged on exit.   

    BETA   - DOUBLE PRECISION.   
             On entry, BETA specifies the scalar beta. When BETA is   
             supplied as zero then Y need not be set on input.   
             Unchanged on exit.   

    Y      - DOUBLE PRECISION array of DIMENSION at least   
             ( 1 + ( m - 1 )*abs( INCY ) ) when TRANS = 'N' or 'n'   
             and at least   
             ( 1 + ( n - 1 )*abs( INCY ) ) otherwise.   
             Before entry with BETA non-zero, the incremented array Y   
             must contain the vector y. On exit, Y is overwritten by the 
  
             updated vector y.   

    INCY   - INTEGER.   
             On entry, INCY specifies the increment for the elements of   
             Y. INCY must not be zero.   
             Unchanged on exit.   


    Level 2 Blas routine.   

    -- Written on 22-October-1986.   
       Jack Dongarra, Argonne National Lab.   
       Jeremy Du Croz, Nag Central Office.   
       Sven Hammarling, Nag Central Office.   
       Richard Hanson, Sandia National Labs.   



       Test the input parameters.   

    
   Parameter adjustments   
       Function Body */
#define X(I) x[(I)-1]
#define Y(I) y[(I)-1]

#define A(I,J) a[(I)-1 + ((J)-1)* ( *lda)]

    info = 0;
    if (! lsame_(trans, "N") && ! lsame_(trans, "T") && ! 
	    lsame_(trans, "C")) {
	info = 1;
    } else if (*m < 0) {
	info = 2;
    } else if (*n < 0) {
	info = 3;
    } else if (*lda < max(1,*m)) {
	info = 6;
    } else if (*incx == 0) {
	info = 8;
    } else if (*incy == 0) {
	info = 11;
    }
    if (info != 0) {
	xerbla_("DGEMV ", &info);
	return 0;
    }

/*     Quick return if possible. */

    if (*m == 0 || *n == 0 || *alpha == 0. && *beta == 1.) {
	return 0;
    }

/*     Set  LENX  and  LENY, the lengths of the vectors x and y, and set 
  
       up the start points in  X  and  Y. */

    if (lsame_(trans, "N")) {
	lenx = *n;
	leny = *m;
    } else {
	lenx = *m;
	leny = *n;
    }
    if (*incx > 0) {
	kx = 1;
    } else {
	kx = 1 - (lenx - 1) * *incx;
    }
    if (*incy > 0) {
	ky = 1;
    } else {
	ky = 1 - (leny - 1) * *incy;
    }

/*     Start the operations. In this version the elements of A are   
       accessed sequentially with one pass through A.   

       First form  y := beta*y. */

    if (*beta != 1.) {
	if (*incy == 1) {
	    if (*beta == 0.) {
		i__1 = leny;
		for (i = 1; i <= leny; ++i) {
		    Y(i) = 0.;
/* L10: */
		}
	    } else {
		i__1 = leny;
		for (i = 1; i <= leny; ++i) {
		    Y(i) = *beta * Y(i);
/* L20: */
		}
	    }
	} else {
	    iy = ky;
	    if (*beta == 0.) {
		i__1 = leny;
		for (i = 1; i <= leny; ++i) {
		    Y(iy) = 0.;
		    iy += *incy;
/* L30: */
		}
	    } else {
		i__1 = leny;
		for (i = 1; i <= leny; ++i) {
		    Y(iy) = *beta * Y(iy);
		    iy += *incy;
/* L40: */
		}
	    }
	}
    }
    if (*alpha == 0.) {
	return 0;
    }
    if (lsame_(trans, "N")) {

/*        Form  y := alpha*A*x + y. */

	jx = kx;
	if (*incy == 1) {
	    i__1 = *n;
	    for (j = 1; j <= *n; ++j) {
		if (X(jx) != 0.) {
		    temp = *alpha * X(jx);
		    i__2 = *m;
		    for (i = 1; i <= *m; ++i) {
			Y(i) += temp * A(i,j);
/* L50: */
		    }
		}
		jx += *incx;
/* L60: */
	    }
	} else {
	    i__1 = *n;
	    for (j = 1; j <= *n; ++j) {
		if (X(jx) != 0.) {
		    temp = *alpha * X(jx);
		    iy = ky;
		    i__2 = *m;
		    for (i = 1; i <= *m; ++i) {
			Y(iy) += temp * A(i,j);
			iy += *incy;
/* L70: */
		    }
		}
		jx += *incx;
/* L80: */
	    }
	}
    } else {

/*        Form  y := alpha*A'*x + y. */

	jy = ky;
	if (*incx == 1) {
	    i__1 = *n;
	    for (j = 1; j <= *n; ++j) {
		temp = 0.;
		i__2 = *m;
		for (i = 1; i <= *m; ++i) {
		    temp += A(i,j) * X(i);
/* L90: */
		}
		Y(jy) += *alpha * temp;
		jy += *incy;
/* L100: */
	    }
	} else {
	    i__1 = *n;
	    for (j = 1; j <= *n; ++j) {
		temp = 0.;
		ix = kx;
		i__2 = *m;
		for (i = 1; i <= *m; ++i) {
		    temp += A(i,j) * X(ix);
		    ix += *incx;
/* L110: */
		}
		Y(jy) += *alpha * temp;
		jy += *incy;
/* L120: */
	    }
	}
    }

    return 0;

/*     End of DGEMV . */

} /* dgemv_ */
コード例 #19
0
ファイル: XYPoint.cpp プロジェクト: mirzashah/MapSystemCore
bool CXYPoint::operator == (const CXYPoint& p) const
/**************************************************/
{
    return (p.X()==X() && p.Y()==Y() && p.Z()==Z());
}
コード例 #20
0
ファイル: RPCA.cpp プロジェクト: jakebolewski/Elemental
inline void ADMM
( const AbstractDistMatrix<F>& MPre, AbstractDistMatrix<F>& LPre, 
        AbstractDistMatrix<F>& SPre, const RPCACtrl<Base<F>>& ctrl )
{
    auto MPtr = ReadProxy<F,MC,MR>( &MPre ); auto& M = *MPtr;
    auto LPtr = WriteProxy<F,MC,MR>( &LPre ); auto& L = *LPtr;
    auto SPtr = WriteProxy<F,MC,MR>( &SPre ); auto& S = *SPtr;

    typedef Base<F> Real;
    const Int m = M.Height();
    const Int n = M.Width();
    const Int commRank = mpi::Rank( M.Grid().Comm() );

    // If tau is not specified, then set it to 1/sqrt(max(m,n))
    const Base<F> tau = 
        ( ctrl.tau <= Real(0) ? Real(1)/sqrt(Real(Max(m,n))) : ctrl.tau );
    if( ctrl.beta <= Real(0) )
        LogicError("beta cannot be non-positive");
    if( ctrl.tol <= Real(0) )
        LogicError("tol cannot be non-positive");
    const Base<F> beta = ctrl.beta;
    const Base<F> tol = ctrl.tol;

    const double startTime = mpi::Time();
    DistMatrix<F> E( M.Grid() ), Y( M.Grid() );
    Zeros( Y, m, n );

    const Real frobM = FrobeniusNorm( M );
    const Real maxM = MaxNorm( M );
    if( ctrl.progress && commRank == 0 )
        cout << "|| M ||_F = " << frobM << "\n"
             << "|| M ||_max = " << maxM << endl;

    Zeros( L, m, n );
    Zeros( S, m, n );

    Int numIts = 0;
    while( true )
    {
        ++numIts;

        // ST_{tau/beta}(M - L + Y/beta)
        S = M;
        Axpy( F(-1), L, S );
        Axpy( F(1)/beta, Y, S );
        SoftThreshold( S, tau/beta );
        const Int numNonzeros = ZeroNorm( S );

        // SVT_{1/beta}(M - S + Y/beta)
        L = M;
        Axpy( F(-1), S, L );
        Axpy( F(1)/beta, Y, L );
        Int rank;
        if( ctrl.usePivQR )
            rank = SVT( L, Real(1)/beta, ctrl.numPivSteps );
        else
            rank = SVT( L, Real(1)/beta );
      
        // E := M - (L + S)
        E = M;    
        Axpy( F(-1), L, E );
        Axpy( F(-1), S, E );
        const Real frobE = FrobeniusNorm( E );

        if( frobE/frobM <= tol )            
        {
            if( ctrl.progress && commRank == 0 )
                cout << "Converged after " << numIts << " iterations "
                     << " with rank=" << rank 
                     << ", numNonzeros=" << numNonzeros << " and "
                     << "|| E ||_F / || M ||_F = " << frobE/frobM
                     << ", and " << mpi::Time()-startTime << " total secs"
                     << endl;
            break;
        }
        else if( numIts >= ctrl.maxIts )
        {
            if( ctrl.progress && commRank == 0 )
                cout << "Aborting after " << numIts << " iterations and "
                     << mpi::Time()-startTime << " total secs" 
                     << endl;
            break;
        }
        else
        {
            if( ctrl.progress && commRank == 0 )
                cout << numIts << ": || E ||_F / || M ||_F = " 
                     << frobE/frobM << ", rank=" << rank 
                     << ", numNonzeros=" << numNonzeros 
                     << ", " << mpi::Time()-startTime << " total secs"
                     << endl;
        }
        
        // Y := Y + beta E
        Axpy( beta, E, Y );
    }
}
コード例 #21
0
ファイル: Subzone_Data.cpp プロジェクト: kravitz/transims4
Subzone_Data::Subzone_Data (int zone, int id) : Class2_Index (zone, id)
{
	X (0);
	Y (0);
	Data (0);
}
コード例 #22
0
ファイル: RPCA.cpp プロジェクト: jakebolewski/Elemental
inline void ALM
( const AbstractDistMatrix<F>& MPre, 
        AbstractDistMatrix<F>& LPre, AbstractDistMatrix<F>& SPre, 
  const RPCACtrl<Base<F>>& ctrl )
{
    auto MPtr = ReadProxy<F,MC,MR>( &MPre ); auto& M = *MPtr;
    auto LPtr = WriteProxy<F,MC,MR>( &LPre ); auto& L = *LPtr;
    auto SPtr = WriteProxy<F,MC,MR>( &SPre ); auto& S = *SPtr;

    typedef Base<F> Real;
    const Int m = M.Height();
    const Int n = M.Width();
    const Int commRank = mpi::Rank( M.Grid().Comm() );

    // If tau is unspecified, set it to 1/sqrt(max(m,n))
    const Base<F> tau = 
      ( ctrl.tau <= Real(0) ? Real(1) / sqrt(Real(Max(m,n))) : ctrl.tau );
    if( ctrl.tol <= Real(0) )
        LogicError("tol cannot be non-positive");
    const Base<F> tol = ctrl.tol;

    const double startTime = mpi::Time();

    DistMatrix<F> Y( M );
    NormalizeEntries( Y );
    const Real twoNorm = TwoNorm( Y );
    const Real maxNorm = MaxNorm( Y );
    const Real infNorm = maxNorm / tau; 
    const Real dualNorm = Max( twoNorm, infNorm );
    Scale( F(1)/dualNorm, Y );

    // If beta is unspecified, set it to 1 / 2 || sign(M) ||_2
    Base<F> beta = 
      ( ctrl.beta <= Real(0) ? Real(1) / (2*twoNorm) : ctrl.beta );

    const Real frobM = FrobeniusNorm( M );
    const Real maxM = MaxNorm( M );
    if( ctrl.progress && commRank == 0 )
        cout << "|| M ||_F = " << frobM << "\n"
             << "|| M ||_max = " << maxM << endl;

    Zeros( L, m, n );
    Zeros( S, m, n );

    Int numIts=0, numPrimalIts=0;
    DistMatrix<F> LLast( M.Grid() ), SLast( M.Grid() ), E( M.Grid() );
    while( true )
    {
        ++numIts;
       
        Int rank, numNonzeros;
        while( true )
        {
            ++numPrimalIts;

            LLast = L;
            SLast = S;

            // ST_{tau/beta}(M - L + Y/beta)
            S = M;
            Axpy( F(-1), L, S );
            Axpy( F(1)/beta, Y, S );
            SoftThreshold( S, tau/beta );
            numNonzeros = ZeroNorm( S );

            // SVT_{1/beta}(M - S + Y/beta)
            L = M;
            Axpy( F(-1), S, L );
            Axpy( F(1)/beta, Y, L );
            if( ctrl.usePivQR )
                rank = SVT( L, Real(1)/beta, ctrl.numPivSteps );
            else
                rank = SVT( L, Real(1)/beta );

            Axpy( F(-1), L, LLast );
            Axpy( F(-1), S, SLast );
            const Real frobLDiff = FrobeniusNorm( LLast );
            const Real frobSDiff = FrobeniusNorm( SLast );

            if( frobLDiff/frobM < tol && frobSDiff/frobM < tol )
            {
                if( ctrl.progress && commRank == 0 )
                    cout << "Primal loop converged: " 
                         << mpi::Time()-startTime << " total secs" << endl;
                break;
            }
            else 
            {
                if( ctrl.progress && commRank == 0 )
                    cout << "  " << numPrimalIts 
                         << ": \n"
                         << "   || Delta L ||_F / || M ||_F = " 
                         << frobLDiff/frobM << "\n"
                         << "   || Delta S ||_F / || M ||_F = "
                         << frobSDiff/frobM << "\n"
                         << "   rank=" << rank
                         << ", numNonzeros=" << numNonzeros 
                         << ", " << mpi::Time()-startTime << " total secs" 
                         << endl;
            } 
        }

        // E := M - (L + S)
        E = M;    
        Axpy( F(-1), L, E );
        Axpy( F(-1), S, E );
        const Real frobE = FrobeniusNorm( E );

        if( frobE/frobM <= tol )            
        {
            if( ctrl.progress && commRank == 0 )
                cout << "Converged after " << numIts << " iterations and "
                     << numPrimalIts << " primal iterations with rank=" 
                     << rank << ", numNonzeros=" << numNonzeros << " and "
                     << "|| E ||_F / || M ||_F = " << frobE/frobM
                     << ", " << mpi::Time()-startTime << " total secs"
                     << endl;
            break;
        }
        else if( numIts >= ctrl.maxIts )
        {
            if( ctrl.progress && commRank == 0 )
                cout << "Aborting after " << numIts << " iterations and "
                     << mpi::Time()-startTime << " total secs" << endl;
            break;
        }
        else
        {
            if( ctrl.progress && commRank == 0 )
                cout << numPrimalIts << ": || E ||_F / || M ||_F = " 
                     << frobE/frobM << ", rank=" << rank 
                     << ", numNonzeros=" << numNonzeros << ", "
                     << mpi::Time()-startTime << " total secs" 
                     << endl;
        }
        
        // Y := Y + beta E
        Axpy( beta, E, Y );
        beta *= ctrl.rho;
    }
}
コード例 #23
0
void BinnedMap::binnedmap() {
    KstVectorPtr x = *_inputVectors.find(VECTOR_X);
    KstVectorPtr y = *_inputVectors.find(VECTOR_Y);
    KstVectorPtr z = *_inputVectors.find(VECTOR_Z);
    KstMatrixPtr map = *_outputMatrices.find(MAP);
    KstMatrixPtr hitsMap = *_outputMatrices.find(HITSMAP);
    KstScalarPtr autobin = *_inputScalars.find(AUTOBIN);

    if (autobin) {
        if (autobin->value() != 0.0) {
            _autoBin = true;
        } else {
            _autoBin = false;
        }
    }

    if (_autoBin) {
        double minx, miny, maxx, maxy;
        int nx, ny;

        autoSize(X(), Y(), &nx, &minx, &maxx, &ny, &miny, &maxy);

        setNX(nx);
        setNY(ny);
        setXMin(minx);
        setXMax(maxx);
        setYMin(miny);
        setYMax(maxy);
    } else {
        KstScalarPtr xmin = *_inputScalars.find(XMIN);
        KstScalarPtr xmax = *_inputScalars.find(XMAX);
        KstScalarPtr ymin = *_inputScalars.find(YMIN);
        KstScalarPtr ymax = *_inputScalars.find(YMAX);
        KstScalarPtr nx = *_inputScalars.find(NX);
        KstScalarPtr ny = *_inputScalars.find(NY);

        if (xmin) {
            _xMin = xmin->value();
        }
        if (xmax) {
            _xMax = xmax->value();
        }
        if (ymin) {
            _yMin = ymin->value();
        }
        if (ymax) {
            _yMax = ymax->value();
        }
        if (nx) {
            _nx = (int)nx->value();
        }
        if (ny) {
            _ny = (int)ny->value();
        }
    }

    bool needsresize = false;

    if (_nx < 2) {
        _nx = 2;
        needsresize = true;
    }
    if (_ny < 2) {
        _ny = 2;
        needsresize = true;
    }

    if ((map->xNumSteps() != _nx) || (map->yNumSteps() != _ny) ||
            (map->minX() != _xMin) || (map->minY() != _yMin)) {
        needsresize = true;
    }

    if (map->xStepSize() != (_xMax - _xMin)/double(_nx-1)) {
        needsresize = true;
    }
    if (map->yStepSize() != (_yMax - _yMin)/double(_ny-1)) {
        needsresize = true;
    }

    if (needsresize) {
        map->change(map->tag(), _nx, _ny, _xMin, _yMin,
                    (_xMax - _xMin)/double(_nx-1), (_yMax - _yMin)/double(_ny-1));
        map->resize(_nx, _ny);
        hitsMap->change(hitsMap->tag(), _nx, _ny, _xMin, _yMin,
                        (_xMax - _xMin)/double(_nx-1), (_yMax - _yMin)/double(_ny-1));
        hitsMap->resize(_nx, _ny);
    }

    map->zero();
    hitsMap->zero();

    int ns = z->length(); // the z vector defines the number of points.
    double n,p, x0, y0, z0;

    for (int i=0; i<ns; i++) {
        x0 = x->interpolate(i, ns);
        y0 = y->interpolate(i, ns);
        z0 = z->interpolate(i, ns);
        p = map->value(x0, y0)+z0;
        map->setValue(x0, y0, p);
        n = hitsMap->value(x0, y0)+1;
        hitsMap->setValue(x0, y0, n);
    }

    for (int i=0; i<_nx; i++) {
        for (int j=0; j<_ny; j++) {
            p = map->valueRaw(i, j);
            n = hitsMap->valueRaw(i, j);
            if (n>0) {
                map->setValueRaw(i, j, p/n);
            } else {
                map->setValueRaw(i, j, KST::NOPOINT);
            }
        }
    }
}
コード例 #24
0
ファイル: SketchTools.cpp プロジェクト: CarlosGS/heekscad
void SimplifySketchTool::SortPoint::ToDoubleArray( double *pArrayOfThree ) const
{
    pArrayOfThree[0] = X();
    pArrayOfThree[1] = Y();
    pArrayOfThree[2] = Z();
} // End ToDoubleArray() method
コード例 #25
0
ファイル: Filter.cpp プロジェクト: dezed/mantid
void Filter::output()
{
    QVarLengthArray<double> X(d_points), Y(d_points);
    calculateOutputData(X.data(), Y.data()); //does the data analysis
	addResultCurve(X.data(), Y.data());
}
コード例 #26
0
void
extract_cli_parser_c::set_blockadd() {
    assert_mode(options_c::em_tracks);
    if (!parse_number(m_next_arg, m_extract_blockadd_level) || (-1 > m_extract_blockadd_level))
        mxerror(boost::format(Y("Invalid BlockAddition level in argument '%1%'.\n")) % m_next_arg);
}
コード例 #27
0
ファイル: cxx_main.cpp プロジェクト: jwillenbring/Trilinos
int main(int argc, char *argv[])
{
#ifdef HAVE_MPI
  MPI_Init(&argc,&argv);
  Epetra_MpiComm Comm( MPI_COMM_WORLD );
#else
  Epetra_SerialComm Comm;
#endif

  if (Comm.NumProc() == 1)
  {
#ifdef HAVE_MPI
    MPI_Finalize();
#endif
    cout << "Test `TestOverlappingRowMatrix.exe' passed!" << endl;
    exit(EXIT_SUCCESS);
  }

  Teuchos::ParameterList GaleriList;
  int nx = 100; 
  GaleriList.set("n", nx * nx);
  GaleriList.set("nx", nx);
  GaleriList.set("ny", nx);
  Teuchos::RCP<Epetra_Map> Map
    (Galeri::CreateMap ("Linear", Comm, GaleriList));
  Teuchos::RCP<Epetra_CrsMatrix> A
    (Galeri::CreateCrsMatrix ("Laplace2D", Map.getRawPtr (), GaleriList));

  int OverlapLevel = 5;
  Epetra_Time Time(Comm);

  // ======================================== //
  // Build the overlapping matrix using class //
  // Ifpack_OverlappingRowMatrix.             //
  // ======================================== //
 
  Time.ResetStartTime();
  Ifpack_OverlappingRowMatrix B(A,OverlapLevel);
  if (Comm.MyPID() == 0)
    cout << "Time to create B = " << Time.ElapsedTime() << endl;

  int NumGlobalRowsB = B.NumGlobalRows();
  int NumGlobalNonzerosB = B.NumGlobalNonzeros();

  Epetra_Vector X(A->RowMatrixRowMap());
  Epetra_Vector Y(A->RowMatrixRowMap());
  for (int i = 0 ; i < A->NumMyRows() ; ++i) 
    X[i] = 1.0* A->RowMatrixRowMap().GID(i);
  Y.PutScalar(0.0);

  Epetra_Vector ExtX_B(B.RowMatrixRowMap());
  Epetra_Vector ExtY_B(B.RowMatrixRowMap());
  ExtY_B.PutScalar(0.0);

  IFPACK_CHK_ERR(B.ImportMultiVector(X,ExtX_B));
  IFPACK_CHK_ERR(B.Multiply(false,ExtX_B,ExtY_B));
  IFPACK_CHK_ERR(B.ExportMultiVector(ExtY_B,Y,Add));

  double Norm_B;
  Y.Norm2(&Norm_B);
  if (Comm.MyPID() == 0)
    cout << "Norm of Y using B = " << Norm_B << endl;
  
  // ================================================== //
  //Build the overlapping matrix as an Epetra_CrsMatrix //
  // ================================================== //

  Time.ResetStartTime();
  Epetra_CrsMatrix& C = 
    *(Ifpack_CreateOverlappingCrsMatrix(&*A,OverlapLevel));
  if (Comm.MyPID() == 0)
    cout << "Time to create C = " << Time.ElapsedTime() << endl;

  // simple checks on global quantities
  int NumGlobalRowsC = C.NumGlobalRows();
  int NumGlobalNonzerosC = C.NumGlobalNonzeros();

  if (NumGlobalRowsB != NumGlobalRowsC) {
    std::ostringstream os;
    os << "NumGlobalRowsB = " << NumGlobalRowsB
       << " != NumGlobalRowsC = " << NumGlobalRowsC
       << "." << std::endl;
    throw std::logic_error (os.str ());
  }
  if (NumGlobalNonzerosB != NumGlobalNonzerosC) {
    std::ostringstream os;
    os << "NumGlobalNonzerosB = " << NumGlobalNonzerosB
       << " != NumGlobalNonzerosC = " << NumGlobalNonzerosC
       << "." << std::endl;
    throw std::logic_error (os.str ());
  }

  Epetra_Vector ExtX_C(C.RowMatrixRowMap());
  Epetra_Vector ExtY_C(C.RowMatrixRowMap());
  ExtY_C.PutScalar(0.0);
  Y.PutScalar(0.0);

  IFPACK_CHK_ERR(C.Multiply(false,X,Y));

  double Norm_C;
  Y.Norm2(&Norm_C);
  if (Comm.MyPID() == 0)
    cout << "Norm of Y using C = " << Norm_C << endl;

  if (IFPACK_ABS(Norm_B - Norm_C) > 1e-5)
    IFPACK_CHK_ERR(-1);

  // ======================= //
  // now localize the matrix //
  // ======================= //

  Ifpack_LocalFilter D(Teuchos::rcp(&B, false));

#ifdef HAVE_MPI
  MPI_Finalize() ; 
#endif

  if (Comm.MyPID() == 0)
    cout << "Test `TestOverlappingRowMatrix.exe' passed!" << endl;

  return(EXIT_SUCCESS);
}
コード例 #28
0
Ref SateliteCam::GetRef()
{
	Point3D Y(0,1,0);
	Point3D Z(0,0,1);
	return Ref(m_Vehicle->MyRef.Position+Z*m_height,Z*(-1.f)+Y*.001f,m_Vehicle->MyRef.GetDirection());
}
コード例 #29
0
ファイル: dger.c プロジェクト: doolin/ntdda
/* Subroutine */ int dger_(int *m, int *n, double *alpha, 
	double *x, int *incx, double *y, int *incy, 
	double *a, int *lda)
{


    /* System generated locals */
    int i__1, i__2;

    /* Local variables */
    static int info;
    static double temp;
    static int i, j, ix, jy, kx;
    extern /* Subroutine */ int xerbla_(char *, int *);


/*  Purpose   
    =======   

    DGER   performs the rank 1 operation   

       A := alpha*x*y' + A,   

    where alpha is a scalar, x is an m element vector, y is an n element 
  
    vector and A is an m by n matrix.   

    Parameters   
    ==========   

    M      - INTEGER.   
             On entry, M specifies the number of rows of the matrix A.   
             M must be at least zero.   
             Unchanged on exit.   

    N      - INTEGER.   
             On entry, N specifies the number of columns of the matrix A. 
  
             N must be at least zero.   
             Unchanged on exit.   

    ALPHA  - DOUBLE PRECISION.   
             On entry, ALPHA specifies the scalar alpha.   
             Unchanged on exit.   

    X      - DOUBLE PRECISION array of dimension at least   
             ( 1 + ( m - 1 )*ABS( INCX ) ).   
             Before entry, the incremented array X must contain the m   
             element vector x.   
             Unchanged on exit.   

    INCX   - INTEGER.   
             On entry, INCX specifies the increment for the elements of   
             X. INCX must not be zero.   
             Unchanged on exit.   

    Y      - DOUBLE PRECISION array of dimension at least   
             ( 1 + ( n - 1 )*ABS( INCY ) ).   
             Before entry, the incremented array Y must contain the n   
             element vector y.   
             Unchanged on exit.   

    INCY   - INTEGER.   
             On entry, INCY specifies the increment for the elements of   
             Y. INCY must not be zero.   
             Unchanged on exit.   

    A      - DOUBLE PRECISION array of DIMENSION ( LDA, n ).   
             Before entry, the leading m by n part of the array A must   
             contain the matrix of coefficients. On exit, A is   
             overwritten by the updated matrix.   

    LDA    - INTEGER.   
             On entry, LDA specifies the first dimension of A as declared 
  
             in the calling (sub) program. LDA must be at least   
             MAX( 1, m ).   
             Unchanged on exit.   


    Level 2 Blas routine.   

    -- Written on 22-October-1986.   
       Jack Dongarra, Argonne National Lab.   
       Jeremy Du Croz, Nag Central Office.   
       Sven Hammarling, Nag Central Office.   
       Richard Hanson, Sandia National Labs.   



       Test the input parameters.   

    
   Parameter adjustments   
       Function Body */
#define X(I) x[(I)-1]
#define Y(I) y[(I)-1]

#define A(I,J) a[(I)-1 + ((J)-1)* ( *lda)]

    info = 0;
    if (*m < 0) {
	info = 1;
    } else if (*n < 0) {
	info = 2;
    } else if (*incx == 0) {
	info = 5;
    } else if (*incy == 0) {
	info = 7;
    } else if (*lda < MAX(1,*m)) {
	info = 9;
    }
    if (info != 0) {
	xerbla_("DGER  ", &info);
	return 0;
    }

/*     Quick return if possible. */

    if (*m == 0 || *n == 0 || *alpha == 0.) {
	return 0;
    }

/*     Start the operations. In this version the elements of A are   
       accessed sequentially with one pass through A. */

    if (*incy > 0) {
	jy = 1;
    } else {
	jy = 1 - (*n - 1) * *incy;
    }
    if (*incx == 1) {
	i__1 = *n;
	for (j = 1; j <= *n; ++j) {
	    if (Y(jy) != 0.) {
		temp = *alpha * Y(jy);
		i__2 = *m;
		for (i = 1; i <= *m; ++i) {
		    A(i,j) += X(i) * temp;
/* L10: */
		}
	    }
	    jy += *incy;
/* L20: */
	}
    } else {
	if (*incx > 0) {
	    kx = 1;
	} else {
	    kx = 1 - (*m - 1) * *incx;
	}
	i__1 = *n;
	for (j = 1; j <= *n; ++j) {
	    if (Y(jy) != 0.) {
		temp = *alpha * Y(jy);
		ix = kx;
		i__2 = *m;
		for (i = 1; i <= *m; ++i) {
		    A(i,j) += X(ix) * temp;
		    ix += *incx;
/* L30: */
		}
	    }
	    jy += *incy;
/* L40: */
	}
    }

    return 0;

/*     End of DGER  . */

} /* dger_ */
コード例 #30
0
bool Vector::operator== (Vector &v)
{
   return X() == v.X() && Y() == v.Y() && Z() == v.Z();
}