Example #1
0
void
ObjectAccessor::AddCorpsesToGrid(GridPair const& gridpair,GridType& grid,Map* map)
{

#ifndef NOTSAFE_SEMAPHORE_OVERHANDLING
    HashMapHolder<Corpse>::ReadGuard g(HashMapHolder<Corpse>::GetLock());
#endif

    for(Player2CorpsesMapType::iterator iter = i_player2corpse.begin(); iter != i_player2corpse.end(); ++iter)
        if(iter->second->GetGrid() == gridpair)
    {
        // verify, if the corpse in our instance (add only corpses which are)
        if (map->Instanceable())
        {
            if (iter->second->GetInstanceId() == map->GetInstanceId())
            {
                grid.AddWorldObject(iter->second);
            }
        }
        else
        {
            grid.AddWorldObject(iter->second);
        }
    }
}
void GameController::readData(std::istream& input)
{
    BlockPairQueue nextBlocks;
    GridType myNewGrid;
    GridType opponentNewGrid;
    for (int i = 0; i < QUEUE_LENGTH; i++)
    {
        int colorA;
        int colorB;
        input >> colorA >> colorB; input.ignore();
        nextBlocks.push_back(std::make_pair(Block(colorA), Block(colorB)));
    }
    for (int i = 0; i < GRID_HEIGHT; i++)
    {
        std::string row;
        input >> row; input.ignore();
        myNewGrid.push_back(row);
    }
    for (int i = 0; i < GRID_HEIGHT; i++)
    {
        std::string row;
        input >> row; input.ignore();
        opponentNewGrid.push_back(row);
    }
    nextBlocks_ = nextBlocks;
    currentGrid_.reset(myNewGrid);
    opponentGrid_.reset(opponentNewGrid);
}
void fnAdvectSemiLagrange_time_fraction(FluidSolver* parent, FlagGrid& flags, MACGrid& vel, GridType& orig, int order, Real strength, Real time_fraction) {
        typedef typename GridType::BASETYPE T;
	
	Real dt = (time_fraction) * parent->getDt();
	std::cout << " time_fraction = " << time_fraction << std::endl ;
	std::cout << " dt = " << dt << std::endl ;
	bool levelset = orig.getType() & GridBase::TypeLevelset;

	// forward step
	GridType fwd(parent);
	SemiLagrange<T> (flags, vel, fwd, orig, dt, levelset);
	
	if (order == 1) {
		orig.swap(fwd);
	}
	else if (order == 2) { // MacCormack
		GridType bwd(parent);
		GridType newGrid(parent);
	
		// bwd <- backwards step
		SemiLagrange<T> (flags, vel, bwd, fwd, -dt, levelset);
		
		// newGrid <- compute correction
		MacCormackCorrect<T> (flags, newGrid, orig, fwd, bwd, strength, levelset);
		
		// clamp values
		MacCormackClamp<T> (flags, vel, newGrid, orig, fwd, dt);
		
		orig.swap(newGrid);
	}
}
  bool singleRPAJastrowBuilder::put(xmlNodePtr cur, int addOrbital)
    {
    MyName="Jep";
    string rpafunc="RPA";
    OhmmsAttributeSet a;
    a.add(MyName,"name");
    a.add(rpafunc,"function");
    a.put(cur);

    ParameterSet params;
    RealType Rs(-1.0);
    RealType Kc(-1.0);
    params.add(Rs,"rs","double");
    params.add(Kc,"kc","double");

    params.put(cur);
        
    if(Rs<0) {
        Rs=tlen;
    }

    if(Kc<0){ 
      Kc = 1e-6 ;
    };


    if (rpafunc=="RPA"){ 
      myHandler= new LRRPAHandlerTemp<EPRPABreakup<RealType>,LPQHIBasis>(targetPtcl,Kc);
      app_log()<<"  using e-p RPA"<<endl;
    }
    else if (rpafunc=="dRPA") {
      myHandler= new LRRPAHandlerTemp<derivEPRPABreakup<RealType>,LPQHIBasis>(targetPtcl,Kc);
      app_log()<<"  using e-p derivRPA"<<endl;
    }
    myHandler->Breakup(targetPtcl,Rs);
    
//     app_log() << "  Maximum K shell " << myHandler->MaxKshell << endl;
//     app_log() << "  Number of k vectors " << myHandler->Fk.size() << endl;
    
    
    //Add short range part
    Rcut = myHandler->get_rc()-0.1;
    GridType* myGrid = new GridType;
    int npts=static_cast<int>(Rcut/0.01)+1;
    myGrid->set(0,Rcut,npts);

      //create the numerical functor
    nfunc = new FuncType;
    SRA = new ShortRangePartAdapter<RealType>(myHandler);
    SRA->setRmax(Rcut);
    nfunc->initialize(SRA, myGrid);
    J1s = new JneType (*sourcePtcl,targetPtcl);
    for(int ig=0; ig<ng; ig++) {
      J1s->addFunc(ig,nfunc);
    }

    app_log()<<" Only Short range part of E-I RPA is implemented"<<endl;
    if (addOrbital) targetPsi.addOrbital(J1s,MyName);
    return true;
  }
