avtCreateBondsFilter.C 37.2 KB
Newer Older
hrchilds's avatar
hrchilds committed
1 2
/*****************************************************************************
*
whitlocb's avatar
whitlocb committed
3
* Copyright (c) 2000 - 2014, Lawrence Livermore National Security, LLC
hrchilds's avatar
hrchilds committed
4
* Produced at the Lawrence Livermore National Laboratory
5
* LLNL-CODE-442911
hrchilds's avatar
hrchilds committed
6 7
* All rights reserved.
*
8
* This file is  part of VisIt. For  details, see https://visit.llnl.gov/.  The
hrchilds's avatar
hrchilds committed
9 10 11 12 13 14 15 16 17 18
* full copyright notice is contained in the file COPYRIGHT located at the root
* of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html.
*
* Redistribution  and  use  in  source  and  binary  forms,  with  or  without
* modification, are permitted provided that the following conditions are met:
*
*  - Redistributions of  source code must  retain the above  copyright notice,
*    this list of conditions and the disclaimer below.
*  - Redistributions in binary form must reproduce the above copyright notice,
*    this  list of  conditions  and  the  disclaimer (as noted below)  in  the
19 20 21
*    documentation and/or other materials provided with the distribution.
*  - Neither the name of  the LLNS/LLNL nor the names of  its contributors may
*    be used to endorse or promote products derived from this software without
hrchilds's avatar
hrchilds committed
22 23 24 25 26
*    specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT  HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR  IMPLIED WARRANTIES, INCLUDING,  BUT NOT  LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND  FITNESS FOR A PARTICULAR  PURPOSE
27 28 29
* ARE  DISCLAIMED. IN  NO EVENT  SHALL LAWRENCE  LIVERMORE NATIONAL  SECURITY,
* LLC, THE  U.S.  DEPARTMENT OF  ENERGY  OR  CONTRIBUTORS BE  LIABLE  FOR  ANY
* DIRECT,  INDIRECT,   INCIDENTAL,   SPECIAL,   EXEMPLARY,  OR   CONSEQUENTIAL
hrchilds's avatar
hrchilds committed
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
* DAMAGES (INCLUDING, BUT NOT  LIMITED TO, PROCUREMENT OF  SUBSTITUTE GOODS OR
* SERVICES; LOSS OF  USE, DATA, OR PROFITS; OR  BUSINESS INTERRUPTION) HOWEVER
* CAUSED  AND  ON  ANY  THEORY  OF  LIABILITY,  WHETHER  IN  CONTRACT,  STRICT
* LIABILITY, OR TORT  (INCLUDING NEGLIGENCE OR OTHERWISE)  ARISING IN ANY  WAY
* OUT OF THE  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
*****************************************************************************/

// ************************************************************************* //
//  File: avtCreateBondsFilter.C
// ************************************************************************* //

#include <avtCreateBondsFilter.h>

#include <vtkDataSet.h>
#include <vtkCellData.h>
#include <vtkCellArray.h>
48
#include <vtkGeometryFilter.h>
hrchilds's avatar
hrchilds committed
49 50 51 52
#include <vtkPointData.h>
#include <vtkPoints.h>
#include <vtkPolyData.h>
#include <DebugStream.h>
53
#include <TimingsManager.h>
54 55
#include <vtkMatrix4x4.h>
#include <vtkMath.h>
56

57
#include <float.h>
58 59 60 61 62 63

#include <map>
#include <string>
#include <utility>
#include <vector>

64
using std::map;
65 66 67
using std::pair;
using std::string;
using std::vector;
hrchilds's avatar
hrchilds committed
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155

// ****************************************************************************
//  Method: avtCreateBondsFilter constructor
//
//  Programmer: Jeremy Meredith
//  Creation:   August 29, 2006
//
// ****************************************************************************

avtCreateBondsFilter::avtCreateBondsFilter()
{
}


// ****************************************************************************
//  Method: avtCreateBondsFilter destructor
//
//  Programmer: Jeremy Meredith
//  Creation:   August 29, 2006
//
//  Modifications:
//
// ****************************************************************************

avtCreateBondsFilter::~avtCreateBondsFilter()
{
}


// ****************************************************************************
//  Method:  avtCreateBondsFilter::Create
//
//  Programmer: Jeremy Meredith
//  Creation:   August 29, 2006
//
// ****************************************************************************

avtFilter *
avtCreateBondsFilter::Create()
{
    return new avtCreateBondsFilter();
}


// ****************************************************************************
//  Method:      avtCreateBondsFilter::SetAtts
//
//  Purpose:
//      Sets the state of the filter based on the attribute object.
//
//  Arguments:
//      a        The attributes to use.
//
//  Programmer: Jeremy Meredith
//  Creation:   August 29, 2006
//
// ****************************************************************************

void
avtCreateBondsFilter::SetAtts(const AttributeGroup *a)
{
    atts = *(const CreateBondsAttributes*)a;
}


// ****************************************************************************
//  Method: avtCreateBondsFilter::Equivalent
//
//  Purpose:
//      Returns true if creating a new avtCreateBondsFilter with the given
//      parameters would result in an equivalent avtCreateBondsFilter.
//
//  Programmer: Jeremy Meredith
//  Creation:   August 29, 2006
//
// ****************************************************************************

