vtkParticleTracerBase.cxx 54.6 KB
Newer Older
1
2
/*=========================================================================

3
4
  Program:   Visualization Toolkit
  Module:    vtkParticleTracerBase.cxx
5

6
7
8
  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
9

10
11
12
  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notice for more information.
13

14
  =========================================================================*/
15
16
#include "vtkParticleTracerBase.h"

17
#include "vtkAbstractParticleWriter.h"
18
19
#include "vtkCellArray.h"
#include "vtkCellData.h"
20
#include "vtkCharArray.h"
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include "vtkCompositeDataIterator.h"
#include "vtkDoubleArray.h"
#include "vtkExecutive.h"
#include "vtkGenericCell.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkIntArray.h"
#include "vtkFloatArray.h"
#include "vtkMath.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkRungeKutta2.h"
#include "vtkRungeKutta4.h"
#include "vtkRungeKutta45.h"
#include "vtkSmartPointer.h"
38
#include "vtkStreamingDemandDrivenPipeline.h"
39
#include "vtkTemporalInterpolatedVelocityField.h"
40
#include <cassert>
41
42

#ifdef WIN32
43
#undef JB_H5PART_PARTICLE_OUTPUT
44
45
46
47
48
49
#else
//  #define JB_H5PART_PARTICLE_OUTPUT
#endif

#ifdef JB_H5PART_PARTICLE_OUTPUT
// #include "vtkH5PartWriter.h"
50
#include "vtkXMLParticleWriter.h"
51
52
53
#endif

#include <functional>
54
#include <algorithm>
55
56
57
58
59
60
61
62
63
64
65
66
67
#ifdef DEBUGPARTICLETRACE
#define Assert(x) assert(x)
#define PRINT(x) cout<<__LINE__<<": "<<x<<endl;
#else
#define PRINT(x)
#define Assert(x)
#endif

const double vtkParticleTracerBase::Epsilon = 1.0E-12;

using namespace vtkParticleTracerBaseNamespace;

vtkCxxSetObjectMacro(vtkParticleTracerBase, ParticleWriter, vtkAbstractParticleWriter);
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
vtkCxxSetObjectMacro(vtkParticleTracerBase,Integrator,vtkInitialValueProblemSolver);

// this SetMacro is different than the regular vtkSetMacro
// because it resets the cache as well.
#define ParticleTracerSetMacro(name,type)               \
  void vtkParticleTracerBase::Set##name (type _arg)     \
  {                                                     \
    if (this->name == _arg)                             \
      {                                                 \
      return;                                           \
      }                                                 \
    this->name = _arg;                                  \
    this->ResetCache();                                 \
    this->Modified();                                   \
  }
ParticleTracerSetMacro(StartTime, double)
ParticleTracerSetMacro(ComputeVorticity, bool);
ParticleTracerSetMacro(RotationScale, double)
ParticleTracerSetMacro(ForceReinjectionEveryNSteps,int);
ParticleTracerSetMacro(TerminalSpeed, double);
88
89
90
91
92
93
94
95
96
97
98

namespace
{
  //return the interval i, such that a belongs to the interval (A[i],A[i+1]]
  inline int FindInterval(double a, const std::vector<double>& A)
  {
    if( a < A[0])
      {
      return -1;
      }

Yuanxin Liu's avatar
Yuanxin Liu committed
99
    for(size_t i=0; i< A.size()-1;i++)
100
101
102
      {
      if(a <= A[i+1])
        {
Yuanxin Liu's avatar
Yuanxin Liu committed
103
        return static_cast<int>(i);
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
        }
      }

    return -1;
  }
};

//---------------------------------------------------------------------------
vtkParticleTracerBase::vtkParticleTracerBase()
{
  // by default process active point vectors
  this->SetInputArrayToProcess(0,0,0,vtkDataObject::FIELD_ASSOCIATION_POINTS,
                               vtkDataSetAttributes::VECTORS);

  this->CurrentTimeStep             = 0;
119
  this->CurrentTimeValue            = 0;
120
121
122
  this->ForceReinjectionEveryNSteps = 0;
  this->ReinjectionCounter          = 0;
  this->AllFixedGeometry            = 1;
123
124
  this->StaticMesh                  = 0;
  this->StaticSeeds                 = 0;
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
  this->ComputeVorticity            = 1;
  this->IgnorePipelineTime          = 1;
  this->ParticleWriter              = NULL;
  this->ParticleFileName            = NULL;
  this->EnableParticleWriting       = false;
  this->UniqueIdCounter             = 0;
  this->Integrator                  = NULL;

  this->StartTime = 0.0;
  this->TerminationTime       = 0.0;
  this->FirstIteration = true;
  this->HasCache = false;

  this->RotationScale    = 1.0;
  this->MaximumError         = 1.0e-6;
  this->TerminalSpeed = vtkParticleTracerBase::Epsilon;
  this->IntegrationStep = 0.5;
142

143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
  this->Interpolator = vtkSmartPointer<vtkTemporalInterpolatedVelocityField>::New();
  this->SetNumberOfInputPorts(2);

#ifdef JB_H5PART_PARTICLE_OUTPUT
#ifdef WIN32
  vtkDebugMacro(<<"Setting vtkH5PartWriter");
  vtkH5PartWriter *writer = vtkH5PartWriter::New();
#else
  vtkDebugMacro(<<"Setting vtkXMLParticleWriter");
  vtkXMLParticleWriter *writer = vtkXMLParticleWriter::New();
#endif
  this->SetParticleWriter(writer);
  writer->Delete();
#endif

  this->SetIntegratorType(RUNGE_KUTTA4);
159
  this->DisableResetCache = 0;
160
}
161

162
163
164
165
//---------------------------------------------------------------------------
vtkParticleTracerBase::~vtkParticleTracerBase()
{
  this->SetParticleWriter(NULL);
166
  this->SetParticleFileName(NULL);
167
168

  this->CachedData[0] = NULL;
169
  this->CachedData[1] = NULL;
170
171
172
173

  this->SetIntegrator(0);
  this->SetInterpolatorPrototype(0);
}
174

175
176
//----------------------------------------------------------------------------
int vtkParticleTracerBase::FillInputPortInformation(
177
  int port, vtkInformation* info)
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
{
  // port 0 must be a temporal collection of any type
  // the executive should put a temporal collection in when
  // we request multiple time steps.
  if (port==0)
    {
    info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataObject");
    info->Set(vtkAlgorithm::INPUT_IS_REPEATABLE(), 1);
    }
  else if (port==1)
    {
    info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet");
    info->Set(vtkAlgorithm::INPUT_IS_REPEATABLE(), 1);
    }
  return 1;
}
194

195
196
197
198
199
//----------------------------------------------------------------------------
void vtkParticleTracerBase::AddSourceConnection(vtkAlgorithmOutput* input)
{
  this->AddInputConnection(1, input);
}
200

201
202
203
204
205
//----------------------------------------------------------------------------
void vtkParticleTracerBase::RemoveAllSources()
{
  this->SetInputConnection(1, 0);
}
206

207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
//----------------------------------------------------------------------------
int vtkParticleTracerBase::ProcessRequest(
  vtkInformation* request,
  vtkInformationVector** inputVector,
  vtkInformationVector* outputVector)
{
  if(request->Has(vtkDemandDrivenPipeline::REQUEST_INFORMATION()))
    {
    if(this->FirstIteration)
      {
      return this->RequestInformation(request, inputVector, outputVector);
      }
    }
  if(request->Has(vtkStreamingDemandDrivenPipeline::REQUEST_UPDATE_EXTENT()))
    {
222
    return this->RequestUpdateExtent(request, inputVector, outputVector);
223
224
225
226
227
228
229
    }
  if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA()))
    {
    return this->RequestData(request, inputVector, outputVector);
    }
  return 1;
}
230