Example #5
0
void ObjectAccessor::AddCorpsesToGrid(GridCoord const& gridpair, GridType& grid, Map* map)
{
    TRINITY_READ_GUARD(ACE_RW_Thread_Mutex, i_corpseLock);

    for (Player2CorpsesMapType::iterator iter = i_player2corpse.begin(); iter != i_player2corpse.end(); ++iter)
    {
        if (iter->second->IsInGrid())
        {
            //TODO: add this assert later
            //ASSERT(iter->second->GetGridCoord() == gridpair);
            continue;
        }

        if (iter->second->GetGridCoord() == gridpair)
        {
            // verify, if the corpse in our instance (add only corpses which are)
            if (map->Instanceable())
            {
                if (iter->second->GetInstanceId() == map->GetInstanceId())
                    grid.AddWorldObject(iter->second);
            }
            else
                grid.AddWorldObject(iter->second);
        }
    }
}
Example #6
0
void Camera::Event_AddedToWorld()
{
    GridType* grid = m_source->GetViewPoint().m_grid;
    MANGOS_ASSERT(grid);
    grid->AddWorldObject(this);

    UpdateVisibilityForOwner();
}
Example #7
0
void Camera::Event_AddedToWorld()
{
    if (!IsInitialized())
        ResetView();

    GridType* grid = GetBody()->GetViewPoint().m_grid;
    MANGOS_ASSERT(grid);
    grid->AddWorldObject(this);

    UpdateVisibilityForOwner();
}
Example #8
0
    void stepFinished(const GridType& grid, unsigned step, WriterEvent event)
    {
        avrgTemperature = 0;

        CoordBox<2> box = grid.boundingBox();
        for (CoordBox<2>::Iterator i = box.begin(); i != box.end(); ++i) {
            avrgTemperature += grid.get(*i).temperature;
        }

        avrgTemperature /= box.dimensions.prod();
        std::cout << "averageTemperature(" << step << ") = " << avrgTemperature << "\n";
    }
