1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 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 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 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 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 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 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 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 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 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 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 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 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 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 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 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 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 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 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkIOSSModel.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
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.
=========================================================================*/
#include "vtkIOSSModel.h"
#include "vtkArrayDispatch.h"
#include "vtkCellData.h"
#include "vtkDataArrayRange.h"
#include "vtkDataAssembly.h"
#include "vtkDummyController.h"
#include "vtkIOSSUtilities.h"
#include "vtkIOSSWriter.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkMultiProcessController.h"
#include "vtkObjectFactory.h"
#include "vtkPartitionedDataSet.h"
#include "vtkPartitionedDataSetCollection.h"
#include "vtkPointData.h"
#include "vtkSMPTools.h"
#include "vtkSmartPointer.h"
#include "vtkUnsignedCharArray.h"
#include "vtkUnstructuredGrid.h"
#include <vtksys/MD5.h>
// Ioss includes
#include <vtk_ioss.h>
// clang-format off
#include VTK_IOSS(Ioss_Assembly.h)
#include VTK_IOSS(Ioss_DatabaseIO.h)
#include VTK_IOSS(Ioss_EdgeBlock.h)
#include VTK_IOSS(Ioss_EdgeSet.h)
#include VTK_IOSS(Ioss_ElementBlock.h)
#include VTK_IOSS(Ioss_ElementSet.h)
#include VTK_IOSS(Ioss_ElementTopology.h)
#include VTK_IOSS(Ioss_FaceBlock.h)
#include VTK_IOSS(Ioss_FaceSet.h)
#include VTK_IOSS(Ioss_IOFactory.h)
#include VTK_IOSS(Ioss_NodeBlock.h)
#include VTK_IOSS(Ioss_NodeSet.h)
#include VTK_IOSS(Ioss_Region.h)
#include VTK_IOSS(Ioss_SideBlock.h)
#include VTK_IOSS(Ioss_SideSet.h)
#include VTK_IOSS(Ioss_StructuredBlock.h)
// clang-format on
#include <map>
#include <set>
#include <numeric>
namespace
{
std::set<unsigned int> GetDatasetIndices(vtkDataAssembly* assembly, const char* name)
{
if (assembly && assembly->GetRootNodeName() && strcmp(assembly->GetRootNodeName(), "IOSS") == 0)
{
const auto idx = assembly->FindFirstNodeWithName(name);
if (idx != -1)
{
const auto vector = assembly->GetDataSetIndices(assembly->FindFirstNodeWithName(name));
return std::set<unsigned int>{ vector.begin(), vector.end() };
}
}
return {};
}
std::map<unsigned char, int64_t> GetElementCounts(
vtkPartitionedDataSet* pd, vtkMultiProcessController* controller)
{
std::set<unsigned char> cellTypes;
auto datasets = vtkCompositeDataSet::GetDataSets<vtkUnstructuredGrid>(pd);
for (auto& ug : datasets)
{
auto* distinctCellTypes = ug->GetDistinctCellTypesArray();
auto range = vtk::DataArrayValueRange(distinctCellTypes);
std::copy(range.begin(), range.end(), std::inserter(cellTypes, cellTypes.end()));
}
// now reduce this across all ranks as well.
if (controller->GetNumberOfProcesses() > 1)
{
vtkNew<vtkUnsignedCharArray> source;
source->SetNumberOfTuples(cellTypes.size());
std::copy(cellTypes.begin(), cellTypes.end(), source->GetPointer(0));
vtkNew<vtkUnsignedCharArray> result;
controller->AllGatherV(source, result);
auto range = vtk::DataArrayValueRange(result);
std::copy(range.begin(), range.end(), std::inserter(cellTypes, cellTypes.end()));
}
// compute element counts
std::map<unsigned char, std::atomic<int64_t>> elementCounts;
for (auto& type : cellTypes)
{
elementCounts[type] = 0;
}
for (auto& ug : datasets)
{
vtkSMPTools::For(0, ug->GetNumberOfCells(), [&](vtkIdType start, vtkIdType end) {
for (vtkIdType cc = start; cc < end; ++cc)
{
++elementCounts[static_cast<unsigned char>(ug->GetCellType(cc))];
}
});
}
return { elementCounts.begin(), elementCounts.end() };
}
Ioss::Field::BasicType GetFieldType(vtkDataArray* array)
{
if (array->GetDataType() == VTK_DOUBLE || array->GetDataType() == VTK_FLOAT)
{
return Ioss::Field::DOUBLE;
}
else if (array->GetDataTypeSize() <= 32)
{
return Ioss::Field::INT32;
}
else
{
return Ioss::Field::INT64;
}
}
std::vector<std::tuple<std::string, Ioss::Field::BasicType, int>> GetFields(
int association, vtkCompositeDataSet* pdc, vtkMultiProcessController* vtkNotUsed(controller))
{
std::vector<std::tuple<std::string, Ioss::Field::BasicType, int>> fields;
vtkDataSetAttributesFieldList fieldList;
for (auto& ds : vtkCompositeDataSet::GetDataSets<vtkUnstructuredGrid>(pdc))
{
fieldList.IntersectFieldList(ds->GetAttributes(association));
}
vtkNew<vtkPointData> tmp;
tmp->CopyAllocate(fieldList, 0);
for (int idx = 0, max = tmp->GetNumberOfArrays(); idx < max; ++idx)
{
if (auto* array = tmp->GetArray(idx))
{
if (array == tmp->GetGlobalIds())
{
// we don't want to add global ids again.
continue;
}
if (strcmp(array->GetName(), "object_id") == 0)
{
// skip "object_id". that's an array added by Ioss reader.
continue;
}
const auto type = ::GetFieldType(array);
fields.emplace_back(array->GetName(), type, array->GetNumberOfComponents());
}
}
// TODO: reduce in parallel; for non IOSS input, we'll need to explicitly
// ensure all blocks have same fields across all ranks.
return fields;
}
template <typename T>
struct PutFieldWorker
{
std::vector<std::vector<T>> Data;
size_t Offset{ 0 };
const std::vector<vtkIdType>* SourceIds = nullptr;
PutFieldWorker(int numComponents, size_t targetSize)
: Data(numComponents)
{
for (int cc = 0; cc < numComponents; ++cc)
{
this->Data[cc].resize(targetSize);
}
}
void SetSourceIds(const std::vector<vtkIdType>* ids) { this->SourceIds = ids; }
template <typename ArrayType>
void operator()(ArrayType* array)
{
using SourceT = vtk::GetAPIType<ArrayType>;
vtkSMPTools::For(0, this->SourceIds->size(), [&](vtkIdType start, vtkIdType end) {
SourceT* tuple = new SourceT[this->Data.size()];
for (vtkIdType cc = start; cc < end; ++cc)
{
array->GetTypedTuple((*this->SourceIds)[cc], tuple);
for (size_t comp = 0; comp < this->Data.size(); ++comp)
{
this->Data[comp][this->Offset + cc] = tuple[comp];
}
}
delete[] tuple;
});
this->Offset += this->SourceIds->size();
}
};
template <typename T>
struct DisplacementWorker
{
std::vector<std::vector<T>>& Data;
size_t Offset{ 0 };
double Magnitude;
const std::vector<vtkIdType>* SourceIds = nullptr;
DisplacementWorker(std::vector<std::vector<T>>& data, double magnitude)
: Data(data)
, Magnitude(magnitude)
{
}
void SetSourceIds(const std::vector<vtkIdType>* ids) { this->SourceIds = ids; }
template <typename ArrayType>
void operator()(ArrayType* array)
{
using SourceT = vtk::GetAPIType<ArrayType>;
vtkSMPTools::For(0, this->SourceIds->size(), [&](vtkIdType start, vtkIdType end) {
SourceT* displ = new SourceT[this->Data.size()];
for (vtkIdType cc = start; cc < end; ++cc)
{
array->GetTypedTuple((*this->SourceIds)[cc], displ);
for (size_t comp = 0; comp < this->Data.size(); ++comp)
{
this->Data[comp][this->Offset + cc] -= (displ[comp] * this->Magnitude);
}
}
delete[] displ;
});
this->Offset += this->SourceIds->size();
}
};
struct vtkGroupingEntity
{
vtkIOSSWriter* Writer = nullptr;
vtkGroupingEntity(vtkIOSSWriter* writer)
: Writer(writer)
{
}
virtual ~vtkGroupingEntity() = default;
virtual void Define(Ioss::Region& region) const = 0;
virtual void Model(Ioss::Region& region) const = 0;
virtual void DefineTransient(Ioss::Region& region) const = 0;
virtual void Transient(Ioss::Region& region) const = 0;
virtual void AppendMD5(vtksysMD5* md5) const = 0;
protected:
template <typename IossGroupingEntityT, typename DatasetT>
void PutFields(IossGroupingEntityT* block,
const std::vector<std::tuple<std::string, Ioss::Field::BasicType, int>>& fields,
const std::vector<std::vector<vtkIdType>>& lIds, const std::vector<DatasetT*>& datasets,
int association) const
{
for (const auto& field : fields)
{
switch (std::get<1>(field))
{
case Ioss::Field::DOUBLE:
this->PutField<double>(
block, std::get<0>(field), std::get<2>(field), lIds, datasets, association);
break;
case Ioss::Field::INT32:
this->PutField<int32_t>(
block, std::get<0>(field), std::get<2>(field), lIds, datasets, association);
break;
case Ioss::Field::INT64:
this->PutField<int64_t>(
block, std::get<0>(field), std::get<2>(field), lIds, datasets, association);
break;
default:
vtkLogF(TRACE, "Unsupported field type. Skipping %s", std::get<0>(field).c_str());
break;
}
}
}
template <typename T, typename IossGroupingEntityT, typename DatasetT>
void PutField(IossGroupingEntityT* block, const std::string& name, int numComponents,
const std::vector<std::vector<vtkIdType>>& lIds, const std::vector<DatasetT*>& datasets,
int association) const
{
assert(datasets.size() == lIds.size());
const size_t totalSize = std::accumulate(lIds.begin(), lIds.end(), static_cast<size_t>(0),
[](size_t sum, const std::vector<vtkIdType>& ids) { return sum + ids.size(); });
using Dispatcher = vtkArrayDispatch::DispatchByValueType<vtkArrayDispatch::AllTypes>;
PutFieldWorker<T> worker(numComponents, totalSize);
for (size_t dsIndex = 0; dsIndex < datasets.size(); ++dsIndex)
{
auto& ds = datasets[dsIndex];
auto& lids = lIds[dsIndex];
worker.SetSourceIds(&lids);
Dispatcher::Execute(ds->GetAttributes(association)->GetArray(name.c_str()), worker);
}
for (int comp = 0; comp < numComponents; ++comp)
{
const auto fieldName = numComponents == 1 ? name : name + std::to_string(comp + 1);
block->put_field_data(fieldName, worker.Data[comp]);
}
}
void DefineFields(Ioss::GroupingEntity* block,
const std::vector<std::tuple<std::string, Ioss::Field::BasicType, int>>& fields,
Ioss::Field::RoleType role, int64_t elementCount) const
{
for (const auto& field : fields)
{
if (std::get<2>(field) == 1)
{
block->field_add(
Ioss::Field(std::get<0>(field), std::get<1>(field), "scalar", role, elementCount));
}
else
{
for (int comp = 0; comp < std::get<2>(field); ++comp)
{
block->field_add(Ioss::Field(std::get<0>(field) + std::to_string(comp + 1),
std::get<1>(field), "scalar", role, elementCount));
}
}
}
}
};
} // end namespace {}
VTK_ABI_NAMESPACE_BEGIN
/**
* Builds an Ioss::NodeBlock. Since an exodus file has a single common node
* block, we need to build one based on all points from all blocks.
*
* Another thing to handle is displacements. If input dataset is coming from
* IOSS reader, the point coordinates may have been displaced using the
* displacement vectors in the dataset.
*/
struct vtkNodeBlock : vtkGroupingEntity
{
const std::vector<vtkUnstructuredGrid*> DataSets;
const std::string Name;
// build a map of ds idx, gid, and lid and use that later.
std::vector<int32_t> Ids;
std::vector<std::vector<vtkIdType>> IdsRaw;
std::vector<std::tuple<std::string, Ioss::Field::BasicType, int>> Fields;
vtkNodeBlock(vtkPartitionedDataSetCollection* pdc, const std::string& name,
vtkMultiProcessController* controller, vtkIOSSWriter* writer)
: vtkGroupingEntity(writer)
, DataSets{ vtkCompositeDataSet::GetDataSets<vtkUnstructuredGrid>(pdc) }
, Name(name)
{
this->IdsRaw.reserve(this->DataSets.size());
std::set<int32_t> id_set;
for (auto& ds : this->DataSets)
{
auto* pd = ds->GetPointData();
auto* gids = vtkIdTypeArray::SafeDownCast(pd->GetGlobalIds());
if (!gids)
{
throw std::runtime_error("point global ids missing.");
}
const auto numPoints = ds->GetNumberOfPoints();
assert(gids->GetNumberOfTuples() == numPoints);
this->Ids.reserve(this->Ids.size() + numPoints);
this->IdsRaw.emplace_back();
this->IdsRaw.back().reserve(numPoints);
const vtkIdType gidOffset = writer->GetOffsetGlobalIds() ? 1 : 0;
for (vtkIdType cc = 0; cc < numPoints; ++cc)
{
const auto gid = gids->GetValue(cc);
if (id_set.insert(gid).second)
{
this->Ids.push_back(gid + gidOffset);
this->IdsRaw.back().push_back(cc);
}
}
}
assert(this->DataSets.size() == this->IdsRaw.size());
this->Fields = ::GetFields(vtkDataObject::POINT, pdc, controller);
}
void AppendMD5(vtksysMD5* md5) const override
{
vtksysMD5_Append(md5, reinterpret_cast<const unsigned char*>(this->Ids.data()),
static_cast<int>(sizeof(int32_t) * this->Ids.size()));
}
void Define(Ioss::Region& region) const override
{
auto* block = new Ioss::NodeBlock(region.get_database(), this->Name, this->Ids.size(), 3);
// block->property_add(Ioss::Property("id", 1)); // block id.
region.add(block);
}
void DefineTransient(Ioss::Region& region) const override
{
auto* block = region.get_node_block(this->Name);
this->DefineFields(block, this->Fields, Ioss::Field::TRANSIENT, this->Ids.size());
}
void Model(Ioss::Region& region) const override
{
auto* block = region.get_node_block(this->Name);
block->put_field_data("ids", this->Ids);
// add mesh coordinates
using Dispatcher = vtkArrayDispatch::DispatchByValueType<vtkArrayDispatch::Reals>;
PutFieldWorker<double> worker(3, this->Ids.size());
for (size_t dsIndex = 0; dsIndex < this->DataSets.size(); ++dsIndex)
{
auto& ds = this->DataSets[dsIndex];
auto& lids = this->IdsRaw[dsIndex];
worker.SetSourceIds(&lids);
Dispatcher::Execute(ds->GetPoints()->GetData(), worker);
}
// if displacement array is present, offset the mesh coordinates by the
// provided displacement.
const auto displMagnitude =
this->DataSets.empty() ? 0.0 : this->Writer->GetDisplacementMagnitude();
const std::string displName =
displMagnitude > 0 ? vtkIOSSUtilities::GetDisplacementFieldName(this->DataSets.front()) : "";
if (!displName.empty() && displMagnitude > 0.0)
{
DisplacementWorker<double> dworker(worker.Data, displMagnitude);
for (size_t dsIndex = 0; dsIndex < this->DataSets.size(); ++dsIndex)
{
auto& ds = this->DataSets[dsIndex];
auto& lids = this->IdsRaw[dsIndex];
dworker.SetSourceIds(&lids);
Dispatcher::Execute(ds->GetPointData()->GetArray(displName.c_str()), dworker);
}
}
block->put_field_data("mesh_model_coordinates_x", worker.Data[0]);
block->put_field_data("mesh_model_coordinates_y", worker.Data[1]);
block->put_field_data("mesh_model_coordinates_z", worker.Data[2]);
}
void Transient(Ioss::Region& region) const override
{
auto* block = region.get_node_block(this->Name);
this->PutFields(block, this->Fields, this->IdsRaw, this->DataSets, vtkDataObject::POINT);
}
};
/**
* Builds a Ioss::ElementBlock from a vtkPartitionedDataSet. The differences
* between the Ioss and VTK data model for the two are handled as follows:
*
* * We only support vtkPartitionedDataSet comprising of one or more vtkUnstructuredGrids.
* All other dataset types are simply ignored.
*
* * An ElementBlock cannot have multiple "pieces" in the same file. So if a
* vtkPartitionedDataSet has multiple datasets, we need to "combine" them into
* one.
*
* * An ElementBlock cannot have elements of different types. However,
* vtkUnstructuredGrid supports heterogeneous cells. So if all
* vtkUnstructuredGrids in the vtkPartitionedDataSet have more than 1 cell type,
* we create multiple element blocks. Each ElementBlock is uniquely named by
* using the given block name and the element type as a suffix.
*
* In MPI world, the cell types are gathered across all ranks to ensure each
* ranks creates identical blocks / block names.
*
*/
struct vtkElementBlock : public vtkGroupingEntity
{
vtkPartitionedDataSet* PartitionedDataSet;
std::string RootName;
std::map<unsigned char, int64_t> ElementCounts;
std::vector<std::tuple<std::string, Ioss::Field::BasicType, int>> Fields;
vtkElementBlock(vtkPartitionedDataSet* pd, const std::string& name,
vtkMultiProcessController* controller, vtkIOSSWriter* writer)
: vtkGroupingEntity(writer)
, PartitionedDataSet(pd)
, RootName{ name }
{
auto datasets = vtkCompositeDataSet::GetDataSets<vtkUnstructuredGrid>(pd);
for (auto& ug : datasets)
{
auto* cd = ug->GetCellData();
auto* gids = vtkIdTypeArray::SafeDownCast(cd->GetGlobalIds());
if (!gids)
{
throw std::runtime_error("cell global ids missing!");
}
}
this->ElementCounts = ::GetElementCounts(pd, controller);
this->Fields = ::GetFields(vtkDataObject::CELL, pd, controller);
}
void AppendMD5(vtksysMD5* md5) const override
{
vtksysMD5_Append(md5, reinterpret_cast<const unsigned char*>(this->RootName.c_str()), -1);
for (auto& pair : this->ElementCounts)
{
vtksysMD5_Append(md5, reinterpret_cast<const unsigned char*>(&pair.first),
static_cast<int>(sizeof(pair.first)));
vtksysMD5_Append(md5, reinterpret_cast<const unsigned char*>(&pair.second),
static_cast<int>(sizeof(pair.second)));
}
}
void Define(Ioss::Region& region) const override
{
for (auto& pair : this->ElementCounts)
{
const int64_t elementCount = pair.second;
const unsigned char vtk_cell_type = pair.first;
const auto* element = vtkIOSSUtilities::GetElementTopology(vtk_cell_type);
const auto& elementType = element->name();
const std::string bname =
(this->ElementCounts.size() == 1) ? this->RootName : this->RootName + "_" + elementType;
auto* block = new Ioss::ElementBlock(region.get_database(), bname, elementType, elementCount);
// FIXME: for now, we let IOSS figure out the id; we need to add logic to
// preserve input id, if we can.
// block->property_add(Ioss::Property("id", id++));
region.add(block);
}
}
void DefineTransient(Ioss::Region& region) const override
{
for (auto& pair : this->ElementCounts)
{
unsigned char vtk_cell_type = pair.first;
const int64_t elementCount = pair.second;
const auto* element = vtkIOSSUtilities::GetElementTopology(vtk_cell_type);
const auto& elementType = element->name();
const std::string bname =
(this->ElementCounts.size() == 1) ? this->RootName : this->RootName + "_" + elementType;
auto* block = region.get_element_block(bname);
this->DefineFields(block, this->Fields, Ioss::Field::TRANSIENT, elementCount);
}
}
void Model(Ioss::Region& region) const override
{
auto datasets = vtkCompositeDataSet::GetDataSets<vtkUnstructuredGrid>(this->PartitionedDataSet);
for (auto& pair : this->ElementCounts)
{
unsigned char vtk_cell_type = pair.first;
const int64_t elementCount = pair.second;
const auto* element = vtkIOSSUtilities::GetElementTopology(vtk_cell_type);
const auto& elementType = element->name();
const int nodeCount = element->number_nodes();
const std::string bname =
(this->ElementCounts.size() == 1) ? this->RootName : this->RootName + "_" + elementType;
auto* block = region.get_element_block(bname);
// populate ids.
std::vector<int32_t> elementIds; // these are global ids.
elementIds.reserve(elementCount);
std::vector<int32_t> connectivity;
connectivity.reserve(elementCount * nodeCount);
const int32_t gidOffset = this->Writer->GetOffsetGlobalIds() ? 1 : 0;
for (auto& ug : datasets)
{
auto* gids = vtkIdTypeArray::SafeDownCast(ug->GetCellData()->GetGlobalIds());
auto* pointGIDs = vtkIdTypeArray::SafeDownCast(ug->GetPointData()->GetGlobalIds());
for (vtkIdType cc = 0, max = ug->GetNumberOfCells(); cc < max; ++cc)
{
if (ug->GetCellType(cc) == vtk_cell_type)
{
elementIds.push_back(gidOffset + gids->GetValue(cc));
vtkIdType numPts;
vtkIdType const* cellPoints;
ug->GetCellPoints(cc, numPts, cellPoints);
assert(numPts == nodeCount);
// map cell's point to global ids for those points.
std::transform(cellPoints, cellPoints + numPts, std::back_inserter(connectivity),
[&](vtkIdType ptid) { return gidOffset + pointGIDs->GetValue(ptid); });
}
}
}
assert(elementIds.size() == static_cast<size_t>(elementCount));
assert(connectivity.size() == static_cast<size_t>(elementCount * nodeCount));
block->put_field_data("ids", elementIds);
block->put_field_data("connectivity", connectivity);
}
}
void Transient(Ioss::Region& region) const override
{
auto datasets = vtkCompositeDataSet::GetDataSets<vtkUnstructuredGrid>(this->PartitionedDataSet);
for (auto& pair : this->ElementCounts)
{
unsigned char vtk_cell_type = pair.first;
const auto* element = vtkIOSSUtilities::GetElementTopology(vtk_cell_type);
const auto& elementType = element->name();
const std::string bname =
(this->ElementCounts.size() == 1) ? this->RootName : this->RootName + "_" + elementType;
auto* block = region.get_element_block(bname);
// populate ids.
std::vector<std::vector<vtkIdType>> lIds; // these are local ids.
for (auto& ug : datasets)
{
lIds.emplace_back();
lIds.back().reserve(ug->GetNumberOfCells());
for (vtkIdType cc = 0, max = ug->GetNumberOfCells(); cc < max; ++cc)
{
if (ug->GetCellType(cc) == vtk_cell_type)
{
lIds.back().push_back(cc);
}
}
}
// add fields.
this->PutFields(block, this->Fields, lIds, datasets, vtkDataObject::CELL);
}
}
};
struct vtkNodeSet : public vtkGroupingEntity
{
vtkPartitionedDataSet* PartitionedDataSet;
std::string Name;
int64_t Count{ 0 };
vtkNodeSet(vtkPartitionedDataSet* pd, const std::string& name,
vtkMultiProcessController* vtkNotUsed(controller), vtkIOSSWriter* writer)
: vtkGroupingEntity(writer)
, PartitionedDataSet(pd)
, Name(name)
{
auto datasets = vtkCompositeDataSet::GetDataSets<vtkUnstructuredGrid>(pd);
for (auto& ug : datasets)
{
auto* gids = vtkIdTypeArray::SafeDownCast(ug->GetPointData()->GetGlobalIds());
if (!gids)
{
throw std::runtime_error("missing point global ids for nodesets.");
}
this->Count += ug->GetNumberOfPoints();
}
// TODO: identify nodeset-only fields.
}
void AppendMD5(vtksysMD5* md5) const override
{
vtksysMD5_Append(md5, reinterpret_cast<const unsigned char*>(this->Name.c_str()), -1);
vtksysMD5_Append(md5, reinterpret_cast<const unsigned char*>(&this->Count),
static_cast<int>(sizeof(this->Count)));
}
void Define(Ioss::Region& region) const override
{
auto* nodeset = new Ioss::NodeSet(region.get_database(), this->Name, this->Count);
// nodeset->property_add(Ioss::Property("id", id++));
region.add(nodeset);
}
void DefineTransient(Ioss::Region& vtkNotUsed(region)) const override {}
void Model(Ioss::Region& region) const override
{
auto* nodeset = region.get_nodeset(this->Name);
std::vector<int32_t> ids;
ids.reserve(this->Count);
for (auto& ug : vtkCompositeDataSet::GetDataSets<vtkUnstructuredGrid>(this->PartitionedDataSet))
{
auto* gids = vtkIdTypeArray::SafeDownCast(ug->GetPointData()->GetGlobalIds());
std::copy(
gids->GetPointer(0), gids->GetPointer(gids->GetNumberOfTuples()), std::back_inserter(ids));
}
nodeset->put_field_data("ids", ids);
}
void Transient(Ioss::Region& vtkNotUsed(region)) const override {}
};
struct vtkSideSet : public vtkGroupingEntity
{
vtkPartitionedDataSet* PartitionedDataSet;
std::string Name;
int64_t Count;
vtkSideSet(vtkPartitionedDataSet* pd, const std::string& name,
vtkMultiProcessController* vtkNotUsed(controller), vtkIOSSWriter* writer)
: vtkGroupingEntity(writer)
, PartitionedDataSet(pd)
, Name(name)
, Count{ 0 }
{
auto datasets = vtkCompositeDataSet::GetDataSets<vtkUnstructuredGrid>(pd);
for (auto& ug : datasets)
{
auto* cd = ug->GetCellData();
if (vtkIdTypeArray::SafeDownCast(cd->GetGlobalIds()) != nullptr)
{
throw std::runtime_error("cell global ids present, must not be a sideset.");
}
if (vtkIntArray::SafeDownCast(cd->GetArray("element_side")) == nullptr)
{
throw std::runtime_error("missing 'element_side' cell array.");
}
this->Count += ug->GetNumberOfCells();
}
}
void AppendMD5(vtksysMD5* md5) const override
{
vtksysMD5_Append(md5, reinterpret_cast<const unsigned char*>(this->Name.c_str()), -1);
vtksysMD5_Append(md5, reinterpret_cast<const unsigned char*>(&this->Count),
static_cast<int>(sizeof(this->Count)));
}
void Define(Ioss::Region& region) const override
{
// for mixed topology blocks, IOSS uses "unknown"
const auto* mixed_topo = Ioss::ElementTopology::factory("unknown");
const auto& elementType = mixed_topo->name();
auto* sideblock = new Ioss::SideBlock(
region.get_database(), "sideblock_0", elementType, elementType, this->Count);
auto* sideset = new Ioss::SideSet(region.get_database(), this->Name);
sideset->add(sideblock);
region.add(sideset);
}
void DefineTransient(Ioss::Region& vtkNotUsed(region)) const override {}
void Model(Ioss::Region& region) const override
{
auto* sideset = region.get_sideset(this->Name);
auto* sideblock = sideset->get_side_block("sideblock_0");
std::vector<int32_t> elementSide;
elementSide.reserve(this->Count * 2);
auto datasets = vtkCompositeDataSet::GetDataSets<vtkUnstructuredGrid>(this->PartitionedDataSet);
for (auto& ug : datasets)
{
for (auto&& tuple : vtk::DataArrayTupleRange(
vtkIntArray::SafeDownCast(ug->GetCellData()->GetArray("element_side"))))
{
for (const auto& comp : tuple)
{
elementSide.push_back(comp);
}
}
}
assert(elementSide.size() == static_cast<size_t>(this->Count * 2));
sideblock->put_field_data("element_side", elementSide);
}
void Transient(Ioss::Region& vtkNotUsed(region)) const override {}
};
//=============================================================================
class vtkIOSSModel::vtkInternals
{
public:
vtkSmartPointer<vtkMultiProcessController> Controller;
std::multimap<Ioss::EntityType, std::shared_ptr<vtkGroupingEntity>> EntityGroups;
};
//----------------------------------------------------------------------------
vtkIOSSModel::vtkIOSSModel(vtkPartitionedDataSetCollection* dataset, vtkIOSSWriter* writer)
: Internals(new vtkIOSSModel::vtkInternals())
{
auto* controller = writer->GetController();
auto& internals = (*this->Internals);
internals.Controller = controller
? vtk::MakeSmartPointer(controller)
: vtk::TakeSmartPointer(vtkMultiProcessController::SafeDownCast(vtkDummyController::New()));
auto* assembly = dataset->GetDataAssembly();
const bool isIOSS = writer->GetPreserveInputEntityGroups() &&
(assembly && assembly->GetRootNodeName() && strcmp(assembly->GetRootNodeName(), "IOSS") == 0);
const auto elementBlockIndices = ::GetDatasetIndices(assembly, "element_blocks");
const auto nodeSetIndices = ::GetDatasetIndices(assembly, "node_sets");
const auto sideSetIndices = ::GetDatasetIndices(assembly, "side_sets");
// first things first, determine all information necessary about nodes.
// there's just 1 node block for exodus, build that.
internals.EntityGroups.emplace(Ioss::EntityType::NODEBLOCK,
std::make_shared<vtkNodeBlock>(dataset, "nodeblock_1", internals.Controller, writer));
// process element blocks.
// now, if input is not coming for IOSS reader, then all blocks are simply
// treated as element blocks, there's no way for us to deduce otherwise.
// let's start by simply doing that.
for (unsigned int pidx = 0; pidx < dataset->GetNumberOfPartitionedDataSets(); ++pidx)
{
std::string bname = "block_" + std::to_string(pidx + 1);
if (auto info = dataset->GetMetaData(pidx))
{
if (info->Has(vtkCompositeDataSet::NAME()))
{
bname = info->Get(vtkCompositeDataSet::NAME());
}
}
// now create each type of GroupingEntity.
if (!isIOSS || elementBlockIndices.find(pidx) != elementBlockIndices.end())
{
try
{
internals.EntityGroups.emplace(Ioss::EntityType::ELEMENTBLOCK,
std::make_shared<vtkElementBlock>(
dataset->GetPartitionedDataSet(pidx), bname, internals.Controller, writer));
continue;
}
catch (std::runtime_error&)
{
// if isIOSS, raise error...perhaps?
break;
}
}
if (sideSetIndices.find(pidx) != sideSetIndices.end())
{
try
{
internals.EntityGroups.emplace(Ioss::EntityType::SIDESET,
std::make_shared<vtkSideSet>(
dataset->GetPartitionedDataSet(pidx), bname, internals.Controller, writer));
continue;
}
catch (std::runtime_error&)
{
break;
}
}
// nodesets are the most forgiving kind, so let's do them last.
if (nodeSetIndices.find(pidx) != nodeSetIndices.end())
{
try
{
internals.EntityGroups.emplace(Ioss::EntityType::NODESET,
std::make_shared<vtkNodeSet>(
dataset->GetPartitionedDataSet(pidx), bname, internals.Controller, writer));
continue;
}
catch (std::runtime_error&)
{
break;
}
}
vtkLogF(WARNING, "Skipping block '%s'. Unsure how classify it.", bname.c_str());
}
}
//----------------------------------------------------------------------------
vtkIOSSModel::~vtkIOSSModel() = default;
//----------------------------------------------------------------------------
void vtkIOSSModel::DefineModel(Ioss::Region& region) const
{
auto& internals = (*this->Internals);
region.begin_mode(Ioss::STATE_DEFINE_MODEL);
for (auto& entity : internals.EntityGroups)
{
entity.second->Define(region);
}
region.end_mode(Ioss::STATE_DEFINE_MODEL);
}
//----------------------------------------------------------------------------
void vtkIOSSModel::Model(Ioss::Region& region) const
{
auto& internals = (*this->Internals);
region.begin_mode(Ioss::STATE_MODEL);
for (auto& entity : internals.EntityGroups)
{
entity.second->Model(region);
}
region.end_mode(Ioss::STATE_MODEL);
}
//----------------------------------------------------------------------------
void vtkIOSSModel::DefineTransient(Ioss::Region& region) const
{
auto& internals = (*this->Internals);
region.begin_mode(Ioss::STATE_DEFINE_TRANSIENT);
for (auto& entity : internals.EntityGroups)
{
entity.second->DefineTransient(region);
}
region.end_mode(Ioss::STATE_DEFINE_TRANSIENT);
}
//----------------------------------------------------------------------------
void vtkIOSSModel::Transient(Ioss::Region& region, double time) const
{
auto& internals = (*this->Internals);
region.begin_mode(Ioss::STATE_TRANSIENT);
const int step = region.add_state(time);
region.begin_state(step);
for (auto& entity : internals.EntityGroups)
{
entity.second->Transient(region);
}
region.end_state(step);
region.end_mode(Ioss::STATE_TRANSIENT);
}
//----------------------------------------------------------------------------
std::string vtkIOSSModel::MD5() const
{
unsigned char digest[16];
char md5Hash[33];
vtksysMD5* md5 = vtksysMD5_New();
vtksysMD5_Initialize(md5);
const auto& internals = (*this->Internals);
size_t numberOfItems = internals.EntityGroups.size();
vtksysMD5_Append(
md5, reinterpret_cast<const unsigned char*>(&numberOfItems), static_cast<int>(sizeof(size_t)));
for (const auto& entity : internals.EntityGroups)
{
entity.second->AppendMD5(md5);
}
vtksysMD5_Finalize(md5, digest);
vtksysMD5_DigestToHex(digest, md5Hash);
vtksysMD5_Delete(md5);
md5Hash[32] = '\0';
return std::string(md5Hash);
}
VTK_ABI_NAMESPACE_END
|