//---------------------------------------------------------------------------// TEUCHOS_UNIT_TEST( WuBasis, wu_basis_order_2 ) { typedef DataTransferKit::WuBasis<2> BasisType; typedef DataTransferKit::RadialBasisPolicy<BasisType> BP; int dim = 3; Teuchos::Array<double> x1(dim, 0.5); Teuchos::Array<double> x2(dim, 0.75); double radius_1 = 1.0; Teuchos::RCP<BasisType> basis_1 = BP::create(); double dist = DataTransferKit::EuclideanDistance<3>::distance( x1.getRawPtr(), x2.getRawPtr() ); double basis_value = BP::evaluateValue( *basis_1, radius_1, dist ); double basis_grad = BP::evaluateGradient( *basis_1, radius_1, dist ); double x = 0.0; for ( int i = 0; i < dim; ++i ) { x += (x2[i]-x1[i])*(x2[i]-x1[i]); } x = std::sqrt(x); double test_value = (1.0-x)*(1.0-x)*(1.0-x)*(1.0-x)*(1.0-x) * ( 5.0*x*x*x*x+25.0*x*x*x+48.0*x*x+40.0*x+8.0 ); double test_grad = -9.0*(x-1.0)*(x-1.0)*(x-1.0)*(x-1.0)*x * ( 5.0*x*x*x+20.0*x*x+29.0*x+16.0 ); TEST_EQUALITY( test_value, basis_value ); TEST_FLOATING_EQUALITY( test_grad, basis_grad, epsilon ); double radius_2 = 0.1; BasisType basis_2; basis_value = BP::evaluateValue( basis_2, radius_2, dist ); basis_grad = BP::evaluateGradient( basis_2, radius_2, dist ); TEST_EQUALITY( 0.0, basis_value ); TEST_EQUALITY( 0.0, basis_grad ); }
double probability_x_less_than_y(const std::valarray<double>& x, const std::valarray<double>& y) { vector<double> x2(x.size()); for(int i=0;i<x2.size();i++) x2[i] = x[i]; sort(x2.begin(),x2.end()); vector<double> y2(y.size()); for(int i=0;i<y2.size();i++) y2[i] = y[i]; sort(y2.begin(),y2.end()); valarray<double> FX(y.size()); int dx=0; for(int dy=0;dy<FX.size();dy++) { while((dx<x2.size()) and (x2[dx]<y2[dy])) dx++; FX[dy] = double(dx)/x2.size(); } return FX.sum()/FX.size(); }
LUALIB_API int luaX_loadstring(lua_State* L, LPCTSTR code, LPCTSTR name) { CString x1(code); int sz = x1.GetLength(); int bs = WideCharToMultiByte(CP_THREAD_ACP, 0, x1, sz + 1, NULL, 0, NULL, NULL); char* b1 = new char[bs]; int rs = WideCharToMultiByte(CP_THREAD_ACP, 0, x1, sz + 1, b1, bs, NULL, NULL); CString x2(name); x2 = CString("=String-") + x2; sz = x2.GetLength(); bs = WideCharToMultiByte(CP_THREAD_ACP, 0, x2, sz + 1, NULL, 0, NULL, NULL); char* b2 = new char[bs]; WideCharToMultiByte(CP_THREAD_ACP, 0, x2, sz + 1, b2, bs, NULL, NULL); int r = luaL_loadbuffer(L, b1, rs - 1, b2); delete b1; delete b2; return r; }
void DrawVisibility(QPainter *p,pigalePaint *paint) {TopologicalGraph G(paint->GCP); Prop<Tpoint> P1(G.Set(tedge()),PROP_DRAW_POINT_1); Prop<Tpoint> P2(G.Set(tedge()),PROP_DRAW_POINT_2); Prop<int> x1(G.Set(tvertex()),PROP_DRAW_INT_1); Prop<int> x2(G.Set(tvertex()),PROP_DRAW_INT_2); Prop<int> y(G.Set(tvertex()),PROP_DRAW_INT_5); Prop<short> ecolor(G.Set(tedge()),PROP_COLOR); Prop<short> vcolor(G.Set(tvertex()),PROP_COLOR); double alpha=0.35; p->setFont(QFont("sans",Min((int)(1.8*alpha * Min(paint->xscale,paint->yscale) + .5),13))); Tpoint a,b; for(tvertex v=1;v<=G.nv();v++) paint->DrawText(p,x1[v]-alpha,y[v]+alpha, x2[v]-x1[v]+2*alpha,2*alpha,v,vcolor[v]); for (tedge e = 1;e <= G.ne();e++) {a.x() = P1[e].x(); a.y() = P1[e].y() + alpha; b.x() = P1[e].x(); b.y() = P2[e].y() - alpha; paint->DrawSeg(p,a,b,ecolor[e]); } }
main() { Punct x1(10, 10), x2(100, 200); Dreptunghi d1(x1, x2), d2(10, 20, 14, 50); clrscr(); d1.List(); getch(); cout<<'\n'; d2.List(); getch(); cout<<'\n'; if (d1 == d2) cout<<"d1 = d2"; else cout<<"d1 != d2"; getch(); cout<<'\n'; cout<<d1.Lung_lat1()<<' '<<d1.Lung_lat2(); getch(); cout<<'\n'; cout<<d2.Lung_lat1()<<' '<<d2.Lung_lat2(); getch(); cout<<'\n'; cout<<"Perimetrul d1: "<<d1.Perimetru(); getch(); cout<<'\n'; cout<<"Perimetrul d2: "<<d2.Perimetru(); getch(); cout<<'\n'; cout<<"d1, colt stanga sus : "<<d1.Colt_st_sus(); getch(); cout<<'\n'; cout<<"d1, colt dreapta jos : "<<d1.Colt_dr_jos(); getch(); cout<<'\n'; return 0; }
void run() { /** * note: this test will deadlock if the code breaks */ #if defined(__linux__) || defined(__APPLE__) // create pthread_rwlock_t lk; verify(pthread_rwlock_init(&lk, 0) == 0); // read lock verify(pthread_rwlock_rdlock(&lk) == 0); AtomicUInt32 x1(0); stdx::thread t1(stdx::bind(worker1, &lk, &x1)); while (!x1.load()) ; verify(x1.load() == 1); sleepmillis(500); verify(x1.load() == 1); AtomicUInt32 x2(0); stdx::thread t2(stdx::bind(worker2, &lk, &x2)); t2.join(); verify(x2.load() == 1); pthread_rwlock_unlock(&lk); for (int i = 0; i < 2000; i++) { if (x1.load() == 2) break; sleepmillis(1); } verify(x1.load() == 2); t1.join(); #endif }
double testCosineTransform (long n) { try { autoNUMvector<double> x (1, n); autoNUMvector<double> y (1, n); autoNUMvector<double> x2 (1, n); autoNUMmatrix<double> cosinesTable (NUMcosinesTable (n), 1, 1); for (long i = 1 ; i <= n; i++) { x[i] = NUMrandomUniform (0, 70); } NUMcosineTransform (x.peek(), y.peek(), n, cosinesTable.peek()); NUMinverseCosineTransform (y.peek(), x2.peek(), n, cosinesTable.peek()); double delta = 0; for (long i =1 ; i <= n; i++) { double dif = x[i] - x2[i]; delta += dif * dif; } delta = sqrt (delta); return delta; } catch (MelderError) { Melder_throw ("Test cosine transform error"); } }
//---------------------------------------------------------------------------// // Tests. //---------------------------------------------------------------------------// TEUCHOS_UNIT_TEST( WendlandBasis, dim_1_order_0 ) { typedef DataTransferKit::WendlandBasis<0> BasisType; typedef DataTransferKit::RadialBasisPolicy<BasisType> BP; int dim = 1; Teuchos::Array<double> x1(dim, 0.5); Teuchos::Array<double> x2(dim, 0.75); double radius_1 = 1.0; Teuchos::RCP<BasisType> basis_1 = BP::create( radius_1 ); double dist = DataTransferKit::EuclideanDistance<1>::distance( x1.getRawPtr(), x2.getRawPtr() ); double basis_value = BP::evaluateValue( *basis_1, dist ); double basis_grad = BP::evaluateGradient( *basis_1, dist ); double x = 0.0; for ( int i = 0; i < dim; ++i ) { x += (x2[i]-x1[i])*(x2[i]-x1[i]); } x = std::sqrt(x); double test_value = (1.0-x)*(1.0-x); double test_grad = 2.0*x-2.0; TEST_EQUALITY( test_value, basis_value ); TEST_EQUALITY( test_grad, basis_grad ); double radius_2 = 0.1; BasisType basis_2( radius_2 ); basis_value = BP::evaluateValue( basis_2, dist ); basis_grad = BP::evaluateGradient( basis_2, dist ); TEST_EQUALITY( 0.0, basis_value ); TEST_EQUALITY( 0.0, basis_grad ); }
// Interpolates between the click points static void interpolate (const dataVec& dataIn, dataVec& dataOut) { const size_t nSteps = 10; const size_t interpolatedSize = (dataIn.size() - 1) * nSteps; dataOut.resize(interpolatedSize); std::vector<double> x(dataIn.size()), y(dataIn.size()); std::transform(begin(dataIn), end(dataIn), begin(x), [](lk::trackDatum d){ return std::get<1>(d).x; }); std::transform(begin(dataIn), end(dataIn), begin(y), [](lk::trackDatum d){ return std::get<1>(d).y; }); std::vector<size_t> frameIndices(interpolatedSize); std::iota(begin(frameIndices), end(frameIndices), 0); std::vector<double> x2(interpolatedSize), y2(interpolatedSize); interpolation::cubic(begin(x), end(x), begin(x2), nSteps); interpolation::cubic(begin(y), end(y), begin(y2), nSteps); for (size_t i = 0; i < interpolatedSize; i++) { dataOut[i] = lk::trackDatum(frameIndices[i], cv::Point2d(x2[i], y2[i])); } }
boost::shared_ptr<Mesh<Simplex<2> > > createMeshLaplacianLM() { typedef Mesh<Simplex<2> > mesh_type; double meshSize = option("gmsh.hsize").as<double>(); GeoTool::Node x1(-2,-1); GeoTool::Node x2(2,1); GeoTool::Rectangle R( meshSize ,"OMEGA",x1,x2); //R.setMarker(_type="line",_name="Paroi",_marker3=true); R.setMarker(_type="line",_name="gamma",_markerAll=true); R.setMarker(_type="surface",_name="Omega",_markerAll=true); GeoTool::Node x3(0,0); //center GeoTool::Node x4(1);//majorRadiusParam GeoTool::Node x5(0.7);//minorRadiusParam GeoTool::Node x6(0.1);//penautRadiusParam GeoTool::Peanut P( meshSize ,"OMEGA2",x3,x4,x5,x6); P.setMarker(_type="line",_name="peanut",_markerAll=true); P.setMarker(_type="surface",_name="Omega2",_markerAll=true); auto mesh = (R-P).createMesh(_mesh=new mesh_type,_name="mymesh.msh"); return mesh; }
Foliage::Fixed Foliage::FastMath::cos(const Foliage::Fixed x) { if (x < Sint16(0)) { return cos(x.opposite()); } if (x > F_TWOPI) { return cos(x - F_TWOPI); } if (x > F_PI) { return cos(x - F_PI).opposite(); } if (x > F_PI_2) { return cos(F_PI - x).opposite(); } Fixed x2(x); x2 *= F_2000_OVER_PI; Sint16 i = Sint16(x2); return Foliage::FastMath::cos_t[i]; }
int main(int argc, char *argv[]) { // Los vectores en C++ son escencialmente arreglos en C con una interfaz // más conveniente. Donde sea que se pueda usar arreglos, se puede usar // vectores. Cuando se necesita la dirección de memoria de un arreglo, hay // que usar la dirección del primer elemento del vector: &x[0]. x por sí // solo no sirve ya que es un objeto que encapsula al verdadero arreglo. std::vector<float> x1; x1.reserve(N); x1.resize(N); // copiar datos del archivo de entrada al vector std::ifstream input_file(data_file_name, std::ios::binary | std::ios::in); if (!input_file) { std::cerr << "No se pudo abrir el archivo " << data_file_name << std::endl; std::exit(-1); } input_file.read((char *) &x1[0], N * sizeof(float)); input_file.close(); // crear una copia del vector, de modo de tener // uno para mapear en la GPU y otro en la CPU std::vector<float> x2(x1); // mapear x1 en la CPU y x2 en la GPU cpu_map(x1); gpu_map(&x2[0], x2.size()); // verificar que los resultados son prácticamente iguales float squared_diff_norm = 0.0; # define SQUARED(x) ((x) * (x)) # pragma omp parallel reduction(+: squared_diff_norm) for (unsigned i = 0; i < N; ++i) squared_diff_norm += SQUARED(x1[i] - x2[i]); std::cout << "Norma de la diferencia: " << std::sqrt(squared_diff_norm) << std::endl; }
/// return the index of the MHM domain of a fracture int TPZFracSet::MHMDomain(TPZFracture &frac) { TPZManVector<REAL,3> x1(3), x2(3), xmid(3); fNodeVec[frac.fNodes[0]].GetCoordinates(x1); fNodeVec[frac.fNodes[1]].GetCoordinates(x2); std::pair<uint32_t,uint32_t> key0 = NodeKey(frac.fNodes[0]); std::pair<uint32_t,uint32_t> key1 = NodeKey(frac.fNodes[1]); if(key0.first == key1.first && key0.first%fMHMSpacingInt[0] == 0) { return -1; } if(key0.second == key1.second && key0.second%fMHMSpacingInt[1] == 0) { return -1; } for (int i=0; i<3; i++) { xmid[i] = (x1[i]+x2[i])*0.5-fLowLeft[i]; } int numfacex = (fTopRight[0]-fLowLeft[0])/fMHMSpacing[0]; int numx = (xmid[0])/fMHMSpacing[0]; int numy = (xmid[1])/fMHMSpacing[1]; return numy*numfacex+numx; }
int fevec5(Epetra_Comm& Comm, bool verbose) { int NumElements = 4; Epetra_Map Map(NumElements, 0, Comm); Epetra_FEVector x1(Map); x1.PutScalar (0); // let all processors set global entry 0 to 1 const int GID = 0; const double value = 1; x1.ReplaceGlobalValues(1, &GID, &value); x1.GlobalAssemble (Insert); if (Comm.MyPID()==0) std::cout << "Entry " << GID << " after construct & set: " << x1[0][0] << std::endl; // copy vector Epetra_FEVector x2 (x1); x2.PutScalar(0); // re-apply 1 to the vector, but only on the // owning processor. should be enough to set // the value (as non-local data in x1 should // have been eliminated after calling // GlobalAssemble). if (Comm.MyPID()==0) x2.ReplaceGlobalValues(1, &GID, &value); x2.GlobalAssemble (Insert); if (Comm.MyPID()==0) std::cout << "Entry " << GID << " after copy & set: " << x2[0][0] << std::endl; return 0; }
TEST(StanAgradRevInternal, precomp_vv_vari) { double value, gradient1, gradient2; AVAR x1(2), x2(3); AVAR y; value = 1; gradient1 = 4; gradient2 = 5; AVEC vars = createAVEC(x1, x2); EXPECT_NO_THROW(y = stan::math::var(new stan::math::precomp_vv_vari(value, x1.vi_, x2.vi_, gradient1, gradient2))); EXPECT_FLOAT_EQ(value, y.val()); VEC g; EXPECT_NO_THROW(y.grad(vars, g)); ASSERT_EQ(2U, g.size()); EXPECT_FLOAT_EQ(gradient1, g[0]); EXPECT_FLOAT_EQ(gradient2, g[1]); stan::math::recover_memory(); }
void RSA_TestInstantiations() { RSASS<PKCS1v15, SHA1>::Verifier x1(1, 1); RSASS<PKCS1v15, SHA1>::Signer x2(NullRNG(), 1); RSASS<PKCS1v15, SHA1>::Verifier x3(x2); RSASS<PKCS1v15, SHA1>::Verifier x4(x2.GetKey()); RSASS<PSS, SHA1>::Verifier x5(x3); #ifndef __MWERKS__ RSASS<PSSR, SHA1>::Signer x6 = x2; x3 = x2; x6 = x2; #endif RSAES<PKCS1v15>::Encryptor x7(x2); #ifndef __GNUC__ RSAES<PKCS1v15>::Encryptor x8(x3); #endif RSAES<OAEP<SHA1> >::Encryptor x9(x2); x4 = x2.GetKey(); RSASS<PKCS1v15, SHA3_256>::Verifier x10(1, 1); RSASS<PKCS1v15, SHA3_256>::Signer x11(NullRNG(), 1); RSASS<PKCS1v15, SHA3_256>::Verifier x12(x11); RSASS<PKCS1v15, SHA3_256>::Verifier x13(x11.GetKey()); }
TEUCHOS_UNIT_TEST( Stokhos_NormalizedHermiteBasis, QuadPointsForUQTK ) { int n = static_cast<int>(std::ceil((setup.p+1)/2.0)); Teuchos::Array<double> x1, w1; Teuchos::Array< Teuchos::Array<double> > v1; setup.basis.getQuadPoints(setup.p, x1, w1, v1); Teuchos::Array<double> x2(n), w2(n); Teuchos::Array< Teuchos::Array<double> > v2(n); int kind = 4; int kpts = 0; double endpts[2] = {0.0, 0.0}; Teuchos::Array<double> b(n); double alpha = 0.0; double beta = 0.0; GAUSSQ_F77(&kind, &n, &alpha, &beta, &kpts, endpts, &b[0], &x2[0], &w2[0]); for (int i=0; i<n; i++) { w2[i] *= 0.5/std::sqrt(std::atan(1.0)); // 1/sqrt(pi) x2[i] *= std::sqrt(2.0); v2[i].resize(setup.p+1); setup.basis.evaluateBases(x2[i], v2[i]); } success = true; success = success && Stokhos::compareArrays(x1, "x1", x2, "x2", setup.rtol, setup.atol, out); success = success && Stokhos::compareArrays(w1, "w1", w2, "w2", setup.rtol, setup.atol, out); for (int i=0; i<n; i++) { std::stringstream ss1, ss2; ss1 << "v1[" << i << "]"; ss2 << "v2[" << i << "]"; success = success && Stokhos::compareArrays(v1[i], ss1.str(), v2[i], ss2.str(), setup.rtol, setup.atol, out); } }
void test1() { Y *y1p = new Y; Y *y2p = new Y; cout << "X::nx after init: " << X::nx << "(2)" << endl; cout << "y1p->nreference() after init: " << y1p->nreference() << "(0)" << endl; X *x1p = y1p; X *x2p = y2p; void *vy1p = (void *)y1p; void *vy2p = (void *)y2p; void *vx1p = (void *)x1p; void *vx2p = (void *)x2p; Ref<Y> y1 = y1p; Ref<Y> y2 = y2p; cout << "X::nx after Ref<Y> assignment: " << X::nx << "(2)" << endl; cout << "y1->nreference() after Ref<Y> assignment: " << y1->nreference() << "(1)" << endl; Ref<X> x1(y1); Ref<X> x2(y2); cout << "X::nx after Ref<X> assignment: " << X::nx << "(2)" << endl; cout << "y1->nreference() after Ref<X> assignment: " << y1->nreference() << "(2)" << endl; x1 = y1; x2 = y2; Ref<Y> yb1, yb2; yb1 << x1; yb2 << x2; cout << "x1 = " << (void *)x1.pointer() << "(" << vx1p << ")" << endl; cout << "x2 = " << (void *)x2.pointer() << "(" << vx2p << ")" << endl; cout << "y1 = " << (void *)y1.pointer() << "(" << vy1p << ")" << endl; cout << "y2 = " << (void *)y2.pointer() << "(" << vy2p << ")" << endl; cout << "yb1 = " << (void *)yb1.pointer() << "(" << (void *)y1.pointer() << ")" << endl; cout << "yb2 = " << (void *)yb2.pointer() << "(" << (void *)y2.pointer() << ")" << endl; }
void scrollable_widget_rep::scroll_event_hor (SI& x, SI& bef, SI& af) { abs_round (x); if ((x + x1() - ox) < ex1) x = ex1 - x1() + ox; if ((x + x2() - ox) > ex2) x = ex2 - x2() + ox; if (attached ()) { int dx= max (-w, min (w, x- scx)); if ((dx>-w) && (dx<w) && (dx!=0)) { win->translate (x1(), y1(), x2(), y2(), -dx, 0); } if (dx>0) this << emit_invalidate (x2()-ox-dx, y1()-oy, x2()-ox, y2()-oy); if (dx<0) this << emit_invalidate (x1()-ox, y1()-oy, x1()-ox-dx, y2()-oy); } scx = x; bef = ox- x1(); af = x2()- ox; a[0]->ox = ox- scx; }
inline void TrsvUN( UnitOrNonUnit diag, const DistMatrix<F>& U, DistMatrix<F>& x ) { #ifndef RELEASE PushCallStack("internal::TrsvUN"); if( U.Grid() != x.Grid() ) throw std::logic_error("{U,x} must be distributed over the same grid"); if( U.Height() != U.Width() ) throw std::logic_error("U must be square"); if( x.Width() != 1 && x.Height() != 1 ) throw std::logic_error("x must be a vector"); const int xLength = ( x.Width() == 1 ? x.Height() : x.Width() ); if( U.Width() != xLength ) throw std::logic_error("Nonconformal TrsvUN"); #endif const Grid& g = U.Grid(); if( x.Width() == 1 ) { // Matrix views DistMatrix<F> U01(g), U11(g); DistMatrix<F> xT(g), x0(g), xB(g), x1(g), x2(g); // Temporary distributions DistMatrix<F,STAR,STAR> U11_STAR_STAR(g); DistMatrix<F,STAR,STAR> x1_STAR_STAR(g); DistMatrix<F,MR, STAR> x1_MR_STAR(g); DistMatrix<F,MC, STAR> z_MC_STAR(g); // Views of z[MC,* ], which will store updates to x DistMatrix<F,MC,STAR> z0_MC_STAR(g), z1_MC_STAR(g); z_MC_STAR.AlignWith( U ); Zeros( x.Height(), 1, z_MC_STAR ); // Start the algorithm PartitionUp ( x, xT, xB, 0 ); while( xT.Height() > 0 ) { RepartitionUp ( xT, x0, x1, /**/ /**/ xB, x2 ); const int n0 = x0.Height(); const int n1 = x1.Height(); LockedView( U01, U, 0, n0, n0, n1 ); LockedView( U11, U, n0, n0, n1, n1 ); View( z0_MC_STAR, z_MC_STAR, 0, 0, n0, 1 ); View( z1_MC_STAR, z_MC_STAR, n0, 0, n1, 1 ); x1_MR_STAR.AlignWith( U01 ); //----------------------------------------------------------------// if( x2.Height() != 0 ) x1.SumScatterUpdate( F(1), z1_MC_STAR ); x1_STAR_STAR = x1; U11_STAR_STAR = U11; Trsv ( UPPER, NORMAL, diag, U11_STAR_STAR.LockedLocalMatrix(), x1_STAR_STAR.LocalMatrix() ); x1 = x1_STAR_STAR; x1_MR_STAR = x1_STAR_STAR; Gemv ( NORMAL, F(-1), U01.LockedLocalMatrix(), x1_MR_STAR.LockedLocalMatrix(), F(1), z0_MC_STAR.LocalMatrix() ); //----------------------------------------------------------------// x1_MR_STAR.FreeAlignments(); SlidePartitionUp ( xT, x0, /**/ /**/ x1, xB, x2 ); } } else { // Matrix views DistMatrix<F> U01(g), U11(g); DistMatrix<F> xL(g), xR(g), x0(g), x1(g), x2(g); // Temporary distributions DistMatrix<F,STAR,STAR> U11_STAR_STAR(g); DistMatrix<F,STAR,STAR> x1_STAR_STAR(g); DistMatrix<F,STAR,MR > x1_STAR_MR(g); DistMatrix<F,MC, MR > z1(g); DistMatrix<F,MR, MC > z1_MR_MC(g); DistMatrix<F,STAR,MC > z_STAR_MC(g); // Views of z[* ,MC] DistMatrix<F,STAR,MC> z0_STAR_MC(g), z1_STAR_MC(g); z_STAR_MC.AlignWith( U ); Zeros( 1, x.Width(), z_STAR_MC ); // Start the algorithm PartitionLeft( x, xL, xR, 0 ); while( xL.Width() > 0 ) { RepartitionLeft ( xL, /**/ xR, x0, x1, /**/ x2 ); const int n0 = x0.Width(); const int n1 = x1.Width(); LockedView( U01, U, 0, n0, n0, n1 ); LockedView( U11, U, n0, n0, n1, n1 ); View( z0_STAR_MC, z_STAR_MC, 0, 0, 1, n0 ); View( z1_STAR_MC, z_STAR_MC, 0, n0, 1, n1 ); x1_STAR_MR.AlignWith( U01 ); z1.AlignWith( x1 ); //----------------------------------------------------------------// if( x2.Width() != 0 ) { z1_MR_MC.SumScatterFrom( z1_STAR_MC ); z1 = z1_MR_MC; Axpy( F(1), z1, x1 ); } x1_STAR_STAR = x1; U11_STAR_STAR = U11; Trsv ( UPPER, NORMAL, diag, U11_STAR_STAR.LockedLocalMatrix(), x1_STAR_STAR.LocalMatrix() ); x1 = x1_STAR_STAR; x1_STAR_MR = x1_STAR_STAR; Gemv ( NORMAL, F(-1), U01.LockedLocalMatrix(), x1_STAR_MR.LockedLocalMatrix(), F(1), z0_STAR_MC.LocalMatrix() ); //----------------------------------------------------------------// x1_STAR_MR.FreeAlignments(); z1.FreeAlignments(); SlidePartitionLeft ( xL, /**/ xR, x0, /**/ x1, x2 ); } } #ifndef RELEASE PopCallStack(); #endif }
void Forcing::EvaluateFunction( Array<OneD, MultiRegions::ExpListSharedPtr> pFields, LibUtilities::SessionReaderSharedPtr pSession, std::string pFieldName, Array<OneD, NekDouble>& pArray, const std::string& pFunctionName, NekDouble pTime) { ASSERTL0(pSession->DefinesFunction(pFunctionName), "Function '" + pFunctionName + "' does not exist."); unsigned int nq = pFields[0]->GetNpoints(); if (pArray.num_elements() != nq) { pArray = Array<OneD, NekDouble> (nq); } LibUtilities::FunctionType vType; vType = pSession->GetFunctionType(pFunctionName, pFieldName); if (vType == LibUtilities::eFunctionTypeExpression) { Array<OneD, NekDouble> x0(nq); Array<OneD, NekDouble> x1(nq); Array<OneD, NekDouble> x2(nq); pFields[0]->GetCoords(x0, x1, x2); LibUtilities::EquationSharedPtr ffunc = pSession->GetFunction(pFunctionName, pFieldName); ffunc->Evaluate(x0, x1, x2, pTime, pArray); } else if (vType == LibUtilities::eFunctionTypeFile) { std::string filename = pSession->GetFunctionFilename( pFunctionName, pFieldName); std::vector<LibUtilities::FieldDefinitionsSharedPtr> FieldDef; std::vector<std::vector<NekDouble> > FieldData; Array<OneD, NekDouble> vCoeffs(pFields[0]->GetNcoeffs()); Vmath::Zero(vCoeffs.num_elements(), vCoeffs, 1); LibUtilities::FieldIOSharedPtr fld = MemoryManager<LibUtilities::FieldIO>::AllocateSharedPtr(m_session->GetComm()); fld->Import(filename, FieldDef, FieldData); int idx = -1; for (int i = 0; i < FieldDef.size(); ++i) { for (int j = 0; j < FieldDef[i]->m_fields.size(); ++j) { if (FieldDef[i]->m_fields[j] == pFieldName) { idx = j; } } if (idx >= 0) { pFields[0]->ExtractDataToCoeffs( FieldDef[i], FieldData[i], FieldDef[i]->m_fields[idx], vCoeffs); } else { cout << "Field " + pFieldName + " not found." << endl; } } pFields[0]->BwdTrans_IterPerExp(vCoeffs, pArray); } }
bool SVGLineElement::hasRelativeValues() const { return (x1().isRelative() || y1().isRelative() || x2().isRelative() || y2().isRelative()); }
Path SVGLineElement::toPathData() const { return Path::createLine(FloatPoint(x1().value(), y1().value()), FloatPoint(x2().value(), y2().value())); }
void MathPlot::setupMultiAxisDemo(QCustomPlot *customPlot) { customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom); customPlot->setLocale(QLocale(QLocale::English, QLocale::UnitedKingdom)); // period as decimal separator and comma as thousand separator customPlot->legend->setVisible(true); QFont legendFont = font(); // start out with MainWindow's font.. legendFont.setPointSize(9); // and make a bit smaller for legend customPlot->legend->setFont(legendFont); customPlot->legend->setBrush(QBrush(QColor(255,255,255,230))); // by default, the legend is in the inset layout of the main axis rect. So this is how we access it to change legend placement: customPlot->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignBottom|Qt::AlignRight); // setup for graph 0: key axis left, value axis bottom // will contain left maxwell-like function customPlot->addGraph(customPlot->yAxis, customPlot->xAxis); customPlot->graph(0)->setPen(QPen(QColor(255, 100, 0))); customPlot->graph(0)->setBrush(QBrush(QPixmap("://skin/images/balboa.jpg"))); // fill with texture of specified image customPlot->graph(0)->setLineStyle(QCPGraph::lsLine); customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, 5)); customPlot->graph(0)->setName("Left maxwell function"); // setup for graph 1: key axis bottom, value axis left (those are the default axes) // will contain bottom maxwell-like function customPlot->addGraph(); customPlot->graph(1)->setPen(QPen(Qt::red)); customPlot->graph(1)->setBrush(QBrush(QPixmap("://skin/images/balboa.jpg"))); // same fill as we used for graph 0 customPlot->graph(1)->setLineStyle(QCPGraph::lsStepCenter); customPlot->graph(1)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::red, Qt::white, 7)); customPlot->graph(1)->setErrorType(QCPGraph::etValue); customPlot->graph(1)->setName("Bottom maxwell function"); // setup for graph 2: key axis top, value axis right // will contain high frequency sine with low frequency beating: customPlot->addGraph(customPlot->xAxis2, customPlot->yAxis2); customPlot->graph(2)->setPen(QPen(Qt::blue)); customPlot->graph(2)->setName("High frequency sine"); // setup for graph 3: same axes as graph 2 // will contain low frequency beating envelope of graph 2 customPlot->addGraph(customPlot->xAxis2, customPlot->yAxis2); QPen blueDotPen; blueDotPen.setColor(QColor(30, 40, 255, 150)); blueDotPen.setStyle(Qt::DotLine); blueDotPen.setWidthF(4); customPlot->graph(3)->setPen(blueDotPen); customPlot->graph(3)->setName("Sine envelope"); // setup for graph 4: key axis right, value axis top // will contain parabolically distributed data points with some random perturbance customPlot->addGraph(customPlot->yAxis2, customPlot->xAxis2); customPlot->graph(4)->setPen(QColor(50, 50, 50, 255)); customPlot->graph(4)->setLineStyle(QCPGraph::lsNone); customPlot->graph(4)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 4)); customPlot->graph(4)->setName("Some random data around\na quadratic function"); // generate data, just playing with numbers, not much to learn here: QVector<double> x0(25), y0(25); QVector<double> x1(15), y1(15), y1err(15); QVector<double> x2(250), y2(250); QVector<double> x3(250), y3(250); QVector<double> x4(250), y4(250); for (int i=0; i<25; ++i) // data for graph 0 { x0[i] = 3*i/25.0; y0[i] = exp(-x0[i]*x0[i]*0.8)*(x0[i]*x0[i]+x0[i]); } for (int i=0; i<15; ++i) // data for graph 1 { x1[i] = 3*i/15.0;; y1[i] = exp(-x1[i]*x1[i])*(x1[i]*x1[i])*2.6; y1err[i] = y1[i]*0.25; } for (int i=0; i<250; ++i) // data for graphs 2, 3 and 4 { x2[i] = i/250.0*3*M_PI; x3[i] = x2[i]; x4[i] = i/250.0*100-50; y2[i] = sin(x2[i]*12)*cos(x2[i])*10; y3[i] = cos(x3[i])*10; y4[i] = 0.01*x4[i]*x4[i] + 1.5*(rand()/(double)RAND_MAX-0.5) + 1.5*M_PI; } // pass data points to graphs: customPlot->graph(0)->setData(x0, y0); customPlot->graph(1)->setDataValueError(x1, y1, y1err); customPlot->graph(2)->setData(x2, y2); customPlot->graph(3)->setData(x3, y3); customPlot->graph(4)->setData(x4, y4); // activate top and right axes, which are invisible by default: customPlot->xAxis2->setVisible(true); customPlot->yAxis2->setVisible(true); // set ranges appropriate to show data: customPlot->xAxis->setRange(0, 2.7); customPlot->yAxis->setRange(0, 2.6); customPlot->xAxis2->setRange(0, 3.0*M_PI); customPlot->yAxis2->setRange(-70, 35); // set pi ticks on top axis: QVector<double> piTicks; QVector<QString> piLabels; piTicks << 0 << 0.5*M_PI << M_PI << 1.5*M_PI << 2*M_PI << 2.5*M_PI << 3*M_PI; piLabels << "0" << QString::fromUtf8("½π") << QString::fromUtf8("π") << QString::fromUtf8("1½π") << QString::fromUtf8("2π") << QString::fromUtf8("2½π") << QString::fromUtf8("3π"); customPlot->xAxis2->setAutoTicks(false); customPlot->xAxis2->setAutoTickLabels(false); customPlot->xAxis2->setTickVector(piTicks); customPlot->xAxis2->setTickVectorLabels(piLabels); // add title layout element: customPlot->plotLayout()->insertRow(0); customPlot->plotLayout()->addElement(0, 0, new QCPPlotTitle(customPlot, "Way too many graphs in one plot")); // set labels: customPlot->xAxis->setLabel("Bottom axis with outward ticks"); customPlot->yAxis->setLabel("Left axis label"); customPlot->xAxis2->setLabel("Top axis label"); customPlot->yAxis2->setLabel("Right axis label"); // make ticks on bottom axis go outward: customPlot->xAxis->setTickLength(0, 5); customPlot->xAxis->setSubTickLength(0, 3); // make ticks on right axis go inward and outward: customPlot->yAxis2->setTickLength(3, 3); customPlot->yAxis2->setSubTickLength(1, 1); }
// This function creates the following model: // Minimize // obj: x1 + x2 + x3 + x4 + x5 + x6 // Subject To // c1: x1 + x2 + x5 = 8 // c2: x3 + x5 + x6 = 10 // q1: [ -x1^2 + x2^2 + x3^2 ] <= 0 // q2: [ -x4^2 + x5^2 ] <= 0 // Bounds // x2 Free // x3 Free // x5 Free // End // which is a second order cone program in standard form. // The function returns objective, variables and constraints in the // values obj, vars and rngs. // The function also sets up cone so that for a column j we have // cone[j] >= 0 Column j is in a cone constraint and is the // cone's head variable. // cone[j] == NOT_CONE_HEAD Column j is in a cone constraint but is // not the cone's head variable.. // cone[j] == NOT_IN_CONE Column j is not contained in any cone constraint. static void createmodel (IloModel& model, IloObjective &obj, IloNumVarArray &vars, IloRangeArray &rngs, IloIntArray& cone) { // The indices we assign as user objects to the modeling objects. // We define them as static data so that we don't have to worry about // dynamic memory allocation/leakage. static int indices[] = { 0, 1, 2, 3, 4, 5, 6 }; IloEnv env = model.getEnv(); // Create variables. IloNumVar x1(env, 0, IloInfinity, "x1"); IloNumVar x2(env, -IloInfinity, IloInfinity, "x2"); IloNumVar x3(env, -IloInfinity, IloInfinity, "x3"); IloNumVar x4(env, 0, IloInfinity, "x4"); IloNumVar x5(env, -IloInfinity, IloInfinity, "x5"); IloNumVar x6(env, 0, IloInfinity, "x6"); // Create objective function and immediately store it in return value. obj = IloMinimize(env, x1 + x2 + x3 + x4 + x5 + x6); // Create constraints. IloRange c1(env, 8, x1 + x2 + x5, 8, "c1"); IloRange c2(env, 10, x3 + x5 + x6, 10, "c2"); IloRange q1(env, -IloInfinity, -x1*x1 + x2*x2 + x3*x3, 0, "q1"); cone.add(2); // x1, cone head of constraint at index 2 cone.add(NOT_CONE_HEAD); // x2 cone.add(NOT_CONE_HEAD); // x3 IloRange q2(env, -IloInfinity, -x4*x4 + x5*x5, 0, "q2"); cone.add(3); // x4, cone head of constraint at index 3 cone.add(NOT_CONE_HEAD); // x5 cone.add(NOT_IN_CONE); // x6 // Setup model. model.add(obj); model.add(obj); model.add(c1); model.add(c2); model.add(q1); model.add(q2); // Setup return values. vars.add(x1); vars.add(x2); vars.add(x3); vars.add(x4); vars.add(x5); vars.add(x6); rngs.add(c1); rngs.add(c2); rngs.add(q1); rngs.add(q2); // We set the user object for each modeling object to its index in the // respective array. This makes the code in checkkkt a little simpler. for (IloInt i = 0; i < vars.getSize(); ++i) vars[i].setObject(&indices[i]); for (IloInt i = 0; i < rngs.getSize(); ++i) rngs[i].setObject(&indices[i]); }
// Private methods // determine the slave/master pair in contact, and setup Vectors (N,T1,T2) int ZeroLengthInterface2D::contactDetect(int s, int m1, int m2, int stage) { //+--------------+-----------------+----------------+----------------+---------------+ // NOTES: some methods to get displacements from nodes //+--------------+-----------------+----------------+----------------+---------------+ // getDisp() : get commit(k-1) disp, will be commit(k) after commit // getTrialDisp(): get Trial(k) disp // getIncrDisp(): get Trial(k)-Commit(k-1), will be 0 after commit // getIncrDeltaDisp(): get Trial(k)-Trial(k-1), will be 0 after commit //+--------------+-----------------+----------------+----------------+-------------- ////////////////////////////// for transient gap /////////////////////////////////// // DEFINE: // gap = (U_master-U_slave) / dot(ContactNormal), // defines overlapped normal distance, always keep positive (+) when contacted ///* // get current position and after trial displacement for (slave, master1, master2) nodes int i; const Vector &xs = nodePointers[s]->getCrds(); const Vector &uxs = nodePointers[s]->getTrialDisp(); const Vector &x1 = nodePointers[m1]->getCrds(); const Vector &ux1= nodePointers[m1]->getTrialDisp(); const Vector &x2 = nodePointers[m2]->getCrds(); const Vector &ux2= nodePointers[m2]->getTrialDisp(); Vector trial_slave(2), trial_master1(2), trial_master2(2); for (i = 0; i < 2; i++) { trial_slave(i) = xs(i) + uxs(i); trial_master1(i) = x1(i) + ux1(i); trial_master2(i) = x2(i) + ux2(i); //opserr << "trial_slave: " << trial_slave(i) << "\n"; //opserr << "trial_master1: " << trial_master1(i) << "\n"; //opserr << "trial_master2: " << trial_master2(i) << "\n"; } // calculate normal gap for contact Vector diff(2); Vector ContactTangent(2); for (i = 0; i < 2; i++) { diff(i) = trial_master2(i) - trial_master1(i); //opserr << "diff: " << diff(i) << "\n"; } double L = diff.Norm(); // tangent vector for (i = 0; i < 2; i++) ContactTangent(i) = (1/L) * (trial_master2(i) - trial_master1(i)); // normal vector ContactNormal(0) = - ContactTangent(1); ContactNormal(1) = ContactTangent(0); normal_gap(s) = 0; double alpha = 0; double alpha_bar = 0; for (i = 0; i < 2; i++) { alpha += (1/L) * (trial_slave(i) - trial_master1(i)) * ContactTangent(i); normal_gap(s) += (trial_slave(i) - trial_master1(i)) * ContactNormal(i); diff(i) = x2(i) - x1(i); } double gapgap = normal_gap(s); double L_bar = diff.Norm(); for (i = 0; i < 2; i++) alpha_bar += (1/L_bar) * (xs(i) - x1(i)) * ContactTangent(i); shear_gap(s) = (alpha - alpha_bar) * L_bar; /* /////////////////////////////// for transient gap /////////////////////////////// // we have another way to define the gap, can replace previous code block if want ////////////////////////////// for dynamic gap ////////////////////////////////// const Vector // get current trial incremental position &U_slave = nodePointers[0]->getCrds() + nodePointers[0]->getIncrDisp(); const Vector &U_master= nodePointers[1]->getCrds() + nodePointers[1]->getIncrDisp(); gap=0; int i; for (i=0; i<2; i++){ gap += (U_master(i)-U_slave(i))* ContactNormal(i); } gap+=gap_n; ///////////////// for dynamic gap ////////////////////// */ // stage = 0 means searching slave nodes against master segments // stage = 1 means searching master nodes against slave segments if ((stage == 0 && normal_gap(s) >= 0 && alpha > 0 && alpha < 1) || (stage == 1 && normal_gap(s) >= 0 && alpha >= 0 && alpha <= 1)) { // in contact N(0) = ContactNormal(0); N(1) = ContactNormal(1); N(2) = -(1 - alpha) * N(0); N(3) = -(1 - alpha) * N(1); N(4) = -(alpha) * N(0); N(5) = -(alpha) * N(1); T(0) = ContactTangent(0); T(1) = ContactTangent(1); T(2) = -(1-alpha) * T(0); T(3) = -(1-alpha) * T(1); T(4) = -(alpha) * T(0); T(5) = -(alpha) * T(1); return 1; } else { return 0; // Not in contact } }
void LEPlic :: doLagrangianPhase(TimeStep *atTime) { //Maps element nodes along trajectories using basic Runge-Kutta method (midpoint rule) int i, ci, ndofman = domain->giveNumberOfDofManagers(); int nsd = 2; double dt = atTime->giveTimeIncrement(); DofManager *dman; Node *inode; IntArray velocityMask; FloatArray x, x2(nsd), v_t, v_tn1; FloatMatrix t; #if 1 EngngModel *emodel = domain->giveEngngModel(); int err; #endif velocityMask.setValues(2, V_u, V_v); updated_XCoords.resize(ndofman); updated_YCoords.resize(ndofman); for ( i = 1; i <= ndofman; i++ ) { dman = domain->giveDofManager(i); // skip dofmanagers with no position information if ( ( dman->giveClassID() != NodeClass ) && ( dman->giveClassID() != RigidArmNodeClass ) && ( dman->giveClassID() != HangingNodeClass ) ) { continue; } inode = ( Node * ) dman; // get node coordinates x = * ( inode->giveCoordinates() ); // get velocity field v(tn, x(tn)) for dof manager #if 1 /* Original version */ dman->giveUnknownVector( v_t, velocityMask, EID_MomentumBalance, VM_Total, atTime->givePreviousStep() ); /* Modified version */ //dman->giveUnknownVector(v_t, velocityMask, EID_MomentumBalance, VM_Total, atTime); // Original version // compute updated position x(tn)+0.5*dt*v(tn,x(tn)) for ( ci = 1; ci <= nsd; ci++ ) { x2.at(ci) = x.at(ci) + 0.5 *dt *v_t.at(ci); } // compute interpolated velocity field at x2 [ v(tn+1, x(tn)+0.5*dt*v(tn,x(tn))) = v(tn+1, x2) ] Field *vfield; vfield = emodel->giveContext()->giveFieldManager()->giveField(FT_Velocity); if ( vfield == NULL ) { _error("doLagrangianPhase: Velocity field not available"); } err = vfield->evaluateAt(v_tn1, x2, VM_Total, atTime); if ( err == 1 ) { // point outside domain -> be explicit v_tn1 = v_t; } else if ( err != 0 ) { _error2("doLagrangianPhase: vfield->evaluateAt failed, error code %d", err); } // compute final updated position for ( ci = 1; ci <= nsd; ci++ ) { x2.at(ci) = x.at(ci) + dt *v_tn1.at(ci); } #else // pure explicit version dman->giveUnknownVector(v_t, velocityMask, EID_MomentumBalance, VM_Total, atTime); for ( ci = 1; ci <= nsd; ci++ ) { x2.at(ci) = x.at(ci) + dt *v_t.at(ci); } #endif // store updated node position updated_XCoords.at(i) = x2.at(1); updated_YCoords.at(i) = x2.at(2); } }
void VCharUnit::run() { VChar x1('x'); VChar x2(0x78); VUNIT_ASSERT_EQUAL_LABELED(x1, 'x', "character ctor"); VUNIT_ASSERT_EQUAL_LABELED(x2, 'x', "integer ctor"); VUNIT_ASSERT_EQUAL_LABELED(x1, x2, "ctor equality"); x1 = 'y'; x2 = 0x79; VUNIT_ASSERT_EQUAL_LABELED(x1, 'y', "character assignment"); VUNIT_ASSERT_EQUAL_LABELED(x2, 'y', "integer assignment"); VUNIT_ASSERT_EQUAL_LABELED(x1, x2, "assignment equality"); x1 = 'a'; VUNIT_ASSERT_TRUE_LABELED(x1.isLowerCase(), "lower case"); VUNIT_ASSERT_TRUE_LABELED(! x1.isUpperCase(), "not upper case"); x2 = 'A'; VUNIT_ASSERT_TRUE_LABELED(! x2.isLowerCase(), "not lower case"); VUNIT_ASSERT_TRUE_LABELED(x2.isUpperCase(), "upper case"); x2.toLowerCase(); VUNIT_ASSERT_TRUE_LABELED(x2.isLowerCase(), "to lower case"); VUNIT_ASSERT_EQUAL_LABELED(x2, x1, "to lower case equality"); x1.toUpperCase(); VUNIT_ASSERT_TRUE_LABELED(x1.isUpperCase(), "to upper case"); VUNIT_ASSERT_EQUAL_LABELED(x1, 'A', "to upper case equality"); x1 = 'b'; VChar bigB = x1.upperCase(); VUNIT_ASSERT_EQUAL_LABELED(bigB, 'B', "return upper case"); VChar littleB = bigB.lowerCase(); VUNIT_ASSERT_EQUAL_LABELED(littleB, 'b', "return lower case"); VUNIT_ASSERT_EQUAL_LABELED(littleB.charValue(), 'b', "char value"); VUNIT_ASSERT_EQUAL_LABELED(littleB.intValue(), 0x62, "int value"); x1.set('c'); VUNIT_ASSERT_EQUAL_LABELED(x1, 'c', "set char"); x1.set(0x64); VUNIT_ASSERT_EQUAL_LABELED(x1, 'd', "set int"); x1 = 'd'; char littleD = x1; VUNIT_ASSERT_EQUAL_LABELED(littleD, 'd', "operator char"); VChar i1('i'); VChar i2('i'); VChar j1('j'); VChar j2('j'); VUNIT_ASSERT_TRUE_LABELED(i1 != j1, "inequality"); VUNIT_ASSERT_TRUE_LABELED(i1 < j1, "LT"); VUNIT_ASSERT_TRUE_LABELED(!(i1 < i2), "not LT"); VUNIT_ASSERT_TRUE_LABELED(j1 > i1, "GT"); VUNIT_ASSERT_TRUE_LABELED(!(j1 > j2), "not GT"); VUNIT_ASSERT_TRUE_LABELED(i1 <= i2, "LTE 1"); VUNIT_ASSERT_TRUE_LABELED(i1 <= j1, "LTE 2"); VUNIT_ASSERT_TRUE_LABELED(j1 >= j2, "GTE 1"); VUNIT_ASSERT_TRUE_LABELED(j1 >= i1, "GTE 2"); VUNIT_ASSERT_TRUE_LABELED(!(j1 <= i1), "not LTE"); VUNIT_ASSERT_TRUE_LABELED(!(i1 >= j1), "not GTE"); VUNIT_ASSERT_TRUE_LABELED(VChar::equalsIgnoreCase(VChar('x'), VChar('X')), "equalsIgnoreCase 1"); VUNIT_ASSERT_TRUE_LABELED(VChar::equalsIgnoreCase('x', VChar('X')), "equalsIgnoreCase 2"); VUNIT_ASSERT_TRUE_LABELED(VChar::equalsIgnoreCase(VChar('x'), 'X'), "equalsIgnoreCase 3"); VUNIT_ASSERT_TRUE_LABELED(VChar::equalsIgnoreCase('x', 'X'), "equalsIgnoreCase 4"); VUNIT_ASSERT_TRUE_LABELED(VChar::equalsIgnoreCase(VChar('5'), VChar('5')), "equalsIgnoreCase 5"); // test numbers VUNIT_ASSERT_TRUE_LABELED(VChar::equalsIgnoreCase(VChar('!'), VChar('!')), "equalsIgnoreCase 6"); // test punctuation VUNIT_ASSERT_TRUE_LABELED(VChar::equalsIgnoreCase(VChar(' '), VChar(' ')), "equalsIgnoreCase 7"); // test whitespace VUNIT_ASSERT_FALSE_LABELED(VChar::equalsIgnoreCase(VChar('x'), VChar('y')), "!equalsIgnoreCase 1"); VUNIT_ASSERT_FALSE_LABELED(VChar::equalsIgnoreCase('x', VChar('y')), "!equalsIgnoreCase 2"); VUNIT_ASSERT_FALSE_LABELED(VChar::equalsIgnoreCase(VChar('x'), 'y'), "!equalsIgnoreCase 3"); VUNIT_ASSERT_FALSE_LABELED(VChar::equalsIgnoreCase('x', 'y'), "!equalsIgnoreCase 4"); VUNIT_ASSERT_FALSE_LABELED(VChar::equalsIgnoreCase(VChar('5'), VChar('6')), "!equalsIgnoreCase 5"); // test numbers VUNIT_ASSERT_FALSE_LABELED(VChar::equalsIgnoreCase(VChar('!'), VChar('@')), "!equalsIgnoreCase 6"); // test punctuation VUNIT_ASSERT_FALSE_LABELED(VChar::equalsIgnoreCase(VChar(' '), VChar('\t')), "!equalsIgnoreCase 7"); // test whitespace // Test the known ranges of alpha/numeric/whitespace values. for (int i = 0; i < 256; ++i) { VChar c(i); if ((i <= 0x20) || (i == 0x7F)) { // This is the range VChar considers "whitespace". this->test( !c.isLowerCase() && !c.isUpperCase() && (c.intValue() == i) && !c.isAlpha() && !c.isNumeric() && !c.isAlphaNumeric() && c.isWhitespace(), VSTRING_FORMAT("%d char properties", i)); } else if (i <= 0x2F) { // This is all punctuation. this->test( !c.isLowerCase() && !c.isUpperCase() && (c.intValue() == i) && !c.isAlpha() && !c.isNumeric() && !c.isAlphaNumeric() && !c.isWhitespace(), VSTRING_FORMAT("%d char properties", i)); } else if (i <= 0x39) { // This is 0 thru 9. this->test( !c.isLowerCase() && !c.isUpperCase() && (c.intValue() == i) && !c.isAlpha() && c.isNumeric() && c.isAlphaNumeric() && !c.isWhitespace(), VSTRING_FORMAT("%d char properties", i)); } else if (i <= 0x40) { // This is all punctuation. this->test( !c.isLowerCase() && !c.isUpperCase() && (c.intValue() == i) && !c.isAlpha() && !c.isNumeric() && !c.isAlphaNumeric() && !c.isWhitespace(), VSTRING_FORMAT("%d char properties", i)); } else if (i <= 0x5A) { // This is A thru Z. this->test( !c.isLowerCase() && c.isUpperCase() && (c.intValue() == i) && c.isAlpha() && !c.isNumeric() && c.isAlphaNumeric() && !c.isWhitespace(), VSTRING_FORMAT("%d char properties", i)); } else if (i <= 0x60) { // This is all punctuation. this->test( !c.isLowerCase() && !c.isUpperCase() && (c.intValue() == i) && !c.isAlpha() && !c.isNumeric() && !c.isAlphaNumeric() && !c.isWhitespace(), VSTRING_FORMAT("%d char properties", i)); } else if (i <= 0x7A) { // This is a thru z. this->test( c.isLowerCase() && !c.isUpperCase() && (c.intValue() == i) && c.isAlpha() && !c.isNumeric() && c.isAlphaNumeric() && !c.isWhitespace(), VSTRING_FORMAT("%d char properties", i)); } else if (i <= 0x7E) { // This is all punctuation. this->test( !c.isLowerCase() && !c.isUpperCase() && (c.intValue() == i) && !c.isAlpha() && !c.isNumeric() && !c.isAlphaNumeric() && !c.isWhitespace(), VSTRING_FORMAT("%d char properties", i)); } else { // (we already checked 0x7F) so 0x80 <= i <= 0xFF // Properties of stuff at 0x80 and higher are not well-defined // and may vary based on the platform's ideas about upper case, // lower case, alphanumeric-ness, etc. Just test the basics. this->test( (c.intValue() == i) && !c.isWhitespace(), VSTRING_FORMAT("%d char properties", i)); } } }
void ApplyNonMaximumSuppresion(std::vector< kstate >& in_source, float in_nms_threshold) { std::vector< kstate > tmp_source = in_source; if (tmp_source.empty()) return ; unsigned int size = in_source.size(); std::vector<float> area(size); std::vector<float> scores(size); std::vector<int> x1(size); std::vector<int> y1(size); std::vector<int> x2(size); std::vector<int> y2(size); std::vector<unsigned int> indices(size); std::vector<bool> is_suppresed(size); for(unsigned int i = 0; i< in_source.size(); i++) { kstate tmp = in_source[i]; area[i] = tmp.pos.width * tmp.pos.height; indices[i] = i; is_suppresed[i] = false; scores[i] = tmp.score; x1[i] = tmp.pos.x; y1[i] = tmp.pos.y; x2[i] = tmp.pos.width + tmp.pos.x; y2[i] = tmp.pos.height + tmp.pos.y; } Sort(scores, indices);//returns indices ordered based on scores for(unsigned int i=0; i< size; i++) { if(!is_suppresed[indices[i]]) { for(unsigned int j= i+1; j< size; j++) { int x1_max = std::max(x1[indices[i]], x1[indices[j]]); int x2_min = std::min(x2[indices[i]], x2[indices[j]]); int y1_max = std::max(y1[indices[i]], y1[indices[j]]); int y2_min = std::min(y2[indices[i]], y2[indices[j]]); int overlap_width = x2_min - x1_max + 1; int overlap_height = y2_min - y1_max + 1; if(overlap_width > 0 && overlap_height>0) { float overlap_part = (overlap_width*overlap_height)/area[indices[j]]; if(overlap_part > in_nms_threshold) { is_suppresed[indices[j]] = true; } } } } } unsigned int size_out = 0; for (unsigned int i = 0; i < size; i++) { if (!is_suppresed[i]) size_out++; } std::vector< kstate > filtered_detections(size_out); unsigned int index = 0; for(unsigned int i = 0 ; i < size_out; i++) { if(!is_suppresed[indices[i]]) { filtered_detections[index] = in_source[indices[i]];//x1[indices[i]]; index++; } } in_source = filtered_detections; }
// ** Temporary version int ClpPdco::pdco( ClpPdcoBase * stuff, Options &options, Info &info, Outfo &outfo) { // D1, D2 are positive-definite diagonal matrices defined from d1, d2. // In particular, d2 indicates the accuracy required for // satisfying each row of Ax = b. // // D1 and D2 (via d1 and d2) provide primal and dual regularization // respectively. They ensure that the primal and dual solutions // (x,r) and (y,z) are unique and bounded. // // A scalar d1 is equivalent to d1 = ones(n,1), D1 = diag(d1). // A scalar d2 is equivalent to d2 = ones(m,1), D2 = diag(d2). // Typically, d1 = d2 = 1e-4. // These values perturb phi(x) only slightly (by about 1e-8) and request // that A*x = b be satisfied quite accurately (to about 1e-8). // Set d1 = 1e-4, d2 = 1 for least-squares problems with bound constraints. // The problem is then // // minimize phi(x) + 1/2 norm(d1*x)^2 + 1/2 norm(A*x - b)^2 // subject to bl <= x <= bu. // // More generally, d1 and d2 may be n and m vectors containing any positive // values (preferably not too small, and typically no larger than 1). // Bigger elements of d1 and d2 improve the stability of the solver. // // At an optimal solution, if x(j) is on its lower or upper bound, // the corresponding z(j) is positive or negative respectively. // If x(j) is between its bounds, z(j) = 0. // If bl(j) = bu(j), x(j) is fixed at that value and z(j) may have // either sign. // // Also, r and y satisfy r = D2 y, so that Ax + D2^2 y = b. // Thus if d2(i) = 1e-4, the i-th row of Ax = b will be satisfied to // approximately 1e-8. This determines how large d2(i) can safely be. // // // EXTERNAL FUNCTIONS: // options = pdcoSet; provided with pdco.m // [obj,grad,hess] = pdObj( x ); provided by user // y = pdMat( name,mode,m,n,x ); provided by user if pdMat // is a string, not a matrix // // INPUT ARGUMENTS: // pdObj is a string containing the name of a function pdObj.m // or a function_handle for such a function // such that [obj,grad,hess] = pdObj(x) defines // obj = phi(x) : a scalar, // grad = gradient of phi(x) : an n-vector, // hess = diag(Hessian of phi): an n-vector. // Examples: // If phi(x) is the linear function c"x, pdObj should return // [obj,grad,hess] = [c"*x, c, zeros(n,1)]. // If phi(x) is the entropy function E(x) = sum x(j) log x(j), // [obj,grad,hess] = [E(x), log(x)+1, 1./x]. // pdMat may be an ifexplicit m x n matrix A (preferably sparse!), // or a string containing the name of a function pdMat.m // or a function_handle for such a function // such that y = pdMat( name,mode,m,n,x ) // returns y = A*x (mode=1) or y = A"*x (mode=2). // The input parameter "name" will be the string pdMat. // b is an m-vector. // bl is an n-vector of lower bounds. Non-existent bounds // may be represented by bl(j) = -Inf or bl(j) <= -1e+20. // bu is an n-vector of upper bounds. Non-existent bounds // may be represented by bu(j) = Inf or bu(j) >= 1e+20. // d1, d2 may be positive scalars or positive vectors (see above). // options is a structure that may be set and altered by pdcoSet // (type help pdcoSet). // x0, y0, z0 provide an initial solution. // xsize, zsize are estimates of the biggest x and z at the solution. // They are used to scale (x,y,z). Good estimates // should improve the performance of the barrier method. // // // OUTPUT ARGUMENTS: // x is the primal solution. // y is the dual solution associated with Ax + D2 r = b. // z is the dual solution associated with bl <= x <= bu. // inform = 0 if a solution is found; // = 1 if too many iterations were required; // = 2 if the linesearch failed too often. // PDitns is the number of Primal-Dual Barrier iterations required. // CGitns is the number of Conjugate-Gradient iterations required // if an iterative solver is used (LSQR). // time is the cpu time used. //---------------------------------------------------------------------- // PRIVATE FUNCTIONS: // pdxxxbounds // pdxxxdistrib // pdxxxlsqr // pdxxxlsqrmat // pdxxxmat // pdxxxmerit // pdxxxresid1 // pdxxxresid2 // pdxxxstep // // GLOBAL VARIABLES: // global pdDDD1 pdDDD2 pdDDD3 // // // NOTES: // The matrix A should be reasonably well scaled: norm(A,inf) =~ 1. // The vector b and objective phi(x) may be of any size, but ensure that // xsize and zsize are reasonably close to norm(x,inf) and norm(z,inf) // at the solution. // // The files defining pdObj and pdMat // must not be called Fname.m or Aname.m!! // // // AUTHOR: // Michael Saunders, Systems Optimization Laboratory (SOL), // Stanford University, Stanford, California, USA. // [email protected] // // CONTRIBUTORS: // Byunggyoo Kim, SOL, Stanford University. // [email protected] // // DEVELOPMENT: // 20 Jun 1997: Original version of pdsco.m derived from pdlp0.m. // 29 Sep 2002: Original version of pdco.m derived from pdsco.m. // Introduced D1, D2 in place of gamma*I, delta*I // and allowed for general bounds bl <= x <= bu. // 06 Oct 2002: Allowed for fixed variabes: bl(j) = bu(j) for any j. // 15 Oct 2002: Eliminated some work vectors (since m, n might be LARGE). // Modularized residuals, linesearch // 16 Oct 2002: pdxxx..., pdDDD... names rationalized. // pdAAA eliminated (global copy of A). // Aname is now used directly as an ifexplicit A or a function. // NOTE: If Aname is a function, it now has an extra parameter. // 23 Oct 2002: Fname and Aname can now be function handles. // 01 Nov 2002: Bug fixed in feval in pdxxxmat. //----------------------------------------------------------------------- // global pdDDD1 pdDDD2 pdDDD3 double inf = 1.0e30; double eps = 1.0e-15; double atolold = -1.0, r3ratio = -1.0, Pinf, Dinf, Cinf, Cinf0; printf("\n --------------------------------------------------------"); printf("\n pdco.m Version of 01 Nov 2002"); printf("\n Primal-dual barrier method to minimize a convex function"); printf("\n subject to linear constraints Ax + r = b, bl <= x <= bu"); printf("\n --------------------------------------------------------\n"); int m = numberRows_; int n = numberColumns_; bool ifexplicit = true; CoinDenseVector<double> b(m, rhs_); CoinDenseVector<double> x(n, x_); CoinDenseVector<double> y(m, y_); CoinDenseVector<double> z(n, dj_); //delete old arrays delete [] rhs_; delete [] x_; delete [] y_; delete [] dj_; rhs_ = NULL; x_ = NULL; y_ = NULL; dj_ = NULL; // Save stuff so available elsewhere pdcoStuff_ = stuff; double normb = b.infNorm(); double normx0 = x.infNorm(); double normy0 = y.infNorm(); double normz0 = z.infNorm(); printf("\nmax |b | = %8g max |x0| = %8g", normb , normx0); printf( " xsize = %8g", xsize_); printf("\nmax |y0| = %8g max |z0| = %8g", normy0, normz0); printf( " zsize = %8g", zsize_); //--------------------------------------------------------------------- // Initialize. //--------------------------------------------------------------------- //true = 1; //false = 0; //zn = zeros(n,1); //int nb = n + m; int CGitns = 0; int inform = 0; //--------------------------------------------------------------------- // Only allow scalar d1, d2 for now //--------------------------------------------------------------------- /* if (d1_->size()==1) d1_->resize(n, d1_->getElements()[0]); // Allow scalar d1, d2 if (d2_->size()==1) d2->resize(m, d2->getElements()[0]); // to mean dk * unit vector */ assert (stuff->sizeD1() == 1); double d1 = stuff->getD1(); double d2 = stuff->getD2(); //--------------------------------------------------------------------- // Grab input options. //--------------------------------------------------------------------- int maxitn = options.MaxIter; double featol = options.FeaTol; double opttol = options.OptTol; double steptol = options.StepTol; int stepSame = 1; /* options.StepSame; // 1 means stepx == stepz */ double x0min = options.x0min; double z0min = options.z0min; double mu0 = options.mu0; int LSproblem = options.LSproblem; // See below int LSmethod = options.LSmethod; // 1=Cholesky 2=QR 3=LSQR int itnlim = options.LSQRMaxIter * CoinMin(m, n); double atol1 = options.LSQRatol1; // Initial atol double atol2 = options.LSQRatol2; // Smallest atol,unless atol1 is smaller double conlim = options.LSQRconlim; //int wait = options.wait; // LSproblem: // 1 = dy 2 = dy shifted, DLS // 11 = s 12 = s shifted, DLS (dx = Ds) // 21 = dx // 31 = 3x3 system, symmetrized by Z^{1/2} // 32 = 2x2 system, symmetrized by X^{1/2} //--------------------------------------------------------------------- // Set other parameters. //--------------------------------------------------------------------- int kminor = 0; // 1 stops after each iteration double eta = 1e-4; // Linesearch tolerance for "sufficient descent" double maxf = 10; // Linesearch backtrack limit (function evaluations) double maxfail = 1; // Linesearch failure limit (consecutive iterations) double bigcenter = 1e+3; // mu is reduced if center < bigcenter. // Parameters for LSQR. double atolmin = eps; // Smallest atol if linesearch back-tracks double btol = 0; // Should be small (zero is ok) double show = false; // Controls lsqr iteration log /* double gamma = d1->infNorm(); double delta = d2->infNorm(); */ double gamma = d1; double delta = d2; printf("\n\nx0min = %8g featol = %8.1e", x0min, featol); printf( " d1max = %8.1e", gamma); printf( "\nz0min = %8g opttol = %8.1e", z0min, opttol); printf( " d2max = %8.1e", delta); printf( "\nmu0 = %8.1e steptol = %8g", mu0 , steptol); printf( " bigcenter= %8g" , bigcenter); printf("\n\nLSQR:"); printf("\natol1 = %8.1e atol2 = %8.1e", atol1 , atol2 ); printf( " btol = %8.1e", btol ); printf("\nconlim = %8.1e itnlim = %8d" , conlim, itnlim); printf( " show = %8g" , show ); // LSmethod = 3; ////// Hardwire LSQR // LSproblem = 1; ////// and LS problem defining "dy". /* if wait printf("\n\nReview parameters... then type "return"\n") keyboard end */ if (eta < 0) printf("\n\nLinesearch disabled by eta < 0"); //--------------------------------------------------------------------- // All parameters have now been set. //--------------------------------------------------------------------- double time = CoinCpuTime(); //bool useChol = (LSmethod == 1); //bool useQR = (LSmethod == 2); bool direct = (LSmethod <= 2 && ifexplicit); char solver[7]; strncpy(solver, " LSQR", 7); //--------------------------------------------------------------------- // Categorize bounds and allow for fixed variables by modifying b. //--------------------------------------------------------------------- int nlow, nupp, nfix; int *bptrs[3] = {0}; getBoundTypes(&nlow, &nupp, &nfix, bptrs ); int *low = bptrs[0]; int *upp = bptrs[1]; int *fix = bptrs[2]; int nU = n; if (nupp == 0) nU = 1; //Make dummy vectors if no Upper bounds //--------------------------------------------------------------------- // Get pointers to local copy of model bounds //--------------------------------------------------------------------- CoinDenseVector<double> bl(n, columnLower_); double *bl_elts = bl.getElements(); CoinDenseVector<double> bu(nU, columnUpper_); // this is dummy if no UB double *bu_elts = bu.getElements(); CoinDenseVector<double> r1(m, 0.0); double *r1_elts = r1.getElements(); CoinDenseVector<double> x1(n, 0.0); double *x1_elts = x1.getElements(); if (nfix > 0) { for (int k = 0; k < nfix; k++) x1_elts[fix[k]] = bl[fix[k]]; matVecMult(1, r1, x1); b = b - r1; // At some stage, might want to look at normfix = norm(r1,inf); } //--------------------------------------------------------------------- // Scale the input data. // The scaled variables are // xbar = x/beta, // ybar = y/zeta, // zbar = z/zeta. // Define // theta = beta*zeta; // The scaled function is // phibar = ( 1 /theta) fbar(beta*xbar), // gradient = (beta /theta) grad, // Hessian = (beta2/theta) hess. //--------------------------------------------------------------------- double beta = xsize_; if (beta == 0) beta = 1; // beta scales b, x. double zeta = zsize_; if (zeta == 0) zeta = 1; // zeta scales y, z. double theta = beta * zeta; // theta scales obj. // (theta could be anything, but theta = beta*zeta makes // scaled grad = grad/zeta = 1 approximately if zeta is chosen right.) for (int k = 0; k < nlow; k++) bl_elts[low[k]] = bl_elts[low[k]] / beta; for (int k = 0; k < nupp; k++) bu_elts[upp[k]] = bu_elts[upp[k]] / beta; d1 = d1 * ( beta / sqrt(theta) ); d2 = d2 * ( sqrt(theta) / beta ); double beta2 = beta * beta; b.scale( (1.0 / beta) ); y.scale( (1.0 / zeta) ); x.scale( (1.0 / beta) ); z.scale( (1.0 / zeta) ); //--------------------------------------------------------------------- // Initialize vectors that are not fully used if bounds are missing. //--------------------------------------------------------------------- CoinDenseVector<double> rL(n, 0.0); CoinDenseVector<double> cL(n, 0.0); CoinDenseVector<double> z1(n, 0.0); CoinDenseVector<double> dx1(n, 0.0); CoinDenseVector<double> dz1(n, 0.0); CoinDenseVector<double> r2(n, 0.0); // Assign upper bd regions (dummy if no UBs) CoinDenseVector<double> rU(nU, 0.0); CoinDenseVector<double> cU(nU, 0.0); CoinDenseVector<double> x2(nU, 0.0); CoinDenseVector<double> z2(nU, 0.0); CoinDenseVector<double> dx2(nU, 0.0); CoinDenseVector<double> dz2(nU, 0.0); //--------------------------------------------------------------------- // Initialize x, y, z, objective, etc. //--------------------------------------------------------------------- CoinDenseVector<double> dx(n, 0.0); CoinDenseVector<double> dy(m, 0.0); CoinDenseVector<double> Pr(m); CoinDenseVector<double> D(n); double *D_elts = D.getElements(); CoinDenseVector<double> w(n); double *w_elts = w.getElements(); CoinDenseVector<double> rhs(m + n); //--------------------------------------------------------------------- // Pull out the element array pointers for efficiency //--------------------------------------------------------------------- double *x_elts = x.getElements(); double *x2_elts = x2.getElements(); double *z_elts = z.getElements(); double *z1_elts = z1.getElements(); double *z2_elts = z2.getElements(); for (int k = 0; k < nlow; k++) { x_elts[low[k]] = CoinMax( x_elts[low[k]], bl[low[k]]); x1_elts[low[k]] = CoinMax( x_elts[low[k]] - bl[low[k]], x0min ); z1_elts[low[k]] = CoinMax( z_elts[low[k]], z0min ); } for (int k = 0; k < nupp; k++) { x_elts[upp[k]] = CoinMin( x_elts[upp[k]], bu[upp[k]]); x2_elts[upp[k]] = CoinMax(bu[upp[k]] - x_elts[upp[k]], x0min ); z2_elts[upp[k]] = CoinMax(-z_elts[upp[k]], z0min ); } //////////////////// Assume hessian is diagonal. ////////////////////// // [obj,grad,hess] = feval( Fname, (x*beta) ); x.scale(beta); double obj = getObj(x); CoinDenseVector<double> grad(n); getGrad(x, grad); CoinDenseVector<double> H(n); getHessian(x , H); x.scale((1.0 / beta)); //double * g_elts = grad.getElements(); double * H_elts = H.getElements(); obj /= theta; // Scaled obj. grad = grad * (beta / theta) + (d1 * d1) * x; // grad includes x regularization. H = H * (beta2 / theta) + (d1 * d1) ; // H includes x regularization. /*--------------------------------------------------------------------- // Compute primal and dual residuals: // r1 = b - Aprod(x) - d2*d2*y; // r2 = grad - Atprod(y) + z2 - z1; // rL = bl - x + x1; // rU = x + x2 - bu; */ //--------------------------------------------------------------------- // [r1,r2,rL,rU,Pinf,Dinf] = ... // pdxxxresid1( Aname,fix,low,upp, ... // b,bl,bu,d1,d2,grad,rL,rU,x,x1,x2,y,z1,z2 ); pdxxxresid1( this, nlow, nupp, nfix, low, upp, fix, b, bl_elts, bu_elts, d1, d2, grad, rL, rU, x, x1, x2, y, z1, z2, r1, r2, &Pinf, &Dinf); //--------------------------------------------------------------------- // Initialize mu and complementarity residuals: // cL = mu*e - X1*z1. // cU = mu*e - X2*z2. // // 25 Jan 2001: Now that b and obj are scaled (and hence x,y,z), // we should be able to use mufirst = mu0 (absolute value). // 0.1 worked poorly on StarTest1 with x0min = z0min = 0.1. // 29 Jan 2001: We might as well use mu0 = x0min * z0min; // so that most variables are centered after a warm start. // 29 Sep 2002: Use mufirst = mu0*(x0min * z0min), // regarding mu0 as a scaling of the initial center. //--------------------------------------------------------------------- // double mufirst = mu0*(x0min * z0min); double mufirst = mu0; // revert to absolute value double mulast = 0.1 * opttol; mulast = CoinMin( mulast, mufirst ); double mu = mufirst; double center, fmerit; pdxxxresid2( mu, nlow, nupp, low, upp, cL, cU, x1, x2, z1, z2, ¢er, &Cinf, &Cinf0 ); fmerit = pdxxxmerit(nlow, nupp, low, upp, r1, r2, rL, rU, cL, cU ); // Initialize other things. bool precon = true; double PDitns = 0; //bool converged = false; double atol = atol1; atol2 = CoinMax( atol2, atolmin ); atolmin = atol2; // pdDDD2 = d2; // Global vector for diagonal matrix D2 // Iteration log. int nf = 0; int itncg = 0; int nfail = 0; printf("\n\nItn mu stepx stepz Pinf Dinf"); printf(" Cinf Objective nf center"); if (direct) { printf("\n"); } else { printf(" atol solver Inexact\n"); } double regx = (d1 * x).twoNorm(); double regy = (d2 * y).twoNorm(); // regterm = twoNorm(d1.*x)^2 + norm(d2.*y)^2; double regterm = regx * regx + regy * regy; double objreg = obj + 0.5 * regterm; double objtrue = objreg * theta; printf("\n%3g ", PDitns ); printf("%6.1f%6.1f" , log10(Pinf ), log10(Dinf)); printf("%6.1f%15.7e", log10(Cinf0), objtrue ); printf(" %8.1f\n" , center ); /* if kminor printf("\n\nStart of first minor itn...\n"); keyboard end */ //--------------------------------------------------------------------- // Main loop. //--------------------------------------------------------------------- // Lsqr ClpLsqr thisLsqr(this); // while (converged) { while(PDitns < maxitn) { PDitns = PDitns + 1; // 31 Jan 2001: Set atol according to progress, a la Inexact Newton. // 07 Feb 2001: 0.1 not small enough for Satellite problem. Try 0.01. // 25 Apr 2001: 0.01 seems wasteful for Star problem. // Now that starting conditions are better, go back to 0.1. double r3norm = CoinMax(Pinf, CoinMax(Dinf, Cinf)); atol = CoinMin(atol, r3norm * 0.1); atol = CoinMax(atol, atolmin ); info.r3norm = r3norm; //------------------------------------------------------------------- // Define a damped Newton iteration for solving f = 0, // keeping x1, x2, z1, z2 > 0. We eliminate dx1, dx2, dz1, dz2 // to obtain the system // // [-H2 A" ] [ dx ] = [ w ], H2 = H + D1^2 + X1inv Z1 + X2inv Z2, // [ A D2^2] [ dy ] = [ r1] w = r2 - X1inv(cL + Z1 rL) // + X2inv(cU + Z2 rU), // // which is equivalent to the least-squares problem // // min || [ D A"]dy - [ D w ] ||, D = H2^{-1/2}. (*) // || [ D2 ] [D2inv r1] || //------------------------------------------------------------------- for (int k = 0; k < nlow; k++) H_elts[low[k]] = H_elts[low[k]] + z1[low[k]] / x1[low[k]]; for (int k = 0; k < nupp; k++) H[upp[k]] = H[upp[k]] + z2[upp[k]] / x2[upp[k]]; w = r2; for (int k = 0; k < nlow; k++) w[low[k]] = w[low[k]] - (cL[low[k]] + z1[low[k]] * rL[low[k]]) / x1[low[k]]; for (int k = 0; k < nupp; k++) w[upp[k]] = w[upp[k]] + (cU[upp[k]] + z2[upp[k]] * rU[upp[k]]) / x2[upp[k]]; if (LSproblem == 1) { //----------------------------------------------------------------- // Solve (*) for dy. //----------------------------------------------------------------- H = 1.0 / H; // H is now Hinv (NOTE!) for (int k = 0; k < nfix; k++) H[fix[k]] = 0; for (int k = 0; k < n; k++) D_elts[k] = sqrt(H_elts[k]); thisLsqr.borrowDiag1(D_elts); thisLsqr.diag2_ = d2; if (direct) { // Omit direct option for now } else {// Iterative solve using LSQR. //rhs = [ D.*w; r1./d2 ]; for (int k = 0; k < n; k++) rhs[k] = D_elts[k] * w_elts[k]; for (int k = 0; k < m; k++) rhs[n+k] = r1_elts[k] * (1.0 / d2); double damp = 0; if (precon) { // Construct diagonal preconditioner for LSQR matPrecon(d2, Pr, D); } /* rw(7) = precon; info.atolmin = atolmin; info.r3norm = fmerit; // Must be the 2-norm here. [ dy, istop, itncg, outfo ] = ... pdxxxlsqr( nb,m,"pdxxxlsqrmat",Aname,rw,rhs,damp, ... atol,btol,conlim,itnlim,show,info ); thisLsqr.input->rhs_vec = &rhs; thisLsqr.input->sol_vec = &dy; thisLsqr.input->rel_mat_err = atol; thisLsqr.do_lsqr(this); */ // New version of lsqr int istop; dy.clear(); show = false; info.atolmin = atolmin; info.r3norm = fmerit; // Must be the 2-norm here. thisLsqr.do_lsqr( rhs, damp, atol, btol, conlim, itnlim, show, info, dy , &istop, &itncg, &outfo, precon, Pr); if (precon) dy = dy * Pr; if (!precon && itncg > 999999) precon = true; if (istop == 3 || istop == 7 ) // conlim or itnlim printf("\n LSQR stopped early: istop = //%d", istop); atolold = outfo.atolold; atol = outfo.atolnew; r3ratio = outfo.r3ratio; }// LSproblem 1 // grad = pdxxxmat( Aname,2,m,n,dy ); // grad = A"dy grad.clear(); matVecMult(2, grad, dy); for (int k = 0; k < nfix; k++) grad[fix[k]] = 0; // grad is a work vector dx = H * (grad - w); } else { perror( "This LSproblem not yet implemented\n" ); } //------------------------------------------------------------------- CGitns += itncg; //------------------------------------------------------------------- // dx and dy are now known. Get dx1, dx2, dz1, dz2. //------------------------------------------------------------------- for (int k = 0; k < nlow; k++) { dx1[low[k]] = - rL[low[k]] + dx[low[k]]; dz1[low[k]] = (cL[low[k]] - z1[low[k]] * dx1[low[k]]) / x1[low[k]]; } for (int k = 0; k < nupp; k++) { dx2[upp[k]] = - rU[upp[k]] - dx[upp[k]]; dz2[upp[k]] = (cU[upp[k]] - z2[upp[k]] * dx2[upp[k]]) / x2[upp[k]]; } //------------------------------------------------------------------- // Find the maximum step. //-------------------------------------------------------------------- double stepx1 = pdxxxstep(nlow, low, x1, dx1 ); double stepx2 = inf; if (nupp > 0) stepx2 = pdxxxstep(nupp, upp, x2, dx2 ); double stepz1 = pdxxxstep( z1 , dz1 ); double stepz2 = inf; if (nupp > 0) stepz2 = pdxxxstep( z2 , dz2 ); double stepx = CoinMin( stepx1, stepx2 ); double stepz = CoinMin( stepz1, stepz2 ); stepx = CoinMin( steptol * stepx, 1.0 ); stepz = CoinMin( steptol * stepz, 1.0 ); if (stepSame) { // For NLPs, force same step stepx = CoinMin( stepx, stepz ); // (true Newton method) stepz = stepx; } //------------------------------------------------------------------- // Backtracking linesearch. //------------------------------------------------------------------- bool fail = true; nf = 0; while (nf < maxf) { nf = nf + 1; x = x + stepx * dx; y = y + stepz * dy; for (int k = 0; k < nlow; k++) { x1[low[k]] = x1[low[k]] + stepx * dx1[low[k]]; z1[low[k]] = z1[low[k]] + stepz * dz1[low[k]]; } for (int k = 0; k < nupp; k++) { x2[upp[k]] = x2[upp[k]] + stepx * dx2[upp[k]]; z2[upp[k]] = z2[upp[k]] + stepz * dz2[upp[k]]; } // [obj,grad,hess] = feval( Fname, (x*beta) ); x.scale(beta); obj = getObj(x); getGrad(x, grad); getHessian(x, H); x.scale((1.0 / beta)); obj /= theta; grad = grad * (beta / theta) + d1 * d1 * x; H = H * (beta2 / theta) + d1 * d1; // [r1,r2,rL,rU,Pinf,Dinf] = ... pdxxxresid1( this, nlow, nupp, nfix, low, upp, fix, b, bl_elts, bu_elts, d1, d2, grad, rL, rU, x, x1, x2, y, z1, z2, r1, r2, &Pinf, &Dinf ); //double center, Cinf, Cinf0; // [cL,cU,center,Cinf,Cinf0] = ... pdxxxresid2( mu, nlow, nupp, low, upp, cL, cU, x1, x2, z1, z2, ¢er, &Cinf, &Cinf0); double fmeritnew = pdxxxmerit(nlow, nupp, low, upp, r1, r2, rL, rU, cL, cU ); double step = CoinMin( stepx, stepz ); if (fmeritnew <= (1 - eta * step)*fmerit) { fail = false; break; } // Merit function didn"t decrease. // Restore variables to previous values. // (This introduces a little error, but save lots of space.) x = x - stepx * dx; y = y - stepz * dy; for (int k = 0; k < nlow; k++) { x1[low[k]] = x1[low[k]] - stepx * dx1[low[k]]; z1[low[k]] = z1[low[k]] - stepz * dz1[low[k]]; } for (int k = 0; k < nupp; k++) { x2[upp[k]] = x2[upp[k]] - stepx * dx2[upp[k]]; z2[upp[k]] = z2[upp[k]] - stepz * dz2[upp[k]]; } // Back-track. // If it"s the first time, // make stepx and stepz the same. if (nf == 1 && stepx != stepz) { stepx = step; } else if (nf < maxf) { stepx = stepx / 2; } stepz = stepx; } if (fail) { printf("\n Linesearch failed (nf too big)"); nfail += 1; } else { nfail = 0; } //------------------------------------------------------------------- // Set convergence measures. //-------------------------------------------------------------------- regx = (d1 * x).twoNorm(); regy = (d2 * y).twoNorm(); regterm = regx * regx + regy * regy; objreg = obj + 0.5 * regterm; objtrue = objreg * theta; bool primalfeas = Pinf <= featol; bool dualfeas = Dinf <= featol; bool complementary = Cinf0 <= opttol; bool enough = PDitns >= 4; // Prevent premature termination. bool converged = primalfeas & dualfeas & complementary & enough; //------------------------------------------------------------------- // Iteration log. //------------------------------------------------------------------- char str1[100], str2[100], str3[100], str4[100], str5[100]; sprintf(str1, "\n%3g%5.1f" , PDitns , log10(mu) ); sprintf(str2, "%8.5f%8.5f" , stepx , stepz ); if (stepx < 0.0001 || stepz < 0.0001) { sprintf(str2, " %6.1e %6.1e" , stepx , stepz ); } sprintf(str3, "%6.1f%6.1f" , log10(Pinf) , log10(Dinf)); sprintf(str4, "%6.1f%15.7e", log10(Cinf0), objtrue ); sprintf(str5, "%3d%8.1f" , nf , center ); if (center > 99999) { sprintf(str5, "%3d%8.1e" , nf , center ); } printf("%s%s%s%s%s", str1, str2, str3, str4, str5); if (direct) { // relax } else { printf(" %5.1f%7d%7.3f", log10(atolold), itncg, r3ratio); } //------------------------------------------------------------------- // Test for termination. //------------------------------------------------------------------- if (kminor) { printf( "\nStart of next minor itn...\n"); // keyboard; } if (converged) { printf("\n Converged"); break; } else if (PDitns >= maxitn) { printf("\n Too many iterations"); inform = 1; break; } else if (nfail >= maxfail) { printf("\n Too many linesearch failures"); inform = 2; break; } else { // Reduce mu, and reset certain residuals. double stepmu = CoinMin( stepx , stepz ); stepmu = CoinMin( stepmu, steptol ); double muold = mu; mu = mu - stepmu * mu; if (center >= bigcenter) mu = muold; // mutrad = mu0*(sum(Xz)/n); // 24 May 1998: Traditional value, but // mu = CoinMin(mu,mutrad ); // it seemed to decrease mu too much. mu = CoinMax(mu, mulast); // 13 Jun 1998: No need for smaller mu. // [cL,cU,center,Cinf,Cinf0] = ... pdxxxresid2( mu, nlow, nupp, low, upp, cL, cU, x1, x2, z1, z2, ¢er, &Cinf, &Cinf0 ); fmerit = pdxxxmerit( nlow, nupp, low, upp, r1, r2, rL, rU, cL, cU ); // Reduce atol for LSQR (and SYMMLQ). // NOW DONE AT TOP OF LOOP. atolold = atol; // if atol > atol2 // atolfac = (mu/mufirst)^0.25; // atol = CoinMax( atol*atolfac, atol2 ); // end // atol = CoinMin( atol, mu ); // 22 Jan 2001: a la Inexact Newton. // atol = CoinMin( atol, 0.5*mu ); // 30 Jan 2001: A bit tighter // If the linesearch took more than one function (nf > 1), // we assume the search direction needed more accuracy // (though this may be true only for LPs). // 12 Jun 1998: Ask for more accuracy if nf > 2. // 24 Nov 2000: Also if the steps are small. // 30 Jan 2001: Small steps might be ok with warm start. // 06 Feb 2001: Not necessarily. Reinstated tests in next line. if (nf > 2 || CoinMin( stepx, stepz ) <= 0.01) atol = atolold * 0.1; } //--------------------------------------------------------------------- // End of main loop. //--------------------------------------------------------------------- } for (int k = 0; k < nfix; k++) x[fix[k]] = bl[fix[k]]; z = z1; if (nupp > 0) z = z - z2; printf("\n\nmax |x| =%10.3f", x.infNorm() ); printf(" max |y| =%10.3f", y.infNorm() ); printf(" max |z| =%10.3f", z.infNorm() ); printf(" scaled"); x.scale(beta); y.scale(zeta); z.scale(zeta); // Unscale x, y, z. printf( "\nmax |x| =%10.3f", x.infNorm() ); printf(" max |y| =%10.3f", y.infNorm() ); printf(" max |z| =%10.3f", z.infNorm() ); printf(" unscaled\n"); time = CoinCpuTime() - time; char str1[100], str2[100]; sprintf(str1, "\nPDitns =%10g", PDitns ); sprintf(str2, "itns =%10d", CGitns ); // printf( [str1 " " solver str2] ); printf(" time =%10.1f\n", time); /* pdxxxdistrib( abs(x),abs(z) ); // Private function if (wait) keyboard; */ //----------------------------------------------------------------------- // End function pdco.m //----------------------------------------------------------------------- /* printf("Solution x values:\n\n"); for (int k=0; k<n; k++) printf(" %d %e\n", k, x[k]); */ // Print distribution double thresh[9] = { 0.00000001, 0.0000001, 0.000001, 0.00001, 0.0001, 0.001, 0.01, 0.1, 1.00001}; int counts[9] = {0}; for (int ij = 0; ij < n; ij++) { for (int j = 0; j < 9; j++) { if(x[ij] < thresh[j]) { counts[j] += 1; break; } } } printf ("Distribution of Solution Values\n"); for (int j = 8; j > 1; j--) printf(" %g to %g %d\n", thresh[j-1], thresh[j], counts[j]); printf(" Less than %g %d\n", thresh[2], counts[0]); return inform; }