예제 #1
0
파일: vector_test.c 프로젝트: mlmhl/cWeb
int main(int argc, char *argv[]) {
	vector a;
	
	vector_init(&a, 0);

	// test for ptr operations
	int n = 5;
	for (int i = 0; i < n; ++i) {
		char *str = malloc(2);
		v_push_ptr(&a, itoa(i, str, 10));
	}
	vector_print(&a);
	
	for (int i = 0; i < n / 2; ++i) {
		void *p = NULL;
		v_get_ptr(&a, i, &p);
		void *q  =NULL;
		v_get_ptr(&a, n - i - 1, &q);
		v_set_ptr(&a, i, q);
		v_set_ptr(&a, n - i - 1, p);
	}
	vector_print(&a);

	while (vector_length(&a) > 0) {
		v_pop_ptr(&a, NULL);
	}

	return 0;
}
예제 #2
0
/**
*   Create a system of size 9-by-9 with known eigenvalues and compare it with the eigenvalues computed from the QR method implemented in ViennaCL.
**/
int main()
{
  // Change to 'double' if supported by your hardware.
  typedef float ScalarType;

  std::cout << "Testing matrix of size " << 9 << "-by-" << 9 << std::endl;

  viennacl::matrix<ScalarType> A_input(9,9);
  viennacl::matrix<ScalarType> Q(9, 9);
  std::vector<ScalarType> eigenvalues_ref(9);
  std::vector<ScalarType> eigenvalues(9);

  viennacl::vector<ScalarType> vcl_eigenvalues(9);

  initialize(A_input, eigenvalues_ref);

  std::cout << std::endl <<"Input matrix: " << std::endl;
  std::cout << A_input << std::endl;

  viennacl::matrix<ScalarType> A_input2(A_input); // duplicate to demonstrate the use with both std::vector and viennacl::vector


  /**
  * Call the function qr_method_sym() to calculate eigenvalues and eigenvectors
  * Parameters:
  *  -     A_input      - input matrix to find eigenvalues and eigenvectors from
  *  -     Q            - matrix, where the calculated eigenvectors will be stored in
  *  -     eigenvalues  - vector, where the calculated eigenvalues will be stored in
  **/

  std::cout << "Calculation..." << std::endl;
  viennacl::linalg::qr_method_sym(A_input, Q, eigenvalues);

  /**
   *  Same as before, but writing the eigenvalues to a ViennaCL-vector:
   **/
  viennacl::linalg::qr_method_sym(A_input2, Q, vcl_eigenvalues);

  /**
  *   Print the computed eigenvalues and eigenvectors:
  **/
  std::cout << std::endl << "Eigenvalues with std::vector<T>:" << std::endl;
  vector_print(eigenvalues);
  std::cout << "Eigenvalues with viennacl::vector<T>: " << std::endl << vcl_eigenvalues << std::endl;
  std::cout << std::endl << "Reference eigenvalues:" << std::endl;
  vector_print(eigenvalues_ref);
  std::cout << std::endl;
  std::cout << "Eigenvectors - each column is an eigenvector" << std::endl;
  std::cout << Q << std::endl;

  /**
  *  That's it. Print a success message and exit.
  **/
  std::cout << std::endl;
  std::cout << "------- Tutorial completed --------" << std::endl;
  std::cout << std::endl;

  return EXIT_SUCCESS;
}
int test_over_gelsd(StreamType& oss)
{
	typedef typename bindings::value_type<MatType>::type val_t;
	typedef typename bindings::remove_imaginary<val_t>::type real_t;
	const real_t rcond = -1;    // use machine precision
	fortran_int_t rank;

	// return value
	int err = 0;

	// overdetermined matrix test
	MatType mat(MatrixGenerator<MatType>()(row_size, col_range));
	VecType vec(VectorGenerator<VecType>()(row_size));

	//const int m = bindings::size_row(mat);
	const int n = bindings::size_column(mat);
	bindings::detail::array<real_t> s(n);

#if USE_OPTIMAL_WORKSPACE
	MatType optimalmat(mat);
	VecType optimalvec(vec);
	err += lapack::gelsd(optimalmat, optimalvec, s, rcond, rank, lapack::optimal_workspace());
	VecType optimalanswer(ublas::project(optimalvec, ublas::range(0, n)));
	VecType optimal_check = ublas::prod(mat, optimalanswer);
#endif
#if USE_MINIMAL_WORKSPACE
	MatType minimalmat(mat);
	VecType minimalvec(vec);
	err += lapack::gelsd(minimalmat, minimalvec, s, rcond, rank, lapack::minimal_workspace());
	VecType minimalanswer(ublas::project(minimalvec, ublas::range(0, n)));
	VecType minimal_check = ublas::prod(mat, minimalanswer);
#endif

	matrix_print(oss, "A", mat);
	oss << std::endl;
	vector_print(oss, "B", vec);
	oss << std::endl;

#if USE_OPTIMAL_WORKSPACE
	vector_print(oss, "optimal workspace x", optimalanswer);
	oss << std::endl;
#endif
#if USE_MINIMAL_WORKSPACE
	vector_print(oss, "minimal workspace x", minimalanswer);
	oss << std::endl;
#endif
#if USE_OPTIMAL_WORKSPACE
	// check A*x=B
	vector_print(oss, "optimal A*x=B", optimal_check);
	oss << std::endl;
#endif
#if USE_MINIMAL_WORKSPACE
	vector_print(oss, "minimal A*x=B", minimal_check);
	oss << std::endl;
#endif

	return err;
}
예제 #4
0
int test_over_gelsd(StreamType& oss)
{
	// return value
	int err = 0;

	// overdetermined matrix test
	MatType mat(MatrixGenerator<MatType>()(row_size, col_range));
	VecType vec(VectorGenerator<VecType>()(row_size));

	const int m = traits::matrix_size1(mat);
	const int n = traits::matrix_size2(mat);

#if USE_OPTIMAL_WORKSPACE
	MatType optimalmat(mat);
	VecType optimalvec(vec);
	err += lapack::gelsd(optimalmat, optimalvec, lapack::optimal_workspace());
	VecType optimalanswer(ublas::project(optimalvec, ublas::range(0, n)));
	VecType optimal_check = ublas::prod(mat, optimalanswer);
#endif
#if USE_MINIMAL_WORKSPACE
	MatType minimalmat(mat);
	VecType minimalvec(vec);
	err += lapack::gelsd(minimalmat, minimalvec, lapack::minimal_workspace());
	VecType minimalanswer(ublas::project(minimalvec, ublas::range(0, n)));
	VecType minimal_check = ublas::prod(mat, minimalanswer);
#endif

	matrix_print(oss, "A", mat);
	oss << std::endl;
	vector_print(oss, "B", vec);
	oss << std::endl;

#if USE_OPTIMAL_WORKSPACE
	vector_print(oss, "optimal workspace x", optimalanswer);
	oss << std::endl;
#endif
#if USE_MINIMAL_WORKSPACE
	vector_print(oss, "minimal workspace x", minimalanswer);
	oss << std::endl;
#endif
#if USE_OPTIMAL_WORKSPACE
	// check A*x=B
	vector_print(oss, "optimal A*x=B", optimal_check);
	oss << std::endl;
#endif
#if USE_MINIMAL_WORKSPACE
	vector_print(oss, "minimal A*x=B", minimal_check);
	oss << std::endl;
#endif

	return err;
}
예제 #5
0
파일: main.c 프로젝트: adilbaig/screener
int main(int argc, char *argv[])
{
	// Read a file of company TRBC codes and RICs
	if(argc < 2) {
		return usage(argv[0]);
	}

	FILE *stream = fopen(argv[1], "r");
	if (!stream) {
		perror("Could not open file");
		exit(1);
	}

	vector_init(&rics);

	char *line = NULL;
	size_t len = 0;
	ssize_t read;

	while((read = getline(&line, &len, stream)) > 0 )
	{
		char code[10];
		char *ric = NULL;

		printf("%s\n", line);

		int scret = sscanf(line, "\"%10s\",\"%m[a-zA-Z\.]\"", code, &ric);
		if(scret > 0) {
			printf("Code : %s, RIC : %s\n", code, ric);


			/* Why assign to NULL and check?
			 * Because, if sscanf fails on a line, ric will not be assigned
			 * but we will attempt to free it. To avoid that, we check if
			 * ric has been assigned by checking if the address it is pointing
			 * to has changed.
			 */
			if(ric != NULL) {
				int idx = vector_append(&rics, ric);//, strlen(ric));
				//add_node(code, idx);
				// Now add it to the tree
				free(ric);
			}
		}
	}

	if(line != NULL) {
		free(line);
	}

	getc(stdin);

	vector_print(&rics);
	vector_free(&rics);

	fclose(stream);
	return 0;
}
예제 #6
0
void matrix_setView3D(Matrix *vtm, View3D *view){
	if(NULL != vtm && NULL != view){
		Vector u;
		Vector vup = view->vup;
		Vector vpn = view->vpn;
		Matrix project;
		double bPrime = view->d +view->b;
		double dPrime = view->d/bPrime;

		matrix_identity(vtm);
		printf("before everything:\n");
 		matrix_print(vtm, stdout);

		vector_cross(&vup,&vpn,&u);
		vector_cross(&vpn,&u,&vup);
		printf("vrp:\n");
		vector_print(&view->vrp,stdout);

		matrix_translate(vtm, -view->vrp.val[0], -view->vrp.val[1],-view->vrp.val[2]);
		printf("After VRP translation:\n");
 		matrix_print(vtm, stdout);

		vector_normalize(&u);
		vector_normalize(&vpn);
		vector_normalize(&vup);
		matrix_rotateXYZ(vtm, &u, &vup, &vpn );
		printf("After Rxyz :\n");
  		matrix_print(vtm, stdout);

		matrix_translate(vtm, 0, 0,view->d);
		printf("After translating COP to origin:\n");
  		matrix_print(vtm, stdout);
  		
		
		matrix_scale(vtm, (2*view->d)/(bPrime*view->du), (2*view->d)/(bPrime*view->dv), 1/bPrime);
		printf("After scaling to CVV:\n");
 		matrix_print(vtm, stdout);

		matrix_identity(&project);
		project.m[3][3]=0;
		project.m[3][2]=1/dPrime;
		printf("projection:\n");
		matrix_print(&project, stdout);
		matrix_multiply(&project,vtm,vtm);
		printf("After perspective:\n");
 		matrix_print(vtm, stdout);

		matrix_scale2D(vtm, -view->screenx/(2*dPrime), -view->screeny/(2*dPrime));
		printf("After scale to image coords:\n");
  		matrix_print(vtm, stdout);

		matrix_translate2D(vtm, view->screenx/2, view->screeny/2);
		printf("After final translation to image coords:\n");
  		matrix_print(vtm, stdout);
	}

}
예제 #7
0
static void check_vector_multiplication_on_random_number______sent_size_vector_array_____returned(void **state){
    const int test_arr1[3] = {1, 2, 3};
vector_t * vc = vector_new_test(3,test_arr1);

vector_print(vc);
int mn=vector_return_value_on_k_position(vc,0);

assert_int_equal(vector_return_value_on_k_position(vc,0),1*mn);
assert_int_equal(vector_return_value_on_k_position(vc,1),2*mn);
assert_int_equal(vector_return_value_on_k_position(vc,2),3*mn);
vector_free(vc);
}
예제 #8
0
int main() {

  igraph_t g;
  igraph_vector_t vids, layers, parents;

  igraph_ring(&g, 10, IGRAPH_UNDIRECTED, 0, 0);
  igraph_vector_init(&vids, 0);
  igraph_vector_init(&layers, 0);
  igraph_vector_init(&parents, 0);
  igraph_i_bfs(&g, 0, IGRAPH_ALL, &vids, &layers, &parents);
  vector_print(&vids);
  vector_print(&layers);
  vector_print(&parents);
  igraph_destroy(&g);  

  igraph_tree(&g, 20, 2, IGRAPH_TREE_UNDIRECTED);
  igraph_i_bfs(&g, 0, IGRAPH_ALL, &vids, &layers, &parents);
  vector_print(&vids);
  vector_print(&layers);
  vector_print(&parents);
  igraph_destroy(&g);  
  
  igraph_vector_destroy(&vids);
  igraph_vector_destroy(&layers);
  igraph_vector_destroy(&parents);

  return 0;
}
예제 #9
0
void input_hilbert(matrix_t *m, vector_t *f)
{
        input_hilbert_m(m);
        int N = m->size;

        *f = vector_create(N);
        for (int i=0; i<N; i++) {
                f->vector[i] = i + 1;
        }
        
        if (N <= 10) {
                fprintf(stderr, "[INPUT] Vector:\n");
                vector_print(stderr, *f, FORMAT_TEXT);
        }
}
예제 #10
0
파일: lplsh.c 프로젝트: caomw/Sampled-LSH
/**
 * @brief Stores lists in the hash table.
 *
 * @param list List to be hashed
 * @param id ID of the list
 * @param hash_table Hash table
 */ 
