mappedPatchBase.C 37.6 KB
Newer Older
1
2
3
4
/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
OpenFOAM bot's avatar
OpenFOAM bot committed
5
    \\  /    A nd           | www.openfoam.com
OpenFOAM bot's avatar
OpenFOAM bot committed
6
7
     \\/     M anipulation  |
-------------------------------------------------------------------------------
OpenFOAM bot's avatar
OpenFOAM bot committed
8
    Copyright (C) 2011-2016 OpenFOAM Foundation
9
    Copyright (C) 2015-2020 OpenCFD Ltd.
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
-------------------------------------------------------------------------------
License
    This file is part of OpenFOAM.

    OpenFOAM is free software: you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    for more details.

    You should have received a copy of the GNU General Public License
    along with OpenFOAM.  If not, see <http://www.gnu.org/licenses/>.

\*---------------------------------------------------------------------------*/

#include "mappedPatchBase.H"
#include "addToRunTimeSelectionTable.H"
#include "ListListOps.H"
32
#include "meshSearchMeshObject.H"
33
34
35
36
#include "meshTools.H"
#include "OFstream.H"
#include "Random.H"
#include "treeDataFace.H"
37
#include "treeDataPoint.H"
38
39
40
41
42
43
#include "indexedOctree.H"
#include "polyMesh.H"
#include "polyPatch.H"
#include "Time.H"
#include "mapDistribute.H"
#include "SubField.H"
44
#include "triPointRef.H"
45
#include "syncTools.H"
46
#include "treeDataCell.H"
47
#include "DynamicField.H"
Andrew Heather's avatar
Andrew Heather committed
48
#include "faceAreaWeightAMI.H"
49
50
51
52
53
54
55
56
57

// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

namespace Foam
{
    defineTypeNameAndDebug(mappedPatchBase, 0);
}


58
59
60
61
62
const Foam::Enum
<
    Foam::mappedPatchBase::sampleMode
>
Foam::mappedPatchBase::sampleModeNames_
Mark OLESEN's avatar
Mark OLESEN committed
63
({
64
65
66
67
68
69
    { sampleMode::NEARESTCELL, "nearestCell" },
    { sampleMode::NEARESTPATCHFACE, "nearestPatchFace" },
    { sampleMode::NEARESTPATCHFACEAMI, "nearestPatchFaceAMI" },
    { sampleMode::NEARESTPATCHPOINT, "nearestPatchPoint" },
    { sampleMode::NEARESTFACE, "nearestFace" },
    { sampleMode::NEARESTONLYCELL, "nearestOnlyCell" },
Mark OLESEN's avatar
Mark OLESEN committed
70
});
71
72
73
74
75
76
77


const Foam::Enum
<
    Foam::mappedPatchBase::offsetMode
>
Foam::mappedPatchBase::offsetModeNames_
Mark OLESEN's avatar
Mark OLESEN committed
78
({
79
80
81
    { offsetMode::UNIFORM, "uniform" },
    { offsetMode::NONUNIFORM, "nonuniform" },
    { offsetMode::NORMAL, "normal" },
Mark OLESEN's avatar
Mark OLESEN committed
82
});
83
84
85
86


// * * * * * * * * * * * * * Private Member Functions  * * * * * * * * * * * //

87
88
89
90
91
92
Foam::tmp<Foam::pointField> Foam::mappedPatchBase::facePoints
(
    const polyPatch& pp
) const
{
    const polyMesh& mesh = pp.boundaryMesh().mesh();
93
94
95

    // Force construction of min-tet decomp
    (void)mesh.tetBasePtIs();
96
97

    // Initialise to face-centre
98
    tmp<pointField> tfacePoints(new pointField(patch_.size()));
99
    pointField& facePoints = tfacePoints.ref();
100

101
    forAll(pp, facei)
102
    {
103
        facePoints[facei] = facePoint
104
105
        (
            mesh,
106
            pp.start()+facei,
107
            polyMesh::FACE_DIAG_TRIS
108
        ).rawPoint();
109
110
111
112
113
114
    }

    return tfacePoints;
}


115
116
void Foam::mappedPatchBase::collectSamples
(
117
    const pointField& facePoints,
118
119
120
121
122
123
124
    pointField& samples,
    labelList& patchFaceProcs,
    labelList& patchFaces,
    pointField& patchFc
) const
{
    // Collect all sample points and the faces they come from.
125
126
127
128
129
130
131
132
133
134
135
136
    {
        List<pointField> globalFc(Pstream::nProcs());
        globalFc[Pstream::myProcNo()] = facePoints;
        Pstream::gatherList(globalFc);
        Pstream::scatterList(globalFc);
        // Rework into straight list
        patchFc = ListListOps::combine<pointField>
        (
            globalFc,
            accessOp<pointField>()
        );
    }
137

138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
    {
        List<pointField> globalSamples(Pstream::nProcs());
        globalSamples[Pstream::myProcNo()] = samplePoints(facePoints);
        Pstream::gatherList(globalSamples);
        Pstream::scatterList(globalSamples);
        // Rework into straight list
        samples = ListListOps::combine<pointField>
        (
            globalSamples,
            accessOp<pointField>()
        );
    }

    {
        labelListList globalFaces(Pstream::nProcs());
        globalFaces[Pstream::myProcNo()] = identity(patch_.size());
        // Distribute to all processors
        Pstream::gatherList(globalFaces);
        Pstream::scatterList(globalFaces);

        patchFaces = ListListOps::combine<labelList>
159
160
161
        (
            globalFaces,
            accessOp<labelList>()
162
163
164
        );
    }

165
    {
166
167
168
169
170
171
172
173
        labelList nPerProc(Pstream::nProcs());
        nPerProc[Pstream::myProcNo()] = patch_.size();
        Pstream::gatherList(nPerProc);
        Pstream::scatterList(nPerProc);

        patchFaceProcs.setSize(patchFaces.size());

        label sampleI = 0;
174
        forAll(nPerProc, proci)
175
        {
176
            for (label i = 0; i < nPerProc[proci]; i++)
177
            {
178
                patchFaceProcs[sampleI++] = proci;
179
            }
180
181
182
183
184
185
186
187
188
        }
    }
}