231
232
233
234
//----------------------------------------------------------------------------
int vtkParticleTracerBase::RequestInformation(
  vtkInformation *vtkNotUsed(request),
  vtkInformationVector **inputVector,
235
  vtkInformationVector *vtkNotUsed(outputVector))
236
237
238
239
240
{
  vtkInformation *inInfo  = inputVector[0]->GetInformationObject(0);

  if (inInfo->Has(vtkStreamingDemandDrivenPipeline::TIME_STEPS()) )
    {
241
242
    unsigned int numberOfInputTimeSteps =
      inInfo->Length(vtkStreamingDemandDrivenPipeline::TIME_STEPS());
243
    vtkDebugMacro(<<"vtkParticleTracerBase "
244
                  "inputVector TIME_STEPS " << numberOfInputTimeSteps);
245
246
247
248
    //
    // Get list of input time step values
    this->InputTimeValues.resize(numberOfInputTimeSteps);
    inInfo->Get( vtkStreamingDemandDrivenPipeline::TIME_STEPS(),
249
                 &this->InputTimeValues[0] );
250
251
    if (numberOfInputTimeSteps==1 && this->DisableResetCache==0)
      {  //warning would be skipped in coprocessing work flow
252
      vtkWarningMacro(<<"Not enough input time steps for particle integration");
253
      }
254
255
256
257

    //clamp the default start time to be within the data time range
    if(this->StartTime < this->InputTimeValues[0])
      {
258
      this->StartTime = this->InputTimeValues[0];
259
260
261
      }
    else if (this->StartTime > this->InputTimeValues.back())
      {
262
      this->StartTime = this->InputTimeValues.back();
263
      }
264
    }
265
266
267
268
269
270
271
272
  else
    {
    vtkErrorMacro(<<"Input information has no TIME_STEPS set");
    return 0;
    }

  return 1;
}
273
namespace
274
{
275
276
277
278
//----------------------------------------------------------------------------
  class WithinTolerance: public std::binary_function<double, double, bool>
  {
  public:
279
280
281
282
283
    result_type operator()(first_argument_type a, second_argument_type b) const
    {
      bool result = (fabs(a-b)<=(a*1E-6));
      return (result_type)result;
    }
284
285
286
  };
}

287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
//----------------------------------------------------------------------------
int vtkParticleTracerBase::RequestUpdateExtent(
  vtkInformation *vtkNotUsed(request),
  vtkInformationVector **inputVector,
  vtkInformationVector *outputVector)
{
  int numInputs = inputVector[0]->GetNumberOfInformationObjects();
  vtkInformation *outInfo = outputVector->GetInformationObject(0);

  PRINT("RUE: "<<this->HasCache<<" "<<this->FirstIteration
        <<" "<<this->StartTime<<" "<<this->TerminationTime<<" "<<this->CurrentTimeStep);
  //
  // The output has requested a time value, what times must we ask from our input
  // do this only for the first time
  if(this->FirstIteration)
    {
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
    if(this->InputTimeValues.size()==1)
      {
      this->StartTimeStep = this->InputTimeValues[0]==this->StartTime? 0 : -1;
      }
    else
      {
      this->StartTimeStep = FindInterval(this->StartTime, this->InputTimeValues);
      }

    if(this->StartTimeStep<0)
      {
      vtkErrorMacro("Start time not in time range");
      return 0;
      }

318
319
320
321
    if (!this->IgnorePipelineTime && outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP()))
      {
      double terminationTime = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP());
      PRINT("Pipeline has set termination time: "<< terminationTime);
322
      this->SetTerminationTimeNoModify(terminationTime);
323
324
325
326
327
328
329
      }

    if(this->TerminationTime> this->InputTimeValues.back())
      {
      this->TerminationTime = this->InputTimeValues.back();
      }

330
331
332
333
334
335
336
337
338
339
340
341
342
343
    if(this->InputTimeValues.size()==1)
      {
      this->TerminationTimeStep = this->TerminationTime == this->InputTimeValues[0]? 0 : -1;
      }
    else
      {
      this->TerminationTimeStep = FindInterval(this->TerminationTime, this->InputTimeValues)+1;
      }

    if(this->TerminationTimeStep<0)
      {
      vtkErrorMacro("Termination time not in time range");
      return 0;
      }
344
345
346
347
348
349
350
351
352
353
354

    for(int i=0; i<this->GetNumberOfInputPorts(); i++)
      {
      vtkAlgorithm* inputAlgorithm = this->GetInputAlgorithm(i,0);
      vtkStreamingDemandDrivenPipeline* sddp = vtkStreamingDemandDrivenPipeline::SafeDownCast(inputAlgorithm->GetExecutive());
      if(sddp)
        {
        sddp->UpdatePipelineMTime();
        unsigned long pmt = sddp->GetPipelineMTime();
        if(pmt>this->ExecuteTime.GetMTime())
          {
355
          PRINT("Reset cache of because upstream is newer")
356
            this->ResetCache();
357
358
359
360
361
362
          }
        }
      }
    if(!this->HasCache)
      {
      this->CurrentTimeStep = this->StartTimeStep;
363
      this->CurrentTimeValue = -DBL_MAX;
364
365
366
367
368
369
      }
    }

  for (int i=0; i<numInputs; i++)
    {
    vtkInformation *inInfo = inputVector[0]->GetInformationObject(i);
370
371
372
373
374
375
376
377
    if(this->CurrentTimeStep < static_cast<int>(this->InputTimeValues.size()))
      {
      inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP(), this->InputTimeValues[this->CurrentTimeStep]);
      }
    else
      {
      Assert(this->CurrentTime == this->InputTimeValues.back());
      }
378
379
380
381
    }

  return 1;
}
382

