Debian Codegraph @

src/thirdparty/PoissonRecon/PoissonRecon.server.inl

raw
1 /*
2 Copyright (c) 2023, 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 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
30 struct Server
31 {
32 typedef typename FEMTree< Dim , Real >::template DensityEstimator< Reconstructor::WeightDegree > DensityEstimator;
33 typedef typename FEMTree< Dim , Real >::template ApproximatePointInterpolationInfo< Real , 0 , Reconstructor::Poisson::ConstraintDual< Dim , Real > , Reconstructor::Poisson::SystemDual< Dim , Real > > ApproximatePointInterpolationInfo;
34 typedef IsotropicUIntPack< Dim , FEMDegreeAndBType< Degree , BType >::Signature > Sigs;
35 typedef IsotropicUIntPack< Dim , Degree > Degrees;
36 typedef IsotropicUIntPack< Dim , FEMDegreeAndBType< Reconstructor::Poisson::NormalDegree , DerivativeBoundary< BType , 1 >::BType >::Signature > NormalSigs;
37 static const unsigned int DataSig = FEMDegreeAndBType< Reconstructor::DataDegree , BOUNDARY_FREE >::Signature;
38 typedef VertexFactory::DynamicFactory< Real > AuxDataFactory;
39 typedef typename AuxDataFactory::VertexType AuxData;
40 typedef VertexFactory::Factory< Real , VertexFactory::PositionFactory< Real , Dim > , VertexFactory::Factory< Real , VertexFactory::NormalFactory< Real , Dim > , AuxDataFactory > > InputSampleFactory;
41 typedef VertexFactory::Factory< Real , VertexFactory::NormalFactory< Real , Dim > , AuxDataFactory > InputSampleDataFactory;
42 typedef DirectSum< Real , Point< Real , Dim > , typename AuxDataFactory::VertexType > InputSampleDataType;
43 typedef DirectSum< Real , Point< Real , Dim > , InputSampleDataType > InputSampleType;
44 typedef InputDataStream< InputSampleType > InputPointStream;
45 typedef RegularTreeNode< Dim , FEMTreeNodeData , depth_and_offset_type > FEMTreeNode;
46
47 protected:
48 std::vector< SocketStream > _clientSockets;
49 PointPartition::PointSetInfo< Real , Dim > _pointSetInfo;
50 PointPartition::Partition _pointPartition;
51
52 struct _State4
53 {
54 FEMTree< Dim , Real > tree;
55 DenseNodeData< Real , Sigs > constraints , solution;
56 ApproximatePointInterpolationInfo *iInfo;
57 SparseNodeData< ProjectiveData< AuxData , Real > , IsotropicUIntPack< Dim , DataSig > > *auxDataField;
58
59 _State4( void ) : tree( MEMORY_ALLOCATOR_BLOCK_SIZE ) , iInfo(NULL) , auxDataField(NULL) {}
60 ~_State4( void ){ delete iInfo ; delete auxDataField; }
61 };
62 struct _State6
63 {
64 using SliceSigs = typename Sigs::Transpose::Rest::Transpose;
65 using Vertex = typename VertexFactory::PositionFactory< Real , Dim-1 >::VertexType;
66 FEMTree< Dim-1 , Real > *sliceTree;
67 XForm< Real , Dim > xForm;
68 DenseNodeData< Real , SliceSigs > solution , dSolution;
69 std::vector< std::conditional_t< Dim==3 , typename LevelSetExtractor< Real , 2 >::SliceValues , char > > sliceValues , dSliceValues;
70 std::vector< Point< Real , Dim-1 > > vertices;
71
72 _State6( void ) : sliceTree(NULL) {}
73 ~_State6( void ){ delete sliceTree; }
74 };
75
76 PhaseInfo _phase0( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , Profiler &profiler );
77 PhaseInfo _phase2( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , ProjectiveData< Real , Real > &cumulativePointWeight , Profiler &profiler );
78 PhaseInfo _phase4( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , ProjectiveData< Real , Real > cumulativePointWeight , unsigned int baseVCycles , Real &isoValue , Profiler &profiler );
79 PhaseInfo _phase6( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , Real isoValue , bool showDiscontinuity , bool outputBoundarySlices , std::vector< unsigned int > &sharedVertexCounts , Profiler &profiler );
80
81 template< typename _Real , unsigned int _Dim , BoundaryType _BType , unsigned int _Degree >
82 friend std::vector< unsigned int > RunServer( PointPartition::PointSetInfo< _Real , _Dim > , PointPartition::Partition , std::vector< Socket > , ClientReconstructionInfo< _Real , _Dim > , unsigned int , unsigned int , bool , bool );
83 };
84
85
86 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
87 std::vector< unsigned int > RunServer
88 (
89 PointPartition::PointSetInfo< Real , Dim > pointSetInfo ,
90 PointPartition::Partition pointPartition ,
91 std::vector< Socket > clientSockets ,
92 ClientReconstructionInfo< Real , Dim > clientReconInfo ,
93 unsigned int baseVCycles ,
94 unsigned int sampleMS ,
95 bool showDiscontinuity ,
96 bool outputBoundarySlices
97 )
98 {
99 std::vector< unsigned int > sharedVertexCounts;
100 Server< Real , Dim , BType , Degree > server;
101 Profiler profiler( sampleMS );
102
103 clientReconInfo.auxProperties = pointSetInfo.auxiliaryProperties;
104
105 // Initialization
106 {
107 server._pointSetInfo = pointSetInfo;
108 server._pointPartition = pointPartition;
109 server._clientSockets.resize( clientSockets.size() );
110
111 for( unsigned int i=0 ; i<clientSockets.size() ; i++ ) server._clientSockets[i] = SocketStream( clientSockets[i] );
112
113 for( unsigned int i=0 ; i<clientSockets.size() ; i++ ) clientReconInfo.write( server._clientSockets[i] );
114 for( unsigned int i=0 ; i<clientSockets.size() ; i++ ) server._clientSockets[i].write( i );
115 }
116
117 if( clientReconInfo.verbose>1 )
118 {
119 for( unsigned int i=0 ; i<clientSockets.size() ; i++ )
120 {
121 #ifdef ADAPTIVE_PADDING
122 std::pair< unsigned int , unsigned int > range = pointPartition.range( i );
123 if( range.first<clientReconInfo.padSize ) range.first = 0;
124 else range.first -= clientReconInfo.padSize;
125 if( range.second+clientReconInfo.padSize>pointPartition.slabs() ) range.second = pointPartition.slabs();
126 else range.second += clientReconInfo.padSize;
127 #else // !ADAPTIVE_PADDING
128 std::pair< unsigned int , unsigned int > range = pointPartition.range( i , clientReconInfo.padSize );
129 #endif // ADAPTIVE_PADDING
130 std::cout << "Range[ " << i << " ]: [ " << range.first << " , " << range.second << " )" << std::endl;
131 }
132 std::cout << "Boundary-type = " << BoundaryNames[BType] << " ; Degree = " << Degree << std::endl;
133 }
134
135 ProjectiveData< Real , Real > cumulativePointWeight;
136 Real isoValue;
137
138 // [PHASE 0] Send the client initial information
139 {
140 profiler.reset();
141 PhaseInfo phaseInfo = server._phase0( clientReconInfo , profiler );
142 if( clientReconInfo.verbose>0 )
143 {
144 StreamFloatPrecision sfp( std::cout , 1 );
145 std::cout << SendDataString( 0 , phaseInfo.writeBytes ) << phaseInfo.writeTime << " (s)" << std::endl;
146 }
147 }
148
149 // [PHASE 2] Accumulate/Send the point weight
150 {
151 profiler.reset();
152 PhaseInfo phaseInfo = server._phase2( clientReconInfo , cumulativePointWeight , profiler );
153 if( clientReconInfo.verbose>0 )
154 {
155 StreamFloatPrecision sfp( std::cout , 1 );
156 std::cout << ReceiveDataString( 2 , phaseInfo.readBytes ) << phaseInfo.readTime << " (s)" << std::endl;
157 std::cout << "[PROCESS 2] : " << phaseInfo.processTime << " (s), " << profiler(false) << std::endl;
158 std::cout << SendDataString( 2 , phaseInfo.writeBytes ) << phaseInfo.writeTime << " (s)" << std::endl;
159 }
160 }
161
162 // [PHASE 4] Accumulate/solve/send coarse system
163 {
164 profiler.reset();
165 PhaseInfo phaseInfo = server._phase4( clientReconInfo , cumulativePointWeight , baseVCycles , isoValue , profiler );
166 if( clientReconInfo.verbose>0 )
167 {
168 StreamFloatPrecision sfp( std::cout , 1 );
169 std::cout << ReceiveDataString( 4 , phaseInfo.readBytes ) << phaseInfo.readTime << " (s)" << std::endl;
170 std::cout << "[PROCESS 4] : " << phaseInfo.processTime << " (s), " << profiler(false) << std::endl;
171 std::cout << SendDataString( 4 , phaseInfo.writeBytes ) << phaseInfo.writeTime << " (s)" << std::endl;
172 }
173 }
174
175 // [PHASE 6] Accumulate/merge/send boundary tree info
176 {
177 profiler.reset();
178 PhaseInfo phaseInfo = server._phase6( clientReconInfo , isoValue , showDiscontinuity , outputBoundarySlices , sharedVertexCounts , profiler );
179 if( clientReconInfo.verbose>0 )
180 {
181 StreamFloatPrecision sfp( std::cout , 1 );
182 std::cout << ReceiveDataString( 6 , phaseInfo.readBytes ) << phaseInfo.readTime << " (s)" << std::endl;
183 std::cout << "[PROCESS 6] : " << phaseInfo.processTime << " (s), " << profiler(false) << std::endl;
184 std::cout << SendDataString( 6 , phaseInfo.writeBytes ) << phaseInfo.writeTime << " (s)" << std::endl;
185 }
186 }
187 return sharedVertexCounts;
188 }
189
190 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
191 PhaseInfo Server< Real , Dim , BType , Degree >::_phase0( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , Profiler &profiler )
192 {
193 PhaseInfo phaseInfo;
194
195 Timer timer;
196 for( unsigned int i=0 ; i<_clientSockets.size() ; i++ )
197 {
198 ClientServerStream< false > clientStream( _clientSockets[i] , i , clientReconInfo );
199 clientStream.ioBytes = 0;
200
201 // Send the information about the point-set
202 clientStream.write( _pointSetInfo.modelToUnitCube );
203
204 // Send the client's range
205 #ifdef ADAPTIVE_PADDING
206 std::pair< unsigned int , unsigned int > range = _pointPartition.range( i );
207 #else // !ADAPTIVE_PADDING
208 std::pair< unsigned int , unsigned int > range = _pointPartition.range( i , 0 );
209 #endif // ADAPTIVE_PADDING
210 clientStream.write( range );
211
212 phaseInfo.writeBytes += clientStream.ioBytes;
213 }
214 phaseInfo.writeTime += timer.wallTime();
215 profiler.update();
216 return phaseInfo;
217 }
218
219 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
220 PhaseInfo Server< Real , Dim , BType , Degree >::_phase2( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , ProjectiveData< Real , Real > &cumulativePointWeight , Profiler &profiler )
221 {
222 PhaseInfo phaseInfo;
223 std::pair< size_t , size_t > cumulativeNodeCounts;
224
225
226 cumulativeNodeCounts = std::pair< size_t , size_t >(0,0);
227 cumulativePointWeight = ProjectiveData< Real , Real >( (Real)0. );
228
229 for( unsigned int i=0 ; i<_clientSockets.size() ; i++ )
230 {
231 Timer timer;
232 ProjectiveData< Real , Real > pointWeight;
233 std::pair< size_t , size_t > nodeCounts;
234 ClientServerStream< true > clientStream( _clientSockets[i] , i , clientReconInfo );
235 clientStream.ioBytes = 0;
236 clientStream.read( pointWeight );
237 clientStream.read( nodeCounts );
238 phaseInfo.readBytes += clientStream.ioBytes;
239 phaseInfo.readTime += timer.wallTime();
240
241 timer = Timer();
242 cumulativePointWeight += pointWeight;
243 cumulativeNodeCounts.first += nodeCounts.first;
244 cumulativeNodeCounts.second += nodeCounts.second;
245 phaseInfo.processTime += timer.wallTime();
246 }
247
248 Timer timer;
249 for( unsigned int i=0 ; i<_clientSockets.size() ; i++ )
250 {
251 ClientServerStream< false > clientStream( _clientSockets[i] , i , clientReconInfo );
252 clientStream.ioBytes = 0;
253 clientStream.write( cumulativePointWeight );
254 phaseInfo.writeBytes += clientStream.ioBytes;
255 }
256 phaseInfo.writeTime = timer.wallTime();
257
258 if( clientReconInfo.verbose>1 ) std::cout << "Redundancy: " << cumulativeNodeCounts.second << " / " << cumulativeNodeCounts.first << " = " << (double)cumulativeNodeCounts.second/cumulativeNodeCounts.first << std::endl;
259
260 profiler.update();
261
262 return phaseInfo;
263 }
264
265 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
266 PhaseInfo Server< Real , Dim , BType , Degree >::_phase4( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , ProjectiveData< Real , Real > cumulativePointWeight , unsigned int baseVCycles , Real &isoValue , Profiler &profiler )
267 {
268 constexpr int MaxDegree = Reconstructor::Poisson::NormalDegree > Degrees::Max() ? Reconstructor::Poisson::NormalDegree : Degrees::Max();
269 const int StartOffset = BSplineSupportSizes< MaxDegree >::SupportStart;
270 const int EndOffset = BSplineSupportSizes< MaxDegree >::SupportEnd+1;
271 PhaseInfo phaseInfo;
272
273 _State4 state4;
274
275 std::vector< std::vector< node_index_type > > clientsToServer( _clientSockets.size() );
276
277 // Initialize the tree
278 {
279 Timer timer;
280 FEMTreeInitializer< Dim , Real >::Initialize( state4.tree.spaceRoot() , clientReconInfo.baseDepth , []( int , int[] ){ return true; } , state4.tree.nodeAllocators[0] , state4.tree.initializer() );
281
282 auto hasDataFunctor = []( const FEMTreeNode * ){ return false; };
283
284 // Set the root of the tree so we can copy constraints into it
285 auto addNodeFunctor = [&]( int d , const int off[Dim] ){ return d<=(int)clientReconInfo.baseDepth; };
286 state4.tree.template finalizeForMultigrid< MaxDegree , Degrees::Max() >( clientReconInfo.baseDepth , addNodeFunctor , hasDataFunctor , std::make_tuple() , std::make_tuple() );
287 phaseInfo.processTime += timer.wallTime();
288 profiler.update();
289 }
290
291 // Get/merge client data
292 for( unsigned int i=0 ; i<_clientSockets.size() ; i++ )
293 {
294 Timer timer;
295
296 std::vector< node_index_type > &clientToServer = clientsToServer[i];
297 ClientServerStream< true > clientStream( _clientSockets[i] , i , clientReconInfo , ClientReconstructionInfo< Real , Dim >::BACK );
298 clientStream.ioBytes = 0;
299
300 // The number of nodes in the client's coarse sub-tree
301 size_t subNodeCount;
302 clientStream.read( subNodeCount );
303
304 // The nodes in the client's coarse sub-tree
305 Pointer( FEMTreeNode ) subNodes = NewPointer< FEMTreeNode >( subNodeCount );
306 clientStream.read( subNodes , subNodeCount );
307
308 phaseInfo.readBytes += clientStream.ioBytes;
309 phaseInfo.readTime += timer.wallTime();
310
311
312 timer = Timer();
313 // Transform the nodes indices back to pointers
314 TreeIndicesToAddresses( subNodes , subNodeCount );
315 clientToServer.resize( subNodeCount , -1 );
316
317 // Find the map from client to index to server index and add client nodes as necessary
318 std::function< void ( FEMTreeNode * , const FEMTreeNode * ) > ProcessIndices = [&]( FEMTreeNode *serverNode , const FEMTreeNode *clientNode )
319 {
320 if( clientNode->nodeData.nodeIndex!=-1 ) clientToServer[ clientNode->nodeData.nodeIndex ] = serverNode->nodeData.nodeIndex;
321 if( clientNode->children )
322 {
323 if( !serverNode->children ) serverNode->template initChildren< false >( state4.tree.nodeAllocators[0] , state4.tree.initializer() );
324 for( int c=0 ; c<(1<<Dim) ; c++ ) ProcessIndices( serverNode->children+c , clientNode->children+c );
325 }
326 };
327 ProcessIndices( const_cast< FEMTreeNode * >( &state4.tree.tree() ) , &subNodes[0] );
328 profiler.update();
329 DeletePointer( subNodes );
330 phaseInfo.processTime += timer.wallTime();
331 }
332
333 {
334 Timer timer;
335 constexpr int MaxDegree = Reconstructor::Poisson::NormalDegree > Degrees::Max() ? Reconstructor::Poisson::NormalDegree : Degrees::Max();
336 auto hasDataFunctor = []( const FEMTreeNode * ){ return true; };
337 auto addNodeFunctor = [&]( int d , const int off[Dim] ){ return d<=(int)clientReconInfo.baseDepth; };
338 std::vector< node_index_type > newToOld = state4.tree.template finalizeForMultigrid< MaxDegree , Degrees::Max() >( clientReconInfo.baseDepth , addNodeFunctor , hasDataFunctor , std::make_tuple() , std::make_tuple() );
339 node_index_type idx = newToOld[0];
340 for( unsigned int i=0 ; i<newToOld.size() ; i++ ) idx = std::max< node_index_type >( idx , newToOld[i] );
341 idx++;
342 std::vector< node_index_type > oldToNew( idx , -1 );
343 for( unsigned int i=0 ; i<newToOld.size() ; i++ ) if( newToOld[i]!=-1 ) oldToNew[ newToOld[i] ] = i;
344 for( unsigned int i=0 ; i<clientsToServer.size() ; i++ ) for( unsigned int j=0 ; j<clientsToServer[i].size() ; j++ ) clientsToServer[i][j] = oldToNew[ clientsToServer[i][j] ];
345 phaseInfo.processTime += timer.wallTime();
346 profiler.update();
347 }
348
349 Timer timer;
350 AuxDataFactory auxDataFactory( _pointSetInfo.auxiliaryProperties );
351 bool needAuxData = clientReconInfo.dataX>0 && auxDataFactory.bufferSize();
352
353 state4.constraints = state4.tree.initDenseNodeData( Sigs() );
354
355 {
356 Real targetValue = clientReconInfo.targetValue;
357 state4.iInfo = new ApproximatePointInterpolationInfo( Reconstructor::Poisson::ConstraintDual< Dim , Real >( targetValue , clientReconInfo.pointWeight * cumulativePointWeight.value() ) , Reconstructor::Poisson::SystemDual< Dim , Real >( clientReconInfo.pointWeight * cumulativePointWeight.value() ) , true );
358 state4.iInfo->iData.reserve( state4.tree.nodesSize() );
359 }
360
361 using InterpolationData = typename ApproximatePointInterpolationInfo::Data;
362 auto preMergeFunctor = []( InterpolationData data ){ data.position *= data.weight ; return data; };
363 auto postMergeFunctor = []( InterpolationData data ){ data.position /= data.weight ; return data; };
364
365 if( needAuxData )
366 {
367 state4.auxDataField = new SparseNodeData< ProjectiveData< AuxData , Real > , IsotropicUIntPack< Dim , DataSig > >();
368 state4.auxDataField->reserve( state4.tree.nodesSize() );
369 }
370 phaseInfo.processTime += timer.wallTime();
371 profiler.update();
372
373 for( unsigned int i=0 ; i<_clientSockets.size() ; i++ )
374 {
375 std::vector< node_index_type > &clientToServer = clientsToServer[i];
376 ClientServerStream< true > clientStream( _clientSockets[i] , i , clientReconInfo , ClientReconstructionInfo< Real , Dim >::FRONT );
377 clientStream.ioBytes = 0;
378
379 // The constraints
380 {
381 Timer timer;
382 DenseNodeData< Real , Sigs > _constraints( clientStream );
383 phaseInfo.readTime += timer.wallTime();
384
385 timer = Timer();
386 for( unsigned int i=0 ; i<_constraints.size() ; i++ )
387 if( clientToServer[i]==-1 || clientToServer[i]>=(node_index_type)state4.constraints.size() ){ MK_WARN_ONCE( "Unmatched client node(s): " , clientToServer[i] ); }
388 else state4.constraints[ clientToServer[i] ] += _constraints[i];
389 phaseInfo.processTime += timer.wallTime();
390 }
391
392 // The points
393 {
394 Timer timer;
395 ApproximatePointInterpolationInfo _iInfo( clientStream );
396 phaseInfo.readTime += timer.wallTime();
397
398 timer = Timer();
399 state4.iInfo->iData.mergeFromTarget( _iInfo.iData , [&]( unsigned int idx ){ return clientToServer[idx]; } , preMergeFunctor );
400 phaseInfo.processTime += timer.wallTime();
401 }
402 // The data field
403 if( needAuxData )
404 {
405 Timer timer;
406 SparseNodeData< ProjectiveData< AuxData , Real > , IsotropicUIntPack< Dim , DataSig > > *_auxDataField;
407 if constexpr( !AuxDataFactory::IsStaticallyAllocated() )
408 {
409 ProjectiveAuxDataTypeSerializer< Real > serializer( clientReconInfo.auxProperties );
410 _auxDataField = new SparseNodeData< ProjectiveData< AuxData , Real > , IsotropicUIntPack< Dim , DataSig > >( clientStream , serializer );
411 }
412 else _auxDataField = new SparseNodeData< ProjectiveData< AuxData , Real > , IsotropicUIntPack< Dim , DataSig > >( clientStream );
413 phaseInfo.readTime += timer.wallTime();
414
415 timer = Timer();
416 state4.auxDataField->mergeFromTarget( *_auxDataField , [&]( unsigned int idx ){ return clientToServer[idx]; } );
417 phaseInfo.processTime += timer.wallTime();
418
419 profiler.update();
420 delete _auxDataField;
421 }
422 else profiler.update();
423 phaseInfo.readBytes += clientStream.ioBytes;
424 }
425
426 if( needAuxData )
427 {
428 Timer timer;
429 auto nodeFunctor = [&]( const RegularTreeNode< Dim , FEMTreeNodeData , depth_and_offset_type >* n )
430 {
431 ProjectiveData< AuxData , Real >* clr = state4.auxDataField->operator()( n );
432 if( clr ) (*clr) *= (Real)pow( clientReconInfo.dataX , state4.tree.depth( n ) );
433 };
434 state4.tree.tree().processNodes( nodeFunctor );
435 phaseInfo.processTime += timer.wallTime();
436 }
437 {
438 Timer timer;
439 for( unsigned int i=0 ; i<state4.iInfo->iData.size() ; i++ ) state4.iInfo->iData[i] = postMergeFunctor( state4.iInfo->iData[i] );
440 phaseInfo.processTime += timer.wallTime();
441 }
442
443 {
444 Timer timer;
445
446 typename FEMTree< Dim , Real >::SolverInfo sInfo;
447 sInfo.cgDepth = 0 , sInfo.cascadic = true , sInfo.vCycles = 1 , sInfo.iters = clientReconInfo.iters , sInfo.cgAccuracy = clientReconInfo.cgSolverAccuracy , sInfo.verbose = clientReconInfo.verbose>1 , sInfo.showResidual = clientReconInfo.verbose>2 , sInfo.showGlobalResidual = SHOW_GLOBAL_RESIDUAL_NONE , sInfo.sliceBlockSize = 1;
448 sInfo.baseVCycles = baseVCycles;
449 typename FEMIntegrator::template System< Sigs , IsotropicUIntPack< Dim , 1 > > F( { 0. , 1. } );
450 state4.solution = state4.tree.solveSystem( Sigs() , F , state4.constraints , clientReconInfo.baseDepth , std::min< unsigned int >( clientReconInfo.sharedDepth , clientReconInfo.solveDepth ) , sInfo , std::make_tuple( state4.iInfo ) );
451 phaseInfo.processTime += timer.wallTime();
452
453 profiler.update();
454 }
455
456 for( unsigned int i=0 ; i<_clientSockets.size() ; i++ )
457 {
458 Timer timer;
459 std::pair< unsigned int , unsigned int > range;
460 #ifdef ADAPTIVE_PADDING
461 // Compute the range of slices @ clientReconInfo.sharedDepth that can contribute to the client
462 {
463 range = _pointPartition.range( i );
464 if( range.first<clientReconInfo.padSize ) range.first = 0;
465 else range.first -= clientReconInfo.padSize;
466 if( range.second+clientReconInfo.padSize>_pointPartition.slabs() ) range.second = _pointPartition.slabs();
467 else range.second += clientReconInfo.padSize;
468 }
469 #else // !ADAPTIVE_PADDING
470 range = _pointPartition.range( i , clientReconInfo.padSize );
471 #endif // ADAPTIVE_PADDING
472
473 ClientServerStream< false > clientStream( _clientSockets[i] , i , clientReconInfo );
474 clientStream.ioBytes = 0;
475 auto keepNodeFunctor = [&]( const FEMTreeNode *node )
476 {
477 int d , off[Dim];
478 state4.tree.depthAndOffset( node , d , off );
479
480 // Pre-tree nodes need to be shared and nodes finer than @ clientReconInfo.sharedDepth don't need to be
481 if( d<0 ) return true;
482 else if( d>(int)clientReconInfo.sharedDepth )
483 {
484 MK_WARN( "Why does the client have fine nodes?" );
485 return false;
486 }
487 else
488 {
489 // Compute the space of the range of the support @ clientReconInfo.sharedDepth
490 int start = ( off[Dim-1] + StartOffset )<<(clientReconInfo.sharedDepth-d);
491 int end = ( off[Dim-1] + EndOffset )<<(clientReconInfo.sharedDepth-d);
492
493 // Keep the node if its support fall within the client's range
494 return start<(int)range.second && end>(int)range.first;
495 }
496 };
497 size_t subNodeCount;
498 Pointer( FEMTreeNode ) subNodes = state4.tree.tree().serializeSubTree( keepNodeFunctor , subNodeCount );
499
500 node_index_type count = 0;
501 subNodes[0].processNodes( [&]( const FEMTreeNode *node ){ if( node->nodeData.nodeIndex!=-1 ) count++; } );
502 std::vector< node_index_type > newToOld( count );
503 count = 0;
504 for( size_t i=0 ; i<subNodeCount ; i++ ) if( subNodes[i].nodeData.nodeIndex!=-1 )
505 {
506 newToOld[ count ] = subNodes[i].nodeData.nodeIndex;
507 subNodes[i].nodeData.nodeIndex = count++;
508 }
509
510 TreeAddressesToIndices( subNodes , subNodeCount );
511 phaseInfo.processTime += timer.wallTime();
512
513 timer = Timer();
514 clientStream.write( subNodeCount );
515 clientStream.write( subNodes , subNodeCount );
516 phaseInfo.writeTime += timer.wallTime();
517
518 timer = Timer();
519 DenseNodeData< Real , Sigs > _solution( count );
520 for( unsigned int i=0 ; i<newToOld.size() ; i++ ) _solution[i] = state4.solution[ newToOld[i] ];
521 phaseInfo.processTime += timer.wallTime();
522
523 timer = Timer();
524 _solution.write( clientStream );
525 phaseInfo.writeTime += timer.wallTime();
526
527 if( needAuxData )
528 {
529 Timer timer;
530 SparseNodeData< ProjectiveData< AuxData , Real > , IsotropicUIntPack< Dim , DataSig > > _auxDataField;
531 _auxDataField.reserve( count );
532 for( size_t i=0 ; i<subNodeCount ; i++ ) if( subNodes[i].nodeData.nodeIndex!=-1 )
533 {
534 const FEMTreeNode *node = state4.tree.node( newToOld[ subNodes[i].nodeData.nodeIndex ] );
535 ProjectiveData< AuxData , Real > *data = state4.auxDataField->operator()( node );
536 if( data ) _auxDataField[ subNodes+i ] = *data;
537 }
538 phaseInfo.processTime += timer.wallTime();
539
540 timer = Timer();
541 if constexpr( !AuxDataFactory::IsStaticallyAllocated() )
542 {
543 ProjectiveAuxDataTypeSerializer< Real > serializer( clientReconInfo.auxProperties );
544 _auxDataField.write( clientStream , serializer );
545 }
546 else _auxDataField.write( clientStream );
547 phaseInfo.writeTime += timer.wallTime();
548 }
549 profiler.update();
550 DeletePointer( subNodes );
551 phaseInfo.writeBytes += clientStream.ioBytes;
552 }
553
554 {
555 std::pair< double , double > isoInfo(0.,0.);
556 for( unsigned int i=0 ; i<_clientSockets.size() ; i++ )
557 {
558 std::pair< double , double > _isoInfo(0.,0.);
559 _clientSockets[i].read( _isoInfo );
560 isoInfo.first += _isoInfo.first;
561 isoInfo.second += _isoInfo.second;
562 }
563 if( clientReconInfo.verbose>1 ) std::cout << "Iso-value: " << ( isoInfo.first / isoInfo.second ) << std::endl;
564 isoValue = (Real)( isoInfo.first / isoInfo.second );
565 }
566
567 if( clientReconInfo.outputSolution )
568 {
569 std::string outFileName = std::string( "solution.tree" );
570 if( clientReconInfo.outDir.length() ) outFileName = PointPartition::FileDir( clientReconInfo.outDir , outFileName );
571
572 FILE* fp = fopen( outFileName.c_str() , "wb" );
573 if( !fp ) MK_THROW( "Failed to open file for writing: " , outFileName );
574 FileStream fs(fp);
575 FEMTree< Dim , Real >::WriteParameter( fs );
576 DenseNodeData< Real , Sigs >::WriteSignatures( fs );
577 XForm< Real , Dim+1 > voxelToUnitCube = XForm< Real , Dim+1 >::Identity();
578 state4.tree.write( fs , false );
579 fs.write( voxelToUnitCube );
580 state4.solution.write( fs );
581 fclose( fp );
582 }
583
584 return phaseInfo;
585 }
586
587 template< typename Real , unsigned int Dim , BoundaryType BType , unsigned int Degree >
588 PhaseInfo Server< Real , Dim , BType , Degree >::_phase6( const ClientReconstructionInfo< Real , Dim > &clientReconInfo , Real isoValue , bool showDiscontinuity , bool outputBoundarySlices , std::vector< unsigned int > &sharedVertexCounts , Profiler &profiler )
589 {
590 using SliceSigs = typename _State6::SliceSigs;
591 using Vertex = typename _State6::Vertex;
592 PhaseInfo phaseInfo;
593
594 sharedVertexCounts.resize( _clientSockets.size()-1 );
595
596 if constexpr( Dim==3 ) for( unsigned int i=0 ; i<_clientSockets.size()-1 ; i++ )
597 {
598 _State6 state6;
599
600 auto ReadSlice = [&]( BinaryStream &clientStream , DenseNodeData< Real , SliceSigs > &solution , DenseNodeData< Real , SliceSigs > &dSolution , XForm< Real , Dim > &modelToUnitCube )
601 {
602 FEMTree< Dim-1 , Real > *sliceTree = new FEMTree< Dim-1 , Real >( clientStream , MEMORY_ALLOCATOR_BLOCK_SIZE );
603 clientStream.read( modelToUnitCube );
604 solution.read( clientStream );
605 if( !clientReconInfo.linearFit ) dSolution.read( clientStream );
606 return sliceTree;
607 };
608
609
610 {
611 ClientServerStream< true > clientStream0( _clientSockets[i+0] , i+0 , clientReconInfo , ClientReconstructionInfo< Real , Dim >::FRONT );
612 ClientServerStream< true > clientStream1( _clientSockets[i+1] , i+1 , clientReconInfo , ClientReconstructionInfo< Real , Dim >::BACK );
613 DenseNodeData< Real , SliceSigs > backSolution , frontSolution , backDSolution , frontDSolution;
614 FEMTree< Dim-1 , Real > *backSliceTree , *frontSliceTree;
615 XForm< Real , Dim > backXForm , frontXForm;
616
617 Timer timer;
618 backSliceTree = ReadSlice( clientStream0 , backSolution , backDSolution , backXForm );
619 frontSliceTree = ReadSlice( clientStream1 , frontSolution , frontDSolution , frontXForm );
620 phaseInfo.readTime += timer.wallTime();
621
622 if( showDiscontinuity )
623 {
624 double discontinuityTime = 0;
625 size_t discontinuityCount = 0;
626 double l1 = 0 , l2 = 0 , d2 = 0 , dInf = 0;
627
628 double t = Time();
629
630 int res1 = 0 , res2 = 0;
631 Pointer( Real ) values1 = backSliceTree->template regularGridEvaluate< true >( backSolution , res1 , -1 , false );
632 Pointer( Real ) values2 = frontSliceTree->template regularGridEvaluate< true >( frontSolution , res2 , -1 , false );
633 if( res1!=res2 ) MK_THROW( "Different resolutions: " , res1 , " != " , res2 );
634 size_t count = 1;
635 for( unsigned int d=0 ; d<(Dim-1) ; d++ ) count *= (unsigned int)res1;
636 discontinuityCount += count;
637 for( unsigned int i=0 ; i<count ; i++ ) l1 += values1[i] * values1[i] , l2 += values2[i] * values2[i] , d2 += ( values1[i] - values2[i] ) * ( values1[i] - values2[i] ) , dInf = std::max< double >( dInf , fabs( values1[i]-values2[i] ) );
638 DeletePointer( values1 );
639 DeletePointer( values2 );
640
641 discontinuityTime += Time()-t;
642
643 if( discontinuityCount )
644 {
645 d2 /= discontinuityCount;
646 l1 /= discontinuityCount;
647 l2 /= discontinuityCount;
648 std::cout << "Discontinuity L2 / L-infinity: " << sqrt(d2) << " / " << dInf << " [ " << sqrt(l1) << " , " << sqrt(l2) << " ] " << discontinuityTime << " (s)" << std::endl;
649 }
650 profiler.update();
651 }
652
653 timer = Timer();
654 state6.sliceTree = FEMTree< Dim-1 , Real >::Merge( *backSliceTree , *frontSliceTree , MEMORY_ALLOCATOR_BLOCK_SIZE );
655 state6.solution = state6.sliceTree->initDenseNodeData( SliceSigs() );
656 state6.sliceTree->merge( * backSliceTree , backSolution , state6.solution );
657 state6.sliceTree->merge( *frontSliceTree , frontSolution , state6.solution );
658 for( unsigned int j=0 ; j<state6.solution.size() ; j++ ) state6.solution[j] /= (Real)2.;
659 if( !clientReconInfo.linearFit )
660 {
661 state6.dSolution = state6.sliceTree->initDenseNodeData( SliceSigs() );
662 state6.sliceTree->merge( * backSliceTree , backDSolution , state6.dSolution );
663 state6.sliceTree->merge( *frontSliceTree , frontDSolution , state6.dSolution );
664 for( unsigned int j=0 ; j<state6.dSolution.size() ; j++ ) state6.dSolution[j] /= (Real)2.;
665 }
666 state6.xForm = ( backXForm + frontXForm )/(Real)2.;
667 phaseInfo.processTime += timer.wallTime();
668
669 profiler.update();
670
671 if( outputBoundarySlices )
672 {
673 auto WriteBoundary = [&]( std::string fileName , const FEMTree< Dim-1 , Real > *sliceTree , const DenseNodeData< Real , SliceSigs > &solution )
674 {
675 FILE* fp = fopen( fileName.c_str() , "wb" );
676 if( !fp ) MK_THROW( "Failed to open file for writing: " , fileName );
677 FileStream fs(fp);
678 FEMTree< Dim-1 , Real >::WriteParameter( fs );
679 DenseNodeData< Real , SliceSigs >::WriteSignatures( fs );
680 sliceTree->write( fs , false );
681 fs.write( state6.xForm );
682 solution.write( fs );
683 fclose( fp );
684 };
685 {
686 std::stringstream ss;
687 ss << "back." << i << ".tree";
688 WriteBoundary( ss.str() , backSliceTree , backSolution );
689 }
690 {
691 std::stringstream ss;
692 ss << "front." << i << ".tree";
693 WriteBoundary( ss.str() , frontSliceTree , frontSolution );
694 }
695 {
696 std::stringstream ss;
697 ss << "merged." << i << ".tree";
698 WriteBoundary( ss.str() , state6.sliceTree , state6.solution );
699 }
700 }
701 delete backSliceTree;
702 delete frontSliceTree;
703
704 phaseInfo.readBytes += clientStream0.ioBytes + clientStream1.ioBytes;
705 }
706
707 {
708 Timer timer;
709 using Factory = VertexFactory::EmptyFactory< Real >;
710 using Data = typename Factory::VertexType;
711 Factory factory;
712 const typename FEMTree< Dim-1 , Real >::template DensityEstimator< Reconstructor::WeightDegree > *density=NULL;
713 const SparseNodeData< ProjectiveData< Data , Real > , IsotropicUIntPack< Dim-1 , DataSig > > *data=NULL;
714 {
715 VectorBackedOutputDataStream< Point< Real , Dim-1 > > _vertexStream( state6.vertices );
716 using ExternalType = std::tuple< Point< Real , Dim-1 > , Point< Real , Dim-1 > , Real >;
717 using InternalType = std::tuple< Point< Real , Dim-1 > >;
718 auto converter = []( const ExternalType &xType )
719 {
720 InternalType iType;
721 std::get< 0 >( iType ) = std::get< 0 >( xType );
722 return iType;
723 };
724 OutputDataStreamConverter< InternalType , ExternalType > __vertexStream( _vertexStream , converter );
725
726 LevelSetExtractor< Real , Dim-1 >::SetSliceValues( SliceSigs() , UIntPack< Reconstructor::WeightDegree >() , *state6.sliceTree , clientReconInfo.reconstructionDepth , density , state6.solution , isoValue , __vertexStream , !clientReconInfo.linearFit , false , state6.sliceValues , LevelSetExtractor< Real , Dim-1 , Vertex >::SetIsoEdgesFlag() );
727 if( !clientReconInfo.linearFit ) LevelSetExtractor< Real , Dim-1 >::SetSliceValues( SliceSigs() , UIntPack< Reconstructor::WeightDegree >() , *state6.sliceTree , clientReconInfo.reconstructionDepth , density , state6.dSolution , isoValue , __vertexStream , false , false , state6.dSliceValues , LevelSetExtractor< Real , Dim-1 , Vertex >::SetCornerValuesFlag() );
728 }
729 sharedVertexCounts[i] = (unsigned int)state6.vertices.size();
730 phaseInfo.processTime += timer.wallTime();
731 }
732 profiler.update();
733
734 {
735 Timer timer;
736 ClientServerStream< false > clientStream0( _clientSockets[i+0] , i+0 , clientReconInfo , ClientReconstructionInfo< Real , Dim >::FRONT );
737 ClientServerStream< false > clientStream1( _clientSockets[i+1] , i+1 , clientReconInfo , ClientReconstructionInfo< Real , Dim >::BACK );
738 clientStream0.ioBytes = 0;
739 clientStream1.ioBytes = 0;
740 clientStream0.write( isoValue );
741 clientStream1.write( isoValue );
742 if( clientReconInfo.mergeType!=ClientReconstructionInfo< Real , Dim >::MergeType::NONE )
743 {
744 LevelSetExtractor< Real , Dim-1 >::TreeSliceValuesAndVertexPositions::Write( clientStream0 , state6.sliceTree , state6.xForm , state6.sliceValues , state6.vertices , true );
745 if( !clientReconInfo.linearFit )
746 {
747 for( unsigned int i=0 ; i<state6.dSliceValues.size() ; i++ )
748 {
749 clientStream0.write( state6.dSliceValues[i].cellIndices.counts[0] );
750 clientStream0.write( state6.dSliceValues[i].cornerValues , state6.dSliceValues[i].cellIndices.counts[0] );
751 }
752 }
753 LevelSetExtractor< Real , Dim-1 >::TreeSliceValuesAndVertexPositions::Write( clientStream1 , state6.sliceTree , state6.xForm , state6.sliceValues , state6.vertices , true );
754 if( !clientReconInfo.linearFit )
755 {
756 for( unsigned int i=0 ; i<state6.dSliceValues.size() ; i++ )
757 {
758 clientStream1.write( state6.dSliceValues[i].cellIndices.counts[0] );
759 clientStream1.write( state6.dSliceValues[i].cornerValues , state6.dSliceValues[i].cellIndices.counts[0] );
760 }
761 }
762 }
763 phaseInfo.writeBytes += clientStream0.ioBytes + clientStream1.ioBytes;
764 phaseInfo.writeTime += timer.wallTime();
765 }
766 profiler.update();
767 }
768
769 return phaseInfo;
770 }