Debian Codegraph @

src/thirdparty/PoissonRecon/FEMTree.System.inl

raw
1 /*
2 Copyright (c) 2006, Michael Kazhdan and Matthew Bolitho
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 ///////////////////////////////////
30 // BaseFEMIntegrator::Constraint //
31 ///////////////////////////////////
32 template< unsigned int ... TDegrees , unsigned int ... CDegrees , unsigned int CDim >
33 template< bool IterateFirst >
34 void BaseFEMIntegrator::Constraint< UIntPack< TDegrees ... > , UIntPack< CDegrees ... > , CDim >::setStencil( CCStencil & stencil ) const
35 {
36 static const int Dim = sizeof ... ( TDegrees );
37 int center = ( 1<<_highDepth )>>1;
38 int femOffset[Dim] , cOffset[Dim];
39 static const int overlapStart[] = { ( IterateFirst ? BSplineOverlapSizes< CDegrees , TDegrees >::OverlapStart : BSplineOverlapSizes< TDegrees , CDegrees >::OverlapStart ) ... };
40 if( IterateFirst )
41 {
42 for( int d=0 ; d<Dim ; d++ ) cOffset[d] = center;
43 WindowLoop< Dim >::Run( IsotropicUIntPack< Dim , 0 >() , UIntPack< BSplineOverlapSizes< TDegrees , CDegrees >::OverlapSize ... >() , [&]( int d , int i ){ femOffset[d] = i + center + overlapStart[d]; } , [&]( Point< double , CDim >& p ){ p = ccIntegrate( femOffset , cOffset ); } , stencil() );
44 }
45 else
46 {
47 for( int d=0 ; d<Dim ; d++ ) femOffset[d] = center;
48 WindowLoop< Dim >::Run( IsotropicUIntPack< Dim , 0 >() , UIntPack< BSplineOverlapSizes< TDegrees , CDegrees >::OverlapSize ... >() , [&]( int d , int i ){ cOffset[d] = i + center + overlapStart[d]; } , [&]( Point< double , CDim >& p ){ p = ccIntegrate( femOffset , cOffset );} , stencil() );
49 }
50 }
51 template< unsigned int ... TDegrees , unsigned int ... CDegrees , unsigned int CDim >
52 template< bool IterateFirst >
53 void BaseFEMIntegrator::Constraint< UIntPack< TDegrees ... > , UIntPack< CDegrees ... > , CDim >::setStencils( PCStencils& stencils ) const
54 {
55 static const int Dim = sizeof ... ( TDegrees );
56 typedef UIntPack< BSplineOverlapSizes< TDegrees, CDegrees >::OverlapSize ... > OverlapSizes;
57 // [NOTE] We want the center to be at the first node of the brood, which is not the case when childDepth is 1.
58 int center = ( 1<<_highDepth )>>1 ; center = ( center>>1 )<<1;
59 int fineCenter[Dim] , femOffset[Dim] , cOffset[Dim];
60 static const int overlapStart[] = { ( IterateFirst ? BSplineOverlapSizes< CDegrees , TDegrees >::OverlapStart : BSplineOverlapSizes< TDegrees , CDegrees >::OverlapStart ) ... };
61 std::function< void ( int , int ) > outerUpdateState = [&]( int d , int i ){ fineCenter[Dim-d-1] = i+center; };
62 std::function< void ( Point< double , CDim >& ) > innerFunction = [&]( Point< double , CDim >& p ){ p = pcIntegrate( femOffset , cOffset ); };
63 std::function< void ( int , int ) > innerUpdateState = [&]( int d , int i ){ femOffset[d] = IterateFirst ? (i+center/2+overlapStart[d]) : center/2 , cOffset[d] = IterateFirst ? fineCenter[d] : (i+fineCenter[d]+overlapStart[d]); };
64 std::function< void ( CCStencil& ) > outerFunction = [&]( CCStencil& s )
65 {
66 WindowLoop< Dim >::Run( IsotropicUIntPack< Dim , 0 >() , OverlapSizes() , innerUpdateState , innerFunction , s() );
67 };
68 WindowLoop< Dim >::Run( IsotropicUIntPack< Dim , 0 >() , IsotropicUIntPack< Dim , 2 >() , outerUpdateState , outerFunction , stencils() );
69 }
70 template< unsigned int ... TDegrees , unsigned int ... CDegrees , unsigned int CDim >
71 template< bool IterateFirst >
72 void BaseFEMIntegrator::Constraint< UIntPack< TDegrees ... > , UIntPack< CDegrees ... > , CDim >::setStencils( CPStencils& stencils ) const
73 {
74 static const int Dim = sizeof ... ( TDegrees );
75 typedef UIntPack< BSplineOverlapSizes< TDegrees , CDegrees >::OverlapSize ... > OverlapSizes;
76 // [NOTE] We want the center to be at the first node of the brood, which is not the case when childDepth is 1.
77 int center = ( 1<<_highDepth )>>1 ; center = ( center>>1 )<<1;
78 static const int overlapStart[] = { ( IterateFirst ? BSplineOverlapSizes< CDegrees , TDegrees >::OverlapStart : BSplineOverlapSizes< TDegrees , CDegrees >::OverlapStart ) ... };
79 int fineCenter[Dim] , femOffset[Dim] , cOffset[Dim];
80 std::function< void ( int , int ) > outerUpdateState = [&]( int d , int i ){ fineCenter[Dim-d-1] = i+center; };
81 std::function< void ( Point< double , CDim >& ) > innerFunction = [&]( Point< double , CDim >& p ){ p = cpIntegrate( femOffset , cOffset ); };
82 std::function< void ( int , int ) > innerUpdateState = [&]( int d , int i ){ femOffset[d] = IterateFirst ? (i+fineCenter[d]+overlapStart[d]) : fineCenter[d] , cOffset[d] = IterateFirst ? center/2 : (i+center/2+overlapStart[d]); };
83 std::function< void ( CCStencil& ) > outerFunction = [&]( CCStencil& s )
84 {
85 WindowLoop< Dim >::Run( IsotropicUIntPack< Dim , 0 >() , OverlapSizes() , innerUpdateState , innerFunction , s() );
86 };
87 WindowLoop< Dim >::Run( IsotropicUIntPack< Dim , 0 >() , IsotropicUIntPack< Dim , 2 >() , outerUpdateState , outerFunction , stencils() );
88 }
89
90 ///////////////////////////////
91 // BaseFEMIntegrator::System //
92 ///////////////////////////////
93 template< unsigned int ... TDegrees >
94 template< bool IterateFirst >
95 void BaseFEMIntegrator::System< UIntPack< TDegrees ... > >::setStencil( CCStencil & stencil ) const
96 {
97 static const int Dim = sizeof ... ( TDegrees );
98 int center = ( 1<<_highDepth )>>1;
99 int offset1[Dim] , offset2[Dim];
100 static const int overlapStart[] = { BSplineOverlapSizes< TDegrees , TDegrees >::OverlapStart ... };
101 if( IterateFirst )
102 {
103 for( int d=0 ; d<Dim ; d++ ) offset2[d] = center;
104 WindowLoop< Dim >::Run( IsotropicUIntPack< Dim , 0 >() , UIntPack< BSplineOverlapSizes< TDegrees , TDegrees >::OverlapSize ... >() , [&]( int d , int i ){ offset1[d] = i + center + overlapStart[d]; } , [&]( double& v ){ v = ccIntegrate( offset1 , offset2 ); } , stencil() );
105 }
106 else
107 {
108 for( int d=0 ; d<Dim ; d++ ) offset1[d] = center;
109 WindowLoop< Dim >::Run( IsotropicUIntPack< Dim , 0 >() , UIntPack< BSplineOverlapSizes< TDegrees , TDegrees >::OverlapSize ... >() , [&]( int d , int i ){ offset2[d] = i + center + overlapStart[d]; } , [&]( double& v ){ v = ccIntegrate( offset1 , offset2 ); } , stencil() );
110 }
111 }
112 template< unsigned int ... TDegrees >
113 template< bool IterateFirst >
114 void BaseFEMIntegrator::System< UIntPack< TDegrees ... > >::setStencils( PCStencils& stencils ) const
115 {
116 static const int Dim = sizeof ... ( TDegrees );
117 typedef UIntPack< BSplineOverlapSizes< TDegrees , TDegrees >::OverlapSize ... > OverlapSizes;
118 // [NOTE] We want the center to be at the first node of the brood
119 // Which is not the case when childDepth is 1.
120 int center = ( 1<<_highDepth )>>1 ; center = ( center>>1 )<<1;
121 static const int overlapStart[] = { BSplineOverlapSizes< TDegrees , TDegrees >::OverlapStart ... };
122 int fineCenter[Dim] , offset1[Dim] , offset2[Dim];
123 std::function< void ( int , int ) > outerUpdateState = [&]( int d , int i ){ fineCenter[Dim-d-1] = i+center; };
124 std::function< void ( double& ) > innerFunction = [&]( double& v ){ v = pcIntegrate( offset1 , offset2 ); };
125 std::function< void ( int , int ) > innerUpdateState = [&]( int d , int i ){ offset1[d] = IterateFirst ? (i+center/2+overlapStart[d]) : center/2 , offset2[d] = IterateFirst ? fineCenter[d] : (i+fineCenter[d]+overlapStart[d]); };
126 std::function< void ( CCStencil& ) > outerFunction = [&]( CCStencil& s )
127 {
128 WindowLoop< Dim >::Run( IsotropicUIntPack< Dim , 0 >() , OverlapSizes() , innerUpdateState , innerFunction , s() );
129 };
130 WindowLoop< Dim >::Run( IsotropicUIntPack< Dim , 0 >() , IsotropicUIntPack< Dim , 2 >() , outerUpdateState , outerFunction , stencils() );
131 }
132 /////////////////////////////////
133 // BaseFEMIntegrator::UpSample //
134 /////////////////////////////////
135 template< unsigned int ... TDegrees >
136 void BaseFEMIntegrator::RestrictionProlongation< UIntPack< TDegrees ... > >::setStencil( UpSampleStencil & stencil ) const
137 {
138 static constexpr int Dim = sizeof ... ( TDegrees );
139 int highCenter = ( 1<<_highDepth )>>1;
140 int pOff[Dim] , cOff[Dim];
141 static const int upSampleStart[] = { BSplineSupportSizes< TDegrees >::UpSampleStart ... };
142 for( int d=0 ; d<Dim ; d++ ) pOff[d] = highCenter/2;
143 WindowLoop< Dim >::Run( IsotropicUIntPack< Dim , 0 >() , UIntPack< BSplineSupportSizes< TDegrees >::UpSampleSize ... >() , [&]( int d , int i ){ cOff[d] = i + highCenter + upSampleStart[d]; } , [&]( double& v ){ v = upSampleCoefficient( pOff , cOff ); } , stencil() );
144 }
145 template< unsigned int ... TDegrees >
146 void BaseFEMIntegrator::RestrictionProlongation< UIntPack< TDegrees ... > >::setStencils( DownSampleStencils& stencils ) const
147 {
148 static constexpr int Dim = sizeof ... ( TDegrees );
149 // [NOTE] We want the center to be at the first node of the brood, which is not the case when childDepth is 1.
150 int highCenter = ( 1<<_highDepth )>>1 ; highCenter = ( highCenter>>1 )<<1;
151 int pOff[Dim] , cOff[Dim];
152 static const int offsets[] = { BSplineSupportSizes< TDegrees >::DownSample0Start ... };
153 std::function< void ( double& ) > innerFunction = [&]( double& v ){ v = upSampleCoefficient( pOff , cOff ); };
154 std::function< void ( int , int ) > innerUpdateState = [&]( int d , int i ){ pOff[d] = cOff[d]/2 + i + offsets[d]; };
155 std::function< void ( int , int ) > outerUpdateState = [&]( int d , int i ){ cOff[Dim-d-1] = i+highCenter; };
156 std::function< void ( DownSampleStencil& ) > outerFunction = [&]( DownSampleStencil& s )
157 {
158 WindowLoop< Dim >::Run( IsotropicUIntPack< Dim , 0 >() , UIntPack< ( - BSplineSupportSizes< TDegrees >::DownSample0Start + BSplineSupportSizes< TDegrees >::DownSample1End + 1 ) ... >() , innerUpdateState , innerFunction , s() );
159 };
160 WindowLoop< Dim >::Run( IsotropicUIntPack< Dim , 0 >() , IsotropicUIntPack< Dim , 2 >() , outerUpdateState , outerFunction , stencils() );
161 }
162
163 ///////////////////////////////
164 // FEMIntegrator::Constraint //
165 ///////////////////////////////
166
167 template< unsigned int ... TSignatures , unsigned int ... TDerivatives , unsigned int ... CSignatures , unsigned int ... CDerivatives , unsigned int CDim >
168 Point< double , CDim > FEMIntegrator::Constraint< UIntPack< TSignatures ... > , UIntPack< TDerivatives ... > , UIntPack< CSignatures ... > , UIntPack< CDerivatives ... > , CDim >::_integrate( IntegrationType iType , const int off1[] , const int off2[] ) const
169 {
170 Point< double , CDim > integral;
171 for( unsigned int i=0 ; i<_weightedIndices.size() ; i++ )
172 {
173 const _WeightedIndices& w = _weightedIndices[i];
174 unsigned int _d1[Dim] , _d2[Dim];
175 TFactorDerivatives( w.d1 , _d1 );
176 CFactorDerivatives( w.d2 , _d2 );
177 double __integral = _integral( iType , off1 , off2 , _d1 , _d2 );
178 for( unsigned int j=0 ; j<w.indices.size() ; j++ ) integral[ w.indices[j].first ] += w.indices[j].second * __integral;
179 }
180 return integral;
181 }
182
183 #ifndef PR_MODULO
184 #define PR_MODULO( a , b ) ( (a)>0 ? (a) % (b) : ( (b) - ( -(a) % (b) ) ) % (b) )
185 #endif // PR_MODULO
186
187 /////////////
188 // FEMTree //
189 /////////////
190 template< unsigned int Dim , class Real >
191 template< unsigned int ... FEMSigs >
192 void FEMTree< Dim , Real >::setMultiColorIndices( UIntPack< FEMSigs ... > , int depth , std::vector< std::vector< size_t > >& indices ) const
193 {
194 _setMultiColorIndices( UIntPack< FEMSigs ... >() , _sNodesBegin(depth) , _sNodesEnd(depth) , indices );
195 }
196 template< unsigned int Dim , class Real >
197 template< unsigned int ... FEMSigs >
198 void FEMTree< Dim , Real >::_setMultiColorIndices( UIntPack< FEMSigs ... > , node_index_type start , node_index_type end , std::vector< std::vector< size_t > >& indices ) const
199 {
200 _setFEM1ValidityFlags( UIntPack< FEMSigs ... >() );
201 typedef UIntPack< ( 1 - BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree , FEMSignature< FEMSigs >::Degree >::OverlapStart ) ... > Moduli;
202 static const unsigned int Colors = WindowSize< Moduli >::Size;
203 indices.resize( Colors );
204 struct ColorCount
205 {
206 size_t count[ Colors ];
207 ColorCount( void ){ memset( count , 0 , sizeof(count) ); }
208 };
209 std::vector< ColorCount > counts( ThreadPool::NumThreads() );
210 size_t count[ Colors ];
211 memset( count , 0 , sizeof(count) );
212 auto MCIndex = [&] ( const FEMTreeNode* node )
213 {
214 LocalDepth d ; LocalOffset off ; _localDepthAndOffset( node , d , off );
215 int index = 0;
216 for( int dd=0 ; dd<Dim ; dd++ ) index = index * Moduli::Values[Dim-dd-1] + PR_MODULO( off[Dim-dd-1] , Moduli::Values[Dim-dd-1] );
217 return index;
218 };
219 ThreadPool::ParallelFor( start , end , [&]( unsigned int thread , size_t i )
220 {
221 if( _isValidFEM1Node( _sNodes.treeNodes[i] ) )
222 {
223 int idx = MCIndex( _sNodes.treeNodes[i] );
224 counts[thread].count[idx]++;
225 }
226 }
227 );
228 for( size_t t=0 ; t<counts.size() ; t++ ) for( int i=0 ; i<Colors ; i++) count[i] += counts[t].count[i];
229
230 for( int i=0 ; i<Colors ; i++ ) indices[i].reserve( count[i] ) , count[i]=0;
231
232 for( node_index_type i=start ; i<end ; i++ ) if( _isValidFEM1Node( _sNodes.treeNodes[i] ) )
233 {
234 int idx = MCIndex( _sNodes.treeNodes[i] );
235 indices[idx].push_back( i - start );
236 }
237 }
238
239 template< unsigned int Dim , class Real >
240 template< unsigned int ... FEMSigs , typename T , typename TDotT , typename SORWeights , typename ... InterpolationInfos >
241 int FEMTree< Dim , Real >::_solveFullSystemGS( UIntPack< FEMSigs ... > , const typename BaseFEMIntegrator::System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , LocalDepth depth , Pointer( T ) solution , ConstPointer( T ) prolongedSolution , ConstPointer( T ) constraints , TDotT Dot , int iters , bool coarseToFine , SORWeights sorWeights , _SolverStats& stats , bool computeNorms , std::tuple< InterpolationInfos *... > interpolationInfos ) const
242 {
243 double& systemTime = stats.systemTime;
244 double& solveTime = stats. solveTime;
245 systemTime = solveTime = 0.;
246
247 CCStencil< UIntPack< FEMSignature< FEMSigs >::Degree ... > > ccStencil;
248 PCStencils< UIntPack< FEMSignature< FEMSigs >::Degree ... > > pcStencils;
249 F.template setStencil< false >( ccStencil );
250 F.template setStencils< true >( pcStencils );
251 double bNorm=0 , inRNorm=0 , outRNorm=0;
252 if( depth>=0 )
253 {
254 SystemMatrixType< FEMSigs ... > M;
255 double t = Time();
256 Pointer( Real ) D = AllocPointer< Real >( _sNodesEnd( depth ) - _sNodesBegin( depth ) );
257 Pointer( T ) _constraints = AllocPointer< T >( _sNodesSize( depth ) );
258 _getSliceMatrixAndProlongationConstraints( UIntPack< FEMSigs ... >() , F , M , D , bsData , depth , _sNodesBegin( depth ) , _sNodesEnd( depth ) , prolongedSolution , _constraints , ccStencil , pcStencils , interpolationInfos );
259 ThreadPool::ParallelFor( _sNodesBegin(depth) , _sNodesEnd(depth) , [&]( unsigned int , size_t i ){ _constraints[ i - _sNodesBegin(depth) ] = constraints[ _sNodes.treeNodes[i]->nodeData.nodeIndex ] - _constraints[ i - _sNodesBegin(depth) ]; } );
260 {
261 node_index_type begin = _sNodesBegin( depth ) , end = _sNodesEnd( depth );
262 for( node_index_type i=begin ; i<end ; i++ ) if( M.rowSize( i-begin ) ) D[i-begin] *= sorWeights[i];
263 }
264
265 systemTime += Time()-t;
266 // The list of multi-colored indices for each in-memory slice
267 std::vector< std::vector< size_t > > mcIndices;
268 _setMultiColorIndices( UIntPack< FEMSigs ... >() , _sNodesBegin( depth ) , _sNodesEnd( depth ) , mcIndices );
269
270 ConstPointer( T ) B = _constraints;
271 Pointer( T ) X = GetPointer( &solution[0] + _sNodesBegin( depth ) , _sNodesSize( depth ) );
272 if( computeNorms )
273 {
274 std::vector< double > bNorms( ThreadPool::NumThreads() , 0 ) , inRNorms( ThreadPool::NumThreads() , 0 );
275 ThreadPool::ParallelFor( 0 , M.rows() , [&]( unsigned int thread , size_t j )
276 {
277 T temp = {};
278 ConstPointer( MatrixEntry< Real , matrix_index_type > ) start = M[j];
279 ConstPointer( MatrixEntry< Real , matrix_index_type > ) end = start + M.rowSize(j);
280 ConstPointer( MatrixEntry< Real , matrix_index_type > ) e;
281 for( e=start ; e!=end ; e++ ) temp += X[ e->N ] * e->Value;
282 bNorms[thread] += Dot( B[j] , B[j] );
283 inRNorms[thread] += Dot( temp - B[j] , temp - B[j] );
284 }
285 );
286 for( unsigned int t=0 ; t<ThreadPool::NumThreads() ; t++ ) bNorm += bNorms[t] , inRNorm += inRNorms[t];
287 }
288
289 t = Time();
290 for( int i=0 ; i<iters ; i++ ) M.gsIteration( mcIndices , ( ConstPointer( Real ) )D , B , X , coarseToFine , true );
291 FreePointer( D );
292 solveTime += Time() - t;
293
294 if( computeNorms )
295 {
296 std::vector< double > outRNorms( ThreadPool::NumThreads() , 0 );
297 ThreadPool::ParallelFor( 0 , M.rows() , [&]( unsigned int thread , size_t j )
298 {
299 T temp = {};
300 ConstPointer( MatrixEntry< Real , matrix_index_type > ) start = M[j];
301 ConstPointer( MatrixEntry< Real , matrix_index_type > ) end = start + M.rowSize(j);
302 ConstPointer( MatrixEntry< Real , matrix_index_type > ) e;
303 for( e=start ; e!=end ; e++ ) temp += X[ e->N ] * e->Value;
304 outRNorms[thread] += Dot( temp-B[j] , temp-B[j] );
305 }
306 );
307 for( unsigned int t=0 ; t<ThreadPool::NumThreads() ; t++ ) outRNorm += outRNorms[t];
308 }
309 FreePointer( _constraints );
310 }
311 if( computeNorms ) stats.bNorm2 = bNorm , stats.inRNorm2 = inRNorm , stats.outRNorm2 = outRNorm;
312
313 return iters;
314 }
315 template< unsigned int Dim , class Real >
316 template< unsigned int ... FEMSigs , typename T , typename TDotT , typename SORWeights , typename ... InterpolationInfos >
317 int FEMTree< Dim , Real >::_solveSlicedSystemGS( UIntPack< FEMSigs ... > , const typename BaseFEMIntegrator::System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , LocalDepth depth , Pointer( T ) solution , ConstPointer( T ) prolongedSolution , ConstPointer( T ) constraints , TDotT Dot , int iters , bool coarseToFine , unsigned int sliceBlockSize , SORWeights sorWeights , _SolverStats& stats , bool computeNorms , std::tuple< InterpolationInfos *... > interpolationInfos ) const
318 {
319 if( sliceBlockSize<=0 ) return _solveFullSystemGS( UIntPack< FEMSigs ... >() , F , bsData , depth , solution , prolongedSolution , constraints , Dot , iters , coarseToFine , sorWeights , stats , computeNorms , interpolationInfos );
320 CCStencil< UIntPack< FEMSignature< FEMSigs >::Degree ... > > ccStencil;
321 PCStencils< UIntPack< FEMSignature< FEMSigs >::Degree ... > > pcStencils;
322 F.template setStencil< false >( ccStencil );
323 F.template setStencils< true >( pcStencils );
324
325 {
326 // Assuming Degree=2 and we are solving forward using two iterations, the pattern of relaxations should look like:
327 // +--+--+--+--+--+
328 // * | | | | |
329 // o| | | | | |
330 // o | | | | | |
331 // o | | | | | |
332 // o | | | | | |
333 // o | | | | | |
334 // | * | | | |
335 // | *| | | | |
336 // |* | | | | |
337 // * | | | | |
338 // o| | | | | |
339 // o | | | | | |
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 // | | | | | | o
366 // | | | | | | o
367 // | | | | | |o
368 // | | | | | *
369 // | | | | | *|
370 // | | | | |* |
371
372 const int SliceBlockSize = (int)sliceBlockSize;
373 // OverlapRadius = Degree
374 const int OverlapRadii[] = { ( -BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapStart ) ... };
375 const int OverlapBlockRadius = ( OverlapRadii[Dim-1] + SliceBlockSize - 1 ) / SliceBlockSize;
376 static const int LastFEMSig = UIntPack< FEMSigs ... >::template Get< Dim-1 >();
377 int _sliceBegin = _BSplineBegin< LastFEMSig >( depth ) , _sliceEnd = _BSplineEnd< LastFEMSig >( depth );
378
379 int blockBegin = ( _sliceBegin - ( SliceBlockSize - 1 ) ) / SliceBlockSize , blockEnd = ( _sliceEnd + ( SliceBlockSize - 1 ) ) / SliceBlockSize;
380 std::function< int ( int ) > BlockFirst = [&]( int b ){ return std::max< int >( b * SliceBlockSize , _sliceBegin ); };
381 std::function< int ( int ) > BlockLast = [&]( int b ){ return std::min< int >( b * SliceBlockSize + SliceBlockSize - 1 , _sliceEnd - 1 ); };
382
383 auto BBlock = [&]( int d , int b , ConstPointer( T ) B )
384 {
385 return GetPointer( &B[0] + _sNodesBegin( d , BlockFirst( b ) ) , _sNodesEnd( d , BlockLast( b ) ) - _sNodesBegin( d , BlockFirst( b ) ) );
386 };
387 auto XBlocks = [&]( int d , int b , Pointer( T ) X )
388 {
389 return GetPointer( &X[0] + _sNodesBegin( d , BlockFirst( b ) ) , _sNodesBegin( d , BlockFirst( b - OverlapBlockRadius ) ) - _sNodesBegin( d , BlockFirst( b ) ) , _sNodesEnd( d , BlockLast( b + OverlapBlockRadius ) ) - _sNodesBegin( d , BlockFirst( b ) ) );
390 };
391
392 double& systemTime = stats.systemTime;
393 double& solveTime = stats. solveTime;
394 systemTime = solveTime = 0.;
395
396 struct BlockWindow
397 {
398 protected:
399 int _begin , _end;
400 public:
401 BlockWindow( int begin , int end )
402 {
403 if( begin<=end ) _begin = begin , _end = end;
404 else _begin = end+1 , _end = begin+1;
405 }
406 int size( void ) const { return _end-_begin; }
407 BlockWindow& operator += ( int off ){ _begin += off , _end += off ; return *this; }
408 BlockWindow& operator -= ( int off ){ _begin -= off , _end -= off ; return *this; }
409 BlockWindow& operator++ ( void ){ _begin++ , _end++ ; return *this; }
410 BlockWindow& operator-- ( void ){ _begin-- , _end-- ; return *this; }
411 int begin( bool forward ) const { return forward ? _begin : _end-1; }
412 int end ( bool forward ) const { return forward ? _end : _begin-1; }
413 bool inBlock( int b ) const { return b>=_begin && b<_end; }
414 };
415 double bNorm=0 , inRNorm=0 , outRNorm=0;
416 bool forward = !coarseToFine;
417 int residualOffset = computeNorms ? OverlapBlockRadius : 0;
418 // Set the number of in-memory blocks required for a temporally blocked solver
419 const int ColorModulus = OverlapBlockRadius;
420 // The number of in-core blocks over which we relax
421 // [WARNING] If the block size is larger than one, we may be able to use fewer blocks
422 int solveBlocks = std::max< int >( 0 , std::min< int >( ColorModulus*iters - ( ColorModulus-1 ) , blockEnd-blockBegin ) );
423 // The number of in-core blocks over which we either solve or compute residuals
424 int matrixBlocks = std::max< int >( 1 , std::min< int >( solveBlocks+2*residualOffset , blockEnd-blockBegin ) );
425 // The list of matrices for each in-memory block
426 Pointer( SystemMatrixType< FEMSigs ... > ) _M = NewPointer< SystemMatrixType< FEMSigs ... > >( matrixBlocks );
427 Pointer( Pointer( Real ) ) _D = AllocPointer< Pointer( Real ) >( matrixBlocks );
428 std::vector< Pointer( T ) > _constraints( matrixBlocks );
429 for( int i=0 ; i<matrixBlocks ; i++ ) _D[i] = NullPointer( Real ) , _constraints[i] = NullPointer( T );
430 // The list of multi-colored indices for each in-memory block
431 Pointer( std::vector< std::vector< size_t > > ) mcIndices = NewPointer< std::vector< std::vector< size_t > > >( solveBlocks );
432 int dir = forward ? 1 : -1 , start = forward ? blockBegin : blockEnd-1 , end = forward ? blockEnd : blockBegin-1;
433 const BlockWindow FullWindow( blockBegin , blockEnd );
434 BlockWindow residualWindow( FullWindow.begin(forward) , FullWindow.begin(forward) - ( ColorModulus*iters - ( ColorModulus-1 ) ) * dir - 2*residualOffset*dir );
435 BlockWindow solveWindow( FullWindow.begin(forward) - residualOffset*dir , FullWindow.begin(forward) - residualOffset*dir - ( ColorModulus*iters - ( ColorModulus-1 ) ) * dir );
436 // If we are solving forward we start in a block S with S mod ColorModulus = ColorModulus-1
437 // and end in a block E with E mod ColorModulus = 0
438 while( PR_MODULO( solveWindow.begin(!forward) , ColorModulus )!=( forward ? ColorModulus-1 : 0 ) ) solveWindow -= dir , residualWindow -= dir;
439 size_t maxBlockSize = 0;
440 BlockWindow _residualWindow = residualWindow;
441 for( ; _residualWindow.end(!forward)*dir<FullWindow.end(forward)*dir ; _residualWindow += dir )
442 {
443 int b = _residualWindow.begin(!forward);
444 if( FullWindow.inBlock( b ) ) maxBlockSize = std::max< size_t >( maxBlockSize , _sNodesEnd( depth , BlockLast( b ) ) - _sNodesBegin( depth , BlockFirst( b ) ) );
445 }
446 if( maxBlockSize>std::numeric_limits< matrix_index_type >::max() ) MK_THROW( "more entries in a block than can be indexed in " , sizeof(matrix_index_type) , " bytes" );
447 for( int i=0 ; i<matrixBlocks ; i++ ) _constraints[i] = AllocPointer< T >( maxBlockSize ) , _D[i] = AllocPointer< Real >( maxBlockSize );
448 for( ; residualWindow.end(!forward)*dir<FullWindow.end(forward)*dir ; residualWindow += dir , solveWindow += dir )
449 {
450 double t;
451 {
452 int frontSolveBlock = solveWindow.begin(!forward);
453 int residualBlock = residualWindow.begin(!forward);
454 // Get the leading matrix and compute the constraint norm / initial residual
455 // [WARNNG] This is likely wrong. We probably have to pull this into its own for "for( int _c=0 ; _c<ColorModulus ; _c++ )" loop
456 // to ensure that adjacent read-only blocks have not been updated yet.
457 if( FullWindow.inBlock( residualBlock ) )
458 {
459 int b = residualBlock , _b = PR_MODULO( b , matrixBlocks );
460
461 t = Time();
462 _getSliceMatrixAndProlongationConstraints( UIntPack< FEMSigs ... >() , F , _M[_b] , _D[_b] , bsData , depth , _sNodesBegin( depth , BlockFirst( b ) ) , _sNodesEnd( depth , BlockLast( b ) ) , prolongedSolution , _constraints[_b] , ccStencil , pcStencils , interpolationInfos );
463 size_t begin = _sNodesBegin( depth , BlockFirst( b ) ) , end = _sNodesEnd( depth , BlockLast( b ) );
464 ThreadPool::ParallelFor( begin , end , [&]( unsigned int , size_t i ){ _constraints[_b][ i-begin ] = constraints[i] - _constraints[_b][ i-begin ]; } );
465 {
466 node_index_type begin = _sNodesBegin( depth , BlockFirst( b ) ) , end = _sNodesEnd( depth , BlockLast( b ) );
467 for( node_index_type i=begin ; i<end ; i++ ) if( _M[_b].rowSize( i-begin ) ) _D[_b][i-begin] *= sorWeights[i];
468 }
469 systemTime += Time()-t;
470 if( computeNorms )
471 {
472 ConstPointer( T ) B = _constraints[_b];
473 ConstPointer( T ) X = XBlocks( depth , b , solution );
474 std::vector< double > bNorms( ThreadPool::NumThreads() , 0 ) , inRNorms( ThreadPool::NumThreads() , 0 );
475 ThreadPool::ParallelFor( 0 , _M[_b].rows() , [&]( unsigned int thread , size_t j )
476 {
477 T temp = {};
478 ConstPointer( MatrixEntry< Real , matrix_index_type > ) start = _M[_b][j];
479 ConstPointer( MatrixEntry< Real , matrix_index_type > ) end = start + _M[_b].rowSize(j);
480 ConstPointer( MatrixEntry< Real , matrix_index_type > ) e;
481 for( e=start ; e!=end ; e++ ) temp += X[ e->N ] * e->Value;
482 bNorms[thread] += Dot( B[j] , B[j] );
483 inRNorms[thread] += Dot( temp - B[j] , temp - B[j] );
484 }
485 );
486 for( unsigned int t=0 ; t<ThreadPool::NumThreads() ; t++ ) bNorm += bNorms[t] , inRNorm += inRNorms[t];
487 }
488 }
489 t = Time();
490 // Get the leading multi-color indices
491 if( iters && FullWindow.inBlock( frontSolveBlock ) )
492 {
493 int b = frontSolveBlock , _b = PR_MODULO( b , matrixBlocks ) , __b = PR_MODULO( b , solveBlocks );
494 for( int i=0 ; i<int( mcIndices[__b].size() ) ; i++ ) mcIndices[__b][i].clear();
495 _setMultiColorIndices( UIntPack< FEMSigs ... >() , _sNodesBegin( depth , BlockFirst( b ) ) , _sNodesEnd( depth , BlockLast( b ) ) , mcIndices[__b] );
496 }
497 }
498
499 // Relax the system
500 for( int block=solveWindow.begin(!forward) ; solveWindow.inBlock(block) ; block-=dir*ColorModulus ) if( FullWindow.inBlock( block ) )
501 {
502 int b = block , _b = PR_MODULO( b , matrixBlocks ) , __b = PR_MODULO( b , solveBlocks );
503 ConstPointer( T ) B = _constraints[_b];
504 Pointer( T ) X = XBlocks( depth , b , solution );
505 _M[_b].gsIteration( mcIndices[__b] , ( ConstPointer( Real ) )_D[_b] , B , X , coarseToFine , true );
506 }
507 solveTime += Time() - t;
508
509 // Compute the final residual
510 {
511 int residualBlock = residualWindow.begin(forward);
512 if( computeNorms && FullWindow.inBlock( residualBlock ) )
513 {
514 int b = residualBlock , _b = PR_MODULO( b , matrixBlocks );
515 ConstPointer( T ) B = _constraints[_b];
516 ConstPointer( T ) X = XBlocks( depth , b , solution );
517 std::vector< double > outRNorms( ThreadPool::NumThreads() , 0 );
518 ThreadPool::ParallelFor( 0 , _M[_b].rows() , [&]( unsigned int thread , size_t j )
519 {
520 T temp = {};
521 ConstPointer( MatrixEntry< Real , matrix_index_type > ) start = _M[_b][j];
522 ConstPointer( MatrixEntry< Real , matrix_index_type > ) end = start + _M[_b].rowSize(j);
523 ConstPointer( MatrixEntry< Real , matrix_index_type > ) e;
524 for( e=start ; e!=end ; e++ ) temp += X[ e->N ] * e->Value;
525 outRNorms[thread] += Dot( temp-B[j] , temp-B[j] );
526 }
527 );
528 for( unsigned int t=0 ; t<ThreadPool::NumThreads() ; t++ ) outRNorm += outRNorms[t];
529 }
530 }
531 }
532 for( int i=0 ; i<matrixBlocks ; i++ ) FreePointer( _D[i] );
533 for( int i=0 ; i<matrixBlocks ; i++ ) FreePointer( _constraints[i] );
534
535 if( computeNorms ) stats.bNorm2 = bNorm , stats.inRNorm2 = inRNorm , stats.outRNorm2 = outRNorm;
536 DeletePointer( _M );
537 DeletePointer( mcIndices );
538 FreePointer( _D );
539 }
540 return iters;
541 }
542 #undef PR_MODULO
543
544 template< unsigned int Dim , class Real >
545 template< unsigned int ... FEMSigs , typename T , typename TDotT , typename ... InterpolationInfos >
546 int FEMTree< Dim , Real >::_solveSystemCG( UIntPack< FEMSigs ... > , const typename BaseFEMIntegrator::System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , LocalDepth depth , Pointer( T ) solution , ConstPointer( T ) prolongedSolution , ConstPointer( T ) constraints , TDotT Dot , int iters , bool coarseToFine , _SolverStats& stats , bool computeNorms , double accuracy , std::tuple< InterpolationInfos *... > interpolationInfos ) const
547 {
548 int iter = 0;
549 Pointer( T ) X = GetPointer( &solution[0] + _sNodesBegin(depth) , _sNodesSize(depth) );
550 ConstPointer( T ) B = GetPointer( &constraints[0] + _sNodesBegin(depth) , _sNodesSize(depth) );
551 SystemMatrixType< FEMSigs ... > M;
552
553 double& systemTime = stats.systemTime;
554 double& solveTime = stats. solveTime;
555 systemTime = solveTime = 0.;
556 // Get the system matrix (and adjust the right-hand-side based on the coarser solution if prolonging)
557 systemTime = Time();
558 Pointer( T ) _constraints = AllocPointer< T >( _sNodesSize( depth ) );
559 B = _constraints;
560 CCStencil< UIntPack< FEMSignature< FEMSigs >::Degree ... > > ccStencil;
561 PCStencils< UIntPack< FEMSignature< FEMSigs >::Degree ... > > pcStencils;
562 F.template setStencil< false >( ccStencil );
563 F.template setStencils< true >( pcStencils );
564 _getSliceMatrixAndProlongationConstraints( UIntPack< FEMSigs ... >() , F , M , NullPointer( Real ) , bsData , depth , _sNodesBegin( depth ) , _sNodesEnd( depth ) , prolongedSolution , _constraints , ccStencil , pcStencils , interpolationInfos );
565 ThreadPool::ParallelFor( _sNodesBegin(depth) , _sNodesEnd(depth) , [&]( unsigned int , size_t i ){ _constraints[ i - _sNodesBegin(depth) ] = constraints[i] - _constraints[ i - _sNodesBegin(depth) ]; } );
566 systemTime = Time()-systemTime;
567 solveTime = Time();
568 // Solve the linear system
569 accuracy = Real( accuracy / 100000 ) * M.rows();
570 int dims[] = { ( _BSplineEnd< FEMSigs >( depth ) - _BSplineBegin< FEMSigs >( depth ) ) ... };
571 size_t nonZeroRows = 0;
572 for( matrix_index_type i=0 ; i<(matrix_index_type)M.rows() ; i++ ) if( M.rowSize(i) ) nonZeroRows++;
573 size_t totalDim = 1;
574 for( int d=0 ; d<Dim ; d++ ) totalDim *= dims[d];
575 BoundaryType bTypes[] = { FEMSignature< FEMSigs >::BType ... };
576 bool hasPartitionOfUnity = true;
577 for( int d=0 ; d<Dim ; d++ ) hasPartitionOfUnity &= HasPartitionOfUnity( bTypes[d] );
578 bool addDCTerm = ( nonZeroRows==totalDim && !ConstrainsDCTerm( interpolationInfos ) && hasPartitionOfUnity && F.vanishesOnConstants() );
579 double bNorm = 0 , inRNorm = 0 , outRNorm = 0;
580 if( computeNorms )
581 {
582 std::vector< double > bNorms( ThreadPool::NumThreads() , 0 ) , inRNorms( ThreadPool::NumThreads() , 0 );
583 ThreadPool::ParallelFor( 0 , M.rows() , [&]( unsigned int thread , size_t j )
584 {
585 T temp = {};
586 ConstPointer( MatrixEntry< Real , matrix_index_type > ) start = M[j];
587 ConstPointer( MatrixEntry< Real , matrix_index_type > ) end = start + M.rowSize(j);
588 ConstPointer( MatrixEntry< Real , matrix_index_type > ) e;
589 for( e=start ; e!=end ; e++ ) temp += X[ e->N ] * e->Value;
590 bNorms[thread] += Dot( B[j] , B[j] );
591 inRNorms[thread] += Dot( temp-B[j] , temp-B[j] );
592 }
593 );
594 for( unsigned int t=0 ; t<ThreadPool::NumThreads() ; t++ ) bNorm += bNorms[t] , inRNorm += inRNorms[t];
595 }
596
597 iters = (int)std::min< size_t >( nonZeroRows , iters );
598 struct SPDFunctor
599 {
600 protected:
601 const SystemMatrixType< FEMSigs ... > &_M;
602 bool _addDCTerm;
603 public:
604 SPDFunctor( const SystemMatrixType< FEMSigs ... > &M , bool addDCTerm ) : _M(M) , _addDCTerm(addDCTerm){ }
605 void operator()( ConstPointer( T ) in , Pointer( T ) out ) const
606 {
607 _M.multiply( in , out );
608 if( _addDCTerm )
609 {
610 T average = {};
611 for( matrix_index_type i=0 ; i<(matrix_index_type)_M.rows() ; i++ ) average += in[i];
612 average /= _M.rows();
613 for( matrix_index_type i=0 ; i<(matrix_index_type)_M.rows() ; i++ ) out[i] += average;
614 }
615 }
616 };
617 if( iters ) iter = (int)SolveCG< SPDFunctor , T , Real >( SPDFunctor( M , addDCTerm ) , M.rows() , ( ConstPointer( T ) )B , iters , X , Real( accuracy ) , Dot );
618
619 solveTime = Time()-solveTime;
620 if( computeNorms )
621 {
622 std::vector< double > outRNorms( ThreadPool::NumThreads() , 0 );
623 ThreadPool::ParallelFor( 0 , M.rows() , [&]( unsigned int thread , size_t j )
624 {
625 T temp = {};
626 ConstPointer( MatrixEntry< Real , matrix_index_type > ) start = M[j];
627 ConstPointer( MatrixEntry< Real , matrix_index_type > ) end = start + M.rowSize(j);
628 ConstPointer( MatrixEntry< Real , matrix_index_type > ) e;
629 for( e=start ; e!=end ; e++ ) temp += X[ e->N ] * e->Value;
630 outRNorms[thread] += Dot( temp-B[j] , temp-B[j] );
631 }
632 );
633 for( unsigned int t=0 ; t<ThreadPool::NumThreads() ; t++ ) outRNorm += outRNorms[t];
634 stats.bNorm2 = bNorm , stats.inRNorm2 = inRNorm , stats.outRNorm2 = outRNorm;
635 }
636 FreePointer( _constraints );
637 return iter;
638 }
639
640 template< unsigned int Dim , class Real >
641 template< typename T , unsigned int ... FEMSigs >
642 void FEMTree< Dim , Real >::pushToBaseDepth( DenseNodeData< T , UIntPack< FEMSigs ... > >& coefficients ) const
643 {
644 Pointer( T ) prolongedCoefficients = AllocPointer< Real >( _sNodesEnd( _baseDepth ) );
645 for( LocalDepth d=1 ; d<=_baseDepth ; d++ )
646 {
647 SparseMatrix< Real , matrix_index_type > P = downSampleMatrix( UIntPack< FEMSigs ... >() , d ).transpose();
648 P.multiply( coefficients() + _sNodesBegin(d-1) , prolongedCoefficients + _sNodesBegin(d) );
649 for( node_index_type i=_sNodesBegin(d-1) ; i<_sNodesEnd(d-1) ; i++ ) coefficients[i] *= 0;
650 for( node_index_type i=_sNodesBegin(d) ; i<_sNodesEnd(d) ; i++ ) coefficients[i] += prolongedCoefficients[i];
651 }
652 FreePointer( prolongedCoefficients );
653 for( node_index_type i=_sNodesBegin(_baseDepth) ; i<_sNodesEnd(_maxDepth) ; i++ ) if( _sNodes.treeNodes[i]->nodeData.getDirichletElementFlag() ) coefficients[i] *= 0;
654 }
655
656 template< unsigned int Dim , class Real >
657 template< unsigned int ... FEMSigs , typename T , typename TDotT , typename ... InterpolationInfos >
658 void FEMTree< Dim , Real >::_solveRegularMG( UIntPack< FEMSigs ... > , typename BaseFEMIntegrator::System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , LocalDepth maxSolveDepth , Pointer( T ) solution , ConstPointer( T ) constraints , TDotT Dot , int vCycles , int iters , _SolverStats& stats , bool computeNorms , double cgAccuracy , std::tuple< InterpolationInfos *... > interpolationInfos ) const
659 {
660 if( maxSolveDepth>_baseDepth ) MK_THROW( "Regular MG depth cannot exceed base depth: " , maxSolveDepth , " <= " , _baseDepth );
661 double& systemTime = stats.systemTime;
662 double& solveTime = stats. solveTime;
663
664 std::vector< SparseMatrix< Real , matrix_index_type > > P( _baseDepth ) , R( _baseDepth ) , M( _baseDepth+1 );
665 std::vector< Pointer( Real ) > D( _baseDepth+1 );
666 std::vector< Pointer( T ) > B( _baseDepth+1 ) , X( _baseDepth+1 ) , MX( _baseDepth+1 );
667 std::vector< std::vector< std::vector< size_t > > > multiColorIndices( _baseDepth+1 );
668
669 systemTime = Time();
670 M.back() = systemMatrix( UIntPack< FEMSigs ... >() , F , _baseDepth , interpolationInfos );
671 for( int d=_baseDepth ; d>0 ; d-- )
672 {
673 R[d-1] = downSampleMatrix( UIntPack< FEMSigs ... >() , d );
674 P[d-1] = R[d-1].transpose( M[d].rows() );
675 M[d-1] = R[d-1] * M[d] * P[d-1];
676 }
677 for( int d=0 ; d<=_baseDepth ; d++ )
678 {
679 size_t dim = M[d].rows();
680 D[d] = AllocPointer< Real >( dim );
681 MX[d] = AllocPointer< T >( dim );
682 M[d].setDiagonalR( D[d] );
683 setMultiColorIndices( UIntPack< FEMSigs ... >() , d , multiColorIndices[d] );
684 if( d<_baseDepth )
685 {
686 X[d] = AllocPointer< T >( dim );
687 B[d] = AllocPointer< T >( dim );
688 }
689 }
690 X.back() = solution + nodesBegin( _baseDepth );
691 B.back() = ( Pointer( T ) )( constraints + nodesBegin( _baseDepth ) );
692 ConstPointer( T ) _B = constraints + nodesBegin( _baseDepth );
693 systemTime = Time() - systemTime;
694
695 solveTime = Time();
696
697 double bNorm = 0 , inRNorm = 0 , outRNorm = 0;
698 if( computeNorms )
699 {
700 const SparseMatrix< Real , matrix_index_type >& _M = M.back();
701 ConstPointer( T ) _X = X.back();
702 std::vector< double > bNorms( ThreadPool::NumThreads() , 0 ) , inRNorms( ThreadPool::NumThreads() , 0 );
703 ThreadPool::ParallelFor( 0 , _M.rows() , [&]( unsigned int thread , size_t j )
704 {
705 T temp = {};
706 ConstPointer( MatrixEntry< Real , matrix_index_type > ) start = _M[j];
707 ConstPointer( MatrixEntry< Real , matrix_index_type > ) end = start + _M.rowSize(j);
708 ConstPointer( MatrixEntry< Real , matrix_index_type > ) e;
709 for( e=start ; e!=end ; e++ ) temp += _X[ e->N ] * e->Value;
710 bNorms[thread] += Dot( _B[j] , _B[j] );
711 inRNorms[thread] += Dot( temp-_B[j] , temp-_B[j] );
712 }
713 );
714 for( unsigned int t=0 ; t<ThreadPool::NumThreads() ; t++ ) bNorm += bNorms[t] , inRNorm += inRNorms[t];
715 }
716
717 for( int v=0 ; v<vCycles ; v++ )
718 {
719 // Restriction
720 for( int d=_baseDepth ; d>0 ; d-- )
721 {
722 ConstPointer( T ) __B = d==_baseDepth ? _B : B[d];
723 if( d<=maxSolveDepth ) for( int i=0 ; i<iters ; i++ ) M[d].gsIteration( multiColorIndices[d] , D[d] , __B , X[d] , true , true );
724 M[d].multiply( X[d] , MX[d] );
725 for( matrix_index_type i=0 ; i<(matrix_index_type)M[d].rows() ; i++ ) MX[d][i] = __B[i] - MX[d][i];
726 R[d-1].multiply( MX[d] , B[d-1] );
727 memset( X[d-1] , 0 , sizeof( T )*M[d-1].rows() );
728 }
729
730 // Base
731 {
732 int d = 0;
733 ConstPointer( T ) __B = d==_baseDepth ? _B : B[d];
734 struct SPDFunctor
735 {
736 protected:
737 const SparseMatrix< Real , matrix_index_type >& _M;
738 bool _addDCTerm;
739 public:
740 SPDFunctor( const SparseMatrix< Real , matrix_index_type >& M , bool addDCTerm ) : _M(M) , _addDCTerm(addDCTerm){ }
741 void operator()( ConstPointer( T ) in , Pointer( T ) out ) const
742 {
743 _M.multiply( in , out );
744 if( _addDCTerm )
745 {
746 T average = {};
747 for( matrix_index_type i=0 ; i<(matrix_index_type)_M.rows() ; i++ ) average += in[i];
748 average /= _M.rows();
749 for( matrix_index_type i=0 ; i<(matrix_index_type)_M.rows() ; i++ ) out[i] += average;
750 }
751 }
752 };
753 size_t nonZeroRows = 0;
754 for( matrix_index_type i=0 ; i<(matrix_index_type)M[d].rows() ; i++ ) if( M[d].rowSize(i) ) nonZeroRows++;
755 size_t totalDim = 1;
756 int dims[] = { ( _BSplineEnd< FEMSigs >( _baseDepth ) - _BSplineBegin< FEMSigs >( _baseDepth ) ) ... };
757 for( int dd=0 ; dd<Dim ; dd++ ) totalDim *= dims[dd];
758 BoundaryType bTypes[] = { FEMSignature< FEMSigs >::BType ... };
759 bool hasPartitionOfUnity = true;
760 for( int dd=0 ; dd<Dim ; dd++ ) hasPartitionOfUnity &= HasPartitionOfUnity( bTypes[dd] );
761 bool addDCTerm = ( nonZeroRows==totalDim && !ConstrainsDCTerm( interpolationInfos ) && hasPartitionOfUnity && F.vanishesOnConstants() );
762
763 SolveCG< SPDFunctor , T , Real >( SPDFunctor( M[d] , addDCTerm ) , M[d].rows() , ( ConstPointer( T ) )__B , nonZeroRows , X[d] , Real( cgAccuracy ) , Dot );
764 }
765
766 // Prolongation
767 for( int d=1 ; d<=_baseDepth ; d++ )
768 {
769 ConstPointer( T ) __B = d==_baseDepth ? _B : B[d];
770 P[d-1].multiply( X[d-1] , X[d] , MULTIPLY_ADD );
771 for( matrix_index_type i=0 ; i<(matrix_index_type)M[d-1].rows() ; i++ ) X[d-1][i] *= 0;
772 if( d<=maxSolveDepth ) for( int i=0 ; i<iters ; i++ ) M[d].gsIteration( multiColorIndices[d] , D[d] , __B , X[d] , false , true );
773 }
774 }
775 if( computeNorms )
776 {
777 const SparseMatrix< Real , matrix_index_type >& _M = M.back();
778 ConstPointer( T ) _X = X.back();
779 std::vector< double > outRNorms( ThreadPool::NumThreads() , 0 );
780 ThreadPool::ParallelFor( 0 , _M.rows() , [&]( unsigned int thread , size_t j )
781 {
782 T temp = {};
783 ConstPointer( MatrixEntry< Real , matrix_index_type > ) start = _M[j];
784 ConstPointer( MatrixEntry< Real , matrix_index_type > ) end = start + _M.rowSize(j);
785 ConstPointer( MatrixEntry< Real , matrix_index_type > ) e;
786 for( e=start ; e!=end ; e++ ) temp += _X[ e->N ] * e->Value;
787 outRNorms[thread] += Dot( temp-_B[j] , temp-_B[j] );
788 }
789 );
790 for( unsigned int t=0 ; t<ThreadPool::NumThreads() ; t++ ) outRNorm += outRNorms[t];
791 stats.bNorm2 = bNorm , stats.inRNorm2 = inRNorm , stats.outRNorm2 = outRNorm;
792 }
793 solveTime = Time() - solveTime;
794
795 for( int d=0 ; d<=_baseDepth ; d++ )
796 {
797 FreePointer( D[d] );
798 FreePointer( MX[d] );
799 if( d<_baseDepth )
800 {
801 FreePointer( X[d] );
802 FreePointer( B[d] );
803 }
804 }
805 }
806
807 template< unsigned int Dim , class Real >
808 template< unsigned int ... FEMSigs >
809 int FEMTree< Dim , Real >::_getProlongedMatrixRowSize( const FEMTreeNode* node , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& pNeighbors ) const
810 {
811 typedef UIntPack< FEMSignature< FEMSigs >::Degree ... > FEMDegrees;
812 typedef UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > OverlapSizes;
813 #ifdef SHOW_WARNINGS
814 #pragma message( "[WARNING] This change needs to be validated" )
815 #endif // SHOW_WARNINGS
816 int count = 0;
817 static const WindowLoopData< OverlapSizes > loopData( []( int c , int* start , int*end ){ _SetParentOverlapBounds( FEMDegrees() , FEMDegrees() , c , start , end );} );
818 if( node->parent )
819 {
820 int c = (int)( node - node->parent->children );
821 const unsigned int size = loopData.size[c];
822 const unsigned int* indices = loopData.indices[c];
823 ConstPointer( FEMTreeNode * const ) nodes = pNeighbors.neighbors().data;
824 for( unsigned int i=0 ; i<size ; i++ ) if( _isValidFEM1Node( nodes[ indices[i] ] ) ) count++;
825 }
826 return count;
827 }
828
829
830 // Given a node:
831 // -- For each of its neighbors:
832 // ---- Compute the weighted sum of the product of the evaluations of the associated basis functions over the points
833 template< unsigned int Dim , class Real >
834 template< unsigned int ... FEMSigs , typename T , unsigned int PointD >
835 void FEMTree< Dim , Real >::_addPointValues( UIntPack< FEMSigs ... > , StaticWindow< Real , UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& pointValues , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& neighbors , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , const InterpolationInfo< T , PointD >* interpolationInfo ) const
836 {
837 typedef UIntPack< FEMSignature< FEMSigs >::Degree ... > FEMDegrees;
838 typedef UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > OverlapSizes;
839 typedef UIntPack< ( -BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapStart ) ... > OverlapRadii;
840 typedef UIntPack< ( -BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::SupportStart ) ... > LeftSupportRadii;
841 typedef UIntPack< BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::SupportEnd ... > RightSupportRadii;
842 typedef UIntPack< BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::SupportEnd ... > LeftPointSupportRadii;
843 typedef UIntPack< ( -BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::SupportStart ) ... > RightPointSupportRadii;
844 typedef UIntPack< BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::SupportSize ... > SupportSizes;
845
846 if( !( FEMDegrees() >= IsotropicUIntPack< Dim , PointD >() ) ) MK_THROW( "Insufficient derivatives" );
847 if( !interpolationInfo ) return;
848 const InterpolationInfo< T , PointD >& iInfo = *interpolationInfo;
849
850
851 const FEMTreeNode* node = neighbors.neighbors.data[ WindowIndex< OverlapSizes , OverlapRadii >::Index ];
852 LocalDepth d ; LocalOffset off;
853 _localDepthAndOffset( node , d , off );
854
855 PointEvaluatorState< UIntPack< FEMSigs ... > , IsotropicUIntPack< Dim , PointD > > peState;
856
857 int idx[Dim]; // The coordinates of the node containing the point _relative_ to the center node
858 int _idx[Dim==1 ? 1 : Dim-1];
859 CumulativeDerivativeValues< double , Dim , PointD > dualValues;
860
861 auto outerFunction = [&]( const FEMTreeNode* _node )
862 {
863 if( _isValidSpaceNode( _node ) )
864 {
865 LocalOffset pOff; // The coordinates of the node containing the point
866 for( int d=0 ; d<Dim ; d++ ) pOff[d] = off[d] + idx[d];
867 size_t begin , end;
868 iInfo.range( _node , begin , end );
869 for( size_t pIndex=begin ; pIndex<end ; pIndex++ )
870 {
871 const DualPointInfo< Dim , Real , T , PointD >& pData = iInfo[ pIndex ];
872 CumulativeDerivativeValues< double , Dim , PointD > values;
873 {
874 Real weight = pData.weight;
875 Point< Real , Dim > p = pData.position;
876 // Compute the partial evaluation of all B-splines (and derivatives) that are supported on the point
877 bsData.initEvaluationState( p , d , pOff , peState );
878
879 // The value (and derivatives) of the function of the center node at this point
880 values = peState.template dValues< Real , CumulativeDerivatives< Dim , PointD > >( off );
881 }
882 dualValues = iInfo( pIndex , values ) * pData.weight;
883 if( Dim==1 )
884 {
885 Point< double , PointD+1 > partialDot = peState.template partialDotDValues< Real , CumulativeDerivatives< Dim , PointD > >( dualValues , _idx );
886 Pointer( Real ) _pointValues = GetPointer( pointValues.data + idx[Dim-1] + OverlapRadii::Values[Dim-1] , - idx[Dim-1] - (int)OverlapRadii::Values[Dim-1] , pointValues.Size() - idx[Dim-1] - (int)OverlapRadii::Values[Dim-1] );
887
888 int _i = idx[Dim-1] + (int)OverlapRadii::Values[Dim-1] - (int)LeftPointSupportRadii::Values[Dim-1];
889 const double (*splineValues)[PointD+1] = peState.template values< Dim-1 >();
890 for( unsigned int i=0 ; i<SupportSizes::Values[Dim-1] ; i++ ) if( _isValidFEM1Node( neighbors.neighbors.data[ _i + i ] ) )
891 for( int d=0 ; d<=PointD ; d++ ) _pointValues[(int)i-(int)LeftPointSupportRadii::Values[Dim-1]] += (Real)( splineValues[i][d] * partialDot[d] );
892 }
893 else
894 {
895 int start[Dim==1 ? 1 : Dim-1] , end[Dim==1 ? 1 : Dim-1];
896 // Compute the bounds of nodes which can be supported on the point
897 for( int d=0 ; d<Dim-1 ; d++ ) start[d] = idx[d] + (int)OverlapRadii::Values[d] - (int)LeftPointSupportRadii::Values[d] , end[d] = idx[d] + (int)OverlapRadii::Values[d] + (int)RightPointSupportRadii::Values[d] + 1;
898 Window::Loop< Dim , Dim-1 >::Run
899 (
900 start , end ,
901 [&]( int d , int i ){ _idx[d] = i - (int)OverlapRadii::Values[d] + off[d]; } ,
902 [&]( const WindowSlice< Real , UIntPack< OverlapSizes::template Get< Dim-1 >() > > pointValues , ConstWindowSlice< const FEMTreeNode* , UIntPack< OverlapSizes::template Get< Dim-1 >() > > neighbors )
903 {
904 Point< double , PointD+1 > partialDot = peState.template partialDotDValues< Real , CumulativeDerivatives< Dim , PointD > >( dualValues , _idx );
905 Pointer( Real ) _pointValues = pointValues.data + idx[Dim-1] + OverlapRadii::Values[Dim-1];
906
907 int _i = idx[Dim-1] + (int)OverlapRadii::Values[Dim-1] - (int)LeftPointSupportRadii::Values[Dim-1];
908 const double (*splineValues)[PointD+1] = peState.template values< Dim-1 >();
909 for( unsigned int i=0 ; i<SupportSizes::Values[Dim-1] ; i++ ) if( _isValidFEM1Node( neighbors[ _i + i ] ) )
910 for( int d=0 ; d<=PointD ; d++ ) _pointValues[(int)i-(int)LeftPointSupportRadii::Values[Dim-1]] += (Real)( splineValues[i][d] * partialDot[d] );
911 } ,
912 pointValues() , neighbors.neighbors()
913 );
914 }
915 }
916 }
917 };
918 // Loop over all nodes which are supported on the center
919 WindowLoop< Dim >::Run
920 (
921 OverlapRadii() - LeftSupportRadii() , OverlapRadii() + RightSupportRadii() + IsotropicUIntPack< Dim , 1 >() ,
922 [&]( int d , int i ){ idx[d] = i - (int)OverlapRadii::Values[d]; } ,
923 outerFunction ,
924 neighbors.neighbors()
925 );
926 }
927
928 template< unsigned int Dim , class Real >
929 template< typename T , unsigned int ... FEMSigs , typename ... InterpolationInfos , typename MatrixType >
930 T FEMTree< Dim , Real >::_setMatrixRowAndGetConstraintFromProlongation( UIntPack< FEMSigs ... > , const BaseSystem< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& pNeighbors , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& neighbors , size_t idx , MatrixType &M , node_index_type offset , const PCStencils< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& pcStencils , const CCStencil< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& ccStencil , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , ConstPointer( T ) prolongedSolution , std::tuple< InterpolationInfos *... > interpolationInfos ) const
931 {
932 T constraint ={};
933 typedef UIntPack< ( -BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapStart ) ... > OverlapRadii;
934 typedef UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > OverlapSizes;
935
936 int count = 0;
937 const FEMTreeNode* node = neighbors.neighbors.data[ WindowIndex< OverlapSizes , OverlapRadii >::Index ];
938 MatrixEntry< Real , matrix_index_type > row[ WindowSize< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >::Size ];
939
940 if( node->nodeData.getDirichletElementFlag() )
941 {
942 M.setRowSize( idx , count );
943 return constraint;
944 }
945
946 LocalDepth d ; LocalOffset off;
947 _localDepthAndOffset( node , d , off );
948 if( d>0 && prolongedSolution )
949 {
950 int cIdx = (int)( node - node->parent->children );
951 constraint = _getConstraintFromProlongedSolution( UIntPack< FEMSigs ... >() , F , neighbors , pNeighbors , node , prolongedSolution , pcStencils.data[cIdx] , bsData , interpolationInfos );
952 }
953
954 bool isInterior = BaseFEMIntegrator::IsInteriorlyOverlapped( UIntPack< FEMSignature< FEMSigs >::Degree ... >() , UIntPack< FEMSignature< FEMSigs >::Degree ... >() , d , off );
955
956 StaticWindow< Real , UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > > pointValues;
957 memset( pointValues.data , 0 , sizeof(Real)*WindowSize< OverlapSizes >::Size );
958 _addPointValues< 0 >( UIntPack< FEMSigs ... >() , pointValues , neighbors , bsData , interpolationInfos );
959 node_index_type nodeIndex = node->nodeData.nodeIndex;
960 if( isInterior ) // General case, so try to make fast
961 {
962 const FEMTreeNode* const * _nodes = neighbors.neighbors.data;
963 ConstPointer( double ) _stencil = ccStencil.data;
964 Real* _values = pointValues.data;
965 row[count++] = MatrixEntry< Real , matrix_index_type >( (matrix_index_type)( nodeIndex-offset ) , (Real)( _values[ WindowIndex< OverlapSizes , OverlapRadii >::Index ] + _stencil[ WindowIndex< OverlapSizes , OverlapRadii >::Index ] ) );
966 for( int i=0 ; i<WindowSize< OverlapSizes >::Size ; i++ ) if( _isValidFEM1Node( _nodes[i] ) && !_nodes[i]->nodeData.getDirichletElementFlag() )
967 {
968 if( i!=WindowIndex< OverlapSizes , OverlapRadii >::Index ) row[count++] = MatrixEntry< Real , matrix_index_type >( (matrix_index_type)( _nodes[i]->nodeData.nodeIndex-offset ) , (Real)( _values[i] + _stencil[i] ) );
969 }
970 }
971 else
972 {
973 LocalDepth d ; LocalOffset off;
974 _localDepthAndOffset( node , d , off );
975 Real temp = (Real)F.ccIntegrate( off , off ) + pointValues.data[ WindowIndex< OverlapSizes , OverlapRadii >::Index ];
976
977 row[count++] = MatrixEntry< Real , matrix_index_type >( (matrix_index_type)( nodeIndex-offset ) , temp );
978 LocalOffset _off;
979 WindowLoop< Dim >::Run
980 (
981 ZeroUIntPack< Dim >() , OverlapSizes() ,
982 [&]( int d , int i ){ _off[d] = off[d] - (int)OverlapRadii::Values[d] + i; } ,
983 [&]( const FEMTreeNode* _node , Real pointValue )
984 {
985 if( node!=_node && _isValidFEM1Node( _node ) && !_node->nodeData.getDirichletElementFlag() )
986 {
987 row[count++] = MatrixEntry< Real , matrix_index_type >( (matrix_index_type)( _node->nodeData.nodeIndex-offset ) , (Real)F.ccIntegrate( _off , off ) + pointValue );
988 }
989 } ,
990 neighbors.neighbors() , pointValues()
991 );
992 }
993 M.setRowSize( idx , count );
994 memcpy( M[idx] , row , sizeof( MatrixEntry< Real , matrix_index_type > ) * count );
995 return constraint;
996 }
997
998 template< unsigned int Dim , class Real >
999 template< unsigned int ... FEMSigs , typename T , unsigned int PointD >
1000 void FEMTree< Dim , Real >::_addProlongedPointValues( UIntPack< FEMSigs ... > , WindowSlice< Real , UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > > pointValues , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& neighbors , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& pNeighbors , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , const InterpolationInfo< T , PointD >* interpolationInfo ) const
1001 {
1002 #ifdef SHOW_WARNINGS
1003 #pragma message( "[WARNING] This code is broken" )
1004 #endif // SHOW_WARNINGS
1005 #if 1
1006 MK_THROW( "Broken code" );
1007 #else
1008 if( !interpolationInfo ) return;
1009 const InterpolationInfo< T , PointD >& iInfo = *interpolationInfo;
1010 typedef UIntPack< ( -BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapStart ) ... > OverlapRadii;
1011 typedef UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > OverlapSizes;
1012
1013 const FEMTreeNode* node = neighbors.neighbors.data[ WindowIndex< OverlapSizes , OverlapRadii >::Index ];
1014
1015 LocalDepth d , parentD ; LocalOffset off , parentOff;
1016 _localDepthAndOffset( node , d , off );
1017 _localDepthAndOffset( node->parent , parentD , parentOff );
1018 int fStart , fEnd;
1019 BSplineData< FEMSig >::FunctionSpan( d , fStart , fEnd );
1020
1021 int fIdx[Dim];
1022 functionIndex( IsotropicUIntPack< Dim , FEMSig >() , node , fIdx );
1023 double splineValues[ Dim ] [ PointD+1 ];
1024 double parentSplineValues[ Dim ][ SupportSize ][ PointD+1 ];
1025 int s[Dim];
1026 CumulativeDerivativeValues< Real , Dim , PointD > dualValues;
1027 std::function< void ( const FEMTreeNode* , Real& ) > innerFunction = [&]( const FEMTreeNode* pNode , Real& pointValue )
1028 {
1029 if( _isValidFEM1Node( pNode ) )
1030 {
1031 CumulativeDerivativeValues< Real , Dim , PointD > values = Evaluate< SupportSize , Dim , Real , PointD >( s , parentSplineValues );
1032 pointValue += CumulativeDerivativeValues< Real , Dim , PointD >::Dot( dualValues , values );
1033 };
1034 };
1035 std::function< void ( const FEMTreeNode* ) > outerFunction = [&]( const FEMTreeNode* _node )
1036 {
1037 if( _isValidSpaceNode( _node ) ) for( const PointData< Dim , Real , T , PointD >* _pData=iInfo.begin( _node ) ; _pData!=iInfo.end( _node ) ; _pData++ )
1038 {
1039 // Evaluate the node's basis function at the sample
1040 const PointData< Dim , Real , T , PointD >& pData = *_pData;
1041 _setDValues< FEMSig , PointD , FEMDegree >( pData.position , _node , node , bsData , splineValues );
1042 _setDValues< FEMSig , PointD , FEMDegree >( pData.position , _node->parent , bsData , parentSplineValues );
1043 dualValues = iInfo.weights * Evaluate< Dim , Real , PointD >( splineValues ) * pData.weight;
1044
1045 // Get the indices of the parent
1046 LocalDepth _parentD ; LocalOffset _parentOff;
1047 _localDepthAndOffset( _node->parent , _parentD , _parentOff );
1048
1049 int _off[Dim];
1050 for( int dd=0 ; dd<Dim ; dd++ ) _off[dd] = _parentOff[dd] - parentOff[dd];
1051
1052 int _start[Dim] , _end[Dim];
1053 for( int dd=0 ; dd<Dim ; dd++ ) _start[dd] = OverlapRadius + _off[dd] - LeftPointSupportRadius , _end[dd] = _start[dd] + SupportSize;
1054 WindowLoop< Dim >::Run
1055 (
1056 _start , _end ,
1057 [&]( int d , int i ){ s[d] = i + LeftPointSupportRadius - _off[d] - OverlapRadius; } ,
1058 innerFunction ,
1059 pNeighbors.neighbors() , pointValues
1060 );
1061 }
1062 };
1063 int start[Dim] , end[Dim];
1064 for( int dd=0 ; dd<Dim ; dd++ ) start[dd] = OverlapRadius - LeftSupportRadius , end[dd] = start[dd] + SupportSize;
1065 WindowLoop< Dim >::Run
1066 (
1067 start , end ,
1068 [&]( int , int ){;} ,
1069 outerFunction ,
1070 neighbors.neighbors()
1071 );
1072 #endif
1073 }
1074
1075 template< unsigned int Dim , class Real >
1076 template< typename T , unsigned int ... FEMSigs , typename ... InterpolationInfos >
1077 int FEMTree< Dim , Real >::_setProlongedMatrixRow( const typename BaseFEMIntegrator::System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& neighbors , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& pNeighbors , Pointer( MatrixEntry< Real , matrix_index_type > ) row , node_index_type offset , const DynamicWindow< double , UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& stencil , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , std::tuple< InterpolationInfos *... > interpolationInfo ) const
1078 {
1079 typedef UIntPack< ( -BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapStart ) ... > OverlapRadii;
1080 typedef UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > OverlapSizes;
1081 typedef UIntPack< FEMSignature< FEMSigs >::Degree ... > FEMDegrees;
1082
1083 int count = 0;
1084 const FEMTreeNode* node = neighbors.neighbors.data[ WindowIndex< OverlapSizes , OverlapRadii >::Index ];
1085 LocalDepth d , parentD ; LocalOffset off , parentOff;
1086 _localDepthAndOffset( node , d , off );
1087 _localDepthAndOffset( node->parent , parentD , parentOff );
1088 bool isInterior = _isInteriorlyOverlapped( FEMDegrees() , FEMDegrees() , node->parent );
1089 StaticWindow< Real , UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > > pointValues;
1090 memset( pointValues.data , 0 , sizeof(Real)*WindowSize< OverlapSizes >::Size );
1091 _addProlongedPointValues< 0 >( UIntPack< FEMSigs ... >() , pointValues() , neighbors , pNeighbors , bsData , interpolationInfo );
1092
1093 node_index_type nodeIndex = node->nodeData.nodeIndex;
1094
1095 int start[Dim] , end[Dim];
1096 _SetParentOverlapBounds( FEMDegrees() , FEMDegrees() , node , start , end );
1097 if( isInterior ) // General case, so try to make fast
1098 {
1099 WindowLoop< Dim >::Run
1100 (
1101 start , end ,
1102 [&]( int , int ){;} ,
1103 [&]( const FEMTreeNode* node , const Real& pointValue , const Real& stencilValue )
1104 {
1105 if( _isValidFEM1Node( node ) ) row[count++] = MatrixEntry< Real , matrix_index_type >( (matrix_index_type)( node->nodeData.nodeIndex - offset ) , pointValue + stencilValue );
1106 } ,
1107 pNeighbors.neighbors() , pointValues() , stencil()
1108 );
1109 }
1110 else
1111 {
1112 LocalDepth d ; LocalOffset off;
1113 _localDepthAndOffset( node , d , off );
1114 WindowLoop< Dim >::Run
1115 (
1116 start , end ,
1117 [&]( int , int ){;} ,
1118 [&]( const FEMTreeNode* node , const Real& pointValue )
1119 {
1120 if( _isValidFEM1Node( node ) )
1121 {
1122 LocalDepth d ; LocalOffset _off;
1123 _localDepthAndOffset( node , d , _off );
1124 row[count++] = MatrixEntry< Real , matrix_index_type >( (matrix_index_type)( node->nodeData.nodeIndex - offset ) , (Real)F.pcIntegrate( _off , off ) + pointValue );
1125 }
1126 } ,
1127 pNeighbors.neighbors() , pointValues()
1128 );
1129 }
1130 return count;
1131 }
1132
1133 template< unsigned int Dim , class Real >
1134 template< unsigned int FEMDegree1 , unsigned int FEMDegree2 >
1135 void FEMTree< Dim , Real >::_SetParentOverlapBounds( const FEMTreeNode* node , int start[Dim] , int end[Dim] )
1136 {
1137 const int OverlapStart = BSplineOverlapSizes< FEMDegree1 , FEMDegree2 >::OverlapStart;
1138
1139 if( node->parent )
1140 {
1141 int cIdx = (int)( node - node->parent->children );
1142 for( int d=0 ; d<Dim ; d++ )
1143 {
1144 start[d] = BSplineOverlapSizes< FEMDegree1 , FEMDegree2 >::ParentOverlapStart[ (cIdx>>d) & 1 ] - OverlapStart;
1145 end [d] = BSplineOverlapSizes< FEMDegree1 , FEMDegree2 >::ParentOverlapEnd [ (cIdx>>d) & 1 ] - OverlapStart + 1;
1146 }
1147 }
1148 }
1149 template< unsigned int Dim , class Real >
1150 template< unsigned int FEMDegree1 , unsigned int FEMDegree2 >
1151 void FEMTree< Dim , Real >::_SetParentOverlapBounds( int cIdx , int start[Dim] , int end[Dim] )
1152 {
1153 const int OverlapStart = BSplineOverlapSizes< FEMDegree1 , FEMDegree2 >::OverlapStart;
1154
1155 for( int d=0 ; d<Dim ; d++ )
1156 {
1157 start[d] = BSplineOverlapSizes< FEMDegree1 , FEMDegree2 >::ParentOverlapStart[ (cIdx>>d) & 1 ] - OverlapStart;
1158 end [d] = BSplineOverlapSizes< FEMDegree1 , FEMDegree2 >::ParentOverlapEnd [ (cIdx>>d) & 1 ] - OverlapStart + 1;
1159 }
1160 }
1161
1162 template< unsigned int Dim , class Real >
1163 template< unsigned int ... FEMSigs , typename T , unsigned int PointD >
1164 T FEMTree< Dim , Real >::_getInterpolationConstraintFromProlongedSolution( const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& neighbors , const FEMTreeNode* node , ConstPointer( T ) prolongedSolution , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , const InterpolationInfo< T , PointD >* interpolationInfo ) const
1165 {
1166 if( !interpolationInfo ) return T();
1167 typedef UIntPack< BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::SupportSize ... > SupportSizes;
1168 typedef UIntPack< ( -BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapStart ) ... > OverlapRadii;
1169 typedef UIntPack< ( -BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::SupportStart ) ... > LeftSupportRadii;
1170 typedef UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > OverlapSizes;
1171 typedef PointEvaluatorState< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > > _PointEvaluatorState;
1172 LocalDepth d ; LocalOffset off;
1173 _localDepthAndOffset( node , d , off );
1174 T temp = {};
1175 if( _isValidFEM1Node( node ) )
1176 {
1177 int s[Dim];
1178 #if defined( _WIN32 ) || defined( _WIN64 )
1179 #ifdef SHOW_WARNINGS
1180 #pragma message ( "[WARNING] You've got me MSVC" )
1181 #endif // SHOW_WARNINGS
1182 auto UpdateFunction = [&]( int d , int i ){ s[d] = (int)SupportSizes::Values[d] - 1 - ( i - (int)OverlapRadii::Values[d] + (int)LeftSupportRadii::Values[d] ); };
1183 auto ProcessFunction = [&]( const FEMTreeNode* pNode )
1184 {
1185 if( _isValidSpaceNode( pNode ) )
1186 {
1187 size_t begin , end;
1188 interpolationInfo->range( pNode , begin , end );
1189 for( size_t pIndex=begin ; pIndex<end ; pIndex++ )
1190 {
1191 const DualPointInfo< Dim , Real , T , PointD > _pData = (*interpolationInfo)[ pIndex ];
1192 _PointEvaluatorState peState;
1193 Point< Real , Dim > p = _pData.position;
1194 LocalDepth pD ; LocalOffset pOff;
1195 _localDepthAndOffset( pNode , pD , pOff );
1196 bsData.initEvaluationState( p , pD , pOff , peState );
1197 #ifdef SHOW_WARNINGS
1198 #pragma message( "[WARNING] Why is this necessary?" )
1199 #endif // SHOW_WARNINGS
1200 const int *_off = off;
1201 CumulativeDerivativeValues< Real , Dim , PointD > values = peState.template dValues< Real , CumulativeDerivatives< Dim , PointD > >( _off );
1202 for( int d=0 ; d<CumulativeDerivatives< Dim , PointD >::Size ; d++ ) temp += _pData.dualValues[d] * values[d];
1203 }
1204 }
1205 };
1206 #endif // _WIN32 || _WIN64
1207 WindowLoop< Dim >::Run
1208 (
1209 OverlapRadii() - LeftSupportRadii() , OverlapRadii() - LeftSupportRadii() + SupportSizes() ,
1210 #if defined( _WIN32 ) || defined( _WIN64 )
1211 UpdateFunction , ProcessFunction ,
1212 #else // !_WIN32 && !_WIN64
1213 [&]( int d , int i ){ s[d] = (int)SupportSizes::Values[d] - 1 - ( i - (int)OverlapRadii::Values[d] + (int)LeftSupportRadii::Values[d] ); } ,
1214 [&]( const FEMTreeNode* pNode )
1215 {
1216 if( _isValidSpaceNode( pNode ) )
1217 {
1218 size_t begin , end;
1219 interpolationInfo->range( pNode , begin , end );
1220 for( size_t pIndex=begin ; pIndex<end ; pIndex++ )
1221 {
1222 const DualPointInfo< Dim , Real , T , PointD > _pData = (*interpolationInfo)[ pIndex ];
1223 _PointEvaluatorState peState;
1224 Point< Real , Dim > p = _pData.position;
1225 LocalDepth pD ; LocalOffset pOff;
1226 _localDepthAndOffset( pNode , pD , pOff );
1227 bsData.initEvaluationState( p , pD , pOff , peState );
1228 #ifdef SHOW_WARNINGS
1229 #pragma message( "[WARNING] Why is this necessary?" )
1230 #endif // SHOW_WARNINGS
1231 const int *_off = off;
1232 CumulativeDerivativeValues< Real , Dim , PointD > values = peState.template dValues< Real , CumulativeDerivatives< Dim , PointD > >( _off );
1233 for( int d=0 ; d<CumulativeDerivatives< Dim , PointD >::Size ; d++ ) temp += _pData.dualValues[d] * values[d];
1234 }
1235 }
1236 } ,
1237 #endif // _WIN32 || _WIN64
1238 neighbors.neighbors()
1239 );
1240 }
1241 return temp;
1242 }
1243
1244 template< unsigned int Dim , class Real >
1245 template< unsigned int ... FEMSigs , typename T , typename ... InterpolationInfos >
1246 T FEMTree< Dim , Real >::_getConstraintFromProlongedSolution( UIntPack< FEMSigs ... > , const BaseSystem< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& neighbors , const typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& pNeighbors , const FEMTreeNode* node , ConstPointer( T ) prolongedSolution , const DynamicWindow< double , UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >& stencil , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , std::tuple< InterpolationInfos *... > interpolationInfos ) const
1247 {
1248 typedef UIntPack< FEMSignature< FEMSigs >::Degree ... > FEMDegrees;
1249
1250 if( _localDepth( node )<=0 ) return T();
1251 // This is a conservative estimate as we only need to make sure that the parent nodes don't overlap the child (not the parent itself)
1252 LocalDepth d ; LocalOffset off;
1253 _localDepthAndOffset( node->parent , d , off );
1254 bool isInterior = BaseFEMIntegrator::IsInteriorlyOverlapped( FEMDegrees() , FEMDegrees() , d , off );
1255
1256 // Offset the constraints using the solution from lower resolutions.
1257 T constraint = {};
1258 static const WindowLoopData< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > > loopData( []( int c , int* start , int* end ){ BaseFEMIntegrator::ParentOverlapBounds( FEMDegrees() , FEMDegrees() , c , start , end ); } );
1259 int cIdx = (int)( node - node->parent->children );
1260 unsigned int size = loopData.size[cIdx];
1261 const unsigned int* indices = loopData.indices[cIdx];
1262 ConstPointer( double ) values = stencil.data;
1263 ConstPointer( FEMTreeNode * const ) nodes = pNeighbors.neighbors().data;
1264 if( isInterior )
1265 {
1266 for( unsigned int i=0 ; i<size ; i++ )
1267 {
1268 unsigned int idx = indices[i];
1269 if( _isValidFEM1Node( nodes[idx] ) ) constraint += (T)( prolongedSolution[ nodes[idx]->nodeData.nodeIndex ] * (Real)values[idx] );
1270 }
1271 }
1272 else
1273 {
1274 LocalDepth d ; LocalOffset off;
1275 _localDepthAndOffset( node , d , off );
1276 for( unsigned int i=0 ; i<size ; i++ )
1277 {
1278 unsigned int idx = indices[i];
1279 if( _isValidFEM1Node( nodes[idx] ) )
1280 {
1281 LocalDepth _d ; LocalOffset _off;
1282 _localDepthAndOffset( nodes[idx] , _d , _off );
1283 constraint += (T)( prolongedSolution[ nodes[idx]->nodeData.nodeIndex ] * (Real)F.pcIntegrate( _off , off ) );
1284 }
1285
1286 }
1287 }
1288 return constraint + _getInterpolationConstraintFromProlongedSolution< 0 >( neighbors , node , prolongedSolution , bsData , interpolationInfos );
1289 }
1290
1291 // Given the solution @( depth ) add to the met constraints @( depth-1 )
1292 template< unsigned int Dim , class Real >
1293 template< unsigned int ... FEMSigs , typename T >
1294 void FEMTree< Dim , Real >::_updateRestrictedIntegralConstraints( UIntPack< FEMSigs ... > , const typename BaseFEMIntegrator::template System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , LocalDepth highDepth , ConstPointer( T ) fineSolution , Pointer( T ) restrictedConstraints ) const
1295 {
1296 typedef UIntPack< FEMSignature< FEMSigs >::Degree ... > FEMDegrees;
1297 typedef UIntPack< ( -BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapStart ) ... > OverlapRadii;
1298 typedef UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > OverlapSizes;
1299
1300 if( highDepth<=0 ) return;
1301 // Get the stencil describing the Laplacian relating coefficients @(highDepth) with coefficients @(highDepth-1)
1302 PCStencils< FEMDegrees > stencils;
1303 F.template setStencils< true >( stencils );
1304 node_index_type start = _sNodesBegin(highDepth) , end = _sNodesEnd(highDepth);
1305 node_index_type range = end-start;
1306 node_index_type lStart = _sNodesBegin(highDepth-1);
1307
1308 // Iterate over the nodes @(highDepth)
1309 std::vector< ConstOneRingNeighborKey > neighborKeys( ThreadPool::NumThreads() );
1310 for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( _localToGlobal( highDepth )-1 );
1311 ThreadPool::ParallelFor( _sNodesBegin(highDepth) , _sNodesEnd(highDepth) , [&]( unsigned int thread , size_t i )
1312 {
1313 if( _isValidFEM1Node( _sNodes.treeNodes[i] ) )
1314 {
1315 ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ];
1316 FEMTreeNode* node = _sNodes.treeNodes[i];
1317
1318 // Offset the coarser constraints using the solution from the current resolutions.
1319 int cIdx = (int)( node - node->parent->children );
1320
1321 {
1322 typename FEMTreeNode::template ConstNeighbors< OverlapSizes > pNeighbors;
1323 neighborKey.getNeighbors( OverlapRadii() , OverlapRadii() , node->parent , pNeighbors );
1324 const DynamicWindow< double , OverlapSizes >& stencil = stencils.data[cIdx];
1325
1326 bool isInterior = _isInteriorlyOverlapped( FEMDegrees() , FEMDegrees() , node->parent );
1327 LocalDepth d ; LocalOffset off;
1328 _localDepthAndOffset( node , d , off );
1329
1330 // Offset the constraints using the solution from finer resolutions.
1331 int start[Dim] , end[Dim];
1332 _SetParentOverlapBounds( FEMDegrees() , FEMDegrees() , node , start , end );
1333
1334 T solution = fineSolution[ node->nodeData.nodeIndex ];
1335 ConstPointer( FEMTreeNode * const ) nodes = pNeighbors.neighbors().data;
1336 ConstPointer( double ) stencilValues = stencil.data;
1337 if( isInterior )
1338 {
1339 for( int i=0 ; i<WindowSize< OverlapSizes >::Size ; i++ ) if( _isValidFEM1Node( nodes[i] ) )
1340 {
1341 Atomic< T >::Add( restrictedConstraints[ nodes[i]->nodeData.nodeIndex ] , solution * (Real)stencilValues[i] );
1342 }
1343 }
1344 else
1345 {
1346 for( int i=0 ; i<WindowSize< OverlapSizes >::Size ; i++ ) if( _isValidFEM1Node( nodes[i] ) )
1347 {
1348 LocalDepth _d ; LocalOffset _off;
1349 _localDepthAndOffset( nodes[i] , _d , _off );
1350 Atomic< T >::Add( restrictedConstraints[ nodes[i]->nodeData.nodeIndex ] , solution * (Real)F.pcIntegrate( _off , off ) );
1351 }
1352 }
1353 }
1354 }
1355 } );
1356 }
1357
1358 template< unsigned int Dim , class Real >
1359 template< unsigned int ... FEMSigs , typename T , unsigned int PointD >
1360 void FEMTree< Dim , Real >::_setPointValuesFromProlongedSolution( LocalDepth highDepth , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , ConstPointer( T ) prolongedSolution , InterpolationInfo< T , PointD >* iInfo ) const
1361 {
1362 if( !iInfo ) return;
1363 typedef UIntPack< FEMSignature< FEMSigs >::Degree ... > FEMDegrees;
1364 InterpolationInfo< T , PointD >& interpolationInfo = *iInfo;
1365
1366 LocalDepth lowDepth = highDepth-1;
1367 if( lowDepth<0 ) return;
1368 // For every node at the current depth
1369 std::vector< ConstPointSupportKey< FEMDegrees > > neighborKeys( ThreadPool::NumThreads() );
1370 for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( _localToGlobal( lowDepth ) );
1371
1372 ThreadPool::ParallelFor( _sNodesBegin(highDepth) , _sNodesEnd(highDepth) , [&]( unsigned int thread , size_t i )
1373 {
1374 if( _isValidFEM1Node( _sNodes.treeNodes[i] ) )
1375 {
1376 ConstPointSupportKey< FEMDegrees >& neighborKey = neighborKeys[ thread ];
1377 if( _isValidSpaceNode( _sNodes.treeNodes[i] ) )
1378 {
1379 size_t begin , end;
1380 interpolationInfo.range( _sNodes.treeNodes[i] , begin , end );
1381 for( size_t pIndex=begin ; pIndex<end ; pIndex++ )
1382 {
1383 DualPointInfo< Dim , Real , T , PointD >& pData = interpolationInfo[ pIndex ];
1384 neighborKey.getNeighbors( _sNodes.treeNodes[i]->parent );
1385 #ifdef _MSC_VER
1386 pData.dualValues = interpolationInfo( pIndex , _coarserFunctionValues< PointD , T , FEMSigs ... >( UIntPack< FEMSigs ... >() , pData.position , neighborKey , _sNodes.treeNodes[i] , bsData , prolongedSolution ) ) * pData.weight;
1387 #else // !_MSC_VER
1388 pData.dualValues = interpolationInfo( pIndex , _coarserFunctionValues< PointD >( UIntPack< FEMSigs ... >() , pData.position , neighborKey , _sNodes.treeNodes[i] , bsData , prolongedSolution ) ) * pData.weight;
1389 #endif // _MSC_VER
1390 }
1391 }
1392 }
1393 }
1394 );
1395 }
1396
1397 template< unsigned int Dim , class Real >
1398 template< unsigned int ... FEMSigs , typename T , unsigned int PointD >
1399 void FEMTree< Dim , Real >::_updateRestrictedInterpolationConstraints( const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , LocalDepth highDepth , ConstPointer( T ) solution , Pointer( T ) restrictedConstraints , const InterpolationInfo< T , PointD >* iInfo ) const
1400 {
1401 if( !iInfo ) return;
1402 const InterpolationInfo< T , PointD >& interpolationInfo = *iInfo;
1403 typedef UIntPack< FEMSignature< FEMSigs >::Degree ... > FEMDegrees;
1404 typedef UIntPack< BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::SupportSize ... > SupportSizes;
1405
1406 // Note: We can't iterate over the finer point nodes as the point weights might be
1407 // scaled incorrectly, due to the adaptive exponent. So instead, we will iterate
1408 // over the coarser nodes and evaluate the finer solution at the associated points.
1409 LocalDepth lowDepth = highDepth-1;
1410 if( lowDepth<0 ) return;
1411
1412 node_index_type start = _sNodesBegin(lowDepth) , end = _sNodesEnd(lowDepth);
1413 std::vector< ConstPointSupportKey< FEMDegrees > > neighborKeys( ThreadPool::NumThreads() );
1414 for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( _localToGlobal( lowDepth ) );
1415 ThreadPool::ParallelFor( _sNodesBegin(lowDepth) , _sNodesEnd(lowDepth) , [&]( unsigned int thread , size_t i )
1416 {
1417 if( _isValidSpaceNode( _sNodes.treeNodes[i] ) ) if( _isValidSpaceNode( _sNodes.treeNodes[i] ) )
1418 {
1419 ConstPointSupportKey< FEMDegrees >& neighborKey = neighborKeys[ thread ];
1420 PointEvaluatorState< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > > peState;
1421 const FEMTreeNode* node = _sNodes.treeNodes[i];
1422
1423 LocalDepth d ; LocalOffset off;
1424 _localDepthAndOffset( node , d , off );
1425 typename FEMTreeNode::template ConstNeighbors< SupportSizes >& neighbors = neighborKey.getNeighbors( node );
1426 size_t begin , end;
1427 interpolationInfo.range( node , begin , end );
1428 for( size_t pIndex=begin ; pIndex<end ; pIndex++ )
1429 {
1430 const DualPointInfo< Dim , Real , T , PointD >& pData = interpolationInfo[ pIndex ];
1431 Point< Real , Dim > p = pData.position;
1432 bsData.initEvaluationState( p , d , off , peState );
1433
1434 #ifdef _MSC_VER
1435 CumulativeDerivativeValues< T , Dim , PointD > dualValues = interpolationInfo( pIndex , _finerFunctionValues< PointD , T , FEMSigs ... >( UIntPack< FEMSigs ... >() , pData.position , neighborKey , node , bsData , solution ) ) * pData.weight;
1436 #else // !_MSC_VER
1437 CumulativeDerivativeValues< T , Dim , PointD > dualValues = interpolationInfo( pIndex , _finerFunctionValues< PointD >( UIntPack< FEMSigs ... >() , pData.position , neighborKey , node , bsData , solution ) ) * pData.weight;
1438 #endif // _MSC_VER
1439 // Update constraints for all nodes @( depth-1 ) that overlap the point
1440 int s[Dim];
1441 WindowLoop< Dim >::Run
1442 (
1443 ZeroUIntPack< Dim >() , SupportSizes() ,
1444 [&]( int d , int i ){ s[d] = i; } ,
1445 [&]( const FEMTreeNode* node )
1446 {
1447 if( _isValidFEM1Node( node ) )
1448 {
1449 LocalDepth d ; LocalOffset off;
1450 _localDepthAndOffset( node , d , off );
1451 CumulativeDerivativeValues< Real , Dim , PointD > values = peState.template dValues< Real , CumulativeDerivatives< Dim , PointD > >( off );
1452 T temp = {};
1453 for( int d=0 ; d<CumulativeDerivatives< Dim , PointD >::Size ; d++ ) temp += dualValues[d] * values[d];
1454 Atomic< T >::Add( restrictedConstraints[ node->nodeData.nodeIndex ] , temp );
1455 }
1456 } ,
1457 neighbors.neighbors()
1458 );
1459 }
1460 }
1461 }
1462 );
1463 }
1464
1465 template< unsigned int Dim , class Real >
1466 template< class C , unsigned int ... FEMSigs >
1467 DenseNodeData< C , UIntPack< FEMSigs ... > > FEMTree< Dim , Real >::coarseCoefficients( const DenseNodeData< C , UIntPack< FEMSigs ... > >& coefficients ) const
1468 {
1469 DenseNodeData< C , UIntPack< FEMSigs ... > > coarseCoefficients( _sNodesEnd(_maxDepth-1) );
1470 memset( coarseCoefficients() , 0 , sizeof(Real)*_sNodesEnd(_maxDepth-1) );
1471 ThreadPool::ParallelFor( _sNodesBegin(0) , _sNodesEnd(_maxDepth-1) , [&]( unsigned int , size_t i ){ coarseCoefficients[i] = coefficients[i]; } );
1472 typename FEMIntegrator::template RestrictionProlongation< UIntPack< FEMSigs ... > > rp;
1473 for( LocalDepth d=1 ; d<_maxDepth ; d++ ) _upSample( UIntPack< FEMSigs ... >() , rp , d , ( ConstPointer(C) )coarseCoefficients()+_sNodesBegin(d-1) , coarseCoefficients()+_sNodesBegin(d) );
1474 return coarseCoefficients;
1475 }
1476
1477 template< unsigned int Dim , class Real >
1478 template< class C , unsigned int ... FEMSigs >
1479 DenseNodeData< C , UIntPack< FEMSigs ... > > FEMTree< Dim , Real >::coarseCoefficients( const SparseNodeData< C , UIntPack< FEMSigs ... > >& coefficients ) const
1480 {
1481 DenseNodeData< C , UIntPack< FEMSigs ... > > coarseCoefficients( _sNodesEnd(_maxDepth-1) );
1482 memset( coarseCoefficients() , 0 , sizeof(C)*_sNodesEnd(_maxDepth-1) );
1483 ThreadPool::ParallelFor( _sNodesBegin(0) , _sNodesEnd(_maxDepth-1) , [&]( unsigned int , size_t i )
1484 {
1485 const C* c = coefficients( _sNodes.treeNodes[i] );
1486 if( c ) coarseCoefficients[i] = *c;
1487 }
1488 );
1489 typename FEMIntegrator::template RestrictionProlongation< UIntPack< FEMSigs ... > > rp;
1490 for( LocalDepth d=1 ; d<_maxDepth ; d++ ) _upSample( UIntPack< FEMSigs ... >() , rp , d , coarseCoefficients()+_sNodesBegin(d-1) , coarseCoefficients()+_sNodesBegin(d) );
1491 return coarseCoefficients;
1492 }
1493
1494 template< unsigned int Dim , class Real >
1495 template< class C , unsigned int ... FEMSigs >
1496 DenseNodeData< C , UIntPack< FEMSigs ... > > FEMTree< Dim , Real >::denseCoefficients( const SparseNodeData< C , UIntPack< FEMSigs ... > >& coefficients ) const
1497 {
1498 DenseNodeData< C , UIntPack< FEMSigs ... > > denseCoefficients( _sNodesEnd(_maxDepth) );
1499 memset( denseCoefficients() , 0 , sizeof(C)*_sNodesEnd(_maxDepth) );
1500 ThreadPool::ParallelFor( _sNodesBegin(0) , _sNodesEnd(_maxDepth) , [&]( unsigned int , size_t i )
1501 {
1502 const C* c = coefficients( _sNodes.treeNodes[i] );
1503 if( c ) denseCoefficients[i] = *c;
1504 }
1505 );
1506 return denseCoefficients;
1507 }
1508
1509 template< unsigned int Dim , class Real >
1510 template< unsigned int PointD , typename T , unsigned int ... FEMSigs >
1511 CumulativeDerivativeValues< T , Dim , PointD > FEMTree< Dim , Real >::_coarserFunctionValues( UIntPack< FEMSigs ... > , Point< Real , Dim > p , const ConstPointSupportKey< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& neighborKey , const FEMTreeNode* pointNode , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , ConstPointer( T ) solution ) const
1512 {
1513 typedef UIntPack< BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::SupportSize ... > SupportSizes;
1514
1515 CumulativeDerivativeValues< T , Dim , PointD > values;
1516 LocalDepth depth = _localDepth( pointNode );
1517 if( depth<0 ) return values;
1518 // Iterate over all basis functions that overlap the point at the coarser resolutions
1519 {
1520
1521 PointEvaluatorState< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > > peState;
1522 LocalDepth _d ; LocalOffset _off;
1523 _localDepthAndOffset( pointNode->parent , _d , _off );
1524 bsData.initEvaluationState( p , _d , _off , peState );
1525 const typename FEMTreeNode::template ConstNeighbors< SupportSizes >& neighbors = neighborKey.neighbors[ _localToGlobal( depth-1 ) ];
1526 ConstPointer( FEMTreeNode * const ) nodes = neighbors.neighbors().data;
1527
1528 for( unsigned int i=0 ; i<WindowSize< SupportSizes >::Size ; i++ ) if( _isValidFEM1Node( nodes[i] ) )
1529 {
1530 LocalDepth d ; LocalOffset off;
1531 _localDepthAndOffset( nodes[i] , d , off );
1532 CumulativeDerivativeValues< Real , Dim , PointD > temp = peState.template dValues< Real , CumulativeDerivatives< Dim , PointD > >( off );
1533 const T& _solution = solution[ nodes[i]->nodeData.nodeIndex ];
1534 for( int s=0 ; s<CumulativeDerivatives< Dim , PointD >::Size ; s++ ) values[s] += _solution * temp[s];
1535 }
1536 }
1537 return values;
1538 }
1539
1540 template< unsigned int Dim , class Real >
1541 template< unsigned int PointD , typename T , unsigned int ... FEMSigs >
1542 CumulativeDerivativeValues< T , Dim , PointD > FEMTree< Dim , Real >::_finerFunctionValues( UIntPack< FEMSigs ... > , Point< Real , Dim > p , const ConstPointSupportKey< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& neighborKey , const FEMTreeNode* pointNode , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , ConstPointer( T ) solution ) const
1543 {
1544 typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::SupportSize ... > > childNeighbors;
1545 typedef UIntPack< BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::SupportSize ... > SupportSizes;
1546
1547 CumulativeDerivativeValues< T , Dim , PointD > values;
1548 LocalDepth depth = _localDepth( pointNode );
1549 neighborKey.getChildNeighbors( _childIndex( pointNode , p ) , _localToGlobal( depth ) , childNeighbors );
1550 PointEvaluatorState< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > > peState;
1551 LocalDepth d ; LocalOffset off;
1552 _localDepthAndOffset( pointNode , d , off );
1553 int cIdx = _childIndex( pointNode , p );
1554 d++;
1555 for( int dd=0 ; dd<Dim ; dd++ ) off[dd] = (off[dd]<<1) | ( (cIdx>>dd) & 1 );
1556 bsData.initEvaluationState( p , d , off , peState );
1557 int s[Dim];
1558 WindowLoop< Dim >::Run
1559 (
1560 ZeroUIntPack< Dim >() , SupportSizes() ,
1561 [&]( int d , int i ){ s[d] = i; } ,
1562 [&]( const FEMTreeNode* node )
1563 {
1564 if( _isValidFEM1Node( node ) )
1565 {
1566 LocalDepth d ; LocalOffset off;
1567 _localDepthAndOffset( node , d , off );
1568 CumulativeDerivativeValues< Real , Dim , PointD > dValues = peState.template dValues< Real , CumulativeDerivatives< Dim , PointD > >( off );
1569 const T& _solution = solution[ node->nodeData.nodeIndex ];
1570 for( int s=0 ; s<CumulativeDerivatives< Dim , PointD >::Size ; s++ ) values[s] += _solution * dValues[s];
1571 }
1572 } ,
1573 childNeighbors.neighbors()
1574 );
1575 return values;
1576 }
1577
1578 template< unsigned int Dim , class Real >
1579 template< unsigned int ... FEMSigs , typename T , typename ... InterpolationInfos >
1580 int FEMTree< Dim , Real >::_getSliceMatrixAndProlongationConstraints( UIntPack< FEMSigs ... > , const typename BaseFEMIntegrator::template System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , SystemMatrixType< FEMSigs ... > &matrix , Pointer( Real ) diagonalR , const PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > >& bsData , LocalDepth depth , node_index_type nBegin , node_index_type nEnd , ConstPointer( T ) prolongedSolution , Pointer( T ) constraints , const CCStencil< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& ccStencil , const PCStencils< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& pcStencils , std::tuple< InterpolationInfos *... > interpolationInfos ) const
1581 {
1582 typedef UIntPack< FEMSignature< FEMSigs >::Degree ... > FEMDegrees;
1583 typedef UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > OverlapSizes;
1584 typedef UIntPack< ( -BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapStart ) ... > OverlapRadii;
1585 size_t range = nEnd - nBegin;
1586 matrix.resize( range );
1587 std::vector< ConstOneRingNeighborKey > neighborKeys( ThreadPool::NumThreads() );
1588 for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( _localToGlobal( depth ) );
1589 ThreadPool::ParallelFor( 0 , range , [&]( unsigned int thread , size_t i )
1590 {
1591 if( _isValidFEM1Node( _sNodes.treeNodes[i+nBegin] ) )
1592 {
1593 ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ];
1594 FEMTreeNode* node = _sNodes.treeNodes[i+nBegin];
1595 // Get the matrix row size
1596 typename FEMTreeNode::template ConstNeighbors< OverlapSizes > neighbors , pNeighbors;
1597 neighborKey.getNeighbors( OverlapRadii() , OverlapRadii() , node , pNeighbors , neighbors );
1598 // Set the row entries
1599 if( constraints ) constraints[i] = _setMatrixRowAndGetConstraintFromProlongation( UIntPack< FEMSigs ... >() , F , pNeighbors , neighbors , i , matrix , nBegin , pcStencils , ccStencil , bsData , prolongedSolution , interpolationInfos );
1600 else _setMatrixRowAndGetConstraintFromProlongation( UIntPack< FEMSigs ... >() , F , pNeighbors , neighbors , i , matrix , nBegin , pcStencils , ccStencil , bsData , prolongedSolution , interpolationInfos );
1601 if( diagonalR )
1602 if( _sNodes.treeNodes[i+nBegin]->nodeData.getDirichletElementFlag() ) diagonalR[i] = (Real)0.;
1603 else diagonalR[i] = (Real)1. / matrix[i][0].Value;
1604 }
1605 else if( constraints ) constraints[i] = T();
1606 }
1607 );
1608 #ifdef SHOW_WARNINGS
1609 #pragma message( "[WARNING] Why do we care if the node is not valid?" )
1610 #endif // SHOW_WARNINGS
1611 #if !defined( _WIN32 ) && !defined( _WIN64 )
1612 #ifdef SHOW_WARNINGS
1613 #pragma message( "[WARNING] I'm not sure how expensive this system call is on non-Windows system. (You may want to comment this out.)" )
1614 #endif // SHOW_WARNINGS
1615 #endif // !_WIN32 && !_WIN64
1616 return 1;
1617 }
1618
1619 template< unsigned int Dim , class Real >
1620 template< unsigned int ... FEMSigs , typename ... InterpolationInfos >
1621 SparseMatrix< Real , matrix_index_type > FEMTree< Dim , Real >::systemMatrix( UIntPack< FEMSigs ... > , typename BaseFEMIntegrator::template System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , LocalDepth depth , std::tuple< InterpolationInfos *... > interpolationInfos ) const
1622 {
1623 _setFEM1ValidityFlags( UIntPack< FEMSigs ... >() );
1624 typedef typename BaseFEMIntegrator::template System< UIntPack< FEMSignature< FEMSigs >::Degree ... > > BaseSystem;
1625 if( depth<0 || depth>_maxDepth ) MK_THROW( "System depth out of bounds: 0 <= " , depth , " <= " , _maxDepth );
1626 SparseMatrix< Real , matrix_index_type > matrix;
1627 F.init( depth );
1628 PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > > bsData( depth );
1629
1630 typedef UIntPack< ( -BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapStart ) ... > OverlapRadii;
1631 typedef UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > OverlapSizes;
1632
1633 CCStencil< UIntPack< FEMSignature< FEMSigs >::Degree ... > > stencil;
1634 PCStencils< UIntPack< FEMSignature< FEMSigs >::Degree ... > > stencils;
1635
1636 F.template setStencil< false >( stencil );
1637
1638 matrix.resize( _sNodesSize(depth) );
1639 std::vector< ConstOneRingNeighborKey > neighborKeys( ThreadPool::NumThreads() );
1640 for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( _localToGlobal( depth ) );
1641 ThreadPool::ParallelFor( _sNodesBegin(depth) , _sNodesEnd( depth ) , [&]( unsigned int thread , size_t i )
1642 {
1643 if( _isValidFEM1Node( _sNodes.treeNodes[i] ) )
1644 {
1645 node_index_type ii = (node_index_type)i - _sNodesBegin(depth);
1646 ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ];
1647 typename FEMTreeNode::template ConstNeighbors< OverlapSizes > neighbors;
1648 neighborKey.getNeighbors( OverlapRadii() , OverlapRadii() , _sNodes.treeNodes[i] , neighbors );
1649 _setMatrixRowAndGetConstraintFromProlongation( UIntPack< FEMSigs ... >() , F , neighbors , neighbors , ii , matrix , _sNodesBegin(depth) , stencils , stencil , bsData , ( ConstPointer( Real ) )NullPointer( Real ) , interpolationInfos );
1650 }
1651 }
1652 );
1653 return matrix;
1654 }
1655
1656 template< unsigned int Dim , class Real >
1657 template< unsigned int ... FEMSigs , typename ... InterpolationInfos >
1658 SparseMatrix< Real , matrix_index_type > FEMTree< Dim , Real >::prolongedSystemMatrix( UIntPack< FEMSigs ... > , typename BaseFEMIntegrator::template System< UIntPack<FEMSignature< FEMSigs >::Degree ... > >& F , LocalDepth highDepth , std::tuple< InterpolationInfos *... > interpolationInfos ) const
1659 {
1660 _setFEM1ValidityFlags( UIntPack< FEMSigs ... >() );
1661 if( highDepth<=0 || highDepth>_maxDepth ) MK_THROW( "System depth out of bounds: 0 < " , highDepth , " <= " , _maxDepth );
1662
1663 LocalDepth lowDepth = highDepth-1;
1664 SparseMatrix< Real , matrix_index_type > matrix;
1665 F.init( highDepth );
1666 PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > > bsData( highDepth );
1667 typedef UIntPack< ( -BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapStart ) ... > OverlapRadii;
1668 typedef UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > OverlapSizes;
1669
1670 PCStencils< UIntPack< FEMSignature< FEMSigs >::Degree ... > > stencils;
1671 F.template setStencils< true >( stencils );
1672
1673 matrix.resize( _sNodesSize(highDepth) );
1674 std::vector< ConstOneRingNeighborKey > neighborKeys( ThreadPool::NumThreads() );
1675 for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( _localToGlobal( highDepth ) );
1676 ThreadPool::ParallelFor( _sNodesBegin(highDepth) , _sNodesEnd(highDepth) , [&]( unsigned int thread , size_t i )
1677 {
1678 if( _isValidFEM1Node( _sNodes.treeNodes[i] ) )
1679 {
1680 node_index_type ii = i - _sNodesBegin(highDepth);
1681 int cIdx = (int)( _sNodes.treeNodes[i]-_sNodes.treeNodes[i]->parent->children );
1682
1683 ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ];
1684 typename FEMTreeNode::template ConstNeighbors< OverlapSizes > neighbors , pNeighbors;
1685 neighborKey.getNeighbors( OverlapRadii() , OverlapRadii() , _sNodes.treeNodes[i] , neighbors );
1686 neighborKey.getNeighbors( OverlapRadii() , OverlapRadii() , _sNodes.treeNodes[i]->parent , pNeighbors );
1687
1688 matrix.setRowSize( ii , _getProlongedMatrixRowSize< FEMSigs ... >( _sNodes.treeNodes[i] , pNeighbors ) );
1689 _setProlongedMatrixRow< Real >( F , neighbors , pNeighbors , matrix[ii] , _sNodesBegin(lowDepth) , stencils.data[cIdx] , bsData , interpolationInfos );
1690 }
1691 }
1692 );
1693 return matrix;
1694 }
1695
1696 template< unsigned int Dim , class Real >
1697 template< unsigned int ... FEMSigs , typename ValidNodeFunctor >
1698 SparseMatrix< Real , matrix_index_type > FEMTree< Dim , Real >::_downSampleMatrix( UIntPack< FEMSigs ... > , LocalDepth highDepth , ValidNodeFunctor validNodeFunctor ) const
1699 {
1700 SparseMatrix< Real , matrix_index_type > matrix;
1701 typedef UIntPack< FEMSignature< FEMSigs >::Degree ... > FEMDegrees;
1702 typedef UIntPack< BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::UpSampleSize ... > UpSampleSizes;
1703 typedef IntPack< BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::UpSampleStart ... > UpSampleStarts;
1704 typedef typename FEMTreeNode::template ConstNeighborKey< UIntPack< -BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::UpSampleStart ... > , UIntPack< BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::UpSampleEnd ... > > UpSampleKey;
1705
1706 LocalDepth lowDepth = highDepth-1;
1707 if( lowDepth<0 ) return matrix;
1708
1709 matrix.resize( _sNodesSize( lowDepth ) );
1710
1711 typename EvaluationData::UpSampleEvaluator* upSampleEvaluators[] = { new typename BSplineEvaluationData< FEMSigs >::UpSampleEvaluator() ... };
1712 for( int d=0 ; d<Dim ; d++ ) upSampleEvaluators[d]->set( lowDepth );
1713 std::vector< UpSampleKey > neighborKeys( ThreadPool::NumThreads() );
1714 for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( _localToGlobal( lowDepth ) );
1715
1716 DynamicWindow< double , UpSampleSizes > upSampleStencil;
1717 int lowCenter = ( 1<<lowDepth )>>1;
1718 double value[Dim+1] ; value[0] = 1;
1719 WindowLoop< Dim >::Run
1720 (
1721 ZeroUIntPack< Dim >() , UpSampleSizes() ,
1722 [&]( int d , int i ){ value[d+1] = value[d] * upSampleEvaluators[d]->value( lowCenter , 2*lowCenter + i + UpSampleStarts::Values[d] ); } ,
1723 [&]( double& stencilValue ){ stencilValue = value[Dim]; } ,
1724 upSampleStencil()
1725 );
1726
1727 ThreadPool::ParallelFor( _sNodesBegin(lowDepth) , _sNodesEnd(lowDepth) , [&]( unsigned int thread , size_t i )
1728 {
1729 if( validNodeFunctor( _sNodes.treeNodes[i] ) )
1730 {
1731 node_index_type _i = (node_index_type)i - _sNodesBegin(lowDepth);
1732 FEMTreeNode* pNode = _sNodes.treeNodes[i];
1733
1734 UpSampleKey& neighborKey = neighborKeys[ thread ];
1735 LocalDepth d ; LocalOffset off;
1736 _localDepthAndOffset( pNode , d , off );
1737 neighborKey.getNeighbors( pNode );
1738 typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::UpSampleSize ... > > neighbors;
1739 neighborKey.getChildNeighbors( 0 , _localToGlobal( d ) , neighbors );
1740
1741 int rowSize = 0;
1742 ConstPointer( FEMTreeNode * const ) nodes = neighbors.neighbors().data;
1743 for( int i=0 ; i<WindowSize< UpSampleSizes >::Size ; i++ ) if( _isValidFEM1Node( nodes[i] ) ) rowSize++;
1744
1745 matrix.setRowSize( _i , rowSize );
1746 matrix.rowSizes[_i] = 0;
1747
1748 // Want to make sure test if contained children are interior.
1749 // This is more conservative because we are test that overlapping children are interior
1750 bool isInterior = _isInteriorlyOverlapped( FEMDegrees() , FEMDegrees() , pNode );
1751
1752 if( isInterior )
1753 {
1754 ConstPointer( FEMTreeNode * const ) nodes = neighbors.neighbors().data;
1755 ConstPointer( double ) stencilValues = upSampleStencil().data;
1756 for( int i=0 ; i<WindowSize< UpSampleSizes >::Size ; i++ ) if( validNodeFunctor( nodes[i] ) )
1757 matrix[_i][ matrix.rowSizes[_i]++ ] = MatrixEntry< Real , matrix_index_type >( (matrix_index_type)( nodes[i]->nodeData.nodeIndex - _sNodesBegin(highDepth) ) , (Real)stencilValues[i] );
1758 }
1759 else
1760 {
1761 double upSampleValues[Dim][ UpSampleSizes::Max() ];
1762
1763 WindowLoop< Dim >::Run
1764 (
1765 ZeroUIntPack< Dim >() , UpSampleSizes() ,
1766 [&]( int d , int i ){ upSampleValues[d][i] = upSampleEvaluators[d]->value( off[d] , 2*off[d] + i + UpSampleStarts::Values[d] ); } ,
1767 [&]( void ){}
1768 );
1769
1770 double values[Dim+1] ; values[0] = 1;
1771 WindowLoop< Dim >::Run
1772 (
1773 ZeroUIntPack< Dim >() , UpSampleSizes() ,
1774 [&]( int d , int i ){ values[d+1] = values[d] * upSampleValues[d][i]; } ,
1775 [&]( const FEMTreeNode* node ){ if( validNodeFunctor( node ) ) matrix[_i][ matrix.rowSizes[_i]++ ] = MatrixEntry< Real , matrix_index_type >( (matrix_index_type)( node->nodeData.nodeIndex - _sNodesBegin(highDepth) ) , (Real)values[Dim] ); } ,
1776 neighbors.neighbors()
1777 );
1778 }
1779 }
1780 }
1781 );
1782 for( int d=0 ; d<Dim ; d++ ) delete upSampleEvaluators[d];
1783 return matrix;
1784 }
1785
1786 template< unsigned int Dim , class Real >
1787 template< unsigned int ... FEMSigs , typename ValidNodeFunctor >
1788 SparseMatrix< Real , matrix_index_type > FEMTree< Dim , Real >::_upSampleMatrix( UIntPack< FEMSigs ... > , LocalDepth highDepth , ValidNodeFunctor validNodeFunctor ) const
1789 {
1790 SparseMatrix< Real , matrix_index_type > matrix;
1791 matrix.resize( _sNodesSize( highDepth ) );
1792 LocalDepth lowDepth = highDepth-1;
1793 if( lowDepth<0 ) return matrix;
1794
1795 typedef typename BaseFEMIntegrator::RestrictionProlongation< UIntPack< FEMSignature< FEMSigs >::Degree ... > > BaseRestrictionProlongation;
1796 typedef typename FEMTreeNode::template ConstNeighborKey< UIntPack< - BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample0Start ... > , UIntPack< BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample1End ... > > DownSampleKey;
1797 typedef typename FEMTreeNode::template ConstNeighbors< UIntPack< ( - BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample0Start + BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample1End + 1 ) ... > > DownSampleNeighbors;
1798 typedef UIntPack< ( - BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample0Start + BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample1End + 1 ) ... > DownSampleSizes;
1799
1800 std::vector< DownSampleKey > neighborKeys( ThreadPool::NumThreads() );
1801 for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( _localToGlobal( lowDepth ) );
1802
1803 typename FEMIntegrator::template RestrictionProlongation< UIntPack< FEMSigs ... > > rp;
1804 ( ( BaseRestrictionProlongation& )rp ).init( highDepth );
1805 typename BaseRestrictionProlongation::DownSampleStencils downSampleStencils;
1806 rp.setStencils( downSampleStencils );
1807
1808 const int Start[2][Dim] = { { BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample0Start ... } , { BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample1Start ... } };
1809 const int End[2][Dim] = { { BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample0End ... } , { BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample1End ... } };
1810
1811 static const WindowLoopData< UIntPack< ( - BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample0Start + BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample1End + 1 ) ... > > loopData
1812 ( []( int c , int* start , int* end )
1813 {
1814 const int Start[2][Dim] = { { BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample0Start ... } , { BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample1Start ... } };
1815 const int End[2][Dim] = { { BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample0End ... } , { BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample1End ... } };
1816 for( int d=0 ; d<Dim ; d++ ) start[d] = Start[(c>>d)&1][d] - Start[0][d] , end[d] = - Start[0][d] + End[(c>>d)&1][d] + 1;
1817 }
1818 );
1819
1820 // For Dirichlet constraints, can't get to all children from parents because boundary nodes are invalid
1821 ThreadPool::ParallelFor( _sNodesBegin(highDepth) , _sNodesEnd(highDepth) , [&]( unsigned int thread , size_t i )
1822 {
1823 if( validNodeFunctor( _sNodes.treeNodes[i] ) )
1824 {
1825 node_index_type _i = (node_index_type)i - _sNodesBegin(highDepth);
1826
1827 FEMTreeNode *cNode = _sNodes.treeNodes[i];
1828 int c = (int)( cNode-cNode->parent->children );
1829
1830 DownSampleKey& neighborKey = neighborKeys[ thread ];
1831 DownSampleNeighbors neighbors = neighborKey.getNeighbors( cNode->parent );
1832 // Want to make sure test if contained children are interior.
1833 // This is more conservative because we are test that overlapping children are interior
1834 bool isInterior;
1835 {
1836 LocalDepth d ; LocalOffset off;
1837 _localDepthAndOffset( cNode->parent , d , off );
1838 isInterior = BaseFEMIntegrator::IsInteriorlyOverlapped( UIntPack< FEMSignature< FEMSigs >::Degree ... >() , UIntPack< FEMSignature< FEMSigs >::Degree ... >() , d , off );
1839 }
1840
1841 unsigned int size = loopData.size[c];
1842 const unsigned int *indices = loopData.indices[c];
1843 typename BaseRestrictionProlongation::DownSampleStencil& downSampleStencil = downSampleStencils.data[c];
1844 Pointer( const FEMTreeNode* ) nodes = neighbors.neighbors().data;
1845 Pointer( double ) downSampleValues = downSampleStencil.data;
1846
1847 int rowSize = 0;
1848 for( unsigned int i=0 ; i<size ; i++ )
1849 {
1850 unsigned int idx = indices[i];
1851 if( validNodeFunctor( nodes[idx] ) ) rowSize++;
1852 }
1853 matrix.setRowSize( _i , rowSize );
1854 matrix.rowSizes[_i] = 0;
1855
1856
1857 if( isInterior )
1858 {
1859 for( unsigned int i=0 ; i<size ; i++ )
1860 {
1861 unsigned int idx = indices[i];
1862 if( validNodeFunctor( nodes[idx] ) ) matrix[_i][ matrix.rowSizes[_i]++ ] = MatrixEntry< Real , matrix_index_type >( (matrix_index_type)( nodes[idx]->nodeData.nodeIndex - _sNodesBegin(lowDepth) ) , (Real)downSampleValues[idx] );
1863 }
1864 }
1865 else
1866 {
1867 LocalDepth d ; LocalOffset off;
1868 _localDepthAndOffset( cNode , d , off );
1869 for( unsigned int i=0 ; i<size ; i++ )
1870 {
1871 unsigned int idx = indices[i];
1872 if( validNodeFunctor( nodes[idx] ) )
1873 {
1874 LocalDepth _d ; LocalOffset _off;
1875 _localDepthAndOffset( nodes[idx] , _d , _off );
1876 matrix[_i][ matrix.rowSizes[_i]++ ] = MatrixEntry< Real , matrix_index_type >( (matrix_index_type)( nodes[idx]->nodeData.nodeIndex - _sNodesBegin(lowDepth) ) , (Real)rp.upSampleCoefficient( _off , off ) );
1877 }
1878 }
1879 }
1880 }
1881 }
1882 );
1883 return matrix;
1884 }
1885
1886 template< unsigned int Dim , class Real >
1887 template< unsigned int ... FEMSigs , typename ValidNodeFunctor >
1888 SparseMatrix< Real , matrix_index_type > FEMTree< Dim , Real >::_restrictSystemMatrix( UIntPack< FEMSigs ... > , LocalDepth highDepth , const SparseMatrix< Real , matrix_index_type > &highM , ValidNodeFunctor validNodeFunctor ) const
1889 {
1890 SparseMatrix< Real , matrix_index_type > lowM , R , P;
1891 LocalDepth lowDepth = highDepth-1;
1892 if( lowDepth<0 ) return lowM;
1893 R = _downSampleMatrix( UIntPack< FEMSigs ... >() , highDepth , validNodeFunctor );
1894 P = _upSampleMatrix( UIntPack< FEMSigs ... >() , highDepth , validNodeFunctor );
1895 #if 1
1896 static const int StartOffset[] = { BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapStart ... };
1897 static const unsigned int Size = WindowSize< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... > >::Size;
1898
1899 lowM.resize( _sNodesSize( lowDepth ) );
1900
1901 // Compute the window indices of all nodes at the coarser resolution
1902 static const unsigned int StartOffsetIndex = GetWindowIndex( UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... >() , StartOffset );
1903 std::vector< unsigned int > windowIndices( _sNodesSize(lowDepth) );
1904 ThreadPool::ParallelFor( _sNodesBegin(lowDepth) , _sNodesEnd(lowDepth) , [&]( unsigned int thread , size_t i )
1905 {
1906 node_index_type _i = (node_index_type)i - _sNodesBegin(lowDepth);
1907 LocalDepth d ; LocalOffset off;
1908 _sNodes.treeNodes[i]->depthAndOffset( d , off );
1909 windowIndices[_i] = GetWindowIndex( UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree >::OverlapSize ... >() , off );
1910 } );
1911
1912 // Iterate over all low-depth nodes
1913 ThreadPool::ParallelFor( _sNodesBegin(lowDepth) , _sNodesEnd(lowDepth) , [&]( unsigned int thread , size_t i )
1914 {
1915 if( validNodeFunctor( _sNodes.treeNodes[i] ) )
1916 {
1917 MatrixEntry< Real , matrix_index_type > row[Size];
1918 for( int s=0 ; s<Size ; s++ ) row[s] = MatrixEntry< Real , matrix_index_type >( -1 , (Real)0 );
1919
1920 // Indices of the form "_X" are depth-local
1921 node_index_type _i = (node_index_type)i - _sNodesBegin(lowDepth);
1922
1923 unsigned int _ii = windowIndices[_i] + StartOffsetIndex;
1924 // Iterate over all child nodes
1925 for( int j=0 ; j<R.rowSizes[_i] ; j++ )
1926 {
1927 node_index_type _j = (node_index_type)R[_i][j].N;
1928 // Iterate over all neighbors of the child node
1929 for( int k=0 ; k<highM.rowSizes[_j] ; k++ ) if( highM[_j][k].Value )
1930 {
1931 node_index_type _k = highM[_j][k].N;
1932 Real _matrixValue = highM[_j][k].Value * R[_i][j].Value;
1933 // Iterate over everything the neighbor node restrict to
1934 for( int l=0 ; l<P.rowSizes[_k] ; l++ )
1935 {
1936 node_index_type _l = (node_index_type)P[_k][l].N;
1937 Real __matrixValue = _matrixValue * P[_k][l].Value;
1938 int ii = windowIndices[_l] - _ii;
1939 row[ii].N = (matrix_index_type)_l;
1940 row[ii].Value += __matrixValue;
1941 }
1942 }
1943 }
1944 int rowSize = 0;
1945 for( int s=0 ; s<Size ; s++ ) if( row[s].N!=-1 ) rowSize++;
1946 lowM.setRowSize( _i , rowSize );
1947 lowM.rowSizes[_i] = 0;
1948 for( int s=0 ; s<Size ; s++ ) if( row[s].N!=-1 ) lowM[_i][ lowM.rowSizes[_i]++ ] = row[s];
1949 }
1950 } );
1951 return lowM;
1952 #else
1953 return R * highM * P;
1954 #endif
1955 }
1956
1957 template< unsigned int Dim , class Real >
1958 template< unsigned int ... FEMSigs >
1959 SparseMatrix< Real , matrix_index_type > FEMTree< Dim , Real >::upSampleMatrix( UIntPack< FEMSigs ... > , LocalDepth highDepth ) const
1960 {
1961 _setFEM1ValidityFlags( UIntPack< FEMSigs ... >() );
1962 return _upSampleMatrix( UIntPack< FEMSigs ... >() , highDepth , [&]( const FEMTreeNode *node ){ return _isValidFEM1Node( node ) && ( _localDepth(node)<_baseDepth || !node->nodeData.getDirichletElementFlag() ); } );
1963 }
1964
1965 template< unsigned int Dim , class Real >
1966 template< unsigned int ... FEMSigs >
1967 SparseMatrix< Real , matrix_index_type > FEMTree< Dim , Real >::downSampleMatrix( UIntPack< FEMSigs ... > , LocalDepth highDepth ) const
1968 {
1969 _setFEM1ValidityFlags( UIntPack< FEMSigs ... >() );
1970 return _downSampleMatrix( UIntPack< FEMSigs ... >() , highDepth , [&]( const FEMTreeNode *node ){ return _isValidFEM1Node( node ) && ( _localDepth(node)<_baseDepth || !node->nodeData.getDirichletElementFlag() ); } );
1971 }
1972
1973 template< unsigned int Dim , class Real >
1974 template< unsigned int ... FEMSigs , typename ... InterpolationInfos >
1975 SparseMatrix< Real , matrix_index_type > FEMTree< Dim , Real >::fullSystemMatrix( UIntPack< FEMSigs ... > , typename BaseFEMIntegrator::template System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , LocalDepth depth , std::tuple< InterpolationInfos *... > interpolationInfos ) const
1976 {
1977 SparseMatrix< Real , matrix_index_type > M;
1978 std::vector< SparseMatrix< Real , matrix_index_type > > systemMatrices( depth+1 );
1979 std::vector< SparseMatrix< Real , matrix_index_type > > prolongedSystemMatrices( depth );
1980 std::vector< std::vector< SparseMatrix< Real , matrix_index_type > > > upSampleMatrices( depth-1 );
1981
1982 for( int d=0 ; d<depth-1 ; d++ ) upSampleMatrices[d].resize( depth );
1983 node_index_type size = _sNodesEnd( depth );
1984 for( int d=0 ; d<=depth ; d++ )
1985 {
1986 SparseMatrix< Real , matrix_index_type >& M = systemMatrices[d];
1987 M.resize( size );
1988 SparseMatrix< Real , matrix_index_type > _M = systemMatrix< Real >( UIntPack< FEMSigs ... >() , F , d , interpolationInfos );
1989 ThreadPool::ParallelFor( 0 , _M.rows() , [&]( unsigned int , size_t i )
1990 {
1991 M.setRowSize( (matrix_index_type)( i + _sNodesBegin(d) ) , _M.rowSize(i) );
1992 for( int j=0 ; j<_M.rowSize(i) ; j++ ) M[i+_sNodesBegin(d)][j] = MatrixEntry< Real , matrix_index_type >( _M[i][j].N + (matrix_index_type)_sNodesBegin(d) , _M[i][j].Value );
1993 }
1994 );
1995 }
1996 for( int d=0 ; d<depth ; d++ )
1997 {
1998 SparseMatrix< Real , matrix_index_type >& M = prolongedSystemMatrices[d];
1999 M.resize( size );
2000 SparseMatrix< Real , matrix_index_type > _M = prolongedSystemMatrix< Real >( UIntPack< FEMSigs ... >() , F , d+1 , interpolationInfos );
2001 ThreadPool::ParallelFor( 0 , _M.rows() , [&]( unsigned int , size_t i )
2002 {
2003 M.setRowSize( i + (matrix_index_type)_sNodesBegin(d+1) , _M.rowSize(i) );
2004 for( int j=0 ; j<_M.rowSize(i) ; j++ ) M[i+_sNodesBegin(d+1)][j] = MatrixEntry< Real , matrix_index_type >( _M[i][j].N + (matrix_index_type)_sNodesBegin(d) , _M[i][j].Value );
2005 }
2006 );
2007 }
2008 for( int d=0 ; d<depth-1 ; d++ )
2009 {
2010 SparseMatrix< Real , matrix_index_type >& M = upSampleMatrices[d][d+1];
2011 M.resize( size );
2012 SparseMatrix< Real , matrix_index_type > _M = downSampleMatrix( UIntPack< FEMSigs ... >() , d+1 ).transpose( _sNodesSize( d+1 ) );
2013 ThreadPool::ParallelFor( 0 , _M.rows() , [&]( unsigned int , size_t i )
2014 {
2015 M.setRowSize( i + (matrix_index_type)_sNodesBegin(d+1) , _M.rowSize(i) );
2016 for( int j=0 ; j<_M.rowSize(i) ; j++ ) M[i+_sNodesBegin(d+1)][j] = MatrixEntry< Real , matrix_index_type >( _M[i][j].N + (matrix_index_type)_sNodesBegin(d) , _M[i][j].Value );
2017 }
2018 );
2019 for( int dd=0 ; dd<d ; dd++ ) upSampleMatrices[dd][d+1] = upSampleMatrices[d][d+1] * upSampleMatrices[dd][d];
2020 }
2021
2022 auto Matrix = [&]( int d1 , int d2 )
2023 {
2024 SparseMatrix< Real , matrix_index_type > _M;
2025 int _d1 = d1<d2 ? d1 : d2 , _d2 = d2<d1 ? d1 : d2;
2026 if ( _d1==_d2 ) _M = systemMatrices[_d1];
2027 else if( _d2==_d1+1 ) _M = prolongedSystemMatrices[_d2-1];
2028 else _M = prolongedSystemMatrices[_d2-1] * upSampleMatrices[_d1][_d2-1];
2029 if( d2<d1 ) return _M.transpose( size );
2030 else return _M;
2031 };
2032
2033 for( int d1=0 ; d1<=depth ; d1++ )
2034 {
2035 M += Matrix( d1 , d1 );
2036 for( int d2=0 ; d2<=depth ; d2++ ) if( d1!=d2 )
2037 {
2038 SparseMatrix< Real , matrix_index_type > _M = Matrix( d1 , d2 );
2039 ThreadPool::ParallelFor( 0 , _M.rows() , [&]( unsigned int , size_t i )
2040 {
2041 if( _M.rowSize(i) )
2042 {
2043 size_t oldSize = M.rowSize(i);
2044 M.resetRowSize( i , oldSize + _M.rowSize(i) );
2045 for( int j=0 ; j<_M.rowSize(i) ; j++ ) M[i][oldSize+j] = _M[i][j];
2046 }
2047 }
2048 );
2049 }
2050 }
2051 return M;
2052 }
2053
2054 template< unsigned int Dim , class Real >
2055 template< class C , typename ArrayWrapper , unsigned int ... Degrees , unsigned int ... FEMSigs >
2056 void FEMTree< Dim , Real >::_downSample( UIntPack< FEMSigs ... > , typename BaseFEMIntegrator::template RestrictionProlongation< UIntPack< Degrees ... > >& rp , LocalDepth highDepth , ArrayWrapper finerConstraints , Pointer( C ) coarserConstraints ) const
2057 {
2058 LocalDepth lowDepth = highDepth-1;
2059 if( lowDepth<0 ) return;
2060
2061 typedef typename BaseFEMIntegrator::RestrictionProlongation< UIntPack< Degrees ... > > BaseRestrictionProlongation;
2062 typedef typename FEMTreeNode::template ConstNeighborKey< UIntPack< ( - BSplineSupportSizes< Degrees >::UpSampleStart ) ... > , UIntPack< BSplineSupportSizes< Degrees >::UpSampleEnd ... > > UpSampleKey;
2063 typedef typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineSupportSizes< Degrees >::UpSampleSize ... > > UpSampleNeighbors;
2064 typedef UIntPack< BSplineSupportSizes< Degrees >::UpSampleSize ... > UpSampleSizes;
2065
2066 std::vector< UpSampleKey > neighborKeys( ThreadPool::NumThreads() );
2067 for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( _localToGlobal( lowDepth ) );
2068
2069 ( ( BaseRestrictionProlongation& )rp ).init( highDepth );
2070 typename BaseRestrictionProlongation::UpSampleStencil upSampleStencil;
2071 rp.setStencil( upSampleStencil );
2072
2073 ThreadPool::ParallelFor( _sNodesBegin(lowDepth) , _sNodesEnd(lowDepth) , [&]( unsigned int thread , size_t i )
2074 {
2075 if( _isValidFEM1Node( _sNodes.treeNodes[i] ) )
2076 {
2077 FEMTreeNode* pNode = _sNodes.treeNodes[i];
2078 UpSampleKey& neighborKey = neighborKeys[ thread ];
2079 LocalDepth d ; LocalOffset off;
2080 _localDepthAndOffset( pNode , d , off );
2081
2082 neighborKey.getNeighbors( pNode );
2083 UpSampleNeighbors neighbors;
2084 neighborKey.getChildNeighbors( 0 , _localToGlobal( d ) , neighbors );
2085
2086 C &coarseConstraint = coarserConstraints[ i-_sNodesBegin(lowDepth) ];
2087
2088 // Want to make sure test if contained children are interior.
2089 // This is more conservative because we are test that overlapping children are interior
2090 bool isInterior = BaseFEMIntegrator::IsInteriorlyOverlapped( UIntPack< Degrees ... >() , UIntPack< Degrees ... >() , d , off );
2091 if( isInterior )
2092 {
2093 Pointer( const FEMTreeNode* ) nodes = neighbors.neighbors().data;
2094 Pointer( double ) stencilValues = upSampleStencil.data;
2095 for( unsigned int i=0 ; i<WindowSize< UpSampleSizes >::Size ; i++ )
2096 if( _isValidFEM1Node( nodes[i] ) ) coarseConstraint += (C)( finerConstraints[ nodes[i]->nodeData.nodeIndex - _sNodesBegin(highDepth) ] * (Real)stencilValues[i] );
2097 }
2098 else
2099 {
2100 ConstPointer( FEMTreeNode * const ) nodes = neighbors.neighbors().data;
2101 for( int i=0 ; i<WindowSize< UpSampleSizes >::Size ; i++ ) if( _isValidFEM1Node( nodes[i] ) )
2102 {
2103 LocalDepth _d ; LocalOffset _off;
2104 _localDepthAndOffset( nodes[i] , _d , _off );
2105 coarseConstraint += (C)( finerConstraints[ nodes[i]->nodeData.nodeIndex - _sNodesBegin(highDepth) ] * (Real)rp.upSampleCoefficient( off , _off ) );
2106 }
2107 }
2108 }
2109 }
2110 );
2111 }
2112
2113 template< unsigned int Dim , class Real >
2114 template< unsigned int ... FEMSigs >
2115 DenseNodeData< Real , UIntPack< FEMSigs ... > > FEMTree< Dim , Real >::supportWeights( UIntPack< FEMSigs ... > ) const
2116 {
2117 typedef typename BaseFEMIntegrator::template System< UIntPack< FEMSignature< FEMSigs >::Degree ... > > BaseSystem;
2118 typedef typename BaseFEMIntegrator::template Constraint< UIntPack< FEMSignature< FEMSigs >::Degree ... > , IsotropicUIntPack< Dim , 0 > , 1 > BaseConstraint;
2119 typedef UIntPack< ( BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree , 0 >::OverlapSize ) ... > OverlapSizes;
2120 typedef UIntPack< ( -BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree , 0 >::OverlapStart ) ... > LeftFEMCOverlapRadii;
2121 typedef UIntPack< ( BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree , 0 >::OverlapEnd ) ... > RightFEMCOverlapRadii;
2122 _setFEM1ValidityFlags( UIntPack< FEMSigs ... >() );
2123 typename FEMIntegrator::template ScalarConstraint< UIntPack< FEMSigs ... > , ZeroUIntPack< Dim > , IsotropicUIntPack< Dim , FEMTrivialSignature > , ZeroUIntPack< Dim > > F( {1.} );
2124 DenseNodeData< Real , UIntPack< FEMSigs ... > > weights = initDenseNodeData( UIntPack< FEMSigs ... >() );
2125 typename BaseConstraint::CCStencil stencil;
2126 std::vector< ConstOneRingNeighborKey > neighborKeys( ThreadPool::NumThreads() );
2127 for( int d=0 ; d<=_maxDepth ; d++ )
2128 {
2129 for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( _localToGlobal( d ) );
2130 F.init( d );
2131 F.template setStencil< false >( stencil );
2132 ThreadPool::ParallelFor( _sNodesBegin(d) , _sNodesEnd(d) , [&]( unsigned int thread , size_t i )
2133 {
2134 if( _isValidFEM1Node( _sNodes.treeNodes[i] ) )
2135 {
2136 ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ];
2137
2138 FEMTreeNode* node = _sNodes.treeNodes[i];
2139 typename FEMTreeNode::template ConstNeighbors< OverlapSizes > neighbors;
2140 LocalOffset off;
2141 {
2142 LocalDepth d ; _localDepthAndOffset( node , d , off );
2143 }
2144 neighborKey.getNeighbors( LeftFEMCOverlapRadii() , RightFEMCOverlapRadii() , node , neighbors );
2145 bool isInterior = BaseFEMIntegrator::IsInteriorlyOverlapped( UIntPack< FEMSignature< FEMSigs >::Degree ... >() , ZeroUIntPack< Dim >() , d , off );
2146 double sum=0 , totalSum=0;
2147 if( isInterior )
2148 {
2149 ConstPointer( FEMTreeNode * const ) nodes = neighbors.neighbors().data;
2150 ConstPointer( Point< double , 1 > ) stencilValues = stencil.data;
2151 for( int i=0 ; i<WindowSize< UIntPack< BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree , 0 >::OverlapSize ... > >::Size ; i++ )
2152 {
2153 double s = stencilValues[i][0];
2154 totalSum += s;
2155 if( isValidSpaceNode( nodes[i] ) ) sum += s;
2156 }
2157 }
2158 else
2159 {
2160 static const int OverlapStart [] = { BSplineOverlapSizes< FEMSignature< FEMSigs >::Degree , 0 >::OverlapStart ... };
2161 LocalOffset _off;
2162 WindowLoop< Dim >::Run
2163 (
2164 IsotropicUIntPack< Dim , 0 >() , OverlapSizes() ,
2165 [&]( int d , int i ){ _off[d] = off[d]+i+OverlapStart[d]; } ,
2166 [&]( const FEMTreeNode* node )
2167 {
2168 double s = F.ccIntegrate( off , _off )[0];
2169 totalSum += s;
2170 if( isValidSpaceNode( node ) ) sum += s;
2171 } ,
2172 neighbors.neighbors()
2173 );
2174 }
2175 weights[i] = (Real)( sum / totalSum );
2176 }
2177 }
2178 );
2179 }
2180 return weights;
2181 }
2182 template< unsigned int Dim , class Real >
2183 template< unsigned int ... FEMSigs >
2184 DenseNodeData< Real , UIntPack< FEMSigs ... > > FEMTree< Dim , Real >::prolongationWeights( UIntPack< FEMSigs ... > , bool prolongToChildren ) const
2185 {
2186 DenseNodeData< Real , UIntPack< FEMSigs ... > > weights = initDenseNodeData( UIntPack< FEMSigs ... >() );
2187
2188 _setFEM1ValidityFlags( UIntPack< FEMSigs ... >() );
2189 typedef typename BaseFEMIntegrator::RestrictionProlongation< UIntPack< FEMSignature< FEMSigs >::Degree ... > > BaseRestrictionProlongation;
2190 typedef typename FEMIntegrator::template RestrictionProlongation< UIntPack< FEMSigs ... > > RestrictionProlongation;
2191
2192 typename BaseRestrictionProlongation::DownSampleStencils downSampleStencils;
2193 RestrictionProlongation rp;
2194
2195 typedef typename FEMTreeNode::template ConstNeighborKey< UIntPack< ( - BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::UpSampleStart ) ... > , UIntPack< BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::UpSampleEnd ... > > UpSampleKey;
2196 typedef typename FEMTreeNode::template ConstNeighbors< UIntPack< BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::UpSampleSize ... > > UpSampleNeighbors;
2197 typedef typename FEMTreeNode::template ConstNeighborKey< UIntPack< - BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample0Start ... > , UIntPack< BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample1End ... > > DownSampleKey;
2198 typedef typename FEMTreeNode::template ConstNeighbors< UIntPack< ( - BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample0Start + BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample1End + 1 ) ... > > DownSampleNeighbors;
2199 const int UpSampleStart[] = { BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::UpSampleStart ... };
2200 const int DownSampleStart[2][Dim] = { { BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample0Start ... } , { BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample1Start ... } };
2201 const int DownSampleEnd[2][Dim] = { { BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample0End ... } , { BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample1End ... } };
2202
2203 std::vector< UpSampleKey > neighborKeys( ThreadPool::NumThreads() );
2204 for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( _localToGlobal( _maxDepth-1 ) );
2205
2206 ThreadPool::ParallelFor( _sNodesBegin(_maxDepth) , _sNodesEnd(_maxDepth) , [&]( unsigned int , size_t i ){ weights[i] = (Real)0.; } );
2207
2208 for( int lowDepth=0 ; lowDepth<_maxDepth ; lowDepth++ )
2209 {
2210 ( ( BaseRestrictionProlongation& )rp ).init( lowDepth+1 );
2211 typename BaseRestrictionProlongation::UpSampleStencil upSampleStencil;
2212 rp.setStencil( upSampleStencil );
2213
2214 ThreadPool::ParallelFor( _sNodesBegin(lowDepth) , _sNodesEnd(lowDepth) , [&]( unsigned int thread , size_t i )
2215 {
2216 if( _isValidFEM1Node( _sNodes.treeNodes[i] ) )
2217 {
2218 FEMTreeNode* pNode = _sNodes.treeNodes[i];
2219 UpSampleKey& neighborKey = neighborKeys[ thread ];
2220 LocalDepth d ; LocalOffset pOff;
2221 _localDepthAndOffset( pNode , d , pOff );
2222
2223 neighborKey.getNeighbors( pNode );
2224 UpSampleNeighbors neighbors;
2225 neighborKey.getChildNeighbors( 0 , _localToGlobal( d ) , neighbors );
2226
2227 double partialSum = 0 , totalSum = 0;
2228
2229 // Want to make sure test if contained children are interior.
2230 // This is more conservative because we are test that overlapping children are interior
2231 bool isInterior = BaseFEMIntegrator::IsInteriorlyOverlapped( UIntPack< FEMSignature< FEMSigs >::Degree ... >() , UIntPack< FEMSignature< FEMSigs >::Degree ... >() , d , pOff );
2232
2233 LocalOffset cOff;
2234 if( isInterior )
2235 {
2236 WindowLoop< Dim >::Run
2237 (
2238 IsotropicUIntPack< Dim , 0 >() , UIntPack< BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::UpSampleSize ... >() ,
2239 [&]( int d , int i ){ cOff[d] = UpSampleStart[d] + pOff[d]*2 + i; } ,
2240 [&]( const FEMTreeNode* node , double stencilValue )
2241 {
2242 if( FEMIntegrator::IsValidFEMNode( UIntPack< FEMSigs ... >() , lowDepth+1 , cOff ) )
2243 {
2244 totalSum += stencilValue;
2245 if( _isValidFEM1Node( node ) ) partialSum += stencilValue;
2246 }
2247 } ,
2248 neighbors.neighbors() , upSampleStencil()
2249 );
2250 }
2251 else
2252 {
2253 WindowLoop< Dim >::Run
2254 (
2255 IsotropicUIntPack< Dim , 0 >() , UIntPack< BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::UpSampleSize ... >() ,
2256 [&]( int d , int i ){ cOff[d] = UpSampleStart[d] + pOff[d]*2 + i; } ,
2257 [&]( const FEMTreeNode* node )
2258 {
2259 if( FEMIntegrator::IsValidFEMNode( UIntPack< FEMSigs ... >() , lowDepth+1 , cOff ) )
2260 {
2261 double stencilValue = rp.upSampleCoefficient( pOff , cOff );
2262 totalSum += stencilValue;
2263 if( _isValidFEM1Node( node ) ) partialSum += stencilValue;
2264 }
2265 } ,
2266 neighbors.neighbors()
2267 );
2268 }
2269 weights[i] = (Real)( partialSum / totalSum );
2270 }
2271 }
2272 );
2273 }
2274 if( prolongToChildren )
2275 {
2276 std::vector< DownSampleKey > neighborKeys( ThreadPool::NumThreads() );
2277 for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( _localToGlobal( _maxDepth-1 ) );
2278
2279 for( int lowDepth=_maxDepth-1 ; lowDepth>=0 ; lowDepth-- )
2280 {
2281 ( ( BaseRestrictionProlongation& )rp ).init( lowDepth+1 );
2282 typename BaseRestrictionProlongation::DownSampleStencils downSampleStencils;
2283 rp.setStencils( downSampleStencils );
2284
2285 ThreadPool::ParallelFor( _sNodesBegin(lowDepth+1) , _sNodesEnd(lowDepth+1) , [&]( unsigned int thread , size_t i )
2286 {
2287 if( _isValidFEM1Node( _sNodes.treeNodes[i] ) )
2288 {
2289 FEMTreeNode *cNode = _sNodes.treeNodes[i];
2290 int c = (int)( cNode-cNode->parent->children );
2291
2292 DownSampleKey& neighborKey = neighborKeys[ thread ];
2293 LocalDepth d ; LocalOffset cOff;
2294 _localDepthAndOffset( cNode , d , cOff );
2295 DownSampleNeighbors neighbors = neighborKey.getNeighbors( cNode->parent );
2296 // Want to make sure test if contained children are interior.
2297 // This is more conservative because we are test that overlapping children are interior
2298 bool isInterior;
2299 {
2300 LocalDepth d ; LocalOffset pOff;
2301 _localDepthAndOffset( cNode->parent , d , pOff );
2302 isInterior = BaseFEMIntegrator::IsInteriorlyOverlapped( UIntPack< FEMSignature< FEMSigs >::Degree ... >() , UIntPack< FEMSignature< FEMSigs >::Degree ... >() , d , pOff );
2303 }
2304
2305 typename BaseRestrictionProlongation::DownSampleStencil& downSampleStencil = downSampleStencils.data[c];
2306 int start[Dim] , end[Dim];
2307 for( int d=0 ; d<Dim ; d++ ) start[d] = DownSampleStart[(c>>d)&1][d] - DownSampleStart[0][d] , end[d] = - DownSampleStart[0][d] + DownSampleEnd[(c>>d)&1][d] + 1;
2308
2309 double partialSum = 0 , totalSum = 0;
2310 if( isInterior )
2311 {
2312 WindowLoop< Dim >::Run
2313 (
2314 start , end ,
2315 [&]( int , int ){ } ,
2316 [&]( const FEMTreeNode* node , double stencilValue ){ if( _isValidFEM1Node( node ) ) totalSum += stencilValue , partialSum += weights[ node->nodeData.nodeIndex ] * stencilValue; } ,
2317 neighbors.neighbors() , downSampleStencil()
2318 );
2319 }
2320 else
2321 {
2322 WindowLoop< Dim >::Run
2323 (
2324 start , end ,
2325 [&]( int , int ){ } ,
2326 [&]( const FEMTreeNode* node )
2327 {
2328 if( _isValidFEM1Node( node ) )
2329 {
2330 LocalDepth d ; LocalOffset pOff;
2331 _localDepthAndOffset( node , d , pOff );
2332 double stencilValue = rp.upSampleCoefficient( pOff , cOff );
2333 totalSum += stencilValue , partialSum += weights[ node->nodeData.nodeIndex ] * stencilValue;
2334 }
2335 } ,
2336 neighbors.neighbors()
2337 );
2338 }
2339 weights[i] = (Real)( partialSum / totalSum );
2340 }
2341 }
2342 );
2343 }
2344 }
2345 return weights;
2346 }
2347
2348 template< unsigned int Dim , class Real >
2349 template< class C , typename ArrayWrapper , unsigned int ... Degrees , unsigned int ... FEMSigs >
2350 void FEMTree< Dim , Real >::_upSample( UIntPack< FEMSigs ... > , typename BaseFEMIntegrator::template RestrictionProlongation< UIntPack< Degrees ... > >& rp , LocalDepth highDepth , ArrayWrapper coarserCoefficients , Pointer( C ) finerCoefficients ) const
2351 {
2352 LocalDepth lowDepth = highDepth-1;
2353 if( lowDepth<0 ) return;
2354 typedef typename BaseFEMIntegrator::RestrictionProlongation< UIntPack< Degrees ... > > BaseRestrictionProlongation;
2355 typedef typename FEMTreeNode::template ConstNeighborKey< UIntPack< - BSplineSupportSizes< Degrees >::DownSample0Start ... > , UIntPack< BSplineSupportSizes< Degrees >::DownSample1End ... > > DownSampleKey;
2356 typedef typename FEMTreeNode::template ConstNeighbors< UIntPack< ( - BSplineSupportSizes< Degrees >::DownSample0Start + BSplineSupportSizes< Degrees >::DownSample1End + 1 ) ... > > DownSampleNeighbors;
2357 typedef UIntPack< ( - BSplineSupportSizes< Degrees >::DownSample0Start + BSplineSupportSizes< Degrees >::DownSample1End + 1 ) ... > DownSampleSizes;
2358
2359 std::vector< DownSampleKey > neighborKeys( ThreadPool::NumThreads() );
2360 for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( _localToGlobal( lowDepth ) );
2361
2362 ( ( BaseRestrictionProlongation& )rp ).init( highDepth );
2363 typename BaseRestrictionProlongation::DownSampleStencils downSampleStencils;
2364 rp.setStencils( downSampleStencils );
2365
2366 const int Start[2][Dim] = { { BSplineSupportSizes< Degrees >::DownSample0Start ... } , { BSplineSupportSizes< Degrees >::DownSample1Start ... } };
2367 const int End[2][Dim] = { { BSplineSupportSizes< Degrees >::DownSample0End ... } , { BSplineSupportSizes< Degrees >::DownSample1End ... } };
2368
2369 static const WindowLoopData< UIntPack< ( - BSplineSupportSizes< Degrees >::DownSample0Start + BSplineSupportSizes< Degrees >::DownSample1End + 1 ) ... > > loopData
2370 ( []( int c , int* start , int* end )
2371 {
2372 const int Start[2][Dim] = { { BSplineSupportSizes< Degrees >::DownSample0Start ... } , { BSplineSupportSizes< Degrees >::DownSample1Start ... } };
2373 const int End[2][Dim] = { { BSplineSupportSizes< Degrees >::DownSample0End ... } , { BSplineSupportSizes< Degrees >::DownSample1End ... } };
2374 for( int d=0 ; d<Dim ; d++ ) start[d] = Start[(c>>d)&1][d] - Start[0][d] , end[d] = - Start[0][d] + End[(c>>d)&1][d] + 1;
2375 }
2376 );
2377 // For Dirichlet constraints, can't get to all children from parents because boundary nodes are invalid
2378 ThreadPool::ParallelFor( _sNodesBegin(highDepth) , _sNodesEnd(highDepth) , [&]( unsigned int thread , size_t i )
2379 {
2380 if( _isValidFEM1Node( _sNodes.treeNodes[i] ) )
2381 {
2382 FEMTreeNode *cNode = _sNodes.treeNodes[i];
2383 int c = (int)( cNode-cNode->parent->children );
2384
2385 DownSampleKey& neighborKey = neighborKeys[ thread ];
2386 DownSampleNeighbors neighbors = neighborKey.getNeighbors( cNode->parent );
2387 // Want to make sure test if contained children are interior.
2388 // This is more conservative because we are test that overlapping children are interior
2389 bool isInterior;
2390 {
2391 LocalDepth d ; LocalOffset off;
2392 _localDepthAndOffset( cNode->parent , d , off );
2393 isInterior = BaseFEMIntegrator::IsInteriorlyOverlapped( UIntPack< Degrees ... >() , UIntPack< Degrees ... >() , d , off );
2394 }
2395
2396 C &fineCoefficient = finerCoefficients[ cNode->nodeData.nodeIndex - _sNodesBegin(highDepth) ];
2397
2398 typename BaseRestrictionProlongation::DownSampleStencil& downSampleStencil = downSampleStencils.data[c];
2399 unsigned int size = loopData.size[c];
2400 const unsigned int* indices = loopData.indices[c];
2401 Pointer( const FEMTreeNode* ) nodes = neighbors.neighbors().data;
2402 Pointer( double ) downSampleValues = downSampleStencil.data;
2403 if( isInterior )
2404 {
2405 for( unsigned int i=0 ; i<size ; i++ )
2406 {
2407 unsigned int idx = indices[i];
2408 if( _isValidFEM1Node( nodes[idx] ) ) fineCoefficient += (C)( coarserCoefficients[ nodes[idx]->nodeData.nodeIndex - _sNodesBegin(lowDepth) ] * (Real)downSampleValues[idx] );
2409 }
2410 }
2411 else
2412 {
2413 LocalDepth d ; LocalOffset off;
2414 _localDepthAndOffset( cNode , d , off );
2415 for( unsigned int i=0 ; i<size ; i++ )
2416 {
2417 unsigned int idx = indices[i];
2418 if( _isValidFEM1Node( nodes[idx] ) )
2419 {
2420 LocalDepth _d ; LocalOffset _off;
2421 _localDepthAndOffset( nodes[idx] , _d , _off );
2422 fineCoefficient += (C)( coarserCoefficients[ nodes[idx]->nodeData.nodeIndex - _sNodesBegin(lowDepth) ] * (Real)rp.upSampleCoefficient( _off , off ) );
2423 }
2424 }
2425 }
2426 }
2427 }
2428 );
2429 }
2430
2431 template< unsigned int Dim , class Real >
2432 template< bool XMajor , class C , unsigned int ... FEMSigs >
2433 void FEMTree< Dim , Real >::_RegularGridUpSample( UIntPack< FEMSigs ... > , LocalDepth highDepth , ConstPointer( C ) lowCoefficients , Pointer( C ) highCoefficients )
2434 {
2435 LocalDepth lowDepth = highDepth - 1;
2436 if( lowDepth<0 ) return;
2437
2438 int lowBegin[Dim] , lowEnd[Dim] , highBegin[Dim] , highEnd[Dim];
2439 FEMIntegrator::BSplineBegin( UIntPack< FEMSigs ... >() , lowDepth , lowBegin );
2440 FEMIntegrator::BSplineEnd ( UIntPack< FEMSigs ... >() , lowDepth , lowEnd );
2441 FEMIntegrator::BSplineBegin( UIntPack< FEMSigs ... >() , highDepth , highBegin );
2442 FEMIntegrator::BSplineEnd ( UIntPack< FEMSigs ... >() , highDepth , highEnd );
2443
2444 _RegularGridUpSample< XMajor >( UIntPack< FEMSigs ... >() , lowBegin , lowEnd , highBegin , highEnd , highDepth , lowCoefficients , highCoefficients );
2445 }
2446 template< unsigned int Dim , class Real >
2447 template< bool XMajor , class C , unsigned int ... FEMSigs >
2448 void FEMTree< Dim , Real >::_RegularGridUpSample( UIntPack< FEMSigs ... > , const int lowBegin[] , const int lowEnd[] , const int highBegin[] , const int highEnd[] , LocalDepth highDepth , ConstPointer( C ) lowCoefficients , Pointer( C ) highCoefficients )
2449 {
2450 // Note: In contrast to the standard grid indexing, where x is the major index in (x,y,z,...)
2451 // For our representation of the grid, x is the minor index
2452 LocalDepth lowDepth = highDepth - 1;
2453 if( lowDepth<0 ) return;
2454
2455 static const int LeftDownSampleRadii[] = { -( ( BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample0Start < BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample1Start ) ? BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample0Start : BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample1Start ) ... };
2456 static const int DownSampleStart[][ sizeof...(FEMSigs) ] = { { BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample0Start ... } , { BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample1Start ... } };
2457 static const unsigned int DownSampleSize [][ sizeof...(FEMSigs) ] = { { BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample0Size ... } , { BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample1Size ... } };
2458 typedef UIntPack< ( - BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample0Start + BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample1End + 1 ) ... > DownSampleSizes;
2459 typedef typename FEMIntegrator::template RestrictionProlongation< UIntPack< FEMSigs ... > > RestrictionProlongation;
2460 typedef typename BaseFEMIntegrator::template RestrictionProlongation< UIntPack< FEMSignature< FEMSigs >::Degree ... > > BaseRestrictionProlongation;
2461
2462 RestrictionProlongation rp;
2463 typename BaseRestrictionProlongation::DownSampleStencils downSampleStencils;
2464 rp.init( highDepth );
2465 rp.setStencils( downSampleStencils );
2466
2467 struct LoopData
2468 {
2469 unsigned int size[1<<Dim];
2470 unsigned int indices[1<<Dim][ WindowSize< UIntPack< ( - BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample0Start + BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample1End + 1 ) ... > >::Size ];
2471 long long offsets[1<<Dim][ WindowSize< UIntPack< ( - BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample0Start + BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::DownSample1End + 1 ) ... > >::Size ];
2472 LoopData( const int lowBegin[] , const int lowEnd[] , const int highBegin[] , const int highEnd[] )
2473 {
2474 int start[Dim] , end[Dim] , lowDim[Dim] , highDim[Dim];
2475 for( int d=0 ; d<Dim ; d++ ) lowDim[d] = lowEnd[d] - lowBegin[d] , highDim[d] = highEnd[d] - highBegin[d];
2476
2477 int lowDimMultiplier[Dim] , highDimMultiplier[Dim];
2478 if( XMajor )
2479 {
2480 lowDimMultiplier[0] = highDimMultiplier[0] = 1;
2481 for( int d=1 ; d<Dim ; d++ ) lowDimMultiplier[d] = lowDimMultiplier[d-1] * (lowEnd[d-1]-lowBegin[d-1]) , highDimMultiplier[d] = highDimMultiplier[d-1] * (highEnd[d-1]-highBegin[d-1]);
2482 }
2483 else
2484 {
2485 lowDimMultiplier[Dim-1] = highDimMultiplier[Dim-1] = 1;
2486 for( int d=Dim-2 ; d>=0 ; d-- ) lowDimMultiplier[d] = lowDimMultiplier[d+1] * (lowEnd[d+1]-lowBegin[d+1]) , highDimMultiplier[d] = highDimMultiplier[d+1] * (highEnd[d+1]-highBegin[d+1]);
2487 }
2488
2489 for( int c=0 ; c<(1<<Dim) ; c++ )
2490 {
2491 size[c] = 0;
2492 for( int d=0 ; d<Dim ; d++ ) start[d] = DownSampleStart[(c>>d)&1][d] + LeftDownSampleRadii[d] , end[d] = start[d] + DownSampleSize[(c>>d)&1][d];
2493
2494 unsigned int idx[Dim];
2495 long long off[Dim+1];
2496 off[0] = 0;
2497 WindowLoop< Dim >::Run
2498 (
2499 start , end ,
2500 [&]( int d , int i ){ idx[d] = i ; off[d+1] = off[d] + ( i - LeftDownSampleRadii[d] - lowBegin[d] ) * lowDimMultiplier[d]; } ,
2501 [&]( void ){ indices[c][ size[c] ] = GetWindowIndex( DownSampleSizes() , idx ) , offsets[c][ size[c] ] = off[Dim] ; size[c]++; }
2502 );
2503 }
2504 }
2505 };
2506 const LoopData loopData( lowBegin , lowEnd , highBegin , highEnd );
2507 int lowDim[Dim] , highDim[Dim];
2508 for( int d=0 ; d<Dim ; d++ ) lowDim[d] = lowEnd[d] - lowBegin[d] , highDim[d] = highEnd[d] - highBegin[d];
2509 int Zero[Dim];
2510 for( int d=0 ; d<Dim ; d++ ) Zero[d] = 0;
2511 int lowDimMultiplier[Dim] , highDimMultiplier[Dim];
2512 if( XMajor )
2513 {
2514 lowDimMultiplier[0] = highDimMultiplier[0] = 1;
2515 for( int d=1 ; d<Dim ; d++ ) lowDimMultiplier[d] = lowDimMultiplier[d-1] * (lowEnd[d-1]-lowBegin[d-1]) , highDimMultiplier[d] = highDimMultiplier[d-1] * (highEnd[d-1]-highBegin[d-1]);
2516 }
2517 else
2518 {
2519 lowDimMultiplier[Dim-1] = highDimMultiplier[Dim-1] = 1;
2520 for( int d=Dim-2 ; d>=0 ; d-- ) lowDimMultiplier[d] = lowDimMultiplier[d+1] * (lowEnd[d+1]-lowBegin[d+1]) , highDimMultiplier[d] = highDimMultiplier[d+1] * (highEnd[d+1]-highBegin[d+1]);
2521 }
2522
2523
2524 struct UpdateData
2525 {
2526 typedef UIntPack< FEMSignature< FEMSigs >::Degree ... > Degrees;
2527 LocalOffset pOff , cOff;
2528 int c;
2529 long long lowIndex[Dim+1] , highIndex[Dim+1];
2530 bool isInterior[Dim+1];
2531 int start[Dim] , end[Dim];
2532 void init( int lowDepth , const int lowBegin[] , const int lowEnd[] , const int highBegin[] , const int highEnd[] )
2533 {
2534 c = 0;
2535 lowIndex[0] = highIndex[0] = 0;
2536 isInterior[0] = true;
2537 this->lowBegin = lowBegin , this->lowEnd = lowEnd , this->highBegin = highBegin , this->highEnd = highEnd;
2538 if( XMajor )
2539 {
2540 _lowDim[0] = _highDim[0] = 1;
2541 for( int d=1 ; d<Dim ; d++ ) _lowDim[d] = _lowDim[d-1] * (lowEnd[d-1]-lowBegin[d-1]) , _highDim[d] = _highDim[d-1] * (highEnd[d-1]-highBegin[d-1]);
2542 }
2543 else
2544 {
2545 _lowDim[Dim-1] = _highDim[Dim-1] = 1;
2546 for( int d=Dim-2 ; d>=0 ; d-- ) _lowDim[d] = _lowDim[d+1] * (lowEnd[d+1]-lowBegin[d+1]) , _highDim[d] = _highDim[d+1] * (highEnd[d+1]-highBegin[d+1]);
2547 }
2548 BaseFEMIntegrator::InteriorOverlappedSpan( Degrees() , Degrees() , lowDepth , _begin , _end );
2549 }
2550 void set( int d , int i )
2551 {
2552 int ii = i + highBegin[d];
2553 cOff[d] = ii;
2554 pOff[d] = (ii>>1);
2555 c = ( c & ( ~(1<<d) ) ) | (ii&1)<<d;
2556 lowIndex[d+1] = lowIndex[d] + pOff[d] * _lowDim[d];
2557 highIndex[d+1] = highIndex[d] + i * _highDim[d];
2558 start[d] = DownSampleStart[(c>>d)&1][d] + LeftDownSampleRadii[d] , end[d] = start[d] + DownSampleSize[(c>>d)&1][d];
2559 isInterior[d+1] = isInterior[d] && ( pOff[d] + start[d] - LeftDownSampleRadii[d] )>=lowBegin[d] && ( pOff[d] + end[d] - LeftDownSampleRadii[d] )<lowEnd[d] && pOff[d]>=_begin[d] && pOff[d]<_end[d];
2560 }
2561 protected:
2562 const int *lowBegin , *lowEnd , *highBegin , *highEnd;
2563 int _lowDim[Dim] , _highDim[Dim] , _begin[Dim] , _end[Dim];
2564 };
2565 std::vector< UpdateData > updateData( ThreadPool::NumThreads() );
2566 for( int i=0 ; i<updateData.size() ; i++ ) updateData[i].init( lowDepth , lowBegin , lowEnd , highBegin , highEnd );
2567 WindowLoop< Dim >::RunParallel
2568 (
2569 Zero , highDim ,
2570 [&]( unsigned int t , int d , size_t i ){ updateData[t].set( d , (int)i ); } ,
2571 [&]( unsigned int t )
2572 {
2573 const UpdateData& data = updateData[t];
2574 const long long highIdx = data.highIndex[Dim] , lowIndex = data.lowIndex[Dim];
2575 const int c = data.c;
2576 const bool isInterior = data.isInterior[Dim];
2577
2578 C highCoefficient = {};
2579
2580 if( isInterior )
2581 {
2582 typename BaseRestrictionProlongation::DownSampleStencil& downSampleStencil = downSampleStencils.data[c];
2583 const unsigned int size = loopData.size[c];
2584 const unsigned int* idx = loopData.indices[c];
2585 const long long* off = loopData.offsets[c];
2586 ConstPointer( double ) stencilValues = downSampleStencil.data;
2587 ConstPointer( C ) _lowCoefficients = lowCoefficients + lowIndex;
2588 for( unsigned int i=0 ; i<size ; i++ ) highCoefficient += (C)( _lowCoefficients[ off[i] ] * (Real)stencilValues[ idx[i] ] );
2589 }
2590 else
2591 {
2592 const LocalOffset& pOff = data.pOff;
2593 const LocalOffset& cOff = data.cOff;
2594 const int* start = data.start;
2595 const int* end = data.end;
2596 long long lowIdx[ Dim+1 ] ; lowIdx[0] = 0;
2597 bool isValid[Dim+1] ; isValid[0] = true;
2598 int _pOff[Dim];
2599
2600 WindowLoop< Dim >::Run
2601 (
2602 start , end ,
2603 [&]( int d , int i )
2604 {
2605 _pOff[d] = pOff[d] + i - LeftDownSampleRadii[d];
2606 lowIdx[d+1] = lowIdx[d] + lowDimMultiplier[d] * ( _pOff[d] - lowBegin[d] );
2607 isValid[d+1] = isValid[d] && ( _pOff[d]>=lowBegin[d] && _pOff[d]<lowEnd[d] );
2608 } ,
2609 [&]( void ){ if( isValid[Dim] ) highCoefficient += (C)( lowCoefficients[ lowIdx[Dim] ] * (Real)rp.upSampleCoefficient( _pOff , cOff ) ); }
2610 );
2611 }
2612 highCoefficients[ highIdx ] += highCoefficient;
2613 }
2614 );
2615 }
2616
2617
2618
2619 template< unsigned int Dim , class Real >
2620 template< unsigned int ... FEMSigs , typename T , typename TDotT , typename ... InterpolationInfos >
2621 DenseNodeData< T , UIntPack< FEMSigs ... > > FEMTree< Dim , Real >::solveSystem( UIntPack< FEMSigs ... > , typename BaseFEMIntegrator::template System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , const DenseNodeData< T , UIntPack< FEMSigs ... > >& constraints , TDotT Dot , LocalDepth minSolveDepth , LocalDepth maxSolveDepth , const typename FEMTree< Dim , Real >::SolverInfo& solverInfo , std::tuple< InterpolationInfos *... > interpolationInfos ) const
2622 {
2623 DenseNodeData< T , UIntPack< FEMSigs ... > > solution;
2624 solveSystem( UIntPack< FEMSigs ... >() , F , constraints , solution , Dot , minSolveDepth , maxSolveDepth , solverInfo , interpolationInfos );
2625 return solution;
2626 }
2627 template< unsigned int Dim , class Real >
2628 template< unsigned int ... FEMSigs , typename T , typename TDotT , typename ... InterpolationInfos >
2629 void FEMTree< Dim , Real >::solveSystem( UIntPack< FEMSigs ... > , typename BaseFEMIntegrator::template System< UIntPack< FEMSignature< FEMSigs >::Degree ... > >& F , const DenseNodeData< T , UIntPack< FEMSigs ... > >& constraints , DenseNodeData< T , UIntPack< FEMSigs ... > >& solution , TDotT Dot , LocalDepth minSolveDepth , LocalDepth maxSolveDepth , const typename FEMTree< Dim , Real >::SolverInfo& solverInfo , std::tuple< InterpolationInfos *... > interpolationInfos ) const
2630 {
2631 static_assert( Dim==sizeof ... ( FEMSigs ) , "[ERROR] FEMTree:solveSystem: Dimensions and number of signatures don't match" );
2632
2633 if( maxSolveDepth>_maxDepth )
2634 {
2635 MK_WARN( "Solver depth should not exceed maximum depth: " , maxSolveDepth , " <= " , _maxDepth );
2636 maxSolveDepth = _maxDepth;
2637 }
2638 if( minSolveDepth>maxSolveDepth ) return;
2639 else if( minSolveDepth<_baseDepth )
2640 {
2641 MK_WARN( "Minimum solver depth should not be smaller than base solver depth: " , minSolveDepth , " >= " , _baseDepth );
2642 minSolveDepth = _baseDepth;
2643 }
2644
2645 // Mark all nodes that define valid finite elements
2646 _setFEM1ValidityFlags( UIntPack< FEMSigs ... >() );
2647 PointEvaluator< UIntPack< FEMSigs ... > , UIntPack< FEMSignature< FEMSigs >::Degree ... > > bsData( sizeof...(InterpolationInfos)==0 ? 0 : maxSolveDepth );
2648
2649 if( solverInfo.clearSolution ) solution = initDenseNodeData< T >( UIntPack< FEMSigs ... >() );
2650 else if( solution.size()!=_sNodesEnd( _maxDepth ) ) MK_THROW( "Solution is the wrong size: " , solution.size() , " != " , _sNodesEnd(_maxDepth) );
2651
2652 // The initial estimate of the solution (may be empty or may come in with an initial guess)
2653 Pointer( T ) _solution = solution();
2654 // The constraints
2655 ConstPointer( T ) _constraints = constraints();
2656
2657 // _residualConstraints:
2658 // -- stores the difference between the initial constraints and the constraints met by the current solution at all _other_ levels
2659 // **** This could implemented in one of two ways:
2660 // **** (1) Repeatedly computing the difference using the entire solution
2661 // **** (2) Iteratively updating using the change in the solution
2662 // **** We have opted for #1 to avoid having to compute/store the change in the solution after each solve
2663 Pointer( T ) _residualConstraints = AllocPointer< T >( _sNodesEnd( _maxDepth-1 ) );
2664 // The constraints met during the restriction phase
2665 Pointer( T ) _restrictedConstraints = NullPointer( T );
2666 // The solution obtained during the prolongation phase
2667 Pointer( T ) _prolongedSolution = AllocPointer< T >( _sNodesEnd( _maxDepth-1 ) );
2668
2669 memset( _prolongedSolution , 0 , sizeof(T) * _sNodesEnd( _maxDepth-1 ) );
2670 if( !( solverInfo.clearSolution && solverInfo.vCycles==1 && solverInfo.cascadic ) )
2671 {
2672 _restrictedConstraints = AllocPointer< T >( _sNodesEnd( _maxDepth-1 ) );
2673 memset( _restrictedConstraints , 0 , sizeof(T) * _sNodesEnd( _maxDepth-1 ) );
2674 }
2675
2676 Pointer( double ) _bNorm2 = NullPointer( double );
2677 if( solverInfo.showGlobalResidual!=SHOW_GLOBAL_RESIDUAL_NONE )
2678 {
2679 _bNorm2 = AllocPointer< double >( _maxDepth+1 );
2680 memset( _bNorm2 , 0 , sizeof(double) * ( _maxDepth+1 ) );
2681 for( LocalDepth d=_baseDepth ; d<=maxSolveDepth ; d++ ) for( node_index_type i=_sNodesBegin(d) ; i<_sNodesEnd(d) ; i++ ) _bNorm2[d] += Dot( _constraints[i] , _constraints[i] );
2682 }
2683
2684 auto UpdateProlongation = [&] ( int depth )
2685 {
2686 if( depth==_maxDepth ) return;
2687
2688 if ( depth< _baseDepth ){}
2689 else if( depth==_baseDepth ) ThreadPool::ParallelFor( _sNodesBegin(depth) , _sNodesEnd(depth) , [&]( unsigned int , size_t i ){ _prolongedSolution[i] = solution[i]; } );
2690 else if( depth< _maxDepth )
2691 {
2692 // Clear the prolonged solution @(depth)
2693 memset( _prolongedSolution + _sNodesBegin( depth ) , 0 , sizeof( T ) * _sNodesSize( depth ) );
2694
2695 // Up-sample the prolonged solution @(depth-1) into the prolonged solution @(depth)
2696 F.init( depth );
2697 _upSample( UIntPack< FEMSigs ... >() , F.restrictionProlongation() , depth , ( ConstPointer(T) )_prolongedSolution+_sNodesBegin(depth-1) , _prolongedSolution+_sNodesBegin(depth) );
2698
2699 // Add in the solution @(depth) to the prolonged solution
2700 ThreadPool::ParallelFor( _sNodesBegin(depth) , _sNodesEnd(depth) , [&]( unsigned int , size_t i ){ _prolongedSolution[i] += solution[i]; } );
2701 }
2702 #ifdef SHOW_WARNINGS
2703 #pragma message( "[WARNING] Should this be here or in SetResidualConstraints" )
2704 #endif // SHOW_WARNINGS
2705 if( depth+1>_baseDepth && depth+1<=_maxDepth && _prolongedSolution ) _setPointValuesFromProlongedSolution< 0 >( depth+1 , bsData , ( ConstPointer( T ) )_prolongedSolution , interpolationInfos );
2706 };
2707 auto UpdateRestriction = [&]( int depth )
2708 {
2709 if( depth>_baseDepth && _restrictedConstraints )
2710 {
2711 memset( _restrictedConstraints + _sNodesBegin( depth-1 ) , 0 , sizeof( T ) * _sNodesSize( depth-1 ) );
2712 // Update the restricted constraints @(depth-1) based on the solution @(depth)
2713 F.init( depth );
2714 _updateRestrictedIntegralConstraints( UIntPack< FEMSigs ... >() , F , depth , ( ConstPointer(T) )_solution , _restrictedConstraints );
2715 _updateRestrictedInterpolationConstraints< 0 >( bsData , depth , ( ConstPointer( T ) )_solution , _restrictedConstraints , interpolationInfos );
2716 // Down-sample the restricted constraints @(depth) into the restricted constraints @(depth-1)
2717 if( depth<_maxDepth ) _downSample( UIntPack< FEMSigs ... >() , F.restrictionProlongation() , depth , ( ConstPointer(T) )_restrictedConstraints + _sNodesBegin(depth) , _restrictedConstraints + _sNodesBegin(depth-1) );
2718 }
2719 };
2720 auto SetResidualConstraints = [&]( int depth )
2721 {
2722 // Copy the constraints
2723 if( depth<_maxDepth ) memcpy( _residualConstraints + _sNodesBegin(depth) , _constraints + _sNodesBegin(depth) , sizeof( T ) * _sNodesSize(depth) );
2724
2725 // Update the constraints @(depth) using the restriced residual @(depth)
2726 if( depth<_maxDepth && _restrictedConstraints )
2727 ThreadPool::ParallelFor( _sNodesBegin(depth) , _sNodesEnd(depth) , [&]( unsigned int , size_t i ){ _residualConstraints[i] -= _restrictedConstraints[i]; } );
2728 };
2729 auto OutputSolverStats = [&] ( int cycle , int depth , const _SolverStats& sStats , bool showResidual , int actualIters )
2730 {
2731 if( solverInfo.verbose )
2732 {
2733 node_index_type femNodes = (node_index_type)validUnlockedFEMNodes( UIntPack< FEMSigs ... >() , depth );
2734 if( maxSolveDepth<10 )
2735 if( solverInfo.vCycles<10 ) printf( "Cycle[%d] Depth[%d/%d]:\t" , cycle , depth , maxSolveDepth );
2736 else printf( "Cycle[%2d] Depth[%d/%d]:\t" , cycle , depth , maxSolveDepth );
2737 else
2738 if( solverInfo.vCycles<10 ) printf( "Cycle[%d] Depth[%2d/%d]:\t" , cycle , depth , maxSolveDepth );
2739 else printf( "Cycle[%2d] Depth[%2d/%d]:\t" , cycle , depth , maxSolveDepth );
2740 printf( "Updated constraints / Got system / Solved in: %6.3f / %6.3f / %6.3f\t(%d MB)\tNodes: %llu\n" , sStats.constraintUpdateTime , sStats.systemTime , sStats.solveTime , MemoryInfo::PeakMemoryUsageMB() , (unsigned long long)femNodes );
2741 }
2742 if( solverInfo.showResidual && showResidual )
2743 {
2744 for( int d=_baseDepth ; d<depth ; d++ ) printf( " " );
2745 if ( depth==_baseDepth ) printf( "MG x %d" , solverInfo.baseVCycles );
2746 else if( depth<=solverInfo.cgDepth ) printf( " CG" );
2747 else printf( " GS" );
2748 printf( ": %.4e -> %.4e -> %.4e (%.1e) [%d]\n" , sqrt( sStats.bNorm2 ) , sqrt( sStats.inRNorm2 ) , sqrt( sStats.outRNorm2 ) , sqrt( sStats.outRNorm2 / sStats.inRNorm2 ) , actualIters );
2749 }
2750 };
2751
2752 // Set the cumulative solution
2753 if( !solverInfo.clearSolution ) for( LocalDepth d=_baseDepth ; d<maxSolveDepth ; d++ ) UpdateProlongation( d );
2754
2755 _SolverStats sStats;
2756 bool showResidual;
2757 int actualIters;
2758 double t;
2759
2760 struct TrivialSORWeights{ Real operator[] ( node_index_type idx ) const { return (Real)1; } };
2761 struct SORWeights
2762 {
2763 DenseNodeData< Real, UIntPack< FEMSigs ... > > supportWeights , prolongationSupportWeights;
2764 std::function< Real (Real,Real) > sorFunction;
2765 Real operator[] ( node_index_type idx ) const
2766 {
2767 if ( supportWeights() && prolongationSupportWeights() ) return sorFunction( supportWeights[idx] , prolongationSupportWeights[idx] );
2768 else if( supportWeights() ) return sorFunction( supportWeights[idx] , 1 );
2769 else if( prolongationSupportWeights() ) return sorFunction( 1 , prolongationSupportWeights[idx] );
2770 else return sorFunction( 1 , 1 );
2771 }
2772 };
2773 SORWeights sorWeights;
2774 if( solverInfo.useSupportWeights ) sorWeights.supportWeights = supportWeights( UIntPack< FEMSigs ... >() );
2775 if( solverInfo.useProlongationSupportWeights ) sorWeights.prolongationSupportWeights = prolongationWeights( UIntPack< FEMSigs ... >() , false );
2776
2777 auto SolveRestriction = [&]( int v , int depth )
2778 {
2779 sorWeights.sorFunction = solverInfo.sorRestrictionFunction;
2780 // The restriction phase
2781 if( solverInfo.cascadic )
2782 {
2783 showResidual = false;
2784 if( !solverInfo.clearSolution || v>0 ) for( LocalDepth d=depth ; d>=_baseDepth ; d-- ) { F.init( d ) ; UpdateRestriction( d ); }
2785 }
2786 else
2787 {
2788 bool coarseToFine = false;
2789 for( LocalDepth d=depth ; d>=minSolveDepth ; d-- )
2790 {
2791 sStats.constraintUpdateTime = 0;
2792 showResidual = ( d!=_baseDepth );
2793 int iters = solverInfo.iters( v , true , d );
2794 t = Time();
2795 F.init( d );
2796 SetResidualConstraints( d );
2797 sStats.constraintUpdateTime += Time()-t;
2798 actualIters = iters;
2799 // In the restriction phase we do not solve at the coarsest resolution since we will do so in the prolongation phase
2800 if( d==_baseDepth )
2801 {
2802 if( solverInfo.baseVCycles ) _solveRegularMG( UIntPack< FEMSigs ... >() , F , bsData , std::min< LocalDepth >( _baseDepth , maxSolveDepth ) , _solution , d==_maxDepth ? _constraints : _residualConstraints , Dot , solverInfo.baseVCycles , iters , sStats , solverInfo.showResidual , solverInfo.cgAccuracy , interpolationInfos );
2803 }
2804 else
2805 {
2806 if( d>solverInfo.cgDepth ) actualIters = _solveSystemGS( UIntPack< FEMSigs ... >() , Dim!=1 , F , bsData , d , _solution , ( ConstPointer( T ) )_prolongedSolution , d==_maxDepth ? _constraints : _residualConstraints , Dot , iters , coarseToFine , solverInfo.sliceBlockSize , sorWeights , sStats , solverInfo.showResidual , interpolationInfos );
2807 else actualIters = _solveSystemCG( UIntPack< FEMSigs ... >() , F , bsData , d , _solution , ( ConstPointer( T ) )_prolongedSolution , d==_maxDepth ? _constraints : _residualConstraints , Dot , iters , coarseToFine , sStats , solverInfo.showResidual , solverInfo.cgAccuracy , interpolationInfos );
2808 }
2809 t = Time();
2810 UpdateRestriction( d );
2811 sStats.constraintUpdateTime += Time()-t;
2812 OutputSolverStats( v , d , sStats , showResidual , actualIters );
2813 }
2814 }
2815 };
2816
2817 auto SolveProlongation = [&]( int v , int depth )
2818 {
2819 sorWeights.sorFunction = solverInfo.sorProlongationFunction;
2820 showResidual = true;
2821 bool coarseToFine = true;
2822 for( LocalDepth d=minSolveDepth ; d<=depth ; d++ )
2823 {
2824 sStats.constraintUpdateTime = 0;
2825 int iters = solverInfo.iters( v , false , d );
2826 t = Time();
2827 F.init( d );
2828 SetResidualConstraints( d );
2829 sStats.constraintUpdateTime += Time()-t;
2830 actualIters = iters;
2831 if( d==_baseDepth )
2832 {
2833 if( solverInfo.baseVCycles ) _solveRegularMG( UIntPack< FEMSigs ... >() , F , bsData , std::min< LocalDepth >( _baseDepth , maxSolveDepth ) , _solution , d==_maxDepth ? _constraints : _residualConstraints , Dot , solverInfo.baseVCycles , iters , sStats , solverInfo.showResidual , solverInfo.cgAccuracy , interpolationInfos );
2834 }
2835 else
2836 {
2837 if( d>solverInfo.cgDepth ) actualIters = _solveSystemGS( UIntPack< FEMSigs ... >() , Dim!=1 , F , bsData , d , _solution , ( ConstPointer( T ) )_prolongedSolution , d==_maxDepth ? _constraints : _residualConstraints , Dot , iters , coarseToFine , solverInfo.sliceBlockSize , sorWeights , sStats , solverInfo.showResidual , interpolationInfos );
2838 else actualIters = _solveSystemCG( UIntPack< FEMSigs ... >() , F , bsData , d , _solution , ( ConstPointer( T ) )_prolongedSolution , d==_maxDepth ? _constraints : _residualConstraints , Dot , iters , coarseToFine , sStats , solverInfo.showResidual , solverInfo.cgAccuracy , interpolationInfos );
2839 }
2840 t = Time();
2841 UpdateProlongation( d );
2842 sStats.constraintUpdateTime += Time()-t;
2843 OutputSolverStats( v , d , sStats , showResidual , actualIters );
2844 }
2845 };
2846
2847 for( int v=0 ; v<solverInfo.vCycles ; v++ )
2848 {
2849 if( solverInfo.wCycle )
2850 {
2851 for( int d=maxSolveDepth ; d>minSolveDepth ; d-- )
2852 {
2853 SolveRestriction ( v , d );
2854 SolveProlongation( v , d-1 );
2855 }
2856 for( int d=_baseDepth+1 ; d<=maxSolveDepth ; d++ )
2857 {
2858 SolveRestriction ( v , d-1 );
2859 SolveProlongation( v , d );
2860 }
2861 }
2862 else
2863 {
2864 SolveRestriction ( v , std::max< LocalDepth >( _baseDepth , maxSolveDepth ) );
2865 SolveProlongation( v , std::max< LocalDepth >( _baseDepth , maxSolveDepth ) );
2866 }
2867 if( solverInfo.showGlobalResidual==SHOW_GLOBAL_RESIDUAL_ALL || ( solverInfo.showGlobalResidual==SHOW_GLOBAL_RESIDUAL_LAST && v==solverInfo.vCycles-1 ) )
2868 {
2869 bool coarseToFine = false;
2870 std::vector< double > rNorms( maxSolveDepth+1 );
2871 for( LocalDepth d=maxSolveDepth ; d>=minSolveDepth ; d-- )
2872 {
2873 F.init( d );
2874 SetResidualConstraints( d );
2875 _solveSystemGS( UIntPack< FEMSigs ... >() , Dim!=1 , F , bsData , d , _solution , ( ConstPointer( T ) )_prolongedSolution , d==_maxDepth ? _constraints : _residualConstraints , Dot , 0 , coarseToFine , solverInfo.sliceBlockSize , TrivialSORWeights() , sStats , true , interpolationInfos );
2876 UpdateRestriction( d );
2877 rNorms[d] = sqrt( sStats.outRNorm2 / _bNorm2[d] );
2878 }
2879 printf( "%3d" , v+1 );
2880 for( int d=_baseDepth ; d<=maxSolveDepth ; d++ ) printf( "\t%.4e" , rNorms[d] );
2881 printf( "\n" );
2882 }
2883 }
2884
2885 FreePointer( _residualConstraints );
2886 FreePointer( _restrictedConstraints );
2887 FreePointer( _prolongedSolution );
2888 FreePointer( _bNorm2 );
2889 }
2890
2891 template< unsigned int Dim , class Real >
2892 template< unsigned int ... FEMSigs >
2893 DenseNodeData< Real , UIntPack< FEMSigs ... > > FEMTree< Dim , Real >::initDenseNodeData( UIntPack< FEMSigs ... > ) const
2894 {
2895 DenseNodeData< Real , UIntPack< FEMSigs ... > > constraints( _sNodes.size() );
2896 memset( constraints() , 0 , sizeof(Real)*_sNodes.size() );
2897 return constraints;
2898 }
2899 template< unsigned int Dim , class Real >
2900 template< class Data , unsigned int ... FEMSigs >
2901 DenseNodeData< Data , UIntPack< FEMSigs ... > > FEMTree< Dim , Real >::initDenseNodeData( UIntPack< FEMSigs ... > ) const
2902 {
2903 DenseNodeData< Data , UIntPack< FEMSigs ... > > constraints( _sNodes.size() );
2904 memset( constraints() , 0 , sizeof(Data)*_sNodes.size() );
2905 return constraints;
2906 }
2907
2908 template< unsigned int Dim , class Real > template< class SReal , class Data , unsigned int _Dim > Data FEMTree< Dim , Real >::_StencilDot( Point< SReal , _Dim > p1 , Point< Data , _Dim > p2 ){ Data dot={} ; for( int d=0 ; d<_Dim ; d++ ) dot += p2[d] * (Real)p1[d] ; return dot; }
2909 template< unsigned int Dim , class Real > template< class SReal , class Data > Data FEMTree< Dim , Real >::_StencilDot( Point< SReal , 1 > p1 , Point< Data , 1 > p2 ){ return p2[0] * (Real)p1[0]; }
2910 template< unsigned int Dim , class Real > template< class SReal , class Data > Data FEMTree< Dim , Real >::_StencilDot( SReal p1 , Point< Data , 1 > p2 ){ return p2[0] * (Real)p1; }
2911 template< unsigned int Dim , class Real > template< class SReal , class Data > Data FEMTree< Dim , Real >::_StencilDot( Point< SReal , 1 > p1 , Data p2 ){ return p2 * (Real)p1[0]; }
2912 template< unsigned int Dim , class Real > template< class SReal , class Data > Data FEMTree< Dim , Real >::_StencilDot( SReal p1 , Data p2 ){ return p2*(Real)p1; }
2913 template< unsigned int Dim , class Real > template< class Real1 , unsigned int _Dim > bool FEMTree< Dim , Real >::_IsZero( Point< Real1 , _Dim > p ){ for( int d=0 ; d<_Dim ; d++ ) if( !_IsZero( p[d] ) ) return false ; return true; }
2914 template< unsigned int Dim , class Real > template< class Real1 > bool FEMTree< Dim , Real >::_IsZero( Real1 p ){ return p==0; }
2915
2916 template< unsigned int Dim , class Real >
2917 template< typename T , unsigned int ... FEMSigs , unsigned int ... CSigs , unsigned int ... FEMDegrees , unsigned int ... CDegrees , unsigned int CDim , class Coefficients >
2918 void FEMTree< Dim , Real >::_addFEMConstraints( UIntPack< FEMSigs ... > , UIntPack< CSigs ... > , typename BaseFEMIntegrator::template Constraint< UIntPack< FEMDegrees ... > , UIntPack< CDegrees ... > , CDim >& F , const Coefficients& coefficients , Pointer( T ) constraints , LocalDepth maxDepth ) const
2919 {
2920 _setFEM1ValidityFlags( UIntPack< FEMSigs ... >() );
2921 _setFEM2ValidityFlags( UIntPack< CSigs ... >() );
2922 typedef typename BaseFEMIntegrator::template Constraint< UIntPack< FEMDegrees ... > , UIntPack< CDegrees ... > , CDim > BaseConstraint;
2923 typedef typename Coefficients::data_type D;
2924 typedef UIntPack< ( BSplineOverlapSizes< CDegrees , FEMDegrees >::OverlapSize ) ... > OverlapSizes;
2925 typedef UIntPack< ( -BSplineOverlapSizes< CDegrees , FEMDegrees >::OverlapStart ) ... > LeftCFEMOverlapRadii;
2926 typedef UIntPack< ( BSplineOverlapSizes< CDegrees , FEMDegrees >::OverlapEnd ) ... > RightCFEMOverlapRadii;
2927 typedef UIntPack< ( -BSplineOverlapSizes< FEMDegrees , CDegrees >::OverlapStart ) ... > LeftFEMCOverlapRadii;
2928 typedef UIntPack< ( BSplineOverlapSizes< FEMDegrees , CDegrees >::OverlapEnd ) ... > RightFEMCOverlapRadii;
2929
2930 // To set the constraints, we iterate over the splatted normals and compute the dot-product of the divergence of the normal field with all the basis functions.
2931 // Within the same depth: set directly as a gather
2932 // Coarser depths
2933 maxDepth = std::min< LocalDepth >( maxDepth , _maxDepth );
2934 Pointer( T ) _constraints = AllocPointer< T >( _sNodesEnd( maxDepth-1 ) );
2935 memset( _constraints , 0 , sizeof(T)*( _sNodesEnd(maxDepth-1) ) );
2936
2937 static const WindowLoopData< UIntPack< BSplineOverlapSizes< CDegrees , FEMDegrees >::OverlapSize ... > > cfemLoopData( []( int c , int* start , int* end ){ BaseFEMIntegrator::ParentOverlapBounds( UIntPack< CDegrees ... >() , UIntPack< FEMDegrees ... >() , c , start , end ); } );
2938 static const WindowLoopData< UIntPack< BSplineOverlapSizes< FEMDegrees , CDegrees >::OverlapSize ... > > femcLoopData( []( int c , int* start , int* end ){ BaseFEMIntegrator::ParentOverlapBounds( UIntPack< FEMDegrees ... >() , UIntPack< CDegrees ... >() , c , start , end ); } );
2939
2940 std::atomic< bool > hasCoarserCoefficients = true;
2941 // Iterate from fine to coarse, setting the constraints @(depth) and the cumulative constraints @(depth-1)
2942 for( LocalDepth d=maxDepth ; d>=0 ; d-- )
2943 {
2944 typename BaseConstraint::CCStencil stencil;
2945 typename BaseConstraint::PCStencils stencils;
2946 F.init( d );
2947 F.template setStencil < false >( stencil );
2948 F.template setStencils< true >( stencils );
2949 std::vector< ConstOneRingNeighborKey > neighborKeys( ThreadPool::NumThreads() );
2950 for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( _localToGlobal( d ) );
2951 ThreadPool::ParallelFor( _sNodesBegin(d) , _sNodesEnd(d) , [&]( unsigned int thread , size_t i )
2952 {
2953 if( d<maxDepth ) constraints[i] += _constraints[i];
2954 ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ];
2955 FEMTreeNode* node = _sNodes.treeNodes[i];
2956 int start[Dim] , end[] = { BSplineOverlapSizes< CDegrees , FEMDegrees >::OverlapSize ... };
2957 memset( start , 0 , sizeof( start ) );
2958 typename FEMTreeNode::template ConstNeighbors< OverlapSizes > neighbors;
2959 neighborKey.getNeighbors( LeftFEMCOverlapRadii() , RightFEMCOverlapRadii() , node , neighbors );
2960 bool isInterior , isInterior2;
2961 {
2962 LocalDepth d ; LocalOffset off ; _localDepthAndOffset( node , d , off );
2963 isInterior = BaseFEMIntegrator::IsInteriorlyOverlapped( UIntPack< FEMDegrees ... >() , UIntPack< CDegrees ... >() , d , off );
2964 }
2965 {
2966 LocalDepth d ; LocalOffset off ; _localDepthAndOffset( node->parent , d , off );
2967 isInterior2 = BaseFEMIntegrator::IsInteriorlyOverlapped( UIntPack< CDegrees ... >() , UIntPack< FEMDegrees ... >() , d , off );
2968 }
2969
2970 LocalDepth d ; LocalOffset off;
2971 _localDepthAndOffset( node , d , off );
2972
2973 // Set constraints from current depth
2974 // Gather the constraints from _node into the constraint stored with node
2975 if( _isValidFEM1Node( node ) )
2976 {
2977 if( isInterior )
2978 {
2979 unsigned int size = neighbors.neighbors.Size();
2980 Pointer( const FEMTreeNode* ) nodes = neighbors.neighbors().data;
2981 Pointer( Point< double , CDim > ) stencilValues = stencil.data;
2982 for( unsigned int j=0 ; j<size ; j++ )
2983 {
2984 if( _isValidFEM2Node( nodes[j] ) )
2985 {
2986 const D* _data = coefficients( nodes[j] );
2987 if( _data ) constraints[i] += _StencilDot< double , T , CDim >( stencilValues[j] , *_data );
2988 }
2989 }
2990 }
2991 else
2992 {
2993 unsigned int size = neighbors.neighbors.Size();
2994 Pointer( const FEMTreeNode* ) nodes = neighbors.neighbors().data;
2995 for( unsigned int j=0 ; j<size ; j++ )
2996 {
2997 if( _isValidFEM2Node( nodes[j] ) )
2998 {
2999 const D* _data = coefficients( nodes[j] );
3000 if( _data )
3001 {
3002 LocalDepth _d ; LocalOffset _off ; _localDepthAndOffset( nodes[j] , _d , _off );
3003 constraints[i] += _StencilDot< double , T , CDim >( F.ccIntegrate( off , _off ) , *_data );
3004 }
3005 }
3006 }
3007 }
3008 BaseFEMIntegrator::ParentOverlapBounds( UIntPack< CDegrees ... >() , UIntPack< FEMDegrees ... >() , d , off , start , end );
3009 }
3010 if( !_isValidFEM2Node( node ) ) return;
3011 const D* _data = coefficients( node );
3012 if( !_data ) return;
3013 else if( d<maxDepth ) hasCoarserCoefficients = true;
3014 const D& data = *_data;
3015 if( _IsZero( data ) ) return;
3016
3017 // Set the _constraints for the parents
3018 if( d>0 )
3019 {
3020 int cIdx = (int)( node - node->parent->children );
3021 const typename BaseConstraint::CCStencil& _stencil = stencils.data[cIdx];
3022 neighborKey.getNeighbors( LeftCFEMOverlapRadii() , RightCFEMOverlapRadii() , node->parent , neighbors );
3023
3024 unsigned int size = cfemLoopData.size[cIdx];
3025 const unsigned int* indices = cfemLoopData.indices[cIdx];
3026 ConstPointer( Point< double , CDim > ) stencilValues = _stencil.data;
3027 Pointer( const FEMTreeNode* ) nodes = neighbors.neighbors().data;
3028 if( isInterior2 )
3029 {
3030 for( unsigned int i=0 ; i<size ; i++ )
3031 {
3032 unsigned int idx = indices[i];
3033 if( nodes[idx] )
3034 {
3035 Atomic< T >::Add( _constraints[ nodes[idx]->nodeData.nodeIndex ] , _StencilDot< double , T , CDim >( stencilValues[idx] , data ) );
3036 }
3037 }
3038 }
3039 else
3040 {
3041 for( unsigned int i=0 ; i<size ; i++ )
3042 {
3043 unsigned int idx = indices[i];
3044 if( nodes[idx] )
3045 {
3046 LocalDepth _d ; LocalOffset _off ; _localDepthAndOffset( nodes[idx] , _d , _off );
3047 Atomic< T >::Add( _constraints[ nodes[idx]->nodeData.nodeIndex ] , _StencilDot< double , T , CDim >( F.pcIntegrate( _off , off ) , data ) );
3048 }
3049 }
3050 }
3051 }
3052 }
3053 );
3054 if( d>0 && d<maxDepth ) _downSample( UIntPack< FEMSigs ... >() , F.tRestrictionProlongation() , d , ( ConstPointer(T) )_constraints + _sNodesBegin(d) , _constraints + _sNodesBegin(d-1) );
3055 }
3056 FreePointer( _constraints );
3057 if( hasCoarserCoefficients )
3058 {
3059 Pointer( D ) _coefficients = AllocPointer< D >( _sNodesEnd( maxDepth-1 ) );
3060 memset( _coefficients , 0 , sizeof(D) * _sNodesEnd(maxDepth-1) );
3061 for( LocalDepth d=maxDepth-1 ; d>=0 ; d-- )
3062 {
3063 ThreadPool::ParallelFor( _sNodesBegin(d) , _sNodesEnd(d) , [&]( unsigned int , size_t i )
3064 {
3065 const D* d = coefficients( _sNodes.treeNodes[i] );
3066 if( d ) _coefficients[i] += *d;
3067 }
3068 );
3069 }
3070
3071 // Coarse-to-fine up-sampling of coefficients
3072 for( LocalDepth d=1 ; d<maxDepth ; d++ ) _upSample< D >( UIntPack< FEMSigs ... >() , F.tRestrictionProlongation() , d , ( ConstPointer(D) )_coefficients+_sNodesBegin(d-1) , _coefficients+_sNodesBegin(d) );
3073 // Compute the contribution from all coarser depths
3074 for( LocalDepth d=1 ; d<=maxDepth ; d++ )
3075 {
3076 node_index_type start = _sNodesBegin( d ) , end = _sNodesEnd( d );
3077 size_t range = end - start;
3078 typename BaseConstraint::CPStencils stencils;
3079 F.init( d );
3080 F.template setStencils< false >( stencils );
3081 std::vector< ConstOneRingNeighborKey > neighborKeys( ThreadPool::NumThreads() );
3082 for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( _localToGlobal( d-1 ) );
3083
3084 ThreadPool::ParallelFor( _sNodesBegin(d) , _sNodesEnd(d) , [&]( unsigned int thread , size_t i )
3085 {
3086 if( _isValidFEM1Node( _sNodes.treeNodes[i] ) )
3087 {
3088 ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ];
3089 FEMTreeNode* node = _sNodes.treeNodes[i];
3090 int start[Dim] , end[Dim];
3091 typename FEMTreeNode::template ConstNeighbors< OverlapSizes > neighbors;
3092 typename FEMTreeNode::template ConstNeighbors< OverlapSizes > pNeighbors;
3093 bool isInterior;
3094 {
3095 BaseFEMIntegrator::ParentOverlapBounds( UIntPack< FEMDegrees ... >() , UIntPack< CDegrees ... >() , (int)( node - node->parent->children ) , start , end );
3096 }
3097 {
3098 LocalDepth d ; LocalOffset off ; _localDepthAndOffset( node->parent , d , off );
3099 neighborKey.getNeighbors( LeftFEMCOverlapRadii() , RightFEMCOverlapRadii() , node->parent , pNeighbors );
3100 isInterior = BaseFEMIntegrator::IsInteriorlyOverlapped( UIntPack< FEMDegrees ... >() , UIntPack< CDegrees ... >() , d , off );
3101 }
3102 int cIdx = (int)( node - node->parent->children );
3103 const typename BaseConstraint::CCStencil& _stencil = stencils.data[cIdx];
3104
3105 T constraint = {};
3106
3107 LocalDepth d ; LocalOffset off;
3108 _localDepthAndOffset( node , d , off );
3109 int corner = (int)( node - node->parent->children );
3110 unsigned int size = femcLoopData.size[corner];
3111 const unsigned int* indices = femcLoopData.indices[corner];
3112 Pointer( const FEMTreeNode* ) nodes = pNeighbors.neighbors().data;
3113 Pointer( Point< double , CDim > ) stencilValues = _stencil.data;
3114 if( isInterior )
3115 for( unsigned int i=0 ; i<size ; i++ )
3116 {
3117 unsigned int idx = indices[i];
3118 if( _isValidFEM2Node( nodes[idx] ) ) constraint += _StencilDot< double , T , CDim >( stencilValues[idx] , _coefficients[ nodes[idx]->nodeData.nodeIndex ] );
3119 }
3120 else
3121 for( unsigned int i=0 ; i<size ; i++ )
3122 {
3123 unsigned int idx = indices[i];
3124 if( _isValidFEM2Node( nodes[idx] ) )
3125 {
3126 LocalDepth _d ; LocalOffset _off ; _localDepthAndOffset ( nodes[idx] , _d , _off );
3127 constraint += _StencilDot< double , T , CDim >( F.cpIntegrate( off , _off ) , _coefficients[ nodes[idx]->nodeData.nodeIndex ] );
3128 }
3129 }
3130 constraints[i] += constraint;
3131 }
3132 }
3133 );
3134 }
3135 FreePointer( _coefficients );
3136 }
3137
3138 ThreadPool::ParallelFor( _sNodesBegin(0) , _sNodesEnd(_maxDepth) , [&]( unsigned int , size_t i )
3139 {
3140 if( _isValidFEM1Node( _sNodes.treeNodes[i] ) && _sNodes.treeNodes[i]->nodeData.getDirichletElementFlag() ) constraints[i] *= (Real)0;
3141 } );
3142 }
3143
3144 template< unsigned int Dim , class Real >
3145 template< typename T , unsigned int ... FEMSigs , unsigned int PointD >
3146 void FEMTree< Dim , Real >::_addInterpolationConstraints( DenseNodeData< T , UIntPack< FEMSigs ... > >& constraints , LocalDepth maxDepth , const InterpolationInfo< T , PointD > *interpolationInfo ) const
3147 {
3148 _setFEM1ValidityFlags( UIntPack< FEMSigs ... >() );
3149 typedef typename FEMIntegrator::template PointEvaluator< UIntPack< FEMSigs ... > , IsotropicUIntPack< Dim , PointD > > PointEvaluator;
3150 PointEvaluator evaluator( std::min< LocalDepth >( maxDepth , _maxDepth ) );
3151
3152 typedef typename FEMTreeNode::template ConstNeighborKey< UIntPack< BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::SupportEnd ... > , UIntPack< ( -BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::SupportStart ) ... > > PointSupportKey;
3153 maxDepth = std::min< LocalDepth >( maxDepth , _maxDepth );
3154 {
3155 typedef UIntPack< (-BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::SupportStart ) ... > LeftSupportRadii;
3156 typedef UIntPack< ( BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::SupportEnd ) ... > LeftPointSupportRadii;
3157 typedef UIntPack< (-BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::SupportStart ) ... > RightPointSupportRadii;
3158 typedef UIntPack< BSplineSupportSizes< FEMSignature< FEMSigs >::Degree >::SupportSize ... > SupportSizes;
3159
3160 for( int d=0 ; d<=maxDepth ; d++ )
3161 {
3162 std::vector< PointSupportKey > neighborKeys( ThreadPool::NumThreads() );
3163 for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( _localToGlobal( maxDepth ) );
3164 #ifdef SHOW_WARNINGS
3165 #pragma message( "[WARNING] Why do I have to wrap the template in a lambda?" )
3166 #endif // SHOW_WARNINGS
3167 typedef PointEvaluatorState< UIntPack< FEMSigs ... > , IsotropicUIntPack< Dim , PointD > > _PointEvaluatorState;
3168 auto WrapperLambda = []( const _PointEvaluatorState &eState , LocalOffset off )
3169 {
3170 return eState.template dValues< Real , CumulativeDerivatives< Dim , PointD > >( off );
3171 };
3172 ThreadPool::ParallelFor( _sNodesBegin(d) , _sNodesEnd(d) , [&]( unsigned int thread , size_t i )
3173 {
3174 if( _isValidSpaceNode( _sNodes.treeNodes[i] ) )
3175 {
3176 _PointEvaluatorState eState;
3177 FEMTreeNode* node = _sNodes.treeNodes[i];
3178
3179 PointSupportKey& neighborKey = neighborKeys[ thread ];
3180 typename FEMTreeNode::template ConstNeighbors< SupportSizes > neighbors;
3181 neighborKey.getNeighbors( LeftPointSupportRadii() , RightPointSupportRadii() , node , neighbors );
3182 LocalDepth d ; LocalOffset off;
3183 _localDepthAndOffset( node , d , off );
3184
3185 size_t begin , end;
3186 interpolationInfo->range( node , begin , end );
3187 for( size_t pIndex=begin ; pIndex<end ; pIndex++ )
3188 {
3189 const DualPointInfo< Dim , Real , T , PointD >& pData = (*interpolationInfo)[ pIndex ];
3190 Point< Real , Dim > p = pData.position;
3191 evaluator.initEvaluationState( p , d , off , eState );
3192
3193 int s[Dim];
3194 WindowLoop< Dim >::Run
3195 (
3196 IsotropicUIntPack< Dim , 0 >() , SupportSizes() ,
3197 [&]( int d , int i ){ s[d] = i; } ,
3198 [&]( const FEMTreeNode* _node )
3199 {
3200 if( _isValidFEM1Node( _node ) && !_node->nodeData.getDirichletElementFlag() )
3201 {
3202 LocalDepth _d ; LocalOffset _off ; _localDepthAndOffset( _node , _d , _off );
3203 CumulativeDerivativeValues< Real , Dim , PointD > values = WrapperLambda( eState , _off );
3204 T dot = {};
3205 for( int s=0 ; s<CumulativeDerivatives< Dim , PointD >::Size ; s++ ) dot += pData.dualValues[s] * values[s];
3206 Atomic< T >::Add( constraints[ _node->nodeData.nodeIndex ] , dot );
3207 }
3208 } ,
3209 neighbors.neighbors()
3210 );
3211 }
3212 }
3213 }
3214 );
3215 }
3216 }
3217 }
3218
3219 template< unsigned int Dim , class Real >
3220 template< typename T , typename TDotT , unsigned int ... FEMSigs1 , unsigned int ... FEMSigs2 , class Coefficients1 , class Coefficients2 , unsigned int PointD >
3221 double FEMTree< Dim , Real >::_interpolationDot( UIntPack< FEMSigs1 ... > , UIntPack< FEMSigs2 ... > , const Coefficients1& coefficients1 , const Coefficients2& coefficients2 , TDotT Dot , const InterpolationInfo< T , PointD >* iInfo ) const
3222 {
3223 typedef UIntPack< FEMSignature< FEMSigs1 >::Degree ... > FEMDegrees1;
3224 typedef UIntPack< FEMSignature< FEMSigs2 >::Degree ... > FEMDegrees2;
3225 typedef UIntPack< FEMSigs1 ... > FEMSignatures1;
3226 typedef UIntPack< FEMSigs2 ... > FEMSignatures2;
3227 double dot = 0;
3228 if( iInfo )
3229 {
3230 MultiThreadedEvaluator< FEMSignatures1 , PointD , T > mt1( this , coefficients1 );
3231 MultiThreadedEvaluator< FEMSignatures2 , PointD , T > mt2( this , coefficients2 );
3232
3233 size_t begin , end;
3234 iInfo->range( _spaceRoot , begin , end );
3235 std::vector< double > dots( ThreadPool::NumThreads() , 0 );
3236 ThreadPool::ParallelFor( begin , end , [&]( unsigned int thread , size_t i )
3237 {
3238 Point< Real , Dim > p = (*iInfo)[i].position;
3239 Real w = (*iInfo)[i].weight;
3240 CumulativeDerivativeValues< T , Dim , PointD > v1 = (*iInfo)( i , mt1.values( p , thread ) );
3241 CumulativeDerivativeValues< T , Dim , PointD > v2 = mt2.values( p , thread );
3242 for( int dd=0 ; dd<CumulativeDerivatives< Dim , PointD >::Size ; dd++ ) dots[thread] += Dot( v1[dd] , v2[dd] ) * w;
3243 }
3244 );
3245 for( unsigned int t=0 ; t<ThreadPool::NumThreads() ; t++ ) dot += dots[t];
3246 }
3247 return dot;
3248 }
3249
3250 template< unsigned int Dim , class Real >
3251 template< typename T , typename TDotT , unsigned int ... FEMSigs1 , unsigned int ... FEMSigs2 , unsigned int ... Degrees1 , unsigned int ... Degrees2 , class Coefficients1 , class Coefficients2 >
3252 double FEMTree< Dim , Real >::_dot( UIntPack< FEMSigs1 ... > , UIntPack< FEMSigs2 ... > , typename BaseFEMIntegrator::template Constraint< UIntPack< Degrees1 ... > , UIntPack< Degrees2 ... > , 1 >& F , const Coefficients1& coefficients1 , const Coefficients2& coefficients2 , TDotT Dot ) const
3253 {
3254 _setFEM1ValidityFlags( UIntPack< FEMSigs1 ... >() );
3255 _setFEM2ValidityFlags( UIntPack< FEMSigs2 ... >() );
3256 typedef typename BaseFEMIntegrator::template Constraint< UIntPack< Degrees1 ... > , UIntPack< Degrees2 ... > , 1 > BaseConstraint;
3257 double dot = 0;
3258 // Calculate the contribution from @(depth,depth)
3259 {
3260 typedef UIntPack< BSplineOverlapSizes< Degrees1 , Degrees2 >::OverlapSize ... > OverlapSizes;
3261 typedef UIntPack< -BSplineOverlapSizes< Degrees1 , Degrees2 >::OverlapStart ... > LeftOverlapRadii;
3262 typedef UIntPack< BSplineOverlapSizes< Degrees1 , Degrees2 >::OverlapEnd ... > RightOverlapRadii;
3263
3264 for( LocalDepth d=0 ; d<=_maxDepth ; d++ )
3265 {
3266 typename BaseConstraint::CCStencil stencil;
3267 F.init( d );
3268 F.template setStencil< false >( stencil );
3269
3270 std::vector< ConstOneRingNeighborKey > neighborKeys( ThreadPool::NumThreads() );
3271 for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( _localToGlobal( d ) );
3272
3273 std::vector< double > dots( ThreadPool::NumThreads() , 0 );
3274 ThreadPool::ParallelFor( _sNodesBegin(d) , _sNodesEnd(d) , [&]( unsigned int thread , size_t i )
3275 {
3276 double &dot = dots[thread];
3277 const FEMTreeNode* node = _sNodes.treeNodes[i];
3278 const T* _data1;
3279 if( _isValidFEM1Node( node ) && ( _data1=coefficients1(node) ) )
3280 {
3281 ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ];
3282 typename FEMTreeNode::template ConstNeighbors< OverlapSizes > neighbors;
3283 neighborKey.getNeighbors( LeftOverlapRadii() , RightOverlapRadii() , node , neighbors );
3284 bool isInterior = _isInteriorlyOverlapped( UIntPack< Degrees1 ... >() , UIntPack< Degrees2 ... >() , node );
3285
3286 LocalDepth d ; LocalOffset off;
3287 _localDepthAndOffset( node , d , off );
3288 ConstPointer( FEMTreeNode * const ) nodes = neighbors.neighbors().data;
3289 ConstPointer( Point< double , 1 > ) stencilValues = stencil.data;
3290 if( isInterior )
3291 {
3292 for( int i=0 ; i<WindowSize< UIntPack< BSplineOverlapSizes< Degrees1 , Degrees2 >::OverlapSize ... > >::Size ; i++ )
3293 {
3294 const T* _data2;
3295 if( _isValidFEM2Node( nodes[i] ) && ( _data2=coefficients2( nodes[i] ) ) ) dot += Dot( *_data1 , *_data2 ) * stencilValues[i][0];
3296 }
3297 }
3298 else
3299 {
3300 for( int i=0 ; i<WindowSize< UIntPack< BSplineOverlapSizes< Degrees1 , Degrees2 >::OverlapSize ... > >::Size ; i++ )
3301 {
3302 const T* _data2;
3303 if( _isValidFEM2Node( nodes[i] ) && ( _data2=coefficients2( nodes[i] ) ) )
3304 {
3305 LocalDepth _d ; LocalOffset _off ; _localDepthAndOffset( nodes[i] , _d , _off );
3306 dot += Dot( *_data1 , *_data2 ) * F.ccIntegrate( off , _off )[0];
3307 }
3308 }
3309 }
3310 }
3311 }
3312 );
3313 for( unsigned int t=0 ; t<ThreadPool::NumThreads() ; t++ ) dot += dots[t];
3314 }
3315 }
3316 // Calculate the contribution from @(<depth,depth)
3317 {
3318 typedef UIntPack< BSplineOverlapSizes< Degrees2 , Degrees1 >::OverlapSize ... > OverlapSizes;
3319 typedef UIntPack< -BSplineOverlapSizes< Degrees2 , Degrees1 >::OverlapStart ... > LeftOverlapRadii;
3320 typedef UIntPack< BSplineOverlapSizes< Degrees2 , Degrees1 >::OverlapEnd ... > RightOverlapRadii;
3321
3322 DenseNodeData< T , UIntPack< FEMSigs1 ... > > cumulative1( _sNodesEnd( _maxDepth-1 ) );
3323 if( _maxDepth>0 ) memset( cumulative1() , 0 , sizeof(T) * _sNodesEnd( _maxDepth-1 ) );
3324
3325 for( LocalDepth d=1 ; d<=_maxDepth ; d++ )
3326 {
3327 // Update the cumulative coefficients with the coefficients @(depth-1)
3328 ThreadPool::ParallelFor( _sNodesBegin(d-1) , _sNodesEnd(d-1) , [&]( unsigned int , size_t i )
3329 {
3330 const T* _data1 = coefficients1( _sNodes.treeNodes[i] );
3331 if( _data1 ) cumulative1[i] += *_data1;
3332 }
3333 );
3334
3335 typename BaseConstraint::PCStencils stencils;
3336 F.init( d );
3337 F.template setStencils< true >( stencils );
3338
3339 std::vector< ConstOneRingNeighborKey > neighborKeys( ThreadPool::NumThreads() );
3340 for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( _localToGlobal( d-1 ) );
3341
3342 std::vector< double > dots( ThreadPool::NumThreads() , 0 );
3343 ThreadPool::ParallelFor( _sNodesBegin(d) , _sNodesEnd(d) , [&]( unsigned int thread , size_t i )
3344 {
3345 double &dot = dots[thread];
3346 const FEMTreeNode* node = _sNodes.treeNodes[i];
3347 const T* _data2;
3348 if( _isValidFEM2Node( node ) && ( _data2=coefficients2( node ) ) )
3349 {
3350 ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ];
3351 bool isInterior = _isInteriorlyOverlapped( UIntPack< Degrees1 ... >() , UIntPack< Degrees2 ... >() , node->parent );
3352
3353 LocalDepth d ; LocalOffset off;
3354 _localDepthAndOffset( node , d , off );
3355
3356 int cIdx = (int)( node - node->parent->children );
3357 typename BaseConstraint::CCStencil& _stencil = stencils.data[cIdx];
3358 typename FEMTreeNode::template ConstNeighbors< OverlapSizes > neighbors;
3359 neighborKey.getNeighbors( LeftOverlapRadii() , RightOverlapRadii() , node->parent , neighbors );
3360
3361 int start[Dim] , end[Dim];
3362 _SetParentOverlapBounds( UIntPack< Degrees1 ... >() , UIntPack< Degrees2 ... >() , node , start , end );
3363 WindowLoop< Dim >::Run
3364 (
3365 start , end ,
3366 [&]( int , int ){;} ,
3367 [&]( const FEMTreeNode* node , Point< double , 1 > stencilValue )
3368 {
3369 const T* _data1;
3370 if( _isValidFEM1Node( node ) && ( _data1=cumulative1(node) ) )
3371 {
3372 if( isInterior ) dot += Dot( *_data1 , *_data2 ) * stencilValue[0];
3373 else
3374 {
3375 LocalDepth _d ; LocalOffset _off ; _localDepthAndOffset( node , _d , _off );
3376 dot += Dot ( *_data1 , *_data2 ) * F.pcIntegrate( _off , off )[0];
3377 }
3378 }
3379 } ,
3380 neighbors.neighbors() , _stencil()
3381 );
3382 }
3383 }
3384 );
3385 for( unsigned int t=0 ; t<ThreadPool::NumThreads() ; t++ ) dot += dots[t];
3386 // Up sample the cumulative coefficients for the next level
3387 if( d<_maxDepth ) _upSample( UIntPack< FEMSigs1 ... >() , F.tRestrictionProlongation() , d , cumulative1()+_sNodesBegin(d-1) , cumulative1()+_sNodesBegin(d) );
3388 }
3389 }
3390
3391 // Calculate the contribution from @(>depth,depth)
3392 {
3393 typedef UIntPack< BSplineOverlapSizes< Degrees1 , Degrees2 >::OverlapSize ... > OverlapSizes;
3394 typedef UIntPack< -BSplineOverlapSizes< Degrees1 , Degrees2 >::OverlapStart ... > LeftOverlapRadii;
3395 typedef UIntPack< BSplineOverlapSizes< Degrees1 , Degrees2 >::OverlapEnd ... > RightOverlapRadii;
3396
3397 DenseNodeData< T , UIntPack< FEMSigs2 ... > > cumulative2( _sNodesEnd( _maxDepth-1 ) );
3398 if( _maxDepth>0 ) memset( cumulative2() , 0 , sizeof(T) * _sNodesEnd( _maxDepth-1 ) );
3399
3400 for( LocalDepth d=_maxDepth ; d>0 ; d-- )
3401 {
3402 typename BaseConstraint::CPStencils stencils;
3403 F.init( d );
3404 F.template setStencils< false >( stencils );
3405
3406 std::vector< ConstOneRingNeighborKey > neighborKeys( ThreadPool::NumThreads() );
3407 for( size_t i=0 ; i<neighborKeys.size() ; i++ ) neighborKeys[i].set( _localToGlobal( d-1 ) );
3408
3409 // Update the cumulative constraints @(depth-1) from @(depth)
3410 std::vector< double > dots( ThreadPool::NumThreads() , 0 );
3411 ThreadPool::ParallelFor( _sNodesBegin(d) , _sNodesEnd(d) , [&]( unsigned int thread , size_t i )
3412 {
3413 double &dot = dots[thread];
3414 const FEMTreeNode* node = _sNodes.treeNodes[i];
3415 const T* _data1;
3416 if( _isValidFEM1Node( node ) && ( _data1=coefficients1( node ) ) )
3417 {
3418 ConstOneRingNeighborKey& neighborKey = neighborKeys[ thread ];
3419 bool isInterior = _isInteriorlyOverlapped( UIntPack< Degrees2 ... >() , UIntPack< Degrees1 ... >() , node->parent );
3420
3421 LocalDepth d ; LocalOffset off;
3422 _localDepthAndOffset( node , d , off );
3423
3424 int cIdx = (int)( node - node->parent->children );
3425 typename BaseConstraint::CCStencil& _stencil = stencils.data[cIdx];
3426 typename FEMTreeNode::template ConstNeighbors< OverlapSizes > neighbors;
3427 neighborKey.getNeighbors( LeftOverlapRadii() , RightOverlapRadii() , node->parent , neighbors );
3428
3429 int start[Dim] , end[Dim];
3430 _SetParentOverlapBounds( UIntPack< Degrees1 ... >() , UIntPack< Degrees2 ... >() , node , start , end );
3431
3432 #ifdef __clang__
3433 #ifdef SHOW_WARNINGS
3434 #pragma message ( "[WARNING] You've got me clang" )
3435 #endif // SHOW_WARNINGS
3436 std::function< void (int,int) > updateFunction = [](int,int){};
3437 #endif // __clang__
3438
3439 WindowLoop< Dim >::Run
3440 (
3441 start , end ,
3442 #ifdef __clang__
3443 updateFunction ,
3444 #else // !__clang__
3445 [&]( int , int ){;} ,
3446 #endif // __clang__
3447 [&]( const FEMTreeNode* node , Point< double , 1 > stencilValue )
3448 {
3449 if( _isValidFEM2Node( node ) )
3450 {
3451 T _dot;
3452 if( isInterior ) _dot = (*_data1) * stencilValue[0];
3453 else
3454 {
3455 LocalDepth _d ; LocalOffset _off ; _localDepthAndOffset( node , _d , _off );
3456 _dot = (*_data1) * F.cpIntegrate( off , _off )[0];
3457 }
3458 Atomic< T >::Add( cumulative2[ node->nodeData.nodeIndex ] , _dot );
3459 }
3460 } ,
3461 neighbors.neighbors() , _stencil()
3462 );
3463 }
3464 }
3465 );
3466 for( unsigned int t=0 ; t<ThreadPool::NumThreads() ; t++ ) dot += dots[t];
3467 // Update the dot-product using the cumulative constraints @(depth-1)
3468 for( unsigned int t=0 ; t<ThreadPool::NumThreads() ; t++ ) dots[t] = 0;
3469 ThreadPool::ParallelFor( _sNodesBegin(d-1) , _sNodesEnd(d-1) , [&]( unsigned int thread , size_t i )
3470 {
3471 double &dot = dots[thread];
3472 const FEMTreeNode* node = _sNodes.treeNodes[i];
3473 const T* _data2;
3474 if( _isValidFEM2Node( node ) && ( _data2=coefficients2( node ) ) ) dot += Dot( cumulative2[ node->nodeData.nodeIndex ] , *_data2 );
3475 }
3476 );
3477 for( unsigned int t=0 ; t<ThreadPool::NumThreads() ; t++ ) dot += dots[t];
3478
3479 // Down-sample the cumulative constraints from @(depth-1) to @(depth-2) for the next pass
3480 if( d-1>0 ) _downSample( UIntPack< FEMSigs2 ... >() , F.cRestrictionProlongation() , d-1 , GetPointer( &cumulative2[0] , cumulative2.size() ) + _sNodesBegin(d-1) , GetPointer( &cumulative2[0] , cumulative2.size() ) + _sNodesBegin(d-2) );
3481 }
3482 }
3483 return dot;
3484 }