Пример #1
0
bool matrix_equals(Matrix M1, Matrix M2)
{
    assert(is_matrix(M1) && is_matrix(M2));
    if(!(M1->r == M2->r && M1->c == M2->c))
        return false;
    for(int i = 0; i < M1->r; i++)
        for(int j = 0; j < M1->c; j++)
            if(M1->A[i][j] != M2->A[i][j])
                return false;
    return true;
}
Пример #2
0
Matrix matrix_transpose(Matrix M)
{
    assert(is_matrix(M));
    int r = M->r;
    int c = M->c;
    Matrix N = matrix_new_empty(c, r);
    for(int i = 0; i < r; i++)
        for(int j = 0; j < c; j++)
            N->A[j][i] = M->A[i][j];
    assert(is_matrix(N));
    return N;
}
Пример #3
0
Matrix matrix_multiply_scalar(Matrix M, double n)
{
    assert(is_matrix(M));
    int r = M->r;
    int c = M->c;
    Matrix N = matrix_new_empty(r, c);
    for(int i = 0; i < r; i++)
        for(int j = 0; j < c; j++) {
                assert(FLT_MAX / n >= M->A[i][j]);
                N->A[i][j] = n * M->A[i][j];
            }
    assert(is_matrix(N));
    return N;
}
Пример #4
0
Matrix matrix_multiply(Matrix M1, Matrix M2)
{
    assert(is_matrix(M1) && is_matrix(M2));
    assert(M1->c == M2->r);
    int r = M1->r;
    int c = M2->c;
    int m = M1->c;
    Matrix M = matrix_new_empty(r, c);
    for(int i = 0; i < r; i++)
        for(int j = 0; j < c; j++)
            for(int k = 0; k < m; k++)
                M->A[i][j] += M1->A[i][k] * M2->A[k][j];
    assert(is_matrix(M));
    return M;
}
Пример #5
0
Matrix matrix_subtract(Matrix M1, Matrix M2)
{
    assert(is_matrix(M1) && is_matrix(M2));
    assert(M1->r == M2->r && M1->c == M2->c);
    int r = M1->r;
    int c = M1->c;
    Matrix M = matrix_new_empty(r, c);
    for(int i = 0; i < r; i++)
        for(int j = 0; j < c; j++) {
            assert(FLT_MIN + M1->A[i][j] >= M2->A[i][j]);
            M->A[i][j] = M1->A[i][j] - M2->A[i][j];
        }
    assert(is_matrix(M));
    return M;
}
Пример #6
0
Matrix* matrix_qr_decomposition(Matrix M)
{
    assert(is_matrix(M));
    int m = M->r;
    int n = M->c;
    Matrix Q = matrix_new_empty(m, n);
    for(int i = 0; i < n; i++) {
        double* u = matrix_column_vector(M, i);
        double* a = matrix_column_vector(M, i);
        for(int k = 0; k < i; k++) {
            double* e = matrix_column_vector(Q, k);
            double* p = vector_projection(e, a, m);
            free(e);
            for(int j = 0; j < m; j++)
                u[j] -= p[j];
            free(p);
        }
        free(a);
        double* e = vector_normalize(u, m);
        free(u);
        for(int l = 0; l < m; l++)
            Q->A[l][i] = e[l];
        free(e);
    }
    Matrix Qt = matrix_transpose(Q);
    Matrix R = matrix_multiply(Qt, M);
    matrix_free(Qt);

    Matrix* QR = calloc(2, sizeof(Matrix));
    QR[0] = Q;
    QR[1] = R;
    return QR;
}
Пример #7
0
/* ----------------------------------------------------------------------------
   function:            cmap_getfontmatrix           author:       Eric Penfold
   creation date:       13-Aug-1997            last modification:   ##-###-####
   arguments:
     cmapdict (Input)
     fontid   (Input)
     matrix   (Output)

   description:
     Obtains the font matrix from the CMap to use with the specified
     descendant font.
     If no matrices are defined at all, or no matrix is defined for this
     fontid, then 'matrix' will be set to a null object.


     Returns FALSE if the object in the matrix array is not a valid matrix,
     or if the fontid is invalid (i.e. the matrix array has fewer entries);
     TRUE is otherwise returned.
---------------------------------------------------------------------------- */
Bool cmap_getfontmatrix(OBJECT *cmapdict, int32 fontid, OBJECT *matrix)
{
  OBJECT *cmap, *matblk;
  OMATRIX omat;

  /* Extract CMap */
  if ( oType(*cmapdict) != ODICTIONARY )
    return FAILURE(FALSE); /* Error - Invalid dictionary */

  cmap = fast_extract_hash_name(cmapdict, NAME_CodeMap);

  /* Extract matrix block */
  if ( oType(*cmap) != ODICTIONARY )
    return FAILURE(FALSE); /* Error - Invalid dictionary */

  matblk = fast_extract_hash_name(cmap, NAME_usematrixblock);

  if ( !matblk ) {
    object_store_null(matrix); /* No usematrix defined, use defaults */
  } else if ( oType(*matblk) != OARRAY ||
              theLen(*matblk) <= fontid ||
              !is_matrix(oArray(*matblk) + fontid, &omat) ) {
    return FAILURE(FALSE); /* usematrix definition is not valid (for this fontid) */
  } else
    Copy(matrix, oArray(*matblk) + fontid);

  return TRUE;
}
Пример #8
0
Matrix matrix_cofactor(Matrix M, int i, int j)
{
    assert(is_matrix(M));
    assert(0 <= i && i < M->r);
    assert(0 <= j && j < M->c);
    Matrix C = matrix_new_empty(M->r - 1, M->c - 1);
    int r = 0;
    for(int k = 0; k < M->r; k++) {
        int c = 0;
        if(k != i) {
            for(int l = 0; l < M->c; l++) {
                if(l != j) {
                    C->A[r][c] = M->A[k][l];
                    c++;
                }
            }
            r++;
        }
    }
    assert(is_matrix(C));
    return C;
}
Пример #9
0
static void to_matrix(void)
{
	HklQuaternion q_ref = {{1./sqrt(2), 0, 0, 1./sqrt(2)}};
	HklMatrix *m_ref = hkl_matrix_new_full(0,-1, 0,
					       1, 0, 0,
					       0, 0, 1);
	HklMatrix *m = hkl_matrix_new();

	hkl_quaternion_to_matrix(&q_ref, m);
	is_matrix(m_ref, m, __func__);

	hkl_matrix_free(m_ref);
	hkl_matrix_free(m);
}
Пример #10
0
		bool is_standard( const builtin_types& btc ){
			if (btc == builtin_types::_sint32 || 
				btc == builtin_types::_uint32 ||
				btc == builtin_types::_sint64 ||
				btc == builtin_types::_uint64 ||
				btc == builtin_types::_float  ||
				btc == builtin_types::_double) 
			{
				return true;
			}

			if ( is_vector(btc) || is_matrix(btc) ){
				return is_standard(scalar_of(btc));
			}

			return false;
		}