383
384
385
//---------------------------------------------------------------------------
int vtkParticleTracerBase::InitializeInterpolator()
{
386
387
388
389
390
  if (!this->CachedData[0] || !this->CachedData[1])
    {
    vtkErrorMacro("Missing data set to process.");
    return VTK_ERROR;
    }
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
  //
  // When Multiblock arrays are processed, some may be empty
  // if the first is empty, we won't find the correct vector name
  // so scan until we get one
  //
  vtkSmartPointer<vtkCompositeDataIterator> iterP;
  iterP.TakeReference(this->CachedData[0]->NewIterator());
  iterP->GoToFirstItem();
  char *vecname = NULL;
  while (!iterP->IsDoneWithTraversal())
    {
    vtkDataArray *vectors = this->GetInputArrayToProcess(
      0,iterP->GetCurrentDataObject());
    if (vectors)
      {
      vecname = vectors->GetName();
      break;
      }
    iterP->GoToNextItem();
    }
  if (!vecname)
    {
413
    vtkErrorMacro(<< "Couldn't find vector array " << vecname);
414
415
416
417
418
419
420
421
422
423
424
    return VTK_ERROR;
    }

  vtkDebugMacro(<< "Interpolator using array " << vecname);
  this->Interpolator->SelectVectors(vecname);

  this->AllFixedGeometry = 1;

  int numValidInputBlocks[2] = {0, 0};
  int numTotalInputBlocks[2] = {0, 0};
  this->DataReferenceT[0] = this->DataReferenceT[1] = 0;
425
426
  for (int T=0; T<2; T++)
    {
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
    this->CachedBounds[T].clear();
    int index = 0;
    // iterate over all blocks of input and cache the bounds information
    // and determine fixed/dynamic mesh status.

    vtkSmartPointer<vtkCompositeDataIterator> anotherIterP;
    anotherIterP.TakeReference(this->CachedData[T]->NewIterator());
    anotherIterP->GoToFirstItem();
    while (!anotherIterP->IsDoneWithTraversal())
      {
      numTotalInputBlocks[T]++;
      vtkDataSet* inp = vtkDataSet::SafeDownCast(anotherIterP->GetCurrentDataObject());
      if (inp)
        {
        if (inp->GetNumberOfCells()==0)
          {
          vtkDebugMacro("Skipping an empty dataset");
          }
        else if (!inp->GetPointData()->GetVectors(vecname) && inp->GetNumberOfPoints()>0)
          {
          vtkDebugMacro("One of the input datasets has no velocity vector.");
          }
        else
          {
          // vtkDebugMacro("pass " << i << " Found dataset with " << inp->GetNumberOfCells() << " cells");
          //
          // store the bounding boxes of each local dataset for faster 'point-in-dataset' testing
          //
          bounds bbox;
          inp->ComputeBounds();
          inp->GetBounds(&bbox.b[0]);
          this->CachedBounds[T].push_back(bbox);
Berk Geveci's avatar
Berk Geveci committed
459
          bool static_dataset = (this->StaticMesh != 0);
460
461
462
          this->AllFixedGeometry = this->AllFixedGeometry && static_dataset;
          // add the dataset to the interpolator
          this->Interpolator->SetDataSetAtTime(index++, T, this->GetCacheDataTime(T), inp, static_dataset);
463
464
          if (!this->DataReferenceT[T])
            {
465
            this->DataReferenceT[T] = inp;
466
            }
467
468
469
470
471
472
          //
          numValidInputBlocks[T]++;
          }
        }
      anotherIterP->GoToNextItem();
      }
473
    }
474
475
  if (numValidInputBlocks[0]==0 || numValidInputBlocks[1]==0)
    {
476
477
    vtkErrorMacro("Not enough inputs have been found. Can not execute."
                  << numValidInputBlocks[0] << " " << numValidInputBlocks[1]);
478
479
    return VTK_ERROR;
    }
480
  if (numValidInputBlocks[0] != numValidInputBlocks[1] && this->StaticMesh)
481
    {
482
483
    vtkErrorMacro("StaticMesh is set to True but the number of datasets is different between time steps "
                  << numValidInputBlocks[0] << " " << numValidInputBlocks[1]);
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
    return VTK_ERROR;
    }
  //
  vtkDebugMacro("Number of Valid input blocks is " << numValidInputBlocks[0] << " from " << numTotalInputBlocks[0]);
  vtkDebugMacro("AllFixedGeometry " << this->AllFixedGeometry);

  // force optimizations if StaticMesh is set.
  if (this->StaticMesh)
    {
    vtkDebugMacro("Static Mesh optimizations Forced ON");
    this->AllFixedGeometry = 1;
    }

  //
  return VTK_OK;
}
500
501

//---------------------------------------------------------------------------
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
int vtkParticleTracerBase::UpdateDataCache(vtkDataObject *data)
{
  double dataTime = data->GetInformation()->Get(vtkDataObject::DATA_TIME_STEP());

  Assert(dataTime>=this->GetCacheDataTime());
  if(dataTime== this->GetCacheDataTime())
    {
    return 1;
    }

  int i = 0;
  if(this->CurrentTimeStep==this->StartTimeStep)
    {
    i = 0;
    }
  else if (this->CurrentTimeStep==this->StartTimeStep+1)
    {
    i = 1;
    }
  else
    {
    i = 1;
    this->CachedData[0] = this->CachedData[1];
    this->CachedData[1] = NULL;
    }


  this->CachedData[i] = vtkSmartPointer<vtkMultiBlockDataSet>::New();

  // if simple dataset, add to our list, otherwise, add blocks
  vtkDataSet           *dsInput = vtkDataSet::SafeDownCast(data);
  vtkMultiBlockDataSet *mbInput = vtkMultiBlockDataSet::SafeDownCast(data);

  if (dsInput)
    {
    vtkSmartPointer<vtkDataSet> copy;
    copy.TakeReference(dsInput->NewInstance());
    copy->ShallowCopy(dsInput);
    this->CachedData[i]->SetBlock(this->CachedData[i]->GetNumberOfBlocks(), copy);
    }
  else if (mbInput)
    {
    vtkSmartPointer<vtkCompositeDataIterator> iter;
    iter.TakeReference(mbInput->NewIterator());
    for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem())
      {
      vtkDataSet *ds = vtkDataSet::SafeDownCast(iter->GetCurrentDataObject());
      if (ds)
        {
        vtkSmartPointer<vtkDataSet> copy;
        copy.TakeReference(ds->NewInstance());
        copy->ShallowCopy(ds);
        this->CachedData[i]->SetBlock(this->CachedData[i]->GetNumberOfBlocks(), copy);
        }
      }
    }
  else
    {
    vtkDebugMacro("This filter cannot handle inputs of type: "
                  << (data?data->GetClassName():"(none)"));
    return 0;
    }

  this->CachedData[i]->GetInformation()->Set(vtkDataObject::DATA_TIME_STEP(), dataTime);
  if(this->CurrentTimeStep==this->StartTimeStep)
    {
    this->CachedData[1] = this->CachedData[0];
    }
  return 1;
}

//---------------------------------------------------------------------------
bool vtkParticleTracerBase::InsideBounds(double point[])
{
  double delta[3] = { 0.0, 0.0, 0.0 };
  for (int t=0; t<2; ++t)
    {
Yuanxin Liu's avatar
Yuanxin Liu committed
579
    for (size_t i=0; i<(this->CachedBounds[t].size()); ++i)
580
581
582
583
584
585
586
587
588
      {
      if (vtkMath::PointIsWithinBounds(point, &((this->CachedBounds[t])[i].b[0]), delta))
        {
        return true;
        }
      }
    }
  return false;
}
589

590
591
592
593
594
595
596
597
598
//---------------------------------------------------------------------------
void vtkParticleTracerBase::TestParticles(
  ParticleVector &candidates, ParticleVector &passed, int &count)
{

  std::vector<int> passedIndices;
  this->TestParticles(candidates, passedIndices);
  count = static_cast<int>(passedIndices.size());

Yuanxin Liu's avatar
Yuanxin Liu committed
599
  for(size_t i=0; i<passedIndices.size();i++)
600
601
602
603
604
    {
    passed.push_back(candidates[passedIndices[i]]);
    }
}

605
606
607
608
//---------------------------------------------------------------------------
void vtkParticleTracerBase::TestParticles(
  vtkParticleTracerBaseNamespace::ParticleVector &candidates,
  std::vector<int> &passed)
609
610
611
612
613
614
615
616
617
{
  int i = 0;
  for (ParticleIterator it=candidates.begin(); it!=candidates.end(); ++it, ++i)
    {
    ParticleInformation &info = (*it);
    double *pos = &info.CurrentPosition.x[0];
    // if outside bounds, reject instantly
    if (this->InsideBounds(pos))
      {
618
      // since this is first test, avoid bad cache tests
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
      this->Interpolator->ClearCache();
      info.LocationState = this->Interpolator->TestPoint(pos);
      if (info.LocationState==ID_OUTSIDE_ALL /*|| location==ID_OUTSIDE_T0*/)
        {
        // can't really use this particle.
        vtkDebugMacro(<< "TestParticles rejected particle");
        }
      else
        {
        // get the cached ids and datasets from the TestPoint call
        this->Interpolator->GetCachedCellIds(info.CachedCellId, info.CachedDataSetId);
        passed.push_back(i);
        }
      }
    }
}

