void run(Mat& A, const int rank){
    if (A.cols() == 0 || A.rows() == 0) return;
    int r = (rank < A.cols()) ? rank : A.cols();
    r = (r < A.rows()) ? r : A.rows();
    
    // Gaussian Random Matrix
    Eigen::MatrixXf O(A.rows(), r);
    Util::sampleGaussianMat(O);
    
    // Compute Sample Matrix of A
    Eigen::MatrixXf Y = A.transpose() * O;
    
    // Orthonormalize Y
    Util::processGramSchmidt(Y);

    Eigen::MatrixXf B = Y.transpose() * A * Y;
    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXf> eigenOfB(B);
    
    eigenValues_ = eigenOfB.eigenvalues();
    eigenVectors_ = Y * eigenOfB.eigenvectors();
  }
IGL_INLINE void igl::all_pairs_distances(
  const Mat & V,
  const Mat & U,
  const bool squared,
  Mat & D)
{
  // dimension should be the same
  assert(V.cols() == U.cols());
  // resize output
  D.resize(V.rows(),U.rows());
  for(int i = 0;i<V.rows();i++)
  {
    for(int j=0;j<U.rows();j++)
    {
      D(i,j) = (V.row(i)-U.row(j)).array().pow(2).sum();
      if(!squared)
      {
        D(i,j) = sqrt(D(i,j));
      }
    }
  }
}
  void run(Mat& A, const int rank){
    if (A.cols() == 0 || A.rows() == 0) return;
    int r = (rank < A.cols()) ? rank : A.cols();
    r = (r < A.rows()) ? r : A.rows();
    
    // Gaussian Random Matrix for A^T
    Eigen::MatrixXf O(A.rows(), r);
    Util::sampleGaussianMat(O);
    
    // Compute Sample Matrix of A^T
    Eigen::MatrixXf Y = A.transpose() * O;
    
    // Orthonormalize Y
    Util::processGramSchmidt(Y);

    // Range(B) = Range(A^T)
    Eigen::MatrixXf B = A * Y;
    
    // Gaussian Random Matrix
    Eigen::MatrixXf P(B.cols(), r);
    Util::sampleGaussianMat(P);
    
    // Compute Sample Matrix of B
    Eigen::MatrixXf Z = B * P;
    
    // Orthonormalize Z
    Util::processGramSchmidt(Z);
    
    // Range(C) = Range(B)
    Eigen::MatrixXf C = Z.transpose() * B; 
    
    Eigen::JacobiSVD<Eigen::MatrixXf> svdOfC(C, Eigen::ComputeThinU | Eigen::ComputeThinV);
    
    // C = USV^T
    // A = Z * U * S * V^T * Y^T()
    matU_ = Z * svdOfC.matrixU();
    matS_ = svdOfC.singularValues();
    matV_ = Y * svdOfC.matrixV();
  }
      void expectedRowsDivide() {
        for(int n = 0; n < _elemInds.n_elem; n++) {
          if(!_genColVec.in_range(_elemInds.at(n))) {
            return;
          }
        }

        cout << "- Compute expectedRowsDivide() ... ";

        _genColVec.rows(_elemInds) /= _genDouble;

        save<double>("Col.rowsDivide", _genColVec);
        cout << "done." << endl;
      }
		void l1SixPointResectionSolver::Solve(const Mat &point_2d, const Mat &point_3d, std::vector<Mat34> *Ps) {

			assert(2 == point_2d.rows());
			assert(3 == point_3d.rows());
			assert(6 <= point_2d.cols());//保证点数大于等于6
			assert(point_2d.cols() == point_3d.cols());

			//-- Translate 3D points in order to have X0 = (0,0,0,1).
			Vec3 vec_translation = -point_3d.col(0);
			Mat4 translation_matrix = Mat4::Identity();
			translation_matrix.block<3, 1>(0, 3) = vec_translation;

			Mat3X output_points;
			Translate(point_3d, vec_translation, &output_points);

			std::vector<double> vec_solution(11);
			OSI_CLP_SolverWrapper wrapper_lp_solver(vec_solution.size());
			Resection_L1_ConstraintBuilder constraint_builder(point_2d, output_points);
			if (
				(BisectionLinearProgramming<Resection_L1_ConstraintBuilder, LP_Constraints_Sparse>(
				wrapper_lp_solver,
				constraint_builder,
				&vec_solution,
				1.0,
				0.0))
				)
			{
				// Move computed value to dataset for residual estimation.
				Mat34 P;
				P << vec_solution[0], vec_solution[1], vec_solution[2], vec_solution[3],
					vec_solution[4], vec_solution[5], vec_solution[6], vec_solution[7],
					vec_solution[8], vec_solution[9], vec_solution[10], 1.0;
				P = P * translation_matrix;
				Ps->push_back(P);
			}
		}
  ACKernelAdaptor(const Mat &x1, int w1, int h1,
             const Mat &x2, int w2, int h2, bool bPointToLine = true)
    : x1_(x1.rows(), x1.cols()), x2_(x2.rows(), x2.cols()),
    N1_(3,3), N2_(3,3), logalpha0_(0.0), bPointToLine_(bPointToLine)
  {
    assert(2 == x1_.rows());
    assert(x1_.rows() == x2_.rows());
    assert(x1_.cols() == x2_.cols());

    NormalizePoints(x1, &x1_, &N1_, w1, h1);
    NormalizePoints(x2, &x2_, &N2_, w2, h2);

    // LogAlpha0 is used to make error data scale invariant
    if(bPointToLine)  {
      // Ratio of containing diagonal image rectangle over image area
      double D = sqrt(w2*(double)w2 + h2*(double)h2); // diameter
      double A = w2*(double)h2; // area
      logalpha0_ = log10(2.0*D/A /N2_(0,0));
    }
    else  {
      // ratio of area : unit circle over image area
      logalpha0_ = log10(M_PI/(w2*(double)h2) /(N2_(0,0)*N2_(0,0)));
    }
  }