// Find the processor/cell containing the samples. Does not account
// for samples being found in two processors.
void Foam::mappedPatchBase::findSamples
(
189
    const sampleMode mode,
190
191
192
193
194
195
196
197
198
199
200
201
    const pointField& samples,
    labelList& sampleProcs,
    labelList& sampleIndices,
    pointField& sampleLocations
) const
{
    // Lookup the correct region
    const polyMesh& mesh = sampleMesh();

    // All the info for nearest. Construct to miss
    List<nearInfo> nearest(samples.size());

202
    switch (mode)
203
204
205
    {
        case NEARESTCELL:
        {
206
            if (samplePatch_.size() && samplePatch_ != "none")
207
            {
208
209
                FatalErrorInFunction
                    << "No need to supply a patch name when in "
210
                    << sampleModeNames_[mode] << " mode." << exit(FatalError);
211
212
            }

213
            //- Note: face-diagonal decomposition
214
            const indexedOctree<Foam::treeDataCell>& tree = mesh.cellTree();
215
216
217
218
219

            forAll(samples, sampleI)
            {
                const point& sample = samples[sampleI];

220
                label celli = tree.findInside(sample);
221

222
                if (celli == -1)
223
224
225
226
227
228
                {
                    nearest[sampleI].second().first() = Foam::sqr(GREAT);
                    nearest[sampleI].second().second() = Pstream::myProcNo();
                }
                else
                {
229
                    const point& cc = mesh.cellCentres()[celli];
230
231
232
233
234

                    nearest[sampleI].first() = pointIndexHit
                    (
                        true,
                        cc,
235
                        celli
236
237
238
239
240
241
242
243
                    );
                    nearest[sampleI].second().first() = magSqr(cc-sample);
                    nearest[sampleI].second().second() = Pstream::myProcNo();
                }
            }
            break;
        }

244
245
246
247
        case NEARESTONLYCELL:
        {
            if (samplePatch_.size() && samplePatch_ != "none")
            {
248
249
                FatalErrorInFunction
                    << "No need to supply a patch name when in "
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
                    << sampleModeNames_[mode] << " mode." << exit(FatalError);
            }

            //- Note: face-diagonal decomposition
            const indexedOctree<Foam::treeDataCell>& tree = mesh.cellTree();

            forAll(samples, sampleI)
            {
                const point& sample = samples[sampleI];

                nearest[sampleI].first() = tree.findNearest(sample, sqr(GREAT));
                nearest[sampleI].second().first() = magSqr
                (
                    nearest[sampleI].first().hitPoint()
                   -sample
                );
                nearest[sampleI].second().second() = Pstream::myProcNo();
            }
            break;
        }

271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
        case NEARESTPATCHFACE:
        {
            Random rndGen(123456);

            const polyPatch& pp = samplePolyPatch();

            if (pp.empty())
            {
                forAll(samples, sampleI)
                {
                    nearest[sampleI].second().first() = Foam::sqr(GREAT);
                    nearest[sampleI].second().second() = Pstream::myProcNo();
                }
            }
            else
            {
                // patch faces
288
                const labelList patchFaces(identity(pp.size(), pp.start()));
289
290
291
292
293
294

                treeBoundBox patchBb
                (
                    treeBoundBox(pp.points(), pp.meshPoints()).extend
                    (
                        rndGen,
295
                        1e-4
296
297
                    )
                );
298
299
                patchBb.min() -= point::uniform(ROOTVSMALL);
                patchBb.max() += point::uniform(ROOTVSMALL);
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344

                indexedOctree<treeDataFace> boundaryTree
                (
                    treeDataFace    // all information needed to search faces
                    (
                        false,      // do not cache bb
                        mesh,
                        patchFaces  // boundary faces only
                    ),
                    patchBb,        // overall search domain
                    8,              // maxLevel
                    10,             // leafsize
                    3.0             // duplicity
                );

                forAll(samples, sampleI)
                {
                    const point& sample = samples[sampleI];

                    pointIndexHit& nearInfo = nearest[sampleI].first();
                    nearInfo = boundaryTree.findNearest
                    (
                        sample,
                        magSqr(patchBb.span())
                    );

                    if (!nearInfo.hit())
                    {
                        nearest[sampleI].second().first() = Foam::sqr(GREAT);
                        nearest[sampleI].second().second() =
                            Pstream::myProcNo();
                    }
                    else
                    {
                        point fc(pp[nearInfo.index()].centre(pp.points()));
                        nearInfo.setPoint(fc);
                        nearest[sampleI].second().first() = magSqr(fc-sample);
                        nearest[sampleI].second().second() =
                            Pstream::myProcNo();
                    }
                }
            }
            break;
        }

345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
        case NEARESTPATCHPOINT:
        {
            Random rndGen(123456);

            const polyPatch& pp = samplePolyPatch();

            if (pp.empty())
            {
                forAll(samples, sampleI)
                {
                    nearest[sampleI].second().first() = Foam::sqr(GREAT);
                    nearest[sampleI].second().second() = Pstream::myProcNo();
                }
            }
            else
            {
                // patch (local) points
                treeBoundBox patchBb
                (
                    treeBoundBox(pp.points(), pp.meshPoints()).extend
                    (
                        rndGen,
                        1e-4
                    )
                );
370
371
                patchBb.min() -= point::uniform(ROOTVSMALL);
                patchBb.max() += point::uniform(ROOTVSMALL);
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415

                indexedOctree<treeDataPoint> boundaryTree
                (
                    treeDataPoint   // all information needed to search faces
                    (
                        mesh.points(),
                        pp.meshPoints() // selection of points to search on
                    ),
                    patchBb,        // overall search domain
                    8,              // maxLevel
                    10,             // leafsize
                    3.0             // duplicity
                );

                forAll(samples, sampleI)
                {
                    const point& sample = samples[sampleI];

                    pointIndexHit& nearInfo = nearest[sampleI].first();
                    nearInfo = boundaryTree.findNearest
                    (
                        sample,
                        magSqr(patchBb.span())
                    );

                    if (!nearInfo.hit())
                    {
                        nearest[sampleI].second().first() = Foam::sqr(GREAT);
                        nearest[sampleI].second().second() =
                            Pstream::myProcNo();
                    }
                    else
                    {
                        const point& pt = nearInfo.hitPoint();

                        nearest[sampleI].second().first() = magSqr(pt-sample);
                        nearest[sampleI].second().second() =
                            Pstream::myProcNo();
                    }
                }
            }
            break;
        }

416
417
        case NEARESTFACE:
        {
418
            if (samplePatch().size() && samplePatch() != "none")
419
            {
420
421
                FatalErrorInFunction
                    << "No need to supply a patch name when in "
422
                    << sampleModeNames_[mode] << " mode." << exit(FatalError);
423
424
            }

425
426
427
            //- Note: face-diagonal decomposition
            const meshSearchMeshObject& meshSearchEngine =
                meshSearchMeshObject::New(mesh);
428
429
430
431
432

            forAll(samples, sampleI)
            {
                const point& sample = samples[sampleI];

433
                label facei = meshSearchEngine.findNearestFace(sample);
434

435
                if (facei == -1)
436
437
438
439
440
441
                {
                    nearest[sampleI].second().first() = Foam::sqr(GREAT);
                    nearest[sampleI].second().second() = Pstream::myProcNo();
                }
                else
                {
442
                    const point& fc = mesh.faceCentres()[facei];
443
444
445
446
447

                    nearest[sampleI].first() = pointIndexHit
                    (
                        true,
                        fc,
448
                        facei
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
                    );
                    nearest[sampleI].second().first() = magSqr(fc-sample);
                    nearest[sampleI].second().second() = Pstream::myProcNo();
                }
            }
            break;
        }

        case NEARESTPATCHFACEAMI:
        {
            // nothing to do here
            return;
        }

        default:
        {
465
            FatalErrorInFunction
466
467
468
469
470
                << "problem." << abort(FatalError);
        }
    }


471
    // Find nearest. Combine on master.
472
473
474
    Pstream::listCombineGather(nearest, nearestEqOp());
    Pstream::listCombineScatter(nearest);

475

476
477
    if (debug)
    {
478
479
480
        InfoInFunction
            << "mesh " << sampleRegion() << " : " << endl;

481
482
        forAll(nearest, sampleI)
        {
483
            label proci = nearest[sampleI].second().second();
484
485
486
            label localI = nearest[sampleI].first().index();

            Info<< "    " << sampleI << " coord:"<< samples[sampleI]
487
                << " found on processor:" << proci
488
489
490
                << " in local cell/face/point:" << localI
                << " with location:" << nearest[sampleI].first().rawPoint()
                << endl;
491
492
493
494
495
496
497
498
499
500
        }
    }

    // Convert back into proc+local index
    sampleProcs.setSize(samples.size());
    sampleIndices.setSize(samples.size());
    sampleLocations.setSize(samples.size());

    forAll(nearest, sampleI)
    {
501
502
503
504
505
506
507
508
509
510
511
512
        if (!nearest[sampleI].first().hit())
        {
            sampleProcs[sampleI] = -1;
            sampleIndices[sampleI] = -1;
            sampleLocations[sampleI] = vector::max;
        }
        else
        {
            sampleProcs[sampleI] = nearest[sampleI].second().second();
            sampleIndices[sampleI] = nearest[sampleI].first().index();
            sampleLocations[sampleI] = nearest[sampleI].first().hitPoint();
        }
513
514
515
516
517
518
    }
}


