void* chill(int *arg) { printf(1, "Chillin' commenced.\n"); int tic, toc; tic = tim(); while((toc = tim()) < tic + (int)*arg) if(!(toc % 50)) printf(1, "%d\n", tic + (int)*arg - toc); exit(); }
int main() { int arg = 100; printf(1, "Chillin' for %d tics.\n", arg); thread_create(&chill, (void *)&arg); int toc; int tic = tim(); while((toc = tim()) < tic + 50); printf(1, "Just kidding! Chillin' for %d tics.\n", (arg = 500)); thread_wait(); printf(1, "\nChillin' complete.\n"); exit(); }
void keyPress(unsigned char key, int x, int y){ if (key == 'w'){ btVector3 velocity(0,0,0); velocity = box2->getLinearVelocity(); box2->applyCentralImpulse(btVector3(0,0,-3)); } if (key == 's'){ btVector3 velocity(0,0,0); velocity = box2->getLinearVelocity(); box2->applyCentralImpulse(btVector3(0,0,3)); } if (key == 'a'){ btVector3 velocity(0,0,0); velocity = box2->getLinearVelocity(); box2->applyCentralImpulse(btVector3(-3,0,0)); } if (key == 'd'){ btVector3 velocity(0,0,0); velocity = box2->getLinearVelocity(); box2->applyCentralImpulse(btVector3(3,0,0)); } else if (key == 27){ quick_exit(0); } tim(); }
int main() { int array1[10],array2[100],array3[1000],j; random(array1,10); random(array2,100); random(array3,1000); tim(array1,9); printf("\n"); i++; tim(array2,99); i++; printf("\n"); tim(array3,999); printf("\n"); getch(); }
// ###################################################################### void CenterSurroundHistogramSegmenter::csTemplateSalientRegion (Point2D<int> pt) { Point2D<int> gpt(pt.i/GRID_SIZE, pt.j/GRID_SIZE); Rectangle intRect = itsIntegralHistogram.getBounds(); Timer tim(1000000); tim.reset(); // try the various center surround combination for(uint i = 0; i < itsCStemplates.size(); i++) { Rectangle cR = itsCStemplates[i].first; Rectangle sR = itsCStemplates[i].second; // only use the rectangle part that overlaps the image Rectangle grC = intRect.getOverlap(cR+gpt); Rectangle grS = intRect.getOverlap(sR+gpt); // get the center and surround histograms rutz::shared_ptr<Histogram> hC = getGridHistogramDistribution(grC); rutz::shared_ptr<Histogram> hCS = getGridHistogramDistribution(grS); Histogram hS = (*hCS) - (*hC); // smooth and normalize int npointC = grC.area()*GRID_SIZE*GRID_SIZE; int npointS = grS.area()*GRID_SIZE*GRID_SIZE - npointC; Histogram shC = smoothAndNormalize(*hC, npointC); Histogram shS = smoothAndNormalize( hS, npointS); // get the difference float diff = shS.getChiSqDiff(shC); // update the center surround belief estimation // we store the max as the best estimation of belief for(int ii = grS.left(); ii <= grS.rightI(); ii++) for(int jj = grS.top(); jj <= grS.bottomI(); jj++) { Point2D<int> pt(ii,jj); // if point is in center if(grC.contains(pt)) { float prevC = itsGridCenterBelief.getVal(ii,jj); if(prevC < diff) itsGridCenterBelief.setVal(ii,jj, diff); } // or surround else { float prevS = itsGridSurroundBelief.getVal(ii,jj); if(prevS < diff) itsGridSurroundBelief.setVal(ii,jj, diff); } } } LINFO("time: %f", tim.get()/1000.0F); }
void gw1(double len, size_t div, std::vector<double> *x, std::vector<double> *results) { MeshLib::IMesh *msh = MeshGenerator::generateLineMesh(len, div, .0, .0, .0); #if 1 GeoLib::Line* line = new GeoLib::Line(Point(0.0, 0.0, 0.0), Point(len, 0.0, 0.0)); Geo::PorousMedia pm; pm.hydraulic_conductivity = new MathLib::SpatialFunctionConstant<double>(1.e-11); pm.porosity = new MathLib::SpatialFunctionConstant<double>(0.2); DiscreteSystem dis(*msh); Geo::GWFemProblem* pGW = defineGWProblem1D(dis, *line, pm); TimeStepFunctionConstant tim(.0, 1e+4, 1e+3); pGW->setTimeSteppingFunction(tim); Base::Options options; Base::Options* op_lis = options.addSubGroup("LinearSolver"); op_lis->addOption("solver_type", "CG"); op_lis->addOption("precon_type", "NONE"); op_lis->addOptionAsNum("error_tolerance", 1e-10); op_lis->addOptionAsNum("max_iteration_step", 500); Geo::FunctionHead<MathLib::DenseLinearEquation> f_head; // Geo::FunctionHead<MathLib::CRSLisSolver> f_head; f_head.define(&dis, pGW, options); f_head.setOutputParameterName(0, "h"); FemFunctionConvergenceCheck checker; MathLib::SerialStaggeredMethod method(checker, 1e-5, 100); NumLib::AsyncPartitionedSystem apart1; apart1.setAlgorithm(method); apart1.resizeOutputParameter(1); apart1.setOutputParameterName(0, "h"); apart1.addProblem(f_head); apart1.connectParameters(); TimeSteppingController timestepping; timestepping.addTransientSystem(apart1); //const double epsilon = 1.e-3; timestepping.setBeginning(.0); timestepping.solve(1.0); const FemLib::FemNodalFunctionScalar* r_f_head = apart1.getOutput<FemLib::FemNodalFunctionScalar>(apart1.getOutputParameterID("h")); const DiscreteLib::DiscreteVector<double>* h = r_f_head->getNodalValues(); #endif x->resize(msh->getNumberOfNodes()); for (size_t i=0; i<x->size(); i++) (*x)[i] = msh->getNodeCoordinatesRef(i)->getData()[0]; #if 1 results->resize(h->size()); for (size_t i=0; i<results->size(); i++) (*results)[i] = (*h)[i]; #else results->resize(x->size(), 1.0); #endif }
double Time::GetTime() const { struct tm t; t.tm_wday = 0; t.tm_yday = 0; t.tm_year = m_year - 1900; t.tm_mon = m_month - 1; t.tm_mday = m_day; t.tm_hour = m_hour; t.tm_min = m_minute; t.tm_sec = m_second; time_t tt = 0; if (m_type == Universal) { t.tm_isdst = 0; tt = _mkgmtime(&t); if (tt <= 1) { throw std::runtime_error("Invalid UTC date/time: " + ToExtendedISO()); } } else if (m_type == Local) { // MSDN: "A value less than zero to have the C run-time library code compute whether standard time or daylight savings time is in effect." t.tm_isdst = -1; tt = mktime(&t); if (tt < 0) { throw std::runtime_error("Invalid local date/time: " + ToExtendedISO()); } } else { #ifdef WIN32 #ifdef _DEBUG OutputDebugStringA("\n--> GetTime(): Time type is unknown - assuming universal time.\n\n"); #endif // _DEBUG #endif // WIN32 t.tm_isdst = 0; tt = _mkgmtime(&t); if (tt <= 1) { throw std::runtime_error("Invalid date/time: " + ToExtendedISO()); } } double d = static_cast<double>(tt); d += m_fraction_of_second; #ifdef _DEBUG Time tim(d, m_type); assert(*this == tim); #endif // _DEBUG return d; }
void WorkerB::operator()(){ boost::chrono::milliseconds tim(100); for(;;){ tm * tiim = TimeGetter::getTime(); if(tiim->tm_min > oldmin) flag = false; if(tiim->tm_min % 2 && tiim->tm_min % 5 && !flag){ cout << "Thread B time " << tiim->tm_hour << ":" << tiim->tm_min << endl; oldmin = tiim->tm_min; flag = true; } boost::this_thread::sleep_for(tim); } }
// ###################################################################### void CenterSurroundHistogramSegmenter::setImageFeatureHistogramValues() { Timer tim(1000000); tim.reset(); // convert to CIElab color space Image<float> lImg; Image<float> aImg; Image<float> bImg; getNormalizedLAB(itsImage, lImg, aImg, bImg); LINFO("nLAB: %f", tim.get()/1000.0F); tim.reset(); // convert to bin numbers itsImageHistogramEntries.clear(); itsImageHistogramEntries.push_back(quantize_values(lImg, NUM_L_BINS)); itsImageHistogramEntries.push_back(quantize_values(aImg, NUM_A_BINS)); itsImageHistogramEntries.push_back(quantize_values(bImg, NUM_B_BINS)); LINFO("qLAB: %f", tim.get()/1000.0F); }
int main() { boost::thread_group tg; asio::io_service svc; { // Start the consumer: auto instance = boost::make_shared<MyClass>(svc); instance->Start(); // Sniper in 2 seconds :) boost::thread([instance] { boost::this_thread::sleep_for(boost::chrono::seconds(2)); instance->Stop(); }).detach(); // Start the producer: auto producer_coro = [instance, &svc](asio::yield_context c) { // a bound function/function object in C++03 asio::deadline_timer tim(svc); while (instance->Write(rand())) { tim.expires_from_now(boost::posix_time::milliseconds(200)); tim.async_wait(c); } }; asio::spawn(svc, producer_coro); // Start the service threads: for(size_t i=0; i < boost::thread::hardware_concurrency(); ++i) tg.create_thread(boost::bind(&asio::io_service::run, &svc)); } // now `instance` is out of scope, it will selfdestruct after the snipe // completed boost::this_thread::sleep_for(boost::chrono::seconds(3)); // wait longer than the snipe std::cout << "This is the main thread _after_ MyClass self-destructed correctly\n"; // cleanup service threads tg.join_all(); }
// Wrapper for elem::HermitianGenDefiniteEig sorts vals ascending ElemEigenSystem HermitianGenEigensolver(const TAMatrix &F, const TAMatrix &S){ // Get mats from TA EMatrix EF = TiledArray::array_to_elem(F, elem::DefaultGrid()); // Fock EMatrix ES = TiledArray::array_to_elem(S, elem::DefaultGrid()); // Overlap // Vec and value storage elem::DistMatrix<double , elem::VR, elem::STAR> vals(elem::DefaultGrid()); EMatrix vecs(elem::DefaultGrid()); // Compute vecs and values elem::mpi::Barrier(elem::mpi::COMM_WORLD); // Compute evals evals sc::Timer tim("Solving HermitianGenEig:"); elem::HermitianGenDefiniteEig(elem::AXBX, elem::LOWER,EF,ES,vals,vecs, elem::ASCENDING); elem::mpi::Barrier(elem::mpi::COMM_WORLD); tim.exit("Solving HermitianGenEig:"); return std::make_pair(vals, vecs); }
// ###################################################################### void CenterSurroundHistogramSegmenter::setImage (Image<PixRGB<byte> > image) { itsImage = image; itsCSrectangle = Rectangle(); Timer tim(1000000); tim.reset(); // create the CIE lab histogram entry images // this is the feature histogram in Martin's pb PAMI 2004 setImageFeatureHistogramValues(); LINFO("fHist time: %f",tim.get()/1000.0F); tim.reset(); // create the grid histogram and integral images computeGridHistogram(); computeHistogramIntegralImage(); LINFO("cHistII time: %f",tim.get()/1000.0F); // reset the center surround belief int gwidth = itsImage.getWidth() /GRID_SIZE; int gheight = itsImage.getHeight()/GRID_SIZE; itsGridCenterBelief = Image<float>(gwidth, gheight, ZEROS); itsGridSurroundBelief = Image<float>(gwidth, gheight, ZEROS); }
// ###################################################################### void CenterSurroundHistogramSegmenter::ptsSalientRegion(Point2D<int> pt) { Timer tim(1000000); tim.reset(); // // display window // uint width = itsImage.getWidth(); // uint height = itsImage.getHeight(); // if(itsWin.is_invalid()) // itsWin.reset(new XWinManaged(Dims(width, height), 0, 0, "CSHse")); // else itsWin->setDims(Dims(width, height)); Point2D<int> gpt(pt.i/GRID_SIZE, pt.j/GRID_SIZE); // try various center surround combination for(uint i = 0; i < itsCSpoints.size(); i++) { Timer tim(1000000); tim.reset(); std::vector<Point2D<int> > cPoints = itsCSpoints[i].first; std::vector<Point2D<int> > sPoints = itsCSpoints[i].second; // create center histogram from the center points // make sure the points are in bounds Histogram hC; bool cinit = false; std::vector<Point2D<int> > cAPoints; for(uint j = 0; j < cPoints.size(); j++) { Point2D<int> pt = gpt + cPoints[j]; if(!itsGridHistogram.coordsOk(pt)) continue; cAPoints.push_back(pt); if(!cinit) { hC = *itsGridHistogram.getVal(pt); cinit = true; } else hC = hC + *itsGridHistogram.getVal(pt); } // create surround histogram from the surround points // make sure the points are in bounds Histogram hS; bool sinit = false; std::vector<Point2D<int> > sAPoints; for(uint j = 0; j < sPoints.size(); j++) { Point2D<int> pt = gpt + sPoints[j]; if(!itsGridHistogram.coordsOk(pt)) continue; sAPoints.push_back(pt); if(!sinit) { hS = *itsGridHistogram.getVal(pt); sinit = true; } else hS = hS + *itsGridHistogram.getVal(pt); } // smooth and normalize the resulting histogram int npointC = cAPoints.size()*GRID_SIZE*GRID_SIZE; int npointS = sAPoints.size()*GRID_SIZE*GRID_SIZE; Histogram shC = smoothAndNormalize(hC, npointC); Histogram shS = smoothAndNormalize(hS, npointS); // print the difference float diff = shS.getChiSqDiff(shC); // update the center belief estimation // we store the max as the best estimation of belief for(uint cc = 0; cc < cAPoints.size(); cc++) { Point2D<int> pt = cAPoints[cc]; float prevC = itsGridCenterBelief.getVal(pt); if(prevC < diff) itsGridCenterBelief.setVal(pt, diff); } // update the surround belief estimation for(uint ss = 0; ss < sAPoints.size(); ss++) { Point2D<int> pt = sAPoints[ss]; float prevS = itsGridSurroundBelief.getVal(pt); if(prevS < diff) itsGridSurroundBelief.setVal(pt, diff); } // // display the window // Image<PixRGB<byte> > disp(width, height, ZEROS); // float mVal = 127; // float bVal = 255 - mVal; // Image<byte> dImaR, dImaG, dImaB; // getComponents(itsImage, dImaR, dImaG, dImaB); // inplaceNormalize(dImaR, byte(0), byte(mVal)); // inplaceNormalize(dImaG, byte(0), byte(mVal)); // inplaceNormalize(dImaB, byte(0), byte(mVal)); // Image<PixRGB<byte> > dIma = makeRGB(dImaR,dImaG,dImaB); // //inplacePaste (disp, dIma, Point2D<int>(0,0)); // Image<PixRGB<byte> > dImaCS(width,height, ZEROS); // for(uint j = 0; j < cAPoints.size(); j++) // drawFilledRect(dImaCS, Rectangle(cAPoints[j],Dims(1,1))*GRID_SIZE, // PixRGB<byte>(byte(bVal),0,0)); // for(uint j = 0; j < sAPoints.size(); j++) // drawFilledRect(dImaCS, Rectangle(sAPoints[j],Dims(1,1))*GRID_SIZE, // PixRGB<byte>(0, byte(bVal),0)); // Image<PixRGB<byte> > tdIma(dIma+dImaCS); // inplacePaste (disp, tdIma, Point2D<int>(0,0)); // drawCross(disp, pt, PixRGB<byte>(255,0,0), 10, 1); // itsWin->drawImage(disp,0,0); // Raster::waitForKey(); } LINFO("time: %f", tim.get()/1000.0F); }
void tileMap(){ sf::RenderWindow window(sf::VideoMode(512, 256), "Tilemap"); sf::View view(sf::Vector2f(0, 0), sf::Vector2f(window.getSize())); sf::View minimap(view.getCenter(), view.getSize()*2.f); minimap.setViewport(sf::FloatRect(0.75f, 0, 0.25f, 0.25f)); sf::Texture tileset; tileset.loadFromFile("terrain-6.png"); sf::Vector2f player_position(90, 90); sf::Vector2f zone_center(player_position); sf::Vector2u tim(300, 300); //Tiles in Map sf::Vector2u tiz(25, 25); // Tiles in Zone sf::Vector2u tile_size(32, 32); sf::Vector2u tex_tile_size(tileset.getSize()/16u); sf::Vector2f zone_size(tiz.x*tile_size.x, tiz.y*tile_size.y); std::vector<uint8_t> tiles(tiz.x*tiz.y); sf::VertexArray vertices(sf::Quads, tiz.x*tiz.y*4); std::ifstream map_file; map_file.open("map.data", std::ifstream::binary); //map_file.read(reinterpret_cast<char*> (&tiles[0]), tiles.size() * sizeof(tiles[0])); while (window.isOpen()){ sf::Event event; while (window.pollEvent(event)){ if(event.type == sf::Event::Closed) window.close(); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)){ player_position.x-=2; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)){ player_position.x+=2; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)){ player_position.y-=1; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)){ player_position.y+=1; } if (std::abs(player_position.x - zone_center.x) > zone_size.x || std::abs(player_position.y - zone_center.y) > zone_size.y){ for (int y = (player_position.y - ((tiz.y-1)/2)); y <= player_position.y + ((tiz.y-1)/2); y++){ int x = (player_position.x - ((tiz.x-1)/2)); int n = y*tiz.x+x; map_file.read(reinterpret_cast<char*> (&tiles[n]), tim.x * sizeof(tiles[0])); } for (size_t y=0; y<tiz.y; y++){ for (size_t x=0; x<tiz.x; x++){ sf::Vertex* quad = &vertices[(y*tiz.x+x)*4]; quad[0].position = sf::Vector2f(y*tile_size.x, x*tile_size.y); quad[1].position = sf::Vector2f((y+1)*tile_size.x, x*tile_size.y); quad[2].position = sf::Vector2f((y+1)*tile_size.x, (x+1)*tile_size.y); quad[3].position = sf::Vector2f(y*tile_size.x, (x+1)*tile_size.y); const int tile_id = tiles[y*tiz.x+x]; const int tx = tile_id % (tileset.getSize().x / tex_tile_size.x); const int ty = tile_id / (tileset.getSize().x / tex_tile_size.x); quad[0].texCoords = sf::Vector2f(tx*tex_tile_size.x, ty*tex_tile_size.y); quad[1].texCoords = sf::Vector2f((tx+1)*tex_tile_size.x, ty*tex_tile_size.y); quad[2].texCoords = sf::Vector2f((tx+1)*tex_tile_size.x, (ty+1)*tex_tile_size.y); quad[3].texCoords = sf::Vector2f(tx*tex_tile_size.x, (ty+1)*tex_tile_size.y); } } } window.clear(sf::Color::White); window.setView(view); view.setCenter(player_position); window.draw(vertices, &tileset); minimap.setCenter(view.getCenter()); window.setView(minimap); window.draw(vertices, &tileset); window.display(); sf::sleep(sf::milliseconds(10)); } }
// ###################################################################### Rectangle CenterSurroundHistogramSegmenter::growCSregion(Point2D<int> pt) { Timer tim(1000000); tim.reset(); Point2D<int> gpt(pt.i/GRID_SIZE, pt.j/GRID_SIZE); int gwidth = itsGridCenterBelief.getWidth(); int gheight = itsGridCenterBelief.getHeight(); int rad_dist = 5; // clamp zero the difference of center and surround belief Image<float> cs = clampedDiff((itsGridCenterBelief - itsGridSurroundBelief), Image<float>(gwidth,gheight,ZEROS)); Image<bool> visited(gwidth, gheight, ZEROS); visited.setVal(gpt, true); // grow from the center std::vector<Point2D<int> > csRegion; std::vector<Point2D<int> > regQueue; regQueue.push_back(gpt); uint cindex = 0; // start growing int tt = gpt.j, ll = gpt.i, bb = gpt.j, rr = gpt.i; float max_dist = 0.0F; while(cindex < regQueue.size()) { Point2D<int> cgpt = regQueue[cindex]; csRegion.push_back(cgpt); // go through all its neighbors for(int di = -1; di <= 1; di++) for(int dj = -1; dj <= 1; dj++) { if(di == 0 && dj == 0) continue; Point2D<int> ncgpt(cgpt.i+di, cgpt.j+dj); // skip if out of bounds and already visited if(!cs.coordsOk(ncgpt)) continue; if(visited.getVal(ncgpt)) continue; // include points that are // within max_dist distance or value above 0.0F float dist = gpt.distance(ncgpt); float val = cs.getVal(ncgpt); if(dist < rad_dist || val > 0.0F) { regQueue.push_back(ncgpt); if(max_dist < dist) max_dist = dist; if(tt > ncgpt.j) tt = ncgpt.j; if(bb < ncgpt.j) bb = ncgpt.j; if(ll > ncgpt.i) ll = ncgpt.i; if(rr < ncgpt.i) rr = ncgpt.i; } visited.setVal(ncgpt, true); } cindex++; } // add a bit of slack int slack = SLACK_SIZE; tt -= slack; bb += slack; ll -= slack; rr += slack; if(tt < 0) tt = 0; if(bb >= gheight) bb = gheight - 1; if(ll < 0) ll = 0; if(rr >= gwidth) rr = gwidth - 1; Rectangle res = Rectangle::tlbrI(tt,ll,bb,rr); res = res.getOverlap(visited.getBounds()); LINFO("grow region: %f", tim.get()/1000.0F); return res; }
TEST(Solution, LinearElastic2D) { try { MeshLib::IMesh *msh = MeshGenerator::generateStructuredRegularQuadMesh(2.0, 2, .0, .0, .0); GeoLib::Rectangle* _rec = new GeoLib::Rectangle(Point(0.0, 0.0, 0.0), Point(2.0, 2.0, 0.0)); Geo::PorousMedia pm; pm.hydraulic_conductivity = new NumLib::TXFunctionConstant(1.e-11); pm.porosity = new NumLib::TXFunctionConstant(0.2); Geo::Solid solid; solid.density = 3e+3; solid.poisson_ratio = 0.2; solid.Youngs_modulus = 10e+9; pm.solidphase = &solid; DiscreteSystem dis(msh); FemLib::LagrangeFeObjectContainer feObjects(msh); Geo::FemLinearElasticProblem* pDe = defineLinearElasticProblem(dis, *_rec, pm, &feObjects); TimeStepFunctionConstant tim(.0, 10.0, 10.0); pDe->setTimeSteppingFunction(tim); // options BaseLib::Options options; BaseLib::Options* op_lis = options.addSubGroup("LinearSolver"); op_lis->addOption("solver_type", "CG"); op_lis->addOption("precon_type", "NONE"); op_lis->addOptionAsNum("error_tolerance", 1e-10); op_lis->addOptionAsNum("max_iteration_step", 500); BaseLib::Options* op_nl = options.addSubGroup("Nonlinear"); op_nl->addOption("solver_type", "Linear"); op_nl->addOptionAsNum("error_tolerance", 1e-6); op_nl->addOptionAsNum("max_iteration_step", 500); MyFunctionDisplacement f_u; f_u.define(&dis, pDe, &pm, options); f_u.setOutputParameterName(0, "u_x"); f_u.setOutputParameterName(1, "u_y"); f_u.setOutputParameterName(2, "Strain"); f_u.setOutputParameterName(3, "Stress"); // MyFunctionStressStrain f_sigma; // f_sigma.setOutputParameterName(0, "strain_xx"); SerialStaggeredMethod method(1e-5, 100); AsyncPartitionedSystem apart1; apart1.setAlgorithm(method); apart1.resizeOutputParameter(4); apart1.setOutputParameterName(0, "u_x"); apart1.setOutputParameterName(1, "u_y"); apart1.setOutputParameterName(2, "Strain"); apart1.setOutputParameterName(3, "Stress"); apart1.addProblem(f_u); apart1.connectParameters(); TimeSteppingController timestepping; timestepping.setTransientSystem(apart1); //const double epsilon = 1.e-3; timestepping.setBeginning(.0); timestepping.solve(tim.getEnd()); // const MyNodalFunctionScalar* r_f_ux = apart1.getOutput<MyNodalFunctionScalar>(apart1.getOutputParameterID("u_x")); // const MyNodalFunctionScalar* r_f_uy = apart1.getOutput<MyNodalFunctionScalar>(apart1.getOutputParameterID("u_y")); const MyIntegrationPointFunctionVector* r_f_strain = apart1.getOutput<MyIntegrationPointFunctionVector>(apart1.getOutputParameterID("Strain")); const MyIntegrationPointFunctionVector* r_f_stress = apart1.getOutput<MyIntegrationPointFunctionVector>(apart1.getOutputParameterID("Stress")); // const IDiscreteVector<double>* vec_r_f_ux = r_f_ux->getDiscreteData(); // const IDiscreteVector<double>* vec_r_f_uy = r_f_uy->getDiscreteData(); const MyIntegrationPointFunctionVector::MyDiscreteVector* vec_strain = r_f_strain->getDiscreteData(); const MyIntegrationPointFunctionVector::MyDiscreteVector* vec_stress = r_f_stress->getDiscreteData(); // r_f_ux->printout(); // r_f_uy->printout(); // r_f_strain->printout(); // r_f_stress->printout(); const MathLib::LocalVector &strain1 = (*vec_strain)[0][0]; const MathLib::LocalVector &stress1 = (*vec_stress)[0][0]; double E = solid.Youngs_modulus; double nu = solid.poisson_ratio; double sx = .0; //E/((1.+nu)*(1-2*nu))*((1-nu)*ex+nu*ey); double sy = -1e+6; //E/((1.-nu)*(1-2*nu))*(nu*ex+(1-nu)*ey); double sxy = .0; //0.5*E/(1.+nu)*exy; double ex = (1+nu)/E*((1-nu)*sx-nu*sy); double ey = (1+nu)/E*((1-nu)*sy-nu*sx); double exy = 2*(1+nu)/E*sxy; double sz = nu*E/((1.+nu)*(1-2*nu))*(ex+ey); double epsilon = 1e-6; ASSERT_NEAR(ex, strain1(0), epsilon); ASSERT_NEAR(ey, strain1(1), epsilon); ASSERT_NEAR(.0, strain1(2), epsilon); ASSERT_NEAR(exy, strain1(3), epsilon); epsilon = 1; ASSERT_NEAR(sx, stress1(0), epsilon); ASSERT_NEAR(sy, stress1(1), epsilon); ASSERT_NEAR(sz, stress1(2), epsilon); ASSERT_NEAR(sxy, stress1(3), epsilon); } catch (const char* e) { std::cout << "***Exception caught! " << e << std::endl; } }
TEST(Solution, CouplingFem2) { // problem definition const size_t div = 20; const double poro = 1.0; const double mol_diff = 1e-6; const double darcy_vel = 1e-5; try { //space MeshLib::IMesh *msh = MeshGenerator::generateStructuredRegularQuadMesh(2.0, div, .0, .0, .0); GeoLib::Rectangle* _rec = new GeoLib::Rectangle(Point(0.0, 0.0, 0.0), Point(2.0, 2.0, 0.0)); //time //TimeStepFunctionConstant tim(.0, 1e+3, 1e+3); TimeStepFunctionConstant tim(.0, 1e+4, 1e+3); //material Geo::PorousMedia pm; pm.hydraulic_conductivity = new NumLib::TXFunctionConstant(1.e-11); pm.porosity = new NumLib::TXFunctionConstant(poro); Geo::Compound tracer; tracer.molecular_diffusion = new NumLib::TXFunctionConstant(mol_diff); //problems DiscreteSystem dis(msh); FemLib::LagrangeFeObjectContainer feObjects(msh); Geo::GWFemProblem* pGW = defineGWProblem(dis, *_rec, pm, &feObjects); Geo::MassFemProblem* pMass = defineMassTransportProblem(dis, *_rec, pm, tracer, &feObjects); pGW->setTimeSteppingFunction(tim); pMass->setTimeSteppingFunction(tim); //options BaseLib::Options optionsGW; BaseLib::Options* op_lis = optionsGW.addSubGroup("LinearSolver"); op_lis->addOption("solver_type", "CG"); op_lis->addOption("precon_type", "NONE"); op_lis->addOptionAsNum("error_tolerance", 1e-10); op_lis->addOptionAsNum("max_iteration_step", 1000); BaseLib::Options* op_nl = optionsGW.addSubGroup("Nonlinear"); op_nl->addOption("solver_type", "Picard"); op_nl->addOptionAsNum("error_tolerance", 1e-6); op_nl->addOptionAsNum("max_iteration_step", 500); BaseLib::Options optionsMT; op_lis = optionsMT.addSubGroup("LinearSolver"); op_lis->addOption("solver_type", "BICG"); op_lis->addOption("precon_type", "NONE"); op_lis->addOptionAsNum("error_tolerance", 1e-10); op_lis->addOptionAsNum("max_iteration_step", 1000); BaseLib::Options* op_nl2 = optionsMT.addSubGroup("Nonlinear"); op_nl2->addOption("solver_type", "Picard"); op_nl2->addOptionAsNum("error_tolerance", 1e-6); op_nl2->addOptionAsNum("max_iteration_step", 500); // unknowns MyFunctionHead f_head; f_head.define(&dis, pGW, optionsGW); f_head.setOutputParameterName(0, "h"); MyFunctionVelocity f_vel; f_vel.define(dis, pm); f_vel.setInputParameterName(0, "h"); f_vel.setOutputParameterName(0, "v"); MyFunctionConcentration f_c; f_c.define(&dis, pMass, optionsMT); f_c.setInputParameterName(0, "v"); f_c.setOutputParameterName(0, "c"); SerialStaggeredMethod method(1e-5, 100); AsyncPartitionedSystem apart1; apart1.setAlgorithm(method); apart1.resizeOutputParameter(3); apart1.setOutputParameterName(0, "h"); apart1.setOutputParameterName(1, "v"); apart1.setOutputParameterName(2, "c"); apart1.addProblem(f_head); apart1.addProblem(f_vel); apart1.addProblem(f_c); apart1.connectParameters(); TimeSteppingController timestepping; timestepping.setTransientSystem(apart1); //const double epsilon = 1.e-3; timestepping.setBeginning(.0); timestepping.solve(tim.getEnd()); const MyNodalFunctionScalar* r_f_head = apart1.getOutput<MyNodalFunctionScalar>(apart1.getOutputParameterID("h")); //const MyIntegrationPointFunctionVector* r_f_v = apart1.getOutput<MyIntegrationPointFunctionVector>(apart1.getOutputParameterID("v")); const MyNodalFunctionScalar* r_f_c = apart1.getOutput<MyNodalFunctionScalar>(apart1.getOutputParameterID("c")); const IDiscreteVector<double>* vec_h = r_f_head->getDiscreteData(); //const FEMIntegrationPointFunctionVector2d::DiscreteVectorType* vec_v = r_f_v->getNodalValues(); const IDiscreteVector<double>* vec_c = r_f_c->getDiscreteData(); //r_f_head->printout(); //r_f_v->printout(); //#undef OUTPUT_C #define OUTPUT_C std::vector<double> expectedHead(msh->getNumberOfNodes()); const double p_left = 2.e+6; const double p_right = .0; const double x_len = 2.0; #ifdef OUTPUT_C std::cout << std::endl << "expected p="; #endif for (size_t i=0; i<expectedHead.size(); i++) { double x = msh->getNodeCoordinatesRef(i)->getData()[0]; expectedHead[i] = (p_right-p_left) / x_len * x + p_left; #ifdef OUTPUT_C std::cout << expectedHead[i] << " "; #endif } // getGWExpectedHead(expectedHead); ASSERT_DOUBLE_ARRAY_EQ(&expectedHead[0], &(*vec_h)[0], expectedHead.size(), 1e-5); std::vector<double> expectedC(msh->getNumberOfNodes()); #ifdef OUTPUT_C std::cout << std::endl << "simulated C:"<< std::endl; r_f_c->printout(); std::cout << "expected C="; #endif for (size_t i=0; i<msh->getNumberOfNodes(); i++) { double x = msh->getNodeCoordinatesRef(i)->getData()[0]; expectedC[i] = analyticalOgataBank(x, tim.getEnd(), darcy_vel/poro, mol_diff); #ifdef OUTPUT_C std::cout << expectedC[i] << " "; #endif } #ifdef OUTPUT_C std::cout << std::endl; #endif ASSERT_DOUBLE_ARRAY_EQ(&expectedC[0], &(*vec_c)[0], expectedC.size(), 5e-2); } catch (const char* e) { std::cout << "***Exception caught! " << e << std::endl; } }
TEST(Solution, line) { try { const double len = 2.0; const size_t div = 2; const double h = len / div; const double p_out = .0; const double q_in = 1e-5; const double k = 1e-11; const double poro = 0.2; MeshLib::IMesh *msh = MeshGenerator::generateLineMesh(len, div, .0, .0, .0); GeoLib::Line* line = new GeoLib::Line(Point(0.0, 0.0, 0.0), Point(len, 0.0, 0.0)); Geo::PorousMedia pm; pm.hydraulic_conductivity = new NumLib::TXFunctionConstant(k); pm.porosity = new NumLib::TXFunctionConstant(poro); DiscreteSystem dis(msh); FemLib::LagrangeFeObjectContainer feObjects(msh); Geo::GWFemProblem* pGW = defineGWProblem1D(dis, *line, pm, &feObjects, p_out, q_in); TimeStepFunctionConstant tim(.0, 10.0, 10.0); pGW->setTimeSteppingFunction(tim); // options BaseLib::Options options; BaseLib::Options* op_lis = options.addSubGroup("LinearSolver"); op_lis->addOption("solver_type", "CG"); op_lis->addOption("precon_type", "NONE"); op_lis->addOptionAsNum("error_tolerance", 1e-10); op_lis->addOptionAsNum("max_iteration_step", 500); MyFunctionHead f_head; f_head.define(&dis, pGW, options); f_head.setOutputParameterName(0, "h"); MyFunctionVelocity f_vel; f_vel.define(dis, pm); f_vel.setInputParameterName(0, "h"); f_vel.setOutputParameterName(0, "v"); SerialStaggeredMethod method(1e-5, 100); AsyncPartitionedSystem apart1; apart1.setAlgorithm(method); apart1.resizeOutputParameter(2); apart1.setOutputParameterName(0, "h"); apart1.setOutputParameterName(1, "v"); apart1.addProblem(f_head); apart1.addProblem(f_vel); apart1.connectParameters(); TimeSteppingController timestepping; timestepping.setTransientSystem(apart1); //const double epsilon = 1.e-3; timestepping.setBeginning(.0); timestepping.solve(tim.getEnd()); const MyNodalFunctionScalar* r_f_head = apart1.getOutput<MyNodalFunctionScalar>(apart1.getOutputParameterID("h")); const MyIntegrationPointFunctionVector* r_f_v = apart1.getOutput<MyIntegrationPointFunctionVector>(apart1.getOutputParameterID("v")); const IDiscreteVector<double>* vec_h = r_f_head->getDiscreteData(); //const FEMIntegrationPointFunctionVector2d::DiscreteVectorType* vec_v = r_f_v->getNodalValues(); r_f_head->printout(); r_f_v->printout(); std::vector<double> expected; expected.resize(div+1); //const double p_left = 2.e+6; const double p_left = p_out + q_in * len / k; const double p_right = p_out; const double x_len = len; for (size_t i=0; i<expected.size(); i++) { double x = i*h; expected[i] = (p_right-p_left) / x_len * x + p_left; } ASSERT_DOUBLE_ARRAY_EQ(&expected[0], &(*vec_h)[0], vec_h->size()); } catch (const char* e) { std::cout << "***Exception caught! " << e << std::endl; } }
TEST(Solution, CouplingFem2D) { try { MeshLib::IMesh *msh = MeshGenerator::generateStructuredRegularQuadMesh(2.0, 2, .0, .0, .0); GeoLib::Rectangle* _rec = new GeoLib::Rectangle(Point(0.0, 0.0, 0.0), Point(2.0, 2.0, 0.0)); Geo::PorousMedia pm; pm.hydraulic_conductivity = new NumLib::TXFunctionConstant(1.e-11); pm.porosity = new NumLib::TXFunctionConstant(0.2); DiscreteSystem dis(msh); FemLib::LagrangeFeObjectContainer feObjects(msh); Geo::GWFemProblem* pGW = defineGWProblem(dis, *_rec, pm, &feObjects); TimeStepFunctionConstant tim(.0, 100.0, 10.0); pGW->setTimeSteppingFunction(tim); // options BaseLib::Options options; BaseLib::Options* op_lis = options.addSubGroup("LinearSolver"); op_lis->addOption("solver_type", "CG"); op_lis->addOption("precon_type", "NONE"); op_lis->addOptionAsNum("error_tolerance", 1e-10); op_lis->addOptionAsNum("max_iteration_step", 500); BaseLib::Options* op_nl = options.addSubGroup("Nonlinear"); op_nl->addOption("solver_type", "Picard"); op_nl->addOptionAsNum("error_tolerance", 1e-6); op_nl->addOptionAsNum("max_iteration_step", 500); MyFunctionHead f_head; f_head.define(&dis, pGW, options); f_head.setOutputParameterName(0, "h"); MyFunctionVelocity f_vel; f_vel.define(dis, pm); f_vel.setInputParameterName(0, "h"); f_vel.setOutputParameterName(0, "v"); SerialStaggeredMethod method(1e-5, 100); AsyncPartitionedSystem apart1; apart1.setAlgorithm(method); apart1.resizeOutputParameter(2); apart1.setOutputParameterName(0, "h"); apart1.setOutputParameterName(1, "v"); apart1.addProblem(f_head); apart1.addProblem(f_vel); apart1.connectParameters(); TimeSteppingController timestepping; timestepping.setTransientSystem(apart1); //const double epsilon = 1.e-3; timestepping.setBeginning(.0); timestepping.solve(tim.getEnd()); const MyNodalFunctionScalar* r_f_head = apart1.getOutput<MyNodalFunctionScalar>(apart1.getOutputParameterID("h")); const MyIntegrationPointFunctionVector* r_f_v = apart1.getOutput<MyIntegrationPointFunctionVector>(apart1.getOutputParameterID("v")); const IDiscreteVector<double>* vec_h = r_f_head->getDiscreteData(); //const FEMIntegrationPointFunctionVector2d::DiscreteVectorType* vec_v = r_f_v->getNodalValues(); r_f_head->printout(); r_f_v->printout(); std::vector<double> expected; getGWExpectedHead(expected); ASSERT_DOUBLE_ARRAY_EQ(&expected[0], &(*vec_h)[0], vec_h->size()); } catch (const char* e) { std::cout << "***Exception caught! " << e << std::endl; } }
// MAIN int main() { Fl_Double_Window win(1000, 440); MyTimer tim(5, 5, win.w()-20, win.h()-20, "Non GA Graph"); win.show(); return(Fl::run()); }
//-------------------------------------------------------------------------------------------------- /// Generate surface representation of the specified cut plane /// /// \note Will compute normals before returning geometry //-------------------------------------------------------------------------------------------------- void StructGridCutPlane::computeCutPlane() { DebugTimer tim("StructGridCutPlane::computeCutPlane", DebugTimer::DISABLED); bool doMapScalar = false; if (m_mapScalarSetIndex != UNDEFINED_UINT && m_scalarMapper.notNull()) { doMapScalar = true; } uint cellCountI = m_grid->cellCountI(); uint cellCountJ = m_grid->cellCountJ(); uint cellCountK = m_grid->cellCountK(); // Clear any current data m_vertices.clear(); m_vertexScalars.clear(); m_triangleIndices.clear(); m_meshLineIndices.clear(); // The indexing conventions for vertices and // edges used in the algorithm: // edg verts // 4-------------5 *------4------* 0 0 - 1 // /| /| /| /| 1 1 - 2 // / | / | 7/ | 5/ | 2 2 - 3 // / | / | |z / 8 / 9 3 3 - 0 // 7-------------6 | | /y *------6------* | 4 4 - 5 // | | | | |/ | | | | 5 5 - 6 // | 0---------|---1 *---x | *------0--|---* 6 6 - 7 // | / | / 11 / 10 / 7 7 - 4 // | / | / | /3 | /1 8 0 - 4 // |/ |/ |/ |/ 9 1 - 5 // 3-------------2 *------2------* 10 2 - 6 // vertex indices edge indices 11 3 - 7 // uint k; for (k = 0; k < cellCountK; k++) { uint j; for (j = 0; j < cellCountJ; j++) { uint i; for (i = 0; i < cellCountI; i++) { size_t cellIndex = m_grid->cellIndexFromIJK(i, j, k); Vec3d minCoord; Vec3d maxCoord; m_grid->cellMinMaxCordinates(cellIndex, &minCoord, &maxCoord); // Early reject for cells outside clipping box if (m_clippingBoundingBox.isValid()) { BoundingBox cellBB(minCoord, maxCoord); if (!m_clippingBoundingBox.intersects(cellBB)) { continue; } } // Check if plane intersects this cell and skip if it doesn't if (!isCellIntersectedByPlane(m_plane, minCoord, maxCoord)) { continue; } GridCell cell; bool isClipped = false; if (m_clippingBoundingBox.isValid()) { if (!m_clippingBoundingBox.contains(minCoord) || !m_clippingBoundingBox.contains(maxCoord)) { isClipped = true; minCoord.x() = CVF_MAX(minCoord.x(), m_clippingBoundingBox.min().x()); minCoord.y() = CVF_MAX(minCoord.y(), m_clippingBoundingBox.min().y()); minCoord.z() = CVF_MAX(minCoord.z(), m_clippingBoundingBox.min().z()); maxCoord.x() = CVF_MIN(maxCoord.x(), m_clippingBoundingBox.max().x()); maxCoord.y() = CVF_MIN(maxCoord.y(), m_clippingBoundingBox.max().y()); maxCoord.z() = CVF_MIN(maxCoord.z(), m_clippingBoundingBox.max().z()); } } cell.p[0].set(minCoord.x(), maxCoord.y(), minCoord.z()); cell.p[1].set(maxCoord.x(), maxCoord.y(), minCoord.z()); cell.p[2].set(maxCoord.x(), minCoord.y(), minCoord.z()); cell.p[3].set(minCoord.x(), minCoord.y(), minCoord.z()); cell.p[4].set(minCoord.x(), maxCoord.y(), maxCoord.z()); cell.p[5].set(maxCoord.x(), maxCoord.y(), maxCoord.z()); cell.p[6].set(maxCoord.x(), minCoord.y(), maxCoord.z()); cell.p[7].set(minCoord.x(), minCoord.y(), maxCoord.z()); // Fetch scalar values double cellScalarValue = 0; if (doMapScalar) { cellScalarValue = m_grid->cellScalar(m_mapScalarSetIndex, i, j, k); // If we're doing node averaging we must populate grid cell with scalar values interpolated to the grid points if (m_mapNodeAveragedScalars) { if (isClipped) { double scalarVal; if (m_grid->pointScalar(m_mapScalarSetIndex, cell.p[0], &scalarVal)) cell.s[0] = scalarVal; if (m_grid->pointScalar(m_mapScalarSetIndex, cell.p[1], &scalarVal)) cell.s[1] = scalarVal; if (m_grid->pointScalar(m_mapScalarSetIndex, cell.p[2], &scalarVal)) cell.s[2] = scalarVal; if (m_grid->pointScalar(m_mapScalarSetIndex, cell.p[3], &scalarVal)) cell.s[3] = scalarVal; if (m_grid->pointScalar(m_mapScalarSetIndex, cell.p[4], &scalarVal)) cell.s[4] = scalarVal; if (m_grid->pointScalar(m_mapScalarSetIndex, cell.p[5], &scalarVal)) cell.s[5] = scalarVal; if (m_grid->pointScalar(m_mapScalarSetIndex, cell.p[6], &scalarVal)) cell.s[6] = scalarVal; if (m_grid->pointScalar(m_mapScalarSetIndex, cell.p[7], &scalarVal)) cell.s[7] = scalarVal; } else { cell.s[0] = m_grid->gridPointScalar(m_mapScalarSetIndex, i, j + 1, k); cell.s[1] = m_grid->gridPointScalar(m_mapScalarSetIndex, i + 1, j + 1, k); cell.s[2] = m_grid->gridPointScalar(m_mapScalarSetIndex, i + 1, j, k); cell.s[3] = m_grid->gridPointScalar(m_mapScalarSetIndex, i, j, k); cell.s[4] = m_grid->gridPointScalar(m_mapScalarSetIndex, i, j + 1, k + 1); cell.s[5] = m_grid->gridPointScalar(m_mapScalarSetIndex, i + 1, j + 1, k + 1); cell.s[6] = m_grid->gridPointScalar(m_mapScalarSetIndex, i + 1, j, k + 1); cell.s[7] = m_grid->gridPointScalar(m_mapScalarSetIndex, i, j, k + 1); } } } Triangles triangles; uint numTriangles = polygonise(m_plane, cell, &triangles); if (numTriangles > 0) { // Add all the referenced vertices // At the same time registering their index in the 'global' vertex list uint globalVertexIndices[12]; int iv; for (iv = 0; iv < 12; iv++) { if (triangles.usedVertices[iv]) { globalVertexIndices[iv] = static_cast<uint>(m_vertices.size()); m_vertices.push_back(Vec3f(triangles.vertices[iv])); if (doMapScalar) { if (m_mapNodeAveragedScalars) { m_vertexScalars.push_back(triangles.scalars[iv]); } else { m_vertexScalars.push_back(cellScalarValue); } } } else { globalVertexIndices[iv] = UNDEFINED_UINT; } } // Build triangles from the cell const size_t prevNumTriangleIndices = m_triangleIndices.size(); uint t; for (t = 0; t < numTriangles; t++) { m_triangleIndices.push_back(globalVertexIndices[triangles.triangleIndices[3*t]]); m_triangleIndices.push_back(globalVertexIndices[triangles.triangleIndices[3*t + 1]]); m_triangleIndices.push_back(globalVertexIndices[triangles.triangleIndices[3*t + 2]]); } // Add mesh line indices addMeshLineIndices(&m_triangleIndices[prevNumTriangleIndices], numTriangles); } } } } //Trace::show("Vertices:%d TriConns:%d Tris:%d", m_vertices.size(), m_triangleIndices.size(), m_triangleIndices.size()/3); tim.reportTimeMS(); }
void GameManager::draw() { int window_width, window_height; platform_get_size(&window_width, &window_height); if (window_width <= 0 || window_height <= 0) // for some reason, GLFW sets these properties to 0 when minimized. return; #ifdef CHOWDREN_FORCE_REMOTE platform_set_remote_value(CHOWDREN_REMOTE_TARGET); #endif PROFILE_FUNC(); PROFILE_BEGIN(platform_begin_draw); platform_begin_draw(); PROFILE_END(); #ifdef CHOWDREN_USE_SUBAPP Frame * render_frame; if (SubApplication::current != NULL && SubApplication::current->flags & VISIBLE) { render_frame = &SubApplication::current->subapp_frame; } else render_frame = frame; #else Frame * render_frame = frame; #endif PROFILE_BEGIN(frame_draw); #ifdef CHOWDREN_IS_WIIU int remote_setting = platform_get_remote_value(); if (remote_setting == CHOWDREN_HYBRID_TARGET) { platform_set_display_target(CHOWDREN_REMOTE_TARGET); render_frame->draw(CHOWDREN_REMOTE_TARGET); draw_fade(); platform_set_display_target(CHOWDREN_TV_TARGET); render_frame->draw(CHOWDREN_TV_TARGET); draw_fade(); } else { platform_set_display_target(CHOWDREN_TV_TARGET); render_frame->draw(CHOWDREN_HYBRID_TARGET); draw_fade(); if (remote_setting == CHOWDREN_REMOTE_TARGET) { platform_clone_buffers(); platform_set_display_target(CHOWDREN_REMOTE_TARGET); render_frame->draw(CHOWDREN_REMOTE_ONLY); } } #elif CHOWDREN_IS_3DS platform_set_display_target(CHOWDREN_TV_TARGET); render_frame->draw(CHOWDREN_TV_TARGET); draw_fade(); // only draw 30 fps on bottom screen static int draw_interval = 0; if (draw_interval == 0) { platform_set_display_target(CHOWDREN_REMOTE_TARGET); render_frame->draw(CHOWDREN_REMOTE_TARGET); draw_fade(); } draw_interval = (draw_interval + 1) % 3; #else render_frame->draw(CHOWDREN_HYBRID_TARGET); draw_fade(); #endif PROFILE_END(); Render::set_offset(0, 0); #ifdef CHOWDREN_IS_DEMO if (show_build_timer > 0.0) { std::string date(__DATE__); std::string tim(__TIME__); std::string val = date + " " + tim; glPushMatrix(); glTranslatef(50, 50, 0); glScalef(5, -5, 5); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); get_font(24)->Render(val.c_str(), val.size(), FTPoint(), FTPoint()); glPopMatrix(); } #endif PROFILE_BEGIN(platform_swap_buffers); platform_swap_buffers(); PROFILE_END(); }