Ioss::EntityBlock::EntityBlock(Ioss::DatabaseIO *io_database, const std::string &my_name, const std::string &entity_type, size_t entity_count) : Ioss::GroupingEntity(io_database, my_name, entity_count), idOffset(0) { // The 'true' means it is ok for the factory to return // nullptr. This is done here just so we can output a better // error message. topology_ = ElementTopology::factory(entity_type, true); if (topology_ == nullptr) { std::ostringstream errmsg; errmsg << "ERROR: The topology type '" << entity_type << "' is not supported" << " on " << name() << " in file " << io_database->get_filename(); IOSS_ERROR(errmsg); } if (topology()->master_element_name() != entity_type && topology()->name() != entity_type) { // Maintain original element type on output database if possible. properties.add(Ioss::Property("original_topology_type", entity_type)); } properties.add(Ioss::Property(this, "topology_node_count", Ioss::Property::INTEGER)); properties.add(Ioss::Property(this, "topology_type", Ioss::Property::STRING)); fields.add(Ioss::Field("connectivity", field_int_type(), topology_->name(), Ioss::Field::MESH, entity_count)); // Returns connectivity in local id space fields.add(Ioss::Field("connectivity_raw", field_int_type(), topology()->name(), Ioss::Field::MESH, entity_count)); }
Ioss::Property Ioss::EntityBlock::get_implicit_property(const std::string& my_name) const { if (my_name == "topology_node_count") return Ioss::Property(my_name, topology()->number_nodes()); else if (my_name == "topology_type") return Ioss::Property(my_name, topology()->name()); else return Ioss::GroupingEntity::get_implicit_property(my_name); }
Ioss::FaceBlock::FaceBlock(Ioss::DatabaseIO *io_database, const std::string& my_name, const std::string& face_type, int64_t number_faces) : Ioss::EntityBlock(io_database, my_name, face_type, number_faces) { if (topology()->master_element_name() != face_type && topology()->name() != face_type) { // Maintain original face type on output database if possible. properties.add(Ioss::Property("original_face_type", face_type)); } }
// ---------------------------------------------------------------------- bool RandomProcessPointGenerator:: make_feasible( shawn::Vec& v ) throw() { return topology().value(v); }
void testClosestCells() { // FIXME: for SLHC HcalTopologyMode::Mode mode = HcalTopologyMode::LHC; int maxDepthHB = 2; int maxDepthHE = 3; HcalTopology topology(mode, maxDepthHB, maxDepthHE); HcalHardcodeGeometryLoader l(topology); HcalHardcodeGeometryLoader::ReturnType g = l .load(); // make sure each cel is its own closest cell HcalDetId barrelDet(HcalBarrel, 1, 1, 1); HcalDetId barrelDet2(HcalBarrel, 16, 50, 1); HcalDetId endcapDet1(HcalEndcap, -17, 72, 1); HcalDetId endcapDet2(HcalEndcap, 29, 35, 1); HcalDetId forwardDet1(HcalForward, 30, 71, 1); HcalDetId forwardDet3(HcalForward, -40, 71, 1); testClosestCell( barrelDet , g ); testClosestCell( barrelDet2 , g ); testClosestCell( endcapDet1 , g ); testClosestCell( endcapDet2 , g ); testClosestCell( forwardDet1, g ); testClosestCell( forwardDet3, g ); const std::vector<DetId>& ids=g->getValidDetIds(DetId::Hcal,HcalBarrel); for (std::vector<DetId>::const_iterator i=ids.begin(); i!=ids.end(); i++) { testClosestCell( HcalDetId(*i), g ); } }
//! Configure and start counters static int intel_snb_pcu_begin(struct stats_type *type) { int nr = 0; uint64_t pcu_events[4] = { FREQ_MAX_TEMP_CYCLES, FREQ_MAX_POWER_CYCLES, FREQ_MIN_IO_CYCLES, FREQ_MIN_SNOOP_CYCLES }; int i; for (i = 0; i < nr_cpus; i++) { char cpu[80]; int pkg_id = -1; int core_id = -1; int smt_id = -1; int nr_events; int nr_cores = 0; snprintf(cpu, sizeof(cpu), "%d", i); if (signature(SANDYBRIDGE, cpu, &nr_events)) { topology(cpu, &pkg_id, &core_id, &smt_id, &nr_cores); if (core_id == 0 && smt_id == 0) if (intel_snb_pcu_begin_socket(cpu, pcu_events,4) == 0) nr++; } } if (nr == 0) type->st_enabled = 0; return nr > 0 ? 0 : -1; }
int main( int argc, char** argv) { ann::FwdNet::Topology topology(3); topology[0]=2; topology[1]=2; topology[2]=1; ann::FwdNet artificialNetwork(topology); ann::FwdNet::TrainingDataSet trainingDataSet; ann::FwdNet::InputData inputs(2); ann::FwdNet::TargetData targets(1); inputs[0]=0.0; inputs[1]=0.0; targets[0]=0.0; trainingDataSet.push_back(std::make_pair(inputs, targets)); inputs[0]=1.0; inputs[1]=1.0; targets[0]=0.0; trainingDataSet.push_back(std::make_pair(inputs, targets)); inputs[0]=0.0; inputs[1]=1.0; targets[0]=1.0; trainingDataSet.push_back(std::make_pair(inputs, targets)); inputs[0]=1.0; inputs[1]=0.0; targets[0]=1.0; trainingDataSet.push_back(std::make_pair(inputs, targets)); artificialNetwork.doTraining(trainingDataSet, 0.001); artificialNetwork.saveGraph(std::string("FwdNet.gv")); ann::FwdNet::OutputData outputs; inputs[0]=0; inputs[1]=0; artificialNetwork.processInputs(inputs); artificialNetwork.getOutputs(outputs); inputs[0]=0; inputs[1]=1; artificialNetwork.processInputs(inputs); artificialNetwork.getOutputs(outputs); inputs[0]=1; inputs[1]=0; artificialNetwork.processInputs(inputs); artificialNetwork.getOutputs(outputs); inputs[0]=1; inputs[1]=1; artificialNetwork.processInputs(inputs); artificialNetwork.getOutputs(outputs); //artificialNetwork.dump(); return 0; }
// ---------------------------------------------------------------------- bool LatticePointGenerator:: make_feasible( shawn::Vec& v ) throw() { return topology().value(v); }
cartesian_topology cartesian_communicator::topology() const { cartesian_topology topo(ndims()); std::vector<int> coords; topology(topo, coords); return topo; }
void MainWindow::addCurrentMesh() { mat topology(2, ENS_DIM); try{ for (int i = 0; i < 2; ++i) { for (int j = 0; j < ENS_DIM; ++j) { topology(j, i) = boost::lexical_cast<double>(ui->tableWidget_mesh->item(j, i)->text().toStdString()); } } } catch (std::exception & e) { warning(e.what() + (std::string)" | invalid topology numbers." ); return; } std::string name = ui->lineEdit->text().toStdString(); for (MeshField* mf : meshFields) { if (mf->description.compare(name) == 0){ warning("A mesh with an equal name already exists."); return; } } MeshField* meshField = new MeshField(topology, *ensemble, name); MeshField* currentMesh = meshFields.at(ui->meshComboBox->currentIndex()); try { addMesh(meshField, currentMesh); } catch (std::exception & e) { warning(e.what() + (std::string)" | invalid mesh topology."); return; } }
void DatabaseIO::create_group(EntityType type, const std::string & /*type_name*/, const std::vector<std::string> &group_spec, const SideSet * /*set_type*/) { // Not generalized yet... This only works for T == SideSet if (type != SIDESET) { return; } int64_t entity_count = 0; int64_t df_count = 0; // Create the new set... auto new_set = new SideSet(this, group_spec[0]); get_region()->add(new_set); // Find the member SideSets... for (size_t i = 1; i < group_spec.size(); i++) { SideSet *set = get_region()->get_sideset(group_spec[i]); if (set != nullptr) { SideBlockContainer side_blocks = set->get_side_blocks(); for (auto &sbold : side_blocks) { size_t side_count = sbold->get_property("entity_count").get_int(); auto sbnew = new SideBlock(this, sbold->name(), sbold->topology()->name(), sbold->parent_element_topology()->name(), side_count); int64_t id = sbold->get_property("id").get_int(); sbnew->property_add(Property("set_offset", entity_count)); sbnew->property_add(Property("set_df_offset", df_count)); sbnew->property_add(Property("id", id)); new_set->add(sbnew); size_t old_df_count = sbold->get_property("distribution_factor_count").get_int(); if (old_df_count > 0) { std::string storage = "Real["; storage += Utils::to_string(sbnew->topology()->number_nodes()); storage += "]"; sbnew->field_add( Field("distribution_factors", Field::REAL, storage, Field::MESH, side_count)); } entity_count += side_count; df_count += old_df_count; } } else { IOSS_WARNING << "WARNING: While creating the grouped surface '" << group_spec[0] << "', the surface '" << group_spec[i] << "' does not exist. " << "This surface will skipped and not added to the group.\n\n"; } } }
void testIEEEHumanDataFunction() { Config config; const bool isSoftmax = false; enum Exp { __L1__, __L2_true__, __L2_negg__, __L3__ }; const Exp exp = __L2_negg__; config.setValue("IEEEHumanDataFunction.datasetsSetBias", isSoftmax); config.setValue("training_accuracy", true); config.setValue("testing_accuracy", true); switch (exp) { case 0: config.setValue("exp", std::string("__L1__")); break; case 1: config.setValue("exp", std::string("__L2_true__")); break; case 2: config.setValue("exp", std::string("__L2_negg__")); break; case 3: config.setValue("exp", std::string("__L3__")); } IEEEHumanDataFunction ieeeHumanData; CostFunction* cf = nullptr; if (isSoftmax) cf = new SoftmaxCostFunction(0.1f); else { Vector_t topology(1); topology << 6; // 5 cf = new SupervisedNeuralNetworkCostFunction(topology, 0.1f); } LIBLBFGSOptimizer lbfgs; Driver drv(&config, &ieeeHumanData, cf, &lbfgs); drv.drive(); delete cf; }
Foam::PtrList<Foam::dictionary> Foam::blockMesh::patchDicts() const { const polyPatchList& patchTopologies = topology().boundaryMesh(); PtrList<dictionary> patchDicts(patchTopologies.size()); forAll(patchTopologies, patchI) { OStringStream os; patchTopologies[patchI].write(os); IStringStream is(os.str()); patchDicts.set(patchI, new dictionary(is)); }
void testMNISTSupervisedNeuralNetworkDriver() { Vector_t topology(1); topology << 100; SupervisedNeuralNetworkCostFunction mnistcf(topology, 0.01f); MNISTDataFunction mnistdf; Config config; updateMNISTConfig(config); config.setValue("addBiasTerm", false); LIBLBFGSOptimizer lbfgs; Driver drv(&config, &mnistdf, &mnistcf, &lbfgs); drv.drive(); }
void main() { int n,CALL,j,i; int a[10][10]; printf("\n enter no. of nodes\t"); scanf("%d",&n); printf("\n Enter Matrix\n"); for(i=1;i<=n;i++) for(j=1;j<=n;j++) scanf("%d",&a[i][j]); printf("\n\n\n\n\n"); CALL=topology(a,n); }
//! Collect values of counters static void intel_snb_pcu_collect(struct stats_type *type) { int i; for (i = 0; i < nr_cpus; i++) { char cpu[80]; int pkg_id = -1; int core_id = -1; int smt_id = -1; int nr_cores = 0; snprintf(cpu, sizeof(cpu), "%d", i); topology(cpu, &pkg_id, &core_id, &smt_id, &nr_cores); if (core_id == 0 && smt_id == 0) intel_snb_pcu_collect_socket(type, cpu, pkg_id); } }
void testSupervisedNeuralNetworkCostFunction() { Matrix_t X = Matrix_t::Random(5, 3); Matrix_t Y = Matrix_t::Identity(5, 4); Y(4, 3) = 1.0f; //<< fill in the missing I std::cout << X << std::endl; std::cout << Y << std::endl; Vector_t topology(2); topology << 2, 6; SupervisedNeuralNetworkCostFunction nn(topology); Vector_t theta = nn.configure(X, Y); double error = nn.getNumGrad(theta, X, Y, 20); std::cout << "error: " << error << std::endl; }
Ioss::Property Ioss::SideBlock::get_implicit_property(const std::string& my_name) const { if (my_name == "distribution_factor_count") { if (field_exists("distribution_factors")) { int64_t nnodes = topology()->number_nodes(); int64_t nside = get_property("entity_count").get_int(); return Ioss::Property(my_name, nnodes*nside); } else { return Ioss::Property(my_name, 0); } } else if (my_name == "parent_topology_type") return Ioss::Property(my_name, parent_element_topology()->name()); else return Ioss::EntityBlock::get_implicit_property(my_name); }
int main_function(int argc, char **argv) { const unsigned POP_SIZE = 6, VEC_SIZE = 2, NEIGHBORHOOD_SIZE=2; // the population: eoPop<Particle> pop; // Evaluation eoEvalFuncPtr<Particle, double, const Particle& > eval( f ); // position + velocity + best init eoUniformGenerator < double >uGen (-3, 3); eoInitFixedLength < Particle > random (VEC_SIZE, uGen); eoUniformGenerator < double >sGen (-2, 2); eoVelocityInitFixedLength < Particle > veloRandom (VEC_SIZE, sGen); eoFirstIsBestInit < Particle > localInit; pop.append (POP_SIZE, random); // topology eoLinearTopology<Particle> topology(NEIGHBORHOOD_SIZE); eoInitializer <Particle> init(eval,veloRandom,localInit,topology,pop); init(); // velocity eoExtendedVelocity <Particle> velocity (topology,1,1,1,1); // the test itself for (unsigned int i = 0; i < POP_SIZE; i++) { std::cout << " Initial particle n°" << i << " velocity: " << std::endl; for (unsigned int j = 0; j < VEC_SIZE; j++) std::cout << " v" << j << "=" << pop[i].velocities[j] << std::endl; } for (unsigned int i = 0; i < POP_SIZE; i++) velocity (pop[i],i); for (unsigned int i = 0; i < POP_SIZE; i++) { std::cout << " Final particle n°" << i << " velocity: " << std::endl; for (unsigned int j = 0; j < VEC_SIZE; j++) std::cout << " v" << j << "=" << pop[i].velocities[j] << std::endl; } return EXIT_SUCCESS; }
void testMNISTBinaryDigitsSupervisedNeuralNetworkCostFunctionDriver() { Vector_t topology(1); topology << 5; SupervisedNeuralNetworkCostFunction mnistcf(topology); //SoftmaxCostFunction mnistcf; //LogisticCostFunction mnistcf; MNISTDataBinaryDigitsFunction mnistdf(true); Config config; updateMNISTConfig(config); config.setValue("addBiasTerm", false); config.setValue("training_accuracy", true); config.setValue("testing_accuracy", true); LIBLBFGSOptimizer lbfgs; Driver drv(&config, &mnistdf, &mnistcf, &lbfgs); drv.drive(); }
int main() { std::cout << "Test current Hcal geometry" << std::endl; HcalTopologyMode::Mode mode = HcalTopologyMode::LHC; int maxDepthHB = 2; int maxDepthHE = 3; HcalTopology topology( mode, maxDepthHB, maxDepthHE ); testValidDetIds( topology, DetId::Hcal, HcalBarrel, " BARREL " ); testValidDetIds( topology, DetId::Hcal, HcalEndcap, " ENDCAP " ); testValidDetIds( topology, DetId::Hcal, HcalOuter, " OUTER " ); testValidDetIds( topology, DetId::Hcal, HcalForward, " FORWARD " ); testTriggerGeometry( topology ); testClosestCells( topology ); std::cout << "Test SLHC Hcal geometry" << std::endl; mode = HcalTopologyMode::SLHC; maxDepthHB = 7; maxDepthHE = 7; HcalTopology stopology( mode, maxDepthHB, maxDepthHE ); testValidDetIds( stopology, DetId::Hcal, HcalBarrel, " SLHC BARREL " ); testValidDetIds( stopology, DetId::Hcal, HcalEndcap, " SLHC ENDCAP " ); testValidDetIds( stopology, DetId::Hcal, HcalOuter, " SLHC OUTER " ); testValidDetIds( stopology, DetId::Hcal, HcalForward, " SLHC FORWARD " ); std::cout << "Test SLHC Hcal Flexi geometry" << std::endl; std::vector<int> dins; testFlexiValidDetIds( stopology, DetId::Hcal, HcalBarrel, " SLHC BARREL ", dins ); testFlexiValidDetIds( stopology, DetId::Hcal, HcalEndcap, " SLHC ENDCAP ", dins ); testFlexiValidDetIds( stopology, DetId::Hcal, HcalOuter, " SLHC OUTER ", dins ); testFlexiValidDetIds( stopology, DetId::Hcal, HcalForward, " SLHC FORWARD ", dins ); testTriggerGeometry( stopology ); testClosestCells( stopology ); return 0; }
void CField::create_data_storage() { cf_assert( m_var_types.size()!=0 ); cf_assert( is_not_null(m_topology->follow()) ); // Check if there are coordinates in this field, and add to map m_coords = find_parent_component<CMesh>(topology()).nodes().coordinates().as_ptr<CTable<Real> >(); Uint row_size(0); boost_foreach(const VarType var_size, m_var_types) row_size += Uint(var_size); m_data->set_row_size(row_size); switch (m_basis) { case Basis::POINT_BASED: { m_used_nodes = CElements::used_nodes(topology()).as_ptr<CList<Uint> >(); m_data->resize(m_used_nodes->size()); break; } case Basis::ELEMENT_BASED: { Uint data_size = 0; boost_foreach(CEntities& field_elements, find_components_recursively<CEntities>(topology())) { if (field_elements.exists_space(m_space_name) == false) throw ValueNotFound(FromHere(),"space \""+m_space_name+"\" does not exist in "+field_elements.uri().path()); m_elements_start_idx[field_elements.as_ptr<CEntities>()] = data_size; CFieldView field_view("tmp_field_view"); data_size = field_view.initialize(*this,field_elements.as_ptr<CEntities>()); } m_data->resize(data_size); break; } case Basis::CELL_BASED: { Uint data_size = 0; boost_foreach(CEntities& field_elements, find_components_recursively<CCells>(topology())) { //CFinfo << name() << ": creating cellbased field storage in " << field_elements.uri().path() << CFendl; if (field_elements.exists_space(m_space_name) == false) throw ValueNotFound(FromHere(),"space \""+m_space_name+"\" does not exist in "+field_elements.uri().path()); m_elements_start_idx[field_elements.as_ptr<CEntities>()] = data_size; CFieldView field_view("tmp_field_view"); data_size = field_view.initialize(*this,field_elements.as_ptr<CEntities>()); } m_data->resize(data_size); break; } case Basis::FACE_BASED: { Uint data_size = 0; boost_foreach(CEntities& field_elements, find_components_recursively_with_tag<CEntities>(topology(),Mesh::Tags::face_entity())) { if (field_elements.exists_space(m_space_name) == false) throw ValueNotFound(FromHere(),"space \""+m_space_name+"\" does not exist in "+field_elements.uri().path()); m_elements_start_idx[field_elements.as_ptr<CEntities>()] = data_size; CFieldView field_view("tmp_field_view"); data_size = field_view.initialize(*this,field_elements.as_ptr<CEntities>()); } m_data->resize(data_size); break; } default: throw NotSupported(FromHere() , "Basis can only be ELEMENT_BASED or NODE_BASED"); break; } }
int main() { // FIXME: for SLHC HcalTopologyMode::Mode mode = HcalTopologyMode::LHC; int maxDepthHB = 2; int maxDepthHE = 3; HcalTopology topology(mode, maxDepthHB, maxDepthHE); HcalHardcodeGeometryLoader l(topology); HcalHardcodeGeometryLoader::ReturnType b=l.load(DetId::Hcal,HcalBarrel); HcalHardcodeGeometryLoader::ReturnType e=l.load(DetId::Hcal,HcalEndcap); HcalHardcodeGeometryLoader::ReturnType o=l.load(DetId::Hcal,HcalOuter); HcalHardcodeGeometryLoader::ReturnType f=l.load(DetId::Hcal,HcalForward); std::cout << std::endl << " BARREL : " << std::endl; const std::vector<DetId>& idshb=b->getValidDetIds(DetId::Hcal,HcalBarrel); for (std::vector<DetId>::const_iterator i=idshb.begin(); i!=idshb.end(); i++) { HcalDetId hid=(*i); if (hid.iphi()!=1) continue; const CaloCellGeometry* geom=b->getGeometry(hid); const CaloCellGeometry::CornersVec& corners=geom->getCorners(); std::cout << hid << std::endl; for (CaloCellGeometry::CornersVec::const_iterator j=corners.begin(); j!=corners.end(); j++) { std::cout << " " << *j << std::endl; } } std::cout << std::endl << " FORWARD : " << std::endl; const std::vector<DetId>& idshf=f->getValidDetIds(DetId::Hcal,HcalForward); for (std::vector<DetId>::const_iterator i=idshf.begin(); i!=idshf.end(); i++) { HcalDetId hid=(*i); // if (hid.iphi()!=1 && hid.iphi()!=2 && hid.iphi()!=3) continue; std::cout << hid << std::endl; const CaloCellGeometry* geom=f->getGeometry(hid); const CaloCellGeometry::CornersVec& corners=geom->getCorners(); for (CaloCellGeometry::CornersVec::const_iterator j=corners.begin(); j!=corners.end(); j++) { std::cout << " " << *j << std::endl; } } std::cout << std::endl << " ENDCAP : " << std::endl; const std::vector<DetId>& idshe=e->getValidDetIds(DetId::Hcal,HcalEndcap); for (std::vector<DetId>::const_iterator i=idshe.begin(); i!=idshe.end(); i++) { HcalDetId hid=(*i); if (hid.iphi()!=1 && hid.iphi()!=2 && hid.iphi()!=3) continue; std::cout << hid << std::endl; const CaloCellGeometry* geom=e->getGeometry(hid); const CaloCellGeometry::CornersVec& corners=geom->getCorners(); for (CaloCellGeometry::CornersVec::const_iterator j=corners.begin(); j!=corners.end(); j++) { std::cout << " " << *j << std::endl; } } std::cout << std::endl << " OUTER : " << std::endl; const std::vector<DetId>& idsho=o->getValidDetIds(DetId::Hcal,HcalOuter); for (std::vector<DetId>::const_iterator i=idsho.begin(); i!=idsho.end(); i++) { HcalDetId hid=(*i); if (hid.iphi()!=1 && hid.iphi()!=2 && hid.iphi()!=3) continue; std::cout << hid << std::endl; const CaloCellGeometry* geom=o->getGeometry(hid); const CaloCellGeometry::CornersVec& corners=geom->getCorners(); for (CaloCellGeometry::CornersVec::const_iterator j=corners.begin(); j!=corners.end(); j++) { std::cout << " " << *j << std::endl; } } testTriggerGeometry(); testClosestCells(); return 0; }
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); for (int i = 0; i < nEvents; ++i) { ui->eventComboBox->addItem(getEventName(i)); } ui->tableWidget->setColumnCount(2); QStringList list; list << "Argument" << "Value"; ui->tableWidget->setHorizontalHeaderLabels(list); QStringList list2; list2 << "X" << "Y"; #if ENS_DIM == 3 list2 << "Z"; #else ui->tableWidget_mesh->setRowCount(2); #endif ui->tableWidget_mesh->setVerticalHeaderLabels(list2); QStringList list3; list3 << "Start" << "End"; ui->tableWidget_mesh->setHorizontalHeaderLabels(list3); vec masses = ones(1); ensemble = new Ensemble(masses); mat topology(ENS_DIM, 2); topology << 0 << ENS_NX << endr << 0 << ENS_NY; #if ENS_DIM == 3 topology << 0 << ENS_NZ << endr; #endif mainMesh = new MainMesh(topology, *ensemble); for (int i = 0; i < 2; ++i) { for (int j = 0; j < ENS_DIM; ++j) { ui->tableWidget_mesh->setItem(j, i, new QTableWidgetItem); } } addMesh(mainMesh); epsTable << 1 << 1 << endr << 1 << 1; sigmaTable << 1 << 1 << endr << 1 << 1; forceAddEvent(MDSOLVER); forceAddEvent(VELOCITYVERLET1); forceAddEvent(PERIODIC); forceAddEvent(LENNARDJONESFORCE); forceAddEvent(VELOCITYVERLET2); params.dt = 1./60; forceAddEvent(STALL); params.dt = 0.005; ui->eventComboBox->setCurrentIndex(0); running = false; }
void MainWindow::fillMeshTopology(int k) { const mat & topology = meshFields.at(k)->topology; for (int i = 0; i < 2; ++i) { for (int j = 0; j < ENS_DIM; ++j) { ui->tableWidget_mesh->item(j, i)->setText(QString::fromStdString(boost::lexical_cast<std::string>(topology(j, i)))); } } }
xdm::RefPtr< xdmGrid::UniformGrid > build2DGrid() { xdm::RefPtr< xdmGrid::UniformGrid > grid( new xdmGrid::UniformGrid ); grid->setName( "FunctionEvaluationGrid" ); // Time { grid->setTime( xdm::makeRefPtr( new xdmGrid::Time( 0.0 ) ) ); } // Topology { xdm::RefPtr< xdmGrid::RectilinearMesh > topology( new xdmGrid::RectilinearMesh ); topology->setShape( xdm::makeShape( kMeshSize[0]-1, kMeshSize[1]-1 ) ); grid->setTopology( topology ); } // Geometry xdm::RefPtr< xdm::VectorStructuredArray< float > > meshValues[2]; { xdm::RefPtr< xdmGrid::TensorProductGeometry > geometry( new xdmGrid::TensorProductGeometry( 2 ) ); for ( int i = 0; i < 2; i++ ) { // Build the Geometry data as single precision to force an up conversion // upon read. xdm::RefPtr< xdm::UniformDataItem > dataItem( new xdm::UniformDataItem ); dataItem->setDataType( xdm::primitiveType::kFloat ); dataItem->setDataspace( xdm::makeShape( kMeshSize[i] ) ); meshValues[i] = xdm::makeRefPtr( new xdm::VectorStructuredArray< float >( kMeshSize[i] ) ); for ( int j = 0; j < kMeshSize[i]; j++ ) { (*meshValues[i])[j] = kRange[i][0] + j * ( (kRange[i][1] - kRange[i][0]) / kMeshSize[i] ); } dataItem->setData( xdm::makeRefPtr( new xdm::ArrayAdapter( meshValues[i] ) ) ); geometry->setCoordinateValues( i, dataItem ); } grid->setGeometry( geometry ); } // Give it an attribute. { xdm::RefPtr< xdmGrid::Attribute > attribute( new xdmGrid::Attribute( xdmGrid::Attribute::kScalar, xdmGrid::Attribute::kNode ) ); attribute->setName( "attr" ); xdm::RefPtr< xdm::VectorStructuredArray< double > > attrValues( new xdm::VectorStructuredArray< double >( kMeshSize[1] * kMeshSize[0] ) ); for ( int j = 0; j < kMeshSize[1]; j++ ) { for ( int i = 0; i < kMeshSize[0]; i++ ) { double xpoint = (*meshValues[0])[i]; double ypoint = (*meshValues[1])[j]; (*attrValues)[j*kMeshSize[0] + i] = function( xpoint, ypoint ); } } xdm::RefPtr< xdm::UniformDataItem > dataItem( new xdm::UniformDataItem( xdm::primitiveType::kDouble, xdm::makeShape( kMeshSize[1], kMeshSize[0] ) ) ); dataItem->setData( xdm::makeRefPtr( new xdm::ArrayAdapter( attrValues, true ) ) ); attribute->setDataItem( dataItem ); grid->addAttribute( attribute ); } return grid; }
int main(int ac, char* av[]) { // // Create a command line processor and parse command line options // Teuchos::CommandLineProcessor command_line_processor; command_line_processor.setDocString( "Test of element separation through nodal insertion.\n" "Remove and replace all nodes in elements.\n"); std::string input_file = "input.e"; command_line_processor.setOption("input", &input_file, "Input File Name"); std::string output_file = "output.e"; command_line_processor.setOption("output", &output_file, "Output File Name"); // Throw a warning and not error for unrecognized options command_line_processor.recogniseAllOptions(true); // Don't throw exceptions for errors command_line_processor.throwExceptions(false); // Parse command line Teuchos::CommandLineProcessor::EParseCommandLineReturn parse_return = command_line_processor.parse(ac, av); if (parse_return == Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED) { return 0; } if (parse_return != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL) { return 1; } // // Read the mesh // // Copied from Partition.cc Teuchos::GlobalMPISession mpiSession(&ac, &av); LCM::Topology topology(input_file, output_file); stk::mesh::BulkData& bulkData = topology.get_bulk_data(); // Node rank should be 0 and element rank should be equal to the dimension of // the system (e.g. 2 for 2D meshes and 3 for 3D meshes) // std::cout << "Node Rank: "<< nodeRank << ", Element Rank: " << // getCellRank() << "\n"; // Print element connectivity before the mesh topology is modified std::cout << "*************************\n" << "Before element separation\n" << "*************************\n"; // Start the mesh update process // Will fully separate the elements in the mesh by replacing element nodes // Get a vector containing the element set of the mesh. std::vector<stk::mesh::Entity> element_lst; stk::mesh::get_entities(bulkData, stk::topology::ELEMENT_RANK, element_lst); // Modifies mesh for graph algorithm // Function must be called each time before there are changes to the mesh topology.removeNodeRelations(); // Check for failure criterion topology.setEntitiesOpen(); std::string gviz_output = LCM::parallelize_string("output") + ".dot"; topology.outputToGraphviz(gviz_output); // test the functions of the class bulkData.modification_begin(); // begin mesh fracture std::cout << "begin mesh fracture\n"; topology.splitOpenFaces(); // std::string gviz_output = "output.dot"; // topology.output_to_graphviz(gviz_output,entity_open); // Recreates connectivity in stk mesh expected by Albany_STKDiscretization // Must be called each time at conclusion of mesh modification topology.restoreElementToNodeConnectivity(); // End mesh update bulkData.modification_end(); std::cout << "*************************\n" << "After element separation\n" << "*************************\n"; // Need to update the mesh to reflect changes in duplicate_entity routine. // Redefine connectivity and coordinate arrays with updated values. // Mesh must only have relations between elements and nodes. Teuchos::RCP<Albany::AbstractDiscretization> discretization_ptr = topology.get_discretization(); Albany::STKDiscretization& stk_discretization = static_cast<Albany::STKDiscretization&>(*discretization_ptr); Teuchos::ArrayRCP<double> coordinates = stk_discretization.getCoordinates(); // Separate the elements of the mesh to illustrate the // disconnected nature of the final mesh // Create a vector to hold displacement values for nodes Teuchos::RCP<const Tpetra_Map> dof_mapT = stk_discretization.getMapT(); Teuchos::RCP<Tpetra_Vector> displacementT = Teuchos::rcp(new Tpetra_Vector(dof_mapT)); Teuchos::ArrayRCP<ST> displacementT_nonconstView = displacementT->get1dViewNonConst(); // Add displacement to nodes stk::mesh::get_entities(bulkData, stk::topology::ELEMENT_RANK, element_lst); // displacement scale factor double alpha = 0.5; for (int i = 0; i < element_lst.size(); ++i) { std::vector<double> centroid(3); std::vector<double> disp(3); stk::mesh::Entity const* relations = bulkData.begin_nodes(element_lst[i]); int const num_relations = bulkData.num_nodes(element_lst[i]); // Get centroid of the element for (int j = 0; j < num_relations; ++j) { stk::mesh::Entity node = relations[j]; int id = static_cast<int>(bulkData.identifier(node)); centroid[0] += coordinates[id * 3 - 3]; centroid[1] += coordinates[id * 3 - 2]; centroid[2] += coordinates[id * 3 - 1]; } centroid[0] /= num_relations; centroid[1] /= num_relations; centroid[2] /= num_relations; // Determine displacement for (int j = 0; j < 3; ++j) { disp[j] = alpha * centroid[j]; } // Add displacement to nodes for (int j = 0; j < num_relations; ++j) { stk::mesh::Entity node = relations[j]; int id = static_cast<int>(bulkData.identifier(node)); displacementT_nonconstView[id * 3 - 3] += disp[0]; displacementT_nonconstView[id * 3 - 2] += disp[1]; displacementT_nonconstView[id * 3 - 1] += disp[2]; } } stk_discretization.setResidualFieldT(*displacementT); Teuchos::RCP<Tpetra_Vector> solution_fieldT = stk_discretization.getSolutionFieldT(); // Write final mesh to exodus file // second arg to output is (pseudo)time // stk_discretization.outputToExodus(*solution_field, 1.0); stk_discretization.writeSolutionT(*solution_fieldT, 1.0); return 0; }
int main() { const unsigned int VEC_SIZE = 2; const unsigned int POP_SIZE = 20; const unsigned int NEIGHBORHOOD_SIZE= 5; unsigned i; // the population: eoPop<Particle> pop; // Evaluation eoEvalFuncPtr<Particle, double, const Particle& > eval( real_value ); // position init eoUniformGenerator < double >uGen (-3, 3); eoInitFixedLength < Particle > random (VEC_SIZE, uGen); // velocity init eoUniformGenerator < double >sGen (-2, 2); eoVelocityInitFixedLength < Particle > veloRandom (VEC_SIZE, sGen); // local best init eoFirstIsBestInit < Particle > localInit; // perform position initialization pop.append (POP_SIZE, random); // topology eoLinearTopology<Particle> topology(NEIGHBORHOOD_SIZE); // the full initializer eoInitializer <Particle> init(eval,veloRandom,localInit,topology,pop); init(); // bounds eoRealVectorBounds bnds(VEC_SIZE,-1.5,1.5); // velocity eoStandardVelocity <Particle> velocity (topology,1,1.6,2,bnds); // flight eoStandardFlight <Particle> flight; // Terminators eoGenContinue <Particle> genCont1 (50); eoGenContinue <Particle> genCont2 (50); // PS flight eoEasyPSO<Particle> pso1(genCont1, eval, velocity, flight); eoEasyPSO<Particle> pso2(init,genCont2, eval, velocity, flight); // flight try { pso1(pop); std::cout << "FINAL POPULATION AFTER PSO n°1:" << std::endl; for (i = 0; i < pop.size(); ++i) std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl; pso2(pop); std::cout << "FINAL POPULATION AFTER PSO n°2:" << std::endl; for (i = 0; i < pop.size(); ++i) std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl; } catch (std::exception& e) { std::cout << "exception: " << e.what() << std::endl;; exit(EXIT_FAILURE); } return 0; }
int main (int __argc, char *__argv[]) { peo :: init( __argc, __argv ); if (getNodeRank()==1) std::cout<<"\n\nTest : PSO Global Best\n\n"; rng.reseed (10); RingTopology topologyMig; eoGenContinue < Indi > genContPara (10); eoCombinedContinue <Indi> continuatorPara (genContPara); eoCheckPoint<Indi> checkpoint(continuatorPara); peoEvalFunc<Indi, double, const Indi& > plainEval(f); peoPopEval< Indi > eval(plainEval); eoUniformGenerator < double >uGen (0, 1.); eoInitFixedLength < Indi > random (2, uGen); eoUniformGenerator < double >sGen (-1., 1.); eoVelocityInitFixedLength < Indi > veloRandom (2, sGen); eoFirstIsBestInit < Indi > localInit; eoRealVectorBounds bndsFlight(2,0,1.); eoStandardFlight < Indi > flight(bndsFlight); eoPop < Indi > pop; pop.append (10, random); eoLinearTopology<Indi> topology(2); eoRealVectorBounds bnds(2,-1.,1.); eoStandardVelocity < Indi > velocity (topology,1,0.5,2.,bnds); eoInitializer <Indi> init(eval,veloRandom,localInit,topology,pop); eoPeriodicContinue< Indi > mig_cont( 2 ); peoPSOSelect<Indi> mig_selec(topology); peoGlobalBestVelocity<Indi> mig_replac (2.,velocity); eoContinuator<Indi> cont(mig_cont, pop); eoSelector <Indi, eoPop<Indi> > mig_select (mig_selec,1,pop); eoReplace <Indi, eoPop<Indi> > mig_replace (mig_replac,pop); eoGenContinue < Indi > genContPara2 (10); eoCombinedContinue <Indi> continuatorPara2 (genContPara2); eoCheckPoint<Indi> checkpoint2(continuatorPara2); peoEvalFunc<Indi, double, const Indi& > plainEval2(f); peoPopEval< Indi > eval2(plainEval2); eoUniformGenerator < double >uGen2 (0, 1.); eoInitFixedLength < Indi > random2 (2, uGen2); eoUniformGenerator < double >sGen2 (-1., 1.); eoVelocityInitFixedLength < Indi > veloRandom2 (2, sGen2); eoFirstIsBestInit < Indi > localInit2; eoRealVectorBounds bndsFlight2(2,0,1.); eoStandardFlight < Indi > flight2(bndsFlight2); eoPop < Indi > pop2; pop2.append (10, random2); eoLinearTopology<Indi> topology2(2); eoRealVectorBounds bnds2(2,-1.,1.); eoStandardVelocity < Indi > velocity2 (topology2,1,0.5,2.,bnds2); eoInitializer <Indi> init2(eval2,veloRandom2,localInit2,topology2,pop2); eoPeriodicContinue< Indi > mig_cont2( 2 ); peoPSOSelect<Indi> mig_selec2(topology2); peoGlobalBestVelocity<Indi> mig_replac2 (2.,velocity2); eoContinuator<Indi> cont2(mig_cont2,pop2); eoSelector <Indi, eoPop<Indi> > mig_select2 (mig_selec2,1,pop2); eoReplace <Indi, eoPop<Indi> > mig_replace2 (mig_replac2,pop2); peoAsyncIslandMig< eoPop<Indi>, eoPop<Indi> > mig(cont,mig_select, mig_replace, topologyMig); checkpoint.add( mig ); peoAsyncIslandMig< eoPop<Indi>, eoPop<Indi> > mig2(cont2,mig_select2, mig_replace2, topologyMig); checkpoint2.add( mig2 ); eoSyncEasyPSO <Indi> psa(init,checkpoint,eval, velocity, flight); peoWrapper parallelPSO( psa, pop); eval.setOwner(parallelPSO); mig.setOwner(parallelPSO); eoSyncEasyPSO <Indi> psa2(init2,checkpoint2,eval2, velocity2, flight2); peoWrapper parallelPSO2( psa2, pop2); eval2.setOwner(parallelPSO2); mig2.setOwner(parallelPSO2); peo :: run(); peo :: finalize(); if (getNodeRank()==1) { pop.sort(); pop2.sort(); std::cout << "Final population :\n" << pop << std::endl; std::cout << "Final population :\n" << pop2 << std::endl; } }