bool
avtCreateBondsFilter::Equivalent(const AttributeGroup *a)
{
    return (atts == *(CreateBondsAttributes*)a);
}


// ****************************************************************************
//  Method:  avtCreateBondsFilter::AtomsShouldBeBondedManual
//
//  Purpose:
156
//    Finds min/max bond lengths for a pair of species.
hrchilds's avatar
hrchilds committed
157 158
//
//  Arguments:
159 160
//    elementA/B        the atomic numbers of the atom pair
//    dmin,dmax         the min/max allowed bonding distance (output)
hrchilds's avatar
hrchilds committed
161 162 163 164
//
//  Programmer:  Jeremy Meredith
//  Creation:    August 29, 2006
//
165 166 167 168 169
//  Modifications:
//    Jeremy Meredith, Mon Feb 11 16:38:48 EST 2008
//    Support wildcards in matches, and bail out if we matched the
//    atom pattern but the distances were wrong.
//
170
//    Jeremy Meredith, Wed May 20 11:49:18 EDT 2009
171
//    MAX_ELEMENT_NUMBER now means the actual max element number, not
172 173 174 175
//    total number of known elements in visit.  Added a fake "0" element
//    which means "unknown", and hydrogen now starts at 1.  This
//    also means we don't have to correct for 1-origin atomic numbers.
//
176 177 178
//    Jeremy Meredith, Tue Jan 26 16:35:41 EST 2010
//    Split into two functions to allow better optimizations.
//
hrchilds's avatar
hrchilds committed
179 180
// ****************************************************************************
bool
181 182
avtCreateBondsFilter::AtomBondDistances(int elementA, int elementB,
                                        double &dmin, double &dmax)
hrchilds's avatar
hrchilds committed
183
{
184 185
    dmin = 0.;
    dmax = 0.;
hrchilds's avatar
hrchilds committed
186 187 188 189 190 191

    vector<double> &minDist = atts.GetMinDist();
    vector<double> &maxDist = atts.GetMaxDist();
    vector<int>    &element1 = atts.GetAtomicNumber1();
    vector<int>    &element2 = atts.GetAtomicNumber2();

192 193 194 195
    size_t n1 = atts.GetAtomicNumber1().size();
    size_t n2 = atts.GetAtomicNumber2().size();
    size_t n3 = atts.GetMinDist().size();
    size_t n4 = atts.GetMaxDist().size();
hrchilds's avatar
hrchilds committed
196 197 198 199 200
    if (n1 != n2 || n1 != n3 || n1 != n4)
    {
        EXCEPTION1(ImproperUseException,
                   "Bond list data arrays were not all the same length.");
    }
201
    size_t n = n1;
hrchilds's avatar
hrchilds committed
202

203
    for (size_t i=0; i<n; i++)
hrchilds's avatar
hrchilds committed
204
    {
205
        // a -1 in the element list means "any"
206 207
        int e1 = element1[i];
        int e2 = element2[i];
208 209 210 211
        bool match11 = (e1 < 0) || (elementA == e1);
        bool match12 = (e1 < 0) || (elementB == e1);
        bool match21 = (e2 < 0) || (elementA == e2);
        bool match22 = (e2 < 0) || (elementB == e2);
212
        if ((match11 && match22) || (match12 && match21))
hrchilds's avatar
hrchilds committed
213
        {
214 215 216
            dmin = minDist[i];
            dmax = maxDist[i];
            return true;
hrchilds's avatar
hrchilds committed
217 218 219 220 221 222
        }
    }

    return false;
}

223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
// ****************************************************************************
// Method:  ShouldAtomsBeBonded
//
// Purpose:
//   Check if two atoms are within the allowable distances.
//
// Arguments:
//   dmin,dmax     the min/max bonding distances
//   pA,pB         the atom locations
//
// Programmer:  Jeremy Meredith
// Creation:    January 26, 2010
//
// ****************************************************************************
inline bool
ShouldAtomsBeBonded(double dmin, double dmax,
                    double *pA, double *pB)
{
    // Check for errors, of in case of no match for this pair
    if (dmax <= 0 || dmax < dmin)
        return false;

    // Okay, now see if the atom pair matches the right distance
    float dx = pA[0] - pB[0];
    float dy = pA[1] - pB[1];
    float dz = pA[2] - pB[2];
    float dist2 = dx*dx + dy*dy + dz*dz;

    if (dist2 > dmin*dmin && dist2 < dmax*dmax)
        return true;
    else
        return false;
}


