forked from rustychris/ugrid_visit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathavtUGRIDFileFormat.C
2098 lines (1737 loc) · 63.5 KB
/
avtUGRIDFileFormat.C
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
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*****************************************************************************
*
* Copyright (c) 2000 - 2015, Lawrence Livermore National Security, LLC
* Produced at the Lawrence Livermore National Laboratory
* LLNL-CODE-442911
* All rights reserved.
*
* This file is part of VisIt. For details, see https://visit.llnl.gov/. The
* 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
* 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
* 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
* 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
* 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.
*
*****************************************************************************/
// ************************************************************************* //
// avtUGRIDFileFormat.C //
// ************************************************************************* //
#include <avtUGRIDFileFormat.h>
#include <FileFunctions.h>
#include <netcdf.h>
#include <DebugStream.h>
#include <string>
#include <algorithm> // sort, transform
#include <vector>
#include <vtkFloatArray.h>
#include <vtkRectilinearGrid.h>
#include <vtkStructuredGrid.h>
#include <vtkUnstructuredGrid.h>
#include <vtkPoints.h>
#include <vtkCellType.h>
#include <vtkCellArray.h>
#include <vtkCellData.h>
#include <vtkPointData.h>
#include <vtkSmartPointer.h>
#include <avtDatabaseMetaData.h>
#include <DBOptionsAttributes.h>
#include <Expression.h>
#include <InvalidVariableException.h>
#include <vtkCellDataToPointData.h>
#if defined(_WIN32)
#include <win32-regex.h>
#else
#include <regex.h>
#endif
using std::string;
// for some reason, there are two ways to read string attributes
// and it's difficult to predict which is correct.
string get_att_as_string(int ncid,int varid,const char *att_name) {
int retval;
char *att_data;
string result("");
if ( !(retval=nc_get_att_string(ncid, varid, att_name,&att_data)) ) {
result=att_data; // is that legal?
return result;
}
// debug5 << "nc_get_att_string failed, will trying get_att_text" << endl;
// is it possible that we have to test for text or string??
size_t att_len;
if ( nc_inq_attlen(ncid,varid,att_name,&att_len) ) {
debug5 << "nc_get_att_string _and_ attlen failed for " << att_name << endl;
return result;
}
char *buff=new char[att_len+1];
if ( nc_get_att_text(ncid,varid,att_name,buff ) ) {
delete[] buff;
return result;
}
buff[att_len]='\0';
result=buff;
delete[] buff;
return result;
}
std::vector<std::string> split(const std::string src, char c = ' ')
{
const char *str=src.c_str();
std::vector<std::string> result;
do {
const char *begin = str;
while(*str != c && *str)
str++;
result.push_back(string(begin, str));
} while (0 != *str++);
return result;
}
//////////---- MeshInfo ----//////////
MeshInfo::MeshInfo(int _ncid, int mesh_var,int z_var)
{
char var_name[NC_MAX_NAME];
char zvar_name[NC_MAX_NAME];
ncid=_ncid;
varid=mesh_var;
layer_z_var=z_var;
active_timestate=-1;
nc_inq_varname(ncid,varid,var_name);
if ( layer_z_var < 0 ) {
name=var_name;
layer_dim=-1;
} else {
nc_inq_varname(ncid,layer_z_var,zvar_name);
name=std::string(var_name) + "." + std::string(zvar_name);
}
debug1 << "Creating mesh info " << name << endl;
string cell_dim_name=get_att_as_string(ncid,varid,"face_dimension");
if ( nc_inq_dimid(ncid,cell_dim_name.c_str(),&cell_dim) ) {
debug1 << "Failed to read id of element dimension" << endl;
return;
}
if ( nc_inq_dimlen(ncid,cell_dim,&n_cells2d) ) {
debug1 << "Failed to read number of 2D cells" << endl;
return;
}
debug1 << "Read n_cells="<< n_cells2d << endl;
if(layer_z_var<0) {
n_cells3d=n_cells2d;
debug1 << "MeshInfo constructor: grid is 2D, so set n_cells3d=n_cells2d" << endl;
}
string node_coords=get_att_as_string(ncid,varid,"node_coordinates");
if( node_coords=="" ) return;
debug1 << "Node coordinate values " << node_coords << endl;
string node_x=node_coords.substr(0,node_coords.find_first_of(" "));
// debug1 << "node x variable '" << node_x << "'" << endl;
string node_y=node_coords.substr(node_coords.find_last_of(" ")+1,
node_coords.length());
// debug1 << "node y variable '" << node_y << "'" << endl;
if( nc_inq_varid(ncid,node_x.c_str(),&node_x_var) ) {
debug1 << "Failed to find node_x variable" << endl;
return;
}
if( nc_inq_varid(ncid,node_y.c_str(),&node_y_var) ) {
debug1 << "Failed to find node_y variable" << endl;
return;
}
// _assume_ that they have exactly one dimension.
nc_inq_vardimid(ncid,node_x_var,&node_dim);
nc_inq_dimlen(ncid,node_dim,&n_nodes);
debug1 << "Found " << n_nodes << " nodes" << endl;
}
vtkPoints *MeshInfo::GetNodes(void) {
float *xcoords=new float[n_nodes];
float *ycoords=new float[n_nodes];
if ( nc_get_var_float(ncid, node_x_var, xcoords) ) {
debug1 << "Failed to read x coordinate" << endl;
return NULL;
}
if ( nc_get_var_float(ncid, node_y_var, ycoords) ) {
debug1 << "Failed to read y coordinate" << endl;
return NULL;
}
debug1 << "Read coordinates" << endl;
vtkPoints *points = vtkPoints::New();
points->SetDataTypeToFloat();
points->SetNumberOfPoints(n_nodes);
float pnt[3];
for(int n=0;n<n_nodes;n++){
pnt[0]=xcoords[n];
pnt[1]=ycoords[n];
pnt[2]=0.0; // unused
points->SetPoint(n,pnt);
}
delete[] xcoords;
delete[] ycoords;
return points;
}
vtkDataSet *
MeshInfo::GetMesh(int timestate)
{
vtkUnstructuredGrid *surface=GetMesh2D(timestate);
debug1 << "GetMesh..." << endl;
if( layer_z_var < 0) {
return surface;
} else {
debug1 << "...ExtrudeTo3D" << endl;
vtkUnstructuredGrid *full=ExtrudeTo3D(timestate,surface);
// without GetMesh2D calling mesh->Register(), this
// crashes. But that was because it was being Deleted
// in multiple places.
surface->Delete(); // is this okay? seems to make it crash.
return full;
}
}
vtkUnstructuredGrid *
MeshInfo::GetMesh2D(int timestate)
{
// the others are built on top of the node mesh
vtkPoints *points = GetNodes();
vtkUnstructuredGrid *mesh=vtkUnstructuredGrid::New();
mesh->SetPoints(points);
points->Delete() ; // pretty sure this is correct...
mesh->Allocate();
// maybe I shouldn't do this?
// mesh->Register(NULL); // returning a pointer which owns itself
// read the node_face info, build up triangles/quads.
debug1 << "GetMesh: ugrid mesh name " << name << endl;
nc_type xtype;
string face_node=get_att_as_string(ncid,varid,"face_node_connectivity");
debug1 << "Face-Node connectivity " << face_node << endl;
int face_node_var;
if( nc_inq_varid(ncid,face_node.c_str(),&face_node_var) ) {
debug1 << "Failed to find face_node_connectivity variable" << endl;
return NULL;
}
int f_n_dims[2]; // _assume_ face_node_connectivity has two dimensions, [Nfaces,MaxNodePerFace]
nc_inq_vardimid(ncid,face_node_var,f_n_dims);
int face_node_start=0;
if ( nc_get_att_int(ncid,face_node_var,"start_index", &face_node_start) ) {
debug1 << "Failed to find start_index for face_node_connectivity - will assume "
<< face_node_start << endl;
}
int face_node_fill=-1;
if ( nc_get_att_int(ncid,face_node_var,"_FillValue", &face_node_fill) ) {
debug1 << "Failed to find fill value for face_node_connectivity - will assume "
<< face_node_fill << endl;
}
size_t max_node_per_face;
// assumes that face_node_var is [cells,nodes]
nc_inq_dimlen(ncid,f_n_dims[1],&max_node_per_face);
int *faces=new int[n_cells2d*max_node_per_face];
if ( nc_get_var_int(ncid, face_node_var, faces) ) {
debug1 << "Failed to read face_node_var" << endl;
return NULL;
}
debug1 << "UGRID: max node per face: " << max_node_per_face << endl;
// Load as 2D, then optionally extrude to 3D
vtkIdType *vertices=new vtkIdType[max_node_per_face];
for(int f=0;f<n_cells2d;f++) {
int n;
for(n=0;n<max_node_per_face;n++) {
if (faces[f*max_node_per_face+n] == face_node_fill )
break;
// last dimension varies fastest
// convert to zero-based index
// have to see if this is the right order
vertices[n] = faces[f*max_node_per_face + n] - face_node_start;
}
// This was failing on ERROR: bad cell type -- what fixed that?
switch ( n ) {
case 3:
// if ( f==0 ) {
// debug1 << "UGRID:GetMesh: inserting triangle cell, vertices="
// << vertices[0] << " " << vertices[1] << " " << vertices[2] << endl;
// }
mesh->InsertNextCell(VTK_TRIANGLE,n,vertices);
break;
case 4:
mesh->InsertNextCell(VTK_QUAD,n,vertices);
// debug1 << "UGRID: Trying to insert VTK_QUAD" << endl;
break;
default:
// debug1 << "UGRID: Trying to insert VTK_POLYGON" << endl;
mesh->InsertNextCell(VTK_POLYGON,n,vertices);
break;
}
}
delete[] vertices;
delete[] faces;
debug1 << "Returning 2D mesh" << endl;
return mesh;
}
/**
Dirty work of creating a prism with more than 6 nodes on top and bottom
Ordering of the points making up faces is in the sense of a positive
outward facing normal. i.e. a right-hand rule curling in the order of
nodes gives the outward normal. Equivalently, when viewed from outside
the volume, nodes are ordered CCW.
Assume that internally the nodes of a cell are stored in CCW order. So
the top face of the prism is already in the proper order.
**/
void
insertNPrism(vtkUnstructuredGrid *full_mesh,
int npoints2d,
vtkIdType *point_ids) {
// following http://www.vtk.org/Wiki/VTK/Examples/Cxx/GeometricObjects/Polyhedron
vtkSmartPointer<vtkCellArray> faces =
vtkSmartPointer<vtkCellArray>::New();
vtkIdType *face=new vtkIdType[npoints2d];
// create the top:
for(int i=0;i<npoints2d;i++) {
face[i]=point_ids[i]; // already proper order, I think.
}
faces->InsertNextCell(npoints2d, face);
for(int i=0;i<npoints2d;i++) {
// and the bottom - reverse the order
face[i]=point_ids[2*npoints2d - 1 - i]; // old: npoints2d+i
}
faces->InsertNextCell(npoints2d, face);
// and each side facet:
for(int facet=0;facet<npoints2d;facet++) {
face[3]=point_ids[facet];
face[2]=point_ids[(facet+1)%npoints2d];
face[1]=point_ids[npoints2d+(facet+1)%npoints2d];
face[0]=point_ids[npoints2d+facet];
faces->InsertNextCell(4,face);
}
full_mesh->InsertNextCell(VTK_POLYHEDRON, 2*npoints2d, point_ids,
2+npoints2d, faces->GetPointer());
delete[] face;
}
void
MeshInfo::activateTimestate(int timestate) {
// get some 3D mesh info for a given time step
if ( (active_timestate == timestate) ||
(layer_dim<0) )
return;
if ( cell_dim < 0 ) {
debug1 << "cell_dim not set - don't know how to set timestate for 3D, nodal field" << endl;
return;
}
n_cells3d=0; // to be incremented below
if(cell_kmin.size() != n_cells2d )
cell_kmin.resize(n_cells2d,-1);
if(cell_kmax.size() != n_cells2d )
cell_kmax.resize(n_cells2d,-1);
// for transcribed delwaq output, typically have
// volumes, which can be used to filter out dry segments.
// for DFM output, it's probably sigma level and we can assume
// all layers are active?
// older DELWAQ code, need to figure out how to support both.
// float *volumes=read_cell_z_full("volume",timestate);
// if ( !volumes ) return;
// for(int cell2d=0;cell2d<n_cells2d;cell2d++) {
// // cell_kmin from first non-zero volume
// int k;
// for(k=0;
// (k<n_layers) && (volumes[cell2d*n_layers+k] <= 0);
// k++) ;
//
// cell_kmin[cell2d]=k;
// for(; (k<n_layers) && ( volumes[cell2d*n_layers+k]==volumes[cell2d*n_layers+k] );
// k++) ;
// cell_kmax[cell2d]=k;
// ncells_3d += (cell_kmax[cell2d] - cell_kmin[cell2d]);
// }
// new DFM code - sigma layers, so they're all full:
for(int i=0;i<n_cells2d;i++){
cell_kmax[i]=n_layers;
cell_kmin[i]=0;
n_cells3d += (cell_kmax[i] - cell_kmin[i]);
}
debug1 << "activateTimestate timestate=" << timestate
<< " cell_kmax[0]=" << cell_kmax[0]
<< " n_cells3d=" << n_cells3d << endl;
active_timestate=timestate;
}
vtkDataArray *MeshInfo::ZoneToNode2D(vtkDataArray *zonal,vtkUnstructuredGrid *ds)
{
// This is leaking
// Taken from avtExpressionFilter.C, just the useful bits without
// mamby pamby error checking.
ds->GetCellData()->SetScalars(zonal);
vtkCellDataToPointData *cd2pd = vtkCellDataToPointData::New();
cd2pd->SetInputData(ds);
// I think Update() is where the leak occurs, possibly leaking b/c
// I was calling outv->Register(NULL) below?
cd2pd->Update();
vtkDataSet *ds3 = cd2pd->GetOutput();
vtkDataArray *outv = ds3->GetPointData()->GetScalars();
// This appears to be correct, but note that the caller must
// Delete() the returned data.
outv->Register(NULL);
cd2pd->Delete();
return outv;
}
/* set_layer_bounds
* based on UGRID layer coordinates and optional layer bounds,
* populate elevations for top/bottom coordinates. does not
* apply sigma transform.
*/
void
MeshInfo::set_layer_bounds(std::string z_std_name,
std::vector<float> &layer_bottom,
std::vector<float> &layer_top)
{
// and the bounds variable? no guarantees that this exists.
int bounds_var;
string bounds_name=get_att_as_string(ncid,layer_z_var,"bounds");
if ( bounds_name == "" ) {
debug1 << "No bounds attribute" << endl;
bounds_var=-1;
} else {
if( nc_inq_varid(ncid,bounds_name.c_str(),&bounds_var) ) {
debug1 << "Failed to find bounds variable" << endl;
bounds_var=-1;
}
debug5 << "Found vertical bounds variable" << endl;
}
// for now, assume one set of z coordinates for the whole grid
// (for z layers, we're ignoring partial layers)
// this is already implicitly assumed by looking only for z coordinates with
// a single dimension.
layer_bottom.resize(n_layers);
layer_top.resize(n_layers);
if ( bounds_var>= 0) {
float *layer_bounds=new float[2*n_layers];
if ( nc_get_var_float(ncid,bounds_var,layer_bounds) ) {
debug1 << "Failed to read layer bounds" << endl;
bounds_var=-1; // fall through to next section
}
for(int i=0;i<n_layers;i++) {
layer_bottom[i]=layer_bounds[2*i];
layer_top[i]=layer_bounds[2*i+1];
}
delete[] layer_bounds;
}
if ( bounds_var<0 ) {
// read layer centers, extrapolate to layer bounds
float *layer_centers=new float[n_layers];
if ( nc_get_var_float(ncid,layer_z_var,layer_centers) ) {
debug1 << "Failed to read layer_z_var" << endl;
debug1 << "Fabricating!" << endl;
for(int i=0;i<n_layers;i++) {
layer_centers[i]=(float)(i+0.5) / (float)n_layers;
}
}
// Special DFlowFM workaround - layer coordinates are
// incorrect after first output, at least in r50237
if( fabs(layer_centers[0]) > 100000 ) {
debug1 << "layer coordinate looks corrupted. Will fabricate." << endl;
for(int i=0;i<n_layers;i++) {
layer_centers[i]=(float)(i+0.5) / (float)n_layers;
}
}
if ( n_layers==1 ) {
if ( z_std_name=="ocean_zlevel_coordinate" ) {
// total punt - could get smarter and look for
// eta and bedlevel.
layer_bottom[0]=layer_centers[0]-0.5;
layer_top[0]=layer_centers[0]+0.5;
} else {
// reasonable guess for sigma coordinates
layer_bottom[0]=0;
layer_top[0]=1;
}
} else {
for(int k=0;k<n_layers;k++) {
debug1 << "k = " << k << " of n_layers = " << n_layers << endl;
// Set the lower bound:
if (k==0) {
if( (z_std_name=="ocean_zlevel_coordinate") ) {
layer_bottom[k]=layer_centers[0] - 0.5*(layer_centers[1]-layer_centers[0]);
} else {
layer_bottom[k]=0; // may need to adjust based on sign conventions.
}
} else {
// copy from previous layer
layer_bottom[k]=layer_top[k-1];
}
// and the top of the layer
if (k==n_layers-1) {
if( (z_std_name=="ocean_zlevel_coordinate") ) {
layer_top[k]=layer_bottom[k] + (layer_centers[k]-layer_centers[k-1]);
} else {
layer_top[k]=1; // may need to adjust based on sign conventions.
}
} else {
layer_top[k]=0.5*(layer_centers[k]+layer_centers[k+1]);
}
debug1 << "Layer bounds: " << layer_bottom[k] << " to " << layer_top[k] << endl;
}
}
delete[] layer_centers;
}
}
vtkUnstructuredGrid *
MeshInfo::ExtrudeTo3D(int timestate,
vtkUnstructuredGrid *surface)
{
vtkDataArray *bedlevel=NULL;
vtkDataArray *eta=NULL;
////// Now basically extrude the surface mesh to prisms
// bounded by the cell_divisions elevations
activateTimestate(timestate);
// the new points
// copy the z=0 points from the flat surface, and then repeat
// for each z-value
int n_surf_points = surface->GetNumberOfPoints();
int offset;
// for z-grid:
// have a vertical dimension - in the current file, nFlowMesh_layers
// hopefully that has a bounds attribute, which points to a variable
// with dimensions nFlowMesh_layers,2, giving top and bottom elevation
// of the z-layers.
// so far we only support layer_z_var having a single dimension.
int layer_var_ndim=-1;
nc_inq_varndims(ncid,layer_z_var,&layer_var_ndim);
if ( layer_var_ndim != 1 ) {
debug1 << "Whoa - layer_var_ndim must be 1, but it was " << layer_var_ndim << endl;
return NULL;
}
// z-coordinate or sigma terrain-following?
std::string z_std_name=get_att_as_string(ncid,layer_z_var,"standard_name");
if ( z_std_name == "" ) {
debug1 << "No standard name on z coordinate variable. Can't tell sigma vs. z" << endl;
return NULL;
}
if ( z_std_name=="ocean_sigma_coordinate" ) {
debug1<< "Vertical coordinate indicates sigma coordinates" << endl;
// which variables define the layers?
std::string formula=get_att_as_string(ncid,layer_z_var,"formula_terms");
if ( formula=="" ) {
debug1 << "Sigma coordinate, but no formula_terms" << endl;
sigma_eta=sigma_bedlevel="";
} else {
// something like:
// LayCoord_cc:formula_terms = "sigma: LayCoord_cc eta: s1 bedlevel: flowelem_bl" ;
std::vector<std::string> tokens = split(formula);
for (int i=0;i<tokens.size();i++) {
if( tokens[i] == "eta:" ) {
i++;
sigma_eta=tokens[i];
} else if ( tokens[i]=="bedlevel:" ) {
i++;
sigma_bedlevel=tokens[i];
} else if ( tokens[i]=="sigma:" ) {
i++;
sigma_sigma=tokens[i];
} else {
debug1 << "sigma formula terms not understood: " << tokens[i] << endl;
}
}
debug1 << "Sigma formula terms, sigma is " << sigma_sigma
<< ", eta is " << sigma_eta
<< ", and bedlevel is " << sigma_bedlevel << endl;
if ( (sigma_eta!="") && (sigma_bedlevel!="") ) {
bedlevel=parent->GetVar(timestate,sigma_bedlevel.c_str());
eta=parent->GetVar(timestate,sigma_eta.c_str());
// sigma_sigma should aleady be loaded as layer_centers, based
// on layer_z_var
debug1 << "Fetched values for sigma formula terms" << endl;
// going out on a limb here --
vtkDataArray *eta_node=ZoneToNode2D(eta,surface);
vtkDataArray *bed_node=ZoneToNode2D(bedlevel,surface);
eta->Delete();
bedlevel->Delete();
eta=eta_node;
bedlevel=bed_node;
}
}
} else if (z_std_name=="ocean_zlevel_coordinate" ) {
debug1<< "Vertical coordinate indicates z-level coordinates" << endl;
}
//----- Extract vertical coordinate bounds -----
std::vector<float> layer_bottom;
std::vector<float> layer_top;
set_layer_bounds(z_std_name,layer_bottom,layer_top);
//----------- Create points ---------
vtkPoints *all_points = vtkPoints::New();
// Here, add +1 to n_layers because 10 layers have 11 unique
// node elevations
all_points->SetNumberOfPoints( (n_layers+1)*n_surf_points );
float *ap_data = (float*)all_points->GetVoidPointer(0);
double *surf_point;
float *a_point;
for(int surf_point_id=0;surf_point_id<n_surf_points;surf_point_id++) {
surf_point = surface->GetPoint(surf_point_id);
for(int k=0;k<n_layers+1;k++){
// pointer to the point being defined
a_point = ap_data + 3*(surf_point_id+k*n_surf_points);
a_point[0] = surf_point[0];
a_point[1] = surf_point[1];
// assumes that bounds are continuous - bottom of one cell same
// as top of the next
if(k==0) {
a_point[2] = layer_bottom[0];
} else {
a_point[2] = layer_top[k-1];
}
// apply the sigma transformation
if ( (eta != NULL) && (bedlevel != NULL) ) {
double z_bed=bedlevel->GetComponent(surf_point_id,0);
double z_surf=eta->GetComponent(surf_point_id,0);
a_point[2]= a_point[2]*(z_surf - z_bed) + z_bed;
}
}
}
debug1 << "Done creating 3D points" << endl;
vtkUnstructuredGrid *full_mesh = vtkUnstructuredGrid::New();
// Copy the cell structure, extruding through depth
vtkIdType surf_cell_npoints;
vtkIdType *surf_cell_point_ids;
// 2*MAX_SIDES: top and bottom points, up to a hexagonal prism, or larger
vtkIdType new_cell_point_ids[2*MAX_SIDES];
// full_cell2valid provides a mapping of expected cell index to
// actual cell index;
// settings['stairstep']=0 -> The bottom of the bottom valid cell is defined
// by the voronoi center depth
// =1 -> Round to next z-level (deeper)
// It's going to be a real pain to do partial depths, because it
// upsets the mapping of points to different depths (bottom points
// can't be reused, and the numbering gets all funky)
// Fetch the depth values in order to evaluate the bottom cells
// this is a little different for the ugrid stuff.
// probably have node-centered depth
// what's the CF convention say about this?
// could create the full mesh?
// probably it is supposed to be a [time,cell,layer] variable
// in the netcdf.
// there's the further consideration that really we want bounds, too,
// so it would be [time,cell,layer,d2]
// regardless, this needs to be time-dependent.
// the most immediate question is how to figure out how many
// cells are in each water column.
// vtkFloatArray *cell_depths =(vtkFloatArray *)GetVarBathymetry();
// float *bath_data = cell_depths->GetPointer(0);
full_mesh->Allocate();
int expected_cell_id=0;
int real_cell_id=0;
for(int surf_cell_id=0 ;
surf_cell_id<n_cells2d ;
surf_cell_id++ ) {
surface->GetCellPoints(surf_cell_id,
surf_cell_npoints,surf_cell_point_ids);
if( surf_cell_npoints > MAX_SIDES ) {
debug1 << "Cell has too many points - truncating! " << surf_cell_npoints << " to " << MAX_SIDES << endl;
surf_cell_npoints=MAX_SIDES;
}
int k; // index into vertical cells
if( surf_cell_id == 0 ) {
debug1 << " surf_cell_id=" << surf_cell_id
<< " cell_kmin=" << cell_kmin[surf_cell_id]
<< " cell_kmax=" << cell_kmax[surf_cell_id]
<< endl;
}
for(k=cell_kmin[surf_cell_id];
k<cell_kmax[surf_cell_id];
k++) {
/// The Visit manual shows this as 0-1-2 being one triangular
// face with outward-facing normal, and 3-4-5 being the other
// end with inward-facing normal (where the normal is defined
// as outward on CCW ordered vertices)
// if this really angers Visit, may have to test ordering here
// and reverse top/bottom if vertices are in wrong order.
// but the general polyhedron wants entirely outward facing
// normals.
// and the illustration of thw VTK_HEXAHEDRON
// shows 0,1,2,3 having an inward facing normal.
// at some point we might add new bottom points to allow
// for partial cell depths, but for now just do stair-stepping
// tricky loop modification to order the nodes in the right way
// for the different cell types.
if( surf_cell_npoints==3 || surf_cell_npoints>6 )
offset=0;
else
offset=surf_cell_npoints;
// the upper level:
for (int vertex=0;vertex<surf_cell_npoints;vertex++) {
new_cell_point_ids[vertex+offset] = k*n_surf_points + surf_cell_point_ids[vertex];
}
offset=surf_cell_npoints-offset;
// the lower level:
for (int vertex=0;vertex<surf_cell_npoints;vertex++) {
new_cell_point_ids[vertex+offset] = (k+1)*n_surf_points +
surf_cell_point_ids[vertex];
}
// Insert the cell into the mesh.
if ( surf_cell_npoints==3 ) {
full_mesh->InsertNextCell(VTK_WEDGE, 6, new_cell_point_ids);
} else if (surf_cell_npoints==4 ) {
full_mesh->InsertNextCell(VTK_HEXAHEDRON, 8, new_cell_point_ids);
} else if (surf_cell_npoints==5 ) {
full_mesh->InsertNextCell(VTK_PENTAGONAL_PRISM, 10, new_cell_point_ids);
} else if (surf_cell_npoints==6 ) {
full_mesh->InsertNextCell(VTK_HEXAGONAL_PRISM, 12, new_cell_point_ids);
} else {
// debug1 << "Surface cell has " << surf_cell_npoints << " points, which is simply too many" << endl;
insertNPrism(full_mesh,surf_cell_npoints,new_cell_point_ids);
// full_mesh->InsertNextCell(VTK_HEXAGONAL_PRISM, 12, new_cell_point_ids);
}
// update the mapping of cell ids:
// the order of the data file is still a bit unclear, so hopefully
// this is the same as in the data file...
// as long as cell_kmin,cell_kmax are correct, there's not a compelling
// reason to additionally store this mapping, afaict.
// int expected_id = surf_cell_id + k*n_cells2d;
// full_cell2valid[ expected_id ] = real_cell_id;
// real_cell_id++;
}
}
debug1 << "Done constructing 3D cells" << endl;
// hopefully it's okay to set the points here, *after* defining the cells
full_mesh->SetPoints(all_points);
all_points->Delete();
// surface->Delete(); // caller does this now.
// this causes a leak.
// full_mesh->Register(NULL);
// this is the counterpart to outv->Register() call in ZoneToNode2D, and
// successfully cleans up the leak without introducing invalid reads
if(eta!=NULL) eta->Delete();
if(bedlevel!=NULL) bedlevel->Delete();
debug1 << "Return 3D mesh" << endl;
return full_mesh;
}
//////////---- VarInfo ----//////////
VarInfo::VarInfo(std::string n)
: name(n)
{
init();
}
VarInfo::VarInfo(void)
{
init();
}
void
VarInfo::init(void)
{
time_dimi=cell_dimi=layer_dimi=node_dimi=-1;
var_id=-1;
ncid=-1;
}
VarInfo::VarInfo(const VarInfo &a)
{
// this really shouldn't be necessary, but it's acting up...
name=a.name;
mesh_name=a.mesh_name;
time_dimi=a.time_dimi;
cell_dimi=a.cell_dimi;
layer_dimi=a.layer_dimi;
node_dimi=a.node_dimi;
time_dim=a.time_dim;
var_id=a.var_id;
ncid=a.ncid;
}
// ****************************************************************************
// Method: avtUGRIDSingle constructor
//
// Programmer: rusty -- generated by xml2avt
// Creation: Sat Mar 5 18:27:45 PST 2016
//
// ****************************************************************************
avtUGRIDSingle::avtUGRIDSingle(const char *filename)
: avtMTSDFileFormat(&filename, 1)
{
// INITIALIZE DATA MEMBERS
int retval;
if ( nc_open(filename, NC_NOWRITE, &ncid) ) {
debug1 << "Failed to open " << filename << endl;
return;
}
debug1 << "UGRID: opened " << filename << endl;
if ( nc_inq_dimid(ncid,"time", &time_dim) ) {
debug1 << "Failed to read time dimensions" << endl;
}
if ( nc_inq_varid(ncid, "time", &time_var) ) {
debug1 << "Couldn't read time variable id" << endl;
return;
}
cell_kmin=cell_kmax=NULL;
active_timestate=-1;
int nvars;
if ( nc_inq_nvars(ncid,&nvars) ) {
debug1 << "Failed. How could nc_inq_nvars fail??" << endl;
return;
}
// Scan the variables, making a note of any cf_role='mesh_topology'
// variables.
default_ugrid_mesh=""; // defaults to first found
for(int varid=0;varid<nvars;varid++) {
string cf_role=get_att_as_string(ncid,varid,"cf_role");
if( cf_role=="mesh_topology" ) {
MeshInfo minfo(ncid,varid);
if(default_ugrid_mesh=="") {
default_ugrid_mesh=minfo.name;
}
minfo.parent=this;
mesh_table[minfo.name]=minfo;
}
}
if ( default_ugrid_mesh=="" ) {
debug1 << "Couldn't find any mesh variables with cf_role=='mesh_topology'" << endl;
return;
}
initialize_metadata();
}
avtUGRIDSingle::~avtUGRIDSingle() {
delete[] cell_kmin;
delete[] cell_kmax;
}
string avtUGRIDSingle::var_mesh2d(std::string varname) {
int varid;
nc_inq_varid(ncid,varname.c_str(),&varid);
return var_mesh2d(varid);
}
string avtUGRIDSingle::var_mesh2d(int varid) {
// any reason not to use this same convenience util?
string result=get_att_as_string(ncid,varid,"mesh");
if( result=="" ) {
result=default_ugrid_mesh;
debug1 << "No mesh attribute - using default" << endl;
} else if( result != default_ugrid_mesh ) {
debug1 << "Found another ugrid mesh. Hold on tight." << endl;
}
return result;
}
// ****************************************************************************
// Method: avtEMSTDFileFormat::GetNTimesteps
//
// Purpose:
// Tells the rest of the code how many timesteps there are in this file.
//
// Programmer: rusty -- generated by xml2avt
// Creation: Sat Mar 5 18:27:45 PST 2016
//
// ****************************************************************************
int
avtUGRIDSingle::GetNTimesteps(void)
{
size_t length;