Debian Codegraph @

src/thirdparty/PoissonRecon/EDTInHeat.cpp

raw
1 /*
2 Copyright (c) 2016, Michael Kazhdan
3 All rights reserved.
4
5 Redistribution and use in source and binary forms, with or without modification,
6 are permitted provided that the following conditions are met:
7
8 Redistributions of source code must retain the above copyright notice, this list of
9 conditions and the following disclaimer. Redistributions in binary form must reproduce
10 the above copyright notice, this list of conditions and the following disclaimer
11 in the documentation and/or other materials provided with the distribution.
12
13 Neither the name of the Johns Hopkins University nor the names of its contributors
14 may be used to endorse or promote products derived from this software without specific
15 prior written permission.
16
17 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
18 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES
19 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
20 SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
21 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
22 TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
23 BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
25 ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
26 DAMAGE.
27 */
28
29 #include "PreProcessor.h"
30
31 #undef USE_DOUBLE // If enabled, double-precesion is used
32 #define DEFAULT_DIMENSION 3 // The dimension of the system
33 #define DEFAULT_FEM_DEGREE 1 // The default finite-element degree
34
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <math.h>
38 #include <float.h>
39 #include <functional>
40 #include "MyMiscellany.h"
41 #include "CmdLineParser.h"
42 #include "PPolynomial.h"
43 #include "FEMTree.h"
44 #include "Ply.h"
45 #include "VertexFactory.h"
46
47 using namespace PoissonRecon;
48
49 CmdLineParameter< char* >
50 In( "in" ) ,
51 Out( "out" ) ,
52 InXForm( "inXForm" ) ,
53 OutXForm( "outXForm" );
54
55 CmdLineReadable
56 Performance( "performance" ) ,
57 ShowResidual( "showResidual" ) ,
58 ExactInterpolation( "exact" ) ,
59 Verbose( "verbose" );
60
61 CmdLineParameter< int >
62 #ifndef FAST_COMPILE
63 Degree( "degree" , DEFAULT_FEM_DEGREE ) ,
64 #endif // !FAST_COMPILE
65 GSIterations( "iters" , 8 ) ,
66 Depth( "depth" , 8 ) ,
67 FullDepth( "fullDepth" , 5 ) ,
68 BaseDepth( "baseDepth" ) ,
69 BaseVCycles( "baseVCycles" , 1 ) ,
70 MaxMemoryGB( "maxMemory" , 0 ) ,
71 ParallelType( "parallel" , 0 ) ,
72 ScheduleType( "schedule" , (int)ThreadPool::Schedule ) ,
73 ThreadChunkSize( "chunkSize" , (int)ThreadPool::ChunkSize );
74
75 CmdLineParameter< float >
76 Scale( "scale" , 2.f ) ,
77 CGSolverAccuracy( "cgAccuracy" , float(1e-3) ) ,
78 DiffusionTime( "diffusion" , 0.0005f ) ,
79 WeightScale( "wScl" , 0.125f ) ,
80 WeightExponent( "wExp" , 6.f ) ,
81 ValueWeight( "valueWeight" , 1e-2f );
82
83 CmdLineReadable* params[] =
84 {
85 #ifndef FAST_COMPILE
86 &Degree ,
87 #endif // !FAST_COMPILE
88 &In , &Out , &Depth , &InXForm , &OutXForm ,
89 &Scale , &Verbose , &CGSolverAccuracy ,
90 &ShowResidual ,
91 &ValueWeight , &DiffusionTime ,
92 &FullDepth ,
93 &GSIterations ,
94 &WeightScale , &WeightExponent ,
95 &BaseDepth , &BaseVCycles ,
96 &Performance ,
97 &ExactInterpolation ,
98 &MaxMemoryGB ,
99 &ParallelType ,
100 &ScheduleType ,
101 &ThreadChunkSize ,
102 NULL
103 };
104
105
106 void ShowUsage( char* ex )
107 {
108 printf( "Usage: %s\n" , ex );
109 printf( "\t --%s <input mesh>\n" , In.name );
110 printf( "\t[--%s <output EDT solution>]\n" , Out.name );
111 #ifndef FAST_COMPILE
112 printf( "\t[--%s <b-spline degree>=%d]\n" , Degree.name , Degree.value );
113 #endif // !FAST_COMPILE
114 printf( "\t[--%s <maximum reconstruction depth>=%d]\n" , Depth.name , Depth.value );
115 printf( "\t[--%s <full depth>=%d]\n" , FullDepth.name , FullDepth.value );
116 printf( "\t[--%s <coarse MG solver depth>]\n" , BaseDepth.name );
117 printf( "\t[--%s <coarse MG solver v-cycles>=%d]\n" , BaseVCycles.name , BaseVCycles.value );
118 printf( "\t[--%s <scale factor>=%f]\n" , Scale.name , Scale.value );
119 printf( "\t[--%s <diffusion time>=%.3e]\n" , DiffusionTime.name , DiffusionTime.value );
120 printf( "\t[--%s <value interpolation weight>=%.3e]\n" , ValueWeight.name , ValueWeight.value );
121 printf( "\t[--%s <iterations>=%d]\n" , GSIterations.name , GSIterations.value );
122 printf( "\t[--%s]\n" , ExactInterpolation.name );
123 printf( "\t[--%s <cg solver accuracy>=%g]\n" , CGSolverAccuracy.name , CGSolverAccuracy.value );
124 printf( "\t[--%s <successive under-relaxation weight>=%f]\n" , WeightScale.name , WeightScale.value );
125 printf( "\t[--%s <successive under-relaxation exponent>=%f]\n" , WeightExponent.name , WeightExponent.value );
126 printf( "\t[--%s <maximum memory (in GB)>=%d]\n" , MaxMemoryGB.name , MaxMemoryGB.value );
127 printf( "\t[--%s]\n" , Performance.name );
128 printf( "\t[--%s]\n" , Verbose.name );
129 }
130
131 template< class Real , unsigned int Dim >
132 XForm< Real , Dim+1 > GetPointXForm( const std::vector< Point< Real , Dim > >& vertices , Real scaleFactor )
133 {
134 Point< Real , Dim > min , max;
135 min = max = vertices[0];
136 for( int i=0 ; i<vertices.size() ; i++ ) for( int j=0 ; j<Dim ; j++ ) min[j] = std::min< Real >( min[j] , vertices[i][j] ) , max[j] = std::max< Real >( max[j] , vertices[i][j] );
137 Point< Real , Dim > center = ( max + min ) / 2;
138
139 Real scale = max[0]-min[0];
140 for( int d=1 ; d<Dim ; d++ ) scale = std::max< Real >( scale , max[d]-min[d] );
141 scale *= scaleFactor;
142 for( int i=0 ; i<Dim ; i++ ) center[i] -= scale/2;
143 XForm< Real , Dim+1 > tXForm = XForm< Real , Dim+1 >::Identity() , sXForm = XForm< Real , Dim+1 >::Identity();
144 for( int i=0 ; i<Dim ; i++ ) sXForm(i,i) = (Real)(1./scale ) , tXForm(Dim,i) = -center[i];
145 return sXForm * tXForm;
146 }
147
148 template< class Real , unsigned int Dim >
149 void Print( const XForm< Real , Dim >& xForm )
150 {
151 for( int j=0 ; j<Dim ; j++ )
152 {
153 for( int i=0 ; i<Dim ; i++ ) printf( " %f" , xForm(i,j) );
154 printf( "\n" );
155 }
156 }
157
158 template< unsigned int Dim , class Real >
159 struct ConstraintDual
160 {
161 CumulativeDerivativeValues< Real , Dim , 0 > operator()( const Point< Real , Dim >& p ) const { return CumulativeDerivativeValues< Real , Dim , 0 >( ); }
162 };
163 template< unsigned int Dim , class Real >
164 struct SystemDual
165 {
166 Real weight;
167 SystemDual( Real w ) : weight(w){ }
168 CumulativeDerivativeValues< Real , Dim , 0 > operator()( Point< Real , Dim > p , const CumulativeDerivativeValues< Real , Dim , 0 >& dValues ) const { return dValues*weight; }
169 CumulativeDerivativeValues< double , Dim , 0 > operator()( Point< Real , Dim > p , const CumulativeDerivativeValues< double , Dim , 0 >& dValues ) const { return dValues * weight; };
170 };
171 template< unsigned int Dim >
172 struct SystemDual< Dim , double >
173 {
174 typedef double Real;
175 Real weight;
176 SystemDual( Real w ) : weight(w){ }
177 CumulativeDerivativeValues< Real , Dim , 0 > operator()( Point< Real , Dim > p , const CumulativeDerivativeValues< Real , Dim , 0 >& dValues ) const { return dValues*weight; }
178 };
179
180 template< unsigned int Dim , class Real , unsigned int FEMSig >
181 void _Execute( int argc , char* argv[] )
182 {
183 ThreadPool::ParallelizationType= (ThreadPool::ParallelType)ParallelType.value;
184 static const unsigned int Degree = FEMSignature< FEMSig >::Degree;
185 typedef typename FEMTree< Dim , Real >::template InterpolationInfo< Real , 0 > InterpolationInfo;
186 typedef typename FEMTree< Dim , Real >::FEMTreeNode FEMTreeNode;
187 std::vector< std::string > comments;
188 if( Verbose.set )
189 {
190 std::cout << "*****************************************" << std::endl;
191 std::cout << "*****************************************" << std::endl;
192 std::cout << "** Running EDT in Heat (Version " << ADAPTIVE_SOLVERS_VERSION ") **" << std::endl;
193 std::cout << "*****************************************" << std::endl;
194 std::cout << "*****************************************" << std::endl;
195 }
196
197 XForm< Real , Dim+1 > modelToUnitCube , unitCubeToModel;
198 if( InXForm.set )
199 {
200 FILE* fp = fopen( InXForm.value , "r" );
201 if( !fp )
202 {
203 MK_WARN( "Could not open file for reading x-form: " , InXForm.value );
204 modelToUnitCube = XForm< Real , Dim+1 >::Identity();
205 }
206 else
207 {
208 for( int i=0 ; i<4 ; i++ ) for( int j=0 ; j<4 ; j++ )
209 {
210 float f;
211 if( fscanf( fp , " %f " , &f )!=1 ) MK_THROW( "Failed to read xform" );
212 modelToUnitCube(i,j) = (Real)f;
213 }
214 fclose( fp );
215 }
216 }
217 else modelToUnitCube = XForm< Real , Dim+1 >::Identity();
218
219 char str[1024];
220 for( int i=0 ; params[i] ; i++ )
221 if( params[i]->set )
222 {
223 params[i]->writeValue( str );
224 if( Verbose.set )
225 {
226 if( strlen( str ) ) std::cout << "\t--" << params[i]->name << " " << str << std::endl;
227 else std::cout << "\t--" << params[i]->name << std::endl;
228 }
229 }
230
231 double startTime = Time();
232
233 FEMTree< Dim , Real > tree( MEMORY_ALLOCATOR_BLOCK_SIZE );
234 Profiler profiler(20);
235 if( !In.set )
236 {
237 ShowUsage( argv[0] );
238 return;
239 }
240
241 std::vector< NodeAndPointSample< Dim , Real > > geometrySamples;
242 std::vector< NodeAndPointSample< Dim , Real > > heatPositions;
243 std::vector< Point< Real , Dim > > heatGradients;
244
245 // Read the mesh into the tree
246 {
247 profiler.reset();
248 // Read the mesh
249 std::vector< Point< Real , Dim > > vertices;
250 std::vector< TriangleIndex< node_index_type > > triangles;
251 {
252 int file_type;
253 std::vector< std::vector< int > > _polygons;
254 std::vector< std::string > comments;
255 PLY::ReadPolygons( In.value , VertexFactory::PositionFactory< Real , Dim >() , vertices , _polygons , file_type , comments );
256 triangles.resize( _polygons.size() );
257 for( int i=0 ; i<triangles.size() ; i++ ) for( int j=0 ; j<Dim ; j++ ) triangles[i][j] = _polygons[i][j];
258 }
259 for( int i=0 ; i<vertices.size() ; i++ ) vertices[i] = modelToUnitCube * vertices[i];
260 XForm< Real , Dim+1 > _modelToUnitCube = GetPointXForm< Real , Dim >( vertices , (Real)Scale.value );
261 for( int i=0 ; i<vertices.size() ; i++ ) vertices[i] = _modelToUnitCube * vertices[i];
262 modelToUnitCube = _modelToUnitCube * modelToUnitCube;
263 FEMTreeInitializer< Dim , Real >::Initialize( tree.spaceRoot() , vertices , triangles , Depth.value , geometrySamples , tree.nodeAllocators , tree.initializer() );
264 unitCubeToModel = modelToUnitCube.inverse();
265 if( OutXForm.set )
266 {
267 FILE* fp = fopen( OutXForm.value , "w" );
268 if( !fp ) MK_WARN( "Could not open file for writing x-form: %s" );
269 else
270 {
271 for( int i=0 ; i<Dim+1 ; i++ )
272 {
273 for( int j=0 ; j<Dim+1 ; j++ ) fprintf( fp , " %f" , (float)unitCubeToModel(i,j) );
274 fprintf( fp , "\n" );
275 }
276 fclose( fp );
277 }
278 }
279
280 double area = 0;
281 std::vector< double > areas( ThreadPool::NumThreads() , 0 );
282 ThreadPool::ParallelFor( 0 , triangles.size() , [&]( unsigned int thread , size_t i )
283 {
284 Simplex< Real , Dim , Dim-1 > s;
285 for( int k=0 ; k<Dim ; k++ ) for( int j=0 ; j<Dim ; j++ ) s[k][j] = vertices[ triangles[i][k] ][j];
286 Real a2 = s.squareMeasure();
287 if( a2>0 ) areas[thread] += sqrt(a2) / 2;
288 }
289 );
290 for( unsigned int t=0 ; t<ThreadPool::NumThreads() ; t++ ) area += areas[t];
291 if( Verbose.set )
292 {
293 std::cout << "Input Vertices / Triangle / Samples / Area: " << vertices.size() << " / " << triangles.size() << " / " << geometrySamples.size() << " / " << area << std::endl;
294 std::cout << "# Read input into tree: " << profiler << std::endl;
295 }
296
297 }
298
299 // Thicken the tree around the mesh
300 {
301 profiler.reset();
302 FEMTreeNode** nodes = new FEMTreeNode*[ geometrySamples.size() ];
303 for( int i=0 ; i<geometrySamples.size() ; i++ ) nodes[i] = geometrySamples[i].node;
304 tree.template processNeighbors< Degree , true >( nodes , (int)geometrySamples.size() , std::make_tuple() );
305 if( Verbose.set ) std::cout << "# Thickened tree: " << profiler << std::endl;
306 delete[] nodes;
307 }
308
309 InterpolationInfo *valueInfo = NULL;
310 if( ValueWeight.value>0 )
311 {
312 profiler.reset();
313 if( ExactInterpolation.set ) valueInfo = FEMTree< Dim , Real >::template InitializeExactPointInterpolationInfo< Real , 0 >( tree , geometrySamples , ConstraintDual< Dim , Real >() , SystemDual< Dim , Real >( std::max< Real >( 0 , (Real)ValueWeight.value ) ) , true , false );
314 else valueInfo = FEMTree< Dim , Real >::template InitializeApproximatePointInterpolationInfo< Real , 0 >( tree , geometrySamples , ConstraintDual< Dim , Real >() , SystemDual< Dim , Real >( std::max< Real >( 0 , (Real)ValueWeight.value ) ) , true , Depth.value , 0 );
315 if( Verbose.set ) std::cout << "#Initialized point interpolation constraints: " << profiler << std::endl;
316 }
317
318 // Finalize the topology of the tree
319 {
320 profiler.reset();
321
322 auto addNodeFunctor = [&]( int d , const int off[Dim] ){ return d<=FullDepth.value; };
323 tree.template finalizeForMultigrid< Degree , Degree >( BaseDepth.value , addNodeFunctor , typename FEMTree< Dim , Real >::TrivialHasDataFunctor() , std::make_tuple( valueInfo ) );
324
325 if( Verbose.set ) std::cout << "# Finalized tree: " << profiler << std::endl;
326 }
327
328 if( Verbose.set )
329 {
330 std::cout << "All Nodes / Active Nodes / Ghost Nodes: " << tree.allNodes() << " / " << tree.activeNodes() << " / " << tree.ghostNodes() << std::endl;
331 std::cout << "Memory Usage: " << float( MemoryInfo::Usage())/(1<<20) << " MB" << std::endl;
332 }
333
334 SparseNodeData< Point< Real , Dim+1 > , IsotropicUIntPack< Dim , FEMTrivialSignature > > leafValues;
335 const double GradientCutOff = 0;
336
337 // Compute the heat solution
338 DenseNodeData< Real , IsotropicUIntPack< Dim , FEMSig > > heatSolution;
339 DenseNodeData< Real , IsotropicUIntPack< Dim , FEMSig > > constraints;
340
341 // Add the FEM constraints
342 {
343 profiler.reset();
344 constraints = tree.initDenseNodeData( IsotropicUIntPack< Dim , FEMSig >() );
345 DenseNodeData< Point< Real , 1 > , IsotropicUIntPack< Dim , FEMTrivialSignature > > _constraints( tree.nodesSize() );
346 for( int i=0 ; i<geometrySamples.size() ; i++ ) _constraints[ geometrySamples[i].node ][0] = geometrySamples[i].sample.weight * ( 1<<(Depth.value*Dim) );
347 typename FEMIntegrator::template ScalarConstraint< IsotropicUIntPack< Dim , FEMSig > , IsotropicUIntPack< Dim , 0 > , IsotropicUIntPack< Dim , FEMTrivialSignature > , IsotropicUIntPack< Dim , 0 > > F( {1.} ); tree.addFEMConstraints( F , _constraints , constraints , Depth.value );
348 if( Verbose.set ) std::cout << "# Set heat constraints: " << profiler << std::endl;
349 }
350
351 // Solve the linear system
352 {
353 profiler.reset();
354 typename FEMTree< Dim , Real >::SolverInfo sInfo;
355 sInfo.cgDepth = 0 , sInfo.cascadic = false , sInfo.iters = GSIterations.value , sInfo.vCycles = 1 , sInfo.cgAccuracy = CGSolverAccuracy.value , sInfo.verbose = Verbose.set , sInfo.showResidual = ShowResidual.set , sInfo.showGlobalResidual = SHOW_GLOBAL_RESIDUAL_NONE , sInfo.sliceBlockSize = 1;
356 sInfo.useSupportWeights = true;
357 sInfo.sorRestrictionFunction = [&]( Real w , Real ){ return ( Real )( WeightScale.value * pow( w , WeightExponent.value ) ); };
358 {
359 typename FEMIntegrator::template System< IsotropicUIntPack< Dim , FEMSig > , IsotropicUIntPack< Dim , 1 > > F( { 1. , (double)DiffusionTime.value } );
360 heatSolution = tree.solveSystem( IsotropicUIntPack< Dim , FEMSig >() , F , constraints , BaseDepth.value , Depth.value , sInfo );
361 }
362 sInfo.baseVCycles = BaseVCycles.value;
363 if( Verbose.set ) std::cout << "# Heat system solved: " << profiler << std::endl;
364 }
365
366 // Evaluate the gradients at the leaves
367 {
368 profiler.reset();
369
370 typename FEMTree< Dim , Real >::template MultiThreadedEvaluator< IsotropicUIntPack< Dim , FEMSig > , 0 > evaluator( &tree , heatSolution );
371 typedef typename RegularTreeNode< Dim , FEMTreeNodeData , depth_and_offset_type >::template ConstNeighbors< IsotropicUIntPack< Dim , 3 > > OneRingNeighbors;
372 typedef typename RegularTreeNode< Dim , FEMTreeNodeData , depth_and_offset_type >::template ConstNeighborKey< IsotropicUIntPack< Dim , 1 > , IsotropicUIntPack< Dim , 1 > > OneRingNeighborKey;
373 std::vector< OneRingNeighborKey > oneRingNeighborKeys( ThreadPool::NumThreads() );
374 int treeDepth = tree.tree().maxDepth();
375 for( int i=0 ; i<oneRingNeighborKeys.size() ; i++ ) oneRingNeighborKeys[i].set( treeDepth );
376 DenseNodeData< Real , IsotropicUIntPack< Dim , FEMTrivialSignature > > leafCenterValues = tree.initDenseNodeData( IsotropicUIntPack< Dim , FEMTrivialSignature >() );
377
378 ThreadPool::ParallelFor( tree.nodesBegin(0) , tree.nodesEnd(Depth.value) , [&]( unsigned int thread , size_t i )
379 {
380 if( tree.isValidSpaceNode( tree.node((node_index_type)i) ) )
381 {
382 Point< Real , Dim > center ; Real width;
383 tree.centerAndWidth( (node_index_type)i , center , width );
384 leafCenterValues[i] = evaluator.values( center , thread )[0];
385 }
386 }
387 );
388
389 auto CenterGradient = [&] ( const RegularTreeNode< Dim , FEMTreeNodeData , depth_and_offset_type >* leaf , int thread )
390 {
391 int d , off[Dim] ; Point< Real , Dim > p ; Real width , _width = (Real)1./(1<<Depth.value);
392 tree.depthAndOffset( leaf , d , off ) , tree.centerAndWidth( leaf->nodeData.nodeIndex , p , width );
393 int res = 1<<d , _res = 1<<Depth.value;
394 Point< Real , Dim > g;
395 unsigned int index1[Dim] , index2[Dim];
396 for( int dd=0 ; dd<Dim ; dd++ ) index1[dd] = index2[dd] = 1;
397 const OneRingNeighbors& neighbors = oneRingNeighborKeys[thread].getNeighbors( leaf );
398 for( int c=0 ; c<Dim ; c++ )
399 {
400 Real value1 , value2;
401 if( off[c]-1>=0 ) index1[c] = 0;
402 if( off[c]+1<res ) index2[c] = 2;
403 const RegularTreeNode< Dim , FEMTreeNodeData , depth_and_offset_type >* node1 = neighbors.neighbors().data[ GetWindowIndex( IsotropicUIntPack< Dim , 3 >() , index1 ) ];
404 const RegularTreeNode< Dim , FEMTreeNodeData , depth_and_offset_type >* node2 = neighbors.neighbors().data[ GetWindowIndex( IsotropicUIntPack< Dim , 3 >() , index2 ) ];
405 if( d==Depth.value && tree.isValidSpaceNode( node2 ) ) value2 = leafCenterValues[ node2->nodeData.nodeIndex ];
406 else
407 {
408 Point< Real , Dim > delta;
409 delta[c] = ( (int)index2[c]-1 ) * _width;
410 value2 = evaluator.values( p+delta , thread )[0];
411 }
412 if( d==Depth.value && tree.isValidSpaceNode( node1 ) ) value1 = leafCenterValues[ node1->nodeData.nodeIndex ];
413 else
414 {
415 Point< Real , Dim > delta;
416 delta[c] = ( (int)index1[c]-1 ) * _width;
417 value1 = evaluator.values( p+delta , thread )[0];
418 }
419
420 g[c] = ( value2 - value1 ) / ( (Real)( index2[c] - index1[c] ) );
421
422 index1[c] = index2[c] = 1;
423 }
424
425 return g * _res;
426 };
427
428 for( node_index_type i=tree.nodesBegin(0) ; i<tree.nodesEnd(Depth.value) ; i++ ) if( tree.isValidSpaceNode( tree.node(i) ) && !tree.isValidSpaceNode( tree.node(i)->children ) )
429 {
430 RegularTreeNode< Dim , FEMTreeNodeData , depth_and_offset_type >* leaf = ( RegularTreeNode< Dim , FEMTreeNodeData , depth_and_offset_type >* )tree.node(i);
431 leafValues[leaf] *= 0;
432 }
433
434 ThreadPool::ParallelFor( tree.nodesBegin(0) , tree.nodesEnd(Depth.value) , [&]( unsigned int thread , size_t i )
435 {
436 if( tree.isValidSpaceNode( tree.node((node_index_type)i) ) && !tree.isValidSpaceNode( tree.node((node_index_type)i)->children ) )
437 {
438 RegularTreeNode< Dim , FEMTreeNodeData , depth_and_offset_type >* leaf = ( RegularTreeNode< Dim , FEMTreeNodeData , depth_and_offset_type >* )tree.node((node_index_type)i);
439 Point< Real , Dim > g = CenterGradient( leaf , thread );
440 Real len = (Real)Length( g );
441 if( len>GradientCutOff ) g /= len;
442 Point< Real , Dim+1 >* leafValue = leafValues(leaf);
443 if( leafValue ) for( int d=0 ; d<Dim ; d++ ) (*leafValue)[d+1] = -g[d];
444 else MK_THROW( "Leaf value doesn't exist" );
445 }
446 }
447 );
448 if( Verbose.set ) std::cout << "# Evaluated gradients: " << profiler << std::endl;
449 }
450
451
452 // Compute the EDT
453 {
454 // Evaluate the gradients at the center of the leaf nodes
455 DenseNodeData< Real , IsotropicUIntPack< Dim , FEMSig > > edtSolution , constraints;
456
457 // Add the FEM constraints
458 {
459 profiler.reset();
460 constraints = tree.initDenseNodeData( IsotropicUIntPack< Dim , FEMSig >() );
461 typename FEMIntegrator::template Constraint< IsotropicUIntPack< Dim , FEMSig > , IsotropicUIntPack< Dim , 1 > , IsotropicUIntPack< Dim , FEMTrivialSignature > , IsotropicUIntPack< Dim , 0 > , Dim+1 > F;
462 typedef IsotropicUIntPack< Dim , 1 > Derivatives1;
463 typedef IsotropicUIntPack< Dim , 0 > Derivatives2;
464 unsigned int derivatives2[Dim];
465 for( int d=0 ; d<Dim ; d++ ) derivatives2[d] = 0;
466 for( int d=0 ; d<Dim ; d++ )
467 {
468 unsigned int derivatives1[Dim];
469 for( int dd=0 ; dd<Dim ; dd++ ) derivatives1[dd] = dd==d ? 1 : 0;
470 F.weights[d+1][TensorDerivatives< Derivatives1 >::Index( derivatives1 )][ TensorDerivatives< Derivatives2 >::Index( derivatives2 )] = 1.;
471 }
472 tree.addFEMConstraints( F , leafValues , constraints , Depth.value );
473 if( Verbose.set ) std::cout << "# Set EDT constraints: " << profiler << std::endl;
474 }
475
476 // Add the interpolation constraints
477 if( valueInfo )
478 {
479 profiler.reset();
480 tree.addInterpolationConstraints( constraints , Depth.value , std::make_tuple( valueInfo ) );
481 if( Verbose.set ) std::cout << "#Set point constraints: " << profiler << std::endl;
482 }
483
484 // Solve the linear system
485 {
486 profiler.reset();
487 typename FEMTree< Dim , Real >::SolverInfo sInfo;
488 sInfo.cgDepth = 0 , sInfo.cascadic = true , sInfo.vCycles = 1 , sInfo.cgAccuracy = CGSolverAccuracy.value , sInfo.verbose = Verbose.set , sInfo.showResidual = ShowResidual.set , sInfo.showGlobalResidual = SHOW_GLOBAL_RESIDUAL_NONE , sInfo.sliceBlockSize = 1;
489 sInfo.iters = GSIterations.value;
490 sInfo.baseVCycles = BaseVCycles.value;
491 sInfo.useSupportWeights = true;
492 sInfo.sorRestrictionFunction = [&]( Real w , Real ){ return (Real)( WeightScale.value * pow( w , WeightExponent.value ) ); };
493 typename FEMIntegrator::template System< IsotropicUIntPack< Dim , FEMSig > , IsotropicUIntPack< Dim , 1 > > F( { 0. , 1. } );
494 edtSolution = tree.solveSystem( IsotropicUIntPack< Dim , FEMSig >() , F , constraints , BaseDepth.value , Depth.value , sInfo , std::make_tuple( valueInfo ) );
495 if( Verbose.set ) std::cout << "# EDT system solved: " << profiler << std::endl;
496 }
497
498 {
499 auto GetAverageValueAndError = [&]( const FEMTree< Dim , Real >* tree , const DenseNodeData< Real , IsotropicUIntPack< Dim , FEMSig > >& coefficients , double& average , double& error )
500 {
501 double errorSum = 0 , valueSum = 0 , weightSum = 0;
502 typename FEMTree< Dim , Real >::template MultiThreadedEvaluator< IsotropicUIntPack< Dim , FEMSig > , 0 > evaluator( tree , coefficients );
503 std::vector< double > errorSums( ThreadPool::NumThreads() , 0 ) , valueSums( ThreadPool::NumThreads() , 0 ) , weightSums( ThreadPool::NumThreads() , 0 );
504 ThreadPool::ParallelFor( 0 , geometrySamples.size() , [&]( unsigned int thread , size_t j )
505 {
506 ProjectiveData< Point< Real , Dim > , Real >& sample = geometrySamples[j].sample;
507 Real w = sample.weight;
508 Real value = evaluator.values( sample.data / sample.weight , thread , geometrySamples[j].node )[0];
509 errorSums[thread] += value * value * w;
510 valueSums[thread] += value * w;
511 weightSums[thread] += w;
512 }
513 );
514 for( unsigned int t=0 ; t<ThreadPool::NumThreads() ; t++ ) errorSum += errorSums[t] , valueSum += valueSums[t] , weightSum += weightSums[t];
515 average = valueSum / weightSum , error = sqrt( errorSum / weightSum );
516 };
517 double average , error;
518 GetAverageValueAndError( &tree , edtSolution , average , error );
519 if( Verbose.set ) printf( "Interpolation average / error: %g / %g\n" , average , error );
520 ThreadPool::ParallelFor( tree.nodesBegin(0) , tree.nodesEnd(0) , [&]( unsigned int , size_t i ){ edtSolution[i] -= (Real)average; } );
521 }
522
523 if( Out.set )
524 {
525 FILE* fp = fopen( Out.value , "wb" );
526 if( !fp ) MK_THROW( "Failed to open file for writing: " , Out.value );
527 FileStream fs(fp);
528 FEMTree< Dim , Real >::WriteParameter( fs );
529 DenseNodeData< Real , IsotropicUIntPack< Dim , FEMSig > >::WriteSignatures( fs );
530 tree.write( fs , false );
531 fs.write( modelToUnitCube );
532 edtSolution.write( fs );
533 fclose( fp );
534 }
535 }
536 if( valueInfo ) delete valueInfo , valueInfo = NULL;
537 }
538
539 #ifndef FAST_COMPILE
540 template< unsigned int Dim , class Real >
541 void Execute( int argc , char* argv[] )
542 {
543 switch( Degree.value )
544 {
545 case 1: return _Execute< Dim , Real , FEMDegreeAndBType< 1 , BOUNDARY_FREE >::Signature >( argc , argv );
546 case 2: return _Execute< Dim , Real , FEMDegreeAndBType< 2 , BOUNDARY_FREE >::Signature >( argc , argv );
547 case 3: return _Execute< Dim , Real , FEMDegreeAndBType< 3 , BOUNDARY_FREE >::Signature >( argc , argv );
548 case 4: return _Execute< Dim , Real , FEMDegreeAndBType< 4 , BOUNDARY_FREE >::Signature >( argc , argv );
549 default: MK_THROW( "Only B-Splines of degree 1 - 4 are supported" );
550 }
551 }
552 #endif // !FAST_COMPILE
553 int main( int argc , char* argv[] )
554 {
555 Timer timer;
556 #ifdef ARRAY_DEBUG
557 MK_WARN( "Array debugging enabled" );
558 #endif // ARRAY_DEBUG
559 CmdLineParse( argc-1 , &argv[1] , params );
560 ThreadPool::ChunkSize = ThreadChunkSize.value;
561 ThreadPool::Schedule = (ThreadPool::ScheduleType)ScheduleType.value;
562 if( MaxMemoryGB.value>0 ) SetPeakMemoryMB( MaxMemoryGB.value<<10 );
563
564 #ifdef USE_DOUBLE
565 typedef double Real;
566 #else // !USE_DOUBLE
567 typedef float Real;
568 #endif // USE_DOUBLE
569
570 #ifdef FAST_COMPILE
571 static const int Degree = DEFAULT_FEM_DEGREE;
572 static const BoundaryType BType = BOUNDARY_FREE;
573
574 MK_WARN( "Compiled for degree-" , Degree , ", boundary-" , BoundaryNames[ BType ] , ", " , sizeof(Real)==4 ? "single" : "double" , "-precision _only_" );
575 if( !BaseDepth.set ) BaseDepth.value = FullDepth.value;
576 if( BaseDepth.value>FullDepth.value )
577 {
578 if( BaseDepth.set ) MK_WARN( "Base depth must be smaller than full depth: " , BaseDepth.value , " <= " , FullDepth.value );
579 BaseDepth.value = FullDepth.value;
580 }
581 _Execute< DEFAULT_DIMENSION , Real , FEMDegreeAndBType< Degree , BType >::Signature >( argc , argv );
582 #else // !FAST_COMPILE
583 Execute< DEFAULT_DIMENSION , Real >( argc , argv );
584 #endif // FAST_COMPILE
585 if( Performance.set )
586 {
587 printf( "Time (Wall/CPU): %.2f / %.2f\n" , timer.wallTime() , timer.cpuTime() );
588 printf( "Peak Memory (MB): %d\n" , MemoryInfo::PeakMemoryUsageMB() );
589 }
590 return EXIT_SUCCESS;
591 }