hrchilds's avatar
hrchilds committed
258
// ****************************************************************************
259
//  Method:  avtCreateBondsFilter::ExecuteData
hrchilds's avatar
hrchilds committed
260 261 262 263 264
//
//  Purpose:
//      Sends the specified input and output through the CreateBonds filter.
//
//  Arguments:
265
//      in_dr      The input data representation.
hrchilds's avatar
hrchilds committed
266
//
267
//  Returns:       The output data representation.
hrchilds's avatar
hrchilds committed
268
//
269 270 271
//  Programmer:  Jeremy Meredith
//  Creation:    January 27, 2010
//
272 273 274 275 276 277 278 279
//  Modifications:
//    Jeremy Meredith, Tue Feb 22 21:36:07 EST 2011
//    Added support for non-polydata mesh types through the geometry filter.
//    Sure, it may be a little blunt, but it doesn't hurt anything and allows
//    e.g. Silo point meshes (which are unstructured, not poly data) to work.
//
//    Eric Brugger, Wed Jul 23 11:25:16 PDT 2014
//    Modified the class to work with avtDataRepresentation.
280
//
281
// ****************************************************************************
282 283
avtDataRepresentation *
avtCreateBondsFilter::ExecuteData(avtDataRepresentation *in_dr)
284
{
285 286 287 288 289
    //
    // Get the VTK data set.
    //
    vtkDataSet *in_ds = in_dr->GetDataVTK();

290
    vtkGeometryFilter *geom = NULL;
291 292
    if (in_ds->GetDataObjectType() != VTK_POLY_DATA)
    {
293
        geom = vtkGeometryFilter::New();
bonnell's avatar
bonnell committed
294 295
        geom->SetInputData(in_ds);
        geom->Update();
296
        in_ds = geom->GetOutput();
297 298 299 300 301 302 303 304
    }

    //
    // Find the maximum bond distance as specified in the atts
    // since this determines the box size.
    //
    float maxBondDist = 0.;
    vector<double> &maxDist = atts.GetMaxDist();
305
    for (size_t i=0; i<maxDist.size(); i++)
306 307 308 309 310
    {
        if (maxDist[i] > maxBondDist)
            maxBondDist = maxDist[i];
    }
    if (maxBondDist <= 0.)
311
        return in_dr;
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335

    //
    // Find the actual extents
    //
    float minx =  FLT_MAX, maxx = -FLT_MAX;
    float miny =  FLT_MAX, maxy = -FLT_MAX;
    float minz =  FLT_MAX, maxz = -FLT_MAX;
    int nPts = in_ds->GetNumberOfPoints();
    for (int p=0; p<nPts; p++)
    {
        double pt[4] = {0,0,0,1};
        in_ds->GetPoint(p, pt);
        if (pt[0] < minx) minx = pt[0];
        if (pt[0] > maxx) maxx = pt[0];
        if (pt[1] < miny) miny = pt[1];
        if (pt[1] > maxy) maxy = pt[1];
        if (pt[2] < minz) minz = pt[2];
        if (pt[2] > maxz) maxz = pt[2];
    }

    // If the max bond distance isn't some smallish percentage of the
    // extents, then no point doing the more complex spatial
    // subdivision scheme.  And if it's too small, the overhead of
    // making such a big vector grid for the box storage could be bad.
336 337
    int approxNBoxes = (int)((maxx - minx)*(maxy - miny)*(maxz - minz) /
                                        (maxBondDist*maxBondDist*maxBondDist));
338 339
    double minAllowable = 8;
    double maxAllowable = 10000000;
340
    vtkDataSet *out_ds = NULL;
341 342 343
    if (approxNBoxes < minAllowable || approxNBoxes > maxAllowable)
    {
        debug4 << "avtCreateBondsFilter: reverting to slow method\n";
344
        out_ds = ExecuteData_Slow((vtkPolyData*)in_ds);
345 346 347 348 349
    }
    else
    {
        debug4 << "avtCreateBondsFilter: using fast method, "
               << "approximately "<<approxNBoxes<<" boxes\n";
350 351
        out_ds = ExecuteData_Fast((vtkPolyData*)in_ds, maxBondDist,
                                  minx,maxx, miny,maxy, minz,maxz);
352
    }
353 354
    if (geom)
        geom->Delete();
355 356 357 358 359 360 361

    avtDataRepresentation *out_dr = new avtDataRepresentation(out_ds,
        in_dr->GetDomain(), in_dr->GetLabel());

    out_ds->Delete();

    return out_dr;
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
}


// ****************************************************************************
// Method:  avtCreateBondsFilter::ExecuteData_Fast
//
// Purpose:
//   Smarter space-subdivision search for bonds.
//
// Arguments:
//   in           the input data set
//   maxBondDist  the maximum distance of any bonding criteria
//   min*,max*    the extents of the actual data set points
//
// Returns:       The output dataset.
//
// Programmer:  Jeremy Meredith
// Creation:    January 27, 2010
//
381 382 383 384 385
// Modifications:
//   Jeremy Meredith, Wed Aug 11 10:21:59 EDT 2010
//   Use the element variable specified in the attributes.
//   Support any type of input nodal array.
//
386 387 388
//   Kathleen Biagas, Tue Aug 21 16:08:27 MST 2012
//   Preserve coordinate type.
//
389 390 391
//   Eric Brugger, Wed Jul 23 11:25:16 PDT 2014
//   Modified the class to work with avtDataRepresentation.
//
392
// ****************************************************************************
393

