/* W = sqrt(inv(cov(X)))  */
void ComputeWhitener (double *W, double *X, int n, int T)  
{//ok
  double threshold_W  = RELATIVE_W_THRESHOLD /  sqrt((double) T) ;
  double *Cov  = (double *) calloc(n*n,     sizeof(double)) ; 
  double rescale ;
  int i,j ;

  if (Cov == NULL) OutOfMemory() ;

  EstCovMat (Cov, X, n, T) ; 

  printf ("covmat\n");
  PrintMat (Cov, n, n) ;
  printf ("\n");

  Diago (Cov, W, n, threshold_W)  ;

  printf ("diago\n");
  PrintMat (Cov, n, n) ;
  printf ("\n");

  for (i=0; i<n; i++) {
    rescale= 1.0 / sqrt (Cov[i+i*n]) ;
    for (j=0; j< n ; j++) 
      W[i*n+j] = rescale * W[i*n+j] ;
  }
  free(Cov);//done
}
コード例 #2
0
ファイル: dls_ml.c プロジェクト: gasche/sundialsml
CAMLprim value c_densematrix_print_mat(value va)
{
    CAMLparam1(va);
    PrintMat(DLSMAT(va));
    fflush(stdout);
    CAMLreturn (Val_unit);
}
コード例 #3
0
void printNumberByMat(IplImage* getNumberPicture, vector<ContourData> contourData){
    CvMat *srcMat, matHeader;
    for (int i = 0; i < contourData.size(); i++) {
        cvSetImageROI(getNumberPicture, cvRect(contourData[i].getMinX(), contourData[i].getMinY(), contourData[i].getWidth(), contourData[i].getHeight()));
        srcMat = cvGetMat(getNumberPicture, &matHeader);
        PrintMat(srcMat, "srcMat");
    }
}
コード例 #4
0
int main (int argc, char* argv[])
{
    int size = 10, bound = 5, rate = 5;
    char* OUTPATH = "data_input";
    int b_print = 0;    //switch for the print
    int option;
    int temp,i,j;
    int ** A;
    FILE *op;

    while ((option = getopt(argc, argv, "s:b:r:po:")) != -1)
        switch(option){
            case 's': size = strtol(optarg, NULL, 10); break;
            case 'b': bound = strtol(optarg, NULL, 10);break;
            case 'r': rate = strtol(optarg, NULL, 10);
            case 'p': b_print = 1; break;
            case 'o': OUTPATH = optarg; break;
            case '?': printf("Unexpected Options. \n"); return -1;
        }

    A = CreateMat(size);
    srand(time(NULL));
    for (i = 0; i < size; ++i){
        for (j = i; j < size; ++j){
            if (rand() % 100 <= rate)
                A[i][j] = INF * bound;
            else
                A[i][j] = rand() % bound + 1;
            A[j][i] = A[i][j];
        }
    }
    for (i = 0; i < size; ++i){
        A[i][i] = 0;
    }

    if ((op = fopen(OUTPATH,"w")) == NULL){
        printf("Cant open a file!/n");
        return -2;
    }
    fprintf(op,"%d\n\n", size);
    for (i = 0; i < size; ++i) {
        for (j = 0; j < size; ++j){
            fprintf(op,"%d\t", A[i][j]);
        }
        fprintf(op,"\n");
    }
    fclose(op);

    if (b_print){
        printf("The matrix size is %d\n", size);
        printf("=====================================\n");
        printf("Matrix A is \n");
        PrintMat(A, size);
    }

    DestroyMat(A, size);
	return 0;
}
コード例 #5
0
/*
 *  function calculates a jacobian matrix
 */