//---------------------------------------------------------------------------
637
638
void vtkParticleTracerBase::AssignSeedsToProcessors(
  double time, vtkDataSet *source, int sourceID, int ptId,
639
  ParticleVector &localSeedPoints, int &localAssignedCount)
640
641
642
643
644
645
646
647
648
649
650
651
{
  ParticleVector candidates;
  //
  // take points from the source object and create a particle list
  //
  int numSeeds = source->GetNumberOfPoints();
  candidates.resize(numSeeds);
  //
  for (int i=0; i<numSeeds; i++)
    {
    ParticleInformation &info = candidates[i];
    memcpy(&(info.CurrentPosition.x[0]), source->GetPoint(i), sizeof(double)*3);
652
    info.CurrentPosition.x[3] = time;
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
    info.LocationState        = 0;
    info.CachedCellId[0]      =-1;
    info.CachedCellId[1]      =-1;
    info.CachedDataSetId[0]   = 0;
    info.CachedDataSetId[1]   = 0;
    info.SourceID             = sourceID;
    info.InjectedPointId      = i+ptId;
    info.InjectedStepId       = this->ReinjectionCounter;
    info.TimeStepAge          = 0;
    info.UniqueParticleId     =-1;
    info.rotation             = 0.0;
    info.angularVel           = 0.0;
    info.time                 = 0.0;
    info.age                  = 0.0;
    info.speed                = 0.0;
    info.ErrorCode            = 0;
669
    info.SimulationTime       = this->GetCurrentTimeValue();
670
    info.PointId = -1;
671
    }
672
673
674
  //
  // Gather all Seeds to all processors for classification
  //
675
  this->TestParticles(candidates, localSeedPoints, localAssignedCount);
676
677
678

  // Assign unique identifiers taking into account uneven distribution
  // across processes and seeds which were rejected
679
  this->AssignUniqueIds(localSeedPoints);
680
681
682
  //

}
683

684
685
//---------------------------------------------------------------------------
void vtkParticleTracerBase::AssignUniqueIds(
686
  vtkParticleTracerBaseNamespace::ParticleVector &localSeedPoints)
687
{
688
689
  vtkIdType particleCountOffset = 0;
  vtkIdType numParticles = localSeedPoints.size();
690
691
  for (vtkIdType i=0; i<numParticles; i++)
    {
692
    localSeedPoints[i].UniqueParticleId =
693
      this->UniqueIdCounter + particleCountOffset + i;
694
695
696
697
698
699
700
701
702
    }
  this->UniqueIdCounter += numParticles;
}

//---------------------------------------------------------------------------
void vtkParticleTracerBase::UpdateParticleList(ParticleVector &candidates)
{
  int numSeedsNew = static_cast<int>(candidates.size());
  //
703
704
  for (int i=0; i<numSeedsNew; i++)
    {
705
706
    // allocate a new particle on the list and get a reference to it
    this->ParticleHistories.push_back(candidates[i]);
707
    }
708
709
710
  vtkDebugMacro(<< "UpdateParticleList completed with " << this->NumberOfParticles() << " particles");
}

711
//---------------------------------------------------------------------------
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
int vtkParticleTracerBase::ProcessInput(vtkInformationVector** inputVector)
{
  Assert(this->CurrentTimeStep>=StartTimeStep  && this->CurrentTimeStep<=TerminationTimeStep);
  int numInputs = inputVector[0]->GetNumberOfInformationObjects();
  if(numInputs!=1)
    {
    if(numInputs==0)
      {
      vtkErrorMacro(<< "No input found.");
      return 0;
      }
    vtkWarningMacro(<< "Multiple inputs founds. Use only the first one.");
    }

  vtkInformation    *inInfo = inputVector[0]->GetInformationObject(0);
  if (inInfo)
    {
    vtkDataObject* input    = inInfo->Get(vtkDataObject::DATA_OBJECT());
    this->UpdateDataCache(input);
    }
  return 1;
}