void Foam::mappedPatchBase::calcMapping() const
{
519
    static bool hasWarned = false;
520
521
    if (mapPtr_.valid())
    {
522
        FatalErrorInFunction
523
524
525
            << "Mapping already calculated" << exit(FatalError);
    }

526
527
528
529
530
    // Get points on face (since cannot use face-centres - might be off
    // face-diagonal decomposed tets.
    tmp<pointField> patchPoints(facePoints(patch_));

    // Get offsetted points
531
    const pointField offsettedPoints(samplePoints(patchPoints()));
532

533
534
    // Do a sanity check - am I sampling my own patch?
    // This only makes sense for a non-zero offset.
535
536
537
    bool sampleMyself =
    (
        mode_ == NEARESTPATCHFACE
538
539
     && sampleRegion() == patch_.boundaryMesh().mesh().name()
     && samplePatch() == patch_.name()
540
541
542
    );

    // Check offset
543
544
545
546
    vectorField d(offsettedPoints-patchPoints());
    bool coincident = (gAverage(mag(d)) <= ROOTVSMALL);

    if (sampleMyself && coincident)
547
    {
548
549
        WarningInFunction
            << "Invalid offset " << d << endl
550
551
552
553
554
555
556
            << "Offset is the vector added to the patch face centres to"
            << " find the patch face supplying the data." << endl
            << "Setting it to " << d
            << " on the same patch, on the same region"
            << " will find the faces themselves which does not make sense"
            << " for anything but testing." << endl
            << "patch_:" << patch_.name() << endl
557
            << "sampleRegion_:" << sampleRegion() << endl
558
            << "mode_:" << sampleModeNames_[mode_] << endl
559
            << "samplePatch_:" << samplePatch() << endl
560
561
562
563
564
565
566
567
            << "offsetMode_:" << offsetModeNames_[offsetMode_] << endl;
    }

    // Get global list of all samples and the processor and face they come from.
    pointField samples;
    labelList patchFaceProcs;
    labelList patchFaces;
    pointField patchFc;
568
569
570
571
572
573
574
575
576
    collectSamples
    (
        patchPoints,
        samples,
        patchFaceProcs,
        patchFaces,
        patchFc
    );

577
578
579
580
    // Find processor and cell/face samples are in and actual location.
    labelList sampleProcs;
    labelList sampleIndices;
    pointField sampleLocations;
581
    findSamples(mode_, samples, sampleProcs, sampleIndices, sampleLocations);
582

583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
    // Check for samples that were not found. This will only happen for
    // NEARESTCELL since finds cell containing a location
    if (mode_ == NEARESTCELL)
    {
        label nNotFound = 0;
        forAll(sampleProcs, sampleI)
        {
            if (sampleProcs[sampleI] == -1)
            {
                nNotFound++;
            }
        }
        reduce(nNotFound, sumOp<label>());

        if (nNotFound > 0)
        {
            if (!hasWarned)
            {
601
602
                WarningInFunction
                    << "Did not find " << nNotFound
603
604
                    << " out of " << sampleProcs.size() << " total samples."
                    << " Sampling these on owner cell centre instead." << endl
605
                    << "On patch " << patch_.name()
606
                    << " on region " << sampleRegion()
607
                    << " in mode " << sampleModeNames_[mode_] << endl
608
609
                    << "with offset mode " << offsetModeNames_[offsetMode_]
                    << ". Suppressing further warnings from " << type() << endl;
610
611
612
613

                hasWarned = true;
            }

614
615
616
            // Collect the samples that cannot be found
            DynamicList<label> subMap;
            DynamicField<point> subSamples;
617
618
619
620
621

            forAll(sampleProcs, sampleI)
            {
                if (sampleProcs[sampleI] == -1)
                {
622
623
                    subMap.append(sampleI);
                    subSamples.append(samples[sampleI]);
624
625
626
                }
            }

627
628
629
630
631
632
633
634
635
636
637
638
639
640
            // And re-search for pure nearest (should not fail)
            labelList subSampleProcs;
            labelList subSampleIndices;
            pointField subSampleLocations;
            findSamples
            (
                NEARESTONLYCELL,
                subSamples,
                subSampleProcs,
                subSampleIndices,
                subSampleLocations
            );

            // Insert
641
642
            labelUIndList(sampleProcs, subMap) = subSampleProcs;
            labelUIndList(sampleIndices, subMap) = subSampleIndices;
643
            UIndirectList<point>(sampleLocations, subMap) = subSampleLocations;
644
645
646
        }
    }

647
648
649
650
651
652
653
654
655
656
657
658
659
    // Now we have all the data we need:
    // - where sample originates from (so destination when mapping):
    //   patchFaces, patchFaceProcs.
    // - cell/face sample is in (so source when mapping)
    //   sampleIndices, sampleProcs.

    //forAll(samples, i)
    //{
    //    Info<< i << " need data in region "
    //        << patch_.boundaryMesh().mesh().name()
    //        << " for proc:" << patchFaceProcs[i]
    //        << " face:" << patchFaces[i]
    //        << " at:" << patchFc[i] << endl
660
    //        << "Found data in region " << sampleRegion()
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
    //        << " at proc:" << sampleProcs[i]
    //        << " face:" << sampleIndices[i]
    //        << " at:" << sampleLocations[i]
    //        << nl << endl;
    //}



    if (debug && Pstream::master())
    {
        OFstream str
        (
            patch_.boundaryMesh().mesh().time().path()
          / patch_.name()
          + "_mapped.obj"
        );
        Pout<< "Dumping mapping as lines from patch faceCentres to"
678
679
            << " sampled cell/faceCentres/points to file " << str.name()
            << endl;
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701

        label vertI = 0;

        forAll(patchFc, i)
        {
            meshTools::writeOBJ(str, patchFc[i]);
            vertI++;
            meshTools::writeOBJ(str, sampleLocations[i]);
            vertI++;
            str << "l " << vertI-1 << ' ' << vertI << nl;
        }
    }

    // Determine schedule.
    mapPtr_.reset(new mapDistribute(sampleProcs, patchFaceProcs));

    // Rework the schedule from indices into samples to cell data to send,
    // face data to receive.

    labelListList& subMap = mapPtr_().subMap();
    labelListList& constructMap = mapPtr_().constructMap();

702
    forAll(subMap, proci)
703
    {
704
705
        subMap[proci] = labelUIndList(sampleIndices, subMap[proci]);
        constructMap[proci] = labelUIndList(patchFaces, constructMap[proci]);
706
707
708

        //if (debug)
        //{
709
710
711
        //    Pout<< "To proc:" << proci << " sending values of cells/faces:"
        //        << subMap[proci] << endl;
        //    Pout<< "From proc:" << proci
712
        //        << " receiving values of patch faces:"
713
        //        << constructMap[proci] << endl;
714
715
716
717
718
719
720
721
722
        //}
    }

    // Redo constructSize
    mapPtr_().constructSize() = patch_.size();

    if (debug)
    {
        // Check that all elements get a value.
723
        bitSet used(patch_.size());
724
        forAll(constructMap, proci)
725
        {
726
            const labelList& map = constructMap[proci];
727
728
729

            forAll(map, i)
            {
730
                label facei = map[i];
731

732
                if (used.test(facei))
733
                {
734
                    FatalErrorInFunction
735
                        << "On patch " << patch_.name()
736
                        << " patchface " << facei
737
738
739
                        << " is assigned to more than once."
                        << abort(FatalError);
                }
740
741
742
743
                else
                {
                    used.set(facei);
                }
744
745
            }
        }
746
        forAll(used, facei)
747
        {
748
            if (!used.test(facei))
749
            {
750
                FatalErrorInFunction
751
                    << "On patch " << patch_.name()
752
                    << " patchface " << facei
753
754
755
756
757
758
759
760
761
762
763
                    << " is never assigned to."
                    << abort(FatalError);
            }
        }
    }
}


