MultiAgent3dNavigation::MultiAgent3dNavigation(const tf::Transform& world_to_cam, const tf::Transform& drone_to_marker, const tf::Transform& drone_to_front_cam, const ranav::TParam &p) { this->params = p; motionModel = new ranav::Rotor3dMotionModel(); motionModel->init(p); ekf = new ranav::EKF(motionModel); ekf->init(p); ttc = new ranav::TargetTrackingController(); ttc->init(p); addOn3d.resize(motionModel->getNumAgents()); this->world_to_cam = world_to_cam; this->drone_to_marker = drone_to_marker; this->drone_to_front_cam = drone_to_front_cam; double roll, pitch, yaw; world_to_cam.getBasis().getEulerYPR(yaw, pitch, roll); Eigen::Vector3d world_to_cam2d(world_to_cam.getOrigin().getX(),world_to_cam.getOrigin().getY(), yaw); world_to_cam2d += Eigen::Vector3d(2, 0, 0); // HACK: move virtual 2D camera pose of tilted camera to have a circular field of view around (0, 0) tf::Quaternion q; q.setRPY(0, 0, world_to_cam2d(2)); world_to_cam_2d = tf::Transform(q, tf::Vector3(world_to_cam2d(0), world_to_cam2d(1), 0)); drone_to_marker.getBasis().getEulerYPR(yaw, pitch, roll); Eigen::Vector3d drone_to_marker2d(drone_to_marker.getOrigin().getX(), drone_to_marker.getOrigin().getY(), yaw); drone_to_front_cam.getBasis().getEulerYPR(yaw, pitch, roll); Eigen::Vector3d drone_to_front_cam2d(drone_to_front_cam.getOrigin().getX(), drone_to_front_cam.getOrigin().getY(), yaw); drone_to_front_cam2d += Eigen::Vector3d(0.8, 0, 0); // HACK: move virtual 2D camera pose of tilted camera to have a circular field of view around (0, 0) q.setRPY(0, 0, drone_to_front_cam2d(2)); drone_to_front_cam_2d = tf::Transform(q, tf::Vector3(drone_to_front_cam2d(0), drone_to_front_cam2d(1), 0)); ranav::AllModels models; ranav::Marker3dSensorModel *sm; sm = new ranav::Marker3dSensorModel(-1, 0); sm->init(p); sm->setCameraPose(world_to_cam2d); // HACK: overwrites parameter of config file sm->setMarkerPose(drone_to_marker2d); // HACK: overwrites parameter of config file models()[ranav::Index(-1, 0)] = sm; sm = new ranav::Marker3dSensorModel(0, 1); sm->init(p); sm->setCameraPose(drone_to_front_cam2d); // HACK: overwrites ... models()[ranav::Index(0, 1)] = sm; ttc->getTopology().setAllSensorModels(models); sensorModels = ttc->getTopology().getSensorModelsNonconst(); }
/***********************************************************************//** * @brief Test CTA Npred computation * * Tests the Npred computation for the diffuse source model. This is done * by loading the model from the XML file and by calling the * GCTAObservation::npred method which in turn calls the * GCTAResponse::npred_diffuse method. The test takes a few seconds. ***************************************************************************/ void TestGCTAResponse::test_response_npred_diffuse(void) { // Set reference value double ref = 11212.26274; // Set parameters double src_ra = 201.3651; double src_dec = -43.0191; double roi_rad = 4.0; // Setup ROI centred on Cen A with a radius of 4 deg GCTARoi roi; GCTAInstDir instDir; instDir.radec_deg(src_ra, src_dec); roi.centre(instDir); roi.radius(roi_rad); // Setup pointing on Cen A GSkyDir skyDir; skyDir.radec_deg(src_ra, src_dec); GCTAPointing pnt; pnt.dir(skyDir); // Setup dummy event list GGti gti; GEbounds ebounds; GTime tstart(0.0); GTime tstop(1800.0); GEnergy emin; GEnergy emax; emin.TeV(0.1); emax.TeV(100.0); gti.append(tstart, tstop); ebounds.append(emin, emax); GCTAEventList events; events.roi(roi); events.gti(gti); events.ebounds(ebounds); // Setup dummy CTA observation GCTAObservation obs; obs.ontime(1800.0); obs.livetime(1600.0); obs.deadc(1600.0/1800.0); obs.response(cta_irf, cta_caldb); obs.events(&events); obs.pointing(pnt); // Load models for Npred computation GModels models(cta_rsp_xml); // Perform Npred computation double npred = obs.npred(models, NULL); // Test Npred test_value(npred, ref, 1.0e-5, "Diffuse Npred computation"); // Return return; }
bool Test1D_EM() { int dimensionality = 1; // Generate some data Eigen::MatrixXd data = GenerateData(40, dimensionality); // Initialize the model std::vector<Model*> models(2); for(unsigned int i = 0; i < models.size(); i++) { Model* model = new GaussianModel(dimensionality); models[i] = model; } MixtureModel mixtureModel; mixtureModel.SetModels(models); ExpectationMaximization expectationMaximization; expectationMaximization.SetData(data); expectationMaximization.SetRandom(false); expectationMaximization.SetMixtureModel(mixtureModel); expectationMaximization.SetMaxIterations(3); expectationMaximization.Compute(); // This is where we got the test output MixtureModel finalModel = expectationMaximization.GetMixtureModel(); for(unsigned int i = 0; i < finalModel.GetNumberOfModels(); ++i) { std::cout << "Model " << i << ":" << std::endl; finalModel.GetModel(i)->Print(); } std::vector<double> testMeans; testMeans.push_back(4.90469); testMeans.push_back(0.00576815); std::vector<double> testVariances; testVariances.push_back(0.830928); testVariances.push_back(0.862264); double epsilon = 1e-4; for(unsigned int i = 0; i < finalModel.GetNumberOfModels(); ++i) { if(fabs(testMeans[i] - finalModel.GetModel(i)->GetMean()(0)) > epsilon) { return false; } if(fabs(testVariances[i] - finalModel.GetModel(i)->GetVariance()(0,0)) > epsilon) { return false; } } return true; }
void babl_base_model_gray (void) { components (); models (); conversions (); formats (); }
/***********************************************************************//** * @brief Print registry information * * @param[in] chatter Chattiness (defaults to NORMAL). * @return Registry content. ***************************************************************************/ std::string GModelSpatialRegistry::print(const GChatter& chatter) const { // Initialise result string std::string result; // Continue only if chatter is not silent if (chatter != SILENT) { // Append header result.append("=== GModelSpatialRegistry ==="); // Append information result.append("\n"+gammalib::parformat("Number of models")); result.append(gammalib::str(size())); // NORMAL: Append models if (chatter >= NORMAL) { for (int i = 0; i < size(); ++i) { result.append("\n"+gammalib::parformat(names()[i])); result.append(models()[i]->type()); } } } // endif: chatter was not silent // Return result return result; }
/***********************************************************************//** * @brief Model constructor * * @param[in] model Model. * * Construct registry by adding a model to the registry. This is the standard * constructor that is used to register a new model to GammaLib. ***************************************************************************/ GModelSpatialRegistry::GModelSpatialRegistry(const GModelSpatial* model) { // Initialise private members for clean destruction init_members(); // Debug option: Notify new registry #if G_DEBUG_REGISTRY std::cout << "GModelSpatialRegistry(const GModelSpatial*): "; std::cout << "add \"" << model->type() << "\" to registry." << std::endl; #endif // Allocate new registry std::string* new_names = new std::string[size()+1]; const GModelSpatial** new_models = new const GModelSpatial*[size()+1]; // Save old registry for (int i = 0; i < size(); ++i) { new_names[i] = names()[i]; new_models[i] = models()[i]; } // Add new model to registry new_names[size()] = model->type(); new_models[size()] = model; // Set pointers on new registry names().assign(new_names); models().assign(new_models); // Increment number of models in registry number()++; // Debug option: Show actual registry #if G_DEBUG_REGISTRY std::cout << "GModelSpatialRegistry(const GModelSpatial*): "; for (int i = 0; i < size(); ++i) { std::cout << "\"" << names()[i] << "\" "; } std::cout << std::endl; #endif // Return return; }
void PerfTimelineModelManager::clear() { QVariantList perfModels = models(); Timeline::TimelineModelAggregator::clear(); for (QVariant &var : perfModels) delete qvariant_cast<PerfTimelineModel *>(var); qDeleteAll(m_unfinished); m_unfinished.clear(); m_resourceContainers.clear(); }
int init (void) { types (); components (); models (); formats (); conversions (); return 0; }
void RecFile::SaveContent( ) { wxASSERT_MSG( m_imPagePtr, "ImPage should not be NULL" ); wxASSERT_MSG( m_musDocPtr, "MusDoc should not be NULL" ); wxASSERT( m_xml_root ); if ( !m_isPreprocessed ) return; else { m_imPagePtr->Save( m_xml_root ); // save in the RecFile directory // binarization variables TiXmlElement binarization( "binarization" ); binarization.SetAttribute( "pre_image_binarization_method", RecFile::m_pre_image_binarization_method ); binarization.SetAttribute( "pre_page_binarization_method", RecFile::m_pre_page_binarization_method ); binarization.SetAttribute( "pre_page_binarization_method_size", RecFile::m_pre_page_binarization_method_size ); m_xml_root->InsertEndChild( binarization ); } if ( !m_isRecognized ) return; else { //possibility of MusDoc being a .mei not a .bin //MusMeiOutput *mei_output = new MusMeiOutput( m_musDocPtr, m_musDocPtr->m_fname ); // save MusMeiOutput *mei_output = new MusMeiOutput( m_musDocPtr, m_musDocPtr->m_fname ); mei_output->ExportFile(); delete mei_output; MusMLFOutput *mlfoutput = new MusMLFOutput( m_musDocPtr, m_basename + "page.mlf", NULL ); mlfoutput->m_pagePosition = true; // !!! No check if layout and page exist! mlfoutput->WritePage( (MusPage*)m_musDocPtr->m_children[0] , "staff", m_imPagePtr ); delete mlfoutput; TiXmlElement root( "recpage" ); // models TiXmlElement models( "models" ); models.SetAttribute( "typographic_model", m_rec_typ_model.c_str() ); models.SetAttribute( "music_model", m_rec_mus_model.c_str() ); root.InsertEndChild( models ); // decoder TiXmlElement decoder( "decoder" ); decoder.SetAttribute( "wrdtrns", m_rec_wrdtrns.c_str() ); decoder.SetAttribute( "lm_delayed", m_rec_delayed ); decoder.SetAttribute( "order", m_rec_lm_order ); decoder.SetDoubleAttribute( "scaling", m_rec_lm_scaling ); root.InsertEndChild( decoder ); m_xml_root->InsertEndChild( root ); } }
void Scene::Init() { std::vector<uint8_t> sceneData; m3d::file::readBinary("D:\\workspace\\m3d\\data\\schema\\scene_data.bin", sceneData); auto mainScene = GetSScene(sceneData.data()); loadPath = mainScene->models()->Get(0)->name()->str(); printf("fbx path: %s", loadPath.c_str()); diffuseMaps = packed_freelist<DiffuseMap>(512); materials = packed_freelist<Material>(512); meshes = packed_freelist<Mesh>(512); transforms = packed_freelist<Transform>(4096); instances = packed_freelist<Instance>(4096); cameras = packed_freelist<Camera>(32); }
/***********************************************************************//** * @brief Allocate spatial model of given name * * @param[in] name Model name. * @return Pointer to model (NULL if name is not registered). * * Returns a pointer to a void spatial model instance of the specified * name. If the name has not been found in the registry, a NULL pointer is * returned. ***************************************************************************/ GModelSpatial* GModelSpatialRegistry::alloc(const std::string& name) const { // Initialise spatial model GModelSpatial* model = NULL; // Search for model in registry for (int i = 0; i < size(); ++i) { if (names()[i] == name) { model = models()[i]->clone(); break; } } // Return spatial model return model; }
bool QLCFixtureDefCache::addFixtureDef(QLCFixtureDef* fixtureDef) { if (fixtureDef == NULL) return false; if (models(fixtureDef->manufacturer()).contains(fixtureDef->model()) == false) { m_defs << fixtureDef; return true; } else { qWarning() << Q_FUNC_INFO << "Cache already contains" << fixtureDef->name(); return false; } }
//-------------------------------------------------------------------------- void FLevelFile::loadModels() { HRCFileManager &hrc_mgr( HRCFileManager::getSingleton() ); ModelList &models( m_model_list->getModels() ); ModelList::const_iterator it ( models.begin() ) , it_end( models.end() ); while( it != it_end ) { String hrc_name( it->hrc_name ); Ogre::LogManager::getSingleton().stream() << "Loading Model: " << hrc_name; StringUtil::toLowerCase( hrc_name ); HRCFilePtr hrc( hrc_mgr.load( hrc_name, mGroup ) ); loadAnimations( hrc, it->animations ); m_hrc_files.push_back( hrc ); ++it; } }
ModelMap ReadModels(FILE *f, int *num_images_out) { char buf[256]; int num_images; fscanf(f, "%d\n", &num_images); ModelMap models(num_images); // assert(num_images == num_images); while (fgets(buf, 256, f)) { int i1, i2; sscanf(buf, "%d %d", &i1, &i2); TwoFrameModel m; m.Read(f); if (m.ComputeTrace(true) < 0.0 || m.ComputeTrace(false) < 0.0) { printf("[ReadModels] Error! Trace(%d,%d) < 0!\n", i1, i2); continue; } if (m.m_num_points < 28 /*33*/) { // printf("[ReadModels] Error! Too few points [%d] for (%d,%d)\n", // m.m_num_points, i1, i2); continue; } if (isnan(m.m_angle) || isnan(m.m_error)) { printf("[ReadModels] Error! NaNs in pair %d,%d!\n", i1, i2); continue; } assert(i1 < i2); models.AddModel(GetMatchIndex(i1, i2), m); } if (num_images_out != NULL) *num_images_out = num_images; return models; }
void AddFixture_Test::initialScanner() { Fixture* fxi = new Fixture(m_doc); fxi->setName("My scanner"); QLCFixtureDef* def = m_doc->fixtureDefCache()->fixtureDef("Martin", "MAC300"); Q_ASSERT(def != NULL); Q_ASSERT(def != NULL); Q_ASSERT(def->channels().size() > 0); QLCFixtureMode* mode = def->modes().first(); Q_ASSERT(def->modes().size() > 1); fxi->setFixtureDefinition(def, mode); fxi->setUniverse(2); fxi->setAddress(484); m_doc->addFixture(fxi); AddFixture af(NULL, m_doc, fxi); QVERIFY(m_doc == af.m_doc); QVERIFY(af.fixtureDef() == def); QVERIFY(af.mode() == mode); QVERIFY(af.name() == QString("My scanner")); QVERIFY(af.address() == 484); QVERIFY(af.universe() == 2); QVERIFY(af.amount() == 1); QVERIFY(af.gap() == 0); QVERIFY(af.channels() == fxi->channels()); // Check that all makes & models are put to the tree QStringList makers(m_doc->fixtureDefCache()->manufacturers()); QVERIFY(makers.isEmpty() == false); for (int i = 0; i < af.m_tree->topLevelItemCount(); i++) { QTreeWidgetItem* top = af.m_tree->topLevelItem(i); if (top->text(0) != KXMLFixtureGeneric) { QStringList models(m_doc->fixtureDefCache()->models(top->text(0))); for (int j = 0; j < top->childCount(); j++) { QTreeWidgetItem* child = top->child(j); QCOMPARE(child->childCount(), 0); QCOMPARE(models.removeAll(child->text(0)), 1); } QCOMPARE(makers.removeAll(top->text(0)), 1); } else { QCOMPARE(i, af.m_tree->topLevelItemCount() - 1); // Generic should be last QCOMPARE(top->childCount(), 3); QCOMPARE(top->child(0)->text(0), QString(KXMLFixtureGeneric)); QStringList models(m_doc->fixtureDefCache()->models(top->text(0))); for (int j = 0; j < top->childCount(); j++) { QTreeWidgetItem* child = top->child(j); QCOMPARE(child->childCount(), 0); QCOMPARE(models.removeAll(child->text(0)), child->text(0) == KXMLFixtureGeneric ? 0 : 1); } QCOMPARE(makers.removeAll(top->text(0)), 1); } } QVERIFY(makers.isEmpty() == true); // Generic / Generic should be selected for dimmers QVERIFY(af.m_tree->currentItem() != NULL); QCOMPARE(af.m_tree->currentItem()->text(0), def->model()); QVERIFY(af.m_tree->currentItem()->parent() != NULL); QCOMPARE(af.m_tree->currentItem()->parent()->text(0), def->manufacturer()); QVERIFY(af.m_modeCombo->isEnabled() == true); QCOMPARE(af.m_modeCombo->count(), def->modes().size()); QCOMPARE(af.m_modeCombo->itemText(0), mode->name()); QVERIFY(af.m_universeCombo->isEnabled() == true); QCOMPARE(af.m_universeCombo->currentIndex(), 2); QCOMPARE(af.m_universeCombo->count(), 4); QVERIFY(af.m_addressSpin->isEnabled() == true); QCOMPARE(af.m_addressSpin->value(), 485); QVERIFY(af.m_channelsSpin->isEnabled() == false); QCOMPARE(af.m_channelsSpin->value(), (int) fxi->channels()); QVERIFY(af.m_nameEdit->isEnabled() == true); QCOMPARE(af.m_nameEdit->text(), QString("My scanner")); QVERIFY(af.m_nameEdit->isModified() == true); QVERIFY(af.m_multipleGroup->isEnabled() == false); QVERIFY(af.m_gapSpin->isEnabled() == false); QCOMPARE(af.m_gapSpin->value(), 0); QVERIFY(af.m_amountSpin->isEnabled() == false); QCOMPARE(af.m_amountSpin->value(), 1); }
void AddFixture_Test::initialNoFixture() { AddFixture af(NULL, m_doc); QVERIFY(m_doc == af.m_doc); QVERIFY(af.fixtureDef() == NULL); QVERIFY(af.mode() == NULL); QCOMPARE(af.name(), tr("Dimmers")); QVERIFY(af.address() == 0); QVERIFY(af.universe() == 0); QVERIFY(af.amount() == 1); QVERIFY(af.gap() == 0); QVERIFY(af.channels() == 1); QVERIFY(af.m_tree->columnCount() == 1); // Check that all makes & models are put to the tree QStringList makers(m_doc->fixtureDefCache()->manufacturers()); QVERIFY(makers.isEmpty() == false); for (int i = 0; i < af.m_tree->topLevelItemCount(); i++) { QTreeWidgetItem* top = af.m_tree->topLevelItem(i); if (top->text(0) != KXMLFixtureGeneric) { QStringList models(m_doc->fixtureDefCache()->models(top->text(0))); for (int j = 0; j < top->childCount(); j++) { QTreeWidgetItem* child = top->child(j); QCOMPARE(child->childCount(), 0); QCOMPARE(models.removeAll(child->text(0)), 1); } QCOMPARE(makers.removeAll(top->text(0)), 1); } else { QCOMPARE(i, af.m_tree->topLevelItemCount() - 1); // Generic should be last QCOMPARE(top->childCount(), 3); QCOMPARE(top->child(0)->text(0), QString(KXMLFixtureGeneric)); QStringList models(m_doc->fixtureDefCache()->models(top->text(0))); for (int j = 0; j < top->childCount(); j++) { QTreeWidgetItem* child = top->child(j); QCOMPARE(child->childCount(), 0); QCOMPARE(models.removeAll(child->text(0)), child->text(0) == KXMLFixtureGeneric ? 0 : 1); } QCOMPARE(makers.removeAll(top->text(0)), 1); } } QVERIFY(makers.isEmpty() == true); // Generic / Generic should be selected by default QVERIFY(af.m_tree->currentItem() != NULL); QCOMPARE(af.m_tree->currentItem()->text(0), QString(KXMLFixtureGeneric)); QVERIFY(af.m_tree->currentItem()->parent() != NULL); QCOMPARE(af.m_tree->currentItem()->parent()->text(0), QString(KXMLFixtureGeneric)); QVERIFY(af.m_modeCombo->isEnabled() == false); QCOMPARE(af.m_modeCombo->count(), 1); QCOMPARE(af.m_modeCombo->itemText(0), QString(KXMLFixtureGeneric)); QVERIFY(af.m_universeCombo->isEnabled() == true); QCOMPARE(af.m_universeCombo->currentIndex(), 0); QCOMPARE(af.m_universeCombo->count(), 4); QVERIFY(af.m_addressSpin->isEnabled() == true); QCOMPARE(af.m_addressSpin->value(), 1); QCOMPARE(af.m_addressSpin->minimum(), 1); QCOMPARE(af.m_addressSpin->maximum(), 512); QVERIFY(af.m_channelsSpin->isEnabled() == true); QCOMPARE(af.m_channelsSpin->value(), 1); QVERIFY(af.m_nameEdit->isEnabled() == true); QCOMPARE(af.m_nameEdit->text(), QString(KXMLFixtureDimmer + QString("s"))); QVERIFY(af.m_nameEdit->isModified() == false); QVERIFY(af.m_multipleGroup->isEnabled() == true); QVERIFY(af.m_gapSpin->isEnabled() == true); QCOMPARE(af.m_gapSpin->value(), 0); QVERIFY(af.m_amountSpin->isEnabled() == true); QCOMPARE(af.m_amountSpin->value(), 1); }
int main(int argc, char *argv[]) #endif { bool context_ok = false; context = new Context(win_w, win_h); #ifdef _WIN32 WNDCLASS wndcl; wndcl.cbClsExtra = 0; wndcl.cbWndExtra = 0; wndcl.hbrBackground = NULL; wndcl.hCursor = LoadCursor(NULL, IDC_ARROW); wndcl.hIcon = LoadIcon(NULL, IDI_WINLOGO); // IDI_APPLICATION wndcl.hInstance = hInstance; wndcl.lpfnWndProc = WndProc; wndcl.lpszClassName = TEXT("OpenGL"); wndcl.lpszMenuName = 0; wndcl.style = CS_OWNDC; // CS_HREDRAW | CS_VREDRAW context_ok = context->init(hInstance, hPrevInstance, szCmdLine, iCmdShow, &wndcl); #else context_ok = context->init(); #endif if (!context_ok) { appclose(); exit(1); } GLenum error = glewInit(); if (GLEW_OK != error) { std::cout << "GLEW Initialisation failed " << glewGetErrorString(error) << std::endl; appclose(); exit(1); } bool hw_ok = false; hw_ok = check_hardware(); if (! hw_ok) { std::cout << "Required extensions are not available." << std::endl; appclose(); exit(0); } initialize(); models(); atexit(appclose); run = true; #ifdef _WIN32 MSG msg; while(run) { double et = timer.getElapsedTime(); timer.start(); v_right = 0; v_left = 0; v_forward = 0; v_backward = 0; heading_degrees = 0.0f; pitch_degrees = 0.0f; short key_w = GetKeyState(0x57); if (key_w & (1 << 15)) v_forward=1; short key_s = GetKeyState(0x53); if (key_s & (1 << 15)) v_backward=1; short key_a = GetKeyState(0x41); if (key_a & (1 << 15)) v_left=1; short key_d = GetKeyState(0x44); if (key_d & (1 << 15)) v_right=1; if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) { if( msg.message == WM_QUIT ) { run = false; break; } TranslateMessage(&msg); DispatchMessage(&msg); } render(et); } return msg.wParam; #else std::cout << "X window ID: " << context->win << std::endl; Window ret_root; Window ret_child; glEnable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); while(run) { double et = timer.getElapsedTime(); timer.start(); fps_ = 1.0/et; v_right = 0; v_left = 0; v_forward = 0; v_backward = 0; heading_degrees = 0.0f; pitch_degrees = 0.0f; #ifdef QUERY_POINTER int win_x, win_y, root_x, root_y; unsigned int mask; bool t = XQueryPointer(context->display, context->win, &ret_root, &ret_child, &root_x, &root_y, &win_x, &win_y, &mask); if (t) { //std::cout << win_x << " " << win_y << " " << root_x << " " << root_y << std::endl; heading_degrees = ((float)root_x/1024.0f - 0.5f)*2.0f; pitch_degrees = ((float)root_y/786.0f - 0.5f)*2.0f; } #endif char keys[32]; XQueryKeymap(context->display, keys); for ( int i = 0; i < 32; i++ ) { int j; if ( !keys[i] ) continue; for ( j = 0; j < 8; j++ ) { if ( keys[i] & (1 << j) ) { KeyCode keycode = (i << 3 | j); KeySym keysym = XKeycodeToKeysym(context->display, keycode, 0); if (keysym == (KeySym)XK_Escape) { run = false; } else if (keysym == (KeySym)XK_a) { v_left = 1; } else if (keysym == (KeySym)XK_d) { v_right = 1; } else if (keysym == (KeySym)XK_w) { v_forward = 1; } else if (keysym == (KeySym)XK_s) { v_backward = 1; } } } } XSync(context->display, False); if (XPending(context->display)>0 && run) { XEvent xevent; memset(&xevent, '\0', sizeof (XEvent)); /* valgrind fix. --ryan. */ XNextEvent(context->display, &xevent); switch (xevent.type) { case EnterNotify: break; case LeaveNotify: break; case FocusIn: break; case FocusOut: break; case KeymapNotify: break; case MotionNotify: #ifndef QUERY_POINTER { XMotionEvent * mevent = (XMotionEvent *) &xevent; if (mevent->same_screen) { heading_degrees = (90.0/(win_w*0.5f)) * ((float)mevent->x - win_w*0.5f); pitch_degrees = (90.0/(win_h*0.5f)) * ((float)mevent->y - win_h*0.5f); } XWarpPointer(context->display, None, context->win, 0, 0, 0, 0, win_w*0.5f, win_h*0.5f); } #endif break; case ButtonPress: break; case ButtonRelease: break; case KeyPress: { } break; case KeyRelease: break; case UnmapNotify: break; case MapNotify: break; case ConfigureNotify: break; case ClientMessage: { if ( (xevent.xclient.format == 32) && (xevent.xclient.data.l[0] == context->WM_DELETE_WINDOW) ) { std::cout << "WM_DELETE_WINDOW" << std::endl; run = false; goto stop; } } break; case Expose: break; default: break; } } XSync(context->display, True); render(et); }; stop: return 0; #endif }
bool Test2D_EM() { int dimensionality = 2; // Generate some data Eigen::MatrixXd data = GenerateData(40, dimensionality); // Initialize the model std::vector<Model*> models(2); for(unsigned int i = 0; i < models.size(); i++) { Model* model = new GaussianModel(dimensionality); models[i] = model; } MixtureModel mixtureModel; mixtureModel.SetModels(models); ExpectationMaximization expectationMaximization; expectationMaximization.SetData(data); expectationMaximization.SetRandom(false); expectationMaximization.SetMixtureModel(mixtureModel); expectationMaximization.SetMaxIterations(3); expectationMaximization.SetInitializationTechniqueToKMeans(); expectationMaximization.Compute(); // This is where we got the test output MixtureModel finalModel = expectationMaximization.GetMixtureModel(); for(unsigned int i = 0; i < finalModel.GetNumberOfModels(); ++i) { std::cout << "Model " << i << ":" << std::endl; finalModel.GetModel(i)->Print(); } Eigen::VectorXd mean0(2); mean0 << 0.0631675, -0.147669; Eigen::VectorXd mean1(2); mean1 << 10.23, 10.069; Eigen::MatrixXd var0(2,2); var0 << 0.818243, -0.027182, -0.027182, 0.836947; Eigen::MatrixXd var1(2,2); var1 << 2.49997, 0.10499, 0.10499, 1.85563; double epsilon = 1e-4; // Check means if((finalModel.GetModel(0)->GetMean() - mean0).norm() > epsilon) { return false; } if((finalModel.GetModel(1)->GetMean() - mean1).norm() > epsilon) { return false; } // Check variances if((finalModel.GetModel(0)->GetVariance() - var0).norm() > epsilon) { return false; } if((finalModel.GetModel(1)->GetVariance() - var1).norm() > epsilon) { return false; } return true; }
/***********************************************************************//** * @brief Simulate event data * * This method runs the simulation. Results are not saved by this method. * Invoke "save" to save the results. ***************************************************************************/ void ctobssim::run(void) { // Switch screen logging on in debug mode if (logDebug()) { log.cout(true); } // Get parameters get_parameters(); // Write input parameters into logger if (logTerse()) { log_parameters(); log << std::endl; } // Special mode: if read ahead is specified we know that we called // the execute() method, hence files are saved immediately and event // lists are disposed afterwards. if (read_ahead()) { m_save_and_dispose = true; } // Determine the number of valid CTA observations, set energy dispersion flag // for all CTA observations and save old values in save_edisp vector int n_observations = 0; std::vector<bool> save_edisp; save_edisp.assign(m_obs.size(), false); for (int i = 0; i < m_obs.size(); ++i) { GCTAObservation* obs = dynamic_cast<GCTAObservation*>(m_obs[i]); if (obs != NULL) { save_edisp[i] = obs->response()->apply_edisp(); obs->response()->apply_edisp(m_apply_edisp); n_observations++; } } // If more than a single observation has been handled then make sure that // an XML file will be used for storage if (n_observations > 1) { m_use_xml = true; } // Write execution mode into logger if (logTerse()) { log << std::endl; log.header1("Execution mode"); log << gammalib::parformat("Event list management"); if (m_save_and_dispose) { log << "Save and dispose (reduces memory needs)" << std::endl; } else { log << "Keep events in memory" << std::endl; } log << gammalib::parformat("Output format"); if (m_use_xml) { log << "Write Observation Definition XML file" << std::endl; } else { log << "Write single event list FITS file" << std::endl; } } // Write seed values into logger if (logTerse()) { log << std::endl; log.header1("Seed values"); for (int i = 0; i < m_rans.size(); ++i) { log << gammalib::parformat("Seed "+gammalib::str(i)); log << gammalib::str(m_rans[i].seed()) << std::endl; } } // Write observation(s) into logger if (logTerse()) { log << std::endl; if (m_obs.size() > 1) { log.header1("Observations"); } else { log.header1("Observation"); } log << m_obs << std::endl; } // Write header if (logTerse()) { log << std::endl; if (m_obs.size() > 1) { log.header1("Simulate observations"); } else { log.header1("Simulate observation"); } } // From here on the code can be parallelized if OpenMP support // is enabled. The code in the following block corresponds to the // code that will be executed in each thread #pragma omp parallel { // Each thread will have it's own logger to avoid conflicts GLog wrklog; if (logDebug()) { wrklog.cout(true); } // Allocate and initialize copies for multi-threading GModels models(m_obs.models()); // Copy configuration from application logger to thread logger wrklog.date(log.date()); wrklog.name(log.name()); // Set a big value to avoid flushing wrklog.max_size(10000000); // Loop over all observation in the container. If OpenMP support // is enabled, this loop will be parallelized. #pragma omp for for (int i = 0; i < m_obs.size(); ++i) { // Get pointer on CTA observation GCTAObservation* obs = dynamic_cast<GCTAObservation*>(m_obs[i]); // Continue only if observation is a CTA observation if (obs != NULL) { // Write header for observation if (logTerse()) { if (obs->name().length() > 1) { wrklog.header3("Observation "+obs->name()); } else { wrklog.header3("Observation"); } } // Work on a clone of the CTA observation. This makes sure that // any memory allocated for computing (for example a response // cache) is properly de-allocated on exit of this run GCTAObservation obs_clone = *obs; // Save number of events before entering simulation int events_before = obs_clone.events()->size(); // Simulate source events simulate_source(&obs_clone, models, m_rans[i], &wrklog); // Simulate source events simulate_background(&obs_clone, models, m_rans[i], &wrklog); // Dump simulation results if (logNormal()) { wrklog << gammalib::parformat("MC events"); wrklog << obs_clone.events()->size() - events_before; wrklog << " (all models)"; wrklog << std::endl; } // Append the event list to the original observation obs->events(*(obs_clone.events())); // If requested, event lists are saved immediately if (m_save_and_dispose) { // Set event output file name. If multiple observations are // handled, build the filename from prefix and observation // index. Otherwise use the outfile parameter. std::string outfile; if (m_use_xml) { m_prefix = (*this)["prefix"].string(); outfile = m_prefix + gammalib::str(i) + ".fits"; } else { outfile = (*this)["outevents"].filename(); } // Store output file name in original observation obs->eventfile(outfile); // Save observation into FITS file. This is a critical zone // to avoid multiple threads writing simultaneously #pragma omp critical { obs_clone.save(outfile, clobber()); } // Dispose events obs->dispose_events(); } // ... otherwise append the event list to the original observation /* else { obs->events(*(obs_clone.events())); } */ } // endif: CTA observation found } // endfor: looped over observations // At the end, the content of the thread logger is added to // the application logger #pragma omp critical (log) { log << wrklog; } } // end pragma omp parallel // Restore energy dispersion flag for all CTA observations for (int i = 0; i < m_obs.size(); ++i) { GCTAObservation* obs = dynamic_cast<GCTAObservation*>(m_obs[i]); if (obs != NULL) { obs->response()->apply_edisp(save_edisp[i]); } } // Return return; }
/***********************************************************************//** * @brief Test CTA IRF computation for diffuse source model * * Tests the IRF computation for the diffuse source model. This is done * by calling the GCTAObservation::model method which in turn calls the * GCTAResponse::irf_diffuse method. The test is done for a small counts * map to keep the test executing reasonably fast. ***************************************************************************/ void TestGCTAResponse::test_response_irf_diffuse(void) { // Set reference value double ref = 13803.800313356; // Set parameters double src_ra = 201.3651; double src_dec = -43.0191; int nebins = 5; // Setup pointing on Cen A GSkyDir skyDir; skyDir.radec_deg(src_ra, src_dec); GCTAPointing pnt; pnt.dir(skyDir); // Setup skymap (10 energy layers) GSkymap map("CAR", "CEL", src_ra, src_dec, 0.5, 0.5, 10, 10, nebins); // Setup time interval GGti gti; GTime tstart(0.0); GTime tstop(1800.0); gti.append(tstart, tstop); // Setup energy boundaries GEbounds ebounds; GEnergy emin; GEnergy emax; emin.TeV(0.1); emax.TeV(100.0); ebounds.setlog(emin, emax, nebins); // Setup event cube centered on Cen A GCTAEventCube cube(map, ebounds, gti); // Setup dummy CTA observation GCTAObservation obs; obs.ontime(1800.0); obs.livetime(1600.0); obs.deadc(1600.0/1800.0); obs.response(cta_irf, cta_caldb); obs.events(&cube); obs.pointing(pnt); // Load model for IRF computation GModels models(cta_rsp_xml); // Reset sum double sum = 0.0; // Iterate over all bins in event cube for (int i = 0; i < obs.events()->size(); ++i) { // Get event pointer const GEventBin* bin = (*(static_cast<const GEventCube*>(obs.events())))[i]; // Get model and add to sum double model = obs.model(models, *bin, NULL) * bin->size(); sum += model; } // Test sum test_value(sum, ref, 1.0e-5, "Diffuse IRF computation"); // Return return; }