735
//---------------------------------------------------------------------------
736
737
738
739
740
vtkPolyData* vtkParticleTracerBase::Execute(vtkInformationVector** inputVector)
{
  Assert(this->CurrentTimeStep>=this->StartTimeStep);

  double from = this->CurrentTimeStep==this->StartTimeStep? this->StartTime : this->GetCacheDataTime(0);
741
  this->CurrentTimeValue =
742
743
744
745
746
    this->CurrentTimeStep==this->StartTimeStep? StartTime:
    (this->CurrentTimeStep==this->TerminationTimeStep? this->TerminationTime : this->GetCacheDataTime(1));

  //set up the output
  vtkPolyData *output = vtkPolyData::New();
747
  //
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
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
795
796
  // Add the datasets to an interpolator object
  //
  if (this->InitializeInterpolator() != VTK_OK)
    {
    if (this->CachedData[0])
      {
      this->CachedData[0] = NULL;
      }
    if (this->CachedData[1])
      {
      this->CachedData[1] = NULL;
      }
    vtkErrorMacro(<<"InitializeInterpolator failed");
    return output;
    }

  vtkDebugMacro(<< "About to allocate point arrays ");
  this->ParticleAge         = vtkSmartPointer<vtkFloatArray>::New();
  this->ParticleIds         = vtkSmartPointer<vtkIntArray>::New();
  this->ParticleSourceIds   = vtkSmartPointer<vtkCharArray>::New();
  this->InjectedPointIds    = vtkSmartPointer<vtkIntArray>::New();
  this->InjectedStepIds     = vtkSmartPointer<vtkIntArray>::New();
  this->ErrorCode           = vtkSmartPointer<vtkIntArray>::New();
  this->ParticleVorticity   = vtkSmartPointer<vtkFloatArray>::New();
  this->ParticleRotation    = vtkSmartPointer<vtkFloatArray>::New();
  this->ParticleAngularVel  = vtkSmartPointer<vtkFloatArray>::New();
  this->CellVectors         = vtkSmartPointer<vtkDoubleArray>::New();
  this->ParticleCells       = vtkSmartPointer<vtkCellArray>::New();
  this->OutputCoordinates   = vtkSmartPointer<vtkPoints>::New();

  this->OutputPointData     = output->GetPointData();
  this->OutputPointData->Initialize();
  vtkDebugMacro(<< "About to Interpolate allocate space");
  this->OutputPointData->InterpolateAllocate(this->DataReferenceT[0]->GetPointData());
  this->ParticleAge->SetName("ParticleAge");
  this->ParticleIds->SetName("ParticleId");
  this->ParticleSourceIds->SetName("ParticleSourceId");
  this->InjectedPointIds->SetName("InjectedPointId");
  this->InjectedStepIds->SetName("InjectionStepId");
  this->ErrorCode->SetName("ErrorCode");

  if (this->ComputeVorticity)
    {
    this->CellVectors->SetNumberOfComponents(3);
    this->CellVectors->Allocate(3*VTK_CELL_SIZE);
    this->ParticleVorticity->SetName("Vorticity");
    this->ParticleRotation->SetName("Rotation");
    this->ParticleAngularVel->SetName("AngularVelocity");
    }
797
  this->InitializeExtraPointDataArrays(output->GetPointData());
798
799
800
801
802
803
804
805
806
807
808

  output->SetPoints(this->OutputCoordinates);
  output->SetVerts(this->ParticleCells);
  vtkDebugMacro(<< "Finished allocating point arrays ");

///
  // How many Seed point sources are connected?
  // Copy the sources into a vector for later use
  //

  int numSources = inputVector[1]->GetNumberOfInformationObjects();
Yuanxin Liu's avatar
Yuanxin Liu committed
809
  std::vector<vtkDataSet*> seedSources;
810
811
812
813
814
815
816
  for (int idx=0; idx<numSources; ++idx)
    {
    vtkDataObject     *dobj   = 0;
    vtkInformation    *inInfo = inputVector[1]->GetInformationObject(idx);
    if (inInfo)
      {
      dobj   = inInfo->Get(vtkDataObject::DATA_OBJECT());
Yuanxin Liu's avatar
Yuanxin Liu committed
817
      seedSources.push_back(vtkDataSet::SafeDownCast(dobj));
818
819
820
821
822
823
824
825
826
827
828
829
830
      }
    }

  //
  // Setup some variables
  //
  vtkSmartPointer<vtkInitialValueProblemSolver> integrator;
  integrator.TakeReference(this->GetIntegrator()->NewInstance());
  integrator->SetFunctionSet(this->Interpolator);

  //
  // Make sure the Particle Positions are initialized with Seed particles
  //
831
  if (this->StartTime==this->CurrentTimeValue)
832
    {
833
    Assert(!this->HasCache); //shouldn't have cache if restarting
834
835
836
837
838
839
840
    int seedPointId=0;
    if (!(this->StaticSeeds && this->AllFixedGeometry && this->LocalSeeds.size()==0))
      {
      // wipe the list and reclassify for each injection
      this->LocalSeeds.clear();
      }

Yuanxin Liu's avatar
Yuanxin Liu committed
841
    for (size_t i=0; i<seedSources.size(); i++)
842
      {
843
      this->AssignSeedsToProcessors(this->CurrentTimeValue,seedSources[i], static_cast<int>(i), 0, this->LocalSeeds, seedPointId);
844
845
846
847
848
849
850
      }

    this->ParticleInjectionTime.Modified();

    // Now update our main list with the ones we are keeping
    vtkDebugMacro(<< "Reinjection about to update candidates (" << this->LocalSeeds.size() << " particles)");
    this->UpdateParticleList(this->LocalSeeds);
851
    //this->ReinjectionCounter += this->ForceReinjectionEveryNSteps;
852
    }
853
854
855
856
857
858
859
860
861
862
863
864
865
866

  if(this->CurrentTimeStep==this->StartTimeStep) //just add all the particles
    {
    for(ParticleListIterator itr = this->ParticleHistories.begin();  itr!=this->ParticleHistories.end();itr++)
      {
      ParticleInformation& info(*itr);
      this->Interpolator->TestPoint(info.CurrentPosition.x);
      double velocity[3];
      this->Interpolator->GetLastGoodVelocity(velocity);
      info.speed = vtkMath::Norm(velocity);
      this->AddParticle(*itr,velocity);
      }
    }
  else
867
    {
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
    ParticleListIterator  it_first = this->ParticleHistories.begin();
    ParticleListIterator  it_last  = this->ParticleHistories.end();
    ParticleListIterator  it_next;

    //
    // Perform 2 passes
    // Pass 0 : Integration of particles created by a source in this process
    // or received at start from a source in another process.
    //
    // Pass 1 : Particles that were sent in mid integration from another process
    // are added in and their integration continued here. In actual fact, the process
    // should be repeated until all particles are finished, but the chances of
    // a particle stepping inside and out again through a single domain
    // in one time step are small (hopefully!)
#define PASSES 2
    for (int pass=0; pass<PASSES; pass++)
      {
      vtkDebugMacro(<<"Begin Pass " << pass << " with " << this->ParticleHistories.size() << " Particles");
      for (ParticleListIterator it=it_first; it!=it_last;)
        {
        // Keep the 'next' iterator handy because if a particle is terminated
        // or leaves the domain, the 'current' iterator will be deleted.
        it_next = it;
        it_next++;
892
        this->IntegrateParticle(it, from, this->CurrentTimeValue, integrator);
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
        if (this->GetAbortExecute())
          {
          break;
          }
        it = it_next;
        }
      // Particles might have been deleted during the first pass as they move
      // out of domain or age. Before adding any new particles that are sent
      // to us, we must know the starting point ready for the second pass
      bool list_valid = (this->ParticleHistories.size()>0);
      if (list_valid)
        {
        // point to one before the end
        it_first = --this->ParticleHistories.end();
        }
      // Send and receive any particles which exited/entered the domain
      if (pass<(PASSES-1))
        {
        this->UpdateParticleListFromOtherProcesses();
        }
      it_last = this->ParticleHistories.end();
      if (list_valid)
        {
        // increment to point to first new entry
        it_first++;
        }
      else
        {
        it_first = this->ParticleHistories.begin();
        }
      }//end of pass
    }

926
  bool injectionFlag(false);
927
  if (this->CurrentTimeValue!=this->StartTime && this->ForceReinjectionEveryNSteps>0)
928
929
930
931
932
    {
    injectionFlag = (this->CurrentTimeStep - this->StartTimeStep)%this->ForceReinjectionEveryNSteps==0;
    }

  if(injectionFlag) //reinject again in the last step
Yuanxin Liu's avatar
Yuanxin Liu committed
933
    {
934
    this->ReinjectionCounter += this->ForceReinjectionEveryNSteps;
935

936
937
938
939
940
    ParticleListIterator lastParticle = this->ParticleHistories.end();
    if (!this->ParticleHistories.empty())
      {
      lastParticle--;
      }
Yuanxin Liu's avatar
Yuanxin Liu committed
941
942
943
944
    int seedPointId=0;
    this->LocalSeeds.clear();
    for (size_t i=0; i<seedSources.size(); i++)
      {
945
      this->AssignSeedsToProcessors(this->CurrentTimeValue,seedSources[i], static_cast<int>(i), 0, this->LocalSeeds, seedPointId);
Yuanxin Liu's avatar
Yuanxin Liu committed
946
947
948
      }
    this->ParticleInjectionTime.Modified();
    this->UpdateParticleList(this->LocalSeeds);
949
950

    ParticleListIterator itr = lastParticle;
951
952
953
954
955
956
957
958
959
960
    if(itr!=this->ParticleHistories.end())
      {
      itr++;
      }
    else
      {
      itr = this->ParticleHistories.begin();
      }

    for(; itr!=this->ParticleHistories.end(); ++itr)
Yuanxin Liu's avatar
Yuanxin Liu committed
961
      {
962
      ParticleInformation& info(*lastParticle);
Yuanxin Liu's avatar
Yuanxin Liu committed
963
964
965
966
967
968
969
      this->Interpolator->TestPoint(info.CurrentPosition.x);
      double velocity[3];
      this->Interpolator->GetLastGoodVelocity(velocity);
      info.speed = vtkMath::Norm(velocity);
      this->AddParticle(*itr,velocity);
      }
    }
970
971
972
973
974
975
976
977
978
979
980
981
982
983

  this->OutputPointData->AddArray(this->ParticleIds);
  this->OutputPointData->AddArray(this->ParticleSourceIds);
  this->OutputPointData->AddArray(this->InjectedPointIds);
  this->OutputPointData->AddArray(this->InjectedStepIds);
  this->OutputPointData->AddArray(this->ErrorCode);
  this->OutputPointData->AddArray(this->ParticleAge);
  if (this->ComputeVorticity)
    {
    this->OutputPointData->AddArray(this->ParticleVorticity);
    this->OutputPointData->AddArray(this->ParticleRotation);
    this->OutputPointData->AddArray(this->ParticleAngularVel);
    }

984
985
986
  this->ParticlePointData = vtkSmartPointer<vtkPointData>::New();
  this->ParticlePointData->ShallowCopy(this->OutputPointData);

987
988
989
  // save some locator building, by re-using them as time progresses
  this->Interpolator->AdvanceOneTimeStep();

990
  output->GetInformation()->Set(vtkDataObject::DATA_TIME_STEP(), this->CurrentTimeValue);
991
992
  this->ExecuteTime.Modified();
  this->HasCache = true;
993
  PRINT("Output "<<output->GetNumberOfPoints()<<" particles, "<<this->ParticleHistories.size()<<" in cache");
994
995

  //Check post condition
996
997
  // To do:  verify here that the particles in ParticleHistories are consistent with CurrentTime

998
999
  // These hold reference to the inputs. Release them.
  this->DataReferenceT[0] = this->DataReferenceT[1] = 0;
1000
1001
1002
  return output;
}