394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
vtkDataSet *
avtCreateBondsFilter::ExecuteData_Fast(vtkPolyData *in, float maxBondDist,
                                       float minx, float maxx,
                                       float miny, float maxy,
                                       float minz, float maxz)
{
    //
    // Extract some input data
    //
    vtkPoints    *inPts = in->GetPoints();
    vtkCellArray *inVerts = in->GetVerts();
    vtkPointData *inPD  = in->GetPointData();
    vtkCellData  *inCD  = in->GetCellData();
    int nPts   = in->GetNumberOfPoints();
    int nVerts = in->GetNumberOfVerts();

410 411 412 413 414 415
    vtkDataArray *element;
    if (atts.GetElementVariable() == "default")
        element = inPD->GetScalars();
    else
        element = inPD->GetArray(atts.GetElementVariable().c_str());
    if (!element)
416
    {
417 418
        debug1 << "avtCreateBondsFilter: did not find appropriate point array\n";
        debug1 << "   -- returning original data set with no bonds changed.\n";
419
        in->Register(NULL);
420 421 422
        return in;
    }

423 424 425 426
    vector<float> elementnos;
    elementnos.resize(nPts);
    for (int i=0; i<nPts; i++)
        elementnos[i] = element->GetTuple1(i);
427 428 429 430 431 432 433

    //
    // Set up the output stuff
    //
    vtkPolyData  *out      = in->NewInstance();
    vtkPointData *outPD    = out->GetPointData();
    vtkCellData  *outCD    = out->GetCellData();
434
    vtkPoints    *outPts   = vtkPoints::New(inPts->GetDataType());
435 436 437 438 439 440 441 442 443 444 445 446
    vtkCellArray *outVerts = vtkCellArray::New();
    vtkCellArray *outLines = vtkCellArray::New();
    out->GetFieldData()->ShallowCopy(in->GetFieldData());
    out->SetPoints(outPts);
    out->SetLines(outLines);
    out->SetVerts(outVerts);
    outPts->Delete();
    outLines->Delete();
    outVerts->Delete();

    //outPts->SetNumberOfPoints(nPts * 1.1);
    outPD->CopyAllocate(inPD,nPts);
447
    outCD->CopyAllocate(inCD,(int)(nVerts*1.2));
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499


    //
    // Copy the input points and verts over.
    //
    for (int p=0; p<nPts; p++)
    {
        double pt[4] = {0,0,0,1};
        in->GetPoint(p, pt);
        int outpt = outPts->InsertNextPoint(pt);
        outPD->CopyData(inPD, p, outpt);
    }
    vtkIdType *vertPtr = inVerts->GetPointer();
    for (int v=0; v<nVerts; v++)
    {
        if (*vertPtr == 1)
        {
            vtkIdType id = *(vertPtr+1);
            int outcell = outVerts->InsertNextCell(1);
            outVerts->InsertCellPoint(id);
            outCD->CopyData(inCD, v, outcell);
        }
        vertPtr += (*vertPtr+1);
    }

    int natoms = in->GetNumberOfPoints();

    //
    // Extract unit cell vectors in case we want to add bonds
    // for periodic atom images
    //
    bool addPeriodicBonds = atts.GetAddPeriodicBonds();
    double xv[3], yv[3], zv[3];
    for (int j=0; j<3; j++)
    {
        if (atts.GetUseUnitCellVectors())
        {
            const avtDataAttributes &datts = GetInput()->GetInfo().GetAttributes();
            const float *unitCell = datts.GetUnitCellVectors();
            xv[j] = unitCell[3*0+j];
            yv[j] = unitCell[3*1+j];
            zv[j] = unitCell[3*2+j];
        }
        else
        {
            xv[j] = atts.GetXVector()[j];
            yv[j] = atts.GetYVector()[j];
            zv[j] = atts.GetZVector()[j];
        }
    }
    
    //
500
    // ni,nj,nk are the number of bins in the i,j,k directions
501
    //
502
    // Why the "3 + ..." here?
503
    // (a) if we weren't doing periodic atom checks, we could
504
    //     make do with 1+ -- that "1" we always need because there
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
    //     will be one atom at maxx,maxy,maxz which will go in
    //     the final cube.  easier than clamping or fuzz factors.
    // (b) for periodic checks, we know they must be within
    //     maxBondDist of the existing cube.
    int ni = 3 + int((maxx - minx) / maxBondDist);
    int nj = 3 + int((maxy - miny) / maxBondDist);
    int nk = 3 + int((maxz - minz) / maxBondDist);

    int max_per_atom = atts.GetMaxBondsClamp();
    
    //
    // Support for per-axis periodicity here
    //
    int perXmin = 0, perXmax = 0;
    int perYmin = 0, perYmax = 0;
    int perZmin = 0, perZmax = 0;
    if (addPeriodicBonds && atts.GetPeriodicInX())
    {
        perXmin = -1;
        perXmax = +1;
    }
    if (addPeriodicBonds && atts.GetPeriodicInY())
    {
        perYmin = -1;
        perYmax = +1;
    }
    if (addPeriodicBonds && atts.GetPeriodicInZ())
    {
        perZmin = -1;
        perZmax = +1;
    }

    //
    // I know -- I'm using a grid of STL vectors, and this could
    // potentially be inefficient.  However, even with STL vectors the
    // algorithm is quite complex, and the benefit of the algorithm so
    // large, that there is little need to do better yet.  I'll
    // probably wait until I see evidence of problems before changing.
    //
    typedef pair<int,int> atomimage;
545 546
    typedef vector<atomimage> atomvec;
    atomvec *atomgrid = new atomvec[ni*nj*nk];
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 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596

    map<atomimage, int> imageMap;

    int nativeImage = -1;
    for (int a=0; a<natoms; a++)
    {
        double pt_orig[4] = {0,0,0,1};
        in->GetPoint(a, pt_orig);
        int image = 0;
        for (int px=perXmin; px<=perXmax; px++)
        {
            for (int py=perYmin; py<=perYmax; py++)
            {
                for (int pz=perZmin; pz<=perZmax; pz++, image++)
                {
                    if (nativeImage < 0 && px==0 && py==0 && pz==0)
                        nativeImage = image;
                    double xoff = (double(px)*xv[0]+
                                   double(py)*yv[0]+
                                   double(pz)*zv[0]);
                    double yoff = (double(px)*xv[1]+
                                   double(py)*yv[1]+
                                   double(pz)*zv[1]);
                    double zoff = (double(px)*xv[2]+
                                   double(py)*yv[2]+
                                   double(pz)*zv[2]);
                    double pt[3] = {pt_orig[0]+xoff,
                                    pt_orig[1]+yoff,
                                    pt_orig[2]+zoff};
                    // Add 1+ here because the outermost boxes are
                    // for holding periodic atoms (though because
                    // the unit cell is not axis-aligned, periodic
                    // atoms coule potentially go anywhere).
                    int ix = 1+int((pt[0] - minx) / maxBondDist);
                    int jx = 1+int((pt[1] - miny) / maxBondDist);
                    int kx = 1+int((pt[2] - minz) / maxBondDist);
                    if (ix<0 || ix>=ni || jx<0 || jx>=nj || kx<0 || kx>=nk)
                        continue;

                    atomgrid[ix + ni*(jx + nj*(kx))].push_back(atomimage(image,a));

                    // We already added the points and vertices for the
                    // original atoms.  Don't add them twice, and don't
                    // add vertex cells for the phoney atoms.
                    if (image != nativeImage)
                    {
                        // Yes, it is memory-wasteful to add all atoms
                        // from all 26 non-native images.  However, we
                        // don't store any which lie any significant
                        // distance outside the original bounding box,
597 598
                        // so the max cost should be one extra bin's
                        // worth of atoms.
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
                        int outpt = outPts->InsertNextPoint(pt);
                        outPD->CopyData(inPD, a, outpt);
                        imageMap[atomimage(image,a)] = outpt;
                    }
                }
            }
        }
    }


    //
    // Loop over all boxes once.  For each atom in the box, loop over
    // all 27 boxes surrounding the current one, since atom matches
    // could be in any of those boxes (by design, this check spans at
    // least maxBondDist every direction from any atom in the box).
    //
    for (int i=1; i<ni-1; i++)
    {
        for (int j=1; j<nj-1; j++)
        {
            for (int k=1; k<nk-1; k++)
            {
                int index1 = i + ni*(j + nj*(k));
622
                int nla1 = (int)atomgrid[index1].size();
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
                // for each atom in each box
                for (int la1=0; la1<nla1; la1++)
                {
                    int ctr = 0;
                    atomimage atom1 = atomgrid[index1][la1];
                    int image1 = atom1.first;
                    int a1 = atom1.second;

                    // we need at least one of the atoms to be
                    // original, i.e. in the native image.
                    // choose it to be atom1.
                    if (image1 != nativeImage)
                        continue;

                    // loop over all 27 surrounding boxes to find
                    // atoms which can bond with the current one.
                    for (int p=-1; p<=+1 && ctr<max_per_atom; p++)
                    {
                        int ii = i+p;
                        for (int q=-1; q<=+1 && ctr<max_per_atom; q++)
                        {
                            int jj = j+q;
                            for (int r=-1; r<=+1 && ctr<max_per_atom; r++)
                            {
                                int kk = k+r;
                                // we don't need to see if ii,jj,kk is
                                // within a valid box here, because we
                                // added a layer of extra boxes around
                                // the real ones in case we want to do
                                // periodic checks.  Note that we always
                                // add this extra layer of boxes, though.

                                int index2 = ii + ni*(jj + nj*(kk));
656
                                int nla2 = (int)atomgrid[index2].size();
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
                                for (int la2=0; la2<nla2 && ctr<max_per_atom; la2++)
                                {
                                    if (index1==index2 && la1==la2)
                                        continue;

                                    atomimage atom2 = atomgrid[index2][la2];
                                    int image2 = atom2.first;
                                    int a2 = atom2.second;

                                    // if both atoms are in the native image,
                                    // don't check both directions.  (noting
                                    // that a1 is always in the native image).
                                    // it's only for periodic checks we need
                                    // to do both directions.
                                    if (image2 == nativeImage && a1>a2)
                                        continue;

                                    // get the element number of the
                                    // atoms.  for a2, must look up
                                    // from its *original* atom number
677 678
                                    int e1 = (int) elementnos[a1];
                                    int e2 = (int) elementnos[a2];
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730

                                    // okay, now check for an actual match.
                                    // note that if it's not the native image,
                                    // we need to look up the new actual
                                    // point index.
                                    double dmin, dmax;
                                    bool possible =
                                        AtomBondDistances(e1,e2, dmin,dmax);
                                    if (possible)
                                    {
                                        int newA2 = a2;
                                        if (image2 != nativeImage)
                                            newA2 = imageMap[atomimage(image2,a2)];
                                        double p1[3];
                                        double p2[3];
                                        outPts->GetPoint(a1,p1);
                                        outPts->GetPoint(newA2,p2);
                                        if (ShouldAtomsBeBonded(dmin,dmax,p1,p2))
                                        {
                                            outLines->InsertNextCell(2);
                                            outLines->InsertCellPoint(a1);
                                            outLines->InsertCellPoint(newA2);
                                            ctr++;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    delete[] atomgrid;

    return out;    
}


// ****************************************************************************
//  Method: avtCreateBondsFilter::ExecuteData_Slow
//
//  Purpose:
//      N^2 brute-force algorithm search for bonds.
//
//  Arguments:
//      in        The input dataset.
//
//  Returns:       The output dataset.
//
//  Programmer: Jeremy Meredith
hrchilds's avatar
hrchilds committed
731 732
//  Creation:   Tue Apr 18 17:24:04 PST 2006
//
733 734 735 736 737 738
//  Modifications:
//    Jeremy Meredith, Mon Feb 11 16:39:51 EST 2008
//    The manual bonding matches now supports wildcards, alleviating the need
//    for a "simple" mode.  (The default for the manual mode is actually
//    exactly what the simple mode was going to be anyway.)
//
739 740 741 742 743
//    Jeremy Meredith, Wed Jan 27 10:37:03 EST 2010
//    Added periodic atom matching support.  This is a bit slow for the moment,
//    about a 10x penalty compared to the non-periodic matching, so we should
//    add a faster version at some point....
//
744 745 746 747 748
//    Jeremy Meredith, Wed Jan 27 16:03:04 EST 2010
//    Added a new fast version which subdivides space into cubes.
//    This is now known as the "slow" version.  Also, fixed a bug
//    with setting the periodic instance min/max.
//
749 750 751 752
//    Jeremy Meredith, Wed Aug 11 10:21:59 EDT 2010
//    Use the element variable specified in the attributes.
//    Support any type of input nodal array.
//
753 754 755
//    Kathleen Biagas, Tue Aug 21 16:08:27 MST 2012 
//    Preserve coordinate type.
//
756 757 758
//    Eric Brugger, Wed Jul 23 11:25:16 PDT 2014
//    Modified the class to work with avtDataRepresentation.
//
hrchilds's avatar
hrchilds committed
759 760 761
// ****************************************************************************

vtkDataSet *
762
avtCreateBondsFilter::ExecuteData_Slow(vtkPolyData *in)
hrchilds's avatar
hrchilds committed
763
{
764 765 766 767 768 769 770 771 772
    //
    // Extract some input data
    //
    vtkPoints    *inPts = in->GetPoints();
    vtkCellArray *inVerts = in->GetVerts();
    vtkPointData *inPD  = in->GetPointData();
    vtkCellData  *inCD  = in->GetCellData();
    int nPts   = in->GetNumberOfPoints();
    int nVerts = in->GetNumberOfVerts();
hrchilds's avatar
hrchilds committed
773

774 775 776 777 778 779
    vtkDataArray *element;
    if (atts.GetElementVariable() == "default")
        element = inPD->GetScalars();
    else
        element = inPD->GetArray(atts.GetElementVariable().c_str());
    if (!element)
hrchilds's avatar
hrchilds committed
780
    {
781 782
        debug1 << "avtCreateBondsFilter: did not find appropriate point array\n";
        debug1 << "   -- returning original data set with no bonds changed.\n";
783
        in->Register(NULL);
784
        return in;
hrchilds's avatar
hrchilds committed
785 786
    }

787 788 789 790
    vector<float> elementnos;
    elementnos.resize(nPts);
    for (int i=0; i<nPts; i++)
        elementnos[i] = element->GetTuple1(i);
hrchilds's avatar
hrchilds committed
791

792 793 794 795 796 797
    //
    // Set up the output stuff
    //
    vtkPolyData  *out      = in->NewInstance();
    vtkPointData *outPD    = out->GetPointData();
    vtkCellData  *outCD    = out->GetCellData();
798
    vtkPoints    *outPts   = vtkPoints::New(inPts->GetDataType());
799 800 801 802 803 804 805 806 807 808 809 810
    vtkCellArray *outVerts = vtkCellArray::New();
    vtkCellArray *outLines = vtkCellArray::New();
    out->GetFieldData()->ShallowCopy(in->GetFieldData());
    out->SetPoints(outPts);
    out->SetLines(outLines);
    out->SetVerts(outVerts);
    outPts->Delete();
    outLines->Delete();
    outVerts->Delete();

    //outPts->SetNumberOfPoints(nPts * 1.1);
    outPD->CopyAllocate(inPD,nPts);
811
    outCD->CopyAllocate(inCD,(int)(nVerts*1.2));
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834

    //
    // Copy the input points and verts over.
    //
    for (int p=0; p<nPts; p++)
    {
        double pt[4] = {0,0,0,1};
        in->GetPoint(p, pt);
        int outpt = outPts->InsertNextPoint(pt);
        outPD->CopyData(inPD, p, outpt);
    }
    vtkIdType *vertPtr = inVerts->GetPointer();
    for (int v=0; v<nVerts; v++)
    {
        if (*vertPtr == 1)
        {
            vtkIdType id = *(vertPtr+1);
            int outcell = outVerts->InsertNextCell(1);
            outVerts->InsertCellPoint(id);
            outCD->CopyData(inCD, v, outcell);
        }
        vertPtr += (*vertPtr+1);
    }
hrchilds's avatar
hrchilds committed
835

836
    int natoms = in->GetNumberOfPoints();
hrchilds's avatar
hrchilds committed
837 838


839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
    //
    // Extract unit cell vectors in case we want to add bonds
    // for periodic atom images
    //
    bool addPeriodicBonds = atts.GetAddPeriodicBonds();
    double xv[3], yv[3], zv[3];
    for (int j=0; j<3; j++)
    {
        if (atts.GetUseUnitCellVectors())
        {
            const avtDataAttributes &datts = GetInput()->GetInfo().GetAttributes();
            const float *unitCell = datts.GetUnitCellVectors();
            xv[j] = unitCell[3*0+j];
            yv[j] = unitCell[3*1+j];
            zv[j] = unitCell[3*2+j];
        }
        else
        {
            xv[j] = atts.GetXVector()[j];
            yv[j] = atts.GetYVector()[j];
            zv[j] = atts.GetZVector()[j];
        }
    }

    map<pair<int, int>, int> imageMap;

    //
    // Loop over the (n^2)/2 atom pairs
    //
hrchilds's avatar
hrchilds committed
868
    int max_per_atom = atts.GetMaxBondsClamp();
869
    int timerMain = visitTimer->StartTimer();
hrchilds's avatar
hrchilds committed
870 871 872
    for (int i=0; i<natoms; i++)
    {
        int ctr = 0;
hrchilds's avatar
hrchilds committed
873
        for (int j=natoms-1; j>i && ctr<max_per_atom; j--)
hrchilds's avatar
hrchilds committed
874 875 876 877
        {
            if (i==j)
                continue;

878 879 880 881
            double p1[3];
            double p2[3];
            inPts->GetPoint(i,p1);
            inPts->GetPoint(j,p2);
hrchilds's avatar
hrchilds committed
882

883 884
            int e1 = (int) elementnos[i];
            int e2 = (int) elementnos[j];
885 886 887 888

            double dmin, dmax;
            bool possible = AtomBondDistances(e1,e2, dmin,dmax);
            if (possible && ShouldAtomsBeBonded(dmin,dmax, p1,p2))
hrchilds's avatar
hrchilds committed
889
            {
890 891 892
                outLines->InsertNextCell(2);
                outLines->InsertCellPoint(i);
                outLines->InsertCellPoint(j);
hrchilds's avatar
hrchilds committed
893 894 895 896
                ctr++;
            }
        }
    }
897 898 899 900 901 902 903 904 905 906 907
    visitTimer->StopTimer(timerMain, "CreateBonds: Main n^2 loop");

    //
    // If we're adding periodic bonds, loop over all n^2 atoms again.
    // This time, look for ones where one of the two atoms is not
    // in the native image (but the other one is).  Note that we're
    // not keeping any earlier bond-per-atom counters, so when this
    // is added, we might get 2*max total bonds.  Since this is
    // typically non-physical and is only a limit for sanity, no big
    // harm done.
    //
908 909 910
    int perXmin = 0, perXmax = 0;
    int perYmin = 0, perYmax = 0;
    int perZmin = 0, perZmax = 0;
911 912
    if (addPeriodicBonds && atts.GetPeriodicInX())
    {
913 914
        perXmin = -1;
        perXmax = +1;
915 916 917
    }
    if (addPeriodicBonds && atts.GetPeriodicInY())
    {
918 919
        perYmin = -1;
        perYmax = +1;
920 921 922
    }
    if (addPeriodicBonds && atts.GetPeriodicInZ())
    {
923 924
        perZmin = -1;
        perZmax = +1;
925 926 927 928 929
    }

    int timerPer = visitTimer->StartTimer();
    for (int j=0; j<natoms && addPeriodicBonds; j++)
    {
930
        int e2 = (int) elementnos[j];
931 932 933 934 935 936 937 938
        double p2[3];
        inPts->GetPoint(j,p2);

        int    newJ[27];
        double newX[27];
        double newY[27];
        double newZ[27];
        int image = 0;
939
        for (int px=perXmin; px<=perXmax; px++)
940
        {
941
            for (int py=perYmin; py<=perYmax; py++)
942
            {
943
                for (int pz=perZmin; pz<=perZmax; pz++)
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
                {
                    double pj[3] = {p2[0],p2[1],p2[2]};
                    for (int c=0; c<3; c++)
                    {
                        pj[c] += xv[c] * double(px);
                        pj[c] += yv[c] * double(py);
                        pj[c] += zv[c] * double(pz);
                    }
                    newJ[image] = -1;
                    newX[image] = pj[0];
                    newY[image] = pj[1];
                    newZ[image] = pj[2];
                    image++;
                }
            }
        }

        int ctr = 0;
        for (int i=0; i<natoms && addPeriodicBonds && ctr<max_per_atom; i++)
        {
            if (i==j)
                continue;

967
            int e1 = (int) elementnos[i];
968 969 970 971 972 973 974 975 976
            double p1[3];
            inPts->GetPoint(i,p1);

            double dmin, dmax;
            bool possible = AtomBondDistances(e1,e2, dmin,dmax);
            if (!possible)
                continue;

            int image = 0;
977
            for (int px=perXmin; px<=perXmax; px++)
978
            {
979
                for (int py=perYmin; py<=perYmax; py++)
980
                {
981
                    for (int pz=perZmin; pz<=perZmax; pz++, image++)
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
                    {
                        bool nativeImage = (px==0 && py==0 && pz==0);
                        if (nativeImage)
                            continue;

                        double *pi = p1;
                        double pj[3] = {newX[image],newY[image],newZ[image]};

                        if (ShouldAtomsBeBonded(dmin,dmax,pi,pj))
                        {
                            if (newJ[image] == -1)
                            {
                                pair<int,int> jthImage(image,j);
                                if (imageMap.count(jthImage)!=0)
                                {
                                    newJ[image] = imageMap[jthImage];
                                }
                                else
                                {
                                    newJ[image] = outPts->InsertNextPoint(pj);
                                    imageMap[jthImage] = newJ[image];
                                    outPD->CopyData(inPD, j, newJ[image]);
                                        
                                    // We're not adding a vertex cell here;
                                    // these are not real atoms, and the
                                    // molecule plot will now avoid drawing
                                    // them if no Vert is associated w/ it.
                                    //int outcell = outVerts->InsertNextCell(1);
                                    //outVerts->InsertCellPoint(newJ[image]);
                                    //outCD->CopyData(inCD, j, outcell);
                                }
                            }
                            outLines->InsertNextCell(2);
                            outLines->InsertCellPoint(i);
                            outLines->InsertCellPoint(newJ[image]);
                            ctr++;
                        }
                    }
                }
            }
        }
    }
    visitTimer->StopTimer(timerPer, "CreateBonds: periodic n^2 * 27images loop");

    vtkDataArray *origCellNums = outPD->GetArray("avtOriginalNodeNumbers");
    if (origCellNums)
    {
        for (int i=nPts; i<out->GetNumberOfPoints(); i++)
            origCellNums->SetTuple1(i,-1);
    }
hrchilds's avatar
hrchilds committed
1032

1033
    return out;
hrchilds's avatar
hrchilds committed
1034 1035 1036
}

// ****************************************************************************
hrchilds's avatar
hrchilds committed
1037
//  Method:  avtCreateBondsFilter::ModifyContract
hrchilds's avatar
hrchilds committed
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
//
//  Purpose:
//    Add element numbers to the secondary variable request.
//
//  Arguments:
//    spec       the pipeline specification
//
//  Programmer:  Jeremy Meredith
//  Creation:    August 29, 2006
//
1048 1049 1050 1051 1052
//  Modifications:
//    Jeremy Meredith, Wed Aug 11 10:21:59 EDT 2010
//    Use the element variable specified in the attributes.
//    Skip the removal of a "bonds" variable -- this was obsolete long ago.
//
hrchilds's avatar
hrchilds committed
1053
// ****************************************************************************
hrchilds's avatar
hrchilds committed
1054 1055
avtContract_p
avtCreateBondsFilter::ModifyContract(avtContract_p spec)
hrchilds's avatar
hrchilds committed
1056 1057 1058 1059
{
    //
    // Get the old specification.
    //
hrchilds's avatar
hrchilds committed
1060
    avtDataRequest_p ds = spec->GetDataRequest();
hrchilds's avatar
hrchilds committed
1061 1062 1063 1064 1065
    const char *primaryVariable = ds->GetVariable();

    //
    // Make a new one
    //
hrchilds's avatar
hrchilds committed
1066
    avtDataRequest_p nds = new avtDataRequest(ds);
hrchilds's avatar
hrchilds committed
1067 1068

    // We need those element numbers.
1069 1070
    if (string(primaryVariable) != atts.GetElementVariable() &&
        atts.GetElementVariable() != "default")
hrchilds's avatar
hrchilds committed
1071
    {
1072
        nds->AddSecondaryVariable(atts.GetElementVariable().c_str());
hrchilds's avatar
hrchilds committed
1073 1074 1075 1076 1077
    }

    //
    // Create the new pipeline spec from the data spec, and return
    //
hrchilds's avatar
hrchilds committed
1078
    avtContract_p rv = new avtContract(spec, nds);
hrchilds's avatar
hrchilds committed
1079 1080 1081

    return rv;
}
whitlocb's avatar
whitlocb committed
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104

// ****************************************************************************
// Method: avtCreateBondsFilter::UpdateDataObjectInfo
//
// Purpose:
//   Update the data object information.
//
// Note:       Work partially supported by DOE Grant SC0007548.
//
// Programmer: Brad Whitlock
// Creation:   Tue Mar 18 10:53:05 PDT 2014
//
// Modifications:
//
// ****************************************************************************

void
avtCreateBondsFilter::UpdateDataObjectInfo(void)
{
    avtPluginDataTreeIterator::UpdateDataObjectInfo();

    GetOutput()->GetInfo().GetAttributes().AddFilterMetaData("CreateBonds");
}