const Foam::autoPtr<Foam::searchableSurface>& Foam::mappedPatchBase::surfPtr()
const
{
764
    const word surfType(surfDict_.getOrDefault<word>("type", "none"));
765
766
767

    if (!surfPtr_.valid() && surfType != "none")
    {
768
        word surfName(surfDict_.getOrDefault("name", patch_.name()));
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794

        const polyMesh& mesh = patch_.boundaryMesh().mesh();

        surfPtr_ =
            searchableSurface::New
            (
                surfType,
                IOobject
                (
                    surfName,
                    mesh.time().constant(),
                    "triSurface",
                    mesh,
                    IOobject::MUST_READ,
                    IOobject::NO_WRITE
                ),
                surfDict_
            );
    }

    return surfPtr_;
}


void Foam::mappedPatchBase::calcAMI() const
{
Andrew Heather's avatar
Andrew Heather committed
795
    if (AMIPtr_->upToDate())
796
    {
797
        DebugInFunction
Andrew Heather's avatar
Andrew Heather committed
798
799
            << "AMI already up-to-date"
            << endl;
800
801

        return;
802
803
    }

804
    const polyPatch& nbr = samplePolyPatch();
805

806
807
    // Transform neighbour patch to local system
    pointField nbrPoints(samplePoints(nbr.localPoints()));
808

809
810
811
    primitivePatch nbrPatch0
    (
        SubList<face>
812
        (
813
814
815
816
817
818
819
820
821
822
823
            nbr.localFaces(),
            nbr.size()
        ),
        nbrPoints
    );


    if (debug)
    {
        OFstream os(patch_.name() + "_neighbourPatch-org.obj");
        meshTools::writeOBJ(os, samplePolyPatch().localFaces(), nbrPoints);
824
825
826
827
828
829
830

        OFstream osN(patch_.name() + "_neighbourPatch-trans.obj");
        meshTools::writeOBJ(osN, nbrPatch0, nbrPoints);

        OFstream osO(patch_.name() + "_ownerPatch.obj");
        meshTools::writeOBJ(osO, patch_.localFaces(), patch_.localPoints());
    }
831

832
    // Construct/apply AMI interpolation to determine addressing and weights
Andrew Heather's avatar
Andrew Heather committed
833
    AMIPtr_->calculate(patch_, nbrPatch0, surfPtr());
834
835
836
837
838
}


