void ParallelFor(const VectorType& items, const FuncType& func) { using SizeType = decltype(items.size()); SizeType totalCount = items.size(); auto lock = AcquireLock(); SizeType offset = 0; for (int i = 0; i < m_ThreadCount; i++) { SizeType count = totalCount / static_cast<SizeType>(m_ThreadCount); if (static_cast<SizeType>(i) < totalCount % static_cast<SizeType>(m_ThreadCount)) count++; EnqueueUnlocked(lock, [&items, func, offset, count, this]() { for (SizeType j = offset; j < offset + count; j++) { RunTaskFunction([&func, &items, j]() { func(items[j]); }); } }); offset += count; } ASSERT(offset == items.size()); }
VectorType model(const VectorType& uv, VectorType& x) { VectorType y; //Change this to use expression template int m = Base::values(); int n = Base::inputs(); eigen_assert(uv.size()%2 == 0); eigen_assert(uv.size() == n); eigen_assert(x.size() == m); y.setZero(m); int half = n/2; VectorBlock<const VectorType> u(uv, 0, half); VectorBlock<const VectorType> v(uv, half, half); Scalar coeff; for (int j = 0; j < m; j++) { for (int i = 0; i < half; i++) { coeff = (x(j)-i)/v(i); coeff *= coeff; if (coeff < 1. && coeff > 0.) y(j) += u(i)*std::pow((1-coeff), 2); } } return y; }
/// Gather the RHS and initial estimate vectors void p_serialSolvePrep(const VectorType& b, VectorType& x) const { // make a buffer for value transfer between vectors if (p_valueBuffer.empty()) { p_valueBuffer.resize(b.size()); } // always collect the RHS vector if (!p_serialRHS) { p_serialRHS.reset(b.localClone()); } else { b.getAllElements(&p_valueBuffer[0]); p_serialRHS->setElementRange(0, b.size() - 1, &p_valueBuffer[0]); } // Collect the initial guess, if it's not zero if (!p_serialSolution) { if (!p_guessZero) { p_serialSolution.reset(x.localClone()); } else { p_serialSolution.reset(p_serialRHS->clone()); } } else { if (!p_guessZero) { x.getAllElements(&p_valueBuffer[0]); p_serialSolution->setElementRange(0, x.size() - 1, &p_valueBuffer[0]); } } }
numeric_type operator()(VectorType const & v) const { if(id_ >= v.size()) throw variable_index_out_of_bounds_exception(id_, v.size()); return get_from_vector(v, id_); }
void householder_vector(VectorType & v, vcl_size_t start) { typedef typename VectorType::value_type ScalarType; ScalarType x_norm = norm_lcl(v, v.size()); ScalarType alpha = -sign(v[start]) * x_norm; v[start] += alpha; normalize(v, v.size()); }
void apply(VectorType & vec) const { assert(vec.size() == diag_A_inv.size()); for (size_t i=0; i<vec.size(); ++i) { vec[i] *= diag_A_inv[i]; } }
numeric_type operator()(VectorType const & v) const { std::vector<double> stl_v(v.size()); for (std::size_t i=0; i<v.size(); ++i) stl_v[i] = v[i]; return this->eval(stl_v); }
Selector selectUnion( const VectorType & union_vector ) { Selector selector; if (union_vector.size() > 0) { selector = dereference_if_pointer(union_vector[0]); for (unsigned i = 1 ; i < union_vector.size() ; ++i) { selector |= dereference_if_pointer(union_vector[i]); } } return selector; }
void copy(const VectorType & cpu_vector, vector_slice<vector<SCALARTYPE> > & gpu_vector_slice ) { if (cpu_vector.size() > 0) { std::vector<SCALARTYPE> temp_buffer(gpu_vector_slice.stride() * gpu_vector_slice.size()); viennacl::backend::memory_read(gpu_vector_slice.handle(), sizeof(SCALARTYPE)*gpu_vector_slice.start(), sizeof(SCALARTYPE)*temp_buffer.size(), &(temp_buffer[0])); for (vcl_size_t i=0; i<cpu_vector.size(); ++i) temp_buffer[i * gpu_vector_slice.stride()] = cpu_vector[i]; viennacl::backend::memory_write(gpu_vector_slice.handle(), sizeof(SCALARTYPE)*gpu_vector_slice.start(), sizeof(SCALARTYPE)*temp_buffer.size(), &(temp_buffer[0])); } }
template<typename VectorType> void map_static_methods(const VectorType& m) { typedef typename VectorType::Index Index; typedef typename VectorType::Scalar Scalar; Index size = m.size(); Scalar* array1 = internal::aligned_new<Scalar>(size); Scalar* array2 = internal::aligned_new<Scalar>(size); Scalar* array3 = new Scalar[size+1]; Scalar* array3unaligned = internal::UIntPtr(array3)%EIGEN_MAX_ALIGN_BYTES == 0 ? array3+1 : array3; VectorType::MapAligned(array1, size) = VectorType::Random(size); VectorType::Map(array2, size) = VectorType::Map(array1, size); VectorType::Map(array3unaligned, size) = VectorType::Map(array1, size); VectorType ma1 = VectorType::Map(array1, size); VectorType ma2 = VectorType::MapAligned(array2, size); VectorType ma3 = VectorType::Map(array3unaligned, size); VERIFY_IS_EQUAL(ma1, ma2); VERIFY_IS_EQUAL(ma1, ma3); internal::aligned_delete(array1, size); internal::aligned_delete(array2, size); delete[] array3; }
void DiscretePolicyManager::UpdateCallback( const ros::TimerEvent& event ) { StampedFeatures inputs; if( !_inputStreams.ReadStream( event.current_real, inputs ) ) { ROS_WARN_STREAM( "Could not read input stream." ); return; } // Generate probability mass function values _networkInput.SetOutput( inputs.features ); _networkInput.Invalidate(); _networkInput.Foreprop(); VectorType pmf = _network->GetProbabilitySource().GetOutput(); // Sample from PMF std::vector<double> weights( pmf.data(), pmf.data() + pmf.size() ); std::vector<unsigned int> draws; NaiveWeightedSample( weights, 1, draws, _engine ); unsigned int actionIndex = draws[0]; // Convert single index into multiple indices std::vector<unsigned int> indices; indices = multibase_long_div( actionIndex, _interface->GetOutputSizes() ); _interface->SetOutput( indices ); // TODO name policy DiscreteParamAction action( event.current_real, inputs.features, actionIndex ); _actionPub.publish( action.ToMsg() ); }
template<typename VectorType> void vectorSum(const VectorType& w) { typedef typename VectorType::Scalar Scalar; int size = w.size(); VectorType v = VectorType::Random(size); for(int i = 1; i < size; i++) { Scalar s = Scalar(0); for(int j = 0; j < i; j++) s += v[j]; VERIFY_IS_APPROX(s, v.start(i).sum()); } for(int i = 0; i < size-1; i++) { Scalar s = Scalar(0); for(int j = i; j < size; j++) s += v[j]; VERIFY_IS_APPROX(s, v.end(size-i).sum()); } for(int i = 0; i < size/2; i++) { Scalar s = Scalar(0); for(int j = i; j < size-i; j++) s += v[j]; VERIFY_IS_APPROX(s, v.segment(i, size-2*i).sum()); } }
template<typename VectorType> void map_class_vector(const VectorType& m) { typedef typename VectorType::Scalar Scalar; int size = m.size(); // test Map.h Scalar* array1 = ei_aligned_new<Scalar>(size); Scalar* array2 = ei_aligned_new<Scalar>(size); Scalar* array3 = new Scalar[size+1]; Scalar* array3unaligned = std::size_t(array3)%16 == 0 ? array3+1 : array3; Map<VectorType, Aligned>(array1, size) = VectorType::Random(size); Map<VectorType>(array2, size) = Map<VectorType>(array1, size); Map<VectorType>(array3unaligned, size) = Map<VectorType>((const Scalar*)array1, size); // test non-const-correctness support in eigen2 VectorType ma1 = Map<VectorType>(array1, size); VectorType ma2 = Map<VectorType, Aligned>(array2, size); VectorType ma3 = Map<VectorType>(array3unaligned, size); VERIFY_IS_APPROX(ma1, ma2); VERIFY_IS_APPROX(ma1, ma3); ei_aligned_delete(array1, size); ei_aligned_delete(array2, size); delete[] array3; }
// Constant vector tests. TEST_F(SmallVectorTest, ConstVectorTest) { const VectorType constVector; EXPECT_EQ(0u, constVector.size()); EXPECT_TRUE(constVector.empty()); EXPECT_TRUE(constVector.begin() == constVector.end()); }
template<typename VectorType> void map_static_methods(const VectorType& m) { typedef typename VectorType::Scalar Scalar; int size = m.size(); // test Map.h Scalar* array1 = ei_aligned_new<Scalar>(size); Scalar* array2 = ei_aligned_new<Scalar>(size); Scalar* array3 = new Scalar[size+1]; Scalar* array3unaligned = std::size_t(array3)%16 == 0 ? array3+1 : array3; VectorType::MapAligned(array1, size) = VectorType::Random(size); VectorType::Map(array2, size) = VectorType::Map(array1, size); VectorType::Map(array3unaligned, size) = VectorType::Map(array1, size); VectorType ma1 = VectorType::Map(array1, size); VectorType ma2 = VectorType::MapAligned(array2, size); VectorType ma3 = VectorType::Map(array3unaligned, size); VERIFY_IS_APPROX(ma1, ma2); VERIFY_IS_APPROX(ma1, ma3); ei_aligned_delete(array1, size); ei_aligned_delete(array2, size); delete[] array3; }
template<typename MatrixType> void generalized_eigensolver_real(const MatrixType& m) { typedef typename MatrixType::Index Index; /* this test covers the following files: GeneralizedEigenSolver.h */ Index rows = m.rows(); Index cols = m.cols(); typedef typename MatrixType::Scalar Scalar; typedef typename NumTraits<Scalar>::Real RealScalar; typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType; typedef Matrix<RealScalar, MatrixType::RowsAtCompileTime, 1> RealVectorType; typedef typename std::complex<typename NumTraits<typename MatrixType::Scalar>::Real> Complex; MatrixType a = MatrixType::Random(rows,cols); MatrixType b = MatrixType::Random(rows,cols); MatrixType a1 = MatrixType::Random(rows,cols); MatrixType b1 = MatrixType::Random(rows,cols); MatrixType spdA = a.adjoint() * a + a1.adjoint() * a1; MatrixType spdB = b.adjoint() * b + b1.adjoint() * b1; // lets compare to GeneralizedSelfAdjointEigenSolver GeneralizedSelfAdjointEigenSolver<MatrixType> symmEig(spdA, spdB); GeneralizedEigenSolver<MatrixType> eig(spdA, spdB); VERIFY_IS_EQUAL(eig.eigenvalues().imag().cwiseAbs().maxCoeff(), 0); VectorType realEigenvalues = eig.eigenvalues().real(); std::sort(realEigenvalues.data(), realEigenvalues.data()+realEigenvalues.size()); VERIFY_IS_APPROX(realEigenvalues, symmEig.eigenvalues()); }
template<typename VectorType> void map_class_vector(const VectorType& m) { typedef typename VectorType::Index Index; typedef typename VectorType::Scalar Scalar; Index size = m.size(); Scalar* array1 = internal::aligned_new<Scalar>(size); Scalar* array2 = internal::aligned_new<Scalar>(size); Scalar* array3 = new Scalar[size+1]; Scalar* array3unaligned = (internal::UIntPtr(array3)%EIGEN_MAX_ALIGN_BYTES) == 0 ? array3+1 : array3; Scalar array4[EIGEN_TESTMAP_MAX_SIZE]; Map<VectorType, AlignedMax>(array1, size) = VectorType::Random(size); Map<VectorType, AlignedMax>(array2, size) = Map<VectorType,AlignedMax>(array1, size); Map<VectorType>(array3unaligned, size) = Map<VectorType>(array1, size); Map<VectorType>(array4, size) = Map<VectorType,AlignedMax>(array1, size); VectorType ma1 = Map<VectorType, AlignedMax>(array1, size); VectorType ma2 = Map<VectorType, AlignedMax>(array2, size); VectorType ma3 = Map<VectorType>(array3unaligned, size); VectorType ma4 = Map<VectorType>(array4, size); VERIFY_IS_EQUAL(ma1, ma2); VERIFY_IS_EQUAL(ma1, ma3); VERIFY_IS_EQUAL(ma1, ma4); #ifdef EIGEN_VECTORIZE if(internal::packet_traits<Scalar>::Vectorizable && size>=AlignedMax) VERIFY_RAISES_ASSERT((Map<VectorType,AlignedMax>(array3unaligned, size))) #endif internal::aligned_delete(array1, size); internal::aligned_delete(array2, size); delete[] array3; }
template<typename VectorType> void ref_vector(const VectorType& m) { typedef typename VectorType::Index Index; typedef typename VectorType::Scalar Scalar; typedef typename VectorType::RealScalar RealScalar; typedef Matrix<Scalar,Dynamic,1,VectorType::Options> DynMatrixType; typedef Matrix<Scalar,Dynamic,Dynamic,ColMajor> MatrixType; typedef Matrix<RealScalar,Dynamic,1,VectorType::Options> RealDynMatrixType; typedef Ref<VectorType> RefMat; typedef Ref<DynMatrixType> RefDynMat; typedef Ref<const DynMatrixType> ConstRefDynMat; typedef Ref<RealDynMatrixType , 0, InnerStride<> > RefRealMatWithStride; typedef Ref<DynMatrixType , 0, InnerStride<> > RefMatWithStride; Index size = m.size(); VectorType v1 = VectorType::Random(size), v2 = v1; MatrixType mat1 = MatrixType::Random(size,size), mat2 = mat1, mat3 = MatrixType::Random(size,size); Index i = internal::random<Index>(0,size-1); Index bsize = internal::random<Index>(1,size-i); RefMat rm0 = v1; VERIFY_IS_EQUAL(rm0, v1); RefDynMat rv1 = v1; VERIFY_IS_EQUAL(rv1, v1); RefDynMat rv2 = v1.segment(i,bsize); VERIFY_IS_EQUAL(rv2, v1.segment(i,bsize)); rv2.setOnes(); v2.segment(i,bsize).setOnes(); VERIFY_IS_EQUAL(v1, v2); v2.segment(i,bsize).setRandom(); rv2 = v2.segment(i,bsize); VERIFY_IS_EQUAL(v1, v2); ConstRefDynMat rm3 = v1.segment(i,bsize); v1.segment(i,bsize) *= 2; v2.segment(i,bsize) *= 2; VERIFY_IS_EQUAL(rm3, v2.segment(i,bsize)); RefRealMatWithStride rm4 = v1.real(); VERIFY_IS_EQUAL(rm4, v2.real()); rm4.array() += 1; v2.real().array() += 1; VERIFY_IS_EQUAL(v1, v2); RefMatWithStride rm5 = mat1.row(i).transpose(); VERIFY_IS_EQUAL(rm5, mat1.row(i).transpose()); rm5.array() += 1; mat2.row(i).array() += 1; VERIFY_IS_EQUAL(mat1, mat2); rm5.noalias() = rm4.transpose() * mat3; mat2.row(i) = v2.real().transpose() * mat3; VERIFY_IS_APPROX(mat1, mat2); }
//************************************************************************************ //************************************************************************************ void ThermalFace2D::CalculateAll(MatrixType& rLeftHandSideMatrix, VectorType& rRightHandSideVector, ProcessInfo& rCurrentProcessInfo, bool CalculateStiffnessMatrixFlag, bool CalculateResidualVectorFlag) { KRATOS_TRY unsigned int number_of_nodes = GetGeometry().size(); //resizing as needed the LHS unsigned int MatSize=number_of_nodes; ConvectionDiffusionSettings::Pointer my_settings = rCurrentProcessInfo.GetValue(CONVECTION_DIFFUSION_SETTINGS); const Variable<double>& rUnknownVar = my_settings->GetUnknownVariable(); const Variable<double>& rSurfaceSourceVar = my_settings->GetSurfaceSourceVariable(); //calculate lenght double x21 = GetGeometry()[1].X() - GetGeometry()[0].X(); double y21 = GetGeometry()[1].Y() - GetGeometry()[0].Y(); double lenght = x21*x21 + y21*y21; lenght = sqrt(lenght); const Properties& ConstProp = GetProperties(); const double& ambient_temperature = ConstProp[AMBIENT_TEMPERATURE]; double StefenBoltzmann = 5.67e-8; double emissivity = ConstProp[EMISSIVITY]; double convection_coefficient = ConstProp[CONVECTION_COEFFICIENT]; const double& T0 = GetGeometry()[0].FastGetSolutionStepValue(rUnknownVar); const double& T1 = GetGeometry()[1].FastGetSolutionStepValue(rUnknownVar); const double& q0 =GetGeometry()[0].FastGetSolutionStepValue(rSurfaceSourceVar); const double& q1 =GetGeometry()[1].FastGetSolutionStepValue(rSurfaceSourceVar); if (CalculateStiffnessMatrixFlag == true) //calculation of the matrix is required { if(rLeftHandSideMatrix.size1() != MatSize ) rLeftHandSideMatrix.resize(MatSize,MatSize,false); noalias(rLeftHandSideMatrix) = ZeroMatrix(MatSize,MatSize); rLeftHandSideMatrix(0,0) = ( convection_coefficient + emissivity*StefenBoltzmann*4.0*pow(T0,3) )* 0.5 * lenght; rLeftHandSideMatrix(1,1) = ( convection_coefficient + emissivity*StefenBoltzmann*4.0*pow(T1,3) )* 0.5 * lenght; } //resizing as needed the RHS double aux = pow(ambient_temperature,4); if (CalculateResidualVectorFlag == true) //calculation of the matrix is required { if(rRightHandSideVector.size() != MatSize ) rRightHandSideVector.resize(MatSize,false); rRightHandSideVector[0] = q0 - emissivity*StefenBoltzmann*(pow(T0,4) - aux) - convection_coefficient * ( T0 - ambient_temperature); rRightHandSideVector[1] = q1 - emissivity*StefenBoltzmann*(pow(T1,4) - aux) - convection_coefficient * ( T1 - ambient_temperature); rRightHandSideVector *= 0.5*lenght; } KRATOS_CATCH("") }
void InfiniteDomainCondition<TDim,TNumNodes>::CalculateRHS( VectorType& rRightHandSideVector, const ProcessInfo& CurrentProcessInfo ) { KRATOS_TRY //const PropertiesType& Prop = this->GetProperties(); const GeometryType& Geom = this->GetGeometry(); const unsigned int element_size = TNumNodes; const GeometryType::IntegrationPointsArrayType& integration_points = Geom.IntegrationPoints( mThisIntegrationMethod ); const unsigned int NumGPoints = integration_points.size(); const unsigned int LocalDim = Geom.LocalSpaceDimension(); //Resetting the RHS if ( rRightHandSideVector.size() != element_size ) rRightHandSideVector.resize( element_size, false ); noalias( rRightHandSideVector ) = ZeroVector( element_size ); boost::numeric::ublas::bounded_matrix<double,TNumNodes,TNumNodes> DampingMatrix; //Defining the shape functions, the jacobian and the shape functions local gradients Containers array_1d<double,TNumNodes> Np; const Matrix& NContainer = Geom.ShapeFunctionsValues( mThisIntegrationMethod ); GeometryType::JacobiansType JContainer(NumGPoints); for(unsigned int i = 0; i<NumGPoints; i++) (JContainer[i]).resize(TDim,LocalDim,false); Geom.Jacobian( JContainer, mThisIntegrationMethod ); double IntegrationCoefficient; // Definition of the speed in the fluid //~ const double BulkModulus = Prop[BULK_MODULUS_FLUID]; //~ const double Water_density = Prop[DENSITY_WATER]; const double BulkModulus = 2.21e9; const double Water_density = 1000.0; const double inv_c_speed = 1.0 /sqrt(BulkModulus/Water_density); //Nodal Variables array_1d<double,TNumNodes> DtPressureVector; for(unsigned int i=0; i<TNumNodes; i++) { DtPressureVector[i] = Geom[i].FastGetSolutionStepValue(Dt_PRESSURE); } for ( unsigned int igauss = 0; igauss < NumGPoints; igauss++ ) { noalias(Np) = row(NContainer,igauss); //calculating weighting coefficient for integration this->CalculateIntegrationCoefficient( IntegrationCoefficient, JContainer[igauss], integration_points[igauss].Weight() ); // Mass matrix contribution noalias(DampingMatrix) = (inv_c_speed)*outer_prod(Np,Np)*IntegrationCoefficient; noalias(rRightHandSideVector) += -1.0*prod(DampingMatrix,DtPressureVector); } KRATOS_CATCH( "" ) }
void testVectorType(const VectorType& base) { typedef typename internal::traits<VectorType>::Index Index; typedef typename internal::traits<VectorType>::Scalar Scalar; const Index size = base.size(); Scalar high = internal::random<Scalar>(-500,500); Scalar low = (size == 1 ? high : internal::random<Scalar>(-500,500)); if (low>high) std::swap(low,high); const Scalar step = ((size == 1) ? 1 : (high-low)/(size-1)); // check whether the result yields what we expect it to do VectorType m(base); m.setLinSpaced(size,low,high); VectorType n(size); for (int i=0; i<size; ++i) n(i) = low+i*step; VERIFY_IS_APPROX(m,n); // random access version m = VectorType::LinSpaced(size,low,high); VERIFY_IS_APPROX(m,n); // Assignment of a RowVectorXd to a MatrixXd (regression test for bug #79). VERIFY( (MatrixXd(RowVectorXd::LinSpaced(3, 0, 1)) - RowVector3d(0, 0.5, 1)).norm() < std::numeric_limits<Scalar>::epsilon() ); // These guys sometimes fail! This is not good. Any ideas how to fix them!? //VERIFY( m(m.size()-1) == high ); //VERIFY( m(0) == low ); // sequential access version m = VectorType::LinSpaced(Sequential,size,low,high); VERIFY_IS_APPROX(m,n); // These guys sometimes fail! This is not good. Any ideas how to fix them!? //VERIFY( m(m.size()-1) == high ); //VERIFY( m(0) == low ); // check whether everything works with row and col major vectors Matrix<Scalar,Dynamic,1> row_vector(size); Matrix<Scalar,1,Dynamic> col_vector(size); row_vector.setLinSpaced(size,low,high); col_vector.setLinSpaced(size,low,high); VERIFY( row_vector.isApprox(col_vector.transpose(), NumTraits<Scalar>::epsilon())); Matrix<Scalar,Dynamic,1> size_changer(size+50); size_changer.setLinSpaced(size,low,high); VERIFY( size_changer.size() == size ); typedef Matrix<Scalar,1,1> ScalarMatrix; ScalarMatrix scalar; scalar.setLinSpaced(1,low,high); VERIFY_IS_APPROX( scalar, ScalarMatrix::Constant(high) ); VERIFY_IS_APPROX( ScalarMatrix::LinSpaced(1,low,high), ScalarMatrix::Constant(high) ); }
void VarReLUPosDefModule::BackpropImplementation( const MatrixType& nextDodx ) { // This first call will terminate at the input source b/c it is expecting // two sources. We have to send a fake backprop signal PosDefModule::BackpropImplementation( nextDodx ); VectorType input = _inputPort.GetInput(); _inputPort.Backprop( MatrixType::Zero( nextDodx.rows(), input.size() ) ); }
/** * calculates only the RHS vector (certainly to be removed due to contact algorithm) */ void MasterContactPoint2D::CalculateRightHandSide( VectorType& rRightHandSideVector, ProcessInfo& rCurrentProcessInfo) { unsigned int ndof = GetGeometry().size()*2; if( rRightHandSideVector.size() != ndof ) rRightHandSideVector.resize(ndof,false); rRightHandSideVector = ZeroVector(ndof); }
bool compareVecs(const VectorType& a1, const std::string& a1_name, const VectorType&a2, const std::string& a2_name, const ValueType& rel_tol, const ValueType& abs_tol, Teuchos::FancyOStream& out) { bool success = true; out << "Comparing " << a1_name << " == " << a2_name << " ... "; const int n = a1.size(); // Compare sizes if (a2.size() != n) { out << "\nError, "<<a1_name<<".size() = "<<a1.size()<<" == " << a2_name<<".size() = "<<a2.size()<<" : failed!\n"; return false; } // Compare elements for( int i = 0; i < n; ++i ) { ValueType err = std::abs(a1.coeff(i) - a2.coeff(i)); ValueType tol = abs_tol + rel_tol*std::max(std::abs(a1.fastAccessCoeff(i)), std::abs(a2.fastAccessCoeff(i))); if (err > tol) { out <<"\nError, relErr("<<a1_name<<"["<<i<<"]," <<a2_name<<"["<<i<<"]) = relErr("<<a1.coeff(i)<<","<<a2.coeff(i) <<") = "<<err<<" <= tol = "<<tol<<": failed!\n"; success = false; } } if (success) { out << "passed\n"; } else { out << std::endl << a1_name << " = " << a1 << std::endl << a2_name << " = " << a2 << std::endl; } return success; }
VectorType solve(const MatrixType & matrix, VectorType const & rhs, cg_tag const & tag, PreconditionerType const & precond) { typedef typename VectorType::value_type ScalarType; typedef typename viennacl::tools::CPU_SCALAR_TYPE_DEDUCER<ScalarType>::ResultType CPU_ScalarType; VectorType result(rhs.size()); result.clear(); VectorType residual = rhs; VectorType tmp(rhs.size()); VectorType z = rhs; precond.apply(z); VectorType p = z; ScalarType ip_rr = viennacl::linalg::inner_prod(residual, z); ScalarType alpha; ScalarType new_ip_rr = 0; ScalarType beta; ScalarType norm_rhs = ip_rr; for (unsigned int i = 0; i < tag.iterations(); ++i) { tag.iters(i+1); tmp = viennacl::linalg::prod(matrix, p); alpha = ip_rr / viennacl::linalg::inner_prod(tmp, p); result += alpha * p; residual -= alpha * tmp; z = residual; precond.apply(z); new_ip_rr = viennacl::linalg::inner_prod(residual, z); if (std::fabs(new_ip_rr / norm_rhs) < tag.tolerance() * tag.tolerance()) //squared norms involved here break; beta = new_ip_rr / ip_rr; ip_rr = new_ip_rr; p = z + beta*p; } //store last error estimate: tag.error(sqrt(std::fabs(new_ip_rr / norm_rhs))); return result; }
void check_vector(const VectorType& v) { typedef typename VectorType::value_type value_type; for (uint64 i = 0; i < v.size(); ++i) { STXXL_CHECK(v[i] == value_type(i)); } }
template<typename VectorType> void lpNorm(const VectorType& v) { VectorType u = VectorType::Random(v.size()); VERIFY_IS_APPROX(u.template lpNorm<Infinity>(), u.cwiseAbs().maxCoeff()); VERIFY_IS_APPROX(u.template lpNorm<1>(), u.cwiseAbs().sum()); VERIFY_IS_APPROX(u.template lpNorm<2>(), internal::sqrt(u.array().abs().square().sum())); VERIFY_IS_APPROX(internal::pow(u.template lpNorm<5>(), typename VectorType::RealScalar(5)), u.array().abs().pow(5).sum()); }
void generate_points(){ mpoints.setRandom(mndim,msize); for(int ii=0; ii < mlikelihoods.size(); ii++){ mlikelihoods(ii) = log_like(point(ii)); } }
VectorType solve(MatrixType const & system_matrix, VectorType const & rhs, viennashe::solvers::linear_solver_config const & config, viennashe::solvers::serial_linear_solver_tag ) { typedef typename VectorType::value_type NumericT; // // Step 1: Convert data to ViennaCL types: // viennacl::compressed_matrix<NumericT> A(system_matrix.size1(), system_matrix.size2()); viennacl::vector<NumericT> b(system_matrix.size1()); viennacl::fast_copy(&(rhs[0]), &(rhs[0]) + rhs.size(), b.begin()); detail::copy(system_matrix, A); // // Step 2: Setup preconditioner and run solver // log::info<log_linear_solver>() << "* solve(): Computing preconditioner (single-threaded)... " << std::endl; //viennacl::linalg::ilut_tag precond_tag(config.ilut_entries(), // config.ilut_drop_tolerance()); viennacl::linalg::ilu0_tag precond_tag; viennacl::linalg::ilu0_precond<viennacl::compressed_matrix<NumericT> > preconditioner(A, precond_tag); log::info<log_linear_solver>() << "* solve(): Solving system (single-threaded)... " << std::endl; viennacl::linalg::bicgstab_tag solver_tag(config.tolerance(), config.max_iters()); //log::debug<log_linear_solver>() << "Compressed matrix: " << system_matrix << std::endl; //log::debug<log_linear_solver>() << "Compressed rhs: " << rhs << std::endl; viennacl::vector<NumericT> vcl_result = viennacl::linalg::solve(A, b, solver_tag, preconditioner); //log::debug<log_linear_solver>() << "Number of iterations (ILUT): " << solver_tag.iters() << std::endl; // // Step 3: Convert data back: // VectorType result(vcl_result.size()); viennacl::fast_copy(vcl_result.begin(), vcl_result.end(), &(result[0])); viennashe::util::check_vector_for_valid_entries(result); // // As a check, compute residual: // log::info<log_linear_solver>() << "* solve(): residual: " << viennacl::linalg::norm_2(viennacl::linalg::prod(A, vcl_result) - b) / viennacl::linalg::norm_2(b) << " after " << solver_tag.iters() << " iterations." << std::endl; //log::debug<log_linear_solver>() << "SHE result (compressed): " << compressed_result << std::endl; return result; }
CovarianceEstimatorInfo CovarianceEstimator::GetParamsMsg() const { CovarianceEstimatorInfo info; info.source_name = _sourceName; VectorType params = _params->GetParamsVec(); info.parameters.resize( params.size() ); // GetVectorView( info.parameters ) = params; SerializeMatrix( params, info.parameters ); return info; }