1003
//---------------------------------------------------------------------------
1004
1005
1006
1007
1008
1009
int vtkParticleTracerBase::RequestData(
  vtkInformation *request,
  vtkInformationVector **inputVector,
  vtkInformationVector *outputVector)
{
  PRINT("RD start: "<<this->CurrentTimeStep<<" "<<this->CurrentTime<<" "<<this->StartTimeStep<<" "<<this->TerminationTimeStep);
1010
1011
1012
1013
  if(this->StartTimeStep<0)
    {
    return 0;
    }
1014
1015
1016
1017

  vtkInformation *outInfo = outputVector->GetInformationObject(0);
  vtkInformation    *inInfo = inputVector[0]->GetInformationObject(0);

1018
  if(this->HasCache && this->CurrentTimeValue == this->TerminationTime)
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
    {
    vtkDataObject* out = outInfo->Get(vtkDataObject::DATA_OBJECT());
    out->ShallowCopy(this->Output);
    request->Remove(vtkStreamingDemandDrivenPipeline::CONTINUE_EXECUTING());
    this->FirstIteration = true;
    return 1; //nothing to be done
    }

  bool finished = this->CurrentTimeStep==this->TerminationTimeStep;
  ProcessInput(inputVector);

  if(this->FirstIteration)
    {
    vtkDataObject* input    = inInfo->Get(vtkDataObject::DATA_OBJECT());
1033
1034
1035
1036
1037
1038
1039
    // first check if the point data is consistent on all blocks of a multiblock
    // and over all processes.
    if(this->IsPointDataValid(input) == false)
      {
      vtkErrorMacro("Point data arrays are not consistent across all data sets. Cannot do flow paths.");
      return 0;
      }
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
    this->CreateProtoPD(input);
    }

  vtkSmartPointer<vtkPolyData> particles;
  particles.TakeReference(this->Execute(inputVector));
  this->OutputParticles(particles);


  if(this->CurrentTimeStep<this->TerminationTimeStep)
    {
    this->CurrentTimeStep++;
    }
  else //we are at the last step
    {
1054
    if(this->TerminationTime == this->InputTimeValues[this->CurrentTimeStep])
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
      {
      this->CurrentTimeStep++;
      }
    }

  if(!finished)
    {
    request->Set(vtkStreamingDemandDrivenPipeline::CONTINUE_EXECUTING(), 1);
    this->FirstIteration = false;
    }
  else
    {
    this->Finalize();
    this->Output->GetInformation()->Set(vtkDataObject::DATA_TIME_STEP(), this->TerminationTime);
    PRINT("RD: "<<this->Output->GetNumberOfLines()<<" lines");
    vtkDataObject* out = outInfo->Get(vtkDataObject::DATA_OBJECT());
    out->ShallowCopy(this->Output);
    request->Remove(vtkStreamingDemandDrivenPipeline::CONTINUE_EXECUTING());
    this->FirstIteration = true;
    }

  PRINT("RD: "<<this->CurrentTimeStep<<" "<<this->StartTimeStep<<" "<<this->TerminationTimeStep);
  return 1;
}
1079

1080
1081
//---------------------------------------------------------------------------
void vtkParticleTracerBase::IntegrateParticle(
1082
  ParticleListIterator &it, double currenttime, double targettime,
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
  vtkInitialValueProblemSolver* integrator)
{
  double epsilon = (targettime-currenttime)/100.0;
  double velocity[3], point1[4], point2[4] = {0.0, 0.0, 0.0, 0.0};
  double minStep=0, maxStep=0;
  double stepWanted, stepTaken=0.0;
  int substeps = 0;

  ParticleInformation &info = (*it);
  ParticleInformation previous = (*it);
  bool particle_good = true;

  info.ErrorCode = 0;

  // Get the Initial point {x,y,z,t}
  memcpy(point1, &info.CurrentPosition, sizeof(Position));

  //
  // begin interpolation between available time values, if the particle has
  // a cached cell ID and dataset - try to use it,
  //
  this->Interpolator->SetCachedCellIds(info.CachedCellId, info.CachedDataSetId);

  if(currenttime==targettime)
    {
    Assert(point1[3]==currenttime);
    }
  else
    {
    Assert (point1[3]>=(currenttime-epsilon) && point1[3]<=(targettime+epsilon));

    double delT = (targettime-currenttime) * this->IntegrationStep;
    epsilon = delT*1E-3;

    while (point1[3] < (targettime-epsilon))
      {
      //
      // Here beginneth the real work
      //
      double error = 0;

      // If, with the next step, propagation will be larger than
      // max, reduce it so that it is (approximately) equal to max.
      stepWanted = delT;
      if ( (point1[3] + stepWanted) > targettime )
        {
        stepWanted = targettime - point1[3];
        maxStep = stepWanted;
        }

      // Calculate the next step using the integrator provided.
      // If the next point is out of bounds, send it to another process
      if (integrator->ComputeNextStep(
            point1, point2, point1[3], stepWanted,
            stepTaken, minStep, maxStep,
            this->MaximumError, error) != 0)
        {
        // if the particle is sent, remove it from the list
        info.ErrorCode = 1;
        if (!this->RetryWithPush(info, point1, delT, substeps))
          {
1144
1145
          if(previous.PointId <0)
            {
1146
            vtkDebugMacro("the particle should have been added");
1147
1148
1149
1150
1151
            }
          else
            {
            this->SendParticleToAnotherProcess(info,previous, this->ParticlePointData);
            }
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
          this->ParticleHistories.erase(it);
          particle_good = false;
          break;
          }
        else
          {
          // particle was not sent, retry saved it, so copy info back
          substeps++;
          memcpy(point1, &info.CurrentPosition, sizeof(Position));
          }
        }
      else // success, increment position/time
        {
        substeps++;

        // increment the particle time
        point2[3] = point1[3] + stepTaken;
        info.age += stepTaken;
1170
        info.SimulationTime += stepTaken;
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244

        // Point is valid. Insert it.
        memcpy(&info.CurrentPosition, point2, sizeof(Position));
        memcpy(point1, point2, sizeof(Position));
        }

      // If the solver is adaptive and the next time step (delT.Interval)
      // that the solver wants to use is smaller than minStep or larger
      // than maxStep, re-adjust it. This has to be done every step
      // because minStep and maxStep can change depending on the Cell
      // size (unless it is specified in time units)
      if (integrator->IsAdaptive())
        {
        // code removed. Put it back when this is stable
        }
      }

    if (particle_good)
      {
      // The integration succeeded, but check the computed final position
      // is actually inside the domain (the intermediate steps taken inside
      // the integrator were ok, but the final step may just pass out)
      // if it moves out, we can't interpolate scalars, so we must send it away
      info.LocationState = this->Interpolator->TestPoint(info.CurrentPosition.x);
      if (info.LocationState==ID_OUTSIDE_ALL)
        {
        info.ErrorCode = 2;
        // if the particle is sent, remove it from the list
        if (this->SendParticleToAnotherProcess(info,previous,this->OutputPointData))
          {
          this->ParticleHistories.erase(it);
          particle_good = false;
          }
        }
      }

    // Has this particle stagnated
    //
    if (particle_good)
      {
      this->Interpolator->GetLastGoodVelocity(velocity);
      info.speed = vtkMath::Norm(velocity);
      if (it->speed <= this->TerminalSpeed)
        {
        this->ParticleHistories.erase(it);
        particle_good = false;
        }
      }
    }

  //
  // We got this far without error :
  // Insert the point into the output
  // Create any new scalars and interpolate existing ones
  // Cache cell ids and datasets
  //
  if (particle_good)
    {
    //
    // store the last Cell Ids and dataset indices for next time particle is updated
    //
    this->Interpolator->GetCachedCellIds(info.CachedCellId, info.CachedDataSetId);
    //
    info.TimeStepAge += 1;
    //
    // Now generate the output geometry and scalars
    //
    this->AddParticle(info,velocity);
    }
  else
    {
    this->Interpolator->ClearCache();
    }

1245
#ifdef DEBUGPARTICLETRACE
1246
1247
  double eps = (this->GetCacheDataTime(1)-this->GetCacheDataTime(0))/100;
  Assert (point1[3]>=(this->GetCacheDataTime(0)-eps) && point1[3]<=(this->GetCacheDataTime(1)+eps));
1248
#endif
1249
}
1250