// * * * * * * * * * * * * Constructors  * * * * * * * * * * * * * * * * * * //

Andrew Heather's avatar
Andrew Heather committed
839
Foam::mappedPatchBase::mappedPatchBase(const polyPatch& pp)
840
841
842
843
:
    patch_(pp),
    sampleRegion_(patch_.boundaryMesh().mesh().name()),
    mode_(NEARESTPATCHFACE),
844
845
    samplePatch_(""),
    coupleGroup_(),
846
    offsetMode_(UNIFORM),
Henry Weller's avatar
Henry Weller committed
847
    offset_(Zero),
848
849
850
    offsets_(pp.size(), offset_),
    distance_(0),
    sameRegion_(sampleRegion_ == patch_.boundaryMesh().mesh().name()),
851
    mapPtr_(nullptr),
852
    AMIReverse_(false),
Andrew Heather's avatar
Andrew Heather committed
853
    AMIPtr_(new faceAreaWeightAMI(true, AMIReverse_)),
854
    surfPtr_(nullptr),
855
    surfDict_(fileName("surface"))
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
{}


Foam::mappedPatchBase::mappedPatchBase
(
    const polyPatch& pp,
    const word& sampleRegion,
    const sampleMode mode,
    const word& samplePatch,
    const vectorField& offsets
)
:
    patch_(pp),
    sampleRegion_(sampleRegion),
    mode_(mode),
    samplePatch_(samplePatch),
