1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
/* *****************************************************************
    MESQUITE -- The Mesh Quality Improvement Toolkit

    Copyright 2004 Sandia Corporation and Argonne National
    Laboratory.  Under the terms of Contract DE-AC04-94AL85000
    with Sandia Corporation, the U.S. Government retains certain
    rights in this software.

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    (lgpl.txt) along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    [email protected], [email protected], [email protected],
    [email protected], [email protected], [email protected]
    [email protected]

  ***************************************************************** */
/*!
  \file   QualityMetric.cpp
  \brief

  \author Michael Brewer
  \author Thomas Leurent
  \date   2002-05-14
  \author Jason Kraftcheck
  \date   2006-04-20
*/

#include "QualityMetric.hpp"
#include "MsqVertex.hpp"
#include "PatchData.hpp"

namespace MBMesquite
{

void QualityMetric::initialize_queue( MeshDomainAssoc*, const Settings*, MsqError& ) {}

void QualityMetric::get_single_pass( PatchData& pd,
                                     std::vector< size_t >& handles,
                                     bool free_vertices_only,
                                     MsqError& err )
{
    get_evaluations( pd, handles, free_vertices_only, err );
}

static inline double get_delta_C( const PatchData& pd, const std::vector< size_t >& indices, MsqError& err )
{
    if( indices.empty() )
    {
        MSQ_SETERR( err )( MsqError::INVALID_ARG );
        return 0.0;
    }

    std::vector< size_t >::const_iterator beg, iter, iter2, end;

    std::vector< size_t > tmp_vect;
    if( indices.size() == 1u )
    {
        pd.get_adjacent_vertex_indices( indices.front(), tmp_vect, err );
        MSQ_ERRZERO( err );
        assert( !tmp_vect.empty() );
        tmp_vect.push_back( indices.front() );
        beg = tmp_vect.begin();
        end = tmp_vect.end();
    }
    else
    {
        beg = indices.begin();
        end = indices.end();
    }

    double min_dist_sqr = HUGE_VAL, sum_dist_sqr = 0.0;
    for( iter = beg; iter != end; ++iter )
    {
        for( iter2 = iter + 1; iter2 != end; ++iter2 )
        {
            Vector3D diff = pd.vertex_by_index( *iter );
            diff -= pd.vertex_by_index( *iter2 );
            double dist_sqr = diff % diff;
            if( dist_sqr < min_dist_sqr ) min_dist_sqr = dist_sqr;
            sum_dist_sqr += dist_sqr;
        }
    }

    return 3e-6 * sqrt( min_dist_sqr ) + 5e-7 * sqrt( sum_dist_sqr / ( end - beg ) );
}

bool QualityMetric::evaluate_with_gradient( PatchData& pd,
                                            size_t handle,
                                            double& value,
                                            std::vector< size_t >& indices,
                                            std::vector< Vector3D >& gradient,
                                            MsqError& err )
{
    indices.clear();
    bool valid = evaluate_with_indices( pd, handle, value, indices, err );
    if( MSQ_CHKERR( err ) || !valid ) return false;
    if( indices.empty() ) return true;

    // get initial pertubation amount
    double delta_C = finiteDiffEps;
    if( !haveFiniteDiffEps )
    {
        delta_C = get_delta_C( pd, indices, err );
        MSQ_ERRZERO( err );
        if( keepFiniteDiffEps )
        {
            finiteDiffEps     = delta_C;
            haveFiniteDiffEps = true;
        }
    }
    const double delta_inv_C  = 1.0 / delta_C;
    const int reduction_limit = 15;

    gradient.resize( indices.size() );
    for( size_t v = 0; v < indices.size(); ++v )
    {
        const Vector3D pos = pd.vertex_by_index( indices[v] );

        /* gradient in the x, y, z direction */
        for( int j = 0; j < 3; ++j )
        {
            double delta     = delta_C;
            double delta_inv = delta_inv_C;
            double metric_value;
            Vector3D delta_v( 0, 0, 0 );

            // perturb the node and calculate gradient.  The while loop is a
            // safety net to make sure the epsilon perturbation does not take
            // the element out of the feasible region.
            int counter = 0;
            for( ;; )
            {
                // perturb the coordinates of the free vertex in the j direction
                // by delta
                delta_v[j] = delta;
                pd.set_vertex_coordinates( pos + delta_v, indices[v], err );
                MSQ_ERRZERO( err );

                // compute the function at the perturbed point location
                valid = evaluate( pd, handle, metric_value, err );
                if( !MSQ_CHKERR( err ) && valid ) break;

                if( ++counter >= reduction_limit )
                {
                    MSQ_SETERR( err )
                    ( "Perturbing vertex by delta caused an inverted element.", MsqError::INTERNAL_ERROR );
                    return false;
                }

                delta *= 0.1;
                delta_inv *= 10.;
            }
            // put the coordinates back where they belong
            pd.set_vertex_coordinates( pos, indices[v], err );
            // compute the numerical gradient
            gradient[v][j] = ( metric_value - value ) * delta_inv;
        }  // for(j)
    }      // for(indices)
    return true;
}

bool QualityMetric::evaluate_with_Hessian( PatchData& pd,
                                           size_t handle,
                                           double& value,
                                           std::vector< size_t >& indices,
                                           std::vector< Vector3D >& gradient,
                                           std::vector< Matrix3D >& Hessian,
                                           MsqError& err )
{
    indices.clear();
    gradient.clear();
    keepFiniteDiffEps = true;
    bool valid        = evaluate_with_gradient( pd, handle, value, indices, gradient, err );
    keepFiniteDiffEps = false;
    if( MSQ_CHKERR( err ) || !valid )
    {
        haveFiniteDiffEps = false;
        return false;
    }
    if( indices.empty() )
    {
        haveFiniteDiffEps = false;
        return true;
    }

    // get initial pertubation amount
    double delta_C;
    if( haveFiniteDiffEps )
    {
        delta_C = finiteDiffEps;
    }
    else
    {
        delta_C = get_delta_C( pd, indices, err );
        MSQ_ERRZERO( err );
    }
    assert( delta_C < 1e30 );
    const double delta_inv_C  = 1.0 / delta_C;
    const int reduction_limit = 15;

    std::vector< Vector3D > temp_gradient( indices.size() );
    const int num_hess = indices.size() * ( indices.size() + 1 ) / 2;
    Hessian.resize( num_hess );

    for( unsigned v = 0; v < indices.size(); ++v )
    {
        const Vector3D pos = pd.vertex_by_index( indices[v] );
        for( int j = 0; j < 3; ++j )
        {  // x, y, and z
            double delta     = delta_C;
            double delta_inv = delta_inv_C;
            double metric_value;
            Vector3D delta_v( 0, 0, 0 );

            // find finite difference for gradient
            int counter = 0;
            for( ;; )
            {
                delta_v[j] = delta;
                pd.set_vertex_coordinates( pos + delta_v, indices[v], err );
                MSQ_ERRZERO( err );
                valid = evaluate_with_gradient( pd, handle, metric_value, indices, temp_gradient, err );
                if( !MSQ_CHKERR( err ) && valid ) break;

                if( ++counter >= reduction_limit )
                {
                    MSQ_SETERR( err )
                    ( "Algorithm did not successfully compute element's "
                      "Hessian.\n",
                      MsqError::INTERNAL_ERROR );
                    haveFiniteDiffEps = false;
                    return false;
                }

                delta *= 0.1;
                delta_inv *= 10.0;
            }
            pd.set_vertex_coordinates( pos, indices[v], err );
            MSQ_ERRZERO( err );

            // compute the numerical Hessian
            for( unsigned w = 0; w <= v; ++w )
            {
                // finite difference to get some entries of the Hessian
                Vector3D fd( temp_gradient[w] );
                fd -= gradient[w];
                fd *= delta_inv;
                // For the block at position w,v in a matrix, we need the corresponding index
                // (mat_index) in a 1D array containing only upper triangular blocks.
                unsigned sum_w           = w * ( w + 1 ) / 2;  // 1+2+3+...+w
                unsigned mat_index       = w * indices.size() + v - sum_w;
                Hessian[mat_index][0][j] = fd[0];
                Hessian[mat_index][1][j] = fd[1];
                Hessian[mat_index][2][j] = fd[2];
            }
        }  // for(j)
    }      // for(indices)
    haveFiniteDiffEps = false;
    return true;
}

bool QualityMetric::evaluate_with_Hessian_diagonal( PatchData& pd,
                                                    size_t handle,
                                                    double& value,
                                                    std::vector< size_t >& indices,
                                                    std::vector< Vector3D >& gradient,
                                                    std::vector< SymMatrix3D >& Hessian_diagonal,
                                                    MsqError& err )
{
    bool rval = evaluate_with_Hessian( pd, handle, value, indices, gradient, tmpHess, err );
    if( MSQ_CHKERR( err ) || !rval ) return rval;
    size_t s = indices.size();
    Hessian_diagonal.resize( s );
    std::vector< Matrix3D >::const_iterator h = tmpHess.begin();
    for( size_t i = 0; i < indices.size(); ++i )
    {
        Hessian_diagonal[i] = h->upper();
        h += s--;
    }
    return rval;
}

uint32_t QualityMetric::fixed_vertex_bitmap( PatchData& pd, const MsqMeshEntity* elem, std::vector< size_t >& indices )
{
    indices.clear();
    uint32_t result        = ~(uint32_t)0;
    unsigned num_vtx       = elem->vertex_count();
    const size_t* vertices = elem->get_vertex_index_array();
    indices.clear();
    for( unsigned i = 0; i < num_vtx; ++i )
    {
        if( vertices[i] < pd.num_free_vertices() )
        {
            indices.push_back( vertices[i] );
            result &= ~(uint32_t)( 1 << i );
        }
    }
    return result;
}

void QualityMetric::remove_fixed_gradients( EntityTopology elem_type, uint32_t fixed, std::vector< Vector3D >& grads )
{
    const unsigned num_vertex = TopologyInfo::corners( elem_type );
    unsigned r, w;
    for( r = 0; r < num_vertex && !( fixed & ( 1 << r ) ); ++r )
        ;
    for( w = r++; r < num_vertex; ++r )
    {
        if( !( fixed & ( 1 << r ) ) )
        {
            grads[w] = grads[r];
            ++w;
        }
    }
    grads.resize( w );
}

void QualityMetric::remove_fixed_diagonals( EntityTopology type,
                                            uint32_t fixed,
                                            std::vector< Vector3D >& grads,
                                            std::vector< SymMatrix3D >& diags )
{
    const unsigned num_vertex = TopologyInfo::corners( type );
    unsigned r, w;
    for( r = 0; r < num_vertex && !( fixed & ( 1 << r ) ); ++r )
        ;
    for( w = r++; r < num_vertex; ++r )
    {
        if( !( fixed & ( 1 << r ) ) )
        {
            grads[w] = grads[r];
            diags[w] = diags[r];
            ++w;
        }
    }
    grads.resize( w );
    diags.resize( w );
}

void QualityMetric::remove_fixed_hessians( EntityTopology elem_type, uint32_t fixed, std::vector< Matrix3D >& hessians )
{
    const unsigned num_vertex = TopologyInfo::corners( elem_type );
    unsigned r, c, i = 0, w = 0;
    for( r = 0; r < num_vertex; ++r )
    {
        if( fixed & ( 1 << r ) )
        {
            i += num_vertex - r;
            continue;
        }
        for( c = r; c < num_vertex; ++c )
        {
            if( !( fixed & ( 1 << c ) ) )
            {
                hessians[w] = hessians[i];
                ++w;
            }
            ++i;
        }
    }
    hessians.resize( w );
}

double QualityMetric::weighted_average_metrics( const double coef[],<--- The function 'weighted_average_metrics' is never used.
                                                const double metric_values[],
                                                const int& num_values,
                                                MsqError& /*err*/ )
{
    // MSQ_MAX needs to be made global?
    // double MSQ_MAX=1e10;
    double total_value = 0.0;
    int i              = 0;
    // if no values, return zero
    if( num_values <= 0 )
    {
        return 0.0;
    }

    for( i = 0; i < num_values; ++i )
    {
        total_value += coef[i] * metric_values[i];
    }
    total_value /= (double)num_values;

    return total_value;
}

}  // namespace MBMesquite