1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
//---------------------------------------------------------------------------
void vtkParticleTracerBase::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "ParticleWriter: " << this->ParticleWriter << endl;
  os << indent << "ParticleFileName: " <<
    (this->ParticleFileName ? this->ParticleFileName : "None") << endl;
  os << indent << "ForceReinjectionEveryNSteps: "
     << this->ForceReinjectionEveryNSteps << endl;
  os << indent << "EnableParticleWriting: " << this->EnableParticleWriting << endl;
  os << indent << "IgnorePipelineTime: " << this->IgnorePipelineTime << endl;
  os << indent << "StaticMesh: " << this->StaticMesh << endl;
  os << indent << "TerminationTime: " << this->TerminationTime << endl;
  os << indent << "StaticSeeds: " << this->StaticSeeds << endl;
}
1267

1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
//---------------------------------------------------------------------------
bool vtkParticleTracerBase::ComputeDomainExitLocation(
  double pos[4], double p2[4], double intersection[4],
  vtkGenericCell *cell)
{
  double t, pcoords[3];
  int subId;
  if (cell->IntersectWithLine(pos, p2, 1E-3, t, intersection, pcoords, subId)==0)
    {
    vtkDebugMacro(<< "No cell/domain exit was found");
    return 0;
    }
  else
    {
    // We found an intersection on the edge of the cell.
    // Shift it by a small amount to ensure that it crosses over the edge
    // into the adjoining cell.
1285
1286
1287
1288
    for (int i=0; i<3; i++)
      {
      intersection[i] = pos[i] + (t+0.01)*(p2[i]-pos[i]);
      }
1289
1290
1291
1292
1293
    // intersection stored, compute T for intersection
    intersection[3] = pos[3] + (t+0.01)*(p2[3]-pos[3]);
    return 1;
    }
}
1294

1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
//---------------------------------------------------------------------------
void vtkParticleTracerBase::SetIntegratorType(int type)
{
  vtkInitialValueProblemSolver* ivp=0;
  switch (type)
    {
    case RUNGE_KUTTA2:
      ivp = vtkRungeKutta2::New();
      break;
    case RUNGE_KUTTA4:
      ivp = vtkRungeKutta4::New();
      break;
    case RUNGE_KUTTA45:
      ivp = vtkRungeKutta45::New();
      break;
    default:
      vtkWarningMacro("Unrecognized integrator type. Keeping old one.");
      break;
    }
  if (ivp)
    {
    this->SetIntegrator(ivp);
    ivp->Delete();
    }
}

1321
//---------------------------------------------------------------------------
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
int vtkParticleTracerBase::GetIntegratorType()
{
  if (!this->Integrator)
    {
    return NONE;
    }
  if (!strcmp(this->Integrator->GetClassName(), "vtkRungeKutta2"))
    {
    return RUNGE_KUTTA2;
    }
  if (!strcmp(this->Integrator->GetClassName(), "vtkRungeKutta4"))
    {
    return RUNGE_KUTTA4;
    }
  if (!strcmp(this->Integrator->GetClassName(), "vtkRungeKutta45"))
    {
    return RUNGE_KUTTA45;
    }
  return UNKNOWN;
}

1343
1344
1345
1346
//---------------------------------------------------------------------------
void vtkParticleTracerBase::CalculateVorticity(
  vtkGenericCell* cell, double pcoords[3],
  vtkDoubleArray* cellVectors, double vorticity[3] )
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
{
  double* cellVel;
  double derivs[9];

  cellVel = cellVectors->GetPointer(0);
  cell->Derivatives(0, pcoords, cellVel, 3, derivs);
  vorticity[0] = derivs[7] - derivs[5];
  vorticity[1] = derivs[2] - derivs[6];
  vorticity[2] = derivs[3] - derivs[1];
}

1358
//---------------------------------------------------------------------------
1359
1360
1361
1362
1363
double vtkParticleTracerBase::GetCacheDataTime(int i)
{
  return this->CachedData[i]->GetInformation()->Get(vtkDataObject::DATA_TIME_STEP());
}

1364
//---------------------------------------------------------------------------
1365
1366
1367
1368
1369
1370
1371
1372
double vtkParticleTracerBase::GetCacheDataTime()
{
  double currentTime = CachedData[1]? this->GetCacheDataTime(1):
    ( CachedData[0]? this->GetCacheDataTime(0) :  -DBL_MAX);
  return currentTime;

}

1373
//---------------------------------------------------------------------------
1374
1375
unsigned int vtkParticleTracerBase::NumberOfParticles()
{
Yuanxin Liu's avatar
Yuanxin Liu committed
1376
  return static_cast<unsigned int>(this->ParticleHistories.size());
1377
1378
}

1379
//---------------------------------------------------------------------------
1380
1381
void vtkParticleTracerBase::ResetCache()
{
1382
1383
1384
1385
1386
1387
1388
  if(this->DisableResetCache==0)
    {
    PRINT("Reset cache");
    this->LocalSeeds.clear();
    this->ParticleHistories.clear();
    this->ReinjectionCounter = 0;
    this->UniqueIdCounter    = 0; ///check
1389

1390
1391
    this->CachedData[0] = NULL;
    this->CachedData[1] = NULL;
1392

1393
1394
1395
    this->Output = NULL;
    this->HasCache = false;
    }
1396
1397
}

