void updateVerletList(const string &verletStringId, Particles & particles, Grid & grid, double radius) { double radiusSquared = radius*radius; int verletId = particles.getVerletId(verletStringId); const unordered_map<int, GridPoint*> &gridpoints = grid.gridpoints(); const mat & R = particles.r(); const vector<int> &mygridPoints = grid.myGridPoints(); particles.clearVerletList(verletId); #ifdef USE_OPENMP #pragma omp parallel for #endif for(int i=0; i<mygridPoints.size(); i++) { double dx, dy, dz; int gridId = mygridPoints.at(i); const GridPoint & gridPoint = *gridpoints.at(gridId); for(const pair<int, int> & idCol_i:gridPoint.particles()) { int id_i = idCol_i.first; vector<int> verletList; const vec & r_i = R.col(idCol_i.second); for(const pair<int, int> & idCol_j:gridPoint.particles()) { int id_j = idCol_j.first; if(id_i == id_j) continue; const vec & r_j = R.col(idCol_j.second); dx = r_i(0) - r_j(0); dy = r_i(1) - r_j(1); dz = r_i(2) - r_j(2); double drSquared = dx*dx + dy*dy + dz*dz; if(drSquared < radiusSquared) { verletList.push_back(id_j); } } // Neighbouring cells const vector<GridPoint*> & neighbours = gridPoint.neighbours(); for(const GridPoint *neighbour:neighbours) { for(const pair<int, int> & idCol_j:neighbour->particles()) { const vec & r_j = R.col(idCol_j.second); dx = r_i(0) - r_j(0); dy = r_i(1) - r_j(1); dz = r_i(2) - r_j(2); double drSquared = dx*dx + dy*dy + dz*dz; if(drSquared < radiusSquared) { verletList.push_back(idCol_j.first); } } } #ifdef USE_OPENMP #pragma omp critical { particles.setVerletList(id_i, verletList, verletId); } #else particles.setVerletList(id_i, verletList, verletId); #endif } } }
void TestGemm ( Orientation orientA, Orientation orientB, Int m, Int n, Int k, T alpha, T beta, const Grid& g, bool print, bool correctness ) { double startTime, runTime, realGFlops, gFlops; DistMatrix<T> A(g), B(g), COrig(g), C(g); if( orientA == NORMAL ) Uniform( A, m, k ); else Uniform( A, k, m ); if( orientB == NORMAL ) Uniform( B, k, n ); else Uniform( B, n, k ); Uniform( COrig, m, n ); if( print ) { Print( A, "A" ); Print( B, "B" ); Print( COrig, "COrig" ); } // Test the variant of Gemm that keeps A stationary C = COrig; if( g.Rank() == 0 ) cout << "Stationary A Algorithm:" << endl; mpi::Barrier( g.Comm() ); startTime = mpi::Time(); Gemm( orientA, orientB, alpha, A, B, beta, C, GEMM_SUMMA_A ); mpi::Barrier( g.Comm() ); runTime = mpi::Time() - startTime; realGFlops = 2.*double(m)*double(n)*double(k)/(1.e9*runTime); gFlops = ( IsComplex<T>::val ? 4*realGFlops : realGFlops ); if( g.Rank() == 0 ) { cout << " Time = " << runTime << " seconds. GFlops = " << gFlops << endl; } if( print ) { ostringstream msg; msg << "C := " << alpha << " A B + " << beta << " C"; Print( C, msg.str() ); } if( correctness ) TestCorrectness( orientA, orientB, alpha, A, B, beta, COrig, C, print ); // Test the variant of Gemm that keeps B stationary C = COrig; if( g.Rank() == 0 ) cout << "Stationary B Algorithm:" << endl; mpi::Barrier( g.Comm() ); startTime = mpi::Time(); Gemm( orientA, orientB, alpha, A, B, beta, C, GEMM_SUMMA_B ); mpi::Barrier( g.Comm() ); runTime = mpi::Time() - startTime; realGFlops = 2.*double(m)*double(n)*double(k)/(1.e9*runTime); gFlops = ( IsComplex<T>::val ? 4*realGFlops : realGFlops ); if( g.Rank() == 0 ) { cout << " Time = " << runTime << " seconds. GFlops = " << gFlops << endl; } if( print ) { ostringstream msg; msg << "C := " << alpha << " A B + " << beta << " C"; Print( C, msg.str() ); } if( correctness ) TestCorrectness( orientA, orientB, alpha, A, B, beta, COrig, C, print ); // Test the variant of Gemm that keeps C stationary C = COrig; if( g.Rank() == 0 ) cout << "Stationary C Algorithm:" << endl; mpi::Barrier( g.Comm() ); startTime = mpi::Time(); Gemm( orientA, orientB, alpha, A, B, beta, C, GEMM_SUMMA_C ); mpi::Barrier( g.Comm() ); runTime = mpi::Time() - startTime; realGFlops = 2.*double(m)*double(n)*double(k)/(1.e9*runTime); gFlops = ( IsComplex<T>::val ? 4*realGFlops : realGFlops ); if( g.Rank() == 0 ) { cout << "DONE. " << endl << " Time = " << runTime << " seconds. GFlops = " << gFlops << endl; } if( print ) { ostringstream msg; msg << "C := " << alpha << " A B + " << beta << " C"; Print( C, msg.str() ); } if( correctness ) TestCorrectness( orientA, orientB, alpha, A, B, beta, COrig, C, print ); if( orientA == NORMAL && orientB == NORMAL ) { // Test the variant of Gemm for panel-panel dot products if( g.Rank() == 0 ) cout << "Dot Product Algorithm:" << endl; C = COrig; mpi::Barrier( g.Comm() ); startTime = mpi::Time(); Gemm( NORMAL, NORMAL, alpha, A, B, beta, C, GEMM_SUMMA_DOT ); mpi::Barrier( g.Comm() ); runTime = mpi::Time() - startTime; realGFlops = 2.*double(m)*double(n)*double(k)/(1.e9*runTime); gFlops = ( IsComplex<T>::val ? 4*realGFlops : realGFlops ); if( g.Rank() == 0 ) { cout << "DONE. " << endl << " Time = " << runTime << " seconds. GFlops = " << gFlops << endl; } if( print ) { ostringstream msg; msg << "C := " << alpha << " A B + " << beta << " C"; Print( C, msg.str() ); } if( correctness ) TestCorrectness ( orientA, orientB, alpha, A, B, beta, COrig, C, print ); } }
void CCmpPathfinder::TerrainUpdateHelper(bool expandPassability) { PROFILE3("TerrainUpdateHelper"); CmpPtr<ICmpObstructionManager> cmpObstructionManager(GetSimContext(), SYSTEM_ENTITY); CmpPtr<ICmpWaterManager> cmpWaterManager(GetSimContext(), SYSTEM_ENTITY); CmpPtr<ICmpTerrain> cmpTerrain(GetSimContext(), SYSTEM_ENTITY); CTerrain& terrain = GetSimContext().GetTerrain(); if (!cmpTerrain || !cmpObstructionManager) return; u16 terrainSize = cmpTerrain->GetTilesPerSide(); if (terrainSize == 0) return; if (!m_TerrainOnlyGrid || m_MapSize != terrainSize) { m_MapSize = terrainSize; SAFE_DELETE(m_TerrainOnlyGrid); m_TerrainOnlyGrid = new Grid<NavcellData>(m_MapSize * Pathfinding::NAVCELLS_PER_TILE, m_MapSize * Pathfinding::NAVCELLS_PER_TILE); } Grid<u16> shoreGrid = ComputeShoreGrid(); // Compute initial terrain-dependent passability for (int j = 0; j < m_MapSize * Pathfinding::NAVCELLS_PER_TILE; ++j) { for (int i = 0; i < m_MapSize * Pathfinding::NAVCELLS_PER_TILE; ++i) { // World-space coordinates for this navcell fixed x, z; Pathfinding::NavcellCenter(i, j, x, z); // Terrain-tile coordinates for this navcell int itile = i / Pathfinding::NAVCELLS_PER_TILE; int jtile = j / Pathfinding::NAVCELLS_PER_TILE; // Gather all the data potentially needed to determine passability: fixed height = terrain.GetExactGroundLevelFixed(x, z); fixed water; if (cmpWaterManager) water = cmpWaterManager->GetWaterLevel(x, z); fixed depth = water - height; // Exact slopes give kind of weird output, so just use rough tile-based slopes fixed slope = terrain.GetSlopeFixed(itile, jtile); // Get world-space coordinates from shoreGrid (which uses terrain tiles) fixed shoredist = fixed::FromInt(shoreGrid.get(itile, jtile)).MultiplyClamp(TERRAIN_TILE_SIZE); // Compute the passability for every class for this cell NavcellData t = 0; for (PathfinderPassability& passability : m_PassClasses) if (!passability.IsPassable(depth, slope, shoredist)) t |= passability.m_Mask; m_TerrainOnlyGrid->set(i, j, t); } } // Compute off-world passability // WARNING: CCmpRangeManager::LosIsOffWorld needs to be kept in sync with this const int edgeSize = 3 * Pathfinding::NAVCELLS_PER_TILE; // number of tiles around the edge that will be off-world NavcellData edgeMask = 0; for (PathfinderPassability& passability : m_PassClasses) edgeMask |= passability.m_Mask; int w = m_TerrainOnlyGrid->m_W; int h = m_TerrainOnlyGrid->m_H; if (cmpObstructionManager->GetPassabilityCircular()) { for (int j = 0; j < h; ++j) { for (int i = 0; i < w; ++i) { // Based on CCmpRangeManager::LosIsOffWorld // but tweaked since it's tile-based instead. // (We double all the values so we can handle half-tile coordinates.) // This needs to be slightly tighter than the LOS circle, // else units might get themselves lost in the SoD around the edge. int dist2 = (i*2 + 1 - w)*(i*2 + 1 - w) + (j*2 + 1 - h)*(j*2 + 1 - h); if (dist2 >= (w - 2*edgeSize) * (h - 2*edgeSize)) m_TerrainOnlyGrid->set(i, j, m_TerrainOnlyGrid->get(i, j) | edgeMask); } } } else { for (u16 j = 0; j < h; ++j) for (u16 i = 0; i < edgeSize; ++i) m_TerrainOnlyGrid->set(i, j, m_TerrainOnlyGrid->get(i, j) | edgeMask); for (u16 j = 0; j < h; ++j) for (u16 i = w-edgeSize+1; i < w; ++i) m_TerrainOnlyGrid->set(i, j, m_TerrainOnlyGrid->get(i, j) | edgeMask); for (u16 j = 0; j < edgeSize; ++j) for (u16 i = edgeSize; i < w-edgeSize+1; ++i) m_TerrainOnlyGrid->set(i, j, m_TerrainOnlyGrid->get(i, j) | edgeMask); for (u16 j = h-edgeSize+1; j < h; ++j) for (u16 i = edgeSize; i < w-edgeSize+1; ++i) m_TerrainOnlyGrid->set(i, j, m_TerrainOnlyGrid->get(i, j) | edgeMask); } if (!expandPassability) return; // Expand the impassability grid, for any class with non-zero clearance, // so that we can stop units getting too close to impassable navcells. // Note: It's not possible to perform this expansion once for all passabilities // with the same clearance, because the impassable cells are not necessarily the // same for all these passabilities. for (PathfinderPassability& passability : m_PassClasses) { if (passability.m_Clearance == fixed::Zero()) continue; int clearance = (passability.m_Clearance / Pathfinding::NAVCELL_SIZE).ToInt_RoundToInfinity(); ExpandImpassableCells(*m_TerrainOnlyGrid, clearance, passability.m_Mask); } }
int main(int argc, char** argv) { cl::ParseCommandLineOptions(argc, argv, "Rician3D example"); ElementType *Ty = new FP32Type(); Grid *GD = new Grid(3); Field *U = new Field(GD, Ty, "U"); Field *G = new Field(GD, Ty, "G"); Field *F = new Field(GD, Ty, "F"); Field *R = new Field(GD, Ty, "R"); FP32Constant *ConstOne = new FP32Constant(1.0); FP32Constant *Epsilon = new FP32Constant(1.0e-20); FP32Constant *Sigma = new FP32Constant(1.0000001); FP32Constant *Lambda = new FP32Constant(1.0000001); Expression *Sigma2 = new BinaryOp(BinaryOp::MUL, Sigma, Sigma); Expression *Gamma = new BinaryOp(BinaryOp::DIV, Lambda, Sigma2); FP32Constant *C1 = new FP32Constant(2.38944); FP32Constant *C2 = new FP32Constant(0.950037); FP32Constant *C3 = new FP32Constant(4.65314); FP32Constant *C4 = new FP32Constant(2.57541); FP32Constant *C5 = new FP32Constant(1.48937); FP32Constant *DT = new FP32Constant(5.0); IntConstant *Offsets[3]; Offsets[0] = new IntConstant(0); Offsets[1] = new IntConstant(0); Offsets[2] = new IntConstant(0); Expression *U_0_0_0 = new FieldRef(U, 3, Offsets); Offsets[0] = new IntConstant(1); Offsets[1] = new IntConstant(0); Offsets[2] = new IntConstant(0); Expression *U_p1_0_0 = new FieldRef(U, 3, Offsets); Offsets[0] = new IntConstant(-1); Offsets[1] = new IntConstant(0); Offsets[2] = new IntConstant(0); Expression *U_m1_0_0 = new FieldRef(U, 3, Offsets); Offsets[0] = new IntConstant(0); Offsets[1] = new IntConstant(1); Offsets[2] = new IntConstant(0); Expression *U_0_p1_0 = new FieldRef(U, 3, Offsets); Offsets[0] = new IntConstant(0); Offsets[1] = new IntConstant(-1); Offsets[2] = new IntConstant(0); Expression *U_0_m1_0 = new FieldRef(U, 3, Offsets); Offsets[0] = new IntConstant(0); Offsets[1] = new IntConstant(0); Offsets[2] = new IntConstant(1); Expression *U_0_0_p1 = new FieldRef(U, 3, Offsets); Offsets[0] = new IntConstant(0); Offsets[1] = new IntConstant(0); Offsets[2] = new IntConstant(-1); Expression *U_0_0_m1 = new FieldRef(U, 3, Offsets); Offsets[0] = new IntConstant(0); Offsets[1] = new IntConstant(0); Offsets[2] = new IntConstant(0); Expression *G_0_0_0 = new FieldRef(G, 3, Offsets); Offsets[0] = new IntConstant(1); Offsets[1] = new IntConstant(0); Offsets[2] = new IntConstant(0); Expression *G_p1_0_0 = new FieldRef(G, 3, Offsets); Offsets[0] = new IntConstant(-1); Offsets[1] = new IntConstant(0); Offsets[2] = new IntConstant(0); Expression *G_m1_0_0 = new FieldRef(G, 3, Offsets); Offsets[0] = new IntConstant(0); Offsets[1] = new IntConstant(1); Offsets[2] = new IntConstant(0); Expression *G_0_p1_0 = new FieldRef(G, 3, Offsets); Offsets[0] = new IntConstant(0); Offsets[1] = new IntConstant(-1); Offsets[2] = new IntConstant(0); Expression *G_0_m1_0 = new FieldRef(G, 3, Offsets); Offsets[0] = new IntConstant(0); Offsets[1] = new IntConstant(0); Offsets[2] = new IntConstant(1); Expression *G_0_0_p1 = new FieldRef(G, 3, Offsets); Offsets[0] = new IntConstant(0); Offsets[1] = new IntConstant(0); Offsets[2] = new IntConstant(-1); Expression *G_0_0_m1 = new FieldRef(G, 3, Offsets); Offsets[0] = new IntConstant(0); Offsets[1] = new IntConstant(0); Offsets[2] = new IntConstant(0); Expression *R_0_0_0 = new FieldRef(R, 3, Offsets); Expression *T1 = new BinaryOp(BinaryOp::SUB, U_0_0_0, U_0_p1_0); T1 = new BinaryOp(BinaryOp::MUL, T1, T1); Expression *T2 = new BinaryOp(BinaryOp::SUB, U_0_0_0, U_0_m1_0); T2 = new BinaryOp(BinaryOp::MUL, T2, T2); Expression *T3 = new BinaryOp(BinaryOp::SUB, U_0_0_0, U_0_0_p1); T3 = new BinaryOp(BinaryOp::MUL, T3, T3); Expression *T4 = new BinaryOp(BinaryOp::SUB, U_0_0_0, U_0_0_m1); T4 = new BinaryOp(BinaryOp::MUL, T4, T4); Expression *T5 = new BinaryOp(BinaryOp::SUB, U_0_0_0, U_p1_0_0); T5 = new BinaryOp(BinaryOp::MUL, T5, T5); Expression *T6 = new BinaryOp(BinaryOp::SUB, U_0_0_0, U_m1_0_0); T6 = new BinaryOp(BinaryOp::MUL, T6, T6); Expression *T7 = new BinaryOp(BinaryOp::ADD, Epsilon, T1); Expression *T8 = new BinaryOp(BinaryOp::ADD, T7, T2); Expression *T9 = new BinaryOp(BinaryOp::ADD, T8, T3); Expression *T10 = new BinaryOp(BinaryOp::ADD, T9, T4); Expression *T11 = new BinaryOp(BinaryOp::ADD, T10, T5); Expression *T12 = new BinaryOp(BinaryOp::ADD, T11, T6); Expression *T13 = new BinaryOp(BinaryOp::DIV, ConstOne, T12); Function *Func = new Function(G, T13); Func->setLowerBound(0, 1); Func->setLowerBound(1, 1); Func->setLowerBound(2, 1); Func->setUpperBound(0, 1); Func->setUpperBound(1, 1); Func->setUpperBound(2, 1); GD->appendFunction(Func); Offsets[0] = new IntConstant(0); Offsets[1] = new IntConstant(0); Offsets[2] = new IntConstant(0); Expression *F_0_0_0 = new FieldRef(F, 3, Offsets); T1 = new BinaryOp(BinaryOp::MUL, U_0_0_0, F_0_0_0); T2 = new BinaryOp(BinaryOp::DIV, T1, Sigma2); T3 = new BinaryOp(BinaryOp::ADD, C2, T2); T4 = new BinaryOp(BinaryOp::MUL, T2, T3); T5 = new BinaryOp(BinaryOp::ADD, C1, T4); T6 = new BinaryOp(BinaryOp::MUL, T2, T5); T7 = new BinaryOp(BinaryOp::ADD, C5, T2); T8 = new BinaryOp(BinaryOp::MUL, T2, T7); T9 = new BinaryOp(BinaryOp::ADD, C4, T8); T10 = new BinaryOp(BinaryOp::MUL, T2, T9); T11 = new BinaryOp(BinaryOp::ADD, C3, T10); T12 = new BinaryOp(BinaryOp::DIV, T6, T11); Func = new Function(R, T12); Func->setLowerBound(0, 1); Func->setLowerBound(1, 1); Func->setLowerBound(2, 1); Func->setUpperBound(0, 1); Func->setUpperBound(1, 1); Func->setUpperBound(2, 1); GD->appendFunction(Func); T1 = new BinaryOp(BinaryOp::MUL, U_0_p1_0, G_0_p1_0); T2 = new BinaryOp(BinaryOp::MUL, U_0_m1_0, G_0_m1_0); T3 = new BinaryOp(BinaryOp::MUL, U_0_0_p1, G_0_0_p1); T4 = new BinaryOp(BinaryOp::MUL, U_0_0_m1, G_0_0_m1); T5 = new BinaryOp(BinaryOp::MUL, U_p1_0_0, G_p1_0_0); T6 = new BinaryOp(BinaryOp::MUL, U_m1_0_0, G_m1_0_0); T7 = new BinaryOp(BinaryOp::MUL, Gamma, F_0_0_0); T8 = new BinaryOp(BinaryOp::MUL, T7, R_0_0_0); T9 = new BinaryOp(BinaryOp::MUL, DT, T8); T10 = new BinaryOp(BinaryOp::ADD, U_0_0_0, T9); T1 = new BinaryOp(BinaryOp::MUL, DT, G_0_p1_0); T2 = new BinaryOp(BinaryOp::ADD, ConstOne, T1); T3 = new BinaryOp(BinaryOp::ADD, T2, G_0_m1_0); T4 = new BinaryOp(BinaryOp::ADD, T3, G_0_0_p1); T5 = new BinaryOp(BinaryOp::ADD, T4, G_0_0_m1); T6 = new BinaryOp(BinaryOp::ADD, T5, G_p1_0_0); T7 = new BinaryOp(BinaryOp::ADD, T6, G_m1_0_0); T8 = new BinaryOp(BinaryOp::ADD, T7, Gamma); T1 = new BinaryOp(BinaryOp::DIV, T10, T8); Func = new Function(U, T1); Func->setLowerBound(0, 1); Func->setLowerBound(1, 1); Func->setLowerBound(2, 1); Func->setUpperBound(0, 1); Func->setUpperBound(1, 1); Func->setUpperBound(2, 1); GD->appendFunction(Func); CudaBackEnd BE(GD); BE.setVerbose(true); BE.setTimeTileSize(TimeTileSize); BE.setBlockSize(0, BlockSizeX); BE.setBlockSize(1, BlockSizeY); BE.setBlockSize(2, BlockSizeZ); BE.setElements(0, ElementsX); BE.setElements(1, ElementsY); BE.setElements(2, ElementsZ); BE.run(); BE.codegen(llvm::outs()); return 0; }
static Widget* convert_xmlelement_to_widget(TiXmlElement* elem, Widget* root) { const char *elem_name = elem->Value(); JWidget widget = NULL; JWidget child; /* TODO error handling: add a message if the widget is bad specified */ // Boxes if (ustrcmp(elem_name, "box") == 0) { bool horizontal = bool_attr_is_true(elem, "horizontal"); bool vertical = bool_attr_is_true(elem, "vertical"); bool homogeneous = bool_attr_is_true(elem, "homogeneous"); widget = new Box((horizontal ? JI_HORIZONTAL: vertical ? JI_VERTICAL: 0) | (homogeneous ? JI_HOMOGENEOUS: 0)); } else if (ustrcmp(elem_name, "vbox") == 0) { bool homogeneous = bool_attr_is_true(elem, "homogeneous"); widget = new VBox(); if (homogeneous) widget->setAlign(widget->getAlign() | JI_HOMOGENEOUS); } else if (ustrcmp(elem_name, "hbox") == 0) { bool homogeneous = bool_attr_is_true(elem, "homogeneous"); widget = new HBox(); if (homogeneous) widget->setAlign(widget->getAlign() | JI_HOMOGENEOUS); } else if (ustrcmp(elem_name, "boxfiller") == 0) { widget = new BoxFiller(); } // Button else if (ustrcmp(elem_name, "button") == 0) { const char *text = elem->Attribute("text"); widget = new Button(text ? TRANSLATE_ATTR(text): NULL); if (widget) { bool left = bool_attr_is_true(elem, "left"); bool right = bool_attr_is_true(elem, "right"); bool top = bool_attr_is_true(elem, "top"); bool bottom = bool_attr_is_true(elem, "bottom"); bool closewindow = bool_attr_is_true(elem, "closewindow"); const char *_bevel = elem->Attribute("bevel"); widget->setAlign((left ? JI_LEFT: (right ? JI_RIGHT: JI_CENTER)) | (top ? JI_TOP: (bottom ? JI_BOTTOM: JI_MIDDLE))); if (_bevel != NULL) { char* bevel = base_strdup(_bevel); int c, b[4]; char *tok; for (c=0; c<4; ++c) b[c] = 0; for (tok=ustrtok(bevel, " "), c=0; tok; tok=ustrtok(NULL, " "), ++c) { if (c < 4) b[c] = ustrtol(tok, NULL, 10); } base_free(bevel); setup_bevels(widget, b[0], b[1], b[2], b[3]); } if (closewindow) { static_cast<Button*>(widget) ->Click.connect(Bind<void>(&Widget::closeWindow, widget)); } } } // Check else if (ustrcmp(elem_name, "check") == 0) { const char *text = elem->Attribute("text"); const char *looklike = elem->Attribute("looklike"); text = (text ? TRANSLATE_ATTR(text): NULL); if (looklike != NULL && strcmp(looklike, "button") == 0) { widget = new CheckBox(text, JI_BUTTON); } else { widget = new CheckBox(text); } if (widget) { bool center = bool_attr_is_true(elem, "center"); bool right = bool_attr_is_true(elem, "right"); bool top = bool_attr_is_true(elem, "top"); bool bottom = bool_attr_is_true(elem, "bottom"); widget->setAlign((center ? JI_CENTER: (right ? JI_RIGHT: JI_LEFT)) | (top ? JI_TOP: (bottom ? JI_BOTTOM: JI_MIDDLE))); } } /* combobox */ else if (ustrcmp(elem_name, "combobox") == 0) { widget = new ComboBox(); } /* entry */ else if (ustrcmp(elem_name, "entry") == 0) { const char *maxsize = elem->Attribute("maxsize"); const char *text = elem->Attribute("text"); if (maxsize != NULL) { bool readonly = bool_attr_is_true(elem, "readonly"); widget = new Entry(ustrtol(maxsize, NULL, 10), text ? TRANSLATE_ATTR(text): NULL); if (readonly) ((Entry*)widget)->setReadOnly(true); } } /* grid */ else if (ustrcmp(elem_name, "grid") == 0) { const char *columns = elem->Attribute("columns"); bool same_width_columns = bool_attr_is_true(elem, "same_width_columns"); if (columns != NULL) { widget = new Grid(ustrtol(columns, NULL, 10), same_width_columns); } } /* label */ else if (ustrcmp(elem_name, "label") == 0) { const char *text = elem->Attribute("text"); widget = new Label(text ? TRANSLATE_ATTR(text): NULL); if (widget) { bool center = bool_attr_is_true(elem, "center"); bool right = bool_attr_is_true(elem, "right"); bool top = bool_attr_is_true(elem, "top"); bool bottom = bool_attr_is_true(elem, "bottom"); widget->setAlign((center ? JI_CENTER: (right ? JI_RIGHT: JI_LEFT)) | (top ? JI_TOP: (bottom ? JI_BOTTOM: JI_MIDDLE))); } } /* listbox */ else if (ustrcmp(elem_name, "listbox") == 0) { widget = new ListBox(); } /* listitem */ else if (ustrcmp(elem_name, "listitem") == 0) { const char *text = elem->Attribute("text"); widget = new ListBox::Item(text ? TRANSLATE_ATTR(text): NULL); } /* splitter */ else if (ustrcmp(elem_name, "splitter") == 0) { bool horizontal = bool_attr_is_true(elem, "horizontal"); bool vertical = bool_attr_is_true(elem, "vertical"); widget = new Splitter(horizontal ? JI_HORIZONTAL: vertical ? JI_VERTICAL: 0); } /* radio */ else if (ustrcmp(elem_name, "radio") == 0) { const char* text = elem->Attribute("text"); const char* group = elem->Attribute("group"); const char *looklike = elem->Attribute("looklike"); text = (text ? TRANSLATE_ATTR(text): NULL); int radio_group = (group ? ustrtol(group, NULL, 10): 1); if (looklike != NULL && strcmp(looklike, "button") == 0) { widget = new RadioButton(text, radio_group, JI_BUTTON); } else { widget = new RadioButton(text, radio_group); } if (widget) { bool center = bool_attr_is_true(elem, "center"); bool right = bool_attr_is_true(elem, "right"); bool top = bool_attr_is_true(elem, "top"); bool bottom = bool_attr_is_true(elem, "bottom"); widget->setAlign((center ? JI_CENTER: (right ? JI_RIGHT: JI_LEFT)) | (top ? JI_TOP: (bottom ? JI_BOTTOM: JI_MIDDLE))); } } /* separator */ else if (ustrcmp(elem_name, "separator") == 0) { const char *text = elem->Attribute("text"); bool center = bool_attr_is_true(elem, "center"); bool right = bool_attr_is_true(elem, "right"); bool middle = bool_attr_is_true(elem, "middle"); bool bottom = bool_attr_is_true(elem, "bottom"); bool horizontal = bool_attr_is_true(elem, "horizontal"); bool vertical = bool_attr_is_true(elem, "vertical"); widget = new Separator(text ? TRANSLATE_ATTR(text): NULL, (horizontal ? JI_HORIZONTAL: 0) | (vertical ? JI_VERTICAL: 0) | (center ? JI_CENTER: (right ? JI_RIGHT: JI_LEFT)) | (middle ? JI_MIDDLE: (bottom ? JI_BOTTOM: JI_TOP))); } /* slider */ else if (ustrcmp(elem_name, "slider") == 0) { const char *min = elem->Attribute("min"); const char *max = elem->Attribute("max"); int min_value = min != NULL ? ustrtol(min, NULL, 10): 0; int max_value = max != NULL ? ustrtol(max, NULL, 10): 0; widget = new Slider(min_value, max_value, min_value); } /* textbox */ else if (ustrcmp(elem_name, "textbox") == 0) { //bool wordwrap = bool_attr_is_true(elem, "wordwrap"); /* TODO add translatable support */ /* TODO here we need jxmlelem_get_text(elem) */ /* widget = jtextbox_new(tag->text, wordwrap ? JI_WORDWRAP: 0); */ ASSERT(false); } /* view */ else if (ustrcmp(elem_name, "view") == 0) { widget = new View(); } /* window */ else if (ustrcmp(elem_name, "window") == 0) { const char *text = elem->Attribute("text"); if (text) { bool desktop = bool_attr_is_true(elem, "desktop"); if (desktop) widget = new Frame(true, NULL); else widget = new Frame(false, TRANSLATE_ATTR(text)); } } /* colorpicker */ else if (ustrcmp(elem_name, "colorpicker") == 0) { widget = new ColorButton(Color::fromMask(), app_get_current_pixel_format()); } // Was the widget created? if (widget) { const char *name = elem->Attribute("name"); const char *tooltip = elem->Attribute("tooltip"); bool selected = bool_attr_is_true(elem, "selected"); bool disabled = bool_attr_is_true(elem, "disabled"); bool expansive = bool_attr_is_true(elem, "expansive"); bool magnetic = bool_attr_is_true(elem, "magnetic"); bool noborders = bool_attr_is_true(elem, "noborders"); const char *width = elem->Attribute("width"); const char *height = elem->Attribute("height"); const char *minwidth = elem->Attribute("minwidth"); const char *minheight = elem->Attribute("minheight"); const char *maxwidth = elem->Attribute("maxwidth"); const char *maxheight = elem->Attribute("maxheight"); const char *childspacing = elem->Attribute("childspacing"); if (name != NULL) widget->setName(name); if (tooltip != NULL) jwidget_add_tooltip_text(widget, tooltip, JI_LEFT); if (selected) widget->setSelected(selected); if (disabled) widget->setEnabled(false); if (expansive) widget->setExpansive(true); if (magnetic) widget->setFocusMagnet(true); if (noborders) jwidget_noborders(widget); if (childspacing) widget->child_spacing = ustrtol(childspacing, NULL, 10); if (width || minwidth || height || minheight) { int w = (width || minwidth) ? ustrtol(width ? width: minwidth, NULL, 10): 0; int h = (height || minheight) ? ustrtol(height ? height: minheight, NULL, 10): 0; jwidget_set_min_size(widget, w*jguiscale(), h*jguiscale()); } if (width || maxwidth || height || maxheight) { int w = (width || maxwidth) ? strtol(width ? width: maxwidth, NULL, 10): INT_MAX; int h = (height || maxheight) ? strtol(height ? height: maxheight, NULL, 10): INT_MAX; jwidget_set_max_size(widget, w*jguiscale(), h*jguiscale()); } if (!root) root = widget; // Children TiXmlElement* child_elem = elem->FirstChildElement(); while (child_elem) { child = convert_xmlelement_to_widget(child_elem, root); if (child) { // Attach the child in the view if (widget->type == JI_VIEW) { static_cast<View*>(widget)->attachToView(child); break; } // Add the child in the grid else if (widget->type == JI_GRID) { const char* cell_hspan = child_elem->Attribute("cell_hspan"); const char* cell_vspan = child_elem->Attribute("cell_vspan"); const char* cell_align = child_elem->Attribute("cell_align"); int hspan = cell_hspan ? ustrtol(cell_hspan, NULL, 10): 1; int vspan = cell_vspan ? ustrtol(cell_vspan, NULL, 10): 1; int align = cell_align ? convert_align_value_to_flags(cell_align): 0; Grid* grid = dynamic_cast<Grid*>(widget); ASSERT(grid != NULL); grid->addChildInCell(child, hspan, vspan, align); } // Just add the child in any other kind of widget else widget->addChild(child); } child_elem = child_elem->NextSiblingElement(); } if (widget->type == JI_VIEW) { bool maxsize = bool_attr_is_true(elem, "maxsize"); if (maxsize) static_cast<View*>(widget)->makeVisibleAllScrollableArea(); } } return widget; }
const std::vector<Field*> Sudoku::getGridElements(const Field* refField) const { Grid* grid = (Grid*) refField->belongsTo; return grid->getGridElements(); }
MAD::MAD(Grid **grid_) { ifc_polygon = NULL; river_polygon = NULL; ascii_grids = NULL; spp_polygon = NULL; PetscReal mx = 1.; PetscReal my = 1.; PetscReal mz = 1.; PetscInt nx, ny, nz; char filename[1024]; PetscBool option_found; strcpy(filename,"mdt.in"); PetscOptionsGetString(PETSC_NULL,"-mdtin",filename,1024,&option_found); FileIO *file = new FileIO(filename); file->getLine(); file->readInt(&nx); file->readInt(&ny); file->readInt(&nz); delete file; PetscReal dx; PetscReal dy; PetscReal dz;// */ PetscReal len_x = 120.; PetscReal len_y = 122; PetscReal len_z = 60.; dx = len_x/(PetscReal)nx; dy = len_y/(PetscReal)ny; dz = len_z/(PetscReal)nz; PetscInt n = nx*ny*nz; PetscPrintf(PETSC_COMM_WORLD,"nx = %d, dx = %f, lenx = %f\n",nx,dx,nx*dx); PetscPrintf(PETSC_COMM_WORLD,"ny = %d, dy = %f, leny = %f\n",ny,dy,ny*dy); PetscPrintf(PETSC_COMM_WORLD,"nz = %d, dz = %f, lenz = %f\n",nz,dz,nz*dz); *grid_ = new Grid(nx,ny,nz); Grid *grid = *grid_; // grid spacing with a bias #if 0 PetscReal sum_x = 0.; PetscReal sum_y = 0.; dx = 0.8470329472543 PetscReal *dx_array = new double[nx]; PetscReal *dy_array = new double[ny]; PetscReal *dz_array = new double[nz]; for (int i=0; i<nx; i++) dx_array[i] = 10.; for (int i=0; i<ny; i++) dy_array[i] = 10.; for (int i=0; i<nz; i++) dz_array[i] = 0.25; for (int i=11; i<19; i++) { dx_array[i] = 10.*pow(1.30242241518419,(double)(10-i)); sum_x += dx_array[i]; } for (int i=19; i<89; i++) { dx_array[i] = 1.; sum_x += dx_array[i]; } for (int i=89; i<97; i++) { dx_array[i] = 10.*pow(1.30242241518419,(double)(i-97)); sum_x += dx_array[i]; } for (int i=97; i<9; i++) { dy_array[110+i] = 10.*pow(1.353088,i+1.); dy_array[9-i] = 10.*pow(1.353088,i+1.); sum_y += dy_array[9-i]; } grid->setGridSpacing(dx_array,dy_array,dz_array); #else grid->setGridSpacing(dx,dy,dz); #endif // grid->setOrigin(593618.9,114565.1,70.); grid->setRotation(34.); // must come before ->setOrigin() grid->setOrigin(594237.2891,115984.7447,70.); // grid->computeCoordinates(); // grid->computeConnectivity(); grid->computeCellMapping(); grid->setUpCells(); grid->computeVertexMapping(); grid->setUpVertices(); grid->mapVerticesToCells(); ifc_polygon = new Polygon(); ifc_polygon->createIFCPolygon(); #if 0 char ascii_filename[1024]; strcpy(ascii_filename,"test.asc"); AsciiGrid **ascii_grid = new AsciiGrid*[2]; ascii_grid[0] = new AsciiGrid(ascii_filename); ascii_grid[0]->setMaterialId(1); ascii_grid[1] = new AsciiGrid("default",2,2,-1.e10,-1.e10,1.e10,-9999., 1.e20,0); #else AsciiGrid::nasciigrids = 6; string *grid_filenames = new string[AsciiGrid::nasciigrids]; #if 0 grid_filenames[0].append("./basalt_300area.asc"); grid_filenames[1].append("./u9_300area.asc"); grid_filenames[2].append("./u8_300area.asc"); grid_filenames[3].append("./u5gravel_300area.asc"); grid_filenames[4].append("./u5silt_300area.asc"); grid_filenames[5].append("./newbath_10mDEM_grid.ascii"); #else grid_filenames[0].append("../basalt_300area.asc"); grid_filenames[1].append("../u9_300area.asc"); grid_filenames[2].append("../u8_300area.asc"); grid_filenames[3].append("../u5gravel_300area.asc"); grid_filenames[4].append("../u5silt_300area.asc"); grid_filenames[5].append("../newbath_10mDEM_grid.ascii"); #endif ascii_grids = new AsciiGrid*[AsciiGrid::nasciigrids]; for (PetscInt i=0; i<AsciiGrid::nasciigrids; i++) { char filename[32]; strcpy(filename,grid_filenames[i].c_str()); ascii_grids[i] = new AsciiGrid(filename); } ascii_grids[0]->setMaterialId(10); ascii_grids[1]->setMaterialId(9); ascii_grids[2]->setMaterialId(8); ascii_grids[3]->setMaterialId(6); ascii_grids[4]->setMaterialId(5); ascii_grids[5]->setMaterialId(1); PetscInt mod = grid->num_cells_ghosted/10; for (PetscInt i=0; i<grid->num_cells_ghosted; i++) { PetscInt material_id = 0; PetscReal x = grid->cells[i].getX(); PetscReal y = grid->cells[i].getY(); PetscReal z = grid->cells[i].getZ(); for (PetscInt ilayer=0; ilayer<AsciiGrid::nasciigrids; ilayer++) { PetscReal zlayer = ascii_grids[ilayer]->computeElevationFromCoordinate(x,y); if (zlayer > ascii_grids[ilayer]->nodata && zlayer >= z) { material_id = ascii_grids[ilayer]->getMaterialId(); break; } } if (material_id == 0) grid->cells[i].setActive(0); grid->cells[i].setMaterialId(material_id); if (river_polygon) { if (!river_polygon->pointInPolygon(x,y)) { grid->cells[i].setActive(0); grid->cells[i].negateMaterialId(); } } if (i%mod == 0) { PetscPrintf(PETSC_COMM_WORLD,"%d of %d cells mapped with materials and activity.\n", i,grid->num_cells_ghosted); } } #endif flagGridCells(grid); #if 0 computeEastBoundary(grid,1); computeWestBoundary(grid,1); computeNorthBoundary(grid,0); computeSouthBoundary(grid,0); computeTopBoundary(grid,0); #endif computeIFCBoundary(grid,ifc_polygon); #if 0 BoundarySet *river = grid->getBoundarySet("East"); BoundarySet *west = grid->getBoundarySet("West"); BoundarySet *north = grid->getBoundarySet("North"); BoundarySet *south = grid->getBoundarySet("South"); BoundarySet *recharge = grid->getBoundarySet("Top"); #endif /* Condition *new_condition = new Condition("river.bc"); river->condition = new_condition; new_condition = new Condition("west.bc"); west->condition = new_condition; new_condition = new Condition("recharge.bc"); recharge->condition = new_condition; new_condition = NULL; */ }
void TimestepSchemeStrang::Step( bool fFirstStep, bool fLastStep, const Time & time, double dDeltaT ) { // Get a copy of the grid Grid * pGrid = m_model.GetGrid(); // Get a copy of the HorizontalDynamics HorizontalDynamics * pHorizontalDynamics = m_model.GetHorizontalDynamics(); // Get a copy of the VerticalDynamics VerticalDynamics * pVerticalDynamics = m_model.GetVerticalDynamics(); // Half a time step double dHalfDeltaT = 0.5 * dDeltaT; // Vertical timestep if (fFirstStep) { pVerticalDynamics->StepImplicit(0, 0, time, dHalfDeltaT); } else { pGrid->LinearCombineData(m_dCarryoverCombination, 0, DataType_State); } // Forward Euler if (m_eExplicitDiscretization == ForwardEuler) { pGrid->CopyData(0, 4, DataType_State); pHorizontalDynamics->StepExplicit(0, 4, time, dDeltaT); pVerticalDynamics->StepExplicit(0, 4, time, dDeltaT); pGrid->PostProcessSubstage(4, DataType_State); pGrid->PostProcessSubstage(4, DataType_Tracers); // Explicit fourth-order Runge-Kutta } else if (m_eExplicitDiscretization == RungeKutta4) { pGrid->CopyData(0, 1, DataType_State); pHorizontalDynamics->StepExplicit(0, 1, time, dHalfDeltaT); pVerticalDynamics->StepExplicit(0, 1, time, dHalfDeltaT); pGrid->PostProcessSubstage(1, DataType_State); pGrid->PostProcessSubstage(1, DataType_Tracers); pGrid->CopyData(0, 2, DataType_State); pHorizontalDynamics->StepExplicit(1, 2, time, dHalfDeltaT); pVerticalDynamics->StepExplicit(1, 2, time, dHalfDeltaT); pGrid->PostProcessSubstage(2, DataType_State); pGrid->PostProcessSubstage(2, DataType_Tracers); pGrid->CopyData(0, 3, DataType_State); pHorizontalDynamics->StepExplicit(2, 3, time, dDeltaT); pVerticalDynamics->StepExplicit(2, 3, time, dDeltaT); pGrid->PostProcessSubstage(3, DataType_State); pGrid->PostProcessSubstage(3, DataType_Tracers); pGrid->LinearCombineData(m_dRK4Combination, 4, DataType_State); pHorizontalDynamics->StepExplicit(3, 4, time, dDeltaT / 6.0); pVerticalDynamics->StepExplicit(3, 4, time, dDeltaT / 6.0); pGrid->PostProcessSubstage(4, DataType_State); pGrid->PostProcessSubstage(4, DataType_Tracers); // Explicit strong stability preserving third-order Runge-Kutta } else if (m_eExplicitDiscretization == RungeKuttaSSP3) { pGrid->CopyData(0, 1, DataType_State); pHorizontalDynamics->StepExplicit(0, 1, time, dDeltaT); pVerticalDynamics->StepExplicit(0, 1, time, dDeltaT); pGrid->PostProcessSubstage(1, DataType_State); pGrid->PostProcessSubstage(1, DataType_Tracers); pGrid->LinearCombineData(m_dSSPRK3CombinationA, 2, DataType_State); pHorizontalDynamics->StepExplicit(1, 2, time, 0.25 * dDeltaT); pVerticalDynamics->StepExplicit(1, 2, time, 0.25 * dDeltaT); pGrid->PostProcessSubstage(2, DataType_State); pGrid->PostProcessSubstage(2, DataType_Tracers); pGrid->LinearCombineData(m_dSSPRK3CombinationB, 4, DataType_State); pHorizontalDynamics->StepExplicit(2, 4, time, (2.0/3.0) * dDeltaT); pVerticalDynamics->StepExplicit(2, 4, time, (2.0/3.0) * dDeltaT); pGrid->PostProcessSubstage(4, DataType_State); pGrid->PostProcessSubstage(4, DataType_Tracers); // Explicit Kinnmark, Gray and Ullrich third-order five-stage Runge-Kutta } else if (m_eExplicitDiscretization == KinnmarkGrayUllrich35) { pGrid->CopyData(0, 1, DataType_State); pHorizontalDynamics->StepExplicit(0, 1, time, dDeltaT / 5.0); pVerticalDynamics->StepExplicit(0, 1, time, dDeltaT / 5.0); pGrid->PostProcessSubstage(1, DataType_State); pGrid->PostProcessSubstage(1, DataType_Tracers); pGrid->CopyData(0, 2, DataType_State); pHorizontalDynamics->StepExplicit(1, 2, time, dDeltaT / 5.0); pVerticalDynamics->StepExplicit(1, 2, time, dDeltaT / 5.0); pGrid->PostProcessSubstage(2, DataType_State); pGrid->PostProcessSubstage(2, DataType_Tracers); pGrid->CopyData(0, 3, DataType_State); pHorizontalDynamics->StepExplicit(2, 3, time, dDeltaT / 3.0); pVerticalDynamics->StepExplicit(2, 3, time, dDeltaT / 3.0); pGrid->PostProcessSubstage(3, DataType_State); pGrid->PostProcessSubstage(3, DataType_Tracers); pGrid->CopyData(0, 2, DataType_State); pHorizontalDynamics->StepExplicit(3, 2, time, 2.0 * dDeltaT / 3.0); pVerticalDynamics->StepExplicit(3, 2, time, 2.0 * dDeltaT / 3.0); pGrid->PostProcessSubstage(2, DataType_State); pGrid->PostProcessSubstage(2, DataType_Tracers); pGrid->LinearCombineData( m_dKinnmarkGrayUllrichCombination, 4, DataType_State); pHorizontalDynamics->StepExplicit(2, 4, time, 3.0 * dDeltaT / 4.0); pVerticalDynamics->StepExplicit(2, 4, time, 3.0 * dDeltaT / 4.0); pGrid->PostProcessSubstage(4, DataType_State); pGrid->PostProcessSubstage(4, DataType_Tracers); // Explicit strong stability preserving five-stage third-order Runge-Kutta } else if (m_eExplicitDiscretization == RungeKuttaSSPRK53) { const double dStepOne = 0.377268915331368; pGrid->CopyData(0, 1, DataType_State); pHorizontalDynamics->StepExplicit(0, 1, time, dStepOne * dDeltaT); pVerticalDynamics->StepExplicit(0, 1, time, dStepOne * dDeltaT); pGrid->PostProcessSubstage(1, DataType_State); pGrid->PostProcessSubstage(1, DataType_Tracers); pGrid->CopyData(1, 2, DataType_State); pHorizontalDynamics->StepExplicit(1, 2, time, dStepOne * dDeltaT); pVerticalDynamics->StepExplicit(1, 2, time, dStepOne * dDeltaT); pGrid->PostProcessSubstage(2, DataType_State); pGrid->PostProcessSubstage(2, DataType_Tracers); const double dStepThree = 0.242995220537396; pGrid->LinearCombineData(m_dSSPRK53CombinationA, 3, DataType_State); pHorizontalDynamics->StepExplicit(2, 3, time, dStepThree * dDeltaT); pVerticalDynamics->StepExplicit(2, 3, time, dStepThree * dDeltaT); pGrid->PostProcessSubstage(3, DataType_State); pGrid->PostProcessSubstage(3, DataType_Tracers); const double dStepFour = 0.238458932846290; pGrid->LinearCombineData(m_dSSPRK53CombinationB, 0, DataType_State); pHorizontalDynamics->StepExplicit(3, 0, time, dStepFour * dDeltaT); pVerticalDynamics->StepExplicit(3, 0, time, dStepFour * dDeltaT); pGrid->PostProcessSubstage(0, DataType_State); pGrid->PostProcessSubstage(0, DataType_Tracers); const double dStepFive = 0.287632146308408; pGrid->LinearCombineData(m_dSSPRK53CombinationC, 4, DataType_State); pHorizontalDynamics->StepExplicit(0, 4, time, dStepFive * dDeltaT); pVerticalDynamics->StepExplicit(0, 4, time, dStepFive * dDeltaT); pGrid->PostProcessSubstage(4, DataType_State); pGrid->PostProcessSubstage(4, DataType_Tracers); // Invalid explicit discretization } else { _EXCEPTIONT("Invalid explicit discretization"); } // Apply hyperdiffusion pGrid->CopyData(4, 1, DataType_State); pHorizontalDynamics->StepAfterSubCycle(4, 1, 2, time, dDeltaT); // Vertical timestep double dOffCenterDeltaT = 0.5 * (1.0 + m_dOffCentering) * dDeltaT; pGrid->CopyData(1, 0, DataType_State); pVerticalDynamics->StepImplicit(0, 0, time, dOffCenterDeltaT); pGrid->LinearCombineData(m_dOffCenteringCombination, 0, DataType_State); if (!fLastStep) { pGrid->LinearCombineData(m_dCarryoverFinal, 1, DataType_State); } //pGrid->CopyData(0, 1, DataType_State); //pVerticalDynamics->StepExplicit(0, 1, time, dDeltaT); //pVerticalDynamics->StepImplicit(0, 0, time, dDeltaT); /* if (0) { //if (fLastStep) { DataVector<double> dDifference; dDifference.Initialize(2); dDifference[0] = -1.0; dDifference[1] = 1.0; pGrid->LinearCombineData(dDifference, 0, DataType_State); } else { pGrid->CopyData(4, 0, DataType_State); } */ }
/** * hex-constraints.exe [TreeSearch arguments] --rules [file] * * Load the rules from the given file (possibly with values?) and use that to generate * all of the constraints for the linear program. */ int main(int argc, char** argv) { // TODO: Make grid and conf be changeable by arguments? int grid_type = HEXAGONAL_GRID; bool blowup = false; // do blowup? bool tblowup = false; // do tight blowup? bool tbt = false; bool tt = false; bool ttt = false; bool dual = false; // do dual? (after blowup, maybe?) int mode = MODE_IDENTIFYING; for ( int i = 1; i < argc; i++ ) { if ( strcmp(argv[i],"--hexagonal")== 0) { grid_type = HEXAGONAL_GRID; } if ( strcmp(argv[i],"--hexnorot")== 0) { grid_type = HEXAGONAL_GRID_NO_ROTATE; } if ( strcmp(argv[i],"--square")== 0) { grid_type = SQUARE_GRID; }if ( strcmp(argv[i],"--triangular")== 0) { grid_type = TRIANGULAR_GRID; } if ( strcmp(argv[i],"--identifying")== 0) { mode = MODE_IDENTIFYING; } if ( strcmp(argv[i],"--dominating")== 0) { mode = MODE_DOMINATING; } if ( strcmp(argv[i],"--locating")== 0) { mode = MODE_LOCATING_DOMINATING; } if ( strcmp(argv[i],"--strongidentifying")== 0) { mode = MODE_STRONG_IDENTIFYING; } if ( strcmp(argv[i],"--openneighborhood")== 0) { mode = MODE_OPEN_NEIGHBORHOOD; } if ( strcmp(argv[i],"--neighbor")== 0) { mode = MODE_NEIGHBOR_IDENTIFYING; } if ( strcmp(argv[i],"--tblowup")== 0) { tblowup = true; } if ( strcmp(argv[i],"--blowup")== 0) { blowup = true; } if ( strcmp(argv[i],"--dual")== 0) { dual = true; } if ( strcmp(argv[i],"--tdt")== 0) { tbt = true; } if ( strcmp(argv[i],"--tt")== 0) { tt = true; } if ( strcmp(argv[i],"--ttt")== 0) { ttt = true; } } Grid* grid = 0; switch ( grid_type ) { case HEXAGONAL_GRID: grid = new HexagonalGrid(12); break; case HEXAGONAL_GRID_NO_ROTATE: grid = new HexagonalGridNoRotate(12); break; case SQUARE_GRID: grid = new SquareGrid(12); break; case TRIANGULAR_GRID: grid = new TriangularGrid(12); break; } if ( blowup ) { Grid* oldgrid = grid; grid = oldgrid->getBlowup(); delete oldgrid; } if ( tblowup ) { Grid* oldgrid = grid; grid = oldgrid->getTightBlowup(); delete oldgrid; } if ( dual ) { Grid* oldgrid = grid; grid = oldgrid->getDual(); delete oldgrid; } if ( tbt ) { Grid* oldgrid = grid; grid = oldgrid->getTightBlowup(); delete oldgrid; oldgrid = grid; grid = oldgrid->getDual(); delete oldgrid; oldgrid = grid; grid = oldgrid->getTightBlowup(); delete oldgrid; } if ( tt ) { Grid* oldgrid = grid; grid = oldgrid->getTightBlowup(); delete oldgrid; oldgrid = grid; grid = oldgrid->getTightBlowup(); delete oldgrid; } if ( ttt ) { Grid* oldgrid = grid; grid = oldgrid->getTightBlowup(); delete oldgrid; oldgrid = grid; grid = oldgrid->getTightBlowup(); delete oldgrid; oldgrid = grid; grid = oldgrid->getTightBlowup(); delete oldgrid; } Configuration* conf = new IdentifyingCodeConfiguration(grid, mode); LinearProgram* lp = new LinearProgram(); ConstraintGenerator* generator = new ConstraintGenerator(grid, conf, lp); generator->importArguments(argc, argv); generator->loadEmptyJob(); generator->doSearch(); delete generator; delete conf; delete grid; delete lp; return 0; }
BOOST_FIXTURE_TEST_CASE(ExposedModelGUITestCase, ExposedModelFixture) { model::Viewer viewer; viewer.height = 500; viewer.width = 500; model.addElement("viewer", viewer); model.addElement<bool>("myTab", false); model.addElement<bool>("myBool", false); model.addElement<std::string>("myVal", "THIS WORKS!"); const char* restrictions[] = {"select1", "select2", "select3", "select4"}; model.addElementWithRestriction<std::string>("myVal2", "select1", &restrictions[0], &restrictions[4]); model.addConstrainedElement<int>("myIntBA", 5,0, 900); model.addConstrainedElement<double>("myDouble", 10., 0., 11.); model.addElement<bool>("myButton", false); using namespace model::gui; TabLayout* root = new TabLayout(); HorizontalLayout *superLayout = new HorizontalLayout(); Grid *mainGrid = new Grid(10, 1); superLayout->addChild(mainGrid); Tab *mainTab = new Tab("myTab"); mainTab->setChild(superLayout); root->addChild(mainTab); // Used to hold our two input fields. // Simple Label-input-layout Grid *input1Grid = new Grid(3,2); mainGrid->setChild(0,0, input1Grid); input1Grid->setChild(0, 0, new Label("myVal")); input1Grid->setChild(0, 1, new TextInput("myVal")); input1Grid->setChild(1,0, new Label("myVal2")); input1Grid->setChild(1,1, new ComboBox("myVal2")); input1Grid->setChild(2,0, new Label("myVal2")); input1Grid->setChild(2,1, new RadioButtons("myVal2")); mainGrid->setChild(1, 0, new SpinBox("myIntBA")); mainGrid->setChild(2, 0, new TextInput("myIntBA")); mainGrid->setChild(3, 0, new CheckBox("myTab")); mainGrid->setChild(4, 0, new CheckBox("myTab")); mainGrid->setChild(5, 0, new Button("myButton")); mainGrid->setChild(6, 0, new HorizontalSlider("myIntBA")); mainGrid->setChild(8,0, new DoubleSpinBox("myDouble")); mainGrid->setChild(9, 0, new CheckBox("myBool")); ElementGroup* elemGroup = new ElementGroup("myTab", false); elemGroup->setChild(new TextInput("myVal")); mainGrid->setChild(7, 0, elemGroup); Grid* canvasGrid = new Grid(2,1); Canvas *canvas = new Canvas("viewer"); canvasGrid->setChild(0,0, canvas); VerticalLayout* verticalLayout = new VerticalLayout; verticalLayout->setVisibilityKey( "myBool" ); canvasGrid->setChild(1,0, verticalLayout); superLayout->addChild(canvasGrid); model.setGUILayout(root, DESKTOP); std::vector<model::StateSchemaElement> elements; model.getFullStateSchema(elements); }
void TestCholeskyMod ( bool testCorrectness, bool print, UpperOrLower uplo, Int m, Int n, Base<F> alpha, const Grid& g ) { DistMatrix<F> T(g), A(g); HermitianUniformSpectrum( T, m, 1e-9, 10 ); if( testCorrectness ) { if( g.Rank() == 0 ) { cout << " Making copy of original matrix..."; cout.flush(); } A = T; if( g.Rank() == 0 ) cout << "DONE" << endl; } if( print ) Print( T, "A" ); if( g.Rank() == 0 ) { cout << " Starting Cholesky factorization..."; cout.flush(); } double startTime = mpi::Time(); Cholesky( uplo, T ); double runTime = mpi::Time() - startTime; double realGFlops = 1./3.*Pow(double(m),3.)/(1.e9*runTime); double gFlops = ( IsComplex<F>::val ? 4*realGFlops : realGFlops ); if( g.Rank() == 0 ) { cout << "DONE\n" << " Time = " << runTime << " seconds. GFlops = " << gFlops << endl; } MakeTrapezoidal( uplo, T ); if( print ) Print( T, "Cholesky factor" ); if( g.Rank() == 0 ) { cout << " Generating random update vectors..."; cout.flush(); } DistMatrix<F> V(g), VMod(g); Uniform( V, m, n ); Scale( F(1)/Sqrt(F(m)*F(n)), V ); VMod = V; if( g.Rank() == 0 ) cout << "DONE" << endl; if( print ) Print( V, "V" ); if( g.Rank() == 0 ) { cout << " Starting Cholesky modification..."; cout.flush(); } startTime = mpi::Time(); CholeskyMod( uplo, T, alpha, VMod ); runTime = mpi::Time() - startTime; if( g.Rank() == 0 ) cout << "DONE\n" << " Time = " << runTime << " seconds." << endl; if( print ) Print( T, "Modified Cholesky factor" ); if( testCorrectness ) TestCorrectness( uplo, T, alpha, V, A ); }
void dump_grid(const Grid & grid, FILE * stream) { dump_grid_range(grid, grid.GetXBegin(), grid.GetYBegin(), grid.GetXEnd() - 1, grid.GetYEnd() - 1, stream); }
T set_incident_angle(const T &theta) const { T n = round(sin(theta)/(lens.lambda*grid.dg_min())); return (isZero(theta))?0:asin(n*lens.lambda*grid.dg_min()); }
void createSolidMaze(Grid& maze, int row, int column) { SFCOORD curTile = { column, row }; stack<SFCOORD> tileList; tileList.push(curTile); while (!tileList.empty()) { vector<int> moves; neighborsSF(maze, curTile, moves); if (!moves.empty()) { SFCOORD temp; switch (moves[0]) { case 1: // Down temp.x = curTile.x; temp.y = curTile.y - 2; maze.getTile(curTile.y - 1, curTile.x)->setWall(false); maze.getTile(curTile.y - 2, curTile.x)->setWall(false); //cout << maze.getTile(row - 1, column)->isWall(); //cout << maze.getTile(row - 2, column)->isWall(); curTile = temp; tileList.push(curTile); break; case 2: // Up temp.x = curTile.x; temp.y = curTile.y + 2; maze.getTile(curTile.y + 1, curTile.x)->setWall(false); maze.getTile(curTile.y + 2, curTile.x)->setWall(false); curTile = temp; tileList.push(curTile); break; case 3: // Left temp.x = curTile.x - 2; temp.y = curTile.y; maze.getTile(curTile.y, curTile.x - 1)->setWall(false); maze.getTile(curTile.y, curTile.x - 2)->setWall(false); curTile = temp; tileList.push(curTile); break; case 4: // Right temp.x = curTile.x + 2; temp.y = curTile.y; maze.getTile(curTile.y, curTile.x + 1)->setWall(false); maze.getTile(curTile.y, curTile.x + 2)->setWall(false); curTile = temp; tileList.push(curTile); break; } } else { curTile = tileList.top(); tileList.pop(); } } }
void MyStrategy::move(const Car& self, const World& world, const Game& game, Move& move) { if (!inited) { inited = true; gr = ToGrid(world.getTilesXY()); gr = gr.Transposed(); ::grid << gr; for (auto& w : world.getWaypoints()) { tiles << "col: " << w[0] << " row: " << w[1] << endl; waypoints.emplace_back(w[1], w[0]); } auto is_neighbor = [&](const Position& p, grid::Direction d) { return neighbors[static_cast<int>(gr[p])][d]; }; // shouldn't use grid at all here... or push values inside is_neighbor // but there maybe some cool logic BFS<TileType, decltype(is_neighbor)> bfs; bfs.Init(gr, is_neighbor); bfs.FindShortestPaths({14,2}, {13,13}); for (int i = 0; i < world.getWaypoints().size(); ++i) { int i_next = (i+1) % world.getWaypoints().size(); auto res = bfs.FindShortestPaths(waypoints[i], waypoints[i_next]); ways << waypoints[i] << "; " << waypoints[i_next] << endl; for (auto r : res) { for (auto p : r) { ways << p << "; "; } ways << endl; } ways << endl; } } Position next_tile{self.getNextWaypointY(), self.getNextWaypointX()}; Point target; target.x = (next_tile.col + 0.5) * game.getTrackTileSize(); target.y = (next_tile.row + 0.5) * game.getTrackTileSize(); // if (next_tile.ManhattanDistance(currentTile(self)) <= 2) { switch (world.getTilesXY()[next_tile.col][next_tile.row]) { case LEFT_TOP_CORNER: target.x += game.getTrackTileSize()/2 - game.getTrackTileMargin() - self.getWidth()/3; target.y += game.getTrackTileSize()/2 - game.getTrackTileMargin() - self.getWidth()/3; // nextWaypointX += cornerTileOffset; // nextWaypointY += cornerTileOffset; break; case RIGHT_TOP_CORNER: target.x -= (game.getTrackTileSize()/2 - game.getTrackTileMargin() - self.getWidth()/3); target.y += game.getTrackTileSize()/2 - game.getTrackTileMargin() - self.getWidth()/3; // nextWaypointX -= cornerTileOffset; // nextWaypointY += cornerTileOffset; break; case LEFT_BOTTOM_CORNER: target.x += game.getTrackTileSize()/2 - game.getTrackTileMargin() - self.getWidth()/3; target.y -= (game.getTrackTileSize()/2 - game.getTrackTileMargin() - self.getWidth()/3); // nextWaypointX += cornerTileOffset; // nextWaypointY -= cornerTileOffset; break; case RIGHT_BOTTOM_CORNER: target.x -= (game.getTrackTileSize()/2 - game.getTrackTileMargin() - self.getWidth()/3); target.y -= (game.getTrackTileSize()/2 - game.getTrackTileMargin() - self.getWidth()/3); // nextWaypointX -= cornerTileOffset; // nextWaypointY -= cornerTileOffset; break; case RIGHT_HEADED_T: break; case LEFT_HEADED_T: break; case TOP_HEADED_T: break; case BOTTOM_HEADED_T: break; case CROSSROADS: break; default: break; } // } double angleToWaypoint = self.getAngleTo(target.x, target.y); double speedModule = hypot(self.getSpeedX(), self.getSpeedY()); move.setWheelTurn(angleToWaypoint * 100. / PI); move.setEnginePower(1.); if (speedModule != prevSpeed) { stats << speedModule << endl; } prevSpeed = speedModule; if (speedModule * speedModule * abs(angleToWaypoint) > 2.5 * 2.5 * PI || speedModule > 30 ) { move.setBrake(true); } }
void GaussSeidelRB::Compute(Grid& sol, Grid& rhs) { const Stencil& mat = MG::GetDiscretization()->GetStencil(); const vmg_float prefactor_inv = 1.0 / MG::GetDiscretization()->OperatorPrefactor(sol); const vmg_float diag_inv = 1.0 / mat.GetDiag(); const int off = rhs.Global().LocalBegin().Sum() - rhs.Local().HaloSize1().Sum(); const LocalIndices& local = rhs.Local(); Comm& comm = *MG::GetComm(); /* * Compute first halfstep */ // Start asynchronous communication comm.CommToGhostsAsyncStart(sol); // Smooth part not depending on ghost cells ComputePartial(sol, rhs, mat, local.Begin()+1, local.End()-1, prefactor_inv, diag_inv, off+1); // Finish asynchronous communication comm.CommToGhostsAsyncFinish(sol); /* * Smooth near boundary cells */ ComputePartial(sol, rhs, mat, local.Begin(), Index(local.Begin().X()+1, local.End().Y(), local.End().Z()), prefactor_inv, diag_inv, off+1); ComputePartial(sol, rhs, mat, Index(local.End().X()-1, local.Begin().Y(), local.Begin().Z()), local.End(), prefactor_inv, diag_inv, off+1); ComputePartial(sol, rhs, mat, Index(local.Begin().X()+1, local.Begin().Y(), local.Begin().Z()), Index(local.End().X()-1, local.Begin().Y()+1, local.End().Z()), prefactor_inv, diag_inv, off+1); ComputePartial(sol, rhs, mat, Index(local.Begin().X()+1, local.End().Y()-1, local.Begin().Z()), Index(local.End().X()-1, local.End().Y(), local.End().Z()), prefactor_inv, diag_inv, off+1); ComputePartial(sol, rhs, mat, Index(local.Begin().X()+1, local.Begin().Y()+1, local.Begin().Z()), Index(local.End().X()-1, local.End().Y()-1, local.Begin().Z()+1), prefactor_inv, diag_inv, off+1); ComputePartial(sol, rhs, mat, Index(local.Begin().X()+1, local.Begin().Y()+1, local.End().Z()-1), Index(local.End().X()-1, local.End().Y()-1, local.End().Z()), prefactor_inv, diag_inv, off+1); /* * Compute second halfstep */ // Start asynchronous communication comm.CommToGhostsAsyncStart(sol); // Smooth part not depending on ghost cells ComputePartial(sol, rhs, mat, local.Begin()+1, local.End()-1, prefactor_inv, diag_inv, off); // Finish asynchronous communication comm.CommToGhostsAsyncFinish(sol); /* * Smooth near boundary cells */ ComputePartial(sol, rhs, mat, local.Begin(), Index(local.Begin().X()+1, local.End().Y(), local.End().Z()), prefactor_inv, diag_inv, off); ComputePartial(sol, rhs, mat, Index(local.End().X()-1, local.Begin().Y(), local.Begin().Z()), local.End(), prefactor_inv, diag_inv, off); ComputePartial(sol, rhs, mat, Index(local.Begin().X()+1, local.Begin().Y(), local.Begin().Z()), Index(local.End().X()-1, local.Begin().Y()+1, local.End().Z()), prefactor_inv, diag_inv, off); ComputePartial(sol, rhs, mat, Index(local.Begin().X()+1, local.End().Y()-1, local.Begin().Z()), Index(local.End().X()-1, local.End().Y(), local.End().Z()), prefactor_inv, diag_inv, off); ComputePartial(sol, rhs, mat, Index(local.Begin().X()+1, local.Begin().Y()+1, local.Begin().Z()), Index(local.End().X()-1, local.End().Y()-1, local.Begin().Z()+1), prefactor_inv, diag_inv, off); ComputePartial(sol, rhs, mat, Index(local.Begin().X()+1, local.Begin().Y()+1, local.End().Z()-1), Index(local.End().X()-1, local.End().Y()-1, local.End().Z()), prefactor_inv, diag_inv, off); }
void TestCholesky ( bool testCorrectness, bool pivot, bool unblocked, bool print, bool printDiag, UpperOrLower uplo, Int m, const Grid& g ) { DistMatrix<F> A(g), AOrig(g); DistMatrix<Int,UPerm,STAR> pPerm(g); HermitianUniformSpectrum( A, m, 1e-9, 10 ); if( testCorrectness ) { if( g.Rank() == 0 ) { cout << " Making copy of original matrix..."; cout.flush(); } AOrig = A; if( g.Rank() == 0 ) cout << "DONE" << endl; } if( print ) Print( A, "A" ); if( g.Rank() == 0 ) { cout << " Starting Cholesky factorization..."; cout.flush(); } mpi::Barrier( g.Comm() ); const double startTime = mpi::Time(); if( pivot ) { if( unblocked ) { if( uplo == LOWER ) cholesky::LUnblockedPivoted( A, pPerm ); else cholesky::UUnblockedPivoted( A, pPerm ); } else Cholesky( uplo, A, pPerm ); } else Cholesky( uplo, A ); mpi::Barrier( g.Comm() ); const double runTime = mpi::Time() - startTime; const double realGFlops = 1./3.*Pow(double(m),3.)/(1.e9*runTime); const double gFlops = ( IsComplex<F>::val ? 4*realGFlops : realGFlops ); if( g.Rank() == 0 ) { cout << "DONE.\n" << " Time = " << runTime << " seconds. GFlops = " << gFlops << endl; } if( print ) { Print( A, "A after factorization" ); if( pivot ) Print( pPerm, "pPerm" ); } if( printDiag ) Print( A.GetRealPartOfDiagonal(), "diag(A)" ); if( testCorrectness ) TestCorrectness( pivot, uplo, A, pPerm, AOrig ); }
void Turn(Player & player1, Grid & newgrid, Playerslist & list, ofstream &fout, int turn = -1, int p = 0) { if(player1.alive == false) { cout << player1.Getname() << " is dead." << endl; return; } char player_type = player1.Get_type(); int AP = 5; string verb, noun, s; cout << endl << endl << player1.Getname(); switch (player_type) { case 's': cout << "(me)" << endl; break; case 'f': cout << "(friend)" << endl; break; case 'e': cout << "(enemy)" << endl; break; default: cout << "invalid playertype" << endl; break; } cout << "Turn " << turn << endl << endl; //player2 string Result; ostringstream convert; convert << turn; Result = convert.str(); fstream f2in; fstream f3in; f2in.open("/Users/laria/Documents/c++/rpg/rpg/f" + Result + ".txt"); f3in.open("/Users/laria/Documents/c++/rpg/rpg/e" + Result + ".txt"); while(AP > 0) { player1.Set_x(player1.activeroom->Get_xcoord()); player1.Set_y(player1.activeroom->Get_ycoord()); if(newgrid.Search_Inv(player1.Getname(), player1.Get_x(), player1.Get_y()) == false) { newgrid.Add_Inv(player1, player1.Get_x(), player1.Get_y()); } describe_start: cout << endl; if(player_type == 's') { player1.activeroom->Descrip(); newgrid.Describe_inv(player1.Get_x(), player1.Get_y()); } action_start: //cout << list.Get("player3").alive; if(AP < 1) break; if(player_type == 's') cout << "Action points: " << AP << endl; if (player_type == 's') { getline(cin, s, '\n'); fout.open("/Users/laria/Documents/c++/rpg/rpg/output.txt"); fout << s; fout.close(); fstream fin; fin.open("/Users/laria/Documents/c++/rpg/rpg/output.txt"); fin>>verb>>noun; fin.close(); } else if (p == 2)
void TestSyrk ( UpperOrLower uplo, Orientation orientation, Int m, Int k, T alpha, T beta, const Grid& g, bool print, bool correctness, Int colAlignA=0, Int rowAlignA=0, Int colAlignC=0, Int rowAlignC=0, bool contigA=true, bool contigC=true ) { DistMatrix<T> A(g), C(g); A.Align( colAlignA, rowAlignA ); C.Align( colAlignC, rowAlignC ); if( orientation == NORMAL ) { if( !contigA ) { A.Resize( m, k ); A.Resize( m, k, 2*A.LDim() ); } Uniform( A, m, k ); } else { if( !contigA ) { A.Resize( k, m ); A.Resize( k, m, 2*A.LDim() ); } Uniform( A, k, m ); } if( !contigC ) { C.Resize( m, m ); C.Resize( m, m, 2*C.LDim() ); } Uniform( C, m, m ); MakeTrapezoidal( uplo, C ); auto COrig = C; if( print ) { Print( A, "A" ); Print( C, "C" ); } if( g.Rank() == 0 ) { cout << " Starting Syrk..."; cout.flush(); } mpi::Barrier( g.Comm() ); const double startTime = mpi::Time(); Syrk( uplo, orientation, alpha, A, beta, C ); mpi::Barrier( g.Comm() ); const double runTime = mpi::Time() - startTime; const double realGFlops = double(m)*double(m)*double(k)/(1.e9*runTime); const double gFlops = ( IsComplex<T>::value ? 4*realGFlops : realGFlops ); if( g.Rank() == 0 ) { cout << "DONE. " << endl << " Time = " << runTime << " seconds. GFlops = " << gFlops << endl; } if( print ) { ostringstream msg; if( orientation == NORMAL ) msg << "C := " << alpha << " A A' + " << beta << " C"; else msg << "C := " << alpha << " A' A + " << beta << " C"; Print( C, msg.str() ); } if( correctness ) TestCorrectness ( uplo, orientation, alpha, A, beta, COrig, C, print ); }
//-------------------------------------------------------------- void init_geostat_stuff(char *argv[]){ /* * * Grilla 1 grande: Nx,ny,nz: 20 x 30 x 12 Xmn,ymn,zmn: -180, -280, 6 Xsiz,ysiz,zsiz: 40 x 40 x 12 Grilla 2 grande: Nx,ny,nz: 40 x 60 x 12 Xmn,ymn,zmn: -190, -290, 6 Xsiz,ysiz,zsiz: 20 x 20 x 12 Grilla 3 grande: Nx,ny,nz: 80 x 120 x 12 Xmn,ymn,zmn: -195, -295, 6 Xsiz,ysiz,zsiz: 10 x 10 x 12 Grilla 1chica: Nx,ny,nz: 20 x 30 x 12 Xmn,ymn,zmn: 152.5, 227.5, 6 Xsiz,ysiz,zsiz: 5 x 5 x 12 Grilla 2 chica: Nx,ny,nz: 40 x 60 x 12 Xmn,ymn,zmn: 151.25, 226.25, 6 Xsiz,ysiz,zsiz: 2.5 x 2.5 x 12 Grilla 3 chica: Nx,ny,nz: 80 x 120 x 12 Xmn,ymn,zmn: 150.625, 225.625, 6 Xsiz,ysiz,zsiz: 1.25 x 1.25 x 12 * * */ //Grid grid = Grid(); grid = Grid(); // Grilla 1 grande grid.nodes[0] = 20; // nx grid.nodes[1] = 30; // ny grid.nodes[2] = 12; // nz grid.start[0] = -180.0; // xmn grid.start[1] = -280.0; // ymn grid.start[2] = 6; // zmn grid.size[0] = 40.0; // xsiz grid.size[1] = 40.0; // ysiz grid.size[2] = 12; // zsiz ////gridSize=7200, inputSize=2376, total=9576 ////gridSize=7200, inputSize=2327, total=9527 <- deleted_rows // Grilla 2 grande //grid.nodes[0] = 40; // nx //grid.nodes[1] = 60; // ny //grid.nodes[2] = 12; // nz //grid.start[0] = -190.0; // xmn //grid.start[1] = -290.0; // ymn //grid.start[2] = 6; // zmn //grid.size[0] = 20.0; // xsiz //grid.size[1] = 20.0; // ysiz //grid.size[2] = 12; // zsiz ////gridSize=28800, inputSize=2376, total=31176 // // Grilla 3 grande // grid.nodes[0] = 80; // nx // grid.nodes[1] = 120; // ny // grid.nodes[2] = 12; // nz // grid.start[0] = -195.0; // xmn // grid.start[1] = -295.0; // ymn // grid.start[2] = 6; // zmn // grid.size[0] = 10.0; // xsiz // grid.size[1] = 10.0; // ysiz // grid.size[2] = 12; // zsiz // //gridSize=115200, inputSize=2376, total=117576 // //gridSize=115200, inputSize=2327, total=117527 nscore // Grilla 2 chica //grid.nodes[0] = 40; // nx //grid.nodes[1] = 60; // ny //grid.nodes[2] = 12; // nz //grid.start[0] = 151.25; // xmn //grid.start[1] = 226.25; // ymn //grid.start[2] = 6; // zmn //grid.size[0] = 2.5; // xsiz //grid.size[1] = 2.5; // ysiz //grid.size[2] = 12; // zsiz ////gridSize=28800, inputSize=2376, total=31176 //gridSize=28800, inputSize=2327, total=31127 nscore // Grilla 3 chica //grid.nodes[0] = 80; // nx //grid.nodes[1] = 120; // ny //grid.nodes[2] = 12; // nz //grid.start[0] = 150.625; // xmn //grid.start[1] = 225.625; // ymn //grid.start[2] = 6; // zmn //grid.size[0] = 1.25; // xsiz //grid.size[1] = 1.25; // ysiz //grid.size[2] = 12; // zsiz ////gridSize=115200, inputSize=2376, total=117576 //VariographicModel vm = VariographicModel(); vm = VariographicModel(); vm.nuggetEffect = 0.1; st = new VariographicModelStructure(); st->angle[0] = 0; st->angle[1] = 0; st->angle[2] = 0; st->range[0] = 100; st->range[1] = 100; st->range[2] = 100; st->sill = 0.9; st->type = VariographicModelStructure::SphericalModel; vm.size = 1; vm.structures = new VariographicModelStructure*[1]; vm.structures[0] = st; vm.setup(); //0.1 Pepa + 0.9 Esférico (100,100,100) //double **inputPoints; //double *inputValues; //int gridSize = grid.length(); gridSize = grid.length(); //int inputSize; char *inputFile = argv[1] ;//"/home/exequiel/workspace/PGSL-lib/data/muestras.dat"; //char *outputFile = argv[2] ;//"/home/exequiel/Projects/alges/oscar_peredo/covamatrix-dense.txt"; load(inputFile,&inputPoints,&inputValues,0,1,2,3,0,1e100, &inputSize); //FILE *fout = fopen(outputFile,"w"); //FILE *fout = stdout; printf("gridSize=%d, inputSize=%d, total=%d\n",gridSize,inputSize,gridSize+inputSize); //double * pi; //double * pj; //double cmax; //double cova; cmax = vm.nuggetEffect; for (int i = 0; i < vm.size; i++) { cmax += vm.structures[i]->sill; } }
int main(int argc, char** argv) { TimerList tm; tm["total"] = new Timer("[Main] Total runtime for this proc"); tm["grid"] = new Timer("[Main] Grid generation"); tm["stencils"] = new Timer("[Main] Stencil generation"); tm["settings"] = new Timer("[Main] Load settings"); tm["decompose"] = new Timer("[Main] Decompose domain"); tm["consolidate"] = new Timer("[Main] Consolidate subdomain solutions"); tm["updates"] = new Timer("[Main] Broadcast solution updates"); tm["send"] = new Timer("[Main] Send subdomains to other processors (master only)"); tm["receive"] = new Timer("[Main] Receive subdomain from master (clients only)"); tm["timestep"] = new Timer("[Main] Advance One Timestep"); tm["tests"] = new Timer("[Main] Test stencil weights"); tm["weights"] = new Timer("[Main] Compute all stencils weights"); tm["oneWeight"] = new Timer("[Main] Compute single stencil weights"); tm["heat_init"] = new Timer("[Main] Initialize heat"); // grid should only be valid instance for MASTER Grid* grid = NULL; Domain* subdomain; tm["total"]->start(); Communicator* comm_unit = new Communicator(argc, argv); cout << " Got Rank: " << comm_unit->getRank() << endl; cout << " Got Size: " << comm_unit->getSize() << endl; tm["settings"]->start(); ProjectSettings* settings = new ProjectSettings(argc, argv, comm_unit->getRank()); int dim = settings->GetSettingAs<int>("DIMENSION", ProjectSettings::required); //----------------- fillGlobalProjectSettings(dim, settings); //----------------- int max_num_iters = settings->GetSettingAs<int>("MAX_NUM_ITERS", ProjectSettings::required); double max_global_rel_error = settings->GetSettingAs<double>("MAX_GLOBAL_REL_ERROR", ProjectSettings::optional, "1e-1"); double max_local_rel_error = settings->GetSettingAs<double>("MAX_LOCAL_REL_ERROR", ProjectSettings::optional, "1e-1"); int use_gpu = settings->GetSettingAs<int>("USE_GPU", ProjectSettings::optional, "1"); int local_sol_dump_frequency = settings->GetSettingAs<int>("LOCAL_SOL_DUMP_FREQUENCY", ProjectSettings::optional, "100"); int global_sol_dump_frequency = settings->GetSettingAs<int>("GLOBAL_SOL_DUMP_FREQUENCY", ProjectSettings::optional, "200"); int prompt_to_continue = settings->GetSettingAs<int>("PROMPT_TO_CONTINUE", ProjectSettings::optional, "0"); int debug = settings->GetSettingAs<int>("DEBUG", ProjectSettings::optional, "0"); double start_time = settings->GetSettingAs<double>("START_TIME", ProjectSettings::optional, "0.0"); double end_time = settings->GetSettingAs<double>("END_TIME", ProjectSettings::optional, "1.0"); double dt = settings->GetSettingAs<double>("DT", ProjectSettings::optional, "1e-5"); int timescheme = settings->GetSettingAs<int>("TIME_SCHEME", ProjectSettings::optional, "1"); int weight_method = settings->GetSettingAs<int>("WEIGHT_METHOD", ProjectSettings::optional, "1"); int compute_eigenvalues = settings->GetSettingAs<int>("DERIVATIVE_EIGENVALUE_TEST", ProjectSettings::optional, "0"); int use_eigen_dt = settings->GetSettingAs<int>("USE_EIGEN_DT", ProjectSettings::optional, "1"); if (comm_unit->isMaster()) { int ns_nx = settings->GetSettingAs<int>("NS_NB_X", ProjectSettings::optional, "10"); int ns_ny = settings->GetSettingAs<int>("NS_NB_Y", ProjectSettings::optional, "10"); int ns_nz = settings->GetSettingAs<int>("NS_NB_Z", ProjectSettings::optional, "10"); int stencil_size = settings->GetSettingAs<int>("STENCIL_SIZE", ProjectSettings::required); tm["settings"]->stop(); grid = getGrid(dim); grid->setMaxStencilSize(stencil_size); Grid::GridLoadErrType err = grid->loadFromFile(); if (err == Grid::NO_GRID_FILES) { printf("************** Generating new Grid **************\n"); //grid->setSortBoundaryNodes(true); // grid->setSortBoundaryNodes(true); tm["grid"]->start(); grid->generate(); tm["grid"]->stop(); grid->writeToFile(); } if ((err == Grid::NO_GRID_FILES) || (err == Grid::NO_STENCIL_FILES)) { std::cout << "Generating stencils files\n"; tm["stencils"]->start(); grid->setNSHashDims(ns_nx, ns_ny, ns_nz); // grid->generateStencils(Grid::ST_BRUTE_FORCE); // DEFINTELY: exact grid->generateStencils(Grid::ST_KDTREE); // MIGHT BE: approximate // grid->generateStencils(Grid::ST_HASH); tm["stencils"]->stop(); grid->writeToFile(); tm.writeToFile("gridgen_timer_log"); } int x_subdivisions = comm_unit->getSize(); // reduce this to impact y dimension as well int y_subdivisions = (comm_unit->getSize() - x_subdivisions) + 1; // TODO: load subdomain from disk // Construct a new domain given a grid. // TODO: avoid filling sets Q, B, etc; just think of it as a copy constructor for a grid Domain* original_domain = new Domain(dim, grid, comm_unit->getSize()); // pre allocate pointers to all of the subdivisions std::vector<Domain*> subdomain_list(x_subdivisions*y_subdivisions); // allocate and fill in details on subdivisions std::cout << "Generating subdomains\n"; tm["decompose"]->start(); //original_domain->printVerboseDependencyGraph(); original_domain->generateDecomposition(subdomain_list, x_subdivisions, y_subdivisions); tm["decompose"]->stop(); tm["send"]->start(); subdomain = subdomain_list[0]; for (int i = 1; i < comm_unit->getSize(); i++) { std::cout << "Sending subdomain[" << i << "]\n"; comm_unit->sendObject(subdomain_list[i], i); } tm["send"]->stop(); printf("----------------------\nEND MASTER ONLY\n----------------------\n\n\n"); } else { tm["settings"]->stop(); cout << "MPI RANK " << comm_unit->getRank() << ": waiting to receive subdomain" << endl; tm["receive"]->start(); subdomain = new Domain(); // EMPTY object that will be filled by MPI comm_unit->receiveObject(subdomain, 0); // Receive from CPU (0) tm["receive"]->stop(); } comm_unit->barrier(); if (debug) { subdomain->printVerboseDependencyGraph(); subdomain->printNodeList("All Centers Needed by This Process"); printf("CHECKING STENCILS: "); for (int irbf = 0; irbf < (int)subdomain->getStencilsSize(); irbf++) { // printf("Stencil[%d] = ", irbf); StencilType& s = subdomain->getStencil(irbf); if (irbf == s[0]) { // printf("PASS\n"); // subdomain->printStencil(s, "S"); } else { printf("FAIL on stencil %d\n", irbf); exit(EXIT_FAILURE); } } printf("OK\n"); } RBFFD* der; if (use_gpu) { der = new RBFFD_CL(RBFFD::LAPL | RBFFD::X | RBFFD::Y | RBFFD::Z, subdomain, dim, comm_unit->getRank()); } else { der = new RBFFD(RBFFD::LAPL | RBFFD::X | RBFFD::Y | RBFFD::Z, subdomain, dim, comm_unit->getRank()); } int use_var_eps = settings->GetSettingAs<int>("USE_VAR_EPSILON", ProjectSettings::optional, "0"); if (use_var_eps) { double alpha = settings->GetSettingAs<double>("VAR_EPSILON_ALPHA", ProjectSettings::optional, "1.0"); double beta = settings->GetSettingAs<double>("VAR_EPSILON_BETA", ProjectSettings::optional, "1.0"); //der->setVariableEpsilon(subdomain->getStencilRadii(), subdomain->getStencils(), alpha, beta); der->setVariableEpsilon(alpha, beta); } else { double epsilon = settings->GetSettingAs<double>("EPSILON", ProjectSettings::required); der->setEpsilon(epsilon); } #if 0 der->setWeightType(RBFFD::ContourSVD); der->setWeightType(RBFFD::Direct); #else der->setWeightType((RBFFD::WeightType)weight_method); #endif // Try loading all the weight files int err = der->loadFromFile(RBFFD::X); err += der->loadFromFile(RBFFD::Y); err += der->loadFromFile(RBFFD::Z); err += der->loadFromFile(RBFFD::LAPL); if (err) { printf("start computing weights\n"); tm["weights"]->start(); // NOTE: good test for Direct vs Contour // Grid 11x11, vareps=0.05; Look at stencil 12. SHould have -100, 25, // 25, 25, 25 (i.e., -4,1,1,1,1) not sure why scaling is off. der->computeAllWeightsForAllStencils(); tm["weights"]->stop(); cout << "end computing weights" << endl; der->writeToFile(RBFFD::X); der->writeToFile(RBFFD::Y); der->writeToFile(RBFFD::Z); der->writeToFile(RBFFD::LAPL); cout << "end write weights to file" << endl; } if (settings->GetSettingAs<int>("RUN_DERIVATIVE_TESTS", ProjectSettings::optional, "1")) { bool weightsPreComputed = true; bool exitIfTestFailed = settings->GetSettingAs<int>("BREAK_ON_DERIVATIVE_TESTS", ProjectSettings::optional, "1"); tm["tests"]->start(); // The test class only computes weights if they havent been done already DerivativeTests* der_test = new DerivativeTests(dim, der, subdomain, weightsPreComputed); if (use_gpu) { // Applies weights on both GPU and CPU and compares results for the first 10 stencils der_test->compareGPUandCPUDerivs(10); } // Test approximations to derivatives of functions f(x,y,z) = 0, x, y, xy, etc. etc. der_test->testAllFunctions(exitIfTestFailed); // For now we can only test eigenvalues on an MPI size of 1 (we could distribute with Par-Eiegen solver) if (comm_unit->getSize() == 1) { if (compute_eigenvalues) { // FIXME: why does this happen? Perhaps because X Y and Z are unidirectional? // Test X and 4 eigenvalues are > 0 // Test Y and 30 are > 0 // Test Z and 36 are > 0 // NOTE: the 0 here implies we compute the eigenvalues but do not run the iterations of the random perturbation test der_test->testEigen(RBFFD::LAPL, 0); } } tm["tests"]->stop(); } // SOLVE HEAT EQUATION ExactSolution* exact = getExactSolution(dim); TimeDependentPDE* pde; tm["heat_init"]->start(); // We need to provide comm_unit to pass ghost node info #if 0 if (use_gpu) { pde = new HeatPDE(subdomain, der, comm_unit, true); } else #endif { // Implies initial conditions are generated // true here indicates the weights are computed. pde = new HeatPDE(subdomain, der, comm_unit, uniformDiffusion, true); } pde->setStartEndTime(start_time, end_time); pde->fillInitialConditions(exact); // Broadcast updates for timestep, initial conditions for ghost nodes, etc. tm["updates"]->start(); comm_unit->broadcastObjectUpdates(pde); comm_unit->barrier(); tm["updates"]->stop(); tm["heat_init"]->stop(); //TODO: pde->setRelErrTol(max_global_rel_error); // Setup a logging class that will monitor our iteration and dump intermediate files #if USE_VTK // TODO: update VtuPDEWriter for the new PDE classes PDEWriter* writer = new VtuPDEWriter(subdomain, pde, comm_unit, local_sol_dump_frequency, global_sol_dump_frequency); #else PDEWriter* writer = new PDEWriter(subdomain, pde, comm_unit, local_sol_dump_frequency, global_sol_dump_frequency); #endif // Test DT: // 1) get the minimum avg stencil radius (for stencil area--i.e., dx^2) double avgdx = 1000.; std::vector<StencilType>& sten = subdomain->getStencils(); for (size_t i=0; i < sten.size(); i++) { double dx = subdomain->getStencilRadius(i); if (dx < avgdx) { avgdx = dx; } } // Laplacian = d^2/dx^2 double sten_area = avgdx*avgdx; // Not sure where Gordon came up with this parameter. // for second centered difference and euler time we have nu = 0.5 double nu = 0.1; // dt <= nu/dx^2 // is valid for stability in some FD schemes. double max_dt = nu*(sten_area); printf("dt = %f (max_dt = %f; 0.5dx^2 = %f)\n", dt, max_dt, 0.5*sten_area); // This appears to be consistent with Chinchipatnam2006 (Thesis) // TODO: get more details on CFL for RBFFD // note: checking stability only works if we have all weights for all // nodes, so we dont do it in parallel if (compute_eigenvalues && (comm_unit->getSize() == 1)) { RBFFD::EigenvalueOutput eigs = der->getEigenvalues(); max_dt = 2. / eigs.max_neg_eig; printf("Suggested max_dt based on eigenvalues (2/lambda_max)= %f\n", max_dt); // CFL condition: if (dt > max_dt) { std::cout << "WARNING! your choice of timestep (" << dt << ") is TOO LARGE for to maintain stability of system. According to eigenvalues, it must be less than " << max_dt << std::endl; if (use_eigen_dt) { dt = max_dt; } else { //exit(EXIT_FAILURE); } } } std::cout << "[MAIN] ********* USING TIMESTEP dt=" << dt << " ********** " << std::endl; // subdomain->printCenterMemberships(subdomain->G, "G = " ); //subdomain->printBoundaryIndices("INDICES OF GLOBAL BOUNDARY NODES: "); int iter; int num_iters = (int) ((end_time - start_time) / dt); std::cout << "NUM_ITERS = " << num_iters << std::endl; for (iter = 0; iter < num_iters && iter < max_num_iters; iter++) { writer->update(iter); #if 0 char label[256]; sprintf(label, "LOCAL INPUT SOLUTION [local_indx (global_indx)] FOR ITERATION %d", iter); pde->printSolution(label); #endif tm["timestep"]->start(); pde->advance((TimeDependentPDE::TimeScheme)timescheme, dt); tm["timestep"]->stop(); // This just double checks that all procs have ghost node info. // pde->advance(..) should broadcast intermediate updates as needed, // but updated solution. tm["updates"]->start(); comm_unit->broadcastObjectUpdates(pde); comm_unit->barrier(); tm["updates"]->stop(); if (!(iter % local_sol_dump_frequency)) { std::cout << "\n*********** Rank " << comm_unit->getRank() << " Local Solution [ Iteration: " << iter << " (t = " << pde->getTime() << ") ] *************" << endl; pde->checkLocalError(exact, max_local_rel_error); } if (!(iter % global_sol_dump_frequency)) { tm["consolidate"]->start(); comm_unit->consolidateObjects(pde); comm_unit->barrier(); tm["consolidate"]->stop(); if (comm_unit->isMaster()) { std::cout << "\n*********** Global Solution [ Iteration: " << iter << " (t = " << pde->getTime() << ") ] *************" << endl; pde->checkGlobalError(exact, grid, max_global_rel_error); } } #if 0 sprintf(label, "LOCAL UPDATED SOLUTION [local_indx (global_indx)] AFTER %d ITERATIONS", iter+1); pde->printSolution(label); #endif // double nrm = pde->maxNorm(); if (prompt_to_continue && comm_unit->isMaster()) { std::string buf; cout << "Press [Enter] to continue" << std::endl; cin.get(); } } #if 1 printf("after heat\n"); // NOTE: all local subdomains have a U_G solution which is consolidated // into the MASTER process "global_U_G" solution. tm["consolidate"]->start(); comm_unit->consolidateObjects(pde); comm_unit->barrier(); tm["consolidate"]->stop(); // subdomain->writeGlobalSolutionToFile(-1); std::cout << "Checking Solution on Master\n"; if (comm_unit->getRank() == 0) { pde->writeGlobalGridAndSolutionToFile(grid->getNodeList(), (char*) "FINAL_SOLUTION.txt"); #if 0 // NOTE: the final solution is assembled, but we have to use the // GLOBAL node list instead of a local subdomain node list cout << "FINAL ITER: " << iter << endl; std::vector<double> final_sol(grid->getNodeListSize()); ifstream fin; fin.open("FINAL_SOLUTION.txt"); int count = 0; for (int count = 0; count < final_sol.size(); count++) { Vec3 node; double val; fin >> node[0] >> node[1] >> node[2] >> val; if (fin.good()) { final_sol[count] = val; // std::cout << "Read: " << node << ", " << final_sol[count] << std::endl; } } fin.close(); #endif std::cout << "============== Verifying Accuracy of Final Solution =============\n"; pde->checkGlobalError(exact, grid, max_global_rel_error); std::cout << "============== Solution Valid =============\n"; delete(grid); }
void phong( const Renderer& /*renderer*/, const Grid& grid, std::shared_ptr<Value> result, std::shared_ptr<Value> normal, std::shared_ptr<Value> view, std::shared_ptr<Value> power_value ) { REYES_ASSERT( result ); REYES_ASSERT( normal ); REYES_ASSERT( view ); REYES_ASSERT( power_value ); result->reset( TYPE_COLOR, STORAGE_VARYING, grid.size() ); result->zero(); std::shared_ptr<Value> P = grid.find_value( "P" ); REYES_ASSERT( P ); REYES_ASSERT( P->type() == TYPE_POINT ); REYES_ASSERT( P->storage() == STORAGE_VARYING ); REYES_ASSERT( P->size() == result->size() ); const vector<std::shared_ptr<Light> >& lights = grid.lights(); for ( vector<std::shared_ptr<Light> >::const_iterator i = lights.begin(); i != lights.end(); ++i ) { Light* light = i->get(); REYES_ASSERT( light ); vec3* colors = result->vec3_values(); const vec3* positions = P->vec3_values(); const vec3* normals = normal->vec3_values(); const vec3* views = view->vec3_values(); const float power = power_value->float_value(); const vec3* light_colors = light->color()->vec3_values(); const int size = result->size(); switch ( light->type() ) { case LIGHT_SOLAR_AXIS: case LIGHT_SOLAR_AXIS_ANGLE: { const vec3& light_direction = -light->position(); if ( light->angle() == 0.0f ) { const vec3 L = normalize( light_direction ); for ( int i = 0; i < size; ++i ) { const vec3 N = normalize( normals[i] ); if ( dot(N, L) >= 0.0f ) { const vec3& Cl = light_colors[i]; const vec3& V = views[i]; const vec3 R = -V - 2.0f * dot(-V, N) * N; colors[i] += Cl * powf( max(0.0f, dot(R, L)), power ); } } } else { const vec3 L = normalize( light_direction ); const vec3& light_axis = light->axis(); const float light_angle_cosine = cosf( light->angle() ); for ( int i = 0; i < size; ++i ) { const vec3 N = normalize( normals[i] ); if ( dot(N, L) >= 0.0f && dot(light_axis, -N) >= light_angle_cosine ) { const vec3& Cl = light_colors[i]; const vec3& V = views[i]; const vec3 R = -V - 2.0f * dot(-V, N) * N; colors[i] += Cl * powf( max(0.0f, dot(R, L)), power ); } } } break; } case LIGHT_ILLUMINATE: { const vec3& light_position = light->position(); for ( int i = 0; i < size; ++i ) { const vec3 L = normalize( light_position - positions[i] ); const vec3 N = normalize( normals[i] ); if ( dot(N, L) >= 0.0f ) { const vec3& Cl = light_colors[i]; const vec3& V = views[i]; const vec3 R = -V - 2.0f * dot(-V, N) * N; colors[i] += Cl * powf( max(0.0f, dot(R, L)), power ); } } break; } case LIGHT_ILLUMINATE_AXIS_ANGLE: { const vec3& light_position = light->position(); const vec3& light_axis = light->axis(); const float light_angle_cosine = cosf( light->angle() ); for ( int i = 0; i < size; ++i ) { const vec3 L = normalize( light_position - positions[i] ); const vec3 N = normalize( normals[i] ); if ( dot(N, L) >= 0.0f && dot(light_axis, -L) >= light_angle_cosine ) { const vec3& Cl = light_colors[i]; const vec3& V = views[i]; const vec3 R = -V - 2.0f * dot(-V, N) * N; colors[i] += Cl * powf( max(0.0f, dot(R, L)), power ); } } break; } default: break; } } }
int main(int argc, char** argv) { osg::ArgumentParser arguments(&argc,argv); osg::DisplaySettings::instance()->setMinimumNumStencilBits( 8 ); osgViewer::Viewer viewer(arguments); // load the .earth file from the command line. osg::Node* earthNode = MapNodeHelper().load( arguments, &viewer ); if (!earthNode) { OE_NOTICE << "Unable to load earth model." << std::endl; return 1; } MapNode* mapNode = MapNode::findMapNode( earthNode ); if ( !mapNode ) { OE_NOTICE << "Input file was not a .earth file" << std::endl; return 1; } earthNode->setNodeMask( 0x1 ); osgEarth::Util::EarthManipulator* earthManip = new EarthManipulator(); viewer.setCameraManipulator( earthManip ); osg::Group* root = new osg::Group(); root->addChild( earthNode ); //Create the MeasureToolHandler MeasureToolHandler* measureTool = new MeasureToolHandler(root, mapNode); measureTool->setIntersectionMask( 0x1 ); viewer.addEventHandler( measureTool ); //Create some controls to interact with the measuretool ControlCanvas* canvas = new ControlCanvas( &viewer ); root->addChild( canvas ); canvas->setNodeMask( 0x1 << 1 ); Grid* grid = new Grid(); grid->setBackColor(0,0,0,0.5); grid->setMargin( 10 ); grid->setPadding( 10 ); grid->setChildSpacing( 10 ); grid->setChildVertAlign( Control::ALIGN_CENTER ); grid->setAbsorbEvents( true ); grid->setVertAlign( Control::ALIGN_BOTTOM ); canvas->addControl( grid ); //Add a label to display the distance // Add a text label: grid->setControl( 0, 0, new LabelControl("Distance:") ); LabelControl* label = new LabelControl(); label->setFont( osgEarth::Registry::instance()->getDefaultFont() ); label->setFontSize( 24.0f ); label->setHorizAlign( Control::ALIGN_LEFT ); label->setText("click to measure"); grid->setControl( 1, 0, label ); //Add a callback to update the label when the distance changes measureTool->addEventHandler( new MyMeasureToolCallback(label) ); Style style = measureTool->getLineStyle(); style.getOrCreate<LineSymbol>()->stroke()->color() = Color::Red; style.getOrCreate<LineSymbol>()->stroke()->width() = 4.0f; measureTool->setLineStyle(style); //Add a checkbox to control if we are doing path based measurement or just point to point grid->setControl( 0, 1, new LabelControl("Path")); CheckBoxControl* checkBox = new CheckBoxControl(false); checkBox->setHorizAlign(Control::ALIGN_LEFT); checkBox->addEventHandler( new TogglePathHandler(measureTool)); grid->setControl( 1, 1, checkBox); //Add a toggle to set the mode of the measuring tool grid->setControl( 0, 2, new LabelControl("Great Circle")); CheckBoxControl* mode = new CheckBoxControl(true); mode->setHorizAlign(Control::ALIGN_LEFT); mode->addEventHandler( new ToggleModeHandler(measureTool)); grid->setControl( 1, 2, mode); //Add a mouse coords readout: LabelControl* mouseLabel = new LabelControl(); grid->setControl( 0, 3, new LabelControl("Mouse:")); grid->setControl( 1, 3, mouseLabel ); viewer.addEventHandler(new MouseCoordsTool(mapNode, mouseLabel) ); viewer.setSceneData( root ); // add some stock OSG handlers: viewer.addEventHandler(new osgViewer::StatsHandler()); viewer.addEventHandler(new osgViewer::WindowSizeHandler()); viewer.addEventHandler(new osgViewer::ThreadingHandler()); viewer.addEventHandler(new osgViewer::LODScaleHandler()); viewer.addEventHandler(new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet())); viewer.addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage())); return viewer.run(); }
void trace( const Renderer& /*renderer*/, const Grid& grid, std::shared_ptr<Value> result, std::shared_ptr<Value> /*point*/, std::shared_ptr<Value> /*reflection*/ ) { REYES_ASSERT( result ); result->reset( TYPE_COLOR, STORAGE_VARYING, grid.size() ); result->zero(); }
void QDesignerSharedSettings::setDefaultGrid(const Grid &grid) { m_settings->setValue(QLatin1String(defaultGridKey), grid.toVariantMap()); }
void diffuse( const Renderer& /*renderer*/, const Grid& grid, std::shared_ptr<Value> color, std::shared_ptr<Value> normal ) { REYES_ASSERT( color ); REYES_ASSERT( normal ); REYES_ASSERT( int(normal->size()) == grid.size() ); color->reset( TYPE_COLOR, STORAGE_VARYING, grid.size() ); color->zero(); std::shared_ptr<Value> P = grid.find_value( "P" ); REYES_ASSERT( P ); REYES_ASSERT( P->type() == TYPE_POINT ); REYES_ASSERT( P->storage() == STORAGE_VARYING ); REYES_ASSERT( P->size() == color->size() ); const vector<std::shared_ptr<Light> >& lights = grid.lights(); for ( vector<std::shared_ptr<Light> >::const_iterator i = lights.begin(); i != lights.end(); ++i ) { Light* light = i->get(); REYES_ASSERT( light ); if ( light->type() != LIGHT_AMBIENT ) { const std::shared_ptr<Value>& light_color = light->color(); REYES_ASSERT( light_color ); vec3* colors = color->vec3_values(); const vec3* positions = P->vec3_values(); const vec3* normals = normal->vec3_values(); const vec3* light_colors = light_color->vec3_values(); const int size = color->size(); switch ( light->type() ) { case LIGHT_SOLAR_AXIS: case LIGHT_SOLAR_AXIS_ANGLE: { const vec3& light_direction = -light->position(); if ( light->angle() == 0.0f ) { for ( int i = 0; i < size; ++i ) { const vec3& L = light_direction; const vec3& N = normals[i]; if ( dot(N, L) >= 0.0f ) { const vec3& Cl = light_colors[i]; colors[i] += Cl * dot( N, normalize(L) ); } } } else { const vec3& light_axis = light->axis(); const float light_angle_cosine = cosf( light->angle() ); for ( int i = 0; i < size; ++i ) { const vec3& L = light_direction; const vec3& N = normals[i]; if ( dot(N, L) >= 0.0f && dot(light_axis, -N) >= light_angle_cosine ) { const vec3& Cl = light_colors[i]; colors[i] += Cl * dot( N, normalize(L) ); } } } break; } case LIGHT_ILLUMINATE: { const vec3& light_position = light->position(); for ( int i = 0; i < size; ++i ) { const vec3 L = normalize( light_position - positions[i] ); const vec3& N = normals[i]; if ( dot(N, L) >= 0.0f ) { const vec3& Cl = light_colors[i]; colors[i] += Cl * dot( N, normalize(L) ); } } break; } case LIGHT_ILLUMINATE_AXIS_ANGLE: { const vec3& light_position = light->position(); const vec3& light_axis = light->axis(); const float light_angle_cosine = cosf( light->angle() ); for ( int i = 0; i < size; ++i ) { const vec3 L = normalize( light_position - positions[i] ); const vec3& N = normals[i]; if ( dot(N, L) >= 0.0f && dot(light_axis, -L) >= light_angle_cosine ) { const vec3& Cl = light_colors[i]; colors[i] += Cl * dot( N, L ); } } break; } default: break; } } } }
int main(int argc, char* argv[]) { cerr << "Lattice MBR Grid search" << endl; Grid grid; grid.addParam(lmbr_p, "-lmbr-p", 0.5); grid.addParam(lmbr_r, "-lmbr-r", 0.5); grid.addParam(lmbr_prune, "-lmbr-pruning-factor",30.0); grid.addParam(lmbr_scale, "-mbr-scale",1.0); grid.parseArgs(argc,argv); Parameter* params = new Parameter(); if (!params->LoadParam(argc,argv)) { params->Explain(); exit(1); } if (!StaticData::LoadDataStatic(params, argv[0])) { exit(1); } StaticData& staticData = const_cast<StaticData&>(StaticData::Instance()); staticData.SetUseLatticeMBR(true); IOWrapper* ioWrapper = IOWrapper::GetIOWrapper(staticData); if (!ioWrapper) { throw runtime_error("Failed to initialise IOWrapper"); } size_t nBestSize = staticData.GetMBRSize(); if (nBestSize <= 0) { throw new runtime_error("Non-positive size specified for n-best list"); } size_t lineCount = 0; InputType* source = NULL; const vector<float>& pgrid = grid.getGrid(lmbr_p); const vector<float>& rgrid = grid.getGrid(lmbr_r); const vector<float>& prune_grid = grid.getGrid(lmbr_prune); const vector<float>& scale_grid = grid.getGrid(lmbr_scale); while(ioWrapper->ReadInput(staticData.GetInputType(),source)) { ++lineCount; source->SetTranslationId(lineCount); Manager manager(*source, staticData.GetSearchAlgorithm()); manager.ProcessSentence(); TrellisPathList nBestList; manager.CalcNBest(nBestSize, nBestList,true); //grid search for (vector<float>::const_iterator pi = pgrid.begin(); pi != pgrid.end(); ++pi) { float p = *pi; staticData.SetLatticeMBRPrecision(p); for (vector<float>::const_iterator ri = rgrid.begin(); ri != rgrid.end(); ++ri) { float r = *ri; staticData.SetLatticeMBRPRatio(r); for (vector<float>::const_iterator prune_i = prune_grid.begin(); prune_i != prune_grid.end(); ++prune_i) { size_t prune = (size_t)(*prune_i); staticData.SetLatticeMBRPruningFactor(prune); for (vector<float>::const_iterator scale_i = scale_grid.begin(); scale_i != scale_grid.end(); ++scale_i) { float scale = *scale_i; staticData.SetMBRScale(scale); cout << lineCount << " ||| " << p << " " << r << " " << prune << " " << scale << " ||| "; vector<Word> mbrBestHypo = doLatticeMBR(manager,nBestList); ioWrapper->OutputBestHypo(mbrBestHypo, lineCount, staticData.GetReportSegmentation(), staticData.GetReportAllFactors(),cout); } } } } } }
int main(int argc, char** argv) { // allocate pager threads based on CPU configuration. int cores = Registry::capabilities().getNumProcessors(); osg::DisplaySettings::instance()->setNumOfDatabaseThreadsHint( osg::clampAbove(cores, 2) ); osg::DisplaySettings::instance()->setNumOfHttpDatabaseThreadsHint( osg::clampAbove(cores/2, 1) ); // parse the command line. osg::ArgumentParser arguments(&argc,argv); osgViewer::Viewer viewer(arguments); // set up the motion model. viewer.setCameraManipulator( new EarthManipulator() ); // simple UI. VBox* vbox = new VBox(); vbox->setMargin( 3 ); vbox->setChildSpacing( 5 ); vbox->setAbsorbEvents( true ); vbox->setHorizAlign( Control::ALIGN_RIGHT ); vbox->setVertAlign ( Control::ALIGN_BOTTOM ); // Control instructions: Grid* grid = vbox->addControl( new Grid() ); grid->setControl( 0, 0, new LabelControl("Pan:")); grid->setControl( 1, 0, new LabelControl("Left mouse")); grid->setControl( 0, 1, new LabelControl("Zoom:")); grid->setControl( 1, 1, new LabelControl("Right mouse / scroll")); grid->setControl( 0, 2, new LabelControl("Rotate:") ); grid->setControl( 1, 2, new LabelControl("Middle mouse")); grid->setControl( 0, 3, new LabelControl("Go to:")); grid->setControl( 1, 3, new LabelControl("Double-click")); ControlCanvas::get(&viewer)->addControl(vbox); // Load an earth file osg::Node* node = MapNodeHelper().load(arguments, &viewer); if ( !node ) return usage( "Failed to load earth file." ); viewer.setSceneData( node ); #ifdef Q_WS_X11 // required for multi-threaded viewer on linux: XInitThreads(); #endif QApplication app(argc, argv); QWidget* viewerWidget = new ViewerWidget( &viewer ); QMainWindow win; win.setWindowTitle( "osgEarth -- The #1 Open Source Terrain SDK for Mission-Critical Applications" ); win.setCentralWidget( viewerWidget ); win.setGeometry(100, 100, 1024, 800); win.statusBar()->showMessage(QString("osgEarth. Terrain on Demand. Copyright 2013 Pelican Mapping. Please visit http://osgearth.org")); win.show(); app.exec(); }
bool AI::constrant_check(Grid g, Cell c) { bool result = true; int i; int num = c.get_number(); int rw = c.get_row()-1; int cl = c.get_col()-1; int sq = c.get_square(); //Check that cell number is between 1-9 if (num < 1 || num > 9) { printf("The cell number is not between one and nine\n"); result = false; } if(result) printf("Number check successful\n"); //Check that the numbers in the Cell's row are different for (i = 0; i < COLS; i++) { Cell curr = g.get_cell(rw, i); if (c.get_number() == curr.get_number() && cl != i) { printf("Two Cells in row %d have the same number\n", rw+1); result = false; break; } } if (result) printf("Row check successful\n"); //Check that the numbers in the Cell's column are different for (i = 0; i < ROWS; i++) { Cell curr = g.get_cell(i, cl); if (c.get_number() == curr.get_number() && rw != i) { printf("Two Cells in column %d have the same number\n", cl+1); result = false; break; } } if (result) printf("Column check successful\n"); //Check that the numbers in the Cell's square are different int j; switch (sq) { case 1: i = 0; j = 0; break; case 2: i = 0; j = 3; break; case 3: i = 0; j = 6; break; case 4: i = 3; j = 0; break; case 5: i = 3; j = 3; break; case 6: i = 3; j = 6; break; case 7: i = 6; j = 0; break; case 8: i = 6; j = 3; break; case 9: i = 6; j = 6; break; } int i_to = i + 3; int j_to = j + 3; //printf("i: %d, j: %d\n", i, j); //printf("i_to: %d, j_to: %d\n", i_to, j_to); for (; i < i_to; i++) { for (j = j_to - 3; j < j_to; j++) { Cell curr = g.get_cell(i, j); //printf("square %d\n", curr.get_number()); if (c.get_number() == curr.get_number() && rw != i && cl != j) { printf("Two Cells in square %d have the same number\n", sq); result = false; break; } } } return result; }
void operator()( const Grid & grid, const unsigned dir, const bool begin, SurfaceMesh & surfaceMesh ) const { //! Sanity check of direction VERIFY_MSG( (dir < Grid::dim), "Input argument for direction wrong" ); //! Dimensions of the grid const MultiIndexType gridSizes = grid.gridSizes(); //! Multi-index component to compare with const int mIndexComp = ( begin == false ? 0 : gridSizes[dir]-1 ); //! Number of elements in the structured grid const std::size_t numElements = MultiIndex::length( gridSizes ); //! Number of elements on the requested surface const std::size_t numElementsOnSurface = numElements / gridSizes[ dir ]; //! Construct parametric geometry of the element const unsigned surfaceID = detail_::convertToSurfaceID<VolumeElement::shape>( dir, begin ); //! List of indices of the parameter space vertices which form the surface typename ParameterSurface::Surface parameterSurfaceIndices = ParameterSurface::surfaceTable[ surfaceID ]; //! Interpolation points of the surface shape function boost::array< typename SurfaceShapeFun::VecDim, SurfaceShapeFun::numFun> surfaceSupportPoints; SurfaceShapeFun::supportPoints( surfaceSupportPoints ); //! Vertices of the parameter volume boost::array< typename LinearVolumeFun::VecDim, LinearVolumeFun::numFun> volumeVertices; LinearVolumeFun::supportPoints( volumeVertices ); // --> Reorder for hiearchical ordering // Then, the object ParameterFaces< shape, dim-1> can be used and // ParamaterSurface discarded. //! Iterator to surface mesh elements typename SurfaceMesh::ElementPtrIter surfElemIter = surfaceMesh.elementsBegin(); //! Linear shape function on the surface simplex LinearSimplexFun linearSimplexFun; //! Hexahedra will have two triangles per face const unsigned numSurfElementsPerElement = detail_::NumSimplicesPerElementSurface<VolumeElement::shape>::value; //! Temporary storage of surface elements and nodes std::vector<SurfaceElement*> surfaceElements; surfaceElements.reserve( numElementsOnSurface * numSurfElementsPerElement ); std::vector<SurfaceNode*> surfaceNodes; //! node counter std::size_t nodeCtr = 0; //! Go through all elements for ( std::size_t e = 0; e < numElements; e ++ ) { //! Construct multi-index from linear counter const MultiIndexType eM = MultiIndex::wrap( e, gridSizes ); //! Check if on requested boundary surface const bool onBoundary = ( eM[ dir ] == mIndexComp ); //! If so, construct the surface element(s) if ( onBoundary ) { //! Get pointer to volume element VolumeElement * vep = grid.elementPtr( eM ); //! Go through elements on the surface of the volume element for ( unsigned se = 0; se < numSurfElementsPerElement; se ++ ) { //! Create new surface element SurfaceElement * surfElem = new SurfaceElement; //! Extract the surface simplex's vertices boost::array<unsigned, numSurfSimplexVertices> surfSimplex; detail_::ExtractSurfaceSimplex<VolumeElement::shape>()( parameterSurfaceIndices, se, surfSimplex ); //! Set volume element pointer surfElem -> setVolumeElementPointer( vep ); //! Access to surface elements geometry nodes typename SurfaceElement::NodePtrIter nodePtrIter = surfElem -> nodesBegin(); //! Go through the parameter points of the surface element typename SurfaceElement::ParamIter paramIter = surfElem -> parametricBegin(); typename SurfaceElement::ParamIter paramEnd = surfElem -> parametricEnd(); for ( unsigned p = 0; paramIter != paramEnd; ++paramIter, ++nodePtrIter, p++ ) { //! .. typename base::Vector<surfaceDim>::Type eta = surfaceSupportPoints[ p ]; typename LinearSimplexFun::FunArray phi; linearSimplexFun.evaluate( eta, phi ); typename base::Vector<volumeDim>::Type xi = base::constantVector<volumeDim>( 0. ); for ( unsigned s = 0; s < phi.size(); s ++ ) { xi += phi[s] * volumeVertices[ surfSimplex[s] ]; } *paramIter = xi; //! evaluate geometry at the parameter point const typename VolumeElement::Node::VecDim x = base::Geometry<VolumeElement>()( vep, xi ); //! convert to vector and pass to node std::vector<double> xV( x.size() ); for ( int d = 0; d < x.size(); d ++ ) xV[d] = x[d]; SurfaceNode * surfNode = new SurfaceNode; surfNode -> setX( xV.begin() ); surfNode -> setID( nodeCtr++ ); *nodePtrIter = surfNode; surfaceNodes.push_back( surfNode ); } // end loop over surface element's nodes //! Store element pointer surfaceElements.push_back( surfElem ); } // end loop over simplices per volume element } // end condition if volume element lies on requested bdry }// end loop over all volume elements surfaceMesh.allocate( surfaceNodes.size(), surfaceElements.size() ); std::copy( surfaceNodes.begin(), surfaceNodes.end(), surfaceMesh.nodesBegin() ); std::copy( surfaceElements.begin(), surfaceElements.end(), surfaceMesh.elementsBegin() ); return; }