Example #9
0
void ObjectGridLoader::Load(GridType &grid)
{
    {
        TypeContainerVisitor<ObjectGridLoader, GridTypeMapContainer > loader(*this);
        grid.Visit(loader);
    }

    {
        ObjectWorldLoader wloader(*this);
        TypeContainerVisitor<ObjectWorldLoader, WorldTypeMapContainer > loader(wloader);
        grid.Visit(loader);
        i_corpses = wloader.i_corpses;
    }
}
Example #10
0
int main(int argc, const char **argv){
    if (argc != 3 && argc != 5){
        printf("Usage: prog sides num_blanks [wid hei]\n");
        return 1;
    }
    size_t blanks = atol(argv[2]);
    size_t sides = atol(argv[1]);
    size_t wid = DEFAULT_WIDTH;
    size_t hei = DEFAULT_HEIGHT;

    if (argc == 5){
        wid = atol(argv[3]);
        hei = atol(argv[4]);
    }

    sierp2d::Model<double, ModelType, GridType> model;
    for (int blank=0; blank < blanks; ++blank){
        model.points.push_back(sierp2d::Point<double>(wid/2, hei/2)); 
    }
    model.add_regular(wid, hei, sides);

    GridType * front = new GridType( {wid, hei} );
    GridType *  back = new GridType( {wid, hei} );
    GridType * temp = NULL;

    front->get_point({wid/2, hei/2}) = INITIAL;

    while (true){
        bool hit_max = model.next(*front, *back);
        if (hit_max) break;
        temp = back;
        back = front;
        front = temp;
    }
    temp = NULL;
    delete back;

    ModelType maxval = front->max();
    double scale = UIMAX(ModelType) / ((double)maxval);
    for (ModelType &val : *front){
        val *= scale;
    }
    front->invert();

    char file_name[255];
    sprintf(file_name, "out-%zu-%zu.png", blanks, sides);
    
    png::write(*front, file_name);
    delete front;
}
Example #11
0
void LoadHelper(CellGuidSet const& guid_set, CellPair& cell, GridRefManager<T>& /*m*/, uint32& count, Map* map, GridType& grid)
{
    BattleGround* bg = map->IsBattleGroundOrArena() ? ((BattleGroundMap*)map)->GetBG() : NULL;

    for (CellGuidSet::const_iterator i_guid = guid_set.begin(); i_guid != guid_set.end(); ++i_guid)
    {
        uint32 guid = *i_guid;

        T* obj = new T;
        // sLog.outString("DEBUG: LoadHelper from table: %s for (guid: %u) Loading",table,guid);
        if (!obj->LoadFromDB(guid, map))
        {
            delete obj;
            continue;
        }

        grid.AddGridObject(obj);

        addUnitState(obj, cell);
        obj->SetMap(map);
        obj->AddToWorld();
        if (obj->isActiveObject())
            map->AddToActive(obj);

        obj->GetViewPoint().Event_AddedToWorld(&grid);

        if (bg)
            bg->OnObjectDBLoad(obj);

        ++count;
    }
}
Example #12
0
void LoadHelper(CellCorpseSet const& cell_corpses, CellPair& cell, CorpseMapType& /*m*/, uint32& count, Map* map, GridType& grid)
{
    if (cell_corpses.empty())
        return;

    for (CellCorpseSet::const_iterator itr = cell_corpses.begin(); itr != cell_corpses.end(); ++itr)
    {
        if (itr->second != map->GetInstanceId())
            continue;

        uint32 player_lowguid = itr->first;

        Corpse* obj = sObjectAccessor.GetCorpseForPlayerGUID(ObjectGuid(HIGHGUID_PLAYER, player_lowguid));
        if (!obj)
            continue;

        grid.AddWorldObject(obj);

        addUnitState(obj, cell);
        obj->SetMap(map);
        obj->AddToWorld();
        if (obj->isActiveObject())
            map->AddToActive(obj);

        ++count;
    }
}
Example #13
0
void ObjectAccessor::AddCorpsesToGrid(GridPair const& gridpair,GridType& grid,Map* map)
{
    ACE_GUARD(LockType, g, i_corpseGuard);
    for (Player2CorpsesMapType::iterator iter = i_player2corpse.begin(); iter != i_player2corpse.end(); ++iter)
        if (iter->second->GetGrid()==gridpair)
    {
        // verify, if the corpse in our instance (add only corpses which are)
        if (map->Instanceable())
        {
            if (iter->second->GetInstanceId() == map->GetInstanceId())
                grid.AddWorldObject(iter->second);
        }
        else
            grid.AddWorldObject(iter->second);
    }
}
Example #14
0
/** main functio to optimize multiple contracted S orbitals
 */
  void GTO2Slater::optimize() {

    //construct one-dim grid
    double ri = 1e-5;
    double rf = 10.0;
    int npts = 101;
    string gridType("log");
    if(gridPtr) {
      OhmmsAttributeSet radAttrib;
      radAttrib.add(gridType,"type"); 
      radAttrib.add(npts,"npts"); 
      radAttrib.add(ri,"ri"); radAttrib.add(rf,"rf");
      radAttrib.put(gridPtr);
    }
    myGrid.set(ri,rf,npts);

    //create a numerical grid funtor
    typedef OneDimCubicSpline<double> RadialOrbitalType;
    RadialOrbitalType radorb(&myGrid);

    int L= 0;
    //Loop over all the constracted S orbitals
    map<string,xmlNodePtr>::iterator it(sPtr.begin()),it_end(sPtr.end());
    while(it != it_end) {

      //create contracted gaussian
      GTOType gset(L,Normalized); 
      //read the radfunc's of basisGroup
      gset.putBasisGroup((*it).second);

      //convert to a radial functor
      Transform2GridFunctor<GTOType,RadialOrbitalType> transform(gset, radorb);
      transform.generate(myGrid.rmin(),myGrid.rmax(),myGrid.size());

      //optimize it with the radial functor
      Any2Slater gto2slater(radorb);
      gto2slater.optimize();
      ++it;
    }
    sPtr.clear();
  }