872
    coupleGroup_(),
873
    offsetMode_(NONUNIFORM),
Henry Weller's avatar
Henry Weller committed
874
    offset_(Zero),
875
876
877
    offsets_(offsets),
    distance_(0),
    sameRegion_(sampleRegion_ == patch_.boundaryMesh().mesh().name()),
878
    mapPtr_(nullptr),
879
    AMIReverse_(false),
Andrew Heather's avatar
Andrew Heather committed
880
    AMIPtr_(new faceAreaWeightAMI(true, AMIReverse_)),
881
    surfPtr_(nullptr),
882
    surfDict_(fileName("surface"))
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
{}


Foam::mappedPatchBase::mappedPatchBase
(
    const polyPatch& pp,
    const word& sampleRegion,
    const sampleMode mode,
    const word& samplePatch,
    const vector& offset
)
:
    patch_(pp),
    sampleRegion_(sampleRegion),
    mode_(mode),
    samplePatch_(samplePatch),
899
    coupleGroup_(),
900
901
902
903
904
    offsetMode_(UNIFORM),
    offset_(offset),
    offsets_(0),
    distance_(0),
    sameRegion_(sampleRegion_ == patch_.boundaryMesh().mesh().name()),
905
    mapPtr_(nullptr),
906
    AMIReverse_(false),
Andrew Heather's avatar
Andrew Heather committed
907
    AMIPtr_(new faceAreaWeightAMI(true, AMIReverse_)),
908
    surfPtr_(nullptr),
909
    surfDict_(fileName("surface"))
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
{}


Foam::mappedPatchBase::mappedPatchBase
(
    const polyPatch& pp,
    const word& sampleRegion,
    const sampleMode mode,
    const word& samplePatch,
    const scalar distance
)
:
    patch_(pp),
    sampleRegion_(sampleRegion),
    mode_(mode),
    samplePatch_(samplePatch),
926
    coupleGroup_(),
927
    offsetMode_(NORMAL),
Henry Weller's avatar
Henry Weller committed
928
    offset_(Zero),
929
930
931
    offsets_(0),
    distance_(distance),
    sameRegion_(sampleRegion_ == patch_.boundaryMesh().mesh().name()),
932
    mapPtr_(nullptr),
933
    AMIReverse_(false),
Andrew Heather's avatar
Andrew Heather committed
934
    AMIPtr_(new faceAreaWeightAMI(true, AMIReverse_)),
935
    surfPtr_(nullptr),
936
    surfDict_(fileName("surface"))
937
938
939
940
941
942
943
944
945
946
{}


Foam::mappedPatchBase::mappedPatchBase
(
    const polyPatch& pp,
    const dictionary& dict
)
:
    patch_(pp),
947
    sampleRegion_(dict.getOrDefault<word>("sampleRegion", "")),
Mark OLESEN's avatar
Mark OLESEN committed
948
    mode_(sampleModeNames_.get("sampleMode", dict)),
949
    samplePatch_(dict.getOrDefault<word>("samplePatch", "")),
950
    coupleGroup_(dict),
951
    offsetMode_(UNIFORM),
Henry Weller's avatar
Henry Weller committed
952
    offset_(Zero),
953
954
    offsets_(),
    distance_(0),
955
    sameRegion_(sampleRegion_ == patch_.boundaryMesh().mesh().name()),
956
    mapPtr_(nullptr),
957
    AMIReverse_(dict.getOrDefault("flipNormals", false)),
Andrew Heather's avatar
Andrew Heather committed
958
959
960
961
962
963
964
965
966
    AMIPtr_
    (
        AMIInterpolation::New
        (
            dict.getOrDefault("AMIMethod", faceAreaWeightAMI::typeName),
            dict,
            AMIReverse_
        )
    ),
967
    surfPtr_(nullptr),
968
969
    surfDict_(dict.subOrEmptyDict("surface"))
{
970
971
972
973
974
975
976
977
978
979
    if (!coupleGroup_.valid())
    {
        if (sampleRegion_.empty())
        {
            // If no coupleGroup and no sampleRegion assume local region
            sampleRegion_ = patch_.boundaryMesh().mesh().name();
            sameRegion_ = true;
        }
    }

Mark OLESEN's avatar
Mark OLESEN committed
980
    if (offsetModeNames_.readIfPresent("offsetMode", dict, offsetMode_))
981
    {
Mark OLESEN's avatar
Mark OLESEN committed
982
        switch (offsetMode_)
983
984
985
        {
            case UNIFORM:
            {
986
                dict.readEntry("offset", offset_);
987
988
989
990
991
            }
            break;

            case NONUNIFORM:
            {
992
                offsets_ = pointField("offsets", dict, patch_.size());
993
994
995
996
997
            }
            break;

            case NORMAL:
            {
998
                dict.readEntry("distance", distance_);
999
1000
1001
1002
            }
            break;
        }
    }
1003
    else if (dict.readIfPresent("offset", offset_))
1004
1005
1006
1007
1008
1009
    {
        offsetMode_ = UNIFORM;
    }
    else if (dict.found("offsets"))
    {
        offsetMode_ = NONUNIFORM;
1010
        offsets_ = pointField("offsets", dict, patch_.size());
1011
    }
1012
    else if (mode_ != NEARESTPATCHFACE && mode_ != NEARESTPATCHFACEAMI)
1013
    {
1014
1015
        FatalIOErrorInFunction(dict)
            << "Please supply the offsetMode as one of "
Mark OLESEN's avatar
Mark OLESEN committed
1016
            << offsetModeNames_
1017
1018
1019
1020
1021
            << exit(FatalIOError);
    }
}