1398
//---------------------------------------------------------------------------
1399
bool vtkParticleTracerBase::SetTerminationTimeNoModify(double t)
1400
1401
1402
{
  if(t==this->TerminationTime)
    {
1403
    return false;
1404
1405
1406
1407
1408
1409
1410
    }

  if (t < this->TerminationTime)
    {
    this->ResetCache();
    }

1411
  if( t < this->StartTime)
1412
1413
1414
1415
1416
    {
    vtkWarningMacro("Can't go backward");
    t = this->StartTime;
    }

1417
  this->TerminationTime = t;
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428

  return true;
}

//---------------------------------------------------------------------------
void vtkParticleTracerBase::SetTerminationTime(double t)
{
  if (this->SetTerminationTimeNoModify(t))
    {
    this->Modified();
    }
1429
1430
}

1431
//---------------------------------------------------------------------------
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
void vtkParticleTracerBase::CreateProtoPD(vtkDataObject* input)
{
  this->ProtoPD = NULL;
  vtkDataSet* inputData(NULL);

  if(vtkCompositeDataSet::SafeDownCast(input))
    {
    vtkSmartPointer<vtkCompositeDataIterator> inputIter;
    inputIter.TakeReference(vtkCompositeDataSet::SafeDownCast(input)->NewIterator());
    inputIter->GoToFirstItem();
    inputData = vtkDataSet::SafeDownCast(inputIter->GetCurrentDataObject());
    }
  else
    {
    inputData = vtkDataSet::SafeDownCast(input);
    }
  if(!inputData)
    {
    return;
    }

  this->ProtoPD  = vtkSmartPointer<vtkPointData>::New();
  this->ProtoPD->InterpolateAllocate(inputData->GetPointData());
}

//---------------------------------------------------------------------------
1458
1459
bool vtkParticleTracerBase::RetryWithPush(
  ParticleInformation &info,  double* point1,double delT, int substeps)
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
{
  double velocity[3];
  this->Interpolator->ClearCache();

  info.LocationState = this->Interpolator->TestPoint(point1);

  if (info.LocationState==ID_OUTSIDE_ALL)
    {
    // something is wrong, the particle has left the building completely
    // we can't get the last good velocity as it won't be valid
    // send the particle 'as is' and hope it lands in another process
    if (substeps>0)
      {
      this->Interpolator->GetLastGoodVelocity(velocity);
      }
    else
      {
      velocity[0] = velocity[1] = velocity[2] = 0.0;
      }
    info.ErrorCode = 3;
    }
  else if (info.LocationState==ID_OUTSIDE_T0)
    {
    // the particle left the volume but can be tested at T2, so use the velocity at T2
    this->Interpolator->GetLastGoodVelocity(velocity);
    info.ErrorCode = 4;
    }
  else if (info.LocationState==ID_OUTSIDE_T1)
    {
    // the particle left the volume but can be tested at T1, so use the velocity at T1
    this->Interpolator->GetLastGoodVelocity(velocity);
    info.ErrorCode = 5;
    }
  else
    {
    // The test returned INSIDE_ALL, so test failed near start of integration,
    this->Interpolator->GetLastGoodVelocity(velocity);
    }

  // try adding a one increment push to the particle to get over a rotating/moving boundary
  for (int v=0; v<3; v++)
    {
    info.CurrentPosition.x[v] += velocity[v]*delT;
    }

  info.CurrentPosition.x[3] += delT;
  info.LocationState = this->Interpolator->TestPoint(info.CurrentPosition.x);
1507
  info.age += delT;
1508
  info.SimulationTime += delT; // = this->GetCurrentTimeValue();
1509

1510
1511
1512
1513
1514
1515
1516
1517
1518
  if (info.LocationState!=ID_OUTSIDE_ALL)
    {
    // a push helped the particle get back into a dataset,
    info.ErrorCode = 6;
    return 1;
    }
  return 0;
}

1519
1520
1521
//---------------------------------------------------------------------------
void vtkParticleTracerBase::AddParticle(
  vtkParticleTracerBaseNamespace::ParticleInformation &info, double* velocity)
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
{
  const double    *coord = info.CurrentPosition.x;
  vtkIdType tempId = this->OutputCoordinates->InsertNextPoint(coord);
  // create the cell
  this->ParticleCells->InsertNextCell(1, &tempId);
  // set the easy scalars for this particle
  this->ParticleIds->InsertNextValue(info.UniqueParticleId);
  this->ParticleSourceIds->InsertNextValue(info.SourceID);
  this->InjectedPointIds->InsertNextValue(info.InjectedPointId);
  this->InjectedStepIds->InsertNextValue(info.InjectedStepId);
  this->ErrorCode->InsertNextValue(info.ErrorCode);
  this->ParticleAge->InsertNextValue(info.age);
1534
  this->AppendToExtraPointDataArrays(info);
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
  info.PointId = tempId;

  //
  // Interpolate all existing point attributes
  // In principle we always integrate the particle until it reaches Time2
  // - so we don't need to do any interpolation of the scalars
  // between T0 and T1, just fetch the values
  // of the spatially interpolated scalars from T1.
  //
  if (info.LocationState==ID_OUTSIDE_T1)
    {
    this->Interpolator->InterpolatePoint(0, this->OutputPointData, tempId);
    }
  else
    {
    this->Interpolator->InterpolatePoint(1, this->OutputPointData, tempId);
    }
  //
  // Compute vorticity
  //
  if (this->ComputeVorticity)
    {
    vtkGenericCell *cell(NULL);
    double pcoords[3], vorticity[3], weights[256];
    double rotation, omega;
    // have to use T0 if particle is out at T1, otherwise use T1
    if (info.LocationState==ID_OUTSIDE_T1)
      {
      this->Interpolator->GetVorticityData(
        0, pcoords, weights, cell, this->CellVectors);
      }
    else
      {
      this->Interpolator->GetVorticityData(
        1, pcoords, weights, cell, this->CellVectors);
      }

    this->CalculateVorticity(cell, pcoords, CellVectors, vorticity);
    this->ParticleVorticity->InsertNextTuple(vorticity);
    // local rotation = vorticity . unit tangent ( i.e. velocity/speed )
    if (info.speed != 0.0)
      {
      omega = vtkMath::Dot(vorticity, velocity);
      omega /= info.speed;
      omega *= this->RotationScale;
      }
    else
      {
      omega = 0.0;
      }
    vtkIdType index = this->ParticleAngularVel->InsertNextValue(omega);
    if (index>0)
      {
      rotation     = info.rotation + (info.angularVel + omega)/2 * (info.CurrentPosition.x[3] - info.time);
      }
    else
      {
      rotation     = 0.0;
      }
    this->ParticleRotation->InsertNextValue(rotation);
    info.rotation   = rotation;
    info.angularVel = omega;
    info.time       = info.CurrentPosition.x[3];
    }

}

1602
//---------------------------------------------------------------------------
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
bool vtkParticleTracerBase::IsPointDataValid(vtkDataObject* input)
{
  if(vtkCompositeDataSet* cdInput = vtkCompositeDataSet::SafeDownCast(input))
    {
    std::vector<std::string> arrayNames;
    return this->IsPointDataValid(cdInput, arrayNames);
    }
  // a single data set on a single process will always have consistent point data
  return true;
}

1614
//---------------------------------------------------------------------------
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
bool vtkParticleTracerBase::IsPointDataValid(vtkCompositeDataSet* input,
                                             std::vector<std::string>& arrayNames)
{