FilterHistoryPoints.cpp 18.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
///////////////////////////////////////////////////////////////////////////////
//
// File FilterHistoryPoints.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: Outputs values at specific points during time-stepping.
//
///////////////////////////////////////////////////////////////////////////////

#include <LibUtilities/Memory/NekMemoryManager.hpp>
37
#include <iomanip>
38
#include <SolverUtils/Filters/FilterHistoryPoints.h>
39
#include <MultiRegions/ExpList3DHomogeneous1D.h>
40

41 42
#include <boost/format.hpp>

43 44
using namespace std;

45 46
namespace Nektar
{
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
namespace SolverUtils
{
std::string FilterHistoryPoints::className = GetFilterFactory().RegisterCreatorFunction("HistoryPoints", FilterHistoryPoints::create);

/**
 *
 */
FilterHistoryPoints::FilterHistoryPoints(
    const LibUtilities::SessionReaderSharedPtr &pSession,
    const ParamMap &pParams) :
    Filter(pSession)
{
    ParamMap::const_iterator it;

    // OutputFile
    it = pParams.find("OutputFile");
    if (it == pParams.end())
64
    {
65 66 67 68 69 70 71 72 73 74 75 76
        m_outputFile = m_session->GetSessionName();
    }
    else
    {
        ASSERTL0(it->second.length() > 0, "Missing parameter 'OutputFile'.");
        m_outputFile = it->second;
    }
    if (!(m_outputFile.length() >= 4
          && m_outputFile.substr(m_outputFile.length() - 4) == ".his"))
    {
        m_outputFile += ".his";
    }
77

78 79 80 81 82 83 84 85 86 87 88
    // OutputFrequency
    it = pParams.find("OutputFrequency");
    if (it == pParams.end())
    {
        m_outputFrequency = 1;
    }
    else
    {
        LibUtilities::Equation equ(m_session, it->second);
        m_outputFrequency = floor(equ.Evaluate());
    }
89

90 91 92 93 94 95 96
    // OutputPlane
    m_session->MatchSolverInfo("Homogeneous", "1D", m_isHomogeneous1D, false);
    if(m_isHomogeneous1D)
    {
        it = pParams.find("OutputPlane");
        if (it == pParams.end())
        {
97
            m_outputPlane = -1;
98 99 100 101 102 103 104
        }
        else
        {
            LibUtilities::Equation equ(m_session, it->second);
            m_outputPlane = floor(equ.Evaluate());
        }
    }
105

106 107 108 109 110 111
    // Points
    it = pParams.find("Points");
    ASSERTL0(it != pParams.end(), "Missing parameter 'Points'.");
    m_historyPointStream.str(it->second);
    m_index = 0;
}
112

113

114 115 116 117 118
/**
 *
 */
FilterHistoryPoints::~FilterHistoryPoints()
{
119

120
}
121 122


123 124 125 126 127 128 129 130 131
/**
 *
 */
void FilterHistoryPoints::v_Initialise(
    const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields,
    const NekDouble &time)
{
    ASSERTL0(!m_historyPointStream.fail(),
             "No history points in stream.");
132

133 134
    m_index = 0;
    m_historyList.clear();
135

136
    vector<unsigned int> planeIDs;
137 138 139
    // Read history points
    Array<OneD, NekDouble>  gloCoord(3,0.0);
    int dim = pFields[0]->GetGraph()->GetSpaceDimension();
140 141 142 143
    if (m_isHomogeneous1D)
    {
        dim++;
    }
144 145 146 147 148 149
    int i = 0;
    while (!m_historyPointStream.fail())
    {
        m_historyPointStream >> gloCoord[0]
                             >> gloCoord[1]
                             >> gloCoord[2];
150 151

        if (!m_historyPointStream.fail())
152
        {
153 154 155
            // Overwrite gloCoord[2] for 3DH1D using m_outputPlane if it is
            //       defined, or a nearby plane otherwise
            if(m_isHomogeneous1D)
156
            {
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
                int nplanes     = pFields[0]->GetHomogeneousBasis()
                                            ->GetZ().num_elements();
                NekDouble lhom  = pFields[0]->GetHomoLen();
                int plane;
                if (m_outputPlane == -1)
                {
                    // Convert to int to pick the previous plane closer to the point
                    plane = (gloCoord[2]*nplanes)/lhom;
                }
                else
                {
                    plane = m_outputPlane;
                }

                NekDouble Z = (pFields[0]->GetHomogeneousBasis()
                                            ->GetZ())[plane];
                Z = (Z+1)*lhom/2;
                if(fabs(gloCoord[2]-Z) > NekConstants::kVertexTheSameDouble)
                {
                    cout << "Reseting History point from " << gloCoord[2]
                         << " to " << Z << endl;
                }
                gloCoord[2] = Z;
                planeIDs.push_back(plane);
181
            }
182

183 184 185 186
            SpatialDomains::PointGeomSharedPtr vert
                = MemoryManager<SpatialDomains::PointGeom>
                ::AllocateSharedPtr(dim, i, gloCoord[0],
                                    gloCoord[1], gloCoord[2]);
187

188 189 190 191
            m_historyPoints.push_back(vert);
            ++i;
        }
    }
192 193


194 195 196
    // Determine the unique process responsible for each history point
    // For points on a partition boundary, must select a single process
    LibUtilities::CommSharedPtr vComm = pFields[0]->GetComm();
197
    int vRank = vComm->GetRowComm()->GetRank();
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
    int vHP   = m_historyPoints.size();
    Array<OneD, int>       procList(vHP, -1   );
    Array<OneD, int>       idList  (vHP, -1   );
    Array<OneD, NekDouble> dist    (vHP,  1e16);
    Array<OneD, NekDouble> dist_loc(vHP,  1e16);
    std::vector<Array<OneD, NekDouble> > LocCoords;

    // Find the nearest element on this process to which the history
    // point could belong and note down the distance from the element
    // and the process ID.
    for (i = 0; i < vHP; ++i)
    {
        Array<OneD, NekDouble> locCoords(3);
        m_historyPoints[i]->GetCoords(  gloCoord[0],
                                        gloCoord[1],
                                        gloCoord[2]);

        // Determine the expansion and local coordinates
216 217 218 219 220 221 222 223
        if (m_isHomogeneous1D)
        {
            idList[i] = pFields[0]->GetPlane(0)->GetExpIndex(gloCoord,locCoords,
                                        NekConstants::kNekZeroTol);
        }
        else
        {
            idList[i] = pFields[0]->GetExpIndex(gloCoord,locCoords,
Douglas Serson's avatar
Douglas Serson committed
224
                                        NekConstants::kNekZeroTol);
225
        }
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240

        // Save Local coordinates for later
        LocCoords.push_back(locCoords);

        // For those points for which a potential nearby element exists
        // compute the perp. distance from the point to the element and
        // store in the distances array.
        if (idList[i] != -1)
        {
            SpatialDomains::GeometrySharedPtr g =
                            pFields[0]->GetExp(idList[i])->GetGeom();
            StdRegions::StdExpansionSharedPtr e = g->GetXmap();
            Array<OneD, NekDouble> coordVals(e->GetTotPoints());
            dist_loc[i] = 0.0;
            for (int j = 0; j < g->GetCoordim(); ++j)
241
            {
242 243 244 245
                e->BwdTrans(g->GetCoeffs(j), coordVals);
                NekDouble x = e->PhysEvaluate(locCoords, coordVals)
                                                         - gloCoord[j];
                dist_loc[i] += x*x;
246
            }
247 248
        }
    }
249

250 251 252 253
    // Reduce distances of points from elements, keeping the smallest
    // distance.
    Vmath::Vcopy(vHP, dist_loc, 1, dist, 1);
    vComm->AllReduce(dist, LibUtilities::ReduceMin);
254

255 256 257
    // If multiple processes find they are the nearest (e.g. point lies
    // on a partition boundary, we will choose the process of highest
    // rank.
258
    m_planeIDs = Array<OneD, int> (planeIDs.size(),-1);
259 260 261 262 263 264 265 266 267 268 269 270
    for (i = 0; i < vHP; ++i)
    {
        if (dist_loc[i] == dist[i])
        {
            // Set element id to Vid of m_history point for later use
            m_historyPoints[i]->SetVid(idList[i]);
        }
        else
        {
            // This history point is not handled by this process
            idList[i] = -1;
        }
Dave Moxey's avatar
Dave Moxey committed
271

272 273 274 275
        // If a matching element is found on this process, note the
        // process ID
        if (idList[i] != -1)
        {
276
            procList[i] = vRank;
277 278 279 280 281 282
            if(m_isHomogeneous1D)
            {
                int j;
                Array<OneD, const unsigned int> IDs
                                            = pFields[0]->GetZIDs();
                for(j = 0; j < IDs.num_elements(); ++j)
283
                {
284
                    if(IDs[j] == planeIDs[i])
285
                    {
286
                        break;
287
                    }
288
                }
289

290
                if(j != IDs.num_elements())
291
                {
292
                    m_planeIDs[i] = j;
293 294
                }
            }
295 296
        }
    }
297

298 299 300 301
    // Reduce process IDs for all history points. The process with
    // largest rank will handle the history point in the case where the
    // distance was the same.
    vComm->AllReduce(procList,  LibUtilities::ReduceMax);
302

303 304 305 306 307 308 309 310 311 312
    // Determine the element in which each history point resides.
    // If point is not in mesh (on this process), id is -1.
    for (i = 0; i < vHP; ++i)
    {
        // If point lies on partition boundary, only the proc with max
        // rank retains possession.
        if (procList[i] != vRank)
        {
            idList[i] = -1;
        }
313

314 315 316 317 318 319 320 321 322 323 324
        // If the current process owns this history point, add it to its
        // local list of history points.
        if (idList[i] != -1)
        {
            m_historyLocalPointMap[m_historyList.size()] = i;
            m_historyList.push_back(
                     std::pair<SpatialDomains::PointGeomSharedPtr,
                                              Array<OneD, NekDouble> >
                              (m_historyPoints[i], LocCoords[i]));
        }
    }
325

326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
    // Collate the element ID list across processes and check each
    // history point is allocated to a process
    vComm->AllReduce(idList, LibUtilities::ReduceMax);
    if (vComm->GetRank() == 0)
    {
        for (i = 0; i < vHP; ++i)
        {
            m_historyPoints[i]->GetCoords(  gloCoord[0],
                                            gloCoord[1],
                                            gloCoord[2]);

            // Write an error if no process owns history point
            ASSERTL0(idList[i] != -1,
                     "History point "
                     + boost::lexical_cast<std::string>(gloCoord[0])
                     + ", "
                     + boost::lexical_cast<std::string>(gloCoord[1])
                     + ", "
                     + boost::lexical_cast<std::string>(gloCoord[2])
                     + " cannot be found in the mesh.");

            // Print a warning if a process owns it but it is not close
            // enough to the element.
            if (dist[i] > NekConstants::kGeomFactorsTol)
            {
                cout << "Warning: History point " << i << " at ("
                     << gloCoord[0] << "," << gloCoord[1] << ","
                     << gloCoord[2] << ") lies a distance of "
                     << sqrt(dist[i]) << " from the manifold." << endl;
355 356 357
            }
        }

358 359 360
        // Open output stream
        m_outputStream.open(m_outputFile.c_str());
        m_outputStream << "# History data for variables (:";
361

362
        for (i = 0; i < pFields.num_elements(); ++i)
363
        {
364 365
            m_outputStream << m_session->GetVariable(i) <<",";
        }
366

367 368
        if(m_isHomogeneous1D)
        {
369
            m_outputStream << ") at points:" << endl;
370 371 372 373 374
        }
        else
        {
            m_outputStream << ") at points:" << endl;
        }
375

376 377 378 379 380 381
        for (i = 0; i < vHP; ++i)
        {
            m_historyPoints[i]->GetCoords(  gloCoord[0],
                                            gloCoord[1],
                                            gloCoord[2]);

382 383 384 385
            m_outputStream << "# " << boost::format("%6.0f") % i;
            m_outputStream << " " << boost::format("%25e") % gloCoord[0];
            m_outputStream << " " << boost::format("%25e") % gloCoord[1];
            m_outputStream << " " << boost::format("%25e") % gloCoord[2];
386 387
            m_outputStream << endl;
        }
388

389 390
        if(m_isHomogeneous1D)
        {
391
            //m_outputStream << "# (in Wavespace)" << endl;
392 393 394 395
        }
    }
    v_Update(pFields, time);
}
396

397

398 399 400 401 402 403 404 405 406 407
/**
 *
 */
void FilterHistoryPoints::v_Update(const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time)
{
    // Only output every m_outputFrequency.
    if ((m_index++) % m_outputFrequency)
    {
        return;
    }
408

409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
    int j         = 0;
    int k         = 0;
    int numPoints = m_historyPoints.size();
    int numFields = pFields.num_elements();
    LibUtilities::CommSharedPtr vComm = pFields[0]->GetComm();
    Array<OneD, NekDouble> data(numPoints*numFields, 0.0);
    std::list<std::pair<SpatialDomains::PointGeomSharedPtr, Array<OneD, NekDouble> > >::iterator x;

    Array<OneD, NekDouble> physvals;
    Array<OneD, NekDouble> locCoord;
    int expId;

    // Pull out data values field by field
    for (j = 0; j < numFields; ++j)
    {
        if(m_isHomogeneous1D)
        {
            for (k = 0, x = m_historyList.begin(); x != m_historyList.end();
                 ++x, ++k)
            {
                locCoord = (*x).second;
                expId    = (*x).first->GetVid();
431 432 433
                NekDouble value;
                int plane = m_planeIDs[m_historyLocalPointMap[k]];
                if (pFields[j]->GetWaveSpace() == false && plane != -1)
434
                {
435 436 437 438 439 440 441 442 443 444 445 446 447 448
                    physvals = pFields[j]->GetPlane(plane)->
                               UpdatePhys() + pFields[j]->GetPhys_Offset(expId);

                    // transform elemental data if required.
                    if(pFields[j]->GetPhysState() == false)
                    {
                        pFields[j]->GetPlane(plane)->GetExp(expId)->
                                  BwdTrans(pFields[j]->GetPlane(plane)->
                                  GetCoeffs() + pFields[j]->
                                  GetCoeff_Offset(expId),physvals);
                    }
                    // Interpolate data
                    value = pFields[j]->GetPlane(plane)->GetExp(expId)->
                            StdPhysEvaluate(locCoord,physvals);
449
                }
450 451 452 453 454 455
                else
                {
                    // Create vector with eIDs across all planes
                    std::vector<unsigned int> eIDs;
                    int nPlanes = pFields[j]->GetZIDs().num_elements();
                    int elmtsPerPlane = pFields[j]->GetExpSize()/nPlanes;
456

457 458 459 460
                    for ( int n = 0; n < nPlanes; n++)
                    {
                        eIDs.push_back(expId + n*elmtsPerPlane);
                    }
461

462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
                    // Create new 3DH1D expansion with one element per plane
                    MultiRegions::ExpList3DHomogeneous1DSharedPtr tmp =
                            boost::dynamic_pointer_cast<MultiRegions::
                            ExpList3DHomogeneous1D>(pFields[j]);
                    ASSERTL0(tmp,"Failed to type cast expansion");

                    MultiRegions::ExpList3DHomogeneous1DSharedPtr exp =
                            MemoryManager<MultiRegions::
                                ExpList3DHomogeneous1D>::
                                AllocateSharedPtr(*tmp, eIDs);
                    // Fill phys array of new expansion and apply HomoBwdTrans
                    for ( int n = 0; n < nPlanes; n++)
                    {
                        int nq = exp->GetPlane(0)->GetTotPoints();
                        Array<OneD, NekDouble> fromPhys =
                                pFields[j]->GetPlane(n)->GetPhys() +
                                pFields[j]->GetPhys_Offset(expId);
                        Array<OneD, NekDouble> toPhys =
                                exp->GetPlane(n)->UpdatePhys();
                        Vmath::Vcopy(nq, fromPhys, 1, toPhys, 1);
                    }
                    exp->HomogeneousBwdTrans(exp->GetPhys(), exp->UpdatePhys());
                    // Interpolate data
                    if (plane != -1)
                    {
                        physvals = exp->GetPlane(plane)->UpdatePhys();

                        value = exp->GetPlane(plane)->GetExp(0)->
                            StdPhysEvaluate(locCoord,physvals);
                    }
                }

                // store data
                if (plane != -1)
                {
                    data[m_historyLocalPointMap[k]*numFields+j] = value;
                }
499 500 501 502 503
            }
        }
        else
        {
            for (k = 0, x = m_historyList.begin(); x != m_historyList.end(); ++x, ++k)
504
            {
505 506 507 508
                locCoord = (*x).second;
                expId    = (*x).first->GetVid();

                physvals = pFields[j]->UpdatePhys() + pFields[j]->GetPhys_Offset(expId);
509

510 511
                // transform elemental data if required.
                if(pFields[j]->GetPhysState() == false)
512
                {
513
                    pFields[j]->GetExp(expId)->BwdTrans(pFields[j]->GetCoeffs() + pFields[j]->GetCoeff_Offset(expId),physvals);
514
                }
515 516 517

                // interpolate point
                data[m_historyLocalPointMap[k]*numFields+j] = pFields[j]->GetExp(expId)->StdPhysEvaluate(locCoord,physvals);
518 519
            }
        }
520 521 522 523 524
    }

    // Exchange history data
    // This could be improved to reduce communication but works for now
    vComm->AllReduce(data, LibUtilities::ReduceSum);
525

526 527 528
    // Only the root process writes out history data
    if (vComm->GetRank() == 0)
    {
529

530 531
        // Write data values point by point
        for (k = 0; k < m_historyPoints.size(); ++k)
532
        {
533
            m_outputStream << boost::format("%25e") % time;
534
            for (int j = 0; j < numFields; ++j)
535
            {
536
                m_outputStream << " " << boost::format("%25e") % data[k*numFields+j];
537
            }
538
            m_outputStream << endl;
539
        }
540 541
    }
}
542 543


544 545 546 547 548 549 550 551
/**
 *
 */
void FilterHistoryPoints::v_Finalise(const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time)
{
    if (pFields[0]->GetComm()->GetRank() == 0)
    {
        m_outputStream.close();
552 553
    }
}
554 555 556 557 558 559 560 561 562 563 564


/**
 *
 */
bool FilterHistoryPoints::v_IsTimeDependent()
{
    return true;
}
}
}