1022
1023
1024
1025
1026
1027
1028
1029
Foam::mappedPatchBase::mappedPatchBase
(
    const polyPatch& pp,
    const sampleMode mode,
    const dictionary& dict
)
:
    patch_(pp),
1030
    sampleRegion_(dict.getOrDefault<word>("sampleRegion", "")),
1031
    mode_(mode),
1032
1033
    samplePatch_(dict.getOrDefault<word>("samplePatch", "")),
    coupleGroup_(dict), //dict.getOrDefault<word>("coupleGroup", "")),
1034
    offsetMode_(UNIFORM),
Henry Weller's avatar
Henry Weller committed
1035
    offset_(Zero),
1036
    offsets_(0),
1037
    distance_(0),
1038
    sameRegion_(sampleRegion_ == patch_.boundaryMesh().mesh().name()),
1039
    mapPtr_(nullptr),
1040
    AMIReverse_(dict.getOrDefault("flipNormals", false)),
Andrew Heather's avatar
Andrew Heather committed
1041
1042
1043
1044
    AMIPtr_
    (
        AMIInterpolation::New
        (
1045
            dict.getOrDefault("AMIMethod", faceAreaWeightAMI::typeName),
Andrew Heather's avatar
Andrew Heather committed
1046
1047
1048
1049
            dict,
            AMIReverse_
        )
    ),
1050
    surfPtr_(nullptr),
1051
1052
1053
1054
    surfDict_(dict.subOrEmptyDict("surface"))
{
    if (mode != NEARESTPATCHFACE && mode != NEARESTPATCHFACEAMI)
    {
1055
1056
        FatalIOErrorInFunction(dict)
            << "Construct from sampleMode and dictionary only applicable for "
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
            << " collocated patches in modes "
            << sampleModeNames_[NEARESTPATCHFACE] << ','
            << sampleModeNames_[NEARESTPATCHFACEAMI]
            << exit(FatalIOError);
    }


    if (!coupleGroup_.valid())
    {
        if (sampleRegion_.empty())
        {
            // If no coupleGroup and no sampleRegion assume local region
            sampleRegion_ = patch_.boundaryMesh().mesh().name();
            sameRegion_ = true;
        }
    }
}


1076
1077
1078
Foam::mappedPatchBase::mappedPatchBase
(
    const polyPatch& pp,
1079
    const mappedPatchBase& mpb
1080
1081
1082
)
:
    patch_(pp),
1083
1084
1085
    sampleRegion_(mpb.sampleRegion_),
    mode_(mpb.mode_),
    samplePatch_(mpb.samplePatch_),
1086
    coupleGroup_(mpb.coupleGroup_),
1087
1088
1089
1090
1091
    offsetMode_(mpb.offsetMode_),
    offset_(mpb.offset_),
    offsets_(mpb.offsets_),
    distance_(mpb.distance_),
    sameRegion_(mpb.sameRegion_),
1092
    mapPtr_(nullptr),
1093
    AMIReverse_(mpb.AMIReverse_),
Andrew Heather's avatar
Andrew Heather committed
1094
    AMIPtr_(mpb.AMIPtr_->clone()),
1095
    surfPtr_(nullptr),
1096
    surfDict_(mpb.surfDict_)
1097
1098
1099
1100
1101
1102
{}


Foam::mappedPatchBase::mappedPatchBase
(
    const polyPatch& pp,
1103
    const mappedPatchBase& mpb,
1104
1105
1106
1107
    const labelUList& mapAddressing
)
:
    patch_(pp),
1108
1109
1110
    sampleRegion_(mpb.sampleRegion_),
    mode_(mpb.mode_),
    samplePatch_(mpb.samplePatch_),
1111
    coupleGroup_(mpb.coupleGroup_),
1112
1113
    offsetMode_(mpb.offsetMode_),
    offset_(mpb.offset_),
1114
1115
1116
1117
    offsets_
    (
        offsetMode_ == NONUNIFORM
      ? vectorField(mpb.offsets_, mapAddressing)
1118
      : vectorField()
1119
    ),
1120
1121
    distance_(mpb.distance_),
    sameRegion_(mpb.sameRegion_),
1122
    mapPtr_(nullptr),
1123
    AMIReverse_(mpb.AMIReverse_),
Andrew Heather's avatar
Andrew Heather committed
1124
    AMIPtr_(mpb.AMIPtr_->clone()),
1125
    surfPtr_(nullptr),
1126
    surfDict_(mpb.surfDict_)
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
{}


// * * * * * * * * * * * * * * * * Destructor  * * * * * * * * * * * * * * * //

Foam::mappedPatchBase::~mappedPatchBase()
{
    clearOut();
}


void Foam::mappedPatchBase::clearOut()
{
    mapPtr_.clear();
1141
    surfPtr_.clear();
Andrew Heather's avatar
Andrew Heather committed
1142
    AMIPtr_->upToDate() = false;
1143
1144
1145
1146
1147
1148
1149
}


