double compute_max_step_from_singularities(const Eigen::MatrixXd& uv,
                                            const Eigen::MatrixXi& F,
                                            Eigen::MatrixXd& d) {
    double max_step = INFINITY;

    // The if statement is outside the for loops to avoid branching/ease parallelizing
    if (uv.cols() == 2) {
      for (int f = 0; f < F.rows(); f++) {
        double min_positive_root = get_min_pos_root_2D(uv,F,d,f);
        max_step = min(max_step, min_positive_root);
      }
    } else { // volumetric deformation
      for (int f = 0; f < F.rows(); f++) {
        double min_positive_root = get_min_pos_root_3D(uv,F,d,f);
        max_step = min(max_step, min_positive_root);
      }
    }
    return max_step;
 }
Example #2
0
  /*
  Train the classifier with the dataset of breastcancer patients from the
  LibSVM Libary
  */
  void TrainSVMClassifier_BreastCancerDataSet_shouldReturnTrue()
  {
    /* Declarating an featurematrixdataset, the first matrix
    of the matrixpair is the trainingmatrix and the second one is the testmatrix.*/
    std::pair<MatrixDoubleType,MatrixDoubleType> matrixDouble;
    matrixDouble = convertCSVToMatrix<double>(GetTestDataFilePath("Classification/FeaturematrixBreastcancer.csv"),';',0.5,true);
    m_TrainingMatrixX = matrixDouble.first;
    m_TestXPredict = matrixDouble.second;

    /* The declaration of the labelmatrixdataset is equivalent to the declaration
    of the featurematrixdataset.*/
    std::pair<MatrixIntType,MatrixIntType> matrixInt;
    matrixInt = convertCSVToMatrix<int>(GetTestDataFilePath("Classification/LabelmatrixBreastcancer.csv"),';',0.5,false);
    m_TrainingLabelMatrixY = matrixInt.first;
    m_TestYPredict = matrixInt.second;

    /* Setting of the SVM-Parameters*/
    classifier = mitk::LibSVMClassifier::New();
    classifier->SetGamma(1/(double)(m_TrainingMatrixX.cols()));
    classifier->SetSvmType(0);
    classifier->SetKernelType(2);

    /* Train the classifier, by giving trainingdataset for the labels and features.
    The result in an colunmvector of the labels.*/
    classifier->Train(m_TrainingMatrixX,m_TrainingLabelMatrixY);
    Eigen::MatrixXi classes = classifier->Predict(m_TestXPredict);

    /* Testing the matching between the calculated colunmvector and the result
    of the SVM */
    unsigned int maxrows = classes.rows();

    bool isYPredictVector = false;
    int count = 0;

    for(int i= 0; i < maxrows; i++){
      if(classes(i,0) == m_TestYPredict(i,0)){
        isYPredictVector = true;
        count++;
      }
    }
    MITK_INFO << 100*count/(double)(maxrows) << "%";
    MITK_TEST_CONDITION(isIntervall<int>(m_TestYPredict,classes,75,100),"Testvalue is in range.");
  }