uint lplsh_store_vector(Vector *vector, uint id, HashTableLP *hash_table)
{
     uint index;

     // get index of the hash table
     printf("\n Vector %d", id);
     vector_print(vector);
     index = lplsh_get_index(vector, hash_table);
     if (hash_table->buckets[index].items.size == 0){ // mark used bucket
          Item new_used_bucket = {index, 1};
          list_push(&hash_table->used_buckets, new_used_bucket);
     }

     // store list id in the hash table
     Item new_item = {id, 1};
     list_push(&hash_table->buckets[index].items, new_item);

     return index;
}
예제 #11
0
파일: vectors.c 프로젝트: gauravcmu/Vectors
int main()
{

    //create a vector vec
    vector * vec = NULL;
    vec = create_vector(4);
    if (!vec)
    printf("\n FAILED");

    
    push_back(vec, 4); 
    push_back(vec, 5); 
    push_back(vec, 6); 
    push_back(vec, 7); 
    push_back(vec, 8); 
    push_back(vec, 9); 
    insert(vec, 2, 11);
    push_back(vec, 10); 
    vector_print(vec);

    vector_destroy(vec);
   return 0; 
}
예제 #12
0
파일: main.c 프로젝트: texane/fsub
int main(int ac, char** av)
{
  int error = 0;

  matrix_t* a = NULL;
  matrix_t* const_a = NULL;
  vector_t* x = NULL;
  vector_t* const_b = NULL;
  vector_t* b = NULL;

#if CONFIG_FSUB_SEQ
  vector_t* bseq = NULL;
#endif

  if (matrix_create_lower(&const_a, CONFIG_ASIZE) == -1)
    goto on_error;
  if (matrix_create_empty(&a, CONFIG_ASIZE) == -1)
    goto on_error;

  if (vector_create(&const_b, CONFIG_ASIZE) == -1)
    goto on_error;
  if (vector_create_empty(&b, CONFIG_ASIZE) == -1)
    goto on_error;
#if CONFIG_FSUB_SEQ
  if (vector_create_empty(&bseq, CONFIG_ASIZE) == -1)
    goto on_error;
#endif

  if (vector_create_empty(&x, CONFIG_ASIZE) == -1)
    goto on_error;

#if CONFIG_FSUB_PTHREAD
  fsub_pthread_initialize();
#endif

  /* apply forward substitution: ax = b */
  size_t i;
  for (i = 0; i < CONFIG_ITER_COUNT; ++i)
  {
    struct timeval tms[4];

    matrix_copy(a, const_a);
    vector_copy(b, const_b);
#if CONFIG_FSUB_SEQ
    vector_copy(bseq, const_b);
#endif

#if CONFIG_FSUB_PTHREAD
    gettimeofday(&tms[0], NULL);
    fsub_pthread_apply(const_a, b);
    gettimeofday(&tms[1], NULL);
    timersub(&tms[1], &tms[0], &tms[2]);
#elif CONFIG_FSUB_XKAAPI
    gettimeofday(&tms[0], NULL);
    fsub_xkaapi_apply(const_a, b);
    gettimeofday(&tms[1], NULL);
    timersub(&tms[1], &tms[0], &tms[2]);
#endif

#if CONFIG_FSUB_GSL
    fsub_gsl_apply(a, x, const_b);
#endif

#if CONFIG_FSUB_SEQ
    gettimeofday(&tms[0], NULL);
    fsub_seq_apply(a, bseq);
    gettimeofday(&tms[1], NULL);
    timersub(&tms[1], &tms[0], &tms[3]);
#endif

    /* report times */
#if CONFIG_TIME
#if CONFIG_FSUB_PTHREAD || CONFIG_FSUB_XKAAPI
    printf("par: %lu\n", tms[2].tv_sec * 1000000 + tms[2].tv_usec);
#endif
#if CONFIG_FSUB_SEQ
    printf("seq: %lu\n", tms[3].tv_sec * 1000000 + tms[3].tv_usec);
#endif
#endif

    /* check against gsl implm */
#if CONFIG_FSUB_GSL
#if CONFIG_FSUB_SEQ
    if (vector_cmp(bseq, x))
    {
      printf("invalid seq\n");
      error = -1;
    }
#endif
#if CONFIG_FSUB_PTHREAD || CONFIG_FSUB_XKAAPI
    if (vector_cmp(b, x))
    {
      printf("invalid parallel\n");
      error = -1;
    }
#endif
    if (error == -1)
    {
      vector_print(b);
      vector_print(x);
      goto on_error;
    }
#endif
  }

#if CONFIG_FSUB_PTHREAD
  fsub_pthread_finalize();
#endif

 on_error:
  if (a != NULL)
    matrix_destroy(a);
  if (const_a != NULL)
    matrix_destroy(const_a);
  if (x != NULL)
    vector_destroy(x);
  if (b != NULL)
    vector_destroy(b);
  if (const_b != NULL)
    vector_destroy(const_b);
#if CONFIG_SEQ
  if (bseq != NULL)
    vector_destroy(bseq);
#endif

  return error;
}
예제 #13
0
파일: subvq.c 프로젝트: 10v/cmusphinx
subvq_t *subvq_init (char *file)
{
    FILE *fp;
    char line[16384];
    int32 n_sv;
    int32 s, k, n, r, c;
    char *strp;
    subvq_t *vq;
    
    E_INFO("Loading Mixture Gaussian sub-VQ file '%s'\n", file);
    
    vq = (subvq_t *) ckd_calloc (1, sizeof(subvq_t));
    
    fp = myfopen(file, "r");
    
    /* Read until "Sub-vectors" */
    for (;;) {
	if (fgets (line, sizeof(line), fp) == NULL)
	    E_FATAL("Failed to read VQParam header\n");
	if (sscanf (line, "VQParam %d %d -> %d %d",
		    &(vq->origsize.r), &(vq->origsize.c), &(vq->n_sv), &(vq->vqsize)) == 4)
	    break;
    }
    
    n_sv = vq->n_sv;
    
    vq->svsize = (int32 *) ckd_calloc (n_sv, sizeof(int32));
    vq->featdim = (int32 **) ckd_calloc (n_sv, sizeof(int32 *));
    vq->mean = (float32 ***) ckd_calloc (n_sv, sizeof(float32 **));
    vq->var  = (float32 ***) ckd_calloc (n_sv, sizeof(float32 **));
    vq->map = (int32 ***) ckd_calloc_3d (vq->origsize.r, vq->origsize.c, n_sv, sizeof(int32));
    vq->cb_invalid = bitvec_alloc (vq->origsize.r);
    
    /* Read subvector sizes and feature dimension maps */
    for (s = 0; s < n_sv; s++) {
	if ((fgets (line, sizeof(line), fp) == NULL) ||
	    (sscanf (line, "Subvector %d length %d%n", &k, &(vq->svsize[s]), &n) != 2) ||
	    (k != s))
	    E_FATAL("Error reading length(subvector %d)\n", s);
	
	vq->mean[s] = (float32 **) ckd_calloc_2d (vq->vqsize, vq->svsize[s], sizeof(float32));
	vq->var[s]  = (float32 **) ckd_calloc_2d (vq->vqsize, vq->svsize[s], sizeof(float32));
	vq->featdim[s] = (int32 *) ckd_calloc (vq->svsize[s], sizeof(int32));
	
	for (strp = line+n, c = 0; c < vq->svsize[s]; c++) {
	    if (sscanf (strp, "%d%n", &(vq->featdim[s][c]), &n) != 1)
		E_FATAL("Error reading subvector(%d).featdim(%d)\n", s, c);
	    strp += n;
	}
    }
    
    /* Echo info for sanity check */
    E_INFO("Original #codebooks(states)/codewords: %d x %d\n", vq->origsize.r, vq->origsize.c);
    E_INFO("Subvectors: %d, VQsize: %d\n", vq->n_sv, vq->vqsize);
    for (s = 0; s < n_sv; s++) {
	E_INFO("Feature dims(%d): ", s);
	for (c = 0; c < vq->svsize[s]; c++)
	    printf (" %2d", vq->featdim[s][c]);
	printf (" (%d)\n", vq->svsize[s]);
    }
    
    /* Read VQ codebooks and maps for each subvector */
    for (s = 0; s < n_sv; s++) {
	E_INFO("Reading subvq %d\n", s);
	
	E_INFO("Reading codebook\n");
	if ((fgets (line, sizeof(line), fp) == NULL) ||
	    (sscanf (line, "Codebook %d", &k) != 1) || (k != s))
	    E_FATAL("Error reading header\n", s);
	
	for (r = 0; r < vq->vqsize; r++) {
	    if (fgets (line, sizeof(line), fp) == NULL)
		E_FATAL("Error reading row(%d)\n", r);
	    
	    for (strp = line, c = 0; c < vq->svsize[s]; c++) {
		if (sscanf (strp, "%f %f%n", &(vq->mean[s][r][c]), &(vq->var[s][r][c]), &k) != 2)
		    E_FATAL("Error reading row(%d) col(%d)\n", r, c);
		strp += k;
	    }
	}
	
#if 0
	E_INFO("Sanity check: mean[0,%d]:\n", vq->vqsize-1);
	vector_print (stdout, vq->mean[s][0], vq->svsize[s]);
	vector_print (stdout, vq->mean[s][vq->vqsize-1], vq->svsize[s]);
	E_INFO("Sanity check: var[0,%d]:\n", vq->vqsize-1);
	vector_print (stdout, vq->var[s][0], vq->svsize[s]);
	vector_print (stdout, vq->var[s][vq->vqsize-1], vq->svsize[s]);
#endif

	E_INFO("Reading map\n");
	if ((fgets (line, sizeof(line), fp) == NULL) ||
	    (sscanf (line, "Map %d", &k) != 1) || (k != s))
	    E_FATAL("Error reading header\n", s);
	
	for (r = 0; r < vq->origsize.r; r++) {
	    if (fgets (line, sizeof(line), fp) == NULL)
		E_FATAL("Error reading row(%d)\n", r);
	    
	    for (strp = line, c = 0; c < vq->origsize.c; c++) {
		if (sscanf (strp, "%d%n", &(vq->map[r][c][s]), &k) != 1)
		    E_FATAL("Error reading row(%d) col(%d)\n", r, c);
		strp += k;
	    }
	}
	
#if 0
	E_INFO("Sanity check: map[0][0]:\n");
	for (c = 0; c < vq->origsize.c; c++)
	    printf (" %d", vq->map[0][c][s]);
	printf ("\n");
#endif
	fflush (stdout);
    }
    
    if ((fscanf (fp, "%s", line) != 1) || (strcmp (line, "End") != 0))
	E_FATAL("Error reading 'End' token\n");
    
    fclose (fp);

    subvq_ivar_idet_precompute (vq, 0.0001 /* varfloor */);

#if 0    
    E_INFO("Sanity check: var[*,0]:\n");
    for (s = 0; s < n_sv; s++)
	vector_print (stdout, vq->var[s][0], vq->svsize[s]);
#endif

    /* Replace invalid entries in map with duplicate of a valid entry, if possible */
    for (r = 0; r < vq->origsize.r; r++) {
	k = -1;
	for (c = 0; c < vq->origsize.c; c++) {
	    if (vq->map[r][c][0] < 0) {
		/* All ought to be < 0 */
		for (s = 1; s < vq->n_sv; s++) {
		    if (vq->map[r][c][s] >= 0)
			E_FATAL("Partially undefined map[%d][%d]\n", r, c);
		}
	    } else {
		/* All ought to be >= 0 */
		for (s = 1; s < vq->n_sv; s++) {
		    if (vq->map[r][c][s] < 0)
			E_FATAL("Partially undefined map[%d][%d]\n", r, c);
		}
		k = c;	/* A valid codeword found; remember it */
	    }
	}
	
	if (k >= 0) {
	    /* Copy k into invalid rows */
	    for (c = 0; c < vq->origsize.c; c++) {
		if (vq->map[r][c][0] < 0) {
		    for (s = 0; s < vq->n_sv; s++)
			vq->map[r][c][s] = vq->map[r][k][s];
		}
	    }
	    bitvec_clear (vq->cb_invalid, r);
	} else
	    bitvec_set (vq->cb_invalid, r);
    }
    
    return vq;
}
예제 #14
0
static void check_print_and_free_new_random_vector_______sent_size_vector_array_____returned(void **state){
vector_t * vc =vector_random();
assert_int_equal(vector_print(vc),1);
assert_int_equal(vector_free(vc),1);
}
예제 #15
0
int32
main(int32 argc, char *argv[])
{
    FILE *fpout;
    mgau_model_t *mgau;
    int32 **subvec;
    int32 max_datarows, datarows, datacols, svqrows, svqcols;
    float32 **data, **vqmean;
    int32 *datamap, *vqmap;
    float64 sqerr;
    int32 stdev;
    int32 i, j, v, m, c;
    cmd_ln_t *config;
    logmath_t *logmath;

    print_appl_info(argv[0]);
    cmd_ln_appl_enter(argc, argv, "default.arg", arg);
    unlimit();

    config = cmd_ln_get();

    logmath = logs3_init(cmd_ln_float64_r(config, "-logbase"), 1, cmd_ln_int32_r(config, "-log3table"));      /*Report Progress, use log table */

    /* Load means/vars but DO NOT precompute variance inverses or determinants */
    mgau = mgau_init(cmd_ln_str_r(config, "-mean"),
                     cmd_ln_str_r(config, "-var"), 0.0 /* no varfloor */ ,
                     cmd_ln_str_r(config, "-mixw"), cmd_ln_float32_r(config, "-mixwfloor"), FALSE,  /* No precomputation */
                     ".cont.", MIX_INT_FLOAT_COMP, logmath);

    /* Parse subvector spec argument; subvec is null terminated; subvec[x] is -1 terminated */
    subvec = parse_subvecs(cmd_ln_str_r(config, "-svspec"));

    if (cmd_ln_str_r(config, "-subvq")) {
        if ((fpout = fopen(cmd_ln_str_r(config, "-subvq"), "w")) == NULL) {
            E_ERROR_SYSTEM("Failed to open output file '%s'", fpout);
            return 1;
        }
    }
    else
        fpout = stdout;

    /* Echo command line to output file */
    for (i = 0; i < argc - 1; i++)
        fprintf(fpout, "# %s \\\n", argv[i]);
    fprintf(fpout, "# %s\n#\n", argv[argc - 1]);

    /* Print input and output configurations to output file */
    for (v = 0; subvec[v]; v++);        /* No. of subvectors */
    svqrows = cmd_ln_int32_r(config, "-svqrows");
    fprintf(fpout, "VQParam %d %d -> %d %d\n",
            mgau_n_mgau(mgau), mgau_max_comp(mgau), v, svqrows);
    for (v = 0; subvec[v]; v++) {
        for (i = 0; subvec[v][i] >= 0; i++);
        fprintf(fpout, "Subvector %d length %d ", v, i);
        for (i = 0; subvec[v][i] >= 0; i++)
            fprintf(fpout, " %2d", subvec[v][i]);
        fprintf(fpout, "\n");
    }
    fflush(fpout);

    /*
     * datamap[] for identifying non-0 input vectors that take part in the clustering process:
     *     datamap[m*max_mean + c] = row index of data[][] containing the copy.
     * vqmap[] for mapping vq input data to vq output.
     */
    max_datarows = mgau_n_mgau(mgau) * mgau_max_comp(mgau);
    datamap = (int32 *) ckd_calloc(max_datarows, sizeof(int32));
    vqmap = (int32 *) ckd_calloc(max_datarows, sizeof(int32));

    stdev = cmd_ln_int32_r(config, "-stdev");

    /* Copy and cluster each subvector */
    for (v = 0; subvec[v]; v++) {
        E_INFO("Clustering subvector %d\n", v);

        for (datacols = 0; subvec[v][datacols] >= 0; datacols++);       /* Input subvec length */
        svqcols = datacols * 2; /* subvec length after concatenating mean + var */

        /* Allocate input/output data areas */
        data =
            (float32 **) ckd_calloc_2d(max_datarows, svqcols,
                                       sizeof(float32));
        vqmean =
            (float32 **) ckd_calloc_2d(svqrows, svqcols, sizeof(float32));

        /* Make a copy of the subvectors from the input data, and initialize maps */
        for (i = 0; i < max_datarows; i++)
            datamap[i] = -1;
        datarows = 0;
        for (m = 0; m < mgau_n_mgau(mgau); m++) {       /* For each mixture m */
            for (c = 0; c < mgau_n_comp(mgau, m); c++) {        /* For each component c in m */
                if (vector_is_zero
                        (mgau_var(mgau, m, c), mgau_veclen(mgau))) {
                    E_INFO("Skipping mgau %d comp %d\n", m, c);
                    continue;
                }

                for (i = 0; i < datacols; i++) {        /* Copy specified dimensions, mean+var */
                    data[datarows][i * 2] =
                        mgau->mgau[m].mean[c][subvec[v][i]];
                    data[datarows][i * 2 + 1] =
                        (!stdev) ? mgau->mgau[m].
                        var[c][subvec[v][i]] : sqrt(mgau->mgau[m].
                                                    var[c][subvec[v][i]]);
                }
                datamap[m * mgau_max_comp(mgau) + c] = datarows++;
            }
        }

        E_INFO("Sanity check: input data[0]:\n");
        vector_print(stderr, data[0], svqcols);

        for (i = 0; i < max_datarows; i++)
            vqmap[i] = -1;
#if 0
        {
            int32 **in;

            printf("Input data: %d x %d\n", datarows, svqcols);
            in = (int32 **) data;
            for (i = 0; i < datarows; i++) {
                printf("%8d:", i);
                for (j = 0; j < svqcols; j++)
                    printf(" %08x", in[i][j]);
                printf("\n");
            }
            for (i = 0; i < datarows; i++) {
                printf("%15d:", i);
                for (j = 0; j < svqcols; j++)
                    printf(" %15.7e", data[i][j]);
                printf("\n");
            }
            fflush(stdout);
        }
#endif
        /* VQ the subvector copy built above */
        sqerr = vector_vqgen(data, datarows, svqcols, svqrows,
                             cmd_ln_float64_r(config, "-eps"), cmd_ln_int32_r(config, "-iter"),
                             vqmean, vqmap, cmd_ln_int32_r(config, "-seed"));

        /* Output VQ */
        fprintf(fpout, "Codebook %d Sqerr %e\n", v, sqerr);
        for (i = 0; i < svqrows; i++) {
            if (stdev) {
                /* Convert clustered stdev back to var */
                for (j = 1; j < svqcols; j += 2)
                    vqmean[i][j] *= vqmean[i][j];
            }
            vector_print(fpout, vqmean[i], svqcols);
        }

        fprintf(fpout, "Map %d\n", v);
        for (i = 0; i < max_datarows; i += mgau_max_comp(mgau)) {
            for (j = 0; j < mgau_max_comp(mgau); j++) {
                if (datamap[i + j] < 0)
                    fprintf(fpout, " -1");
                else
                    fprintf(fpout, " %d", vqmap[datamap[i + j]]);
            }
            fprintf(fpout, "\n");
        }
        fflush(fpout);

        /* Cleanup */
        ckd_free_2d((void **) data);
        ckd_free_2d((void **) vqmean);
    }

    subvecs_free(subvec);
    ckd_free(datamap);
    ckd_free(vqmap);

    mgau_free(mgau);

    fprintf(fpout, "End\n");
    fclose(fpout);

    logmath_free(logmath);

    cmd_ln_free_r(config);
    exit(0);
}
예제 #16
0
void command(vector_t *** vecs)
{
int terminated = 0;
int i = 0;
int N = 0, rc = 0;
int fr = 0, fsk = 0, fpr = 0, fskkv = 0, fkav = 0, max = 0;
char input[N_MAX];
char *p, *p2, *output;
vector_t * vec, * vec1;
double val;

vector_t ** vectors = *vecs;

while (!terminated) {

  printf("\n> ");
  gets( input );
  
  fr = fsk = fpr = fskkv = 0;
  for (i = 0; i < strlen(input); i ++) {
    if (input[i] == '=') fr = 1;
    if ((input[i] == '(') || (input[i] == ')')) fsk = 1;
    if (input[i] == ' ') fpr = 1;
    if (input[i] == '[') fskkv = 1;
    if (input[i] == '"') fkav = 1;
  }
    
  if ((fr == 0) && (fsk == 0) && (fpr == 0) && (fskkv == 0)) {
    if (strcmp("ls", input) == 0) 
	ls(vectors);

    else if (strcmp("help", input) == 0) 
	help();

    else if (strcmp("quit", input) == 0)
	terminated = 1;

    else printf("Command is not found\n");
  }


  if ((fr == 0) && (fsk == 1)) {
    p = strtok(input, "(");

    if (strcmp(p, "disp") == 0) {
	p = strtok(NULL, ")");
	vec = vectors_search( vectors, p);
	if (vec)
	  printf("dispersion %s = %f\n", p, disp(vec->size, vec->vals));
        else
          printf("ERROR: Parameter '%s' not found\n", p );
    }

    else if (strcmp(p, "avg") == 0) {
	p = strtok(NULL, ")");
	vec = vectors_search( vectors, p);
	if (vec)
	  printf("average %s = %f\n", p, avg(vec->size, vec->vals));
        else
          printf("ERROR: Parameter '%s' not found\n", p );
 
    }

    else if (strcmp(p, "print") == 0) {
	p = strtok(NULL, ")");
	vec = vectors_search( vectors, p);
	if (vec) {
	  printf("Vector %s: \n", p);
	  vector_print(vec);
        }
        else
          printf("ERROR: Parameter '%s' not found\n", p );
 
    }
    
    else if (strcmp(p, "load") == 0)
    {
      p = strtok(NULL, ")");
      rc = load_csv(&vectors, p);
      if (rc == -1) printf("Failed to load file: %s \n", p);
    }

    else if (strcmp(p, "save") == 0)
    {
      p = strtok(NULL, ")");
      rc = save_csv(vectors, p);
      if (rc == -1) printf("Failed to save file: %s \n", p);
    }


    else if (strcmp(p, "delete") == 0)
    {
      p = strtok(NULL, ")");
      vec = vectors_search( vectors, p);
	if (vec) {
	  vectors_remove(&vectors, vec);
        }
        else
          printf("ERROR: Parameter '%s' not found\n", p );
    }

    else if (strcmp(p, "gnuplot") == 0)
    {
      p = strtok(NULL, ")");
      gcmd(p);
    }

    else printf("Command is not found\n");
  } 


  if ((fr == 1) && (fskkv == 1)) {
    p = strtok(input, " =");

    vec = (vector_t*) malloc (sizeof( vector_t ) );
    vector_init( p, 0, vec );
    
    p = strtok(NULL, "= [,]");
    while ( p )
    {
      val = strtod( p, &p2 );
      if ( p == p2 )
      { 
        vector_clear( vec );
        free( vec );
        vec = 0;
        printf( "ERROR: Input data is invalid\n" );
        break;
      }
      else
      {
         vector_append( vec, 1, &val );
      }
      p = strtok(NULL, " ,]");
    }	

    if ( vec )
    {
      vec1 = vectors_search( vectors, vec->name );
      if (vec1) 
      {
	vector_clear( vec1 );
        vector_append( vec1, vec->size, vec->vals );
        vector_clear( vec );
        free( vec );
        vec = 0;
      }
      else
      { 
        vectors_add( &vectors, vec );

      }   
    }		
  }

  if ((fr == 1) && (fskkv == 0))
  {
    for (i = 0; i < vectors_count(vectors); i ++)
      if (max < vectors[i]->size) max = vectors[i]->size;
    printf("%d\n", max);
    printf("%d\n", vectors_count(vectors));
    sergey(vectors, input, max, vectors_count(vectors));
  }

  if ((fpr == 1) && (fskkv == 0) && (fsk == 0))
  {
    p = strtok(input, " ");
    if (strcmp(p, "plot") == 0)
    {
      p = strtok(NULL, " ");
      vec = vectors_search(vectors, p);
      if (vec)
      {
        p = strtok(NULL, " ");
        vec1 = vectors_search(vectors, p);
        if (vec1)
        {
          p = strtok(NULL, " ");
          output = p;
          if (strcmp(p, "wxt") == 0) { output = NULL; }
          p = strtok(NULL, ".");
          N = atoi(p);
          gplot_vector(vec, vec1, output, N);
        }
      }
   }
   else printf("Command is not found\n");
  }
}
 *vecs = vectors;
}
예제 #17
0
static
bool matrix_approximate_constraint_1x(pk_internal_t* pk, matrix_t* C, matrix_t* F,
				      bool outerfallback, bool combine)
{
  size_t i,j,size,nbrows,nbrows2;
  bool change,finite,removed;
  itv_t itv;
  numint_t* vecs = NULL;

  itv_init(itv);
  change = false;
  i = 0;
  nbrows = C->nbrows;
  nbrows2 = nbrows;
  while (i<nbrows){
    numint_t* vec = C->p[i];
    removed = false;
    if (numint_sgn(vec[0]) &&
	(pk->strict ? numint_sgn(vec[polka_eps])<=0 : true)){
      /* Look for a too big coefficient in the row */
      size=0;
      for (j=pk->dec; j<C->nbcolumns; j++){
	size = numint_size2(vec[j]);
	if (size > pk->approximate_max_coeff_size) /* Too big coefficient detected  */
	  break;
      }
      if (size > pk->approximate_max_coeff_size){ /* Too big coefficient detected */
	change = true;
	/* save the vector */
	if (vecs==NULL) vecs=vector_alloc(C->nbcolumns);
	vector_copy(vecs,vec,C->nbcolumns);
	if (false){ printf("\nconstraint to be rounded: "); vector_print(vec,C->nbcolumns); }
	/* A. Compute maximum magnitude */
	size_t maxsize = size;
	for (j=j+1; j<C->nbcolumns; j++){
	  size = numint_size2(vec[j]);
	  if (size>maxsize) maxsize=size;
	}
	/* B. Perform rounding (inner truncation) of non constant coefficients */
	size = maxsize - pk->approximate_max_coeff_size;
	for (j=pk->dec; j<C->nbcolumns; j++){
	  numint_tdiv_q_2exp(vec[j],vec[j], size);
	}
	if (false){ printf("rounding 1: "); vector_print(vec,C->nbcolumns); }
	/* C. Compute new constant coefficient */
	numint_set_int(vec[0],1);
	numint_set_int(vec[polka_cst],0);
	matrix_bound_vector(pk,itv,vec,F);
	finite = !bound_infty(itv->inf);
	if (finite){
	  /* D. We round the constant to an integer and keep the constraint */
	  bound_neg(itv->inf,itv->inf);
	  numint_fdiv_q(numrat_numref(bound_numref(itv->inf)),
			numrat_numref(bound_numref(itv->inf)),
			numrat_denref(bound_numref(itv->inf)));
	  numint_neg(vec[polka_cst],numrat_numref(bound_numref(itv->inf)));
	  if (false){ printf("before norm 1: "); vector_print(vec,C->nbcolumns); }
	  vector_normalize(pk,vec,C->nbcolumns);
	  if (false){ printf("after norm 1: "); vector_print(vec,C->nbcolumns); }
	} else {
	  /* we remove the vector */
	  removed = true;
	  matrix_exch_rows(C,i,nbrows-1);
	  matrix_exch_rows(C,nbrows-1,nbrows2-1);
	  nbrows--; nbrows2--;
	}
	if (combine || (!finite && outerfallback)){
	  /* we work on vecs */
	  vec = vecs;
	  /* E. perform rounding (outer truncation) of non-constant coefficients */
	  for (j=pk->dec; j<C->nbcolumns; j++){
	    int sgn = numint_sgn(vec[j]);
	    if (sgn>0) numint_cdiv_q_2exp(vec[j],vec[j], size);
	    else if (sgn<0) numint_fdiv_q_2exp(vec[j],vec[j], size);
	  }
	  if (false){ printf("rounding 2: "); vector_print(vec,C->nbcolumns); }
	  /* G. Compute new constant coefficient */
	  numint_set_int(vec[0],1);
	  numint_set_int(vec[polka_cst],0);
	  matrix_bound_vector(pk,itv,vec,F);
	  finite = !bound_infty(itv->inf);
	  if (finite){
	    /* E. We round the constant to an integer and keep the constraint */
	    bound_neg(itv->inf,itv->inf);
	    numint_fdiv_q(numrat_numref(bound_numref(itv->inf)),
			  numrat_numref(bound_numref(itv->inf)),
			  numrat_denref(bound_numref(itv->inf)));
	    numint_neg(vec[polka_cst],numrat_numref(bound_numref(itv->inf)));
	    if (false){ printf("before norm 2: "); vector_print(vec,C->nbcolumns); }
	    vector_normalize(pk,vec,C->nbcolumns);
	    if (false){ printf("after norm 2: "); vector_print(vec,C->nbcolumns); }
	    if (nbrows2>=C->_maxrows) matrix_resize_rows(C,(C->_maxrows*3+1)/2);
	    vector_copy(C->p[nbrows2],vec,C->nbcolumns);
	    nbrows2++;
	  }
	}
      }
    }
    if (!removed) i++;
  }
  if (change){
    C->nbrows = nbrows2;
    /* Add positivity and strictness that may not be implied any more */
    size_t nbrows = C->nbrows;
    matrix_resize_rows_lazy(C,nbrows+pk->dec-1);
    matrix_fill_constraint_top(pk,C,nbrows);
    C->_sorted = false;
  }
  itv_clear(itv);
  if (vecs) vector_free(vecs,C->nbcolumns);
  return change;
}
예제 #18
0
파일: hw5.c 프로젝트: jdw6359/LinearAlgebra
int main(int argc, char *argv[]){

	/* Declare vars that hold numRow and numCols values scanned from txt file */
	int numRows, numCols;

	/* Declare pointer to matrix */
	MatElement **matrix, **perm;

	/* Declare pointer to vector */
	VectorElement  *solution, *right;


	/* Declare row and column values to loop over rows / cols */
	int rowCounter, colCounter;

	/* Check to make sure there are the correct number of cmdline args */
	if(argc==2){

		/* Declare FILE variable */
		FILE* inputFile;

		/* Attempt to open file provided in cmdline arg */
		inputFile=fopen(argv[1],"r");

		/* Check to make sure file was opened properly */
		if(inputFile==NULL){

			/* Alert user file was not opened properly */
			fprintf(stdout,"\nFile was not opened properly\n");
			return 2;

		}else{

			/* Scan numRows and numCols from file */
			fscanf(inputFile, "%d %d", &numRows, &numCols);

			/* Check that numRows and numCols are equal */
			if(numRows!=numCols){

				/* numRows and numCols dont match, alert and exit */
				fprintf(stdout, "Matrix has %d rows and %d columns, not a square matrix.\nExiting...\n", numRows, numCols);
				return 0;
			}

			/* Call matrix_alloc to allocate memory for matrix */
			matrix=matrix_alloc(numRows,numCols);
			perm=matrix_identity(numRows);

			/* Call vector_alloc to allocate memory for vector */
			right=vector_alloc(numRows);
			solution=vector_alloc(numRows);



			/* For each row, read in value for each column, in
			 * addition to permutation value at end of row */
			for(rowCounter=0;rowCounter<numRows;rowCounter++){

				/* Declare variable for right hand side */
				double rightValue;

				/* Loop over cols of each row */
				for(colCounter=0;colCounter<numCols;colCounter++){

					/* Declare variable for value stored in amtrix */
					double matValue;

					/* Grab value for matrix at A[rowCounter][colCounter] */
					fscanf(inputFile, "%lf", &matValue);

					/* Set matrix value at [rowCount][colCount] */
					matrix[rowCounter][colCounter]=matValue;

				}
				/* End for over cols */

				/* Grab the value for matrix at right[rowCounter] */
				fscanf(inputFile, "%lf", &rightValue);

				/*  Set right value at right[rowCounter] */
				right[rowCounter]=rightValue;

			}
			/* End for over rows */

			fprintf(stdout, "Original Matrix: \n");
			matrix_print(matrix, " %g ", numRows, numCols);

			fprintf(stdout, "\nRight hand side vector:\n");
			vector_print(right, " %g ", numRows);

			fprintf(stdout, "\nPermutation Matrix: \n");
			matrix_print(perm, " %g ", numRows, numCols);

			/* make call to decomp */
			linalg_LU_decomp(matrix,perm,numRows);

			print_plu(matrix, perm, numRows);


			fprintf(stdout, "Matrix after decomposition \n");
			matrix_print(matrix, " %g ", numRows, numCols);

			fprintf(stdout, "\nPermuation after decomposition \n");
			matrix_print(perm, " %g ", numRows, numCols);

			/* make call to solve */
			linalg_LU_solve(matrix,perm,right,solution, numRows);


			vector_print(solution, " %g ", numRows);


			fprintf(stdout,"Freeing matrices\n");
			matrix_free(matrix);
			matrix_free(perm);

			fprintf(stdout,"Freeing vectors\n");
			vector_free(solution);



		}
		/* End check for valid input file */

	}else{

		/* Alert user to proper usage */
		fprintf(stdout,"Usage: ./linalg <xxxx.txt>\n");
		return 1;

	}
	/* End check for cmdline args */


	/* Program completed successfully, return 0 to user */
	return 0;

}
예제 #19
0
파일: proj3io.c 프로젝트: zcsevcik/edu
bool test(const char* filename, FILE* fout)
{
    FILE* fp = fopen(filename, "r");
    if (fp == NULL) {
        perror(filename);
        return false;
    }

    int fmt;

    int suc = fscanf(fp, "%d", &fmt);
    if (suc == EOF || suc != 1) {
        fclose(fp);
        return false;
    }
    if (fclose(fp) != 0) {
        perror(filename);
    }

    switch (fmt) {
        case FMT_VECTOR: {
            Vector vect = { .count = 0, .items = NULL };
            if (!vector_load(&vect, filename)) {
                return false;
            }

            vector_print(&vect, fout);
            vector_free(&vect);
        }   break;

        case FMT_MATRIX: {
            Matrix mat = { .rows = 0, .cols = 0, .items = NULL };
            if (!matrix_load(&mat, filename)) {
                return false;
            }

            matrix_print(&mat, fout);
            matrix_free(&mat);
        }   break;

        case FMT_VECTOR_OF_MATRICES: {
            VectorOfMatrices vm = { .count = 0, .rows = 0, .cols = 0, .items = NULL };
            if (!vm_load(&vm, filename)) {
                return false;
            }

            vm_print(&vm, fout);
            vm_free(&vm);
        }   break;

        default:
            return false;
    }

    return true;
}