Пример #11
0
		builtin_types replace_scalar( builtin_types const& btc, builtin_types const& scalar_btc )
		{
			assert( is_scalar(scalar_btc) );
			if( !is_scalar(scalar_btc) ) { return scalar_btc; }

			if( is_vector(btc) )
			{
				return vector_of( scalar_btc, vector_size(btc) );
			}
			else if ( is_matrix(btc) )
			{
				return matrix_of( scalar_btc, vector_size(btc), vector_count(btc) );
			}
			else
			{
				return scalar_btc;
			}
		}
Пример #12
0
void make_split(Tree* MTree, Tnode * Root)
{//get all the children of a certain node
	if(is_matrix(Root))
	{
		Root->ChildTnodeArray = 0;
		Root->ChildTnodeNum = 0;
		return;
	}
	Tnode * CreatedTnode1, * CreatedTnode2;
	CreatedTnode1 = (Tnode *)malloc(sizeof(Tnode));
	CreatedTnode2 = (Tnode *)malloc(sizeof(Tnode));

	step_split_differentlevel(MTree, Root, CreatedTnode1, CreatedTnode2);

	if(((float)CreatedTnode1->TTransactionNum) / Root->TTransactionNum < FThreshold || ((float)CreatedTnode1->TTransactionNum) / MTree->Root->TTransactionNum < WThreshold)
	{//if a spliting is failed, it is based on the rate of the number of children in created1(if the bigger node is too small)
		MTree->TnodeNum -= 2;
		Root->ChildTnodeNum = 0;
		Root->ChildTnodeArray = 0;
		return;
	}
	//below we should deal with the case where the bigger node is so big that we should discard the rest node
	else if( ((float)CreatedTnode2->TTransactionNum) / Root->TTransactionNum < FThreshold || ((float)CreatedTnode2->TTransactionNum) / MTree->Root->TTransactionNum < WThreshold)
	{//if the bigger node is too big
		MTree->TnodeNum --;
		
		UsedTransactionNum -= CreatedTnode2->TTransactionNum;
		en_queue(Root->ChildTnodeArray[0]);
		return;
	}
	Tnode * CreatedTnode3;
	
	CreatedTnode3 = step_split_samelevel(MTree,CreatedTnode2);

	for(;;)
	{
		if(((float)CreatedTnode2->TTransactionNum) / CreatedTnode2->FatherTnode->TTransactionNum < FThreshold || ((float)CreatedTnode2->TTransactionNum) / MTree->Root->TTransactionNum < WThreshold)
		{// if the bigger node is too small, we do retreat for this node
			// usually we should stop spliting at this node, and this means some Transactions are discarded. We deal with that case from two aspects
			if((CreatedTnode2->TTransactionNum + (float)CreatedTnode3->TTransactionNum) / CreatedTnode2->FatherTnode->TTransactionNum > DiscardThreshold)//if the number of effective children discarded is more than certain percentage of the number in Fathernode 
			{//we refuse to discard too many children, we would rather stop growing. And this is to handle the case where there are too many 1-transaction-nodes which is too specific
				MTree->TnodeNum -= 1;
				MTree->TnodeNum -= Root->ChildTnodeNum;
				Root->ChildTnodeArray = NULL;
				Root->ChildTnodeNum = 0;
				return;
			}
			MTree->TnodeNum -= 2;
			Root->ChildTnodeNum --;
			CreatedTnode2->PreviousTnode->NextTnode = NULL;// retreat, prune at the previous node
			UsedTransactionNum -= (CreatedTnode3->TTransactionNum + CreatedTnode2->TTransactionNum);
			break;
		}
		else if(((float)CreatedTnode3->TTransactionNum) / CreatedTnode2->FatherTnode->TTransactionNum < FThreshold || ((float)CreatedTnode3->TTransactionNum) / MTree->Root->TTransactionNum < WThreshold)
		{
			MTree->TnodeNum -= 1;
			CreatedTnode2->NextTnode = NULL;
			UsedTransactionNum -= CreatedTnode3->TTransactionNum;
			break;
		}
		CreatedTnode2 = CreatedTnode3;
		CreatedTnode3 = step_split_samelevel(MTree,CreatedTnode2);
	}
	
	Tnode ** ChildTnodeArray;
	ChildTnodeArray = (Tnode **)malloc(Root->ChildTnodeNum *sizeof(Tnode *));
	Tnode * FirstChild;
	FirstChild = *(Root->ChildTnodeArray);
	for( int i = 0; i < Root->ChildTnodeNum; i ++)
	{
		ChildTnodeArray[i] = FirstChild;
		FirstChild = FirstChild->NextTnode;
	}
	Root->ChildTnodeArray = ChildTnodeArray;
	for( int i = 0; i < Root->ChildTnodeNum; i ++)
		en_queue(Root->ChildTnodeArray[i]);
}
Пример #13
0
/**
 * The Stan print function.
 *
 * @param argc Number of arguments
 * @param argv Arguments
 * 
 * @return 0 for success, 
 *         non-zero otherwise
 */