Example #3
0
bool BlockSparseMatrix::ConjugateGradientSolve(const Eigen::MatrixXd& rhs, Eigen::MatrixXd& sol)
{
	return LltSolve(rhs, sol);

	MatrixSolver* solver = new PCGSolver();
	int numRows = rhs.rows();
	int numCols = rhs.cols();
	int num = numRows * numCols;
	double* result = new double[num];
	double* rhsData = new double[num];
	int ithElem = 0;
	for (int i = 0; i < numCols; ++i)
	{
		for (int j = 0; j < numRows; ++j)
		{
			rhsData[ithElem++] = rhs(j, i);
		}
	}

	if (mbCSRDirty)
	{
		mCSREquivalent.ConvertFromBlockSparseMatrix(*this);
		mbCSRDirty = false;
	}

	solver->SetMatrix(&mCSREquivalent);
	solver->SetRHS(rhsData, numCols);
	solver->Solve(result, true);
	sol = Eigen::MatrixXd::Zero(numRows, numCols);
	ithElem = 0;
	for (int i = 0; i < numCols; ++i)
	{
		for (int j = 0; j < numRows; ++j)
		{
			sol(j, i) = result[ithElem++];
		}
	}

	delete[] rhsData;
	delete[] result;
	delete solver;
	return true;
}
Example #4
0
// Derived from code by Yohann Solaro ( http://listengine.tuxfamily.org/lists.tuxfamily.org/eigen/2010/01/msg00187.html )
// see : http://en.wikipedia.org/wiki/Moore-Penrose_pseudoinverse#The_general_case_and_the_SVD_method
Eigen::MatrixXd pinv( const Eigen::MatrixXd &b, double rcond )
{
  // TODO: Figure out why it wants fewer rows than columns
  // if ( a.rows()<a.cols() )
  // return false;
  bool flip = false;
  Eigen::MatrixXd a;
  if( a.rows() < a.cols() )
  {
    a = b.transpose();
    flip = true;
  }
  else
    a = b;
  // SVD
  Eigen::JacobiSVD<Eigen::MatrixXd> svdA;
  svdA.compute( a, Eigen::ComputeFullU | Eigen::ComputeThinV );
  Eigen::JacobiSVD<Eigen::MatrixXd>::SingularValuesType vSingular = svdA.singularValues();
  // Build a diagonal matrix with the Inverted Singular values
  // The pseudo inverted singular matrix is easy to compute :
  // is formed by replacing every nonzero entry by its reciprocal (inversing).
  Eigen::VectorXd vPseudoInvertedSingular( svdA.matrixV().cols() );

  for (int iRow=0; iRow<vSingular.rows(); iRow++)
  {
    if ( fabs(vSingular(iRow)) <= rcond )
    {
      vPseudoInvertedSingular(iRow)=0.;
    }
    else
      vPseudoInvertedSingular(iRow)=1./vSingular(iRow);
  }
  // A little optimization here
  Eigen::MatrixXd mAdjointU = svdA.matrixU().adjoint().block( 0, 0, vSingular.rows(), svdA.matrixU().adjoint().cols() );
  // Pseudo-Inversion : V * S * U'
  Eigen::MatrixXd a_pinv = (svdA.matrixV() * vPseudoInvertedSingular.asDiagonal()) * mAdjointU;
  if( flip )
  {
    a = a.transpose();
    a_pinv = a_pinv.transpose();
  }
  return a_pinv;
}
Example #5
0
IGL_INLINE void igl::n_polyvector_general(const Eigen::MatrixXd &V,
                             const Eigen::MatrixXi &F,
                             const Eigen::VectorXi& b,
                             const Eigen::MatrixXd& bc,
                             const Eigen::VectorXi &I,
                             Eigen::MatrixXd &output)
{
  Eigen::VectorXi isConstrained = Eigen::VectorXi::Constant(F.rows(),0);
  Eigen::MatrixXd cfW = Eigen::MatrixXd::Constant(F.rows(),bc.cols(),0);

  for(unsigned i=0; i<b.size();++i)
  {
    isConstrained(b(i)) = 1;
    cfW.row(b(i)) << bc.row(i);
  }
  int n = I.rows();
  igl::GeneralPolyVectorFieldFinder<Eigen::MatrixXd, Eigen::MatrixXi> pvff(V,F,n);
  pvff.solve(isConstrained, cfW, I, output);
}
//! Function to read the amplitudes and fundamental argument multiplers for tidal corrections
std::pair< Eigen::MatrixXd, Eigen::MatrixXd > readAmplitudesAndFundamentalArgumentMultipliers(
        const std::string amplitudesFile,
        const std::string fundamentalArgumentMultipliersFile,
        const double minimumAmplitude )
{

    // Read amplitudes and fundamental argument multipliers into matrices.
    Eigen::MatrixXd amplitudesRaw = input_output::readMatrixFromFile( amplitudesFile );
    Eigen::MatrixXd fundamentalArgumentMultipliersRaw = input_output::readMatrixFromFile( fundamentalArgumentMultipliersFile );

    // Check whether amplitudes and fundamental argument multipliers matrices have same number of rows
    if( amplitudesRaw.rows( ) != fundamentalArgumentMultipliersRaw.rows( ) )
    {
        throw std::runtime_error( "Amplitude and argument multipler files contain unequal set of entries" );
    }

    // Check whether number of columns in fundamental argument multiplier matrix is equal to 6.
    if( fundamentalArgumentMultipliersRaw.cols( ) != 6 )
    {
        throw std::runtime_error( "Number of columns in fundamental argument multipler matrix not equal to 6" );
    }


    // If acceptance amplitude is larger than 0.0 check RSS of amplitudes for each entry.
    Eigen::MatrixXd fundamentalArgumentMultipliers, amplitudes;
    if( minimumAmplitude > 0.0 )
    {
        // Filter raw data and remove entries with RSS amplitude that is too low
        std::pair< Eigen::MatrixXd, Eigen::MatrixXd > filteredData =
                filterRawDataForAmplitudes( fundamentalArgumentMultipliersRaw, amplitudesRaw, minimumAmplitude );
        amplitudes = filteredData.first;
        fundamentalArgumentMultipliers = filteredData.second;
    }
    // If all amplitudes are to be expected, raw data is same as return data.
    else
    {
        amplitudes = amplitudesRaw;
        fundamentalArgumentMultipliers = fundamentalArgumentMultipliersRaw;
    }

    // return amplitudes and fundamental argument multipliers.
    return std::pair< Eigen::MatrixXd, Eigen::MatrixXd >( amplitudes, fundamentalArgumentMultipliers );
}
Example #7
0
void RBMTestCase::inputGradient()
{
    OpenANN::OutputInfo info;
    info.dimensions.push_back(3);
    OpenANN::RBM layer(3, 2, 1, 0.01, 0.0, true);
    LayerAdapter opt(layer, info);

    Eigen::MatrixXd X = Eigen::MatrixXd::Random(2, 3);
    Eigen::MatrixXd Y = Eigen::MatrixXd::Random(2, 2);
    opt.trainingSet(X, Y);
    Eigen::MatrixXd gradient = opt.inputGradient();
    ASSERT_EQUALS(gradient.rows(), 2);
    Eigen::MatrixXd estimatedGradient = OpenANN::FiniteDifferences::
                                        inputGradient(X, Y, opt);
    ASSERT_EQUALS(estimatedGradient.rows(), 2);
    for(int j = 0; j < gradient.rows(); j++)
        for(int i = 0; i < gradient.cols(); i++)
            ASSERT_EQUALS_DELTA(gradient(j, i), estimatedGradient(j, i), 1e-10);
}
Example #8
0
//------------------------------------------------------------------------------
void LocalAssembler::assemble_exterior_facet(Eigen::MatrixXd& A,
        UFC& ufc,
        const std::vector<double>& vertex_coordinates,
        const ufc::cell& ufc_cell,
        const Cell& cell,
        const Facet& facet,
        const std::size_t local_facet,
        const MeshFunction<std::size_t>* domains)
{
    // Skip if there are no exterior facet integrals
    if (!ufc.form.has_exterior_facet_integrals())
        return;

    // Extract default exterior facet integral
    ufc::exterior_facet_integral* integral
        = ufc.default_exterior_facet_integral.get();

    // Get integral for sub domain (if any)
    if (domains && !domains->empty())
        integral = ufc.get_exterior_facet_integral((*domains)[facet]);

    // Skip integral if zero
    if (!integral)
        return;

    // Update to current cell
    ufc.update(cell, vertex_coordinates, ufc_cell,
               integral->enabled_coefficients());

    // Tabulate exterior facet tensor
    integral->tabulate_tensor(ufc.A.data(),
                              ufc.w(),
                              vertex_coordinates.data(),
                              local_facet,
                              ufc_cell.orientation);

    // Stuff a_ufc.A into A
    const std::size_t M = A.rows();
    const std::size_t N = A.cols();
    for (std::size_t i = 0; i < M; i++)
        for (std::size_t j = 0; j < N; j++)
            A(i, j) += ufc.A[N*i + j];
}
Example #9
0
void BranchList::smoothBranchPositions()
{
	for (int i = 0; i < mBranches.size(); i++)
	{
		Eigen::MatrixXd positions = mBranches[i]->getPositions();
		int numberOfInputPoints = positions.cols();
		int controlPointFactor = 5;
		int numberOfControlPoints = numberOfInputPoints / controlPointFactor;

		vtkCardinalSplinePtr splineX = vtkSmartPointer<vtkCardinalSpline>::New();
		vtkCardinalSplinePtr splineY = vtkSmartPointer<vtkCardinalSpline>::New();
		vtkCardinalSplinePtr splineZ = vtkSmartPointer<vtkCardinalSpline>::New();

		if (numberOfControlPoints >= 2)
		{
			//add control points to spline
			for(int j=0; j<numberOfControlPoints; j++)
			{
				int indexP = (j*numberOfInputPoints)/numberOfControlPoints;

				splineX->AddPoint(indexP,positions(0,indexP));
				splineY->AddPoint(indexP,positions(1,indexP));
				splineZ->AddPoint(indexP,positions(2,indexP));
			}
			//Always add the last point to complete spline
			splineX->AddPoint(numberOfInputPoints-1,positions(0,numberOfInputPoints-1));
			splineY->AddPoint(numberOfInputPoints-1,positions(1,numberOfInputPoints-1));
			splineZ->AddPoint(numberOfInputPoints-1,positions(2,numberOfInputPoints-1));

			//evaluate spline - get smoothed positions
			Eigen::MatrixXd smoothingResult(3 , numberOfInputPoints);
			for(int j=0; j<numberOfInputPoints; j++)
			{
				double splineParameter = j;
				smoothingResult(0,j) = splineX->Evaluate(splineParameter);
				smoothingResult(1,j) = splineY->Evaluate(splineParameter);
				smoothingResult(2,j) = splineZ->Evaluate(splineParameter);
			}
			mBranches[i]->setPositions(smoothingResult);
		}
	}
}
//! Initialize atmosphere table reader.
void TabulatedAtmosphere::initialize( const std::string& atmosphereTableFile )
{
    // Locally store the atmosphere table file name.
    atmosphereTableFile_ = atmosphereTableFile;

    Eigen::MatrixXd containerOfAtmosphereTableFileData
            = input_output::readMatrixFromFile( atmosphereTableFile_, " \t", "%" );

    // Check whether data is present in the file.
    if ( containerOfAtmosphereTableFileData.rows( ) < 1
         || containerOfAtmosphereTableFileData.cols( ) < 1 )
    {
        std::cerr << "The atmosphere table file is empty." << std::endl;
        std::cerr << atmosphereTableFile_ << std::endl;
    }

    // Initialize vectors.
    altitudeData_.resize( containerOfAtmosphereTableFileData.rows( ) );
    densityData_.resize( containerOfAtmosphereTableFileData.rows( ) );
    pressureData_.resize( containerOfAtmosphereTableFileData.rows( ) );
    temperatureData_.resize( containerOfAtmosphereTableFileData.rows( ) );

    // Loop through all the strings stored in the container and store the data
    // in the right Eigen::VectorXd.
    for ( int i = 0; i < containerOfAtmosphereTableFileData.rows( ); i++  )
    {
        altitudeData_[ i ] = containerOfAtmosphereTableFileData( i, 0 );
        densityData_[ i ] = containerOfAtmosphereTableFileData( i, 1 );
        pressureData_[ i ] = containerOfAtmosphereTableFileData( i, 2 );
        temperatureData_[ i ] = containerOfAtmosphereTableFileData( i, 3 );
    }

    using namespace interpolators;

    cubicSplineInterpolationForDensity_
            = boost::make_shared< CubicSplineInterpolatorDouble >( altitudeData_, densityData_ );
    cubicSplineInterpolationForPressure_
            = boost::make_shared< CubicSplineInterpolatorDouble >( altitudeData_, pressureData_ );
    cubicSplineInterpolationForTemperature_
            = boost::make_shared< CubicSplineInterpolatorDouble >(
                altitudeData_, temperatureData_ );
}
Example #11
0
bool pre_draw(igl::opengl::glfw::Viewer & viewer)
{
  using namespace Eigen;
  using namespace std;
  if(viewer.core.is_animating)
  {
    // Interpolate pose and identity
    RotationList anim_pose(pose.size());
    for(int e = 0;e<pose.size();e++)
    {
      anim_pose[e] = pose[e].slerp(anim_t,Quaterniond::Identity());
    }
    // Propagate relative rotations via FK to retrieve absolute transformations
    RotationList vQ;
    vector<Vector3d> vT;
    igl::forward_kinematics(C,BE,P,anim_pose,vQ,vT);
    const int dim = C.cols();
    MatrixXd T(BE.rows()*(dim+1),dim);
    for(int e = 0;e<BE.rows();e++)
    {
      Affine3d a = Affine3d::Identity();
      a.translate(vT[e]);
      a.rotate(vQ[e]);
      T.block(e*(dim+1),0,dim+1,dim) =
        a.matrix().transpose().block(0,0,dim+1,dim);
    }
    // Compute deformation via LBS as matrix multiplication
    U = M*T;

    // Also deform skeleton edges
    MatrixXd CT;
    MatrixXi BET;
    igl::deform_skeleton(C,BE,T,CT,BET);

    viewer.data().set_vertices(U);
    viewer.data().set_edges(CT,BET,sea_green);
    viewer.data().compute_normals();
    anim_t += anim_t_dir;
    anim_t_dir *= (anim_t>=1.0 || anim_t<=0.0?-1.0:1.0);
  }
  return false;
}
Example #12
0
IGL_INLINE void igl::ViewerData::add_points(const Eigen::MatrixXd& P,  const Eigen::MatrixXd& C)
{
  Eigen::MatrixXd P_temp;

  // If P only has two columns, pad with a column of zeros
  if (P.cols() == 2)
  {
    P_temp = Eigen::MatrixXd::Zero(P.rows(),3);
    P_temp.block(0,0,P.rows(),2) = P;
  }
  else
    P_temp = P;

  int lastid = points.rows();
  points.conservativeResize(points.rows() + P_temp.rows(),6);
  for (unsigned i=0; i<P_temp.rows(); ++i)
    points.row(lastid+i) << P_temp.row(i), i<C.rows() ? C.row(i) : C.row(C.rows()-1);

  dirty |= DIRTY_OVERLAY_POINTS;
}
Example #13
0
// Trying to assign from matrix to noOfPoints
void mitk::LibSVMClassifier::ReadXValues(LibSVM::svm_problem * problem, LibSVM::svm_node** xSpace, const Eigen::MatrixXd &X)
{
  auto noOfPoints = static_cast<int>(X.rows());
  auto features = static_cast<int>(X.cols());

  problem->x = static_cast<LibSVM::svm_node **>(malloc(sizeof(LibSVM::svm_node *)  * noOfPoints));
  (*xSpace) = static_cast<LibSVM::svm_node *> (malloc(sizeof(LibSVM::svm_node) * noOfPoints * (features+1)));

  for (int row = 0; row < noOfPoints; ++row)
  {
    for (int col = 0; col < features; ++col)
    {
      (*xSpace)[row*features + col].index = col;
      (*xSpace)[row*features + col].value = X(row,col);
    }
    (*xSpace)[row*features + features].index = -1;

    problem->x[row] = &((*xSpace)[row*features]);
  }
}
Example #14
0
bool init_weights(
  const Eigen::MatrixXd & V,
  const Eigen::MatrixXi & F,
  const Eigen::MatrixXd & C,
  const Eigen::MatrixXi & BE,
  Eigen::MatrixXd & W)
{
  using namespace igl;
  using namespace Eigen;
  // Mesh with samples on skeleton
  // New vertices of tet mesh, V prefaces VV
  MatrixXd VV;
  MatrixXi TT,FF,CE;
  VectorXi P;
  if(!mesh_with_skeleton(V,F,C,P,BE,CE,10,VV,TT,FF))
  {
    return false;
  }
  // List of boundary indices (aka fixed value indices into VV)
  VectorXi b;
  // List of boundary conditions of each weight function
  MatrixXd bc;
  if(!boundary_conditions(VV,TT,C,P,BE,CE,b,bc))
  {
    return false;
  }

  // compute BBW
  // Default bbw data and flags
  BBWData bbw_data;
  bbw_data.active_set_params.max_iter = 4;
  // Weights matrix
  if(!bbw(VV,TT,b,bc,bbw_data,W))
  {
    return false;
  }
  // Normalize weights to sum to one
  normalize_row_sums(W,W);
  W.conservativeResize(V.rows(),W.cols());
  return true;
}
Example #15
0
double accuracy( const Eigen::MatrixXd& X, const Eigen::VectorXd& y, const Eigen::VectorXd& theta ) {
  const unsigned N = X.rows(), K = X.cols();
  // Eigen:::VectorXd p;
  // p.resize(N, 0); p.setZero();

  double correct = 0.0;
  Eigen::VectorXd xtheta = X*theta;
  Eigen::VectorXd predicted;
  maths::Sigmoid()( predicted, xtheta );

      
  std::cout << predicted << std::endl;
  for ( size_t i = 0; i < N; ++i ) {
    int p = predicted[i]> 0.5 ? 1 : 0;
    // printf("%d, %d, %f\n", )
    if ( p == y(i,0) ) ++correct;
  }

  return correct / N;
  
}
Example #16
0
void setMatrix(PETScMatrix& m, Eigen::MatrixXd const& tmp)
{
    using IndexType = PETScMatrix::IndexType;

    auto const rows = tmp.rows();
    auto const cols = tmp.cols();

    assert(rows == m.getNumberOfRows() && cols == m.getNumberOfColumns());

    m.setZero();
    std::vector<IndexType> row_idcs(rows);
    std::vector<IndexType> col_idcs(cols);

    std::iota(row_idcs.begin(), row_idcs.end(), 0);
    std::iota(col_idcs.begin(), col_idcs.end(), 0);

    // PETSc wants row-major
    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> tmp_ = tmp;

    m.add(row_idcs, col_idcs, tmp_);
}
Example #17
0
double computePlaneToPlaneHomographyError(
		const Eigen::MatrixXd &points1,
		const Eigen::MatrixXd &points2,
		const Eigen::MatrixXd &H,
		Eigen::VectorXd &error
	)
{
	double sum = 0;
	unsigned int nPoints = points1.cols();
	error.resize( nPoints );

	for( unsigned int i = 0; i < nPoints; i++ )
	{
		Eigen::Vector3d p1 = H * points1.col(i).homogeneous();
		Eigen::Vector3d p2 = points2.col(i).homogeneous();
		p1 /= p1[2];
		double err = (p1 - p2).norm();
		sum += error[i] = err * err;
	}
	return sum / double( nPoints );
}
Example #18
0
void PCATestCase::dimensionalityReduction()
{
  OpenANN::RandomNumberGenerator rng;
  const int N = 100;
  const int D = 5;
  Eigen::MatrixXd X(N, D);
  rng.fillNormalDistribution(X);

  // Strong correlation
  Eigen::MatrixXd A = Eigen::MatrixXd::Identity(D, D) * 0.5 +
      Eigen::MatrixXd::Ones(D, D);
  Eigen::MatrixXd Xt = X * A.transpose();
  // Dimensionality reduction
  OpenANN::PCA pca(1);
  pca.fit(Xt);
  Eigen::MatrixXd Y = pca.transform(Xt);
  ASSERT_EQUALS(Y.rows(), N);
  ASSERT_EQUALS(Y.cols(), 1);
  ASSERT_EQUALS(pca.explainedVarianceRatio().rows(), 1);
  ASSERT(pca.explainedVarianceRatio().sum() > 0.9);
}
Example #19
0
//==============================================================================
Eigen::VectorXd Spline::evaluatePolynomial(
    const Eigen::MatrixXd& _coefficients, double _t, int _derivative)
{
  const auto numOutputs = _coefficients.rows();
  const auto numCoeffs = _coefficients.cols();

  const auto timeVector
      = common::SplineProblem<>::createTimeVector(_t, _derivative, numCoeffs);
  const auto derivativeMatrix
      = common::SplineProblem<>::createCoefficientMatrix(numCoeffs);
  const auto derivativeVector = derivativeMatrix.row(_derivative);
  const auto evaluationVector
      = derivativeVector.cwiseProduct(timeVector.transpose());

  Eigen::VectorXd outputVector(numOutputs);

  for (int ioutput = 0; ioutput < numOutputs; ++ioutput)
    outputVector[ioutput] = _coefficients.row(ioutput).dot(evaluationVector);

  return outputVector;
}
Example #20
0
Eigen::VectorXd BicZ_j_cpp(Eigen::MatrixXd X,Eigen::MatrixXd Z,Eigen::VectorXd Bic_vide_vect,Eigen::VectorXd BicOld,double methode,int j)
{
  int size=X.cols();
  int sizerow = X.rows();
  Eigen::VectorXd BicRes(size);
  Eigen::MatrixXd mat_var_a_droite;
  int k;
  //debut de la boucle colonne de Z
  BicRes=BicOld;
   
  //colonne de Z sur laquelle on va travailler (variable a gauche)
  Eigen::VectorXd colZ=Z.block(0,j,size,1);
  int newsize=colZ.sum(); 
  //si la somme de la colonne=0 alors on appelle mixmod
  if(newsize==0)
  {
    BicRes(j)=Bic_vide_vect(j);
  }
  else
  {
    //calcul du nouveau BIC    
    
    mat_var_a_droite.resize(sizerow,newsize);
    k=0;
    //on echerche l'emplacement des 1 dans le vecteur colonne (variables a droite)
    for(int p=0;p<size;p++)
    {
      if (colZ(p)==1)
      {
        //on regroupe les variables a droite dans une matrice
        mat_var_a_droite.block(0,k,sizerow,1)=X.block(0,p,sizerow,1);
        k=k+1;
      }//fin if
    }//fin for j
        //calcul de son BIC en appellant OLS (les parametres sont : Y=X[,colonne],X=X[,matrice des variables à droite])
       BicRes(j)=BicLoc_cpp(mat_var_a_droite,X.block(0,j,sizerow,1),"T",methode);
  }//fin else
    return BicRes;
    
}
Example #21
0
// Helpers that draws the most common meshes
IGL_INLINE void igl::ViewerData::set_mesh(const Eigen::MatrixXd& _V, const Eigen::MatrixXi& _F)
{
  using namespace std;

  Eigen::MatrixXd V_temp;

  // If V only has two columns, pad with a column of zeros
  if (_V.cols() == 2)
  {
    V_temp = Eigen::MatrixXd::Zero(_V.rows(),3);
    V_temp.block(0,0,_V.rows(),2) = _V;
  }
  else
    V_temp = _V;

  if (V.rows() == 0 && F.rows() == 0)
  {
    clear();
    V = V_temp;
    F = _F;

    compute_normals();
    uniform_colors(Eigen::Vector3d(51.0/255.0,43.0/255.0,33.3/255.0),
                   Eigen::Vector3d(255.0/255.0,228.0/255.0,58.0/255.0),
                   Eigen::Vector3d(255.0/255.0,235.0/255.0,80.0/255.0));

    grid_texture();
  }
  else
  {
    if (_V.rows() == V.rows() && _F.rows() == F.rows())
    {
      V = V_temp;
      F = _F;
    }
    else
      cerr << "ERROR (set_mesh): The new mesh has a different number of vertices/faces. Please clear the mesh before plotting.";
  }
  dirty |= DIRTY_FACE | DIRTY_POSITION;
}
Example #22
0
void ODELCPSolver::transferToODEFormulation(const Eigen::MatrixXd& _A,
                                         const Eigen::VectorXd& _b,
                                         Eigen::MatrixXd* _AOut,
                                         Eigen::VectorXd* _bOut,
                                         int _numDir,
                                         int _numContacts) {
  int numOtherConstrs = _A.rows() - _numContacts * (2 + _numDir);
  int n = _numContacts * 3 + numOtherConstrs;
  Eigen::MatrixXd AIntermediate = Eigen::MatrixXd::Zero(n, _A.cols());
  *_AOut = Eigen::MatrixXd::Zero(n, n);
  *_bOut = Eigen::VectorXd::Zero(n);
  int offset = _numDir / 4;
  for (int i = 0; i < _numContacts; ++i) {
    AIntermediate.row(i) = _A.row(i);
    (*_bOut)[i] = _b[i];

    AIntermediate.row(_numContacts + i * 2 + 0) =
        _A.row(_numContacts + i * _numDir + 0);
    AIntermediate.row(_numContacts + i * 2 + 1) =
        _A.row(_numContacts + i * _numDir + offset);
    (*_bOut)[_numContacts + i * 2 + 0] = _b[_numContacts + i * _numDir + 0];
    (*_bOut)[_numContacts + i * 2 + 1] = _b[_numContacts + i * _numDir
                                            + offset];
  }
  for (int i = 0; i < numOtherConstrs; i++) {
    AIntermediate.row(_numContacts * 3 + i) =
        _A.row(_numContacts * (_numDir + 2) + i);
    (*_bOut)[_numContacts * 3 + i] = _b[_numContacts * (_numDir + 2) + i];
  }
  for (int i = 0; i < _numContacts; ++i) {
    _AOut->col(i) = AIntermediate.col(i);
    _AOut->col(_numContacts + i * 2 + 0) =
        AIntermediate.col(_numContacts + i * _numDir + 0);
    _AOut->col(_numContacts + i * 2 + 1) =
        AIntermediate.col(_numContacts + i * _numDir + offset);
  }
  for (int i = 0; i < numOtherConstrs; i++)
    _AOut->col(_numContacts * 3 + i) =
        AIntermediate.col(_numContacts * (_numDir + 2) + i);
}
Example #23
0
void evaluateSVDSPQRSolver(const Eigen::MatrixXd& A, const Eigen::VectorXd& b,
    const Eigen::VectorXd& x, double tol = 1e-9) {
  cholmod_common cholmod;
  cholmod_l_start(&cholmod);
  cholmod_sparse* A_CS = aslam::calibration::eigenDenseToCholmodSparseCopy(A,
    &cholmod);
  cholmod_dense b_CD;
  aslam::calibration::eigenDenseToCholmodDenseView(b, &b_CD);
  Eigen::VectorXd x_est;
  aslam::calibration::LinearSolver linearSolver;
  for (std::ptrdiff_t i = 1; i < A.cols(); ++i) {
//    double before = aslam::calibration::Timestamp::now();
    linearSolver.solve(A_CS, &b_CD, i, x_est);
//    double after = aslam::calibration::Timestamp::now();
    double error = (b - A * x_est).norm();
//    std::cout << std::fixed << std::setprecision(18) << "noscale: " << "error: "
//      << error << " est_diff: " << (x - x_est).norm() << " time: "
//      << after - before << std::endl;
    ASSERT_NEAR(error, 0, tol);
    linearSolver.getOptions().columnScaling = true;
//    before = aslam::calibration::Timestamp::now();
    linearSolver.solve(A_CS, &b_CD, i, x_est);
//    after = aslam::calibration::Timestamp::now();
    error = (b - A * x_est).norm();
//    std::cout << std::fixed << std::setprecision(18) << "onscale: " << "error: "
//      << error << " est_diff: " << (x - x_est).norm() << " time: "
//      << after - before << std::endl;
    linearSolver.getOptions().columnScaling = false;
    ASSERT_NEAR(error, 0, tol);
//    std::cout << "SVD rank: " << linearSolver.getSVDRank() << std::endl;
//    std::cout << "SVD rank deficiency: " << linearSolver.getSVDRankDeficiency()
//      << std::endl;
//    std::cout << "QR rank: " << linearSolver.getQRRank() << std::endl;
//    std::cout << "QR rank deficiency: "
//      << linearSolver.getQRRankDeficiency() << std::endl;
//    std::cout << "SV gap: " << linearSolver.getSvGap() << std::endl;
  }
  cholmod_l_free_sparse(&A_CS, &cholmod);
  cholmod_l_finish(&cholmod);
}
Example #24
0
Evrot::Evrot(Eigen::MatrixXd& X, int method):
	mMethod(method),
	mNumDims(X.cols()),
	mNumData(X.rows()),
	mNumAngles((int)(mNumDims*(mNumDims-1)/2)), // get the number of angles
	ik(Eigen::VectorXi(mNumAngles)),
	jk(Eigen::VectorXi(mNumAngles)),
	mX(X),
	mClusters(std::vector<std::vector<int> >(mNumDims)) //allocate clusters vector
{
	// build index mapping (to index upper triangle)
	int k = 0;
	for( int i=0; i<mNumDims-1; i++ ){
		for( int j=i+1; j<=mNumDims-1; j++ ){
			ik[k] = i;
			jk[k] = j;
			k++;
		}
	}

	evrot();
}
Example #25
0
IGL_INLINE void igl::ViewerData::set_edges(
  const Eigen::MatrixXd& P,
  const Eigen::MatrixXi& E,
  const Eigen::MatrixXd& C)
{
  using namespace Eigen;
  lines.resize(E.rows(),9);
  assert(C.cols() == 3);
  for(int e = 0;e<E.rows();e++)
  {
    RowVector3d color;
    if(C.size() == 3)
    {
      color<<C;
    }else if(C.rows() == E.rows())
    {
      color<<C.row(e);
    }
    lines.row(e)<< P.row(E(e,0)), P.row(E(e,1)), color;
  }
  dirty |= DIRTY_OVERLAY_LINES;
}
Example #26
0
std::tuple<Eigen::MatrixXd, Eigen::MatrixXd> 
    lu_no_pivoting(const Eigen::MatrixXd & A)
{
    Eigen::MatrixXd Acopy = A;
    int n = Acopy.rows();
    assert(n == Acopy.cols());

    Eigen::MatrixXd L(n,n);
    Eigen::MatrixXd U(n,n);

    L.triangularView<Eigen::StrictlyUpper>().setZero();
    U.triangularView<Eigen::StrictlyLower>().setZero();

    for (int k=0; k<n-1; k++) {
        lu_helper(k, n, &Acopy, &L, &U);
    }

    L(n-1,n-1) = 1;
    U(n-1,n-1) = Acopy(n-1,n-1);

    return std::make_tuple(L,U);
}
Example #27
0
void MassRegistration::show(std::vector<Eigen::MatrixXd> Xv, bool save, std::string filename, bool stop){
	viewer->removeAllPointClouds();

	srand(0);
    for(unsigned int xi = 0; xi < Xv.size(); xi++){
		Eigen::MatrixXd X = Xv[xi];
		pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGBNormal>);
		int r = 256*(1+(rand()%4))/4 - 1;//255*((xi+1) & 1);
		int g = 256*(1+(rand()%4))/4 - 1;//255*((xi+1) & 1);
		int b = 256*(1+(rand()%4))/4 - 1;//255*(xi & 1);

		unsigned int nr_data = X.cols();
		cloud->points.clear();
		for(unsigned int i = 0; i < nr_data; i++){
			pcl::PointXYZRGBNormal p;
			p.x = X(0,i);
			p.y = X(1,i);
			p.z = X(2,i);
			p.b = r;
			p.g = g;
			p.r = b;
			cloud->points.push_back(p);
		}
		char buf [1024];
		sprintf(buf,"cloud%i",xi);
		viewer->addPointCloud<pcl::PointXYZRGBNormal> (cloud, pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGBNormal>(cloud), buf);
	}
	if(!save){
		viewer->spin();
	}else{
		viewer->spinOnce();
	}
	//void pcl::visualization::PCLVisualizerInteractorStyle::saveScreenshot	(	const std::string & 	file	)
	if(save){
		printf("saving: %s\n",filename.c_str());
		viewer->saveScreenshot(filename);
	}
	viewer->removeAllPointClouds();
}
Example #28
0
Balloon::Balloon(double r, double dt, Eigen::MatrixXd positions, Eigen::MatrixXi faces)
    :
    ParticleObject(r)
{
    m_radius = r;
    m_step = dt;
    m_positions = positions;
    m_speeds = Eigen::MatrixXd::Zero(positions.rows(), positions.cols());
    m_forces = Eigen::MatrixXd::Zero(m_positions.rows(), m_positions.cols());
    m_num_point = m_positions.rows();
    m_mass = m_mass_all / (double)m_num_point;
    c = 2.0*sqrt(m_mass*k)/3.0;
    m_faces = faces;
    m_faceactive = Eigen::VectorXi::Zero(m_faces.rows());
    for(int i=0; i<m_faceactive.rows(); i++)
    {
        m_faceactive(i) = 1;
    }
    igl::adjacency_list(m_faces, m_adjacency_list);
    igl::triangle_triangle_adjacency(m_positions, m_faces, m_facetoface);

    std::vector<std::vector<int>> tmp_list;
    igl::vertex_triangle_adjacency(m_positions, m_faces, m_vertextoface, tmp_list);
    initEdges();
    computeNormals();


    calcAveRadius();

    m_threshold_ratio = Eigen::VectorXd::Ones(m_edges.rows()) * threshold_ratio;

    // for(int i=0; i<m_positions.rows(); i++){
    //   // std::cout << "adjacent to " << i << ": " << m_adjacency_list[i].size() << std::endl;
    // }
    // for(int i=0; i<m_positions.rows(); i++){
    //   // std::cout << "normal " << i << ": " << m_normals.norm() << std::endl;
    // }
}
Example #29
0
QPair<Eigen::MatrixXd, QList<int> > Epidetect::prepareData(Eigen::MatrixXd mat)
{
    MatrixXd trimmedMatrix;
    QList<int> stimLocations;
    QStringList badChs = m_pFiffInfo->bads;
    QStringList chNames = m_pFiffInfo->ch_names;
    trimmedMatrix.resize(mat.rows()- badChs.size(), mat.cols());

    int j = 0;

    for (int i=0 ; i < mat.rows(); i++)
    {
        QString type = m_pFiffInfo->channel_type(i);

        if (type == "stim")
            stimLocations << i;
        if (!(badChs.contains(chNames[i])))
        {
            if ((type != "stim") && (type != "ecg") && (type != "eeg"))
            {
                trimmedMatrix.row(j) = mat.row(i);
                j++;

            }
        }

    }

    qSort(stimLocations);

    trimmedMatrix.conservativeResize(j,trimmedMatrix.cols());
    QPair<MatrixXd, QList<int> > out;
    out.first = trimmedMatrix;
    out.second = stimLocations;

    return out;

}
Example #30
0
//==============================================================================
void Spline::addSegment(
    const Eigen::MatrixXd& _coefficients,
    double _duration,
    const statespace::StateSpace::State* _startState)
{
  if (_duration <= 0.)
    throw std::invalid_argument("Duration must be positive.");

  if (static_cast<std::size_t>(_coefficients.rows())
      != mStateSpace->getDimension())
    throw std::invalid_argument("Incorrect number of dimensions.");

  if (_coefficients.cols() < 1)
    throw std::invalid_argument("At least one coefficient is required.");

  PolynomialSegment segment;
  segment.mCoefficients = _coefficients;
  segment.mDuration = _duration;
  segment.mStartState = mStateSpace->allocateState();
  mStateSpace->copyState(_startState, segment.mStartState);

  mSegments.emplace_back(std::move(segment));
}