void GuidedMatching(
  const ModelArg & mod, // The model
  const Mat & xLeft,    // The left data points
  const Mat & xRight,   // The right data points
  double errorTh,       // Maximal authorized error threshold
  std::vector<IndMatch> & vec_corresponding_index) // Ouput corresponding index
{
  assert(xLeft.rows() == xRight.rows());

  // Looking for the corresponding points that have
  //  the smallest distance (smaller than the provided Threshold)

  for (size_t i = 0; i < xLeft.cols(); ++i) {

    double min = std::numeric_limits<double>::max();
    IndMatch match;
    for (size_t j = 0; j < xRight.cols(); ++j) {
      // Compute error to the model
      double err = ErrorArg::Error(
        mod,  // The model
        xLeft.col(i), xRight.col(j)); // The corresponding points
      // if smaller error update corresponding index
      if (err < errorTh && err < min) {
        min = err;
        match = IndMatch(i,j);
      }
    }
    if (min < errorTh)  {
      // save the best corresponding index
      vec_corresponding_index.push_back(match);
    }
  }

  // Remove duplicates (when multiple points at same position exist)
  IndMatch::getDeduplicated(vec_corresponding_index);
}
Example #8
0
bool LocalNetwork::singular_coords(const Mat& A)
{
  bool result = false;

  Double a, b, aa, ab, bb, D;          // testing xy submatrix is sufficient
  Index  indx, indy, r;

  for (PointData::iterator i=PD.begin(); i!=PD.end(); ++i)
    {
      LocalPoint&  p  = (*i).second;
      if (!p.free_xy() || p.index_x()==0) continue;

      indx = p.index_x();
      indy = p.index_y();

      aa = ab = bb = 0;
      for (r=1; r<=A.rows(); r++)
        {
          a = A(r,indx);
          b = A(r,indy);
          aa += a*a;
          ab += a*b;
          bb += b*b;
        }

      // old scale dependent test:
      //
      // D = aa*bb - ab*ab;
      // 
      // if ((aa == 0) || (fabs(D) <= aa*1e-6))

      if (bb > aa) std::swap(aa, bb);
      if (aa == 0)
        D = 0;
      else
        D = 1 - std::abs(ab)/std::sqrt(aa*bb);     // 1 - |cos(a,b)|

      if (D < 1e-12)
        {
          result = true;
          p.unused_xy();
          removed( (*i).first, rm_singular_xy );
        }
      
    }

  return result;
}
Example #9
0
void MeanAndVarianceAlongRows(const Mat &A,
  Vec *mean_pointer,
  Vec *variance_pointer) {
    Vec &mean = *mean_pointer;
    Vec &variance = *variance_pointer;
    Mat::Index n = A.rows();
    double m = static_cast<double>(A.cols());
    mean = variance = Vec::Zero(n);

    for (Mat::Index i = 0; i < n; ++i) {
      mean(i) += A.row(i).array().sum();
      variance(i) += (A.row(i).array() * A.row(i).array()).array().sum();
    }

    mean /= m;
    for (Mat::Index i = 0; i < n; ++i) {
      variance(i) = variance(i) / m - Square(mean(i));
    }
}
Example #10
0
		bool ExportMatToTextFile(const Mat & mat, const std::string & filename,
			const std::string & prefix)
		{
			bool is_ok = false;
			std::ofstream outfile;
			outfile.open(filename.c_str(), std::ios_base::out);
			if (outfile.is_open()) {
				outfile << prefix << "=[" << std::endl;
				for (int j = 0; j < mat.rows(); ++j)  {
					for (int i = 0; i < mat.cols(); ++i)  {
						outfile << mat(j, i) << " ";
					}
					outfile << ";\n";
				}
				outfile << "];";
				is_ok = true;
			}
			outfile.close();
			return is_ok;
		}