bool vector_load(Vector* vect, const char* filename)
{
    assert(vect != NULL);

    FILE* fp = fopen(filename, "r");
    if (fp == NULL) {
        perror(filename);
        goto return_false;
    }

    int fmt;
    unsigned long count;

    int suc = fscanf(fp, "%d", &fmt);
    CHECK_IO(suc, 1, return_false);
    if (fmt != FMT_VECTOR) {
        goto return_false;
    }

    suc = fscanf(fp, "%lu", &count);
    CHECK_IO(suc, 1, return_false);
    if (count <= 0) {
        goto return_false;
    }
    vect->count = count;
    if (!vector_alloc(vect)) {
        goto return_false;
    }

    int* pVect = vect->items;
    for (size_t i = 0; i < vect->count; ++i) {
        suc = fscanf(fp, "%d", pVect++);
        CHECK_IO(suc, 1, return_false);
    }

    if (fclose(fp) != 0) {
        perror(filename);
    }

    return true;

return_false:
    if (fp != NULL && fclose(fp) != 0) {
        perror(filename);
    }

    vector_free(vect);
    return false;
}

void vector_print(const Vector* vect, FILE* fp)
{
    assert(vect != NULL);
    assert(fp != NULL);
    assert(vect->count > 0);
    assert(vect->items != NULL);

    fprintf(fp, "%d\n", FMT_VECTOR);
    fprintf(fp, "%zu\n", vect->count);

    int* pVect = vect->items;
    for (size_t i = 0; i < vect->count; ++i) {
        fprintf(fp, "%d ", *pVect++);
    }
}

void noop_print(FILE* fp)
{
    assert(fp != NULL);
    fprintf(fp, "false\n");
}