Example #15
0
void
ObjectAccessor::AddCorpsesToGrid(GridPair const& gridpair, GridType& grid, Map* map)
{
    Guard guard(i_corpseGuard);
    for (auto& iter : i_player2corpse)
        if (iter.second->GetGrid() == gridpair)
        {
            // verify, if the corpse in our instance (add only corpses which are)
            if (map->Instanceable())
            {
                if (iter.second->GetInstanceId() == map->GetInstanceId())
                {
                    grid.AddWorldObject(iter.second);
                }
            }
            else
            {
                grid.AddWorldObject(iter.second);
            }
        }
}
Grid3D<uint32_t> computeDistanceMap26_WithQueue(const GridType& grid, Predicate isInObject, bool outsideIsObject) {
    auto w = grid.width(), h = grid.height(), d = grid.depth();
    uint32_t maxDist = std::numeric_limits<uint32_t>::max();
    Grid3D<uint32_t> distanceGrid(w, h, d, maxDist);

    std::queue<Vec4i> queue;

    for(auto z = 0u; z < d; ++z) {
        for(auto y = 0u; y < h; ++y) {
            for(auto x = 0u; x < w; ++x) {
                auto voxel = Vec3i(x, y, z);
                if(!isInObject(x, y, z, grid)) {
                    queue.push(Vec4i(voxel, 0u));
                } else if(!outsideIsObject && (x == 0 || y == 0 || z == 0 || x == w - 1 || y == h - 1 || z == d - 1)) {
                    queue.push(Vec4i(voxel, 1u));
                }
            }
        }
    }

    while(!queue.empty()) {
        auto voxel = Vec3i(queue.front());
        auto dist = queue.front().w;
        queue.pop();

        if(dist < distanceGrid(voxel)) {
            distanceGrid(voxel) = dist;

            foreach26Neighbour(grid.resolution(), voxel, [&](const Vec3i& neighbour) {
                auto newDist = dist + 1;
                if(newDist < distanceGrid(neighbour)) {
                    queue.push(Vec4i(neighbour, newDist));
                }
            });
        }
    }

    return distanceGrid;
}
Example #17
0
void ObjectAccessor::AddCorpsesToGrid(GridCoord const& gridpair, GridType& grid, Map* map)
{
    TRINITY_READ_GUARD(ACE_RW_Thread_Mutex, i_corpseLock);

    for (Player2CorpsesMapType::iterator iter = i_player2corpse.begin(); iter != i_player2corpse.end(); ++iter)
    {
        // We need this check otherwise a corpose may be added to a grid twice
        if (iter->second->IsInGrid())
            continue;

        if (iter->second->GetGridCoord() == gridpair)
        {
            // verify, if the corpse in our instance (add only corpses which are)
            if (map->Instanceable())
            {
                if (iter->second->GetInstanceId() == map->GetInstanceId())
                    grid.AddWorldObject(iter->second);
            }
            else
                grid.AddWorldObject(iter->second);
        }
    }
}
Example #18
0
void
ObjectGridCleaner::Stop(GridType &grid)
{
    TypeContainerVisitor<ObjectGridCleaner, GridTypeMapContainer > stoper(*this);
    grid.Visit(stoper);
}
Example #19
0
void
ObjectGridRespawnMover::Move(GridType &grid)
{
    TypeContainerVisitor<ObjectGridRespawnMover, GridTypeMapContainer > mover(*this);
    grid.Visit(mover);
}
Example #20
0
void
ObjectGridUnloader::Unload(GridType &grid)
{
    TypeContainerVisitor<ObjectGridUnloader, GridTypeMapContainer > unloader(*this);
    grid.Visit(unloader);
}
Grid3D<uint32_t> computeDistanceMap26(const GridType& grid, Predicate isInObject, bool outsideIsObject) {
    int w = grid.width(), h = grid.height(), d = grid.depth();
    uint32_t maxDist = std::numeric_limits<uint32_t>::max();
    Grid3D<uint32_t> distanceGrid(w, h, d, maxDist);

    static const auto MASK_SIZE = 13;

    auto processVoxel = [&distanceGrid, &grid, &isInObject, maxDist, outsideIsObject, w, h, d](const Vec3i* mask, int x, int y, int z) {
        auto voxel = Vec3i(x, y, z);
        if(!isInObject(x, y, z, grid)) {
            distanceGrid(voxel) = 0u;
        } else if(!outsideIsObject && (x == 0 || y == 0 || z == 0 || x == w - 1 || y == h - 1 || z == d - 1)) {
            distanceGrid(voxel) = 1u;
        }
        auto currentDist = distanceGrid(voxel);
        if(currentDist != maxDist) {
            auto dist = currentDist + 1;
            for(auto i = 0u; i < MASK_SIZE; ++i) {
                auto offset = mask[i];
                auto neighbour = voxel + offset;

                if(grid.contains(neighbour) && isInObject(neighbour.x, neighbour.y, neighbour.z, grid) && dist < distanceGrid(neighbour)) {
                    distanceGrid(neighbour) = dist;
                }
            }
        }
    };

    static const Vec3i masks[][MASK_SIZE] = {
        {
            Vec3i(1, 0, 0),
            Vec3i(1, 1, 0),
            Vec3i(0, 1, 0),
            Vec3i(-1, 1, 0),
            Vec3i(0, 0, 1),
            Vec3i(1, 0, 1),
            Vec3i(1, 1, 1),
            Vec3i(0, 1, 1),
            Vec3i(-1, 1, 1),
            Vec3i(-1, 0, 1),
            Vec3i(-1, -1, 1),
            Vec3i(0, -1, 1),
            Vec3i(1, -1, 1),
        },
        {
            -Vec3i(1, 0, 0),
            -Vec3i(1, 1, 0),
            -Vec3i(0, 1, 0),
            -Vec3i(-1, 1, 0),
            -Vec3i(0, 0, 1),
            -Vec3i(1, 0, 1),
            -Vec3i(1, 1, 1),
            -Vec3i(0, 1, 1),
            -Vec3i(-1, 1, 1),
            -Vec3i(-1, 0, 1),
            -Vec3i(-1, -1, 1),
            -Vec3i(0, -1, 1),
            -Vec3i(1, -1, 1),
        }
    };

    for(auto z = 0; z < d; ++z) {
        for(auto y = 0; y < h; ++y) {
            for(auto x = 0; x < w; ++x) {
                processVoxel(masks[0], x, y, z);
            }
        }
    }

    for(auto z = d - 1; z >= 0; --z) {
        for(auto y = h - 1; y >= 0; --y) {
            for(auto x = w - 1; x >= 0; --x) {
                processVoxel(masks[1], x, y, z);
            }
        }
    }

    return distanceGrid;
}
//! \brief Main driver
int main(int argc, char** argv)
try
{
    try {
        static const int dim = 3;

        typedef Dune::CpGrid GridType;

        if (argc < 2 || strcmp(argv[1],"-h") == 0
                || strcmp(argv[1],"--help") == 0
                || strcmp(argv[1],"-?") == 0) {
            syntax(argv);
            exit(1);
        }
        Params p;
        parseCommandLine(argc,argv,p);

        Opm::time::StopWatch watch;
        watch.start();

        GridType grid;
        if (p.file == "uniform") {
            std::array<int,3> cells;
            cells[0] = p.cellsx;
            cells[1] = p.cellsy;
            cells[2] = p.cellsz;
            std::array<double,3> cellsize;
            cellsize[0] = cellsize[1] = cellsize[2] = 1.f;
            grid.createCartesian(cells,cellsize);
        } else
            grid.readEclipseFormat(p.file,p.ctol,false);

        typedef GridType::ctype ctype;
        Opm::Elasticity::ElasticityUpscale<GridType> upscale(grid, p.ctol,
                p.Emin, p.file,
                p.rocklist,
                p.verbose);
        if (p.max[0] < 0 || p.min[0] < 0) {
            std::cout << "determine side coordinates..." << std::endl;
            upscale.findBoundaries(p.min,p.max);
            std::cout << "  min " << p.min[0] << " " << p.min[1] << " " << p.min[2] << std::endl;
            std::cout << "  max " << p.max[0] << " " << p.max[1] << " " << p.max[2] << std::endl;
        }
        if (p.n1 == -1 || p.n2 == -1) {
            p.n1 = grid.logicalCartesianSize()[0];
            p.n2 = grid.logicalCartesianSize()[1];
        }
        if (p.linsolver.zcells == -1) {
            double lz = p.max[2]-p.min[2];
            int nz = grid.logicalCartesianSize()[2];
            double hz = lz/nz;
            double lp = sqrt((double)(p.max[0]-p.min[0])*(p.max[1]-p.min[1]));
            int np = std::max(grid.logicalCartesianSize()[0],
                              grid.logicalCartesianSize()[1]);
            double hp = lp/np;
            p.linsolver.zcells = (int)(2*hp/hz+0.5);
        }
        std::cout << "logical dimension: " << grid.logicalCartesianSize()[0]
                  << "x"                   << grid.logicalCartesianSize()[1]
                  << "x"                   << grid.logicalCartesianSize()[2]
                  << std::endl;

        if (p.method == UPSCALE_MPC) {
            std::cout << "using MPC couplings in all directions..." << std::endl;
            upscale.periodicBCs(p.min, p.max);
            std::cout << "preprocessing grid..." << std::endl;
            upscale.A.initForAssembly();
        } else if (p.method == UPSCALE_MORTAR) {
            std::cout << "using Mortar couplings.." << std::endl;
            upscale.periodicBCsMortar(p.min, p.max, p.n1, p.n2,
                                      p.lambda[0], p.lambda[1]);
        } else if (p.method == UPSCALE_NONE) {
            std::cout << "no periodicity approach applied.." << std::endl;
            upscale.fixCorners(p.min, p.max);
            upscale.A.initForAssembly();
        }
        Dune::FieldMatrix<double,6,6> C;
        Dune::VTKWriter<GridType::LeafGridView>* vtkwriter=0;
        if (!p.vtufile.empty())
            vtkwriter = new Dune::VTKWriter<GridType::LeafGridView>(grid.leafView());
        Opm::Elasticity::Vector field[6];
        std::cout << "assembling elasticity operator..." << "\n";
        upscale.assemble(-1,true);
        std::cout << "setting up linear solver..." << std::endl;
        upscale.setupSolvers(p.linsolver);

//#pragma omp parallel for schedule(static)
        for (int i=0; i<6; ++i) {
            std::cout << "processing case " << i+1 << "..." << std::endl;
            std::cout << "\tassembling load vector..." << std::endl;
            upscale.assemble(i,false);
            std::cout << "\tsolving..." << std::endl;
            upscale.solve(i);
            upscale.A.expandSolution(field[i],upscale.u[i]);
#define CLAMP(x) (fabs(x)<1.e-4?0.0:x)
            for (size_t j=0; j<field[i].size(); ++j) {
                double val = field[i][j];
                field[i][j] = CLAMP(val);
            }
            Dune::FieldVector<double,6> v;
            upscale.averageStress(v,upscale.u[i],i);
            for (int j=0; j<6; ++j)
                C[i][j] = CLAMP(v[j]);
        }
        for (int i=0; i<6; ++i) {
            std::stringstream str;
            str << "sol " << i+1;
            if (vtkwriter)
                vtkwriter->addVertexData(field[i], str.str().c_str(), dim);
        }
        if (vtkwriter) {
            vtkwriter->write(p.vtufile);
            delete vtkwriter;
        }
        // voigt notation
        for (int j=0; j<6; ++j)
            std::swap(C[3][j],C[5][j]);
        for (int j=0; j<6; ++j)
            std::swap(C[j][3],C[j][5]);
        std::cout << "---------" << std::endl;
        std::cout << C << std::endl;
        if (!p.output.empty()) {
            writeOutput(p,watch,grid.size(0),upscale.volumeFractions,C);
        }

        return 0;
    }
    catch (Dune::Exception &e) {
        std::cerr << "Dune reported error: " << e << std::endl;
    }
    catch (...) {
        std::cerr << "Unknown exception thrown!" << std::endl;
    }
    return 1;
}
catch (const std::exception &e) {
    std::cerr << "Program threw an exception: " << e.what() << "\n";
    throw;
}
Grid3D<uint32_t> computeDistanceGrid6Connexity_outsideIsInObject(const GridType& grid, Predicate isInObject) {
    auto w = grid.width(), h = grid.height(), d = grid.depth();
    auto maxDist = w + h + d;
    Grid3D<uint32_t> distanceGrid(w, h, d, maxDist);

    using DistType = decltype(maxDist);

    auto processVoxel = [&distanceGrid, &grid, &isInObject, maxDist](DistType& dist, int x, int y, int z) {
        if(!isInObject(x, y, z, grid)) {
            dist = 0u;
        } else if(dist != maxDist) {
            ++dist;
        }
        if(dist < distanceGrid(x, y, z)) {
            distanceGrid(x, y, z) = dist;
        } else {
            dist = distanceGrid(x, y, z);
        }
    };

    for(auto y = 0u; y < h; ++y) {
        for(auto x = 0u; x < w; ++x) {
            auto dist = maxDist;
            for(auto z = 0; z < d; ++z) {
                processVoxel(dist, x, y, z);
            }
            dist = maxDist;
            for(int z = d - 1; z >= 0; --z) {
                processVoxel(dist, x, y, z);
            }
        }
    }

    for(auto z = 0u; z < d; ++z) {
        for(auto x = 0u; x < w; ++x) {
            auto dist = maxDist;
            for(auto y = 0; y < h; ++y) {
                processVoxel(dist, x, y, z);
            }
            dist = maxDist;
            for(int y = h - 1; y >= 0; --y) {
                processVoxel(dist, x, y, z);
            }
        }
    }

    for(auto z = 0u; z < d; ++z) {
        for(auto y = 0u; y < h; ++y) {
            auto dist = maxDist;
            for(auto x = 0; x < w; ++x) {
                processVoxel(dist, x, y, z);
            }
            dist = maxDist;
            for(int x = w - 1; x >= 0; --x) {
                processVoxel(dist, x, y, z);
            }
        }
    }

    return distanceGrid;
}
Example #24
0
void
ObjectGridLoader::Load(GridType &grid)
{
    TypeContainerVisitor<ObjectGridLoader, TypeMapContainer<AllObjectTypes> > loader(*this);
    grid.VisitGridObjects(loader);
}
int run(Params& p)
{
  try {
    static const int dim = 3;

    Opm::time::StopWatch watch;
    watch.start();

    GridType grid;
    if (p.file == "uniform") {
      std::array<int,3> cells;
      cells[0] = p.cellsx;
      cells[1] = p.cellsy;
      cells[2] = p.cellsz;
      std::array<double,3> cellsize;
      cellsize[0] = p.max[0] > -1?p.max[0]/cells[0]:1.0;
      cellsize[1] = p.max[1] > -1?p.max[1]/cells[1]:1.0;
      cellsize[2] = p.max[2] > -1?p.max[2]/cells[2]:1.0;
      grid.createCartesian(cells,cellsize);
    } else {
        Opm::ParseContext parseContext;
        Opm::ParserPtr parser(new Opm::Parser());
        Opm::DeckConstPtr deck(parser->parseFile(p.file , parseContext));
        Opm::EclipseGrid inputGrid(deck);
        grid.processEclipseFormat(inputGrid, false);
    }
    ElasticityUpscale<GridType, AMG> upscale(grid, p.ctol, p.Emin, p.file,
                                             p.rocklist, p.verbose);

    if (p.max[0] < 0 || p.min[0] < 0) {
      std::cout << "determine side coordinates..." << std::endl;
      upscale.findBoundaries(p.min,p.max);
      std::cout << "  min " << p.min[0] << " " << p.min[1] << " " << p.min[2] << std::endl;
      std::cout << "  max " << p.max[0] << " " << p.max[1] << " " << p.max[2] << std::endl;
    }
    if (p.n1 == -1 || p.n2 == -1) {
      p.n1 = grid.logicalCartesianSize()[0];
      p.n2 = grid.logicalCartesianSize()[1];
    }
    if (p.linsolver.zcells == -1) {
      double lz = p.max[2]-p.min[2];
      int nz = grid.logicalCartesianSize()[2];
      double hz = lz/nz;
      double lp = sqrt((double)(p.max[0]-p.min[0])*(p.max[1]-p.min[1]));
      int np = std::max(grid.logicalCartesianSize()[0],
                        grid.logicalCartesianSize()[1]);
      double hp = lp/np;
      p.linsolver.zcells = (int)(2*hp/hz+0.5);
    }
    std::cout << "logical dimension: " << grid.logicalCartesianSize()[0]
              << "x"                   << grid.logicalCartesianSize()[1]
              << "x"                   << grid.logicalCartesianSize()[2]
              << std::endl;

    if (p.inspect == "mesh")
      return 0;

    if (p.linsolver.pre == UNDETERMINED) {
      double hx = (p.max[0]-p.min[0])/grid.logicalCartesianSize()[0];
      double hy = (p.max[1]-p.min[1])/grid.logicalCartesianSize()[1];
      double hz = (p.max[2]-p.min[2])/grid.logicalCartesianSize()[2];
      double aspect = sqrt(hx*hy)/hz;
      std::cout << "Estimated cell aspect ratio: " << aspect;
      if (aspect > 80) {
        p.linsolver.pre = TWOLEVEL;
        std::cout << " => Using two level preconditioner" << std::endl;
      } else {
        p.linsolver.pre = Opm::Elasticity::AMG;
        std::cout << " => Using AMG preconditioner" << std::endl;
      }
    }

    if (p.method == UPSCALE_MPC) {
      std::cout << "using MPC couplings in all directions..." << std::endl;
      upscale.periodicBCs(p.min, p.max);
      std::cout << "preprocessing grid..." << std::endl;
      upscale.A.initForAssembly();
    } else if (p.method == UPSCALE_MORTAR) {
      std::cout << "using Mortar couplings.." << std::endl;
      upscale.periodicBCsMortar(p.min, p.max, p.n1, p.n2,
                                p.lambda[0], p.lambda[1]);
    } else if (p.method == UPSCALE_NONE) {
      std::cout << "no periodicity approach applied.." << std::endl;
      upscale.fixCorners(p.min, p.max);
      upscale.A.initForAssembly();
    }

    Dune::FieldMatrix<double,6,6> C;
    Opm::Elasticity::Vector field[6];
    std::cout << "assembling elasticity operator..." << "\n";
    upscale.assemble(-1,true);
    std::cout << "setting up linear solver..." << std::endl;
    upscale.setupSolvers(p.linsolver);

    if (p.inspect == "load")
      Dune::storeMatrixMarket(upscale.A.getOperator(), "A.mtx");

    // the uzawa solver cannot run multithreaded
#ifdef HAVE_OPENMP
    if (p.linsolver.uzawa) {
      std::cout << "WARNING: disabling multi-threaded solves due to uzawa" << std::endl;
      omp_set_num_threads(1);
    }
#endif

#pragma omp parallel for schedule(static)
    for (int i=0;i<6;++i) {
      std::cout << "processing case " << i+1 << "..." << std::endl;
      if (p.inspect == "results") {
        char temp[1024];
        sprintf(temp, p.resultfilename.c_str(), "x", i+1);
        Dune::loadMatrixMarket(upscale.u[i], temp);
      } else {
        std::cout << "\tassembling load vector..." << std::endl;
        upscale.assemble(i,false);
        if (p.inspect == "load") {
          char temp[1024];
          sprintf(temp, p.resultfilename.c_str(), "b", i+1);
          Dune::storeMatrixMarket(upscale.b[i], temp);
        }
        std::cout << "\tsolving..." << std::endl;
        upscale.solve(i);
        if (p.inspect == "load") {
          char temp[1024];
          sprintf(temp, p.resultfilename.c_str(), "x", i+1);
          Dune::storeMatrixMarket(upscale.u[i], temp);
        }
      }
      upscale.A.expandSolution(field[i],upscale.u[i]);
#define CLAMP(x) (fabs(x)<1.e-4?0.0:x)
      for (size_t j=0;j<field[i].size();++j) {
        double val = field[i][j];
        field[i][j] = CLAMP(val);
      }
      Dune::FieldVector<double,6> v;
      upscale.averageStress(v,upscale.u[i],i);
      for (int j=0;j<6;++j)
        C[i][j] = CLAMP(v[j]);
    }

    if (!p.vtufile.empty()) {
      Dune::VTKWriter<typename GridType::LeafGridView> vtkwriter(grid.leafGridView());

      for (int i=0;i<6;++i) {
        std::stringstream str;
        str << "sol " << i+1;
        vtkwriter.addVertexData(field[i], str.str().c_str(), dim);
      }
      vtkwriter.write(p.vtufile);
    }

    Dune::FieldVector<double,3> speeds;
    if (upscale.upscaledRho > -1) {
      speeds = Opm::Elasticity::waveSpeeds(C, p.dip, p.azimuth, 1.0);
      std::cout << "Wave speeds: " << speeds << std::endl;
    }

    // voigt notation
    for (int j=0;j<6;++j)
      std::swap(C[3][j],C[5][j]);
    for (int j=0;j<6;++j)
      std::swap(C[j][3],C[j][5]);
    std::cout << "---------" << std::endl;
    std::cout << C << std::endl;
    if (!p.output.empty())
      writeOutput(p, watch, grid.size(0), upscale.volumeFractions,
                  upscale.bySat, C, upscale.upscaledRho, speeds);

    return 0;
  }
  catch (Dune::Exception &e) {
    throw e;
  }
  catch (...) {
    throw;
  }
  return 1;
}