Example #11
0
void fileProcess(const std::string& inputFileName,
		 const std::string& outputFileName,
		 int rank){
  double startSec = Util::getSec();
  std::cout << "read matrix from " << inputFileName << " ... " << std::flush;
  Mat A;
  readMatrix(inputFileName.c_str(), A);
  std::cout << Util::getSec() - startSec << " sec." <<std:: endl;
  std::cout << "rows:\t" << A.rows() << std::endl
	    << "cols:\t" << A.cols() << std::endl
	    << "rank:\t" << rank  << std::endl;

  std::cout << "compute ... " << std::flush;
  startSec = Util::getSec();
  RetMat retMat(A, rank);
  std::cout << Util::getSec() - startSec << " sec." << std::endl;
  
  startSec = Util::getSec();
  writeMatrix(outputFileName, retMat);
  std::cout << Util::getSec() - startSec << " sec." << std::endl
	    << "finished." << std::endl;
}
Example #12
0
bool SpeechRec::ProcessOffline(data_format inpf, data_format outpf, void *inpSig, int sigNBytes, Mat<float> *inpMat, Mat<float> *outMat)
{
	assert((int)inpf < (int)outpf);
	assert(outMat || outpf == dfStrings);
	assert(inpMat || inpf == dfWaveform);

	Mat<float> *paramMat = 0;
	Mat<float> *posteriorsMat = 0;

	// waveform -> parameters
	int nFrames;
	if(inpf == dfWaveform)
	{
		if(!ConvertWaveformFormat(waveFormat, inpSig, sigNBytes, &waveform, &waveformLen))
			return false;

		nFrames = (waveformLen > actualParams->GetVectorSize() ? (waveformLen - actualParams->GetVectorSize()) / actualParams->GetStep() + 1 : 1);
				
		actualParams->AddWaveform(waveform, waveformLen);
			
		if(outpf == dfParams)
		{
			paramMat = outMat;
		}
		else
		{
			paramMat = new Mat<float>; 
			if(!paramMat)
			{
				MERROR("Insufficient memory\n");
				return false;
			}
		}
		if(actualParams->GetNParams() != paramMat->columns() || nFrames != paramMat->rows())
		   paramMat->init(nFrames, actualParams->GetNParams());

		int fr = 0;
		while(actualParams->GetFeatures(params))
		{				
			FrameBasedNormalization(params, actualParams->GetNParams());
			paramMat->set(fr, fr, 0, actualParams->GetNParams() - 1, params);
			fr++;
		}

		if(outpf == dfParams)
			return true;
	}

	// sentence based normalization
	if(inpf == dfWaveform || inpf == dfParams)
	{
		if(inpf == dfParams)
			paramMat = inpMat;

                if(paramMat->columns() < actualParams->GetNParams())
                {
			MERROR("Invalid dimensionality of parameter vectors\n");
			return false;
                }
		else if(paramMat->columns() > actualParams->GetNParams())
		{
			Mat<float> *tmpMat = new Mat<float>;
			tmpMat->init(paramMat->rows(), actualParams->GetNParams());
			tmpMat->copy(*paramMat, 0, paramMat->rows() - 1, 0, actualParams->GetNParams() - 1, 
                                                   0, paramMat->rows() - 1, 0, actualParams->GetNParams() - 1);
			delete paramMat;
			paramMat = tmpMat;
			inpMat = paramMat;
		}

		SentenceBasedNormalization(paramMat);
	}

	// parameters -> posteriors
	if(outpf == dfPosteriors && !mTrapsEnabled)
        {
		MERROR("The 'traps' module have to be enabled for generating posteriors\n");
		return false;
        }

	if((inpf == dfWaveform || inpf == dfParams) && mTrapsEnabled)
	{
		if(inpf == dfParams)
			paramMat = inpMat;

		if(outpf == dfPosteriors)
		{
			posteriorsMat = outMat;
		}
		else
		{
			posteriorsMat = new Mat<float>;
			if(!posteriorsMat)
			{
				if(inpf != dfParams)
						delete paramMat;
				MERROR("Insufficient memory\n");
				return false;
			}
		}

		nFrames = paramMat->rows();

		if(TR.GetNumOuts() != posteriorsMat->columns() || nFrames != posteriorsMat->rows())
			posteriorsMat->init(nFrames, TR.GetNumOuts());

		// first part - initialization
		int i;
		int trapShift = TR.GetTrapShift();
		int nparams = actualParams->GetNParams();
		if(nFrames >= trapShift)
		{
			TR.CalcFeaturesBunched((float *)paramMat->getMem(), posteriors, trapShift, false);
		}
		else
		{
			sCopy(nFrames * paramMat->columns(), params, (float *)paramMat->getMem());
			for(i = nFrames; i < TR.GetTrapShift(); i++)
				paramMat->extr(nFrames - 1, nFrames - 1, 0, nparams - 1, params + i * nparams);
			TR.CalcFeaturesBunched(params, posteriors, trapShift, false);
		}

		// second part - main block
		if(nFrames > trapShift)
			TR.CalcFeaturesBunched((float *)paramMat->getMem() + trapShift * nparams, (float *)posteriorsMat->getMem(), nFrames - trapShift);

		// last part - termination
		int n = (nFrames > trapShift ? trapShift : nFrames);
		for(i = 0; i < n; i++)
			paramMat->extr(nFrames - 1, nFrames - 1, 0, nparams - 1, params + i * nparams);
		TR.CalcFeaturesBunched(params, (float *)posteriorsMat->getMem() + (nFrames - n) * posteriorsMat->columns(), n);

		// softening function: posteriors -> posteriors/log. posteriors
                int nPost = posteriorsMat->columns();
		for(i = 0; i < nFrames; i++)
		{
			posteriorsMat->extr(i, i, 0, nPost - 1, posteriors);
			int j;
			for(j = 0; j < nPost; j++)
				posteriors[j] = (*postSoftFunc)(posteriors[j], postSoftArg1, postSoftArg2, postSoftArg3);
			posteriorsMat->set(i, i, 0, nPost - 1, posteriors);
		}

		if(inpf != dfParams)
			delete paramMat;

		if(outpf == dfPosteriors)
			return true;
	}

	// posteriors -> strings
	if(inpf == dfWaveform || inpf == dfParams || inpf == dfPosteriors)
	{
		if(inpf == dfPosteriors || (inpf == dfParams && !mTrapsEnabled))
			posteriorsMat = inpMat;

		nFrames = posteriorsMat->rows();
                int nPost = posteriorsMat->columns(); // TR.GetNumOuts()

		// softening function: posteriors -> log. posteriors
		int i;
		for(i = 0; i < nFrames; i++)
		{
			posteriorsMat->extr(i, i, 0, nPost - 1, posteriors);
			int j;
			for(j = 0; j < nPost; j++)
				posteriors[j] = (*decSoftFunc)(posteriors[j], decSoftArg1, decSoftArg2, decSoftArg3);
			posteriorsMat->set(i, i, 0, nPost - 1, posteriors);
		}

		// log posteriors -> strings
		for(i = 0; i <  nFrames; i++)
		{
			posteriorsMat->extr(i, i, 0, nPost - 1, posteriors);
			DE->ProcessFrame(posteriors);
		}

		if(inpf != dfPosteriors)
			delete posteriorsMat;
	}

	return true;
}
Example #13
0
void SpeechRec::SentenceBasedNormalization(Mat<float> *mat)
{
//        mat->saveAscii("c:\\before");

	// sentence mean and variance normalization
	bool mean_norm = C.GetBool("offlinenorm", "sent_mean_norm");
	bool var_norm = C.GetBool("offlinenorm", "sent_var_norm");

	if(mean_norm || var_norm)
	{
		Mat<float> mean;

		// mean calcualtion
		mat->sumColumns(mean);
		mean.div((float)mat->rows());

		// mean norm
		int i, j;
		for(i = 0; i < mat->columns(); i++)
			mat->sub(0, mat->rows() - 1, i, i, mean.get(0, i));

		if(var_norm)
		{
			// variance calculation
			Mat<float> var;
			var.init(mean.rows(), mean.columns());
			var.set(0.0f);
			for(i = 0; i < mat->columns(); i++)
			{
				for(j = 0; j < mat->rows(); j++)
				{
					float v = mat->get(j, i);
					var.add(0, i, v * v);
				}
			}
			var.div((float)mat->rows());
			var.sqrt();

			// lower threshold
			float lowerThr = C.GetFloat("melbanks", "sent_std_thr");
			var.lowerLimit(lowerThr);

			// variance norm
			for(i = 0; i < mat->columns(); i++)
				mat->mul(0, mat->rows() - 1, i, i, 1.0f / var.get(0, i));

			// add mean if not mean norm
			if(!mean_norm)
			{
				for(i = 0; i < mat->columns(); i++)
					mat->add(0, mat->rows() - 1, i, i, mean.get(0, i));
			}
		}
	}

	// sentence maximum normalization
	bool max_norm = C.GetBool("offlinenorm", "sent_max_norm");
	bool channel_max_norm = C.GetBool("offlinenorm", "sent_chmax_norm");

	if(max_norm || channel_max_norm)
	{
		Mat<float> max;
		max.init(1, mat->columns());
		max.set(-9999.9f);
		int i, j;

		for(i = 0; i < mat->columns(); i++)
		{
			for(j = 0; j < mat->rows(); j++)
			{
				float v = mat->get(j, i);
				if(v > max.get(0, i))
				{
				   max.set(0, i, v);
				}
			}
		}

		// global sentence maximum normalization
		if(max_norm)
		{
			float global_max = -9999.9f;
			for(i = 0; i < max.columns(); i++)
			{
				if(max.get(0, i) > global_max)
				{
				   global_max = max.get(0, i);
				}
				max.set(global_max);
			}
		}

		for(i = 0; i < mat->columns(); i++)
		{
			for(j = 0; j < mat->rows(); j++)
			{
	            		mat->set(j, i, mat->get(j, i) - max.get(0, i));
			}
		}
	}
}
 RedSVD(Mat& A){
   int r = (A.rows() < A.cols()) ? A.rows() : A.cols();
   run(A, r);
 }