// * * * * * * * * * * * * * * * Member Functions  * * * * * * * * * * * * * //

const Foam::polyMesh& Foam::mappedPatchBase::sampleMesh() const
{
1150
1151
1152
    const polyMesh& thisMesh = patch_.boundaryMesh().mesh();

    return
1153
    (
1154
1155
1156
        sameRegion_
      ? thisMesh
      : thisMesh.time().lookupObject<polyMesh>(sampleRegion())
1157
1158
1159
1160
1161
1162
1163
1164
    );
}


const Foam::polyPatch& Foam::mappedPatchBase::samplePolyPatch() const
{
    const polyMesh& nbrMesh = sampleMesh();

1165
    const label patchi = nbrMesh.boundaryMesh().findPatchID(samplePatch());
1166

1167
    if (patchi == -1)
1168
    {
1169
        FatalErrorInFunction
1170
            << "Cannot find patch " << samplePatch()
1171
1172
1173
1174
1175
            << " in region " << sampleRegion_ << endl
            << "Valid patches are " << nbrMesh.boundaryMesh().names()
            << exit(FatalError);
    }

1176
    return nbrMesh.boundaryMesh()[patchi];
1177
1178
1179
}


1180
1181
1182
1183
Foam::tmp<Foam::pointField> Foam::mappedPatchBase::samplePoints
(
    const pointField& fc
) const
1184
{
1185
    tmp<pointField> tfld(new pointField(fc));
1186
    pointField& fld = tfld.ref();
1187

1188
    switch (offsetMode_)
1189
1190
1191
1192
    {
        case UNIFORM:
        {
            fld += offset_;
1193
            break;
1194
1195
1196
1197
        }
        case NONUNIFORM:
        {
            fld += offsets_;
1198
            break;
1199
1200
1201
1202
1203
1204
1205
1206
        }
        case NORMAL:
        {
            // Get outwards pointing normal
            vectorField n(patch_.faceAreas());
            n /= mag(n);

            fld += distance_*n;
1207
            break;
1208
1209
1210
1211
1212
1213
1214
        }
    }

    return tfld;
}


1215
1216
1217
1218
1219
1220
Foam::tmp<Foam::pointField> Foam::mappedPatchBase::samplePoints() const
{
    return samplePoints(facePoints(patch_));
}


1221
1222
1223
Foam::pointIndexHit Foam::mappedPatchBase::facePoint
(
    const polyMesh& mesh,
1224
    const label facei,
1225
    const polyMesh::cellDecomposition decompMode
1226
1227
)
{
1228
    const point& fc = mesh.faceCentres()[facei];
1229
1230
1231

    switch (decompMode)
    {
1232
1233
        case polyMesh::FACE_PLANES:
        case polyMesh::FACE_CENTRE_TRIS:
1234
1235
1236
        {
            // For both decompositions the face centre is guaranteed to be
            // on the face
1237
            return pointIndexHit(true, fc, facei);
1238
1239
1240
        }
        break;

1241
1242
        case polyMesh::FACE_DIAG_TRIS:
        case polyMesh::CELL_TETS:
1243
        {
1244
            // Find the intersection of a ray from face centre to cell centre
1245
1246
1247
1248
            // Find intersection of (face-centre-decomposition) centre to
            // cell-centre with face-diagonal-decomposition triangles.

            const pointField& p = mesh.points();
1249
            const face& f = mesh.faces()[facei];
1250
1251
1252
1253
1254
1255
1256

            if (f.size() <= 3)
            {
                // Return centre of triangle.
                return pointIndexHit(true, fc, 0);
            }

1257
1258
            label celli = mesh.faceOwner()[facei];
            const point& cc = mesh.cellCentres()[celli];
1259
1260
            vector d = fc-cc;

1261
            const label fp0 = mesh.tetBasePtIs()[facei];
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
            const point& basePoint = p[f[fp0]];

            label fp = f.fcIndex(fp0);
            for (label i = 2; i < f.size(); i++)
            {
                const point& thisPoint = p[f[fp]];
                label nextFp = f.fcIndex(fp);
                const point& nextPoint = p[f[nextFp]];

                const triPointRef tri(basePoint, thisPoint, nextPoint);
                pointHit hitInfo = tri.intersection
                (
                    cc,
                    d,
                    intersection::HALF_RAY
                );

                if (hitInfo.hit() && hitInfo.distance() > 0)
                {
                    return pointIndexHit(true, hitInfo.hitPoint(), i-2);
                }

                fp = nextFp;
            }

            // Fall-back
            return pointIndexHit(false, fc, -1);
        }
        break;

        default:
        {
1294
            FatalErrorInFunction
1295
1296
1297
1298
1299
1300
1301
                << "problem" << abort(FatalError);
            return pointIndexHit();
        }
    }
}


1302
1303
void Foam::mappedPatchBase::write(Ostream& os) const
{
1304
    os.writeEntry("sampleMode", sampleModeNames_[mode_]);
1305
1306
    if (!sampleRegion_.empty())
    {
1307
        os.writeEntry("sampleRegion", sampleRegion_);
1308
1309
1310
    }
    if (!samplePatch_.empty())
    {
1311
        os.writeEntry("samplePatch", samplePatch_);
1312
    }
1313
    coupleGroup_.write(os);
1314

1315
1316
1317
1318
1319
1320