void CodeLiteLLDBApp::NotifyStopped() { m_variables.clear(); LLDBReply reply; wxPrintf("codelite-lldb: NotifyStopped() called. m_interruptReason=%d\n", (int)m_interruptReason); reply.SetReplyType( kReplyTypeDebuggerStopped ); reply.SetInterruptResaon( m_interruptReason ); // If we find a thread that was stopped due to breakpoint, make it the active one int threadCount = m_target.GetProcess().GetNumThreads(); for(int i=0; i<threadCount; ++i) { lldb::SBThread thr = m_target.GetProcess().GetThreadAtIndex(i); if ( thr.GetStopReason() == lldb::eStopReasonBreakpoint ) { m_target.GetProcess().SetSelectedThread( thr ); break; } } lldb::SBThread thread = m_target.GetProcess().GetSelectedThread(); LLDBBacktrace bt( thread, m_settings ); reply.SetBacktrace( bt ); int selectedThreadId = thread.GetThreadID(); // set the selected frame file:line if ( thread.IsValid() && thread.GetSelectedFrame().IsValid() ) { lldb::SBFrame frame = thread.GetSelectedFrame(); lldb::SBLineEntry lineEntry = thread.GetSelectedFrame().GetLineEntry(); if ( lineEntry.IsValid() ) { reply.SetLine(lineEntry.GetLine()); lldb::SBFileSpec fileSepc = frame.GetLineEntry().GetFileSpec(); reply.SetFilename( wxFileName(fileSepc.GetDirectory(), fileSepc.GetFilename()).GetFullPath() ); } } // Prepare list of threads LLDBThread::Vect_t threads; for(int i=0; i<threadCount; ++i) { LLDBThread t; lldb::SBThread thr = m_target.GetProcess().GetThreadAtIndex(i); t.SetStopReason(thr.GetStopReason()); t.SetId( thr.GetThreadID() ); t.SetActive( selectedThreadId == thr.GetThreadID() ); lldb::SBFrame frame = thr.GetSelectedFrame(); t.SetFunc( frame.GetFunctionName() ? frame.GetFunctionName() : "" ); lldb::SBLineEntry lineEntry = thr.GetSelectedFrame().GetLineEntry(); // get the stop reason string char buffer[1024]; memset(buffer, 0x0, sizeof(buffer)); thr.GetStopDescription( buffer, sizeof( buffer ) ); t.SetStopReasonString( buffer ); wxPrintf("codelite-lldb: thread %d stop reason is %s\n", t.GetId(), t.GetStopReasonString()); if ( lineEntry.IsValid() ) { t.SetLine(lineEntry.GetLine()); lldb::SBFileSpec fileSepc = frame.GetLineEntry().GetFileSpec(); t.SetFile( wxFileName(fileSepc.GetDirectory(), fileSepc.GetFilename()).GetFullPath() ); } threads.push_back( t ); } reply.SetThreads( threads ); SendReply( reply ); // reset the interrupt reason m_interruptReason = kInterruptReasonNone; }
void tst_QGeometryData::interleaveWith() { QVector3D a(1.1, 1.2, 1.3); QVector3D b(2.1, 2.2, 2.3); QVector3D c(3.1, 3.2, 3.3); QVector3D d(4.1, 4.2, 4.3); QVector3D vx(0.7071, 0.7071, 0.0); QVector2D at(0.11, 0.12); QVector2D bt(0.21, 0.22); QVector2D ct(0.31, 0.32); QVector2D dt(0.41, 0.42); QVector2D tx(1.0, 1.0); QGeometryData data; data.appendVertex(a, b, c, d); data.appendTexCoord(at, bt, ct, dt); QGeometryData dat2; // count is the smaller of the two - nothing in this null case // also make sure the argument doesnt somehow change - its a const // so it shouldn't... dat2.interleaveWith(data); QCOMPARE(data.count(), 4); QCOMPARE(data.vertex(0), a); QCOMPARE(dat2.count(), 0); QCOMPARE(dat2.count(QGL::Position), 0); QCOMPARE(dat2.fields(), quint32(0)); // dat2 is smaller and has less fields dat2.appendVertex(a + vx, b + vx); dat2.interleaveWith(data); QCOMPARE(data.count(), 4); QCOMPARE(data.vertex(0), a); QCOMPARE(dat2.count(), 4); QCOMPARE(dat2.count(QGL::Position), 4); QCOMPARE(dat2.count(QGL::TextureCoord0), 0); QCOMPARE(dat2.fields(), QGL::fieldMask(QGL::Position)); QCOMPARE(dat2.vertex(0), a + vx); QCOMPARE(dat2.vertex(1), a); QCOMPARE(dat2.vertex(2), b + vx); QCOMPARE(dat2.vertex(3), b); // full zip with both sides have 4 verts & textures dat2.clear(); for (int i = 0; i < data.count(); ++i) { dat2.appendVertex(data.vertex(i) + vx); dat2.appendTexCoord(data.texCoord(i) + tx); } dat2.interleaveWith(data); QCOMPARE(dat2.count(), 8); QCOMPARE(dat2.count(QGL::Position), 8); QCOMPARE(dat2.count(QGL::TextureCoord0), 8); QCOMPARE(dat2.fields(), QGL::fieldMask(QGL::Position) | QGL::fieldMask(QGL::TextureCoord0)); QCOMPARE(dat2.vertex(0), a + vx); QCOMPARE(dat2.vertex(1), a); QCOMPARE(dat2.vertex(4), c + vx); QCOMPARE(dat2.vertex(7), d); QCOMPARE(dat2.texCoord(0), at + tx); QCOMPARE(dat2.texCoord(3), bt); QCOMPARE(dat2.texCoord(7), dt); }
int main(int argc, char* argv[]) { // Choose a Butcher's table or define your own. ButcherTable bt(butcher_table_type); if (bt.is_explicit()) info("Using a %d-stage explicit R-K method.", bt.get_size()); if (bt.is_diagonally_implicit()) info("Using a %d-stage diagonally implicit R-K method.", bt.get_size()); if (bt.is_fully_implicit()) info("Using a %d-stage fully implicit R-K method.", bt.get_size()); // Load the mesh. Mesh mesh; H2DReader mloader; mloader.load("cathedral.mesh", &mesh); // Perform initial mesh refinements. for(int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(); mesh.refine_towards_boundary(BDY_AIR, INIT_REF_NUM_BDY); mesh.refine_towards_boundary(BDY_GROUND, INIT_REF_NUM_BDY); // Enter boundary markers. BCTypes bc_types; bc_types.add_bc_dirichlet(Hermes::vector<std::string>(BDY_GROUND)); bc_types.add_bc_newton(BDY_AIR); // Enter Dirichlet boundary values. BCValues bc_values; bc_values.add_const(BDY_GROUND, TEMP_INIT); // Initialize an H1 space with default shapeset. H1Space space(&mesh, &bc_types, &bc_values, P_INIT); int ndof = Space::get_num_dofs(&space); info("ndof = %d.", ndof); // Previous time level solution (initialized by the external temperature). Solution u_prev_time(&mesh, TEMP_INIT); // Initialize weak formulation. WeakForm wf; wf.add_matrix_form(callback(stac_jacobian_vol)); wf.add_vector_form(callback(stac_residual_vol)); wf.add_matrix_form_surf(callback(stac_jacobian_surf), BDY_AIR); wf.add_vector_form_surf(callback(stac_residual_surf), BDY_AIR); // Project the initial condition on the FE space to obtain initial solution coefficient vector. info("Projecting initial condition to translate initial condition into a vector."); scalar* coeff_vec = new scalar[ndof]; OGProjection::project_global(&space, &u_prev_time, coeff_vec, matrix_solver); // Initialize the FE problem. bool is_linear = false; DiscreteProblem dp(&wf, &space, is_linear); // Initialize views. ScalarView Tview("Temperature", new WinGeom(0, 0, 450, 600)); Tview.set_min_max_range(0,20); Tview.fix_scale_width(30); // Time stepping loop: double current_time = 0.0; int ts = 1; do { // Perform one Runge-Kutta time step according to the selected Butcher's table. info("Runge-Kutta time step (t = %g, tau = %g, stages: %d).", current_time, time_step, bt.get_size()); bool verbose = true; bool is_linear = true; if (!rk_time_step(current_time, time_step, &bt, coeff_vec, &dp, matrix_solver, verbose, is_linear)) { error("Runge-Kutta time step failed, try to decrease time step size."); } // Convert coeff_vec into a new time level solution. Solution::vector_to_solution(coeff_vec, &space, &u_prev_time); // Update time. current_time += time_step; // Show the new time level solution. char title[100]; sprintf(title, "Time %3.2f, exterior temperature %3.5f", current_time, temp_ext(current_time)); Tview.set_title(title); Tview.show(&u_prev_time); // Increase counter of time steps. ts++; } while (current_time < T_FINAL); // Cleanup. delete [] coeff_vec; // Wait for the view to be closed. View::wait(); return 0; }
void cover_sc_bit() { sc_bit bdef; sc_bit bf(false); sc_bit bt(true); sc_bit b0(0); sc_bit b1(1); try { sc_bit foo(2); } catch (sc_report) { cout << "Caught exception for sc_bit(2)\n"; } sc_bit bc0('0'); sc_bit bc1('1'); try { sc_bit foo('2'); } catch (sc_report) { cout << "Caught exception for sc_bit('2')\n"; } sc_bit blc0(sc_logic('0')); sc_bit blc1(sc_logic('1')); sc_bit blcx(sc_logic('X')); sc_bit bcop(bt); cout << bdef << bf << bt << b0 << b1 << bc0 << bc1 << blc0 << blc1 << blcx << bcop << endl; sc_bit b; b = bt; sc_assert(b); b = 0; sc_assert(!b); b = true; sc_assert(b.to_bool()); b = '0'; sc_assert(!b.to_bool()); b = sc_logic('1'); sc_assert(b.to_char() == '1'); b = bf; sc_assert(~b); b |= bt; sc_assert(b); b &= bf; sc_assert(!b); b |= 1; sc_assert(b); b &= 0; sc_assert(!b); b |= '1'; sc_assert(b); b &= '0'; sc_assert(!b); b |= true; sc_assert(b); b &= false; sc_assert(!b); b ^= bt; sc_assert(b); b ^= 1; sc_assert(!b); b ^= '1'; sc_assert(b); b ^= true; sc_assert(!b); sc_assert(b == bf); sc_assert(b == 0); sc_assert(b == '0'); sc_assert(b == false); b = 1; sc_assert(b == bt); sc_assert(b == 1); sc_assert(b == '1'); sc_assert(b == true); sc_assert(1 == b); sc_assert('1' == b); sc_assert(true == b); sc_assert(equal(b, bt)); sc_assert(equal(b, 1)); sc_assert(equal(b, '1')); sc_assert(equal(b, true)); sc_assert(equal(1, b)); sc_assert(equal('1', b)); sc_assert(equal(true, b)); b = 0; sc_assert(b != bt); sc_assert(b != 1); sc_assert(b != '1'); sc_assert(b != true); sc_assert(1 != b); sc_assert('1' != b); sc_assert(true != b); sc_assert(not_equal(b, bt)); sc_assert(not_equal(b, 1)); sc_assert(not_equal(b, '1')); sc_assert(not_equal(b, true)); sc_assert(not_equal(1, b)); sc_assert(not_equal('1', b)); sc_assert(not_equal(true, b)); // the following assertion is incorrect, because the b_not() method // is destructive, i.e., it implements something like b ~= void. /// sc_assert(b == b_not(b.b_not())); b.b_not(); sc_assert(b); sc_bit bx; b_not(bx, b0); sc_assert(bx); b_not(bx, b1); sc_assert(!bx); cout << (b0|b0) << (b0|b1) << (b1|b0) << (b1|b1) << endl; cout << (b0&b0) << (b0&b1) << (b1&b0) << (b1&b1) << endl; cout << (b0^b0) << (b0^b1) << (b1^b0) << (b1^b1) << endl; cout << (b0|0) << (b0|1) << (b1|0) << (b1|1) << endl; cout << (b0&0) << (b0&1) << (b1&0) << (b1&1) << endl; cout << (b0^0) << (b0^1) << (b1^0) << (b1^1) << endl; cout << (b0|'0') << (b0|'1') << (b1|'0') << (b1|'1') << endl; cout << (b0&'0') << (b0&'1') << (b1&'0') << (b1&'1') << endl; cout << (b0^'0') << (b0^'1') << (b1^'0') << (b1^'1') << endl; cout << (b0|true) << (b0|false) << (b1|true) << (b1|false) << endl; cout << (b0&true) << (b0&false) << (b1&true) << (b1&false) << endl; cout << (b0^true) << (b0^false) << (b1^true) << (b1^false) << endl; cout << (0|b0) << (0|b1) << (1|b0) << (1|b1) << endl; cout << (0&b0) << (0&b1) << (1&b0) << (1&b1) << endl; cout << (0^b0) << (0^b1) << (1^b0) << (1^b1) << endl; cout << ('0'|b0) << ('0'|b1) << ('1'|b0) << ('1'|b1) << endl; cout << ('0'&b0) << ('0'&b1) << ('1'&b0) << ('1'&b1) << endl; cout << ('0'^b0) << ('0'^b1) << ('1'^b0) << ('1'^b1) << endl; cout << (false|b0) << (false|b1) << (true|b0) << (true|b1) << endl; cout << (false&b0) << (false&b1) << (true&b0) << (true&b1) << endl; cout << (false^b0) << (false^b1) << (true^b0) << (true^b1) << endl; cout << b_or(b0,b0) << b_or(b0,b1) << b_or(b1,b0) << b_or(b1,b1) << endl; cout << b_and(b0,b0) << b_and(b0,b1) << b_and(b1,b0) << b_and(b1,b1) << endl; cout << b_xor(b0,b0) << b_xor(b0,b1) << b_xor(b1,b0) << b_xor(b1,b1) << endl; cout << b_or(b0,0) << b_or(b0,1) << b_or(b1,0) << b_or(b1,1) << endl; cout << b_and(b0,0) << b_and(b0,1) << b_and(b1,0) << b_and(b1,1) << endl; cout << b_xor(b0,0) << b_xor(b0,1) << b_xor(b1,0) << b_xor(b1,1) << endl; cout << b_or(b0,'0') << b_or(b0,'1') << b_or(b1,'0') << b_or(b1,'1') << endl; cout << b_and(b0,'0') << b_and(b0,'1') << b_and(b1,'0') << b_and(b1,'1') << endl; cout << b_xor(b0,'0') << b_xor(b0,'1') << b_xor(b1,'0') << b_xor(b1,'1') << endl; cout << b_or(b0,false) << b_or(b0,true) << b_or(b1,false) << b_or(b1,true) << endl; cout << b_and(b0,false) << b_and(b0,true) << b_and(b1,false) << b_and(b1,true) << endl; cout << b_xor(b0,false) << b_xor(b0,true) << b_xor(b1,false) << b_xor(b1,true) << endl; cout << b_or(0,b0) << b_or(0,b1) << b_or(1,b0) << b_or(1,b1) << endl; cout << b_and(0,b0) << b_and(0,b1) << b_and(1,b0) << b_and(1,b1) << endl; cout << b_xor(0,b0) << b_xor(0,b1) << b_xor(1,b0) << b_xor(1,b1) << endl; cout << b_or('0',b0) << b_or('0',b1) << b_or('1',b0) << b_or('1',b1) << endl; cout << b_and('0',b0) << b_and('0',b1) << b_and('1',b0) << b_and('1',b1) << endl; cout << b_xor('0',b0) << b_xor('0',b1) << b_xor('1',b0) << b_xor('1',b1) << endl; cout << b_or(false,b0) << b_or(false,b1) << b_or(true,b0) << b_or(true,b1) << endl; cout << b_and(false,b0) << b_and(false,b1) << b_and(true,b0) << b_and(true,b1) << endl; cout << b_xor(false,b0) << b_xor(false,b1) << b_xor(true,b0) << b_xor(true,b1) << endl; b_or(b, b0, b1); sc_assert(b); b_and(b, b0, b1); sc_assert(!b); b_xor(b, b0, b1); sc_assert(b); }
void checkBN(QString a, bool tr, QString b) { check(QString().sprintf("binaryName('%s', %s)", a.latin1(), bt(tr)), KRun::binaryName(a, tr), b); }
void run_bench() { if(do_sync) { std::cerr << "no support for do_sync" << std::endl; exit(1); } Bench b("luxio_bench", comment); { std::auto_ptr<Lux::IO::Btree> bt(new Lux::IO::Btree(Lux::IO::CLUSTER)); bt->open(dbfile, Lux::IO::DB_CREAT); b.cp("db init"); int ik = 0; if(NUM_PREW > 0) { for(int i = 0; i < NUM_PREW; ++ i) { int k = keys[ik++]; char buf[9]; sprintf(buf, "%08u", k); Lux::IO::data_t key = {buf, strlen(buf)}; Lux::IO::data_t val = {&k, sizeof(int)}; bt->put(&key, &val); // insert operation } // don't include preloading time fprintf(stderr, "prewrite %d keys done\n", ik); b.start(); b.cp("db init"); } for(int itx = 0; itx < NUM_TX; ++ itx) { for(int iw = 0; iw < NUM_W_PER_TX; ++ iw) { int k = keys[ik++]; char buf[9]; sprintf(buf, "%08u", k); Lux::IO::data_t key = {buf, strlen(buf)}; Lux::IO::data_t val = {&k, sizeof(int)}; bt->put(&key, &val); // insert operation } for(int ir = 0; ir < NUM_R_PER_TX; ++ ir) { int k = keys[rand() % ik]; char buf[9]; sprintf(buf, "%08u", k); Lux::IO::data_t key = {buf, strlen(buf)}; Lux::IO::data_t* val = bt->get(&key); bt->clean_data(val); } } b.cp("tx done"); if(NUM_W_PER_TX == 0) { // avoid measuring clean up time b.end();b.dump(); exit(0); } bt->close(); } b.end(); b.dump(); }
int main(int argc, char* argv[]) { // Choose a Butcher's table or define your own. ButcherTable bt(butcher_table_type); // Load the mesh. Mesh mesh; H2DReader mloader; mloader.load("cathedral.mesh", &mesh); // Perform initial mesh refinements. for(int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(); mesh.refine_towards_boundary(BDY_AIR, INIT_REF_NUM_BDY); mesh.refine_towards_boundary(BDY_GROUND, INIT_REF_NUM_BDY); // Enter boundary markers. BCTypes bc_types; bc_types.add_bc_dirichlet(Hermes::vector<std::string>(BDY_GROUND)); bc_types.add_bc_newton(BDY_AIR); // Enter Dirichlet boundary values. BCValues bc_values; bc_values.add_const(BDY_GROUND, TEMP_INIT); // Initialize an H1 space with default shapeset. H1Space space(&mesh, &bc_types, &bc_values, P_INIT); int ndof = Space::get_num_dofs(&space); info("ndof = %d.", ndof); // Previous time level solution (initialized by the external temperature). Solution u_prev_time(&mesh, TEMP_INIT); // Initialize weak formulation. WeakForm wf; wf.add_matrix_form(callback(stac_jacobian)); wf.add_vector_form(callback(stac_residual)); wf.add_matrix_form_surf(callback(bilinear_form_surf), BDY_AIR); wf.add_vector_form_surf(callback(linear_form_surf), BDY_AIR); // Project the initial condition on the FE space to obtain initial solution coefficient vector. info("Projecting initial condition to translate initial condition into a vector."); scalar* coeff_vec = new scalar[ndof]; OGProjection::project_global(&space, &u_prev_time, coeff_vec, matrix_solver); // Initialize the FE problem. bool is_linear = false; DiscreteProblem dp(&wf, &space, is_linear); // Time stepping loop: double current_time = 0.0; int ts = 1; do { // Perform one Runge-Kutta time step according to the selected Butcher's table. info("Runge-Kutta time step (t = %g, tau = %g, stages: %d).", current_time, time_step, bt.get_size()); bool verbose = true; if (!rk_time_step(current_time, time_step, &bt, coeff_vec, &dp, matrix_solver, verbose, NEWTON_TOL, NEWTON_MAX_ITER)) { error("Runge-Kutta time step failed, try to decrease time step size."); } // Convert coeff_vec into a new time level solution. Solution::vector_to_solution(coeff_vec, &space, &u_prev_time); // Update time. current_time += time_step; // Increase counter of time steps. ts++; } while (current_time < time_step*5); double sum = 0; for (int i = 0; i < ndof; i++) sum += coeff_vec[i]; printf("sum = %g\n", sum); int success = 1; if (fabs(sum - 3617.55) > 1e-1) success = 0; // Cleanup. delete [] coeff_vec; if (success == 1) { printf("Success!\n"); return ERR_SUCCESS; } else { printf("Failure!\n"); return ERR_FAILURE; } }
void DebugCLI::enterDebugger() { setCurrentSource( (core->callStack) ? (core->callStack->filename()) : 0 ); for (;;) { printIP(); core->console << "(asdb) "; Platform::GetInstance()->getUserInput(commandLine, kMaxCommandLine); commandLine[VMPI_strlen(commandLine)-1] = 0; if (!commandLine[0]) { VMPI_strcpy(commandLine, lastCommand); } else { VMPI_strcpy(lastCommand, commandLine); } currentToken = commandLine; char *command = nextToken(); int cmd = commandFor(command); switch (cmd) { case -1: // ambiguous, we already printed error message break; case CMD_INFO: info(); break; case CMD_BREAK: breakpoint(nextToken()); break; case CMD_DELETE: deleteBreakpoint(nextToken()); break; case CMD_LIST: list(nextToken()); break; case CMD_UNKNOWN: core->console << "Unknown command.\n"; break; case CMD_QUIT: Platform::GetInstance()->exit(0); break; case CMD_CONTINUE: return; case CMD_PRINT: print(nextToken()); break; case CMD_NEXT: stepOver(); return; case INFO_STACK_CMD: bt(); break; case CMD_FINISH: stepOut(); return; case CMD_STEP: stepInto(); return; case CMD_SET: set(); break; default: core->console << "Command not implemented.\n"; break; } } }
int main(int argc, char** argv) { boost::log::core::get()->set_filter(boost::log::trivial::severity >= boost::log::trivial::info); int32_t port = (argc >= 3) ? atoi(argv[2]) : 9092; csi::kafka::broker_address broker; if (argc >= 2) { broker = csi::kafka::broker_address(argv[1], port); } else { broker = csi::kafka::broker_address(DEFAULT_BROKER_ADDRESS, port); } boost::asio::io_service io_service; std::auto_ptr<boost::asio::io_service::work> work(new boost::asio::io_service::work(io_service)); boost::thread bt(boost::bind(&boost::asio::io_service::run, &io_service)); //HIGHLEVEL CONSUMER csi::kafka::highlevel_consumer consumer(io_service, TOPIC_NAME, 1000, 10000); consumer.connect( { broker } ); //std::vector<int64_t> result = consumer.get_offsets(); consumer.connect_forever({ broker } ); consumer.set_offset(csi::kafka::earliest_available_offset); boost::thread do_log([&consumer] { boost::accumulators::accumulator_set<double, boost::accumulators::stats<boost::accumulators::tag::rolling_mean> > acc(boost::accumulators::tag::rolling_window::window_size = 10); while (true) { boost::this_thread::sleep(boost::posix_time::seconds(1)); std::vector<csi::kafka::highlevel_consumer::metrics> metrics = consumer.get_metrics(); uint32_t rx_msg_sec_total = 0; uint32_t rx_kb_sec_total = 0; for (std::vector<csi::kafka::highlevel_consumer::metrics>::const_iterator i = metrics.begin(); i != metrics.end(); ++i) { std::cerr << "\t partiton:" << (*i).partition << "\t" << (*i).rx_msg_sec << " msg/s \t" << (*i).rx_kb_sec << "KB/s \troundtrip:" << (*i).rx_roundtrip << " ms" << std::endl; rx_msg_sec_total += (*i).rx_msg_sec; rx_kb_sec_total += (*i).rx_kb_sec; } std::cerr << "\t \t" << rx_msg_sec_total << " msg/s \t" << rx_kb_sec_total << "KB/s" << std::endl; } }); consumer.stream_async([](const boost::system::error_code& ec1, csi::kafka::error_codes ec2, std::shared_ptr<csi::kafka::fetch_response::topic_data::partition_data> response) { if (ec1 || ec2) { std::cerr << " decode error: ec1:" << ec1 << " ec2" << csi::kafka::to_string(ec2) << std::endl; return; } std::cerr << "+"; }); consumer.fetch(boost::bind(handle_fetch, &consumer, _1)); while (true) boost::this_thread::sleep(boost::posix_time::seconds(30)); consumer.close(); work.reset(); io_service.stop(); return EXIT_SUCCESS; }
int main(int argc, char* argv[]) { // Choose a Butcher's table or define your own. ButcherTable bt(butcher_table_type); if (bt.is_explicit()) info("Using a %d-stage explicit R-K method.", bt.get_size()); if (bt.is_diagonally_implicit()) info("Using a %d-stage diagonally implicit R-K method.", bt.get_size()); if (bt.is_fully_implicit()) info("Using a %d-stage fully implicit R-K method.", bt.get_size()); // Load the mesh. Mesh mesh; H2DReader mloader; mloader.load("../domain.mesh", &mesh); // Convert to quadrilaterals. mesh.convert_triangles_to_quads(); // Refine towards boundary. mesh.refine_towards_boundary("Bdy", 1, true); // Refine once towards vertex #4. mesh.refine_towards_vertex(4, 1); // Initialize solutions. CustomInitialConditionWave u_sln(&mesh); Solution v_sln(&mesh, 0.0); Hermes::vector<Solution*> slns(&u_sln, &v_sln); // Initialize the weak formulation. CustomWeakFormWave wf(time_step, C_SQUARED, &u_sln, &v_sln); // Initialize boundary conditions DefaultEssentialBCConst bc_essential("Bdy", 0.0); EssentialBCs bcs(&bc_essential); // Create x- and y- displacement space using the default H1 shapeset. H1Space u_space(&mesh, &bcs, P_INIT); H1Space v_space(&mesh, &bcs, P_INIT); info("ndof = %d.", Space::get_num_dofs(Hermes::vector<Space *>(&u_space, &v_space))); // Initialize the FE problem. DiscreteProblem dp(&wf, Hermes::vector<Space *>(&u_space, &v_space)); // Initialize Runge-Kutta time stepping. RungeKutta runge_kutta(&dp, &bt, matrix_solver); // Time stepping loop. double current_time = 0; int ts = 1; do { // Perform one Runge-Kutta time step according to the selected Butcher's table. info("Runge-Kutta time step (t = %g s, time_step = %g s, stages: %d).", current_time, time_step, bt.get_size()); bool jacobian_changed = false; bool verbose = true; if (!runge_kutta.rk_time_step(current_time, time_step, slns, slns, jacobian_changed, verbose)) error("Runge-Kutta time step failed, try to decrease time step size."); // Update time. current_time += time_step; } while (current_time < T_FINAL); double coord_x[4] = {1, 3, 5, 7}; double coord_y[4] = {1, 3, 5, 7}; info("Coordinate (1.0, 0.0) value = %lf", u_sln.get_pt_value(coord_x[0], coord_y[0])); info("Coordinate (3.0, 3.0) value = %lf", u_sln.get_pt_value(coord_x[1], coord_y[1])); info("Coordinate (5.0, 5.0) value = %lf", u_sln.get_pt_value(coord_x[2], coord_y[2])); info("Coordinate (7.0, 7.0) value = %lf", u_sln.get_pt_value(coord_x[3], coord_y[3])); info("Coordinate (1.0, 0.0) value = %lf", v_sln.get_pt_value(coord_x[0], coord_y[0])); info("Coordinate (3.0, 3.0) value = %lf", v_sln.get_pt_value(coord_x[1], coord_y[1])); info("Coordinate (5.0, 5.0) value = %lf", v_sln.get_pt_value(coord_x[2], coord_y[2])); info("Coordinate (7.0, 7.0) value = %lf", v_sln.get_pt_value(coord_x[3], coord_y[3])); double t_value[8] = {0.212655, 0.000163, 0.000000, 0.000000, -0.793316, 0.007255, 0.000001, 0.000000}; bool success = true; for (int i = 0; i < 4; i++) { if (fabs(t_value[i] - u_sln.get_pt_value(coord_x[i], coord_y[i])) > 1E-6) success = false; } for (int i = 4; i < 8; i++) { if (fabs(t_value[i] - v_sln.get_pt_value(coord_x[i-4], coord_y[i-4])) > 1E-6) success = false; } if (success) { printf("Success!\n"); return ERR_SUCCESS; } else { printf("Failure!\n"); return ERR_FAILURE; } // Wait for the view to be closed. View::wait(); return 0; }
int main(int argc, char* argv[]) { // Choose a Butcher's table or define your own. ButcherTable bt(butcher_table_type); if (bt.is_explicit()) info("Using a %d-stage explicit R-K method.", bt.get_size()); if (bt.is_diagonally_implicit()) info("Using a %d-stage diagonally implicit R-K method.", bt.get_size()); if (bt.is_fully_implicit()) info("Using a %d-stage fully implicit R-K method.", bt.get_size()); // Load the mesh. Mesh mesh; H2DReader mloader; mloader.load("cathedral.mesh", &mesh); // Perform initial mesh refinements. for(int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(); mesh.refine_towards_boundary(BDY_AIR, INIT_REF_NUM_BDY); mesh.refine_towards_boundary(BDY_GROUND, INIT_REF_NUM_BDY); // Enter boundary markers. BCTypes bc_types; bc_types.add_bc_dirichlet(Hermes::vector<std::string>(BDY_GROUND)); bc_types.add_bc_newton(BDY_AIR); // Enter Dirichlet boundary values. BCValues bc_values; bc_values.add_const(BDY_GROUND, TEMP_INIT); // Initialize an H1 space with default shapeset. H1Space space(&mesh, &bc_types, &bc_values, P_INIT); int ndof = Space::get_num_dofs(&space); info("ndof = %d.", ndof); // Previous and next time level solutions. Solution* sln_time_prev = new Solution(&mesh, TEMP_INIT); Solution* sln_time_new = new Solution(&mesh); // Initialize weak formulation. WeakForm wf; wf.add_matrix_form(callback(stac_jacobian_vol)); wf.add_vector_form(callback(stac_residual_vol), HERMES_ANY, sln_time_prev); wf.add_matrix_form_surf(callback(stac_jacobian_surf), BDY_AIR, sln_time_prev); wf.add_vector_form_surf(callback(stac_residual_surf), BDY_AIR, sln_time_prev); // Initialize the FE problem. bool is_linear = false; DiscreteProblem dp(&wf, &space, is_linear); // Time stepping loop: double current_time = time_step; int ts = 1; do { // Perform one Runge-Kutta time step according to the selected Butcher's table. info("Runge-Kutta time step (t = %g s, tau = %g s, stages: %d).", current_time, time_step, bt.get_size()); bool verbose = true; bool is_linear = true; if (!rk_time_step(current_time, time_step, &bt, sln_time_prev, sln_time_new, &dp, matrix_solver, verbose, is_linear)) { error("Runge-Kutta time step failed, try to decrease time step size."); } // Convert coeff_vec into a new time level solution. //Solution::vector_to_solution(coeff_vec, &space, &u_prev_time); // Increase current time and time step counter. current_time += time_step; ts++; } while (current_time < T_FINAL); info("Coordinate (-2.0, 2.0) value = %lf", sln_time_new->get_pt_value(-2.0, 2.0)); info("Coordinate (-1.0, 2.0) value = %lf", sln_time_new->get_pt_value(-1.0, 2.0)); info("Coordinate ( 0.0, 2.0) value = %lf", sln_time_new->get_pt_value(0.0, 2.0)); info("Coordinate ( 1.0, 2.0) value = %lf", sln_time_new->get_pt_value(1.0, 2.0)); info("Coordinate ( 2.0, 2.0) value = %lf", sln_time_new->get_pt_value(2.0, 2.0)); bool success = true; if (fabs(sln_time_new->get_pt_value(-2.0, 2.0) - 9.999982) > 1E-6) success = false; if (fabs(sln_time_new->get_pt_value(-1.0, 2.0) - 10.000002) > 1E-6) success = false; if (fabs(sln_time_new->get_pt_value( 0.0, 2.0) - 9.999995) > 1E-6) success = false; if (fabs(sln_time_new->get_pt_value( 1.0, 2.0) - 10.000002) > 1E-6) success = false; if (fabs(sln_time_new->get_pt_value( 2.0, 2.0) - 9.999982) > 1E-6) success = false; if (success) { printf("Success!\n"); return ERR_SUCCESS; } else { printf("Failure!\n"); return ERR_FAILURE; } }
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { return bt(inorder, postorder, 0, 0, postorder.size()); }
int main(int argc, char* argv[]) { // Choose a Butcher's table or define your own. ButcherTable bt(butcher_table_type); if (bt.is_explicit()) info("Using a %d-stage explicit R-K method.", bt.get_size()); if (bt.is_diagonally_implicit()) info("Using a %d-stage diagonally implicit R-K method.", bt.get_size()); if (bt.is_fully_implicit()) info("Using a %d-stage fully implicit R-K method.", bt.get_size()); // Load the mesh. Mesh mesh, basemesh; MeshReaderH2D mloader; mloader.load("square.mesh", &basemesh); mesh.copy(&basemesh); // Initial mesh refinements. for(int i = 0; i < INIT_GLOB_REF_NUM; i++) mesh.refine_all_elements(); mesh.refine_towards_boundary("Top", INIT_REF_NUM_BDY); // Initialize boundary conditions. CustomEssentialBCNonConst bc_essential(Hermes::vector<std::string>("Bottom", "Right", "Top", "Left")); EssentialBCs<double> bcs(&bc_essential); // Create an H1 space with default shapeset. H1Space<double> space(&mesh, &bcs, P_INIT); int ndof_coarse = Space<double>::get_num_dofs(&space); info("ndof_coarse = %d.", ndof_coarse); // Zero initial solution. This is why we use H_OFFSET. ZeroSolution h_time_prev(&mesh), h_time_new(&mesh); // Initialize the constitutive relations. ConstitutiveRelations* constitutive_relations; if(constitutive_relations_type == CONSTITUTIVE_GENUCHTEN) constitutive_relations = new ConstitutiveRelationsGenuchten(ALPHA, M, N, THETA_S, THETA_R, K_S, STORATIVITY); else constitutive_relations = new ConstitutiveRelationsGardner(ALPHA, THETA_S, THETA_R, K_S); // Initialize the weak formulation. CustomWeakFormRichardsRK wf(constitutive_relations); // Initialize the FE problem. DiscreteProblem<double> dp(&wf, &space); // Create a refinement selector. H1ProjBasedSelector<double> selector(CAND_LIST, CONV_EXP, H2DRS_DEFAULT_ORDER); // Visualize initial condition. char title[100]; ScalarView view("Initial condition", new WinGeom(0, 0, 440, 350)); OrderView ordview("Initial mesh", new WinGeom(445, 0, 440, 350)); view.show(&h_time_prev); ordview.show(&space); // DOF and CPU convergence graphs initialization. SimpleGraph graph_dof, graph_cpu; // Time measurement. TimePeriod cpu_time; cpu_time.tick(); // Time stepping loop. double current_time = 0; int ts = 1; do { // Periodic global derefinement. if (ts > 1 && ts % UNREF_FREQ == 0) { info("Global mesh derefinement."); switch (UNREF_METHOD) { case 1: mesh.copy(&basemesh); space.set_uniform_order(P_INIT); break; case 2: mesh.unrefine_all_elements(); space.set_uniform_order(P_INIT); break; case 3: space.unrefine_all_mesh_elements(); space.adjust_element_order(-1, -1, P_INIT, P_INIT); break; default: error("Wrong global derefinement method."); } ndof_coarse = Space<double>::get_num_dofs(&space); } // Spatial adaptivity loop. Note: h_time_prev must not be changed // during spatial adaptivity. bool done = false; int as = 1; double err_est; do { info("Time step %d, adaptivity step %d:", ts, as); // Construct globally refined reference mesh and setup reference space. Space<double>* ref_space = Space<double>::construct_refined_space(&space); int ndof_ref = Space<double>::get_num_dofs(ref_space); // Time measurement. cpu_time.tick(); // Initialize Runge-Kutta time stepping. RungeKutta<double> runge_kutta(&wf, ref_space, &bt, matrix_solver); // Perform one Runge-Kutta time step according to the selected Butcher's table. info("Runge-Kutta time step (t = %g s, tau = %g s, stages: %d).", current_time, time_step, bt.get_size()); bool freeze_jacobian = false; bool block_diagonal_jacobian = false; bool verbose = true; double damping_coeff = 1.0; double max_allowed_residual_norm = 1e10; try { runge_kutta.rk_time_step_newton(current_time, time_step, &h_time_prev, &h_time_new, freeze_jacobian, block_diagonal_jacobian, verbose, NEWTON_TOL, NEWTON_MAX_ITER, damping_coeff, max_allowed_residual_norm); } catch(Exceptions::Exception& e) { e.printMsg(); error("Runge-Kutta time step failed"); } // Project the fine mesh solution onto the coarse mesh. Solution<double> sln_coarse; info("Projecting fine mesh solution on coarse mesh for error estimation."); OGProjection<double>::project_global(&space, &h_time_new, &sln_coarse, matrix_solver); // Calculate element errors and total error estimate. info("Calculating error estimate."); Adapt<double>* adaptivity = new Adapt<double>(&space); double err_est_rel_total = adaptivity->calc_err_est(&sln_coarse, &h_time_new) * 100; // Report results. info("ndof_coarse: %d, ndof_ref: %d, err_est_rel: %g%%", Space<double>::get_num_dofs(&space), Space<double>::get_num_dofs(ref_space), err_est_rel_total); // Time measurement. cpu_time.tick(); // If err_est too large, adapt the mesh. if (err_est_rel_total < ERR_STOP) done = true; else { info("Adapting the coarse mesh."); done = adaptivity->adapt(&selector, THRESHOLD, STRATEGY, MESH_REGULARITY); if (Space<double>::get_num_dofs(&space) >= NDOF_STOP) done = true; else // Increase the counter of performed adaptivity steps. as++; } // Clean up. delete adaptivity; if(!done) { delete h_time_new.get_space(); delete h_time_new.get_mesh(); } } while (done == false); // Add entry to DOF and CPU convergence graphs. graph_dof.add_values(current_time, Space<double>::get_num_dofs(&space)); graph_dof.save("conv_dof_est.dat"); graph_cpu.add_values(current_time, cpu_time.accumulated()); graph_cpu.save("conv_cpu_est.dat"); // Visualize the solution and mesh. char title[100]; sprintf(title, "Solution, time %g", current_time); view.set_title(title); view.show_mesh(false); view.show(&h_time_new); sprintf(title, "Mesh, time %g", current_time); ordview.set_title(title); ordview.show(&space); // Copy last reference solution into h_time_prev. h_time_prev.copy(&h_time_new); delete h_time_new.get_mesh(); // Increase current time and counter of time steps. current_time += time_step; ts++; } while (current_time < T_FINAL); // Wait for all views to be closed. View::wait(); return 0; }
int main(int argc, char** argv) { boost::log::trivial::severity_level log_level; boost::program_options::options_description desc("options"); desc.add_options() ("help", "produce help message") ("topic", boost::program_options::value<std::string>(), "topic") ("broker", boost::program_options::value<std::string>(), "broker") ("partition", boost::program_options::value<std::string>(), "partition") ("key_schema_id", boost::program_options::value<std::string>(), "key_schema_id") ("write,w", boost::program_options::bool_switch()->default_value(false), "write to kafka") ("log_level", boost::program_options::value<boost::log::trivial::severity_level>(&log_level)->default_value(boost::log::trivial::info), "log level to output"); ; boost::program_options::variables_map vm; try { boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm); } catch (std::exception& e) { std::cout << "bad command line: " << e.what() << std::endl; return 0; } boost::program_options::notify(vm); boost::log::core::get()->set_filter(boost::log::trivial::severity >= log_level); BOOST_LOG_TRIVIAL(info) << "loglevel " << log_level; if (vm.count("help")) { std::cout << desc << std::endl; return 0; } int32_t kafka_port = 9092; std::vector<csi::kafka::broker_address> brokers; if (vm.count("broker")) { std::string s = vm["broker"].as<std::string>(); size_t last_colon = s.find_last_of(':'); if (last_colon != std::string::npos) kafka_port = atoi(s.substr(last_colon + 1).c_str()); s = s.substr(0, last_colon); // now find the brokers... size_t last_separator = s.find_last_of(','); while (last_separator != std::string::npos) { std::string host = s.substr(last_separator + 1); brokers.push_back(csi::kafka::broker_address(host, kafka_port)); s = s.substr(0, last_separator); last_separator = s.find_last_of(','); } brokers.push_back(csi::kafka::broker_address(s, kafka_port)); } else { std::cout << "--broker must be specified" << std::endl; return 0; } int32_t schema_registry_port = 8081; std::vector<csi::kafka::broker_address> schema_registrys; std::string used_schema_registry; std::string topic; if (vm.count("topic")) { topic = vm["topic"].as<std::string>(); } else { std::cout << "--topic must be specified" << std::endl; return -1; } std::vector<int> key_schemas; bool delete_all = false; if (vm.count("key_schema_id")) { std::string s = vm["key_schema_id"].as<std::string>(); //special case * if (s == "*") { delete_all = true; } else { // now find the brokers... size_t last_separator = s.find_last_of(','); while (last_separator != std::string::npos) { std::string token = s.substr(last_separator + 1); key_schemas.push_back(atoi(token.c_str())); s = s.substr(0, last_separator); last_separator = s.find_last_of(','); } key_schemas.push_back(atoi(s.c_str())); } } else { std::cout << "--key_schema_id must be specified" << std::endl; return 0; } std::vector<int> partition_mask; if (vm.count("partition")) { std::string s = vm["partition"].as<std::string>(); //special case * if (s == "*") { } else { // now find the brokers... size_t last_separator = s.find_last_of(','); while (last_separator != std::string::npos) { std::string token = s.substr(last_separator + 1); partition_mask.push_back(atoi(token.c_str())); s = s.substr(0, last_separator); last_separator = s.find_last_of(','); } partition_mask.push_back(atoi(s.c_str())); } } bool dry_run = true; if (vm["write"].as<bool>()) dry_run = false; boost::asio::io_service io_service; std::auto_ptr<boost::asio::io_service::work> work(new boost::asio::io_service::work(io_service)); boost::thread bt(boost::bind(&boost::asio::io_service::run, &io_service)); csi::kafka::highlevel_consumer consumer(io_service, topic, partition_mask, 500, 1000000); csi::kafka::highlevel_producer producer(io_service, topic, -1, 500, 1000000); consumer.connect(brokers); //std::vector<int64_t> result = consumer.get_offsets(); consumer.connect_forever(brokers); { producer.connect(brokers); BOOST_LOG_TRIVIAL(info) << "connected to kafka"; producer.connect_forever(brokers); } std::map<int, int64_t> highwater_mark_offset; consumer.set_offset(csi::kafka::latest_offsets); // this is assuming to much - what if anything goes wrong... auto r = consumer.fetch(); for (std::vector<csi::kafka::rpc_result<csi::kafka::fetch_response>>::const_iterator i = r.begin(); i != r.end(); ++i) { if (i->ec) continue; // or die?? for (std::vector<csi::kafka::fetch_response::topic_data>::const_iterator j = (*i)->topics.begin(); j != (*i)->topics.end(); ++j) { for (std::vector<std::shared_ptr<csi::kafka::fetch_response::topic_data::partition_data>>::const_iterator k = j->partitions.begin(); k != j->partitions.end(); ++k) { if ((*k)->error_code) continue; // or die?? highwater_mark_offset[(*k)->partition_id] = (*k)->highwater_mark_offset; } } } consumer.set_offset(csi::kafka::earliest_available_offset); std::map<int, int64_t> last_offset; int64_t _remaining_records = 1; std::map<boost::uuids::uuid, std::shared_ptr<csi::kafka::basic_message>> _to_delete; consumer.stream_async([delete_all, key_schemas, &last_offset, &highwater_mark_offset, &_remaining_records, &_to_delete](const boost::system::error_code& ec1, csi::kafka::error_codes ec2, std::shared_ptr<csi::kafka::fetch_response::topic_data::partition_data> response) { if (ec1 || ec2) { BOOST_LOG_TRIVIAL(error) << "stream failed ec1::" << ec1 << " ec2" << csi::kafka::to_string(ec2); return; } if (response->error_code) { BOOST_LOG_TRIVIAL(error) << "stream failed for partition: " << response->partition_id << " ec:" << csi::kafka::to_string((csi::kafka::error_codes) response->error_code); return; } int partition_id = response->partition_id; int64_t lo = -1; for (std::vector<std::shared_ptr<csi::kafka::basic_message>>::const_iterator i = response->messages.begin(); i != response->messages.end(); ++i) { if ((*i)->key.is_null()) { //BOOST_LOG_TRIVIAL(warning) << "got key==NULL"; continue; } if ((*i)->key.size() < 4) { BOOST_LOG_TRIVIAL(warning) << "got keysize==" << (*i)->key.size(); continue; } int32_t be; memcpy(&be, (*i)->key.data(), 4); int32_t key_schema_id = boost::endian::big_to_native<int32_t>(be); // should we kill this schema? if (delete_all || std::find(std::begin(key_schemas), std::end(key_schemas), key_schema_id) != std::end(key_schemas)) { boost::uuids::uuid key = get_md5((*i)->key.data(), (*i)->key.size()); //not already dead if (!(*i)->value.is_null()) { std::map<boost::uuids::uuid, std::shared_ptr<csi::kafka::basic_message>>::iterator item = _to_delete.find(key); if (item == _to_delete.end()) { std::shared_ptr<csi::kafka::basic_message> msg(new csi::kafka::basic_message()); msg->key = (*i)->key; msg->value.set_null(true); msg->partition = partition_id; // make sure we write the same partion that we got the message from... _to_delete[key] = msg; } } else { //we must search map to se if we should refrain from deleting the item since a deleete marker is already on kafka. (the previous messages has not yet been removed by compaction) //std::map<boost::uuids::uuid, std::shared_ptr<csi::kafka::basic_message>> std::map<boost::uuids::uuid, std::shared_ptr<csi::kafka::basic_message>>::iterator item = _to_delete.find(key); if (item != _to_delete.end()) { _to_delete.erase(item); } } } lo = (*i)->offset; } if (lo >= 0) last_offset[partition_id] = lo; int64_t remaining_records = 0; for (std::map<int, int64_t>::const_iterator i = highwater_mark_offset.begin(); i != highwater_mark_offset.end(); ++i) remaining_records += ((int64_t)(i->second - 1)) - (int64_t)last_offset[i->first]; _remaining_records = remaining_records; }); while (true) { boost::this_thread::sleep(boost::posix_time::seconds(1)); BOOST_LOG_TRIVIAL(info) << " to be deleted: " << _to_delete.size() << ", remaining: " << _remaining_records; if (_remaining_records <= 0) break; } BOOST_LOG_TRIVIAL(info) << "consumer finished"; consumer.close(); BOOST_LOG_TRIVIAL(info) << "consumer closed"; BOOST_LOG_TRIVIAL(info) << "sending delete messages"; std::vector<std::shared_ptr<csi::kafka::basic_message>> messages; for (std::map<boost::uuids::uuid, std::shared_ptr<csi::kafka::basic_message>>::iterator i = _to_delete.begin(); i != _to_delete.end(); ++i) { messages.push_back(i->second); } if (messages.size()) { if (!dry_run) { producer.send_sync(messages); } else { std::cout << "dry run - should write " << messages.size() << " add -w to delete from kafka" << std::endl; } } else { std::cout << "uptodate - nothing to do" << std::endl; } BOOST_LOG_TRIVIAL(info) << "producer finished"; producer.close(); BOOST_LOG_TRIVIAL(info) << "producer closed"; boost::this_thread::sleep(boost::posix_time::seconds(5)); BOOST_LOG_TRIVIAL(info) << "done"; work.reset(); io_service.stop(); return EXIT_SUCCESS; }
int main(int argc, char* argv[]) { // Instantiate a class with global functions. Hermes2D hermes2d; // Choose a Butcher's table or define your own. ButcherTable bt(butcher_table_type); if (bt.is_explicit()) info("Using a %d-stage explicit R-K method.", bt.get_size()); if (bt.is_diagonally_implicit()) info("Using a %d-stage diagonally implicit R-K method.", bt.get_size()); if (bt.is_fully_implicit()) info("Using a %d-stage fully implicit R-K method.", bt.get_size()); // Load the mesh. Mesh mesh; H2DReader mloader; mloader.load("../wall.mesh", &mesh); // Perform initial mesh refinements. for(int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(); mesh.refine_towards_boundary(BDY_RIGHT, 2); mesh.refine_towards_boundary(BDY_FIRE, INIT_REF_NUM_BDY); // Initialize essential boundary conditions (none). EssentialBCs bcs; // Initialize an H1 space with default shapeset. H1Space space(&mesh, &bcs, P_INIT); int ndof = Space::get_num_dofs(&space); info("ndof = %d.", ndof); // Previous and next time level solutions. Solution* sln_time_prev = new Solution(&mesh, TEMP_INIT); Solution* sln_time_new = new Solution(&mesh); Solution* time_error_fn = new Solution(&mesh, 0.0); // Initialize the weak formulation. double current_time = 0; CustomWeakFormHeatRK wf(BDY_FIRE, BDY_AIR, ALPHA_FIRE, ALPHA_AIR, RHO, HEATCAP, TEMP_EXT_AIR, TEMP_INIT, ¤t_time); // Initialize the FE problem. DiscreteProblem dp(&wf, &space); // Graph for time step history. SimpleGraph time_step_graph; info("Time step history will be saved to file time_step_history.dat."); // Initialize Runge-Kutta time stepping. RungeKutta runge_kutta(&dp, &bt, matrix_solver); // Time stepping loop: int ts = 1; do { // Perform one Runge-Kutta time step according to the selected Butcher's table. info("Runge-Kutta time step (t = %g s, tau = %g s, stages: %d).", current_time, time_step, bt.get_size()); bool jacobian_changed = false; bool verbose = true; if (!runge_kutta.rk_time_step(current_time, time_step, sln_time_prev, sln_time_new, time_error_fn, jacobian_changed, verbose)) { error("Runge-Kutta time step failed, try to decrease time step size."); } // Calculate relative time stepping error and decide whether the // time step can be accepted. If not, then the time step size is // reduced and the entire time step repeated. If yes, then another // check is run, and if the relative error is very low, time step // is increased. double rel_err_time = hermes2d.calc_norm(time_error_fn, HERMES_H1_NORM) / hermes2d.calc_norm(sln_time_new, HERMES_H1_NORM) * 100; info("rel_err_time = %g%%", rel_err_time); if (rel_err_time > TIME_TOL_UPPER) { info("rel_err_time above upper limit %g%% -> decreasing time step from %g to %g and restarting time step.", TIME_TOL_UPPER, time_step, time_step * TIME_STEP_DEC_RATIO); time_step *= TIME_STEP_DEC_RATIO; continue; } if (rel_err_time < TIME_TOL_LOWER) { info("rel_err_time = below lower limit %g%% -> increasing time step from %g to %g", TIME_TOL_UPPER, time_step, time_step * TIME_STEP_INC_RATIO); time_step *= TIME_STEP_INC_RATIO; } // Add entry to the timestep graph. time_step_graph.add_values(current_time, time_step); time_step_graph.save("time_step_history.dat"); // Update time. current_time += time_step; // Copy solution for the new time step. sln_time_prev->copy(sln_time_new); // Increase counter of time steps. ts++; } while (current_time < T_FINAL); info("Coordinate (1.0, 0.0) value = %lf", sln_time_prev->get_pt_value(1.0, 0.0)); info("Coordinate (1.5, 0.0) value = %lf", sln_time_prev->get_pt_value(1.5, 0.0)); info("Coordinate (2.0, 0.0) value = %lf", sln_time_prev->get_pt_value(2.0, 0.0)); info("Coordinate (2.5, 0.0) value = %lf", sln_time_prev->get_pt_value(2.5, 0.0)); info("Coordinate (3.0, 0.0) value = %lf", sln_time_prev->get_pt_value(3.0, 0.0)); info("Coordinate (3.5, 0.0) value = %lf", sln_time_prev->get_pt_value(3.5, 0.0)); double coor_x[6] = {1.0, 1.5, 2.0, 2.5, 3.0, 3.5}; double value[6] = {28.942554, 38.108420, 48.615642, 59.122873, 68.288669, 74.772370}; bool success = true; for (int i = 0; i < 6; i++) { if (fabs(value[i] - sln_time_prev->get_pt_value(coor_x[i], 0)) > 1E-6) success = false; } // Cleanup. delete sln_time_prev; delete sln_time_new; delete time_error_fn; if (success) { printf("Success!\n"); return ERR_SUCCESS; } else { printf("Failure!\n"); return ERR_FAILURE; } }
int main(int , char**) { std::cout << "Starting hard_work, ready?"; std::cin.ignore(); std::thread my_thread(hard_work); my_thread.join(); std::cout << "Starting background_task, ready?"; std::cin.ignore(); background_task bt; bt(); std::thread my_thread2(bt); //std::thread my_thread2({background_task()}); my_thread2.join(); std::cout << "Starting lambda, ready?"; std::cin.ignore(); std::thread my_thread3( []() { hard_work(); more_hard_work_after_hard_work(); }); my_thread3.join(); std::cout << "ready to crash?"; std::cin.ignore(); { std::thread my_thread( []() { hard_work(); more_hard_work_after_hard_work(); }); my_thread.detach(); } { std::cout << "ready to pass arguments?" << std::endl; std::cin.ignore(); int a = 42; std::thread my_thread(foo, a, "soy un thread!"); std::string str = "soy otro thread"; std::thread my_thread2([](int a1, const std::string& a2) { std::cout << "t2: a1=" << a1 << " a2=" << a2 << std::endl; }, a, str); std::thread my_thread2_capture([&]() { std::cout << "t2 capturing: a1=" << a << " a2=" << str << std::endl; }); background_task_with_args bt1; std::thread my_thread3(bt1,a, "casi el final..."); background_task_with_args_in_ctor bt2(a, "el final del todo"); std::thread my_thread4(bt2); my_thread.join(); my_thread2.join(); my_thread2_capture.join(); my_thread3.join(); my_thread4.join(); } { //std::cout << "ready to pass arguments (oops)?" << std::endl; //std::cin.ignore(); //ooops(1000); //std::cin.ignore(); } { std::unique_ptr<big_object> bo(new big_object); bo->load("machodedatos.raw"); //std::thread process_thread(process_big_object, std::move(bo)); //process_thread.join(); } { std::thread r_thread = return_thread(); join_thread(std::move(r_thread)); } { std::cout << "ready to pass arguments with ScopedThread?" << std::endl; std::cin.ignore(); int a = 42; ScopedThread my_thread(std::thread(foo, a, "soy un thread!")); std::string str = "soy otro thread"; ScopedThread my_thread2(std::thread([](int a1, const std::string& a2) { std::cout << "t2: a1=" << a1 << " a2=" << a2 << std::endl; }, a, str)); ScopedThread my_thread3(std::thread([&]() { std::cout << "t2 capturing: a1=" << a << " a2=" << str << std::endl; })); background_task_with_args bt1; ScopedThread my_thread4(std::thread(bt1,a, "casi el final...")); background_task_with_args_in_ctor bt2(a, "el final del todo"); ScopedThread my_thread5((std::thread(bt2))); } { std::cout << "ready to count cpus?" << std::endl; std::cin.ignore(); std::cout << "num of cpus:" << std::thread::hardware_concurrency() << std::endl; } { std::cout << "ready to check ids?" << std::endl; std::cin.ignore(); std::cout << "main thread id=" << std::this_thread::get_id() << std::endl; std::thread t(check_id); std::thread::id id = t.get_id(); t.join(); std::cout << "thread id=" << id << std::endl; } { std::cout << "ready to fill and find in a list?" << std::endl; std::cin.ignore(); auto producer_function = [](unsigned int numelements) { for(unsigned int i=0;i<numelements;i++) { add_to_list(i); std::this_thread::sleep_for(std::chrono::milliseconds(1)); } }; ScopedThread thread_producer1(std::thread(producer_function,100)); ScopedThread thread_producer2(std::thread(producer_function,100)); auto finder_function = [](unsigned int value_to_find) { auto attempts = 0u; bool found = false; while(!found && attempts < 100) { found = contains_in_list(value_to_find); attempts++; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } if(found) std::cout << std::this_thread::get_id() << ": Found! after " << attempts << " attempts" << std::endl; else std::cout << std::this_thread::get_id() << ": not found! :(" << std::endl; }; ScopedThread thread_finder1(std::thread(finder_function,88)); ScopedThread thread_finder2(std::thread(finder_function,101)); } { std::cout << "ready to crush a stack?" << std::endl; std::cin.ignore(); std::stack<int> s; s.push(42); if(!s.empty()) { int const value = s.top(); s.pop(); foo(value, "do_something"); } std::atomic<int> producersWorking(0); std::atomic<bool> started(false); ThreadSafeStack<int> ts; auto producer_function = [&started, &producersWorking](ThreadSafeStack<int>& ts, unsigned int numelements) { producersWorking++; started = true; for(unsigned int i=0;i<numelements;i++) { ts.push(i); std::this_thread::sleep_for(std::chrono::milliseconds(1)); } producersWorking--; }; auto consumer_function = [&started, &producersWorking](ThreadSafeStack<int>& ts) { while (!started) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } while(producersWorking > 0) { int value; if (ts.pop(value)) { std::cout << std::this_thread::get_id() << ":popped value=" << value << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } std::cout << std::this_thread::get_id() << ":stack is empty" << std::endl; }; ScopedThread thread_producer1(std::thread(producer_function,std::ref(ts),100)); ScopedThread thread_producer2(std::thread(producer_function,std::ref(ts),100)); ScopedThread thread_producer3(std::thread(producer_function, std::ref(ts), 100)); ScopedThread thread_producer4(std::thread(producer_function, std::ref(ts), 100)); ScopedThread thread_consumer1(std::thread(consumer_function,std::ref(ts))); ScopedThread thread_consumer2(std::thread(consumer_function,std::ref(ts))); ScopedThread thread_consumer3(std::thread(consumer_function, std::ref(ts))); } return EXIT_SUCCESS; }
int main(int argc, char* argv[]) { try { // Sanity check for omega. double K_squared = Hermes::sqr(OMEGA / M_PI) * (OMEGA - 2) / (1 - OMEGA); if (K_squared <= 0) throw Hermes::Exceptions::Exception("Wrong choice of omega, K_squared < 0!"); double K_norm_coeff = std::sqrt(K_squared) / std::sqrt(Hermes::sqr(K_x) + Hermes::sqr(K_y)); Hermes::Mixins::Loggable::Static::info("Wave number K = %g", std::sqrt(K_squared)); K_x *= K_norm_coeff; K_y *= K_norm_coeff; // Wave number. double K = std::sqrt(Hermes::sqr(K_x) + Hermes::sqr(K_y)); // Choose a Butcher's table or define your own. ButcherTable bt(butcher_table); if (bt.is_explicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage explicit R-K method.", bt.get_size()); if (bt.is_diagonally_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage diagonally implicit R-K method.", bt.get_size()); if (bt.is_fully_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage fully implicit R-K method.", bt.get_size()); // Load the mesh. MeshSharedPtr E_mesh(new Mesh), H_mesh(new Mesh), P_mesh(new Mesh); MeshReaderH2D mloader; mloader.load("domain.mesh", E_mesh); mloader.load("domain.mesh", H_mesh); mloader.load("domain.mesh", P_mesh); // Perform initial mesh refinemets. for (int i = 0; i < INIT_REF_NUM; i++) { E_mesh->refine_all_elements(); H_mesh->refine_all_elements(); P_mesh->refine_all_elements(); } // Initialize solutions. double current_time = 0; MeshFunctionSharedPtr<double> E_time_prev(new CustomInitialConditionE(E_mesh, current_time, OMEGA, K_x, K_y)); MeshFunctionSharedPtr<double> H_time_prev(new CustomInitialConditionH(H_mesh, current_time, OMEGA, K_x, K_y)); MeshFunctionSharedPtr<double> P_time_prev(new CustomInitialConditionP(P_mesh, current_time, OMEGA, K_x, K_y)); std::vector<MeshFunctionSharedPtr<double> > slns_time_prev({ E_time_prev, H_time_prev, P_time_prev }); MeshFunctionSharedPtr<double> E_time_new(new Solution<double>(E_mesh)), H_time_new(new Solution<double>(H_mesh)), P_time_new(new Solution<double>(P_mesh)); MeshFunctionSharedPtr<double> E_time_new_coarse(new Solution<double>(E_mesh)), H_time_new_coarse(new Solution<double>(H_mesh)), P_time_new_coarse(new Solution<double>(P_mesh)); std::vector<MeshFunctionSharedPtr<double> > slns_time_new({ E_time_new, H_time_new, P_time_new }); // Initialize the weak formulation. WeakFormSharedPtr<double> wf(new CustomWeakFormMD(OMEGA, K_x, K_y, MU_0, EPS_0, EPS_INF, EPS_Q, TAU)); // Initialize boundary conditions DefaultEssentialBCConst<double> bc_essential("Bdy", 0.0); EssentialBCs<double> bcs(&bc_essential); SpaceSharedPtr<double> E_space(new HcurlSpace<double>(E_mesh, &bcs, P_INIT)); SpaceSharedPtr<double> H_space(new H1Space<double>(H_mesh, NULL, P_INIT)); //L2Space<double> H_space(mesh, P_INIT)); SpaceSharedPtr<double> P_space(new HcurlSpace<double>(P_mesh, &bcs, P_INIT)); std::vector<SpaceSharedPtr<double> > spaces = std::vector<SpaceSharedPtr<double> >({ E_space, H_space, P_space }); // Initialize views. ScalarView E1_view("Solution E1", new WinGeom(0, 0, 400, 350)); E1_view.fix_scale_width(50); ScalarView E2_view("Solution E2", new WinGeom(410, 0, 400, 350)); E2_view.fix_scale_width(50); ScalarView H_view("Solution H", new WinGeom(0, 410, 400, 350)); H_view.fix_scale_width(50); ScalarView P1_view("Solution P1", new WinGeom(410, 410, 400, 350)); P1_view.fix_scale_width(50); ScalarView P2_view("Solution P2", new WinGeom(820, 410, 400, 350)); P2_view.fix_scale_width(50); // Visualize initial conditions. char title[100]; sprintf(title, "E1 - Initial Condition"); E1_view.set_title(title); E1_view.show(E_time_prev, H2D_FN_VAL_0); sprintf(title, "E2 - Initial Condition"); E2_view.set_title(title); E2_view.show(E_time_prev, H2D_FN_VAL_1); sprintf(title, "H - Initial Condition"); H_view.set_title(title); H_view.show(H_time_prev); sprintf(title, "P1 - Initial Condition"); P1_view.set_title(title); P1_view.show(P_time_prev, H2D_FN_VAL_0); sprintf(title, "P2 - Initial Condition"); P2_view.set_title(title); P2_view.show(P_time_prev, H2D_FN_VAL_1); // Initialize Runge-Kutta time stepping. RungeKutta<double> runge_kutta(wf, spaces, &bt); runge_kutta.set_newton_max_allowed_iterations(NEWTON_MAX_ITER); runge_kutta.set_newton_tolerance(NEWTON_TOL); runge_kutta.set_verbose_output(true); // Initialize refinement selector. H1ProjBasedSelector<double> H1selector(CAND_LIST); HcurlProjBasedSelector<double> HcurlSelector(CAND_LIST); // Time stepping loop. int ts = 1; do { // Perform one Runge-Kutta time step according to the selected Butcher's table. Hermes::Mixins::Loggable::Static::info("\nRunge-Kutta time step (t = %g s, time_step = %g s, stages: %d).", current_time, time_step, bt.get_size()); // Periodic global derefinements. if (ts > 1 && ts % UNREF_FREQ == 0 && REFINEMENT_COUNT > 0) { Hermes::Mixins::Loggable::Static::info("Global mesh derefinement."); REFINEMENT_COUNT = 0; E_space->unrefine_all_mesh_elements(true); H_space->unrefine_all_mesh_elements(true); P_space->unrefine_all_mesh_elements(true); E_space->adjust_element_order(-1, P_INIT); H_space->adjust_element_order(-1, P_INIT); P_space->adjust_element_order(-1, P_INIT); E_space->assign_dofs(); H_space->assign_dofs(); P_space->assign_dofs(); } // Adaptivity loop: int as = 1; bool done = false; do { Hermes::Mixins::Loggable::Static::info("Adaptivity step %d:", as); // Construct globally refined reference mesh and setup reference space. int order_increase = 1; Mesh::ReferenceMeshCreator refMeshCreatorE(E_mesh); Mesh::ReferenceMeshCreator refMeshCreatorH(H_mesh); Mesh::ReferenceMeshCreator refMeshCreatorP(P_mesh); MeshSharedPtr ref_mesh_E = refMeshCreatorE.create_ref_mesh(); MeshSharedPtr ref_mesh_H = refMeshCreatorH.create_ref_mesh(); MeshSharedPtr ref_mesh_P = refMeshCreatorP.create_ref_mesh(); Space<double>::ReferenceSpaceCreator refSpaceCreatorE(E_space, ref_mesh_E, order_increase); SpaceSharedPtr<double> ref_space_E = refSpaceCreatorE.create_ref_space(); Space<double>::ReferenceSpaceCreator refSpaceCreatorH(H_space, ref_mesh_H, order_increase); SpaceSharedPtr<double> ref_space_H = refSpaceCreatorH.create_ref_space(); Space<double>::ReferenceSpaceCreator refSpaceCreatorP(P_space, ref_mesh_P, order_increase); SpaceSharedPtr<double> ref_space_P = refSpaceCreatorP.create_ref_space(); std::vector<SpaceSharedPtr<double> > ref_spaces({ ref_space_E, ref_space_H, ref_space_P }); int ndof = Space<double>::get_num_dofs(ref_spaces); Hermes::Mixins::Loggable::Static::info("ndof = %d.", ndof); try { runge_kutta.set_spaces(ref_spaces); runge_kutta.set_time(current_time); runge_kutta.set_time_step(time_step); runge_kutta.rk_time_step_newton(slns_time_prev, slns_time_new); } catch (Exceptions::Exception& e) { e.print_msg(); throw Hermes::Exceptions::Exception("Runge-Kutta time step failed"); } // Visualize the solutions. char title[100]; sprintf(title, "E1, t = %g", current_time + time_step); E1_view.set_title(title); E1_view.show(E_time_new, H2D_FN_VAL_0); sprintf(title, "E2, t = %g", current_time + time_step); E2_view.set_title(title); E2_view.show(E_time_new, H2D_FN_VAL_1); sprintf(title, "H, t = %g", current_time + time_step); H_view.set_title(title); H_view.show(H_time_new); sprintf(title, "P1, t = %g", current_time + time_step); P1_view.set_title(title); P1_view.show(P_time_new, H2D_FN_VAL_0); sprintf(title, "P2, t = %g", current_time + time_step); P2_view.set_title(title); P2_view.show(P_time_new, H2D_FN_VAL_1); // Project the fine mesh solution onto the coarse mesh. Hermes::Mixins::Loggable::Static::info("Projecting reference solution on coarse mesh."); OGProjection<double>::project_global({ E_space, H_space, P_space }, { E_time_new, H_time_new, P_time_new }, { E_time_new_coarse, H_time_new_coarse, P_time_new_coarse }); // Calculate element errors and total error estimate. Hermes::Mixins::Loggable::Static::info("Calculating error estimate."); adaptivity.set_spaces({ E_space, H_space, P_space }); errorCalculator.calculate_errors({ E_time_new_coarse, H_time_new_coarse, P_time_new_coarse }, { E_time_new, H_time_new, P_time_new }); double err_est_rel_total = errorCalculator.get_total_error_squared() * 100.; // Report results. Hermes::Mixins::Loggable::Static::info("Error estimate: %g%%", err_est_rel_total); // If err_est too large, adapt the mesh. if (err_est_rel_total < ERR_STOP) { Hermes::Mixins::Loggable::Static::info("Error estimate under the specified threshold -> moving to next time step."); done = true; } else { Hermes::Mixins::Loggable::Static::info("Adapting coarse mesh."); REFINEMENT_COUNT++; done = adaptivity.adapt({ &HcurlSelector, &H1selector, &HcurlSelector }); if (!done) as++; } } while (!done); //View::wait(); E_time_prev->copy(E_time_new); H_time_prev->copy(H_time_new); P_time_prev->copy(P_time_new); // Update time. current_time += time_step; ts++; } while (current_time < T_FINAL); // Wait for the view to be closed. View::wait(); } catch (std::exception& e) { std::cout << e.what(); } return 0; }
int main(int argc, char* argv[]) { // Choose a Butcher's table or define your own. ButcherTable bt(butcher_table_type); if (bt.is_explicit()) info("Using a %d-stage explicit R-K method.", bt.get_size()); if (bt.is_diagonally_implicit()) info("Using a %d-stage diagonally implicit R-K method.", bt.get_size()); if (bt.is_fully_implicit()) info("Using a %d-stage fully implicit R-K method.", bt.get_size()); // Load the mesh. Mesh mesh; MeshReaderH2D mloader; mloader.load("domain.mesh", &mesh); // Perform initial mesh refinemets. for (int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(); // Initialize solutions. CustomInitialConditionWave E_sln(&mesh); ZeroSolution B_sln(&mesh); Hermes::vector<Solution<double>*> slns(&E_sln, &B_sln); // Initialize the weak formulation. CustomWeakFormWave wf(C_SQUARED); // Initialize boundary conditions DefaultEssentialBCConst<double> bc_essential("Perfect conductor", 0.0); EssentialBCs<double> bcs_E(&bc_essential); EssentialBCs<double> bcs_B; // Create x- and y- displacement space using the default H1 shapeset. HcurlSpace<double> E_space(&mesh, &bcs_E, P_INIT); H1Space<double> B_space(&mesh, &bcs_B, P_INIT); //L2Space<double> B_space(&mesh, P_INIT); Hermes::vector<Space<double> *> spaces = Hermes::vector<Space<double> *>(&E_space, &B_space); info("ndof = %d.", Space<double>::get_num_dofs(spaces)); // Initialize the FE problem. DiscreteProblem<double> dp(&wf, spaces); // Initialize views. ScalarView E1_view("Solution E1", new WinGeom(0, 0, 400, 350)); E1_view.fix_scale_width(50); ScalarView E2_view("Solution E2", new WinGeom(410, 0, 400, 350)); E2_view.fix_scale_width(50); ScalarView B_view("Solution B", new WinGeom(0, 405, 400, 350)); B_view.fix_scale_width(50); // Initialize Runge-Kutta time stepping. RungeKutta<double> runge_kutta(&dp, &bt, matrix_solver_type); // Time stepping loop. double current_time = time_step; int ts = 1; do { // Perform one Runge-Kutta time step according to the selected Butcher's table. info("Runge-Kutta time step (t = %g s, time_step = %g s, stages: %d).", current_time, time_step, bt.get_size()); bool jacobian_changed = false; bool verbose = true; try { runge_kutta.rk_time_step_newton(current_time, time_step, slns, slns, jacobian_changed, verbose); } catch(Exceptions::Exception& e) { e.printMsg(); error("Runge-Kutta time step failed"); } // Visualize the solutions. char title[100]; sprintf(title, "E1, t = %g", current_time); E1_view.set_title(title); E1_view.show(&E_sln, HERMES_EPS_NORMAL, H2D_FN_VAL_0); sprintf(title, "E2, t = %g", current_time); E2_view.set_title(title); E2_view.show(&E_sln, HERMES_EPS_NORMAL, H2D_FN_VAL_1); sprintf(title, "B, t = %g", current_time); B_view.set_title(title); B_view.show(&B_sln, HERMES_EPS_NORMAL, H2D_FN_VAL_0); // Update time. current_time += time_step; } while (current_time < T_FINAL); // Wait for the view to be closed. View::wait(); return 0; }
void d() { bt(); assert(!profile::IsBelowStackFrame((void*)&main, (void*)&test1)); }
int main(int argc, char* argv[]) { // Choose a Butcher's table or define your own. ButcherTable bt(butcher_table_type); if (bt.is_explicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage explicit R-K method.", bt.get_size()); if (bt.is_diagonally_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage diagonally implicit R-K method.", bt.get_size()); if (bt.is_fully_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage fully implicit R-K method.", bt.get_size()); // Turn off adaptive time stepping if R-K method is not embedded. if (bt.is_embedded() == false && ADAPTIVE_TIME_STEP_ON == true) { Hermes::Mixins::Loggable::Static::warn("R-K method not embedded, turning off adaptive time stepping."); ADAPTIVE_TIME_STEP_ON = false; } // Load the mesh. MeshSharedPtr mesh(new Mesh), basemesh(new Mesh); MeshReaderH2D mloader; mloader.load("wall.mesh", basemesh); mesh->copy(basemesh); // Perform initial mesh refinements. for(int i = 0; i < INIT_REF_NUM; i++) mesh->refine_all_elements(); mesh->refine_towards_boundary(BDY_RIGHT, 2); mesh->refine_towards_boundary(BDY_FIRE, INIT_REF_NUM_BDY); // Initialize essential boundary conditions (none). EssentialBCs<double> bcs; // Initialize an H1 space with default shapeset. SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT)); int ndof = Space<double>::get_num_dofs(space); Hermes::Mixins::Loggable::Static::info("ndof = %d.", ndof); // Convert initial condition into a Solution. MeshFunctionSharedPtr<double> sln_prev_time(new ConstantSolution<double> (mesh, TEMP_INIT)); // Initialize the weak formulation. double current_time = 0; CustomWeakFormHeatRK wf(BDY_FIRE, BDY_AIR, ALPHA_FIRE, ALPHA_AIR, RHO, HEATCAP, TEMP_EXT_AIR, TEMP_INIT, ¤t_time); // Initialize the FE problem. DiscreteProblem<double> dp(&wf, space); // Create a refinement selector. H1ProjBasedSelector<double> selector(CAND_LIST); // Visualize initial condition. char title[100]; ScalarView sln_view("Initial condition", new WinGeom(0, 0, 1500, 360)); OrderView ordview("Initial mesh", new WinGeom(0, 410, 1500, 360)); ScalarView time_error_view("Temporal error", new WinGeom(0, 800, 1500, 360)); time_error_view.fix_scale_width(40); ScalarView space_error_view("Spatial error", new WinGeom(0, 1220, 1500, 360)); space_error_view.fix_scale_width(40); sln_view.show(sln_prev_time); ordview.show(space); // Graph for time step history. SimpleGraph time_step_graph; if (ADAPTIVE_TIME_STEP_ON) Hermes::Mixins::Loggable::Static::info("Time step history will be saved to file time_step_history.dat."); // Class for projections. OGProjection<double> ogProjection; // Time stepping loop: int ts = 1; do { Hermes::Mixins::Loggable::Static::info("Begin time step %d.", ts); // Periodic global derefinement. if (ts > 1 && ts % UNREF_FREQ == 0) { Hermes::Mixins::Loggable::Static::info("Global mesh derefinement."); switch (UNREF_METHOD) { case 1: mesh->copy(basemesh); space->set_uniform_order(P_INIT); break; case 2: space->unrefine_all_mesh_elements(); space->set_uniform_order(P_INIT); break; case 3: space->unrefine_all_mesh_elements(); //space->adjust_element_order(-1, P_INIT); space->adjust_element_order(-1, -1, P_INIT, P_INIT); break; default: throw Hermes::Exceptions::Exception("Wrong global derefinement method."); } space->assign_dofs(); ndof = Space<double>::get_num_dofs(space); } // Spatial adaptivity loop. Note: sln_prev_time must not be // changed during spatial adaptivity. MeshFunctionSharedPtr<double> ref_sln(new Solution<double>()); MeshFunctionSharedPtr<double> time_error_fn(new Solution<double>(mesh)); bool done = false; int as = 1; double err_est; do { // Construct globally refined reference mesh and setup reference space. Mesh::ReferenceMeshCreator refMeshCreator(mesh); MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh(); Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh); SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space(); // Initialize Runge-Kutta time stepping on the reference mesh. RungeKutta<double> runge_kutta(&wf, ref_space, &bt); try { ogProjection.project_global(ref_space, sln_prev_time, sln_prev_time); } catch(Exceptions::Exception& e) { std::cout << e.what() << std::endl; Hermes::Mixins::Loggable::Static::error("Projection failed."); return -1; } // Runge-Kutta step on the fine mesh-> Hermes::Mixins::Loggable::Static::info("Runge-Kutta time step on fine mesh (t = %g s, tau = %g s, stages: %d).", current_time, time_step, bt.get_size()); bool verbose = true; bool jacobian_changed = false; try { runge_kutta.set_time(current_time); runge_kutta.set_time_step(time_step); runge_kutta.set_max_allowed_iterations(NEWTON_MAX_ITER); runge_kutta.set_tolerance(NEWTON_TOL_FINE); runge_kutta.rk_time_step_newton(sln_prev_time, ref_sln, bt.is_embedded() ? time_error_fn : NULL); } catch(Exceptions::Exception& e) { std::cout << e.what() << std::endl; Hermes::Mixins::Loggable::Static::error("Runge-Kutta time step failed"); return -1; } /* If ADAPTIVE_TIME_STEP_ON == true, estimate temporal error. If too large or too small, then adjust it and restart the time step. */ double rel_err_time = 0; if (bt.is_embedded() == true) { Hermes::Mixins::Loggable::Static::info("Calculating temporal error estimate."); // Show temporal error. char title[100]; sprintf(title, "Temporal error est, spatial adaptivity step %d", as); time_error_view.set_title(title); //time_error_view.show_mesh(false); time_error_view.show(time_error_fn); rel_err_time = Global<double>::calc_norm(time_error_fn.get(), HERMES_H1_NORM) / Global<double>::calc_norm(ref_sln.get(), HERMES_H1_NORM) * 100; if (ADAPTIVE_TIME_STEP_ON == false) Hermes::Mixins::Loggable::Static::info("rel_err_time: %g%%", rel_err_time); } if (ADAPTIVE_TIME_STEP_ON) { if (rel_err_time > TIME_ERR_TOL_UPPER) { Hermes::Mixins::Loggable::Static::info("rel_err_time %g%% is above upper limit %g%%", rel_err_time, TIME_ERR_TOL_UPPER); Hermes::Mixins::Loggable::Static::info("Decreasing tau from %g to %g s and restarting time step.", time_step, time_step * TIME_STEP_DEC_RATIO); time_step *= TIME_STEP_DEC_RATIO; continue; } else if (rel_err_time < TIME_ERR_TOL_LOWER) { Hermes::Mixins::Loggable::Static::info("rel_err_time = %g%% is below lower limit %g%%", rel_err_time, TIME_ERR_TOL_LOWER); Hermes::Mixins::Loggable::Static::info("Increasing tau from %g to %g s.", time_step, time_step * TIME_STEP_INC_RATIO); time_step *= TIME_STEP_INC_RATIO; } else { Hermes::Mixins::Loggable::Static::info("rel_err_time = %g%% is in acceptable interval (%g%%, %g%%)", rel_err_time, TIME_ERR_TOL_LOWER, TIME_ERR_TOL_UPPER); } // Add entry to time step history graph. time_step_graph.add_values(current_time, time_step); time_step_graph.save("time_step_history.dat"); } /* Estimate spatial errors and perform mesh refinement */ Hermes::Mixins::Loggable::Static::info("Spatial adaptivity step %d.", as); // Project the fine mesh solution onto the coarse mesh. MeshFunctionSharedPtr<double> sln(new Solution<double>()); Hermes::Mixins::Loggable::Static::info("Projecting fine mesh solution on coarse mesh for error estimation."); ogProjection.project_global(space, ref_sln, sln); // Show spatial error. sprintf(title, "Spatial error est, spatial adaptivity step %d", as); MeshFunctionSharedPtr<double> space_error_fn(new DiffFilter<double>(Hermes::vector<MeshFunctionSharedPtr<double> >(ref_sln, sln))); space_error_view.set_title(title); //space_error_view.show_mesh(false); MeshFunctionSharedPtr<double> abs_sef(new AbsFilter(space_error_fn)); space_error_view.show(abs_sef); // Calculate element errors and spatial error estimate. Hermes::Mixins::Loggable::Static::info("Calculating spatial error estimate."); adaptivity.set_space(space); double err_rel_space = errorCalculator.get_total_error_squared() * 100; // Report results. Hermes::Mixins::Loggable::Static::info("ndof: %d, ref_ndof: %d, err_rel_space: %g%%", Space<double>::get_num_dofs(space), Space<double>::get_num_dofs(ref_space), err_rel_space); // If err_est too large, adapt the mesh. if (err_rel_space < SPACE_ERR_TOL) done = true; else { Hermes::Mixins::Loggable::Static::info("Adapting the coarse mesh."); done = adaptivity.adapt(&selector); if (Space<double>::get_num_dofs(space) >= NDOF_STOP) done = true; else // Increase the counter of performed adaptivity steps. as++; } // Clean up. if(!done) } while (done == false); // Visualize the solution and mesh-> char title[100]; sprintf(title, "Solution, time %g s", current_time); sln_view.set_title(title); //sln_view.show_mesh(false); sln_view.show(ref_sln); sprintf(title, "Mesh, time %g s", current_time); ordview.set_title(title); ordview.show(space); // Copy last reference solution into sln_prev_time sln_prev_time->copy(ref_sln); // Increase current time and counter of time steps. current_time += time_step; ts++; } while (current_time < T_FINAL); // Wait for all views to be closed. View::wait(); return 0; }
int main(int argc, char* argv[]) { // Instantiate a class with global functions. // Choose a Butcher's table or define your own. ButcherTable bt(butcher_table_type); if (bt.is_explicit()) info("Using a %d-stage explicit R-K method.", bt.get_size()); if (bt.is_diagonally_implicit()) info("Using a %d-stage diagonally implicit R-K method.", bt.get_size()); if (bt.is_fully_implicit()) info("Using a %d-stage fully implicit R-K method.", bt.get_size()); // Turn off adaptive time stepping if R-K method is not embedded. if (bt.is_embedded() == false && ADAPTIVE_TIME_STEP_ON == true) { warn("R-K method not embedded, turning off adaptive time stepping."); ADAPTIVE_TIME_STEP_ON = false; } // Load the mesh. Mesh mesh, basemesh; MeshReaderH2D mloader; mloader.load("square.mesh", &basemesh); mesh.copy(&basemesh); // Initial mesh refinements. for(int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(); // Convert initial condition into a Solution<std::complex<double> >. CustomInitialCondition psi_time_prev(&mesh); // Initialize the weak formulation. double current_time = 0; CustomWeakFormGPRK wf(h, m, g, omega); // Initialize boundary conditions. DefaultEssentialBCConst<std::complex<double> > bc_essential("Bdy", 0.0); EssentialBCs<std::complex<double> > bcs(&bc_essential); // Create an H1 space with default shapeset. H1Space<std::complex<double> > space(&mesh, &bcs, P_INIT); int ndof = space.get_num_dofs(); info("ndof = %d", ndof); // Initialize the FE problem. DiscreteProblem<std::complex<double> > dp(&wf, &space); // Create a refinement selector. H1ProjBasedSelector<std::complex<double> > selector(CAND_LIST, CONV_EXP, H2DRS_DEFAULT_ORDER); // Visualize initial condition. char title[100]; ScalarView sview_real("Initial condition - real part", new WinGeom(0, 0, 600, 500)); ScalarView sview_imag("Initial condition - imaginary part", new WinGeom(610, 0, 600, 500)); sview_real.show_mesh(false); sview_imag.show_mesh(false); sview_real.fix_scale_width(50); sview_imag.fix_scale_width(50); OrderView ord_view("Initial mesh", new WinGeom(445, 0, 440, 350)); ord_view.fix_scale_width(50); ScalarView time_error_view("Temporal error", new WinGeom(0, 400, 440, 350)); time_error_view.fix_scale_width(50); time_error_view.fix_scale_width(60); ScalarView space_error_view("Spatial error", new WinGeom(445, 400, 440, 350)); space_error_view.fix_scale_width(50); RealFilter real(&psi_time_prev); ImagFilter imag(&psi_time_prev); sview_real.show(&real); sview_imag.show(&imag); ord_view.show(&space); // Graph for time step history. SimpleGraph time_step_graph; if (ADAPTIVE_TIME_STEP_ON) info("Time step history will be saved to file time_step_history.dat."); // Time stepping: int num_time_steps = (int)(T_FINAL/time_step + 0.5); for(int ts = 1; ts <= num_time_steps; ts++) // Time stepping loop. double current_time = 0.0; int ts = 1; do { info("Begin time step %d.", ts); // Periodic global derefinement. if (ts > 1 && ts % UNREF_FREQ == 0) { info("Global mesh derefinement."); switch (UNREF_METHOD) { case 1: mesh.copy(&basemesh); space.set_uniform_order(P_INIT); break; case 2: mesh.unrefine_all_elements(); space.set_uniform_order(P_INIT); break; case 3: mesh.unrefine_all_elements(); //space.adjust_element_order(-1, P_INIT); space.adjust_element_order(-1, -1, P_INIT, P_INIT); break; default: error("Wrong global derefinement method."); } ndof = Space<std::complex<double> >::get_num_dofs(&space); } info("ndof: %d", ndof); // Spatial adaptivity loop. Note: psi_time_prev must not be // changed during spatial adaptivity. Solution<std::complex<double> > ref_sln; Solution<std::complex<double> >* time_error_fn; if (bt.is_embedded() == true) time_error_fn = new Solution<std::complex<double> >(&mesh); else time_error_fn = NULL; bool done = false; int as = 1; double err_est; do { // Construct globally refined reference mesh and setup reference space. Space<std::complex<double> >* ref_space = Space<std::complex<double> >::construct_refined_space(&space); // Initialize discrete problem on reference mesh. DiscreteProblem<std::complex<double> >* ref_dp = new DiscreteProblem<std::complex<double> >(&wf, ref_space); RungeKutta<std::complex<double> > runge_kutta(ref_dp, &bt, matrix_solver_type); // Runge-Kutta step on the fine mesh. info("Runge-Kutta time step on fine mesh (t = %g s, time step = %g s, stages: %d).", current_time, time_step, bt.get_size()); bool verbose = true; try { runge_kutta.rk_time_step_newton(current_time, time_step, &psi_time_prev, &ref_sln, time_error_fn, false, false, verbose, NEWTON_TOL_FINE, NEWTON_MAX_ITER); } catch(Exceptions::Exception& e) { e.printMsg(); error("Runge-Kutta time step failed"); } /* If ADAPTIVE_TIME_STEP_ON == true, estimate temporal error. If too large or too small, then adjust it and restart the time step. */ double rel_err_time = 0; if (bt.is_embedded() == true) { info("Calculating temporal error estimate."); // Show temporal error. char title[100]; sprintf(title, "Temporal error est, spatial adaptivity step %d", as); time_error_view.set_title(title); time_error_view.show_mesh(false); RealFilter abs_time(time_error_fn); AbsFilter abs_tef(&abs_time); time_error_view.show(&abs_tef, HERMES_EPS_HIGH); rel_err_time = Global<std::complex<double> >::calc_norm(time_error_fn, HERMES_H1_NORM) / Global<std::complex<double> >::calc_norm(&ref_sln, HERMES_H1_NORM) * 100; if (ADAPTIVE_TIME_STEP_ON == false) info("rel_err_time: %g%%", rel_err_time); } if (ADAPTIVE_TIME_STEP_ON) { if (rel_err_time > TIME_ERR_TOL_UPPER) { info("rel_err_time %g%% is above upper limit %g%%", rel_err_time, TIME_ERR_TOL_UPPER); info("Decreasing time step from %g to %g s and restarting time step.", time_step, time_step * TIME_STEP_DEC_RATIO); time_step *= TIME_STEP_DEC_RATIO; delete ref_space; delete ref_dp; continue; } else if (rel_err_time < TIME_ERR_TOL_LOWER) { info("rel_err_time = %g%% is below lower limit %g%%", rel_err_time, TIME_ERR_TOL_LOWER); info("Increasing time step from %g to %g s.", time_step, time_step * TIME_STEP_INC_RATIO); time_step *= TIME_STEP_INC_RATIO; delete ref_space; delete ref_dp; continue; } else { info("rel_err_time = %g%% is in acceptable interval (%g%%, %g%%)", rel_err_time, TIME_ERR_TOL_LOWER, TIME_ERR_TOL_UPPER); } // Add entry to time step history graph. time_step_graph.add_values(current_time, time_step); time_step_graph.save("time_step_history.dat"); } /* Estimate spatial errors and perform mesh refinement */ info("Spatial adaptivity step %d.", as); // Project the fine mesh solution onto the coarse mesh. Solution<std::complex<double> > sln; info("Projecting fine mesh solution on coarse mesh for error estimation."); OGProjection<std::complex<double> >::project_global(&space, &ref_sln, &sln, matrix_solver_type); // Show spatial error. sprintf(title, "Spatial error est, spatial adaptivity step %d", as); DiffFilter<std::complex<double> >* space_error_fn = new DiffFilter<std::complex<double> >(Hermes::vector<MeshFunction<std::complex<double> >*>(&ref_sln, &sln)); space_error_view.set_title(title); space_error_view.show_mesh(false); RealFilter abs_space(space_error_fn); AbsFilter abs_sef(&abs_space); space_error_view.show(&abs_sef); // Calculate element errors and spatial error estimate. info("Calculating spatial error estimate."); Adapt<std::complex<double> >* adaptivity = new Adapt<std::complex<double> >(&space); double err_rel_space = adaptivity->calc_err_est(&sln, &ref_sln) * 100; // Report results. info("ndof: %d, ref_ndof: %d, err_rel_space: %g%%", Space<std::complex<double> >::get_num_dofs(&space), Space<std::complex<double> >::get_num_dofs(ref_space), err_rel_space); // If err_est too large, adapt the mesh. if (err_rel_space < SPACE_ERR_TOL) done = true; else { info("Adapting the coarse mesh."); done = adaptivity->adapt(&selector, THRESHOLD, STRATEGY, MESH_REGULARITY); if (Space<std::complex<double> >::get_num_dofs(&space) >= NDOF_STOP) done = true; else // Increase the counter of performed adaptivity steps. as++; } // Clean up. delete adaptivity; delete ref_space; delete ref_dp; delete space_error_fn; } while (done == false); // Clean up. if (time_error_fn != NULL) delete time_error_fn; // Visualize the solution and mesh. char title[100]; sprintf(title, "Solution - real part, Time %3.2f s", current_time); sview_real.set_title(title); sprintf(title, "Solution - imaginary part, Time %3.2f s", current_time); sview_imag.set_title(title); RealFilter real(&ref_sln); ImagFilter imag(&ref_sln); sview_real.show(&real); sview_imag.show(&imag); sprintf(title, "Mesh, time %g s", current_time); ord_view.set_title(title); ord_view.show(&space); // Copy last reference solution into psi_time_prev. psi_time_prev.copy(&ref_sln); // Increase current time and counter of time steps. current_time += time_step; ts++; } while (current_time < T_FINAL); // Wait for all views to be closed. View::wait(); return 0; }
int comms_send(cpu_state* state) { unsigned int port = state->ebx; void *req_buf = (void*)state->ecx; unsigned int req_size = state->edx; void *rep_buf = (void*)state->esi; unsigned int rep_size = state->edi; //return no such port when if the port doesn't exist if (bt(comms_bitmap,port)) { state->eax = -ERR_IPC_NO_SUCH_PORT; return 0; } //return invalid port if port exceeds max ports if (port >= COMMS_MAX_PORTS) { state->eax = -ERR_IPC_INVALID_PORT; return 0; } //return invalid msg size if req_size or rep_size is less than 1 or exceeds max msg size if ((req_size < 1) | (req_size > COMMS_MAX_MSG) | (rep_size < 1) | (rep_size >= COMMS_MAX_MSG)) { state->eax = -ERR_IPC_INVALID_MSG_SIZE; return 0; } //return invalid buffer when a buffer equals NULL if ((req_buf == NULL) | (rep_buf == NULL)) { state->eax = -ERR_IPC_INVALID_BUFFER; return 0; } //allocate memory for the message msg *temp = (struct msg*)mem_alloc(sizeof(struct msg)); //is this the first message? if (msg_port[port]->queue == NULL) { //set as first node msg_port[port]->queue = temp; }else { //let the last message point to it msg_port[port]->last->next = temp; } //the msg is also the last msg msg_port[port]->last = temp; //save it's page directory temp->pd = (void*)cr3(); //save the adress of the request and it's size temp->req_buf = req_buf; temp->req_size = req_size; //save the adress we need to reply to and it's size temp->rep_buf = rep_buf; temp->rep_size = rep_size; //there isn't a next temp->next = NULL; //get the server page directory page_directory* pd = (page_directory*)(msg_port[port]->pcb->pd); //get the page table entry where the server is located unsigned int pt_entry = pd->table[msg_port[port]->index]; //get the client page directory pd = (page_directory*)(temp->pd); //get a open slot in the page directory temp->offset = 0; while ((temp->offset < PTES) && (pd->table[temp->offset] != 0)) { temp->offset++; } //add the server page table into the client's page directory pd->table[temp->offset] = pt_entry; //save the multiplier to work with the server adresses in the client pd temp->mult = (temp->offset - msg_port[port]->index) * 0x400000; //unblock the server if it's blocked and send the message dadelik if (unblock_server(port)) { //flush tlb mem_switch_to_kernel_directory(); i386_set_page_directory(temp->pd); void *buf = (void*)msg_port[port]->pcb->state->ecx; //copy the message request into buf copy_4(temp->req_buf,(unsigned int)buf+temp->mult,req_size/4); } //block the client state->eax = OK; block_process(port,state); //return reschedule return 1; }
static void asic3_compute_hold(void) { // The mode is dependant on the region static int modes[4] = { 1, 1, 3, 2 }; int mode = modes[PgmInput[7] & 3]; switch(mode) { case 1: asic3_hold = (asic3_hold << 1) ^0x2bad ^bt(asic3_hold, 15)^bt(asic3_hold, 10)^bt(asic3_hold, 8)^bt(asic3_hold, 5) ^bt(asic3_z, asic3_y) ^(bt(asic3_x, 0) << 1)^(bt(asic3_x, 1) << 6)^(bt(asic3_x, 2) << 10)^(bt(asic3_x, 3) << 14); break; case 2: asic3_hold = (asic3_hold << 1) ^0x2bad ^bt(asic3_hold, 15)^bt(asic3_hold, 7)^bt(asic3_hold, 6)^bt(asic3_hold, 5) ^bt(asic3_z, asic3_y) ^(bt(asic3_x, 0) << 4)^(bt(asic3_x, 1) << 6)^(bt(asic3_x, 2) << 10)^(bt(asic3_x, 3) << 12); break; case 3: asic3_hold = (asic3_hold << 1) ^0x2bad ^bt(asic3_hold, 15)^bt(asic3_hold, 10)^bt(asic3_hold, 8)^bt(asic3_hold, 5) ^bt(asic3_z, asic3_y) ^(bt(asic3_x, 0) << 4)^(bt(asic3_x, 1) << 6)^(bt(asic3_x, 2) << 10)^(bt(asic3_x, 3) << 12); break; } }
int comms_reply(unsigned int port, void *buf, unsigned int size) { //return no such port when port doesn't exist if (bt(comms_bitmap,port)) { update_port_error(cr3(),-ERR_IPC_NO_SUCH_PORT); return -ERR_IPC_NO_SUCH_PORT; } //return invalid port when port exceeds max ports if (port >= COMMS_MAX_PORTS) { update_error(port,-ERR_IPC_INVALID_PORT); return -ERR_IPC_INVALID_PORT; } //return invalid msg size if buf is less than 1 or exceeds max msg size if ((size < 1) | (size > COMMS_MAX_MSG)) { update_error(port,-ERR_IPC_INVALID_MSG_SIZE); return -ERR_IPC_INVALID_MSG_SIZE; } //return invalid buffer when a buffer equals NULL if (buf == NULL) { update_error(port,-ERR_IPC_INVALID_BUFFER); return -ERR_IPC_INVALID_BUFFER; } //double check if the message is still there if (msg_port[port]->queue != NULL) { //save message into temp msg* temp = msg_port[port]->queue; //check if the sizes are correct if (temp->rep_size != size) { return -ERR_IPC_REPLY_MISMATCH; } //move to next message msg_port[port]->queue = msg_port[port]->queue->next; //if there is no messages make sure last knows this if (msg_port[port] == NULL) { msg_port[port]->last = NULL; } //switch to client pd i386_set_page_directory(temp->pd); //copy buf into reply address copy_4((unsigned int)buf+temp->mult,temp->rep_buf,size/4); //switch back to server pd i386_set_page_directory(msg_port[port]->pcb->pd); //remove the server page table from the message ((page_directory*)(temp->pd))->table[temp->offset] = 0; //free the memory the message used mem_free(temp); //unblock the client unblock_process(port); }else { //will this happen? } //return OK return OK; }
int main(int argc, char ** argv) { window = new Fl_Single_Window(COLS*W,ROWS*H+90); bt("@->"); bt("@>"); bt("@>>"); bt("@>|"); bt("@>[]"); bt("@|>"); bt("@<-"); bt("@<"); bt("@<<"); bt("@|<"); bt("@[]<"); bt("@<|"); bt("@<->"); bt("@-->"); bt("@+"); bt("@->|"); bt("@||"); bt("@arrow"); bt("@returnarrow"); bt("@square"); bt("@circle"); bt("@line"); bt("@menu"); bt("@UpArrow"); bt("@DnArrow"); Fl_Value_Slider slider(80, window->h()-60, window->w()-90, 16, "Orientation"); slider.align(FL_ALIGN_LEFT); slider.type(Fl_Slider::HORIZONTAL); slider.range(0.0, 9.0); slider.value(0.0); slider.step(1); slider.callback(slider_cb, &slider); Fl_Value_Slider slider2(80, window->h()-30, window->w()-90, 16, "Scale"); slider2.align(FL_ALIGN_LEFT); slider2.type(Fl_Slider::HORIZONTAL); slider2.range(-9.0, 9.0); slider2.value(0.0); slider2.step(1); slider2.callback(slider_cb, &slider); rot = &slider; scale = &slider2; window->resizable(window); window->show(argc,argv); return Fl::run(); }
bool SceneObject_Prop_Physics_Static::Create(const std::string &modelName, const Vec3f &position, const Quaternion &rotation, float restitution, float friction) { assert(!m_created); assert(GetScene() != NULL); Asset* pModelAsset; if(!GetScene()->GetAssetManager_AutoCreate("modelOBJPhy", Model_OBJ_Physics_Static::Asset_Factory)->GetAsset(modelName, pModelAsset)) return false; m_pModel = static_cast<Model_OBJ_Physics_Static*>(pModelAsset); m_pModel->SetRenderer(GetScene()); // Get reference to physics world m_pPhysicsWorld = static_cast<SceneObject_PhysicsWorld*>(GetScene()->GetNamed_SceneObject("physWrld")); assert(m_pPhysicsWorld != NULL); m_physicsWorldTracker.Set(m_pPhysicsWorld); m_pMotionState = new btDefaultMotionState(btTransform(bt(rotation).normalized(), bt(position))); const float mass = 0.0f; btVector3 intertia; m_pModel->GetShape()->calculateLocalInertia(mass, intertia); btRigidBody::btRigidBodyConstructionInfo rigidBodyCI(mass, m_pMotionState, m_pModel->GetShape(), intertia); rigidBodyCI.m_restitution = restitution; rigidBodyCI.m_friction = friction; m_pRigidBody = new btRigidBody(rigidBodyCI); m_pPhysicsWorld->m_pDynamicsWorld->addRigidBody(m_pRigidBody); m_pRigidBody->setUserPointer(this); // Default texture setting: nearest filtering /*for(unsigned int i = 0, size = m_pModel->GetNumMaterials(); i < size; i++) { Model_OBJ::Material* pMat = m_pModel->GetMaterial(i); pMat->m_pDiffuseMap->Bind(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); if(pMat->m_pSpecularMap != NULL) { pMat->m_pSpecularMap->Bind(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); } if(pMat->m_pNormalMap != NULL) { pMat->m_pNormalMap->Bind(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); } }*/ RegenAABB(); m_created = true; return true; }
void MeshExtractor( const MeshData& mesh_data, const Ogre::String& material_name, File* file, int offset_to_data, VectorTexForGen& textures, const Ogre::MeshPtr& mesh ) { File* file12 = new File( "./data/field/5/1b/1/12/1" ); u32 offset_to_clut_tex = 4 + file12->GetU32LE( 4 + 4 ) & 0x00ffffff; LOGGER->Log( "offset_to_clut_tex = \"" + HexToString( offset_to_clut_tex, 8, '0' ) + "\".\n" ); u32 offset_to_tx_ty = offset_to_clut_tex + file12->GetU8( 4 + 7 ) * 4; LOGGER->Log( "offset_to_tx_ty = \"" + HexToString( offset_to_tx_ty, 8, '0' ) + "\".\n" ); int number_of_monochrome_textured_quads = file->GetU16LE( offset_to_data + 0x02 ); int number_of_monochrome_textured_triangles = file->GetU16LE( offset_to_data + 0x04 ); int number_of_shaded_textured_quads = file->GetU16LE( offset_to_data + 0x06 ); int number_of_shaded_textured_triangles = file->GetU16LE( offset_to_data + 0x08 ); int number_of_gradated_quads = file->GetU16LE( offset_to_data + 0x0a ); int number_of_gradated_triangles = file->GetU16LE( offset_to_data + 0x0c ); int number_of_monochrome_quads = file->GetU16LE( offset_to_data + 0x0e ); int number_of_monochrome_triangles = file->GetU16LE( offset_to_data + 0x10 ); u32 pointer_to_vertex_groups = file->GetU32LE( offset_to_data + 0x14 ); u32 pointer_to_vertex_data = file->GetU32LE( offset_to_data + 0x18 ); u32 pointer_to_mesh_data = file->GetU32LE( offset_to_data + 0x1c ); u32 pointer_to_texture_data = file->GetU32LE( offset_to_data + 0x20 ); Ogre::SubMesh* sub_mesh = mesh->createSubMesh(/* name */); sub_mesh->setMaterialName( material_name ); sub_mesh->useSharedVertices = false; sub_mesh->operationType = Ogre::RenderOperation::OT_TRIANGLE_LIST; // Allocate and prepare vertex data sub_mesh->vertexData = new Ogre::VertexData(); sub_mesh->vertexData->vertexStart = 0; sub_mesh->vertexData->vertexCount = static_cast< size_t >( number_of_monochrome_textured_quads * 6 + number_of_monochrome_textured_triangles * 3/* + number_of_shaded_textured_quads * 6 + number_of_shaded_textured_triangles * 3 + number_of_gradated_quads * 6 + number_of_gradated_triangles * 3 + number_of_monochrome_quads * 6 + number_of_monochrome_triangles * 3*/ ); sub_mesh->indexData = new Ogre::IndexData(); sub_mesh->indexData->indexStart = 0; sub_mesh->indexData->indexCount = sub_mesh->vertexData->vertexCount; sub_mesh->indexData->indexBuffer = Ogre::HardwareBufferManager::getSingleton().createIndexBuffer( Ogre::HardwareIndexBuffer::IT_16BIT, sub_mesh->indexData->indexCount, Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY ); u16* idata = static_cast< u16* >( sub_mesh->indexData->indexBuffer->lock( Ogre::HardwareBuffer::HBL_DISCARD ) ); u32 cur_index = 0; Ogre::VertexDeclaration* decl = sub_mesh->vertexData->vertexDeclaration; Ogre::VertexBufferBinding* bind = sub_mesh->vertexData->vertexBufferBinding; // 1st buffer decl->addElement( POSITION_BINDING, 0, Ogre::VET_FLOAT3, Ogre::VES_POSITION ); Ogre::HardwareVertexBufferSharedPtr vbuf0 = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer( decl->getVertexSize( POSITION_BINDING ), sub_mesh->vertexData->vertexCount, Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY ); bind->setBinding( POSITION_BINDING, vbuf0 ); // 2nd buffer decl->addElement( COLOUR_BINDING, 0, Ogre::VET_COLOUR, Ogre::VES_DIFFUSE ); Ogre::HardwareVertexBufferSharedPtr vbuf1 = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer( decl->getVertexSize( COLOUR_BINDING ), sub_mesh->vertexData->vertexCount, Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY ); // Set vertex buffer binding so buffer 1 is bound to our colour buffer bind->setBinding( COLOUR_BINDING, vbuf1 ); // 3rd buffer decl->addElement( TEXTURE_BINDING, 0, Ogre::VET_FLOAT2, Ogre::VES_TEXTURE_COORDINATES, 0 ); Ogre::HardwareVertexBufferSharedPtr vbuf2 = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer( decl->getVertexSize( TEXTURE_BINDING ), sub_mesh->vertexData->vertexCount, Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY ); bind->setBinding( TEXTURE_BINDING, vbuf2 ); float* pPos = static_cast< float* >( vbuf0->lock( Ogre::HardwareBuffer::HBL_DISCARD ) ); float* tPos = static_cast< float* >( vbuf2->lock( Ogre::HardwareBuffer::HBL_DISCARD ) ); Ogre::RenderSystem* rs = Ogre::Root::getSingleton().getRenderSystem(); std::vector<Ogre::RGBA> coloursVec(sub_mesh->vertexData->vertexCount); Ogre::RGBA* colours = coloursVec.data(); for( int i = 0; i < number_of_monochrome_textured_quads; ++i ) { int index_a = file->GetU16LE( pointer_to_mesh_data + 0x0 ); int index_b = file->GetU16LE( pointer_to_mesh_data + 0x2 ); int index_c = file->GetU16LE( pointer_to_mesh_data + 0x4 ); int index_d = file->GetU16LE( pointer_to_mesh_data + 0x6 ); Ogre::Vector3 a( ( s16 )file->GetU16LE( pointer_to_vertex_data + index_a * 0x8 + 0x0 ), ( s16 )file->GetU16LE( pointer_to_vertex_data + index_a * 0x8 + 0x2 ), ( s16 )file->GetU16LE( pointer_to_vertex_data + index_a * 0x8 + 0x4 ) ); Ogre::Vector3 b( ( s16 )file->GetU16LE( pointer_to_vertex_data + index_b * 0x8 + 0x0 ), ( s16 )file->GetU16LE( pointer_to_vertex_data + index_b * 0x8 + 0x2 ), ( s16 )file->GetU16LE( pointer_to_vertex_data + index_b * 0x8 + 0x4 ) ); Ogre::Vector3 c( ( s16 )file->GetU16LE( pointer_to_vertex_data + index_c * 0x8 + 0x0 ), ( s16 )file->GetU16LE( pointer_to_vertex_data + index_c * 0x8 + 0x2 ), ( s16 )file->GetU16LE( pointer_to_vertex_data + index_c * 0x8 + 0x4 ) ); Ogre::Vector3 d( ( s16 )file->GetU16LE( pointer_to_vertex_data + index_d * 0x8 + 0x0 ), ( s16 )file->GetU16LE( pointer_to_vertex_data + index_d * 0x8 + 0x2 ), ( s16 )file->GetU16LE( pointer_to_vertex_data + index_d * 0x8 + 0x4 ) ); a /= 512; b /= 512; c /= 512; d /= 512; int image_id = file->GetU8( pointer_to_mesh_data + 0x13 ); u16 blend = file12->GetU16LE( offset_to_clut_tex + image_id * 4 + 0 ); u16 clut = file12->GetU16LE( offset_to_clut_tex + image_id * 4 + 2 ); LOGGER->Log( "image_id = \"" + HexToString( image_id, 2, '0' ) + "\", clut = \"" + HexToString( clut, 4, '0' ) + "\", blend = \"" + HexToString( blend, 4, '0' ) + "\".\n" ); /* int clut_x = (clut & 0x003f) << 3; int clut_y = (clut & 0xffc0) >> 6; int bpp = (tpage >> 0x7) & 0x3; int vram_x = (tpage & 0xf) * 64; int vram_y = ((tpage & 0x10) >> 4) * 256; */ TexForGen texture; texture.palette_x = 128/*clut_x*/; texture.palette_y = 224/*clut_y*/; if( image_id == 1 ) { texture.texture_x = 768/*vram_x*/; } else { texture.texture_x = 832/*vram_x*/; } texture.texture_y = 256/*vram_y*/; texture.bpp = BPP_8/*bpp*/; AddTexture( texture, mesh_data, textures, LOGGER ); Ogre::Vector2 at( 0, 0 ); Ogre::Vector2 bt( 0, 0 ); Ogre::Vector2 ct( 0, 0 ); Ogre::Vector2 dt( 0, 0 ); u16 vertex1_uv = file->GetU16LE( pointer_to_mesh_data + 0x8 ); at.x = ( file->GetU8( pointer_to_texture_data + vertex1_uv * 2 + 0x0 ) + texture.start_x ) / ( float )mesh_data.tex_width; at.y = ( file->GetU8( pointer_to_texture_data + vertex1_uv * 2 + 0x1 ) + texture.start_y ) / ( float )mesh_data.tex_height; u16 vertex2_uv = file->GetU16LE( pointer_to_mesh_data + 0xa ); bt.x = ( file->GetU8( pointer_to_texture_data + vertex2_uv * 2 + 0x0 ) + texture.start_x ) / ( float )mesh_data.tex_width; bt.y = ( file->GetU8( pointer_to_texture_data + vertex2_uv * 2 + 0x1 ) + texture.start_y ) / ( float )mesh_data.tex_height; u16 vertex3_uv = file->GetU16LE( pointer_to_mesh_data + 0xc ); ct.x = ( file->GetU8( pointer_to_texture_data + vertex3_uv * 2 + 0x0 ) + texture.start_x ) / ( float )mesh_data.tex_width; ct.y = ( file->GetU8( pointer_to_texture_data + vertex3_uv * 2 + 0x1 ) + texture.start_y ) / ( float )mesh_data.tex_height; u16 vertex4_uv = file->GetU16LE( pointer_to_mesh_data + 0xe ); dt.x = ( file->GetU8( pointer_to_texture_data + vertex4_uv * 2 + 0x0 ) + texture.start_x ) / ( float )mesh_data.tex_width; dt.y = ( file->GetU8( pointer_to_texture_data + vertex4_uv * 2 + 0x1 ) + texture.start_y ) / ( float )mesh_data.tex_height; *pPos++ = a.x; *pPos++ = a.y; *pPos++ = a.z; *pPos++ = c.x; *pPos++ = c.y; *pPos++ = c.z; *pPos++ = b.x; *pPos++ = b.y; *pPos++ = b.z; *pPos++ = b.x; *pPos++ = b.y; *pPos++ = b.z; *pPos++ = c.x; *pPos++ = c.y; *pPos++ = c.z; *pPos++ = d.x; *pPos++ = d.y; *pPos++ = d.z; *tPos++ = at.x; *tPos++ = at.y; *tPos++ = ct.x; *tPos++ = ct.y; *tPos++ = bt.x; *tPos++ = bt.y; *tPos++ = bt.x; *tPos++ = bt.y; *tPos++ = ct.x; *tPos++ = ct.y; *tPos++ = dt.x; *tPos++ = dt.y; Ogre::ColourValue colour = Ogre::ColourValue( file->GetU8( pointer_to_mesh_data + 0x10 ) / 256.0f, file->GetU8( pointer_to_mesh_data + 0x11 ) / 256.0f, file->GetU8( pointer_to_mesh_data + 0x12 ) / 256.0f, 1.0f ); rs->convertColourValue( colour, colours + cur_index + 0 ); rs->convertColourValue( colour, colours + cur_index + 1 ); rs->convertColourValue( colour, colours + cur_index + 2 ); rs->convertColourValue( colour, colours + cur_index + 3 ); rs->convertColourValue( colour, colours + cur_index + 4 ); rs->convertColourValue( colour, colours + cur_index + 5 ); idata[ cur_index + 0 ] = cur_index + 0; idata[ cur_index + 1 ] = cur_index + 1; idata[ cur_index + 2 ] = cur_index + 2; idata[ cur_index + 3 ] = cur_index + 3; idata[ cur_index + 4 ] = cur_index + 4; idata[ cur_index + 5 ] = cur_index + 5; Ogre::VertexBoneAssignment vba; vba.weight = 1.0f; vba.vertexIndex = cur_index + 0; vba.boneIndex = file->GetU8( pointer_to_vertex_data + index_a * 0x8 + 0x6 ) * 2 + 3; sub_mesh->addBoneAssignment( vba ); vba.vertexIndex = cur_index + 1; vba.boneIndex = file->GetU8( pointer_to_vertex_data + index_c * 0x8 + 0x6 ) * 2 + 3; sub_mesh->addBoneAssignment( vba ); vba.vertexIndex = cur_index + 2; vba.boneIndex = file->GetU8( pointer_to_vertex_data + index_b * 0x8 + 0x6 ) * 2 + 3; sub_mesh->addBoneAssignment( vba ); vba.vertexIndex = cur_index + 3; vba.boneIndex = file->GetU8( pointer_to_vertex_data + index_b * 0x8 + 0x6 ) * 2 + 3; sub_mesh->addBoneAssignment( vba ); vba.vertexIndex = cur_index + 4; vba.boneIndex = file->GetU8( pointer_to_vertex_data + index_c * 0x8 + 0x6 ) * 2 + 3; sub_mesh->addBoneAssignment( vba ); vba.vertexIndex = cur_index + 5; vba.boneIndex = file->GetU8( pointer_to_vertex_data + index_d * 0x8 + 0x6 ) * 2 + 3; sub_mesh->addBoneAssignment( vba ); cur_index += 6; pointer_to_mesh_data += 0x18; } for( int i = 0; i < number_of_monochrome_textured_triangles; ++i ) { int index_a = file->GetU16LE( pointer_to_mesh_data + 0x0 ); int index_b = file->GetU16LE( pointer_to_mesh_data + 0x2 ); int index_c = file->GetU16LE( pointer_to_mesh_data + 0x4 ); Ogre::Vector3 a( ( s16 )file->GetU16LE( pointer_to_vertex_data + index_a * 0x8 + 0x0 ), ( s16 )file->GetU16LE( pointer_to_vertex_data + index_a * 0x8 + 0x2 ), ( s16 )file->GetU16LE( pointer_to_vertex_data + index_a * 0x8 + 0x4 ) ); Ogre::Vector3 b( ( s16 )file->GetU16LE( pointer_to_vertex_data + index_b * 0x8 + 0x0 ), ( s16 )file->GetU16LE( pointer_to_vertex_data + index_b * 0x8 + 0x2 ), ( s16 )file->GetU16LE( pointer_to_vertex_data + index_b * 0x8 + 0x4 ) ); Ogre::Vector3 c( ( s16 )file->GetU16LE( pointer_to_vertex_data + index_c * 0x8 + 0x0 ), ( s16 )file->GetU16LE( pointer_to_vertex_data + index_c * 0x8 + 0x2 ), ( s16 )file->GetU16LE( pointer_to_vertex_data + index_c * 0x8 + 0x4 ) ); a /= 512; b /= 512; c /= 512; int image_id = file->GetU8( pointer_to_mesh_data + 0x6 ); u16 blend = file12->GetU16LE( offset_to_clut_tex + image_id * 4 + 0 ); u16 clut = file12->GetU16LE( offset_to_clut_tex + image_id * 4 + 2 ); LOGGER->Log( "image_id = \"" + HexToString( image_id, 2, '0' ) + "\", clut = \"" + HexToString( clut, 4, '0' ) + "\", blend = \"" + HexToString( blend, 4, '0' ) + "\".\n" ); /* int clut_x = (clut & 0x003f) << 3; int clut_y = (clut & 0xffc0) >> 6; int bpp = (tpage >> 0x7) & 0x3; int vram_x = (tpage & 0xf) * 64; int vram_y = ((tpage & 0x10) >> 4) * 256; */ TexForGen texture; texture.palette_x = 128/*clut_x*/; texture.palette_y = 224/*clut_y*/; if( image_id == 1 ) { texture.texture_x = 768/*vram_x*/; } else { texture.texture_x = 832/*vram_x*/; } texture.texture_y = 256/*vram_y*/; texture.bpp = BPP_8/*bpp*/; AddTexture( texture, mesh_data, textures, LOGGER ); Ogre::Vector2 at( 0, 0 ); Ogre::Vector2 bt( 0, 0 ); Ogre::Vector2 ct( 0, 0 ); u16 vertex1_uv = file->GetU16LE( pointer_to_mesh_data + 0xc ); at.x = ( file->GetU8( pointer_to_texture_data + vertex1_uv * 2 + 0x0 ) + texture.start_x ) / ( float )mesh_data.tex_width; at.y = ( file->GetU8( pointer_to_texture_data + vertex1_uv * 2 + 0x1 ) + texture.start_y ) / ( float )mesh_data.tex_height; u16 vertex2_uv = file->GetU16LE( pointer_to_mesh_data + 0xe ); bt.x = ( file->GetU8( pointer_to_texture_data + vertex2_uv * 2 + 0x0 ) + texture.start_x ) / ( float )mesh_data.tex_width; bt.y = ( file->GetU8( pointer_to_texture_data + vertex2_uv * 2 + 0x1 ) + texture.start_y ) / ( float )mesh_data.tex_height; u16 vertex3_uv = file->GetU16LE( pointer_to_mesh_data + 0x10 ); ct.x = ( file->GetU8( pointer_to_texture_data + vertex3_uv * 2 + 0x0 ) + texture.start_x ) / ( float )mesh_data.tex_width; ct.y = ( file->GetU8( pointer_to_texture_data + vertex3_uv * 2 + 0x1 ) + texture.start_y ) / ( float )mesh_data.tex_height; *pPos++ = a.x; *pPos++ = a.y; *pPos++ = a.z; *pPos++ = c.x; *pPos++ = c.y; *pPos++ = c.z; *pPos++ = b.x; *pPos++ = b.y; *pPos++ = b.z; *tPos++ = at.x; *tPos++ = at.y; *tPos++ = ct.x; *tPos++ = ct.y; *tPos++ = bt.x; *tPos++ = bt.y; Ogre::ColourValue colour = Ogre::ColourValue( file->GetU8( pointer_to_mesh_data + 0x08 ) / 256.0f, file->GetU8( pointer_to_mesh_data + 0x09 ) / 256.0f, file->GetU8( pointer_to_mesh_data + 0x0a ) / 256.0f, 1.0f ); rs->convertColourValue( colour, colours + cur_index + 0 ); rs->convertColourValue( colour, colours + cur_index + 1 ); rs->convertColourValue( colour, colours + cur_index + 2 ); idata[ cur_index + 0 ] = cur_index + 0; idata[ cur_index + 1 ] = cur_index + 1; idata[ cur_index + 2 ] = cur_index + 2; Ogre::VertexBoneAssignment vba; vba.weight = 1.0f; vba.vertexIndex = cur_index + 0; vba.boneIndex = file->GetU8( pointer_to_vertex_data + index_a * 0x8 + 0x6 ) * 2 + 3; sub_mesh->addBoneAssignment( vba ); vba.vertexIndex = cur_index + 1; vba.boneIndex = file->GetU8( pointer_to_vertex_data + index_c * 0x8 + 0x6 ) * 2 + 3; sub_mesh->addBoneAssignment( vba ); vba.vertexIndex = cur_index + 2; vba.boneIndex = file->GetU8( pointer_to_vertex_data + index_b * 0x8 + 0x6 ) * 2 + 3; sub_mesh->addBoneAssignment( vba ); cur_index += 3; pointer_to_mesh_data += 0x14; } vbuf0->unlock(); vbuf1->writeData( 0, vbuf1->getSizeInBytes(), colours, true ); vbuf2->unlock(); sub_mesh->indexData->indexBuffer->unlock(); // Optimize index data sub_mesh->indexData->optimiseVertexCacheTriList(); delete file12; }
int main(int argc, char* argv[]) { // Choose a Butcher's table or define your own. ButcherTable bt(butcher_table_type); if (bt.is_explicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage explicit R-K method.", bt.get_size()); if (bt.is_diagonally_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage diagonally implicit R-K method.", bt.get_size()); if (bt.is_fully_implicit()) Hermes::Mixins::Loggable::Static::info("Using a %d-stage fully implicit R-K method.", bt.get_size()); // Load the mesh. MeshSharedPtr mesh(new Mesh), basemesh(new Mesh); MeshReaderH2D mloader; mloader.load("square.mesh", basemesh); mesh->copy(basemesh); // Initial mesh refinements. for(int i = 0; i < INIT_GLOB_REF_NUM; i++) mesh->refine_all_elements(); mesh->refine_towards_boundary("Top", INIT_REF_NUM_BDY); // Initialize boundary conditions. CustomEssentialBCNonConst bc_essential(Hermes::vector<std::string>("Bottom", "Right", "Top", "Left")); EssentialBCs<double> bcs(&bc_essential); // Create an H1 space with default shapeset. SpaceSharedPtr<double> space(new H1Space<double>(mesh, &bcs, P_INIT)); int ndof_coarse = Space<double>::get_num_dofs(space); adaptivity.set_space(space); Hermes::Mixins::Loggable::Static::info("ndof_coarse = %d.", ndof_coarse); // Zero initial solution. This is why we use H_OFFSET. MeshFunctionSharedPtr<double> h_time_prev(new ZeroSolution<double>(mesh)), h_time_new(new ZeroSolution<double>(mesh)); // Initialize the constitutive relations. ConstitutiveRelations* constitutive_relations; if(constitutive_relations_type == CONSTITUTIVE_GENUCHTEN) constitutive_relations = new ConstitutiveRelationsGenuchten(ALPHA, M, N, THETA_S, THETA_R, K_S, STORATIVITY); else constitutive_relations = new ConstitutiveRelationsGardner(ALPHA, THETA_S, THETA_R, K_S); // Initialize the weak formulation. CustomWeakFormRichardsRK wf(constitutive_relations); // Initialize the FE problem. DiscreteProblem<double> dp(&wf, space); // Create a refinement selector. H1ProjBasedSelector<double> selector(CAND_LIST); // Visualize initial condition. char title[100]; ScalarView view("Initial condition", new WinGeom(0, 0, 440, 350)); OrderView ordview("Initial mesh", new WinGeom(445, 0, 440, 350)); view.show(h_time_prev); ordview.show(space); // DOF and CPU convergence graphs initialization. SimpleGraph graph_dof, graph_cpu; // Time measurement. Hermes::Mixins::TimeMeasurable cpu_time; cpu_time.tick(); // Time stepping loop. double current_time = 0; int ts = 1; do { // Periodic global derefinement. if (ts > 1 && ts % UNREF_FREQ == 0) { Hermes::Mixins::Loggable::Static::info("Global mesh derefinement."); switch (UNREF_METHOD) { case 1: mesh->copy(basemesh); space->set_uniform_order(P_INIT); break; case 2: mesh->unrefine_all_elements(); space->set_uniform_order(P_INIT); break; case 3: space->unrefine_all_mesh_elements(); space->adjust_element_order(-1, -1, P_INIT, P_INIT); break; default: throw Hermes::Exceptions::Exception("Wrong global derefinement method."); } space->assign_dofs(); ndof_coarse = Space<double>::get_num_dofs(space); } // Spatial adaptivity loop. Note: h_time_prev must not be changed // during spatial adaptivity. bool done = false; int as = 1; double err_est; do { Hermes::Mixins::Loggable::Static::info("Time step %d, adaptivity step %d:", ts, as); // Construct globally refined reference mesh and setup reference space. Mesh::ReferenceMeshCreator refMeshCreator(mesh); MeshSharedPtr ref_mesh = refMeshCreator.create_ref_mesh(); Space<double>::ReferenceSpaceCreator refSpaceCreator(space, ref_mesh); SpaceSharedPtr<double> ref_space = refSpaceCreator.create_ref_space(); int ndof_ref = Space<double>::get_num_dofs(ref_space); // Time measurement. cpu_time.tick(); // Initialize Runge-Kutta time stepping. RungeKutta<double> runge_kutta(&wf, ref_space, &bt); // Perform one Runge-Kutta time step according to the selected Butcher's table. Hermes::Mixins::Loggable::Static::info("Runge-Kutta time step (t = %g s, tau = %g s, stages: %d).", current_time, time_step, bt.get_size()); try { runge_kutta.set_time(current_time); runge_kutta.set_time_step(time_step); runge_kutta.set_max_allowed_iterations(NEWTON_MAX_ITER); runge_kutta.set_tolerance(NEWTON_TOL); runge_kutta.rk_time_step_newton(h_time_prev, h_time_new); } catch(Exceptions::Exception& e) { e.print_msg(); throw Hermes::Exceptions::Exception("Runge-Kutta time step failed"); } // Project the fine mesh solution onto the coarse mesh. MeshFunctionSharedPtr<double> sln_coarse(new Solution<double>); Hermes::Mixins::Loggable::Static::info("Projecting fine mesh solution on coarse mesh for error estimation."); OGProjection<double> ogProjection; ogProjection.project_global(space, h_time_new, sln_coarse); // Calculate element errors and total error estimate. Hermes::Mixins::Loggable::Static::info("Calculating error estimate."); errorCalculator.calculate_errors(sln_coarse, h_time_new, true); double err_est_rel_total = errorCalculator.get_total_error_squared() * 100; // Report results. Hermes::Mixins::Loggable::Static::info("ndof_coarse: %d, ndof_ref: %d, err_est_rel: %g%%", Space<double>::get_num_dofs(space), Space<double>::get_num_dofs(ref_space), err_est_rel_total); // Time measurement. cpu_time.tick(); // If err_est too large, adapt the mesh. if (err_est_rel_total < ERR_STOP) done = true; else { Hermes::Mixins::Loggable::Static::info("Adapting the coarse mesh."); done = adaptivity.adapt(&selector); // Increase the counter of performed adaptivity steps. as++; } } while (done == false); // Add entry to DOF and CPU convergence graphs. graph_dof.add_values(current_time, Space<double>::get_num_dofs(space)); graph_dof.save("conv_dof_est.dat"); graph_cpu.add_values(current_time, cpu_time.accumulated()); graph_cpu.save("conv_cpu_est.dat"); // Visualize the solution and mesh-> char title[100]; sprintf(title, "Solution, time %g", current_time); view.set_title(title); view.show_mesh(false); view.show(h_time_new); sprintf(title, "Mesh, time %g", current_time); ordview.set_title(title); ordview.show(space); // Copy last reference solution into h_time_prev. h_time_prev->copy(h_time_new); // Increase current time and counter of time steps. current_time += time_step; ts++; } while (current_time < T_FINAL); // Wait for all views to be closed. View::wait(); return 0; }
int main(int argc, char *argv[]) { int choice = atoi(argv[1]); bool isPairEnd = false; if (choice) { char *kmerPath = argv[2]; char *refPath = argv[3]; char *taxonomyNodesPath = argv[4]; char *giTaxidPath = argv[5]; char *dirPath = argv[6]; //vector<uint64_t> fKmer; _kmer = (uint8_t) atoi(argv[7]); string bwt_s; vector<uint32_t> nKmerTaxonID; fprintf(stderr,"start preprocessing......\n"); uint64_t hash_index_size = (uint64_t)1 <<((PREINDEXLEN<<1) + 1); uint64_t *hash_index = new uint64_t[hash_index_size](); preprocess(refPath, kmerPath, taxonomyNodesPath, giTaxidPath, bwt_s, nKmerTaxonID, hash_index); fprintf(stderr,"writing index....\n"); //char *dirPath = "."; // bwt bt(bwt_s.c_str(), bwt_s.length(),hash_index); bt.bwt_init(); bt.write_info(dirPath, nKmerTaxonID); //uint64_t sp,ep; //bt.exactMatch("GCTTCGCTGTTATTGGCACCAATTGGATCAC",31, sp,ep); } else { char *readPath; char *taxonomyNodesPath; char * dirPath; char *readPath_s; fprintf(stderr,"%d", argc); if (argc > 7 ) { isPairEnd = true; readPath = argv[2]; readPath_s = argv[3]; taxonomyNodesPath = argv[4]; dirPath = argv[5]; _kmer = (uint8_t) atoi(argv[6]); _interval = atoi(argv[7]); } else { readPath = argv[2]; taxonomyNodesPath = argv[3]; dirPath = argv[4]; _kmer = (uint8_t) atoi(argv[5]); _interval = atoi(argv[6]); } --_kmer; bwt bt(_kmer); fprintf(stderr,"loading index\n"); bt.load_info(dirPath); taxonTree(taxonomyNodesPath); //map<uint32_t, uint32_t>::iterator it = taxonomyTree.begin(); //while (it!=taxonomyTree.end()) { // cout<<it->first<<"\t"<<it->second<<endl; // ++it; //} //cout<<taxonomyTree.size()<<endl; fprintf(stderr,"classifying...\n"); gzFile fp; //uint32_t *nKmerTaxonID = bt.taxonIDTab; fp = gzopen(readPath, "r"); if (!fp) return FILE_OPEN_ERROR; kstream_t *_fp = ks_init(fp); kseq_t *seqs = (kseq_t *) calloc(N_NEEDED, sizeof(kseq_t)); if (!seqs) return MEM_ALLOCATE_ERROR; // //parameters for pair-end reads gzFile fp_s; kstream_t *_fp_s; kseq_t *seqs_s; if (isPairEnd) { fp_s = gzopen(readPath_s, "r"); if (!fp_s) return FILE_OPEN_ERROR; _fp_s = ks_init(fp_s); seqs_s = (kseq_t *) calloc(N_NEEDED, sizeof(kseq_t)); if (!seqs_s) return MEM_ALLOCATE_ERROR; } if (!seqs) return MEM_ALLOCATE_ERROR; cly_r *results = (cly_r *)calloc(2 * N_NEEDED, sizeof(cly_r)); struct timeval tv1, tv2; int n_seqs; total_sequences = 0; gettimeofday(&tv1,NULL); if (isPairEnd) { while ((n_seqs = read_reads(_fp, seqs, N_NEEDED) )> 0 && read_reads(_fp_s, seqs_s, N_NEEDED)) { classify_seq(seqs, n_seqs , bt, results, 0); classify_seq(seqs_s, n_seqs, bt, results, 1); output_results(results, n_seqs, isPairEnd); total_sequences += n_seqs; } } else { while ((n_seqs = read_reads(_fp, seqs, N_NEEDED) )> 0) { classify_seq(seqs, n_seqs , bt, results, 0); output_results(results, n_seqs, isPairEnd); total_sequences += n_seqs; } } gettimeofday(&tv2,NULL); report_stats(tv1,tv2); //fprintf(stderr,"%f seconds\n",((float)t)/CLOCKS_PER_SEC); if (results) free(results); if (seqs) free(seqs); } //char *st; //uint32_t *uts; //uint64_t z; //load_index(dirPath, st, uts, &z ); //cerr<<<<endl; //fprintf(stderr,"%s\n",st); //uint64_t sp, ep; //bwt b(st, uts, z); //b.bwt_init(); //char *read = "GGCT"; //cout<<b.exactMatch(read,4,sp,ep )<<endl; //cout<<sp<<"\t"<<ep<<endl; //read reads file //output(kmerValue, kmerInfo, _2kmers); return NORMAL_EXIT; }
int main(int argc, char* argv[]) { // Choose a Butcher's table or define your own. ButcherTable bt(butcher_table_type); if (bt.is_explicit()) info("Using a %d-stage explicit R-K method.", bt.get_size()); if (bt.is_diagonally_implicit()) info("Using a %d-stage diagonally implicit R-K method.", bt.get_size()); if (bt.is_fully_implicit()) info("Using a %d-stage fully implicit R-K method.", bt.get_size()); // Load the mesh. Mesh mesh; H2DReader mloader; mloader.load("../domain.mesh", &mesh); // Perform initial mesh refinemets. for (int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(); // Initialize solutions. CustomInitialConditionWave E_sln(&mesh); Solution F_sln(&mesh, 0.0, 0.0); Hermes::vector<Solution*> slns(&E_sln, &F_sln); // Initialize the weak formulation. CustomWeakFormWave wf(C_SQUARED); // Initialize boundary conditions DefaultEssentialBCConst bc_essential(BDY, 0.0); EssentialBCs bcs(&bc_essential); // Create x- and y- displacement space using the default H1 shapeset. HcurlSpace E_space(&mesh, &bcs, P_INIT); HcurlSpace F_space(&mesh, &bcs, P_INIT); Hermes::vector<Space *> spaces = Hermes::vector<Space *>(&E_space, &F_space); info("ndof = %d.", Space::get_num_dofs(spaces)); // Initialize the FE problem. DiscreteProblem dp(&wf, spaces); // Initialize Runge-Kutta time stepping. RungeKutta runge_kutta(&dp, &bt, matrix_solver); // Time stepping loop. double current_time = 0; int ts = 1; do { // Perform one Runge-Kutta time step according to the selected Butcher's table. info("Runge-Kutta time step (t = %g s, time_step = %g s, stages: %d).", current_time, time_step, bt.get_size()); bool verbose = true; bool jacobian_changed = true; if (!runge_kutta.rk_time_step(current_time, time_step, slns, slns, jacobian_changed, verbose)) error("Runge-Kutta time step failed, try to decrease time step size."); // Update time. current_time += time_step; } while (current_time < T_FINAL); double coord_x[4] = {0.3, 0.6, 0.9, 1.4}; double coord_y[4] = {0, 0.3, 0.5, 0.7}; info("Coordinate (0.3, 0.0) value = %lf", F_sln.get_pt_value(coord_x[0], coord_y[0])); info("Coordinate (0.6, 0.3) value = %lf", F_sln.get_pt_value(coord_x[1], coord_y[1])); info("Coordinate (0.9, 0.5) value = %lf", F_sln.get_pt_value(coord_x[2], coord_y[2])); info("Coordinate (1.4, 0.7) value = %lf", F_sln.get_pt_value(coord_x[3], coord_y[3])); double t_value[4] = {-0.144673, -0.264077, -0.336536, -0.368983}; bool success = true; for (int i = 0; i < 4; i++) { if (fabs(t_value[i] - F_sln.get_pt_value(coord_x[i], coord_y[i])) > 1E-6) success = false; } if (success) { printf("Success!\n"); return ERR_SUCCESS; } else { printf("Failure!\n"); return ERR_FAILURE; } }