static
int nlsDenseJac(long int N, N_Vector vecX, N_Vector vecFX, DlsMat Jac, void *userData, N_Vector tmp1, N_Vector tmp2)
{
  NLS_KINSOL_USERDATA *kinsolUserData = (NLS_KINSOL_USERDATA*) userData;
  DATA* data = kinsolUserData->data;
  threadData_t *threadData = kinsolUserData->threadData;
  int sysNumber = kinsolUserData->sysNumber;
  NONLINEAR_SYSTEM_DATA *nlsData = &(data->simulationInfo->nonlinearSystemData[sysNumber]);
  NLS_KINSOL_DATA* kinsolData = (NLS_KINSOL_DATA*) nlsData->solverData;

  /* prepare variables */
  double *x = N_VGetArrayPointer(vecX);
  double *fx = N_VGetArrayPointer(vecFX);
  double *xScaling = NV_DATA_S(kinsolData->xScale);
  double *fRes = NV_DATA_S(kinsolData->fRes);
  double xsave, xscale, sign;
  double delta_hh;
  const double delta_h = sqrt(DBL_EPSILON*2e1);

  long int i,j;

  /* performance measurement */
  rt_ext_tp_tick(&nlsData->jacobianTimeClock);

  for(i = 0; i < N; i++)
  {
    xsave = x[i];
    delta_hh = delta_h * (fabs(xsave) + 1.0);
    if ((xsave + delta_hh >=  nlsData->max[i]))
      delta_hh *= -1;
    x[i] += delta_hh;

    /* Calculate difference quotient */
    nlsKinsolResiduals(vecX, kinsolData->fRes, userData);

    /* Calculate scaled difference quotient */
    delta_hh = 1. / delta_hh;

    for(j = 0; j < N; j++)
    {
      DENSE_ELEM(Jac, j, i) = (fRes[j] - fx[j]) * delta_hh;
    }
    x[i] = xsave;
  }

  /* debug */
  if (ACTIVE_STREAM(LOG_NLS_JAC)){
    infoStreamPrint(LOG_NLS_JAC, 0, "##KINSOL## omc dense matrix.");
    PrintMat(Jac);
  }

  /* performance measurement and statistics */
  nlsData->jacobianTime += rt_ext_tp_tock(&(nlsData->jacobianTimeClock));
  nlsData->numberOfJEval++;

  return 0;
}
コード例 #6
0
static int build_nbayes_classifier( char* data_filename, CvNormalBayesClassifier **nbayes){
    const int var_count = 51;
    CvMat* data = 0;
    CvMat train_data;
    CvMat* responses;

    int ok = read_num_class_data( data_filename, 51, &data, &responses );
    int nsamples_all = 0;
    int i, j;
    double train_hr = 0, test_hr = 0;
    CvANN_MLP mlp;

    if( !ok ){
        printf( "No se pudo leer la información de entrenamiento %s\n", data_filename );
        return -1;
    }

    printf( "La base de datos %s está siendo cargada...\n", data_filename );
    nsamples_all = data->rows;

    printf( "Entrenando el clasificador...\n");
	// 1. unroll the responses
    cvGetRows( data, &train_data, 0, nsamples_all);
    // 2. train classifier
    CvMat* train_resp = cvCreateMat( nsamples_all, 1, CV_32FC1);
    for (int i = 0; i < nsamples_all; i++)
        train_resp->data.fl[i] = responses->data.fl[i];
	*nbayes = new CvNormalBayesClassifier(&train_data, train_resp);

	if(DEBUG){
		std::cout << "Train_data = "<< std::endl << std::endl;
		PrintMat(&train_data);
		std::cout << "Train_resp = "<< std::endl << " "  << train_resp << std::endl << std::endl;
		PrintMat(train_resp);
	}
    cvReleaseMat( &train_resp );
    cvReleaseMat( &data );
    cvReleaseMat( &responses );
    return 0;
}
コード例 #7
0
void StartAssignment2()
{
	cv::Mat TrainingMask = ReadImageFromTXT("training_mask.txt");

	cv::Mat TrainingImg = ReadImageFromTXT("mosaic1_train.txt");
	std::vector<int> offsets;
	//Direction 1
	offsets.push_back(1);
	offsets.push_back(0);
	//Direction 2
	offsets.push_back(1);
	offsets.push_back(1);

	//Training
	//Calculate the features, Q1 to Qn.
	std::vector<cv::Mat> QFeatImgs = ComputeQFeatureImgs(TrainingImg, offsets);
	
	//Use the test mask to generate a descriptor using the N means of the N features for all M classes. We should have M descriptors now.
	std::vector<ClassDescriptor> Descriptors = ComputeClassDescriptors(QFeatImgs, TrainingMask);
	//Use the function cv::calcCovarMatrix() to calculate the covariance matrix for each class descriptor.
	

	//Classification
	cv::Mat ImgTOClassify = ReadImageFromTXT("mosaic2_test.txt");

	//Calculate the new feature imgs.
	QFeatImgs = ComputeQFeatureImgs(ImgTOClassify, offsets);

	std::vector<cv::Mat> CovarMats;
	//Generate feature imgs. Store each pixel into an array called X;
	//Compute the QFeature
	//Calculate descriptor from the QFeature images.
	//Use the function given in the book to calculate the probability of a pixel being class 1...M. Select the one with the highest probability. 
	//Input is the image, the class descriptors and the covariance matrices.
	auto samples = computeSamples(TrainingMask, QFeatImgs);
	cv::Mat classifiedImage = MultivariateGaussian(ImgTOClassify, Descriptors, samples, QFeatImgs);
	PrintMat(classifiedImage);
	cv::imshow("ClassifiedImage", 63 * classifiedImage);
	cv::imshow("ClassifiedImageBase", 63 * TrainingMask);
	cv::waitKey();
	float accuracy = ConfusionMatrix(TrainingMask, classifiedImage);

	std::cout << "Accuracy of classifier: " << accuracy;

}
コード例 #8
0
void classify(CvNormalBayesClassifier *nbayes){
	/// Probando el clasificador
	CvMat sample = cvMat(1, 51, CV_32FC1, relevanceVector);
	CvMat *result = cvCreateMat(1, 1, CV_32FC1);
	// Predict
	float prediccion = 0.0000;
	if(nbayes != NULL){
		std::cout << "I GOT HERE" << std::endl;
		PrintMat(&sample);
		//prediccion = nbayes->predict(&sample, result);
		//prediccion = nbayes->predict(&sample, 0);
		prediccion = (float) nbayes->predict(&sample);
		std::cout << "I GOT HERE 1" << std::endl;
	}
	/* Imprimiendo el Valor */
    //printf("Classify = %f\n", result->data.fl[0]);
    printf("Classify = %f\n",prediccion);
	// Liberando Memoria */
	cvReleaseMat(&result);
}
コード例 #9
0
cv::Mat MultivariateGaussian(cv::Mat Img, std::vector<ClassDescriptor>& Descriptors, std::vector<std::vector<std::vector<float>>>& samples, std::vector<cv::Mat>& featureImgs)
{
	int numClasses = 4;
	cv::Mat ClassificationMask(Img.rows, Img.cols, CV_8U);
	std::vector<cv::Mat> ProbabilityForClass(numClasses);
	for (size_t i = 0; i < numClasses; i++) {
		ProbabilityForClass[i] = cv::Mat::zeros(Img.rows, Img.cols, CV_32F);
	}

	for (size_t i = 0; i < numClasses; i++) {
		float d = Descriptors[0].num_features_t_;
		cv::Mat myu = Descriptors[i].Descriptor;
		cv::Mat sigma;
		std::vector<std::vector<float>> S = samples[i];
		//cv::calcCovarMatrix(S, sigma, myu, CV_COVAR_ROWS, CV_32F);
		sigma = CalcCovarMatrix(S, myu, d);


		for (size_t y_t = 0; y_t < Img.rows; y_t++) {
			std::cout << "Calculating probability row " << y_t << std::endl;
			for (size_t x_t = 0; x_t < Img.cols; x_t++) {

				//Calculate the probability for all the classes. 
				cv::Mat x = getPixelDescriptor(featureImgs, y_t, x_t);
			
					
					//PrintMat(sigma);
					//std::cout << "\n\n";


				float n = 4; //What is this? Num classes it seems.
				if (x.rows != myu.rows || x.rows != sigma.rows)
					std::cout << "Something bad happened as the vectors x and myu and the matrix sigma does not match.";

				float detSigma = cv::determinant(sigma);
				float scalar = 1 / (pow(2 * M_PI, n / 2) * pow(cv::determinant(sigma), 0.5f));
				
				cv::Mat difference;
				cv::subtract(x, myu, difference, cv::Mat(), CV_32F);
				cv::Mat exponent = -0.5f * difference.t() * sigma.inv() * difference;

				float Probability = scalar * exp(exponent.at<float>(0, 0));
				if (Probability > 90000.0f) {
					PrintMat(sigma);
					std::cout << "Infinite probability detected." << std::endl;
				}
				ProbabilityForClass[i].at<float>(y_t, x_t) = Probability;
			}
		}
		cv::imshow("Probability image", 64*ProbabilityForClass[i]);
		cv::waitKey();
	}


	for (size_t y_t = 0; y_t < Img.rows; y_t++) {
		std::cout << "Classified row " << y_t << std::endl;
		for (size_t x_t = 0; x_t < Img.cols; x_t++) {
			int MostProbableClass = 0;
			float maxProbability = 0;
			for (size_t i = 0; i < ProbabilityForClass.size(); i++) {
				float currentClassProbability = ProbabilityForClass[i].at<float>(y_t, x_t);
			
				if (currentClassProbability > maxProbability) {
					maxProbability = currentClassProbability;
					MostProbableClass = i;
				}
			}

			ClassificationMask.at<uchar>(y_t, x_t) = MostProbableClass;
		}
	}

	return ClassificationMask;
}
コード例 #10
0
ファイル: Exercise6.1.c プロジェクト: CarlChenCC/examples
int main (int argc, const char * argv[])
{
    if ( argc != 2 )
    {
        fprintf(stderr, "Usage: <image>\n");
        exit(1);
    }

    IplImage* image = cvLoadImage(argv[1], CV_LOAD_IMAGE_GRAYSCALE);

    if ( image == NULL )
    {
        fprintf(stderr, "Couldn't load image %s\n", argv[1]);
        exit(1);
    }

    IplImage* dst = cvCloneImage(image);
    //cvSetZero(dst);

    CvMat* rotation = cvCreateMat(2, 3, CV_32FC1);

#if 0
    // Optimized for a finding 3 pixel wide lines.
    float zeroDegreeLineData[] = {
        -10, -10, -10, -10, -10,
        3, 3, 3, 3, 3,
        14, 14, 14, 14, 14,
        3, 3, 3, 3, 3,
        -10, -10, -10, -10, -10
    };
#if 0
    float zeroDegreeLineData[] = {
        10, 10, 10, 10, 10,
        -3, -3, -3, -3, -3,
        -14, -14, -14, -14, -14,
        -3, -3, -3, -3, -3,
        10, 10, 10, 10, 10
    };
#endif

    CvMat zeroDegreeLine = cvMat(5, 5, CV_32FC1, zeroDegreeLineData);
    PrintMat("Zero Degree Line", &zeroDegreeLine);

    cv2DRotationMatrix(cvPoint2D32f(2,2), 60.0, 1.0, rotation);

    CvMat* kernel = cvCreateMat(5, 5, CV_32FC1);

#else
    // Optimized for finding 1 pixel wide lines. The sum of all co-efficients is 0, so this kernel has
    // the tendency to send pixels towards zero
#if 0
    float zeroDegreeLineData[] = {
        10, 10, 10,
        -20, -20, -20,
        10, 10, 10
    };
#elif 0
    float zeroDegreeLineData[] = {
        -10, -10, -10,
        20, 20, 20,
        -10, -10, -10
    };
#else
    // Line detector optimized to find a horizontal line 1 pixel wide that is darker (smaller value) than it’s surrounding pixels. This works because darker (smaller value) horizontal 1 pixel wide lines will have a smaller magnitude negative
    // component, which means their convoluted value will be higher than surrounding pixels. See Convolution.numbers
    // for a simple example how this works.
    float zeroDegreeLineData[] = {
        1, 1, 1,
        -2, -2, -2,
        1, 1, 1
    };
#endif

    CvMat zeroDegreeLine = cvMat(3, 3, CV_32FC1, zeroDegreeLineData);
    PrintMat("Zero Degree Line", &zeroDegreeLine);

    // Going to rotate the horizontal line detecting kernel by 60 degrees to that it will detect 60 degree lines.
    cv2DRotationMatrix(cvPoint2D32f(1,1), 60.0, 1.0, rotation);

    CvMat* kernel = cvCreateMat(3, 3, CV_32FC1);

#endif

    PrintMat("Rotation", rotation);

    cvWarpAffine(&zeroDegreeLine, kernel, rotation, CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS, cvScalarAll(0));
    PrintMat("Kernel", kernel);

    cvFilter2D( image, dst, kernel, cvPoint(-1,-1));

    cvNamedWindow("main", CV_WINDOW_NORMAL);
    cvShowImage("main", image);
    cvWaitKey(0);

    cvShowImage("main", dst);
    cvWaitKey(0);

    return 0;
}
void Jade (
	     double *B, /* Output. Separating matrix. nbc*nbc */
	     double *X, /* Input.  Data set nbc x nbs */
	     int nbc,   /* Input.  Number of sensors  */
	     int nbs    /* Input.  Number of samples  */
	     )
{
  double threshold_JD = RELATIVE_JD_THRESHOLD / sqrt((double)nbs) ;
  int rots = 1 ;
  double *Transf  = (double *) calloc(nbc*nbc,         sizeof(double)) ; 
  double *CumTens = (double *) calloc(nbc*nbc*nbc*nbc, sizeof(double)) ; 
  if ( Transf == NULL || CumTens == NULL ) OutOfMemory() ;

  /* Init */
  Message0(2, "Init...\n") ;
  Identity(B, nbc); 

  MeanRemoval(X, nbc, nbs)  ; 
printf ("mean\n");

  PrintMat (X, nbc, nbs) ;
printf ("\n");

Message0(2, "Whitening...\n") ;	
  ComputeWhitener(Transf, X, nbc, nbs)  ; 
	
  printf ("Whitener:\n");
  PrintMat (Transf, nbc, nbc) ;
printf ("\n");

  Transform (X, Transf,          nbc, nbs) ;
printf ("Trans X\n");
PrintMat (X, nbc, nbs) ;
printf ("\n");

  Transform (B, Transf,          nbc, nbc) ;


  Message0(2, "Estimating the cumulant tensor...\n") ;
  EstCumTens (CumTens, X,      nbc, nbs) ;

  printf ("cum tens \n");
  PrintMat (CumTens, nbc*nbc, nbc*nbc) ;
	printf ("\n");

  Message0(2, "Joint diagonalization...\n") ;
  rots = JointDiago (CumTens, Transf,  nbc, nbc*nbc, threshold_JD) ;
  MessageI(3, "Total number of plane rotations: %6i.\n", rots) ;
  MessageF(3, "Size of the total rotation: %10.7e\n", NonIdentity(Transf,nbc) )  ;
  
  printf ("Trans mat\n");
  PrintMat (Transf, nbc, nbc) ;
  printf ("\n");

  Message0(2, "Updating...\n") ;
  Transform  (X, Transf,        nbc, nbs ) ;
  Transform  (B, Transf,        nbc, nbc ) ;

  printf ("resultant \n");
  PrintMat (X, nbc, nbs) ;
  printf ("\n");

  printf ("estimated mix \n");
  PrintMat (B, nbc, nbc) ;
  printf ("\n");

  free(Transf) ; 
  free(CumTens) ;
}
コード例 #12
0
ファイル: lucas_kanade_opencv.cpp プロジェクト: kroo/BBS
void processImagePair(const char *file1, const char *file2, CvVideoWriter *out, struct CvMat *currentOrientation) {
  // Load two images and allocate other structures
	IplImage* imgA = cvLoadImage(file1, CV_LOAD_IMAGE_GRAYSCALE);
	IplImage* imgB = cvLoadImage(file2, CV_LOAD_IMAGE_GRAYSCALE);
	IplImage* imgBcolor = cvLoadImage(file2);
 
	CvSize img_sz = cvGetSize( imgA );
	int win_size = 15;
  
	// Get the features for tracking
	IplImage* eig_image = cvCreateImage( img_sz, IPL_DEPTH_32F, 1 );
	IplImage* tmp_image = cvCreateImage( img_sz, IPL_DEPTH_32F, 1 );
 
	int corner_count = MAX_CORNERS;
	CvPoint2D32f* cornersA = new CvPoint2D32f[ MAX_CORNERS ];
 
	cvGoodFeaturesToTrack( imgA, eig_image, tmp_image, cornersA, &corner_count,
		0.05, 3.0, 0, 3, 0, 0.04 );
 
  fprintf(stderr, "%s: Corner count = %d\n", file1, corner_count);
 
	cvFindCornerSubPix( imgA, cornersA, corner_count, cvSize( win_size, win_size ),
		cvSize( -1, -1 ), cvTermCriteria( CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 50, 0.03 ) );
 
	// Call Lucas Kanade algorithm
	char features_found[ MAX_CORNERS ];
	float feature_errors[ MAX_CORNERS ];
 
	CvSize pyr_sz = cvSize( imgA->width+8, imgB->height/3 );
 
	IplImage* pyrA = cvCreateImage( pyr_sz, IPL_DEPTH_32F, 1 );
	IplImage* pyrB = cvCreateImage( pyr_sz, IPL_DEPTH_32F, 1 );
 
	CvPoint2D32f* cornersB = new CvPoint2D32f[ MAX_CORNERS ];
 
  calcNecessaryImageRotation(imgA);
 
	cvCalcOpticalFlowPyrLK( imgA, imgB, pyrA, pyrB, cornersA, cornersB, corner_count, 
		cvSize( win_size, win_size ), 5, features_found, feature_errors,
		 cvTermCriteria( CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.3 ), 0 );
 
   CvMat *transform = cvCreateMat(3,3, CV_32FC1);
   CvMat *invTransform = cvCreateMat(3,3, CV_32FC1);
	// Find a homography based on the gradient
   CvMat cornersAMat = cvMat(1, corner_count, CV_32FC2, cornersA);
   CvMat cornersBMat = cvMat(1, corner_count, CV_32FC2, cornersB);
   cvFindHomography(&cornersAMat, &cornersBMat, transform, CV_RANSAC, 15, NULL);

   cvInvert(transform, invTransform);
   cvMatMul(currentOrientation, invTransform, currentOrientation);
   // save the translated image
 	 IplImage* trans_image = cvCloneImage(imgBcolor);
   cvWarpPerspective(imgBcolor, trans_image, currentOrientation, CV_INTER_CUBIC+CV_WARP_FILL_OUTLIERS);

   printf("%s:\n", file1);
   PrintMat(currentOrientation);

  // cvSaveImage(out, trans_image);
  cvWriteFrame(out, trans_image);

  cvReleaseImage(&eig_image);
  cvReleaseImage(&tmp_image);  
  cvReleaseImage(&trans_image);
  cvReleaseImage(&imgA);
  cvReleaseImage(&imgB);
  cvReleaseImage(&imgBcolor);
  cvReleaseImage(&pyrA);
  cvReleaseImage(&pyrB);
  
  cvReleaseData(transform);
  delete [] cornersA;
  delete [] cornersB;
  
  
}
コード例 #13
0
ファイル: gaussianElim.cpp プロジェクト: zwang4/dividend
int main(int argc, char *argv[]) {

	printf("WG size of kernel 1 = %d, WG size of kernel 2= %d X %d\n", BLOCK_SIZE_0, BLOCK_SIZE_1_X, BLOCK_SIZE_1_Y);
	float *a=NULL, *b=NULL, *finalVec=NULL;
	float *m=NULL;
	int size = -1;

	FILE *fp;

	// args
	char filename[200];
	int quiet=1,timing=0,platform=-1,device=-1;

	// parse command line
	if (parseCommandline(argc, argv, filename,
				&quiet, &timing, &platform, &device, &size)) {
		printUsage();
		return 0;
	}

	context = cl_init_context(platform,device,quiet);

	if(size < 1)
	{
		fp = fopen(filename, "r");
		fscanf(fp, "%d", &size);

		a = (float *) malloc(size * size * sizeof(float));
		InitMat(fp,size, a, size, size);

		b = (float *) malloc(size * sizeof(float));
		InitAry(fp, b, size);

		fclose(fp);

	}
	else
	{
		printf("create input internally before create, size = %d \n", size);

		a = (float *) malloc(size * size * sizeof(float));
		create_matrix(a, size);

		b = (float *) malloc(size * sizeof(float));
		for (int i =0; i< size; i++)
			b[i]=1.0;

	}

	if (!quiet) {    
		printf("The input matrix a is:\n");
		PrintMat(a, size, size, size);

		printf("The input array b is:\n");
		PrintAry(b, size);
	}

	// create the solution matrix
	m = (float *) malloc(size * size * sizeof(float));

	// create a new vector to hold the final answer

	finalVec = (float *) malloc(size * sizeof(float));

	InitPerRun(size,m);

	//begin timing	
	// printf("The result of array b is before run: \n");
	// PrintAry(b, size);

	// run kernels
	ForwardSub(context,a,b,m,size,timing);
	// printf("The result of array b is after run: \n");
	// PrintAry(b, size);

	DIVIDEND_CL_WRAP(clFinish)(command_queue);

	//end timing
	if (!quiet) {
		printf("The result of matrix m is: \n");

		PrintMat(m, size, size, size);
		printf("The result of matrix a is: \n");
		PrintMat(a, size, size, size);
		printf("The result of array b is: \n");
		PrintAry(b, size);

		BackSub(a,b,finalVec,size);
		printf("The final solution is: \n");
		PrintAry(finalVec,size);
	}

	free(m);
	free(a);
	free(b);
	free(finalVec);
	cl_cleanup();
	//OpenClGaussianElimination(context,timing);

	return 0;
}
コード例 #14
0
int main (int argc, char* argv[]){   
	int i, j, option;
	int size = 100;
	int b_print = 0;
	int range = 100;
	double **A, **T, **S;
	double *b;
	double temp;
	char* OUTPATH = "data_input";
	FILE* fp;

	srand(time(NULL));

	while ((option = getopt(argc, argv, "s:b:po:")) != -1)
		switch(option){
			case 's': size = strtol(optarg, NULL, 10); break;
			case 'b': range = strtol(optarg, NULL, 10);break;
			case 'p': b_print = 1; break;
			case 'o': OUTPATH = optarg; break;
			case '?': printf("Unexpected Options. \n"); return -1;
		}
	
	/*Generate the data*/
	A = CreateMat(size, size);
	T = CreateMat(size, size);
	S = CreateMat(size, size);
	b = malloc(size * sizeof(double));
	for (i = 0; i < size; ++i)
		for (j = 0; j < size; ++j){
			A[i][j] = 0;
			T[i][j] = 0;
		}
	MatGen(size, T, (double)range);
	GenPerm(size, A);
	MatMul(size, T, A, S);
	for (i = 0; i < size; ++i){
		temp = (double)(rand() % (int)(range * DECIMAL)) / DECIMAL;
		if (rand() % 2)
			temp *= -1;
		b[i] = temp;
	}
	/*Output the data*/
	if ((fp = fopen(OUTPATH,"w")) == NULL){
		printf("Fail to open a file to save the data. \n");
		return -2;
	}
	fprintf(fp, "%d\n\n", size);
	for (i = 0; i < size; ++i){
		for (j = 0; j < size; ++j)
			fprintf(fp, "%lf\t", S[i][j]);
		fprintf(fp, "\n");
	}
	fprintf(fp, "\n");
	for (i = 0; i < size; ++i)
		fprintf(fp, "%lf\n", b[i]);
	fclose(fp);
	/*Print the result if neccesary*/
	if (b_print){
		printf("The problem size is %d.\n", size);
		printf("============\n The A is \n============\n");
		PrintMat(S, size, size);
		printf("============\n The b is \n============\n");
		PrintVec(b, size);
	}
	DestroyMat(A, size);
	DestroyMat(T, size);
	DestroyMat(S, size);
	free(b);
	return 0;
}