int main(int argc, const char* argv[]) {
  
  if (argc == 1) {
    print_usage();
    return 0;
  }
  
  // Parse any arguments specifying filenames
  std::ifstream ifstream;
  std::vector<std::string> filenames;
  
  for (int i = 1; i < argc; i++) {
    
    if (std::string(argv[i]).find("--autocorr=") != std::string::npos)
      continue;
    
    if (std::string(argv[i]).find("--sig_figs=") != std::string::npos)
      continue;
    
    if (std::string("--help") == std::string(argv[i])) {
      print_usage();
      return 0;
    }
    
    ifstream.open(argv[i]);
    
    if (ifstream.good()) {
      filenames.push_back(argv[i]);
      ifstream.close();
    } else {
      std::cout << "File " << argv[i] << " not found" << std::endl;
    }
    
  }
  
  if (!filenames.size()) {
    std::cout << "No valid input files, exiting." << std::endl;
    return 0;
  }
  
  // Parse specified files
  Eigen::VectorXd warmup_times(filenames.size());
  Eigen::VectorXd sampling_times(filenames.size());
  
  Eigen::VectorXi thin(filenames.size());
  
  ifstream.open(filenames[0].c_str());
  
  stan::io::stan_csv stan_csv = stan::io::stan_csv_reader::parse(ifstream);
  warmup_times(0) = stan_csv.timing.warmup;
  sampling_times(0) = stan_csv.timing.sampling;
  
  stan::mcmc::chains<> chains(stan_csv);
  ifstream.close();
  
  thin(0) = stan_csv.metadata.thin;
  
  for (std::vector<std::string>::size_type chain = 1; 
       chain < filenames.size(); chain++) {
    ifstream.open(filenames[chain].c_str());
    stan_csv = stan::io::stan_csv_reader::parse(ifstream);
    chains.add(stan_csv);
    ifstream.close();
    thin(chain) = stan_csv.metadata.thin;
    
    warmup_times(chain) = stan_csv.timing.warmup;
    sampling_times(chain) = stan_csv.timing.sampling;
    
  }
  
  double total_warmup_time = warmup_times.sum();
  double total_sampling_time = sampling_times.sum();

  // Compute largest variable name length
  const int skip = 0;
  std::string model_name = stan_csv.metadata.model;
  size_t max_name_length = 0;
  for (int i = skip; i < chains.num_params(); i++) 
    if (chains.param_name(i).length() > max_name_length)
      max_name_length = chains.param_name(i).length();
  for (int i = 0; i < 2; i++) 
    if (chains.param_name(i).length() > max_name_length)
      max_name_length = chains.param_name(i).length();


  // Prepare values
  int n = 9;
  
  Eigen::MatrixXd values(chains.num_params(), n);
  values.setZero();
  Eigen::VectorXd probs(3);
  probs << 0.05, 0.5, 0.95;
  
  for (int i = 0; i < chains.num_params(); i++) {
    double sd = chains.sd(i);
    double n_eff = chains.effective_sample_size(i);
    values(i,0) = chains.mean(i);
    values(i,1) = sd / sqrt(n_eff);
    values(i,2) = sd;
    Eigen::VectorXd quantiles = chains.quantiles(i,probs);
    for (int j = 0; j < 3; j++)
      values(i,3+j) = quantiles(j);
    values(i,6) = n_eff;
    values(i,7) = n_eff / total_sampling_time;
    values(i,8) = chains.split_potential_scale_reduction(i);
  }
  
  // Prepare header
  Eigen::Matrix<std::string, Eigen::Dynamic, 1> headers(n);
  headers << 
    "Mean", "MCSE", "StdDev",
    "5%", "50%", "95%", 
    "N_Eff", "N_Eff/s", "R_hat";
  
  // Set sig figs
  Eigen::VectorXi column_sig_figs(n);
  
  int sig_figs = 2;
  
  for (int k = 1; k < argc; k++)
    if (std::string(argv[k]).find("--sig_figs=") != std::string::npos)
      sig_figs = atoi(std::string(argv[k]).substr(11).c_str());
  
  // Compute column widths
  Eigen::VectorXi column_widths(n);
  Eigen::Matrix<std::ios_base::fmtflags, Eigen::Dynamic, 1> formats(n);
  column_widths = calculate_column_widths(values, headers, sig_figs, formats);
  
  // Initial output
  std::cout << "Inference for Stan model: " << model_name << std::endl
            << chains.num_chains() << " chains: each with iter=(" << chains.num_kept_samples(0);
  for (int chain = 1; chain < chains.num_chains(); chain++)
    std::cout << "," << chains.num_kept_samples(chain);
  std::cout << ")";
  
  // Timing output
  std::cout << "; warmup=(" << chains.warmup(0);
  for (int chain = 1; chain < chains.num_chains(); chain++)
    std::cout << "," << chains.warmup(chain);
  std::cout << ")";
                          
  std::cout << "; thin=(" << thin(0);
  
  for (int chain = 1; chain < chains.num_chains(); chain++)
    std::cout << "," << thin(chain);
  std::cout << ")";
                          
  std::cout << "; " << chains.num_samples() << " iterations saved."
            << std::endl << std::endl;

  std::string warmup_unit = "seconds";
  
  if (total_warmup_time / 3600 > 1) {
    total_warmup_time /= 3600;
    warmup_unit = "hours";
  } else if (total_warmup_time / 60 > 1) {
    total_warmup_time /= 60;
    warmup_unit = "minutes";
  }
  
  std::cout << "Warmup took ("
            << std::fixed
            << std::setprecision(compute_precision(warmup_times(0), sig_figs, false))
            << warmup_times(0);
  for (int chain = 1; chain < chains.num_chains(); chain++)
    std::cout << ", " << std::fixed
              << std::setprecision(compute_precision(warmup_times(chain), sig_figs, false))
              << warmup_times(chain);
  std::cout << ") seconds, ";
  std::cout << std::fixed
            << std::setprecision(compute_precision(total_warmup_time, sig_figs, false))
            << total_warmup_time << " " << warmup_unit << " total" << std::endl;

  std::string sampling_unit = "seconds";
  
  if (total_sampling_time / 3600 > 1) {
    total_sampling_time /= 3600;
    sampling_unit = "hours";
  } else if (total_sampling_time / 60 > 1) {
    total_sampling_time /= 60;
    sampling_unit = "minutes";
  }

  std::cout << "Sampling took ("
            << std::fixed
            << std::setprecision(compute_precision(sampling_times(0), sig_figs, false))
            << sampling_times(0);
  for (int chain = 1; chain < chains.num_chains(); chain++)
    std::cout << ", " << std::fixed
              << std::setprecision(compute_precision(sampling_times(chain), sig_figs, false))
              << sampling_times(chain);
  std::cout << ") seconds, ";
  std::cout << std::fixed
            << std::setprecision(compute_precision(total_sampling_time, sig_figs, false))
            << total_sampling_time << " " << sampling_unit << " total" << std::endl;
  std::cout << std::endl;

  // Header output
  std::cout << std::setw(max_name_length + 1) << "";
  for (int i = 0; i < n; i++) {
    std::cout << std::setw(column_widths(i)) << headers(i);
  }
  std::cout << std::endl;
  
  // Value output
  for (int i = skip; i < chains.num_params(); i++) {
    if (!is_matrix(chains.param_name(i))) {
      std::cout << std::setw(max_name_length + 1) << std::left << chains.param_name(i);
      std::cout << std::right;
      for (int j = 0; j < n; j++) {
        std::cout.setf(formats(j), std::ios::floatfield);
        std::cout << std::setprecision(
                                       compute_precision(values(i,j), sig_figs, formats(j) == std::ios_base::scientific))
                  << std::setw(column_widths(j)) << values(i, j);
      }
      std::cout << std::endl;
    } else {
      std::vector<int> dims = dimensions(chains, i);
      std::vector<int> index(dims.size(), 1);
      int max = 1;
      for (int j = 0; j < dims.size(); j++)
        max *= dims[j];
      
      for (int k = 0; k < max; k++) {
        int param_index = i + matrix_index(index, dims);
        std::cout << std::setw(max_name_length + 1) << std::left 
                  << chains.param_name(param_index);
        std::cout << std::right;
        for (int j = 0; j < n; j++) {
          std::cout.setf(formats(j), std::ios::floatfield);
          std::cout 
            << std::setprecision(compute_precision(values(param_index,j), 
                                                   sig_figs, 
                                                   formats(j) == std::ios_base::scientific))
            << std::setw(column_widths(j)) << values(param_index, j);
        }
        std::cout << std::endl;
        next_index(index, dims);
      }
      i += max-1;
    }
  }

  /// Footer output
  std::cout << std::endl;
  std::cout << "Samples were drawn using " << stan_csv.metadata.algorithm
            << " with " << stan_csv.metadata.engine << "." << std::endl
            << "For each parameter, N_Eff is a crude measure of effective sample size," << std::endl
            << "and R_hat is the potential scale reduction factor on split chains (at " << std::endl
            << "convergence, R_hat=1)." << std::endl
            << std::endl;
  
  // Print autocorrelation, if desired
  for (int k = 1; k < argc; k++) {
    
    if (std::string(argv[k]).find("--autocorr=") != std::string::npos) {
      
      const int c = atoi(std::string(argv[k]).substr(11).c_str());
      
      if (c < 0 || c >= chains.num_chains()) {
        std::cout << "Bad chain index " << c << ", aborting autocorrelation display." << std::endl;
        break;
      }
      
      Eigen::MatrixXd autocorr(chains.num_params(), chains.num_samples(c));
      
      for (int i = 0; i < chains.num_params(); i++) {
        autocorr.row(i) = chains.autocorrelation(c, i);
      }
      
      // Format and print header
      std::cout << "Displaying the autocorrelations for chain " << c << ":" << std::endl;
      std::cout << std::endl;
      
      const int n_autocorr = autocorr.row(0).size();
      
      int lag_width = 1;
      int number = n_autocorr; 
      while ( number != 0) { number /= 10; lag_width++; }

      std::cout << std::setw(lag_width > 4 ? lag_width : 4) << "Lag";
      for (int i = 0; i < chains.num_params(); ++i) {
        std::cout << std::setw(max_name_length + 1) << std::right << chains.param_name(i);
      }
      std::cout << std::endl;

      // Print body  
      for (int n = 0; n < n_autocorr; ++n) {
        std::cout << std::setw(lag_width) << std::right << n;
        for (int i = 0; i < chains.num_params(); ++i) {
          std::cout << std::setw(max_name_length + 1) << std::right << autocorr(i, n);
        }
        std::cout << std::endl;
      }
  
    }
        
  }
      
  return 0;
        
}
Пример #14
0
int main(void) {
  clock_t begin, end;
  double time_spent;
  begin = clock();

  matrix* a = create_matrix(4, 4);
  value temp_a[16] = { 18, 60, 57, 96,
		       41, 24, 99, 58,
		       14, 30, 97, 66,
		       51, 13, 19, 85 };
  insert_array(temp_a, a);

  matrix* b = create_matrix(4, 4);
  assert(insert_array(temp_a, b));


  //tests check_boundaries
  assert(check_boundaries(1,1,a));
  assert(check_boundaries(4,4,a));
  assert(!check_boundaries(4,5,a));
  assert(!check_boundaries(5,4,a));
  assert(!check_boundaries(0,1,a));
  assert(!check_boundaries(1,0,a));
  assert(!check_boundaries(-1,1,a));
  assert(!check_boundaries(1,-1,a));


  //tests compare_matrices,insert_value and get_value
  assert(compare_matrices(a,b));
  assert(insert_value(10,1,1,b));
  assert(!compare_matrices(a,b));
  assert(get_value(1,1,b)==10);
  assert(insert_value(18,1,1,b));
  assert(compare_matrices(a,b));


  //tests is_matrix
  matrix* c=a;
  assert(compare_matrices(a,c));
  assert(!is_matrix(a,b));
  assert(is_matrix(a,c));


  //tests insert_value by trying to go outside the matrix
  assert(insert_value(1,1,1,c));
  assert(insert_value(2,2,2,c));
  assert(insert_value(3,3,3,c));
  assert(insert_value(4,4,4,c));
  assert(!insert_value(5,5,5,c));
  assert(!insert_value(-1,-1,-1,c));
  assert(!insert_value(-1,-1,1,c));
  assert(!insert_value(-1,1,-1,c));

  //test get_value
  assert(get_value(1,1,c)==1);
  assert(get_value(2,2,c)==2);
  assert(get_value(3,3,c)==3);
  assert(get_value(4,4,c)==4);
  assert(get_value(0,0,c)==0);
  assert(get_value(1,-1,c)==0);
  assert(get_value(-1,1,c)==0);
  assert(get_value(5,5,c)==0);

  //tests insert and get without boundary checks
  insert_value_without_check(4,1,1,c);
  insert_value_without_check(3,2,2,c);
  insert_value_without_check(2,3,3,c);
  insert_value_without_check(1,4,4,c);
  assert(get_value_without_check(1,1,c)==4);
  assert(get_value_without_check(2,2,c)==3);
  assert(get_value_without_check(3,3,c)==2);
  assert(get_value_without_check(4,4,c)==1);

  //tests add_matrices
  value temp_b[16]={
    36,120,114,192,
    82,48,198,116,
    28, 60, 194,132,
    102,26,38,170};
  assert(insert_array(temp_b,a));
  matrix* d = create_matrix(4, 4);
  assert(add_matrices(b,b,d));
  assert(compare_matrices(d,a));

  //tests subtract_matrices
  value temp_c[16]={
    0,0,0,0,
    0,0,0,0,
    0, 0, 0,0,
    0,0,0,0};
  assert(insert_array(temp_c,a));
  assert(subtract_matrices(b,b,d));
  assert(compare_matrices(d,a));

  //tests sum_of_row
  assert(insert_array(temp_a,a));
  assert(sum_of_row(1,a)==231);
  assert(sum_of_row(4,a)==168);
  assert(sum_of_row(0,a)==0);
  assert(sum_of_row(5,a)==0);

  //tests sum_of_column
  assert(sum_of_column(1,a)==124);
  assert(sum_of_column(4,a)==305);
  assert(sum_of_column(0,a)==0);
  assert(sum_of_column(5,a)==0);

  //tests get_row_vector
  matrix* e = create_matrix(1, 4);
  value temp_d[4] = { 18, 60, 57, 96};
  assert(insert_array(temp_d,e));
  matrix* f = create_matrix(1, 4);
  assert(!get_row_vector(0,a,f));
  assert(!get_row_vector(5,a,f));
  assert(get_row_vector(1,a,f));
  assert(compare_matrices(e,f));

  //tests get_column_vector
  matrix* g = create_matrix(4, 1);
  assert(insert_array(temp_d,e));
  matrix* h = create_matrix(1, 4);
  assert(!get_row_vector(0,a,h));
  assert(!get_row_vector(5,a,h));
  assert(get_row_vector(1,a,h));
  assert(compare_matrices(e,h));

  //tests mulitply_matrices
  assert(multiply_matrices(a,a,b));
  value temp_f[16]={8478,5478,14319,17130,
		    6066,6760,15418,16792,
		    6206,5328,14431,15096,
		    6052,5047,7652,14129.00};
  assert(insert_array(temp_f,d));
  assert(compare_matrices(b,d));
  assert(!multiply_matrices(a,h,b));
  assert(!multiply_matrices(a,a,h));

  //tests transpose_matrix
  value temp_g[16]={18,41,14,51,
		    60,24,30,13,
		    57,99,97,19,
		    96,58,66,85};
  assert(insert_array(temp_g,d));
  assert(transpose_matrix(a,b));
  assert(compare_matrices(b,d));
  assert(!transpose_matrix(e,b));
  assert(!transpose_matrix(a,e));

  //tests multiply_matrix_with_scalar
  value temp_h[16] = { 36, 120, 114, 192,
		       82, 48, 198, 116,
		       28, 60, 194, 132,
		       102, 26, 38, 170 };
  assert(insert_array(temp_h,b));
  multiply_matrix_with_scalar(2,a);
  assert(compare_matrices(a,b));

  //test get_sub_matrix
  matrix* i=create_matrix(2,2);
  assert(insert_array(temp_a,a));
  assert(get_sub_matrix(1,2,1,2,a,i));
  matrix* j=create_matrix(2,2);
  value temp_i[4] = { 18, 60, 41, 24};
  assert(insert_array(temp_i,j));
  assert(compare_matrices(j,i));
  value temp_j[4] = { 97, 66, 19, 85};
  assert(insert_array(temp_j,j));
  assert(get_sub_matrix(3,4,3,4,a,i));
  assert(compare_matrices(j,i));
  assert(!get_sub_matrix(2,4,3,4,a,i));
  assert(!get_sub_matrix(3,4,2,4,a,i));
  assert(!get_sub_matrix(4,5,4,5,a,i));
  assert(!get_sub_matrix(0,1,0,1,a,i));

  //test insert_row_vector
  assert(insert_array(temp_a,a));
  value temp_k[16] = { 18, 60, 57, 96,
		       18, 60, 57, 96,
		       14, 30, 97, 66,
		       51, 13, 19, 85 };
  assert(insert_array(temp_k,b));
  assert(insert_array(temp_d,e));
  assert(insert_row_vector(2,e,a));
  assert(compare_matrices(a,b));

  end = clock();
  time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
  printf("time taken was: %f \n",time_spent);
  free_matrix(a);
  free_matrix(b);
  free_matrix(d);
  free_matrix(e);
  free_matrix(f);
  free_matrix(g);
  free_matrix(h);
  free_matrix(i);
  free_matrix(j);

  return 0;
}
Пример #15
0
static Bool set_cid_subfont(FONTinfo *fontInfo, OBJECT *dict)
{
  CID0_CACHE *cid_font ;
  OBJECT *theo;
  OMATRIX matrix ;

  enum { mch_subdict_Private, mch_subdict_FontMatrix, mch_subdict_dummy };
  static NAMETYPEMATCH mch_subdict[mch_subdict_dummy + 1] = {
    /* Use the enum above to index these */
    { NAME_Private,              1, { ODICTIONARY }},
    { NAME_FontMatrix,           2, { OARRAY, OPACKEDARRAY }},
    DUMMY_END_MATCH
  };

  enum { mch_private_Subrs, mch_private_SubrMapOffset, mch_private_SubrCount,
         mch_private_SDBytes, mch_private_RunInt, mch_private_dummy };
  static NAMETYPEMATCH mch_private[mch_private_dummy + 1] = {
    /* Use the enum above to index these */
    { NAME_Subrs | OOPTIONAL,         2, { OARRAY, OPACKEDARRAY }},
    { NAME_SubrMapOffset | OOPTIONAL, 1, { OINTEGER }},
    { NAME_SubrCount | OOPTIONAL,     1, { OINTEGER }},
    { NAME_SDBytes | OOPTIONAL,       1, { OINTEGER }},
    { NAME_RunInt | OOPTIONAL,        1, { ONAME }},
    DUMMY_END_MATCH
  };

  HQASSERT(fontInfo, "No font info") ;
  HQASSERT(dict, "No CID sub-dict") ;

  if ( (cid_font = cid0_set_font(fontInfo)) == NULL )
    return FALSE ;

  VERIFY_OBJECT(cid_font, CID0_CACHE_NAME) ;

  /* Extract the necessary font parameters */
  if ( !dictmatch(dict, mch_subdict) ||
       !dictmatch(mch_subdict[mch_subdict_Private].result, mch_private) )
    return error_handler(INVALIDFONT);

  if ( mch_private[mch_private_Subrs].result ) {
    cid_font->subrs = mch_private[mch_private_Subrs].result ;
    cid_font->subrcount = theLen(*cid_font->subrs) ;
    cid_font->subrmapoffset = cid_font->sdbytes = 0 ;
  } else {
    /* No Subrs, look for SubrMap details. We don't enforce requiring the
       offsets if there is no SubrCount or it is zero. */
    cid_font->subrs = NULL ;

    if ( (theo = mch_private[mch_private_SubrCount].result) != NULL ) {
      if ( oInteger(*theo) < 0 )
        return error_handler(INVALIDFONT) ;

      cid_font->subrcount = (uint32)oInteger(*theo) ;
    }

    if ( (theo = mch_private[mch_private_SDBytes].result) != NULL ) {
      if ( oInteger(*theo) < 0 || oInteger(*theo) > 4 )
        return error_handler(INVALIDFONT) ;

      cid_font->sdbytes = (uint32)oInteger(*theo) ;
    }

    if ( (theo = mch_private[mch_private_SubrMapOffset].result) != NULL ) {
      if ( oInteger(*theo) < 0 )
        return error_handler(INVALIDFONT) ;

      cid_font->subrmapoffset = (uint32)oInteger(*theo) ;
    }
 }

  /* No Encoding array. */
  theTags(theEncoding(*fontInfo)) = ONULL;

  /* No charstring dictionary. */
  theCharStrings(*fontInfo) = NULL;

  /* Metrics dictionary will be inherited from the top level CIDFont, so don't
     do anything with theMetrics and theMetrics2. */

  /* Test if it's a Morisawa or ATL encypted CID font */
  isEncrypted(*fontInfo) = PROTECTED_NONE ;
  theo = mch_private[mch_private_RunInt].result;
  if ( theo ) {
    if ( oName(*theo) == &system_names[ NAME_SpecialRun ] )
      isEncrypted(*fontInfo) = PROTECTED_MRSWA ;
    else if ( oName(*theo) == &system_names[ NAME_eCCRun ] )
      isEncrypted(*fontInfo) = PROTECTED_ATL ;
  }

  theSubsCount(*fontInfo) = 0;

  if ( !is_matrix(mch_subdict[mch_subdict_FontMatrix].result, &matrix) )
    return FALSE;

  /* Multiply this by the current fontmatrix to give a new one */
  matrix_mult(&matrix, &theFontMatrix(*fontInfo), &theFontMatrix(*fontInfo));
  matrix_mult(&matrix, &theFontCompositeMatrix(*fontInfo),
              &theFontCompositeMatrix(*fontInfo));

  /* gotFontMatrix is still set, from the set_font call preceding this. Leave
     theLookupFont set if it was already, since the FID in the parent
     dictionary is still valid. The matrix has changed though, so clear the
     lookup matrix. */
  theLookupMatrix(*fontInfo) = NULL ;

  /* Finally, install the FDArray subdict as the source for Private
     information */
  Copy(&fontInfo->subfont, dict) ;

  return TRUE;
}
Пример #16
0
int display(list<string>::iterator &ifname,
	    bool signd, bool load, list<string> *mats) {
  //cout << "displaying " << ifname->c_str() << endl;
  // conf mode
  if (conf)
    return display_net<T>(ifname, signd, load, mats);
  // mat mode
  if (is_matrix(ifname->c_str())) {
    idxdim d = get_matrix_dims(ifname->c_str());
    if (interleaved)
      d.shift_dim(0, 2);
    if (save_individually || print
        || !(d.order() == 2  || (d.order() == 3 &&
                                 (d.dim(2) == 1 || d.dim(2) == 3)))) {
      // this is probably not an image, just display info and print matrix
      string type;
      get_matrix_type(ifname->c_str(), type);
      idx<T> m = load_matrix<T>(ifname->c_str());
      cout << "Matrix " << ifname->c_str() << " is of type " << type
	   << " with dimensions " << d << " (min " << idx_min(m)
	   << ", max " << idx_max(m) << ", mean " << idx_mean(m)
	   << "):" << endl;
      m.print();
      if (has_multiple_matrices(ifname->c_str())) {
	midx<T> ms = load_matrices<T>(ifname->c_str(), true);
	// saving sub-matrices
	if (save_individually) {
	  cout << "Saving each sub-matrix of " << *ifname << " individually..."
	       << endl;
	  save_matrices_individually(ms, *ifname, true);
	}
	// printing sub-matrices
	cout << "This file contains " << m << " matrices: ";
	if (ms.order() == 1) {
	  for (intg i = 0; i < ms.dim(0); ++i) {
	    idx<T> tmp = ms.mget(i);
	    cout << tmp.info() << " ";
	  }
	} else if (ms.order() == 2) {
	  for (intg i = 0; i < ms.dim(0); ++i) {
	    for (intg j = 0; j < ms.dim(1); ++j) {
	      idx<T> tmp = ms.mget(i, j);
	      cout << tmp.info() << " ";
	    }
	    cout << endl;
	  }
	}
	cout << endl;
      } else
	cout << "This is a single-matrix file." << endl;
      return 0;
    }
  }
  // image mode
  int loaded = 0;
  static idx<T> mat;
  uint h = 0, w = 0, rowh = 0, maxh = 0;
  list<string>::iterator fname = ifname;
#ifdef __GUI__
  disable_window_updates();
  clear_window();
  if (show_filename) {
    gui << at(h, w) << black_on_white() << ifname->c_str();
    h += 16;
  }
#endif
  maxh = h;
  for (uint i = 0; i < nh; ++i) {
    rowh = maxh;
    for (uint j = 0; j < nw; ++j) {
      if (fname == mats->end())
	fname = mats->begin();
      try {
	//      if (load)
	mat = load_image<T>(*fname);
	if (print)
	  cout << *fname << ": " << mat << endl << mat.str() << endl;
	// show only some channels
	if (chans >= 0)
	  mat = mat.select(2, chans);
	loaded++;
	maxh = (std::max)(maxh, (uint) (rowh + mat.dim(0)));
	T min = 0, max = 0;
#ifdef __GUI__
	if (autorange || signd) {
	  if (autorange) {
	    min = idx_min(mat);
	    max = idx_max(mat);
	  } else if (signd) {
	    T matmin = idx_min(mat);
	    if ((double)matmin < 0) {
	      min = -1;
	      max = -1;
	    }
	  }
	  draw_matrix(mat, rowh, w, zoom, zoom, min, max);
	} else
	  draw_matrix(mat, rowh, w, zoom, zoom, (T) range[0], (T) range[1]);
#endif
	w += mat.dim(1) + 1;
      } catch(string &err) {
	ERROR_MSG(err.c_str());
      }
      fname++;
      if (fname == ifname)
	break ;
    }
    if (fname == ifname)
      break ;
    maxh++;
    w = 0;
  }
#ifdef __GUI__
  // info
  if (show_info) {
    set_text_colors(0, 0, 0, 255, 255, 255, 255, 200);
    gui << mat;
    gui << at(15, 0) << *fname;
    gui << at(29, 0) << "min: " << idx_min(mat) << " max: " << idx_max(mat);
  }
  // help
  if (show_help) {
    h = 0;
    w = 0;
    uint hstep = 14;
    set_text_colors(0, 0, 255, 255, 255, 255, 255, 200);
    gui << at(h, w) << "Controls:"; h += hstep;
    set_text_colors(0, 0, 0, 255, 255, 255, 255, 200);
    gui << at(h, w) << "Right/Space: next image"; h += hstep;
    gui << at(h, w) << "Left/Backspace: previous image"; h += hstep;
    gui << at(h, w) << "i: image info"; h += hstep;
    gui << at(h, w) << "a: auto-range (use min and max as range)"; h += hstep;
    gui << at(h, w) << "x/z: show more/less images on width axis"; h += hstep;
    gui << at(h, w) << "y/t: show more/less images on height axis"; h += hstep;
    gui << at(h, w) << "0,1,2: show channel 0, 1 or 2 only"; h += hstep;
    gui << at(h, w) << "9: show alls channels"; h += hstep;
    gui << at(h, w) << "h: help";
  }
  // update title
  string title;
  title << "matshow: " << ebl::basename(ifname->c_str());
  set_window_title(title.c_str());
  enable_window_updates();
#endif
  return loaded;
}