GetFEM  5.6
getfem_contact_and_friction_common.cc
1 /*===========================================================================
2 
3  Copyright (C) 2013-2026 Yves Renard, Konstantinos Poulios.
4 
5  This file is a part of GetFEM
6 
7  GetFEM is free software; you can redistribute it and/or modify it
8  under the terms of the GNU Lesser General Public License as published
9  by the Free Software Foundation; either version 3 of the License, or
10  (at your option) any later version along with the GCC Runtime Library
11  Exception either version 3.1 or (at your option) any later version.
12  This program is distributed in the hope that it will be useful, but
13  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14  or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
15  License and GCC Runtime Library Exception for more details.
16  You should have received a copy of the GNU Lesser General Public License
17  along with this program. If not, see https://www.gnu.org/licenses/.
18 
19 ===========================================================================*/
20 
23 #ifndef _WIN32
24 #include <unistd.h>
25 #endif
26 
27 namespace getfem {
28 
29  bool boundary_has_fem_nodes(bool slave_flag, int nodes_mode) {
30  return (slave_flag && nodes_mode) ||
31  (!slave_flag && nodes_mode == 2);
32  }
33 
34  void compute_normal(const fem_interpolation_context &ctx,
35  size_type face, bool in_reference_conf,
36  const model_real_plain_vector &coeff,
37  base_node &n0, base_node &n,
38  base_matrix &grad) {
39  if (face == size_type(short_type(-1))) {
40  // inside an element of a curve in 2D or a surface in 3D (shell):
41  // its unit normal, oriented by its parametrization
43  GMM_ASSERT1(n0.size() == ctx.N(), "Contact boundaries are faces of "
44  "elements, or elements of curves in 2D and surfaces "
45  "in 3D");
46  } else
47  n0 = bgeot::compute_normal(ctx, face);
48  if (in_reference_conf) {
49  n = n0;
50  } else {
51  ctx.pf()->interpolation_grad(ctx, coeff, grad, dim_type(ctx.N()));
52  gmm::add(gmm::identity_matrix(), grad);
53  scalar_type J = bgeot::lu_inverse(&(*(grad.begin())), ctx.N());
54  if (J <= scalar_type(0)) {GMM_WARNING1("Inverted element !" << J);
55  gmm::mult(gmm::transposed(grad), n0, n);
56  gmm::scale(n, gmm::sgn(J));
57  //cout<< "n0 =" << n0 << "n =" <<n<< endl;
58  //cout<< "x0=" << ctx.xref() << "x =" <<ctx.xreal()<< endl;
59  }
60  else {
61  gmm::mult(gmm::transposed(grad), n0, n);
62  gmm::scale(n, gmm::sgn(J));} // Test
63  }
64  }
65 
66  //=========================================================================
67  //
68  // Structure which store the contact boundaries, rigid obstacles and
69  // computes the contact pairs in large sliding/large deformation.
70  //
71  //=========================================================================
72 
73  size_type multi_contact_frame::add_U
74  (const model_real_plain_vector *U, const std::string &name,
75  const model_real_plain_vector *w, const std::string &wname) {
76  if (!U) return size_type(-1);
77  size_type i = 0;
78  for (; i < Us.size(); ++i) if (Us[i] == U) return i;
79  Us.push_back(U);
80  Ws.push_back(w);
81  Unames.push_back(name);
82  Wnames.push_back(wname);
83  ext_Us.resize(Us.size());
84  ext_Ws.resize(Us.size());
85  return i;
86  }
87 
88  size_type multi_contact_frame::add_lambda
89  (const model_real_plain_vector *lambda, const std::string &name) {
90  if (!lambda) return size_type(-1);
91  size_type i = 0;
92  for (; i < lambdas.size(); ++i) if (lambdas[i] == lambda) return i;
93  lambdas.push_back(lambda);
94  lambdanames.push_back(name);
95  ext_lambdas.resize(lambdas.size());
96  return i;
97  }
98 
99  void multi_contact_frame::extend_vectors() {
100  dal::bit_vector iU, ilambda;
101  for (size_type i = 0; i < contact_boundaries.size(); ++i) {
102  size_type ind_U = contact_boundaries[i].ind_U;
103  if (!(iU[ind_U])) {
104  const mesh_fem &mf = *(contact_boundaries[i].mfu);
105  gmm::resize(ext_Us[ind_U], mf.nb_basic_dof());
106  mf.extend_vector(*(Us[ind_U]), ext_Us[ind_U]);
107  if (Ws[ind_U]) {
108  gmm::resize(ext_Ws[ind_U], mf.nb_basic_dof());
109  mf.extend_vector(*(Ws[ind_U]), ext_Ws[ind_U]);
110  } else gmm::resize(ext_Ws[ind_U], 0);
111  iU.add(ind_U);
112  }
113  size_type ind_lambda = contact_boundaries[i].ind_lambda;
114  if (ind_lambda != size_type(-1) && !(ilambda[ind_lambda])) {
115  const mesh_fem &mf = *(contact_boundaries[i].mflambda);
116  gmm::resize(ext_lambdas[ind_lambda], mf.nb_basic_dof());
117  mf.extend_vector(*(lambdas[ind_lambda]), ext_lambdas[ind_lambda]);
118  ilambda.add(ind_lambda);
119  }
120  }
121  }
122 
123  void multi_contact_frame::normal_cone_simplification() {
124  if (nodes_mode) {
125  scalar_type threshold = ::cos(cut_angle);
126  for (size_type i = 0; i < boundary_points_info.size(); ++i) {
127  normal_cone &nc = boundary_points_info[i].normals;
128  if (nc.size() > 1) {
129  base_small_vector n_mean = nc[0];
130  for (size_type j = 1; j < nc.size(); ++j) n_mean += nc[j];
131  scalar_type nn_mean = gmm::vect_norm2(n_mean);
132  GMM_ASSERT1(nn_mean != scalar_type(0), "oupssss");
133  if (nn_mean != scalar_type(0)) {
134  gmm::scale(n_mean, scalar_type(1)/nn_mean);
135  bool reduce = true;
136  for (size_type j = 0; j < nc.size(); ++j)
137  if (gmm::vect_sp(n_mean, nc[j]) < threshold)
138  { reduce = false; break; }
139  if (reduce) {
140  boundary_points_info[i].normals = normal_cone(n_mean);
141  }
142  }
143  }
144  }
145  }
146  }
147 
148  bool multi_contact_frame::test_normal_cones_compatibility
149  (const normal_cone &nc1, const normal_cone &nc2) {
150  for (size_type i = 0; i < nc1.size(); ++i)
151  for (size_type j = 0; j < nc2.size(); ++j)
152  if (gmm::vect_sp(nc1[i], nc2[j]) < scalar_type(0))
153  return true;
154  return false;
155  }
156 
157  bool multi_contact_frame::test_normal_cones_compatibility
158  (const base_small_vector &n, const normal_cone &nc2) {
159  for (size_type j = 0; j < nc2.size(); ++j)
160  if (gmm::vect_sp(n, nc2[j]) < scalar_type(0))
161  return true;
162  return false;
163  }
164 
165  bool multi_contact_frame::are_dof_linked(size_type ib1, size_type idof1,
166  size_type ib2, size_type idof2) {
167  const mesh_fem &mf1 = mfdisp_of_boundary(ib1);
168  const mesh_fem &mf2 = mfdisp_of_boundary(ib2);
169  if ( &(mf1.linked_mesh()) != &(mf2.linked_mesh())) return false;
170  GMM_ASSERT1(!(mf1.is_reduced()) && !(mf2.is_reduced()),
171  "Nodal strategy can only be applied for non reduced fems");
172  const mesh::ind_cv_ct &ic1 = mf1.convex_to_basic_dof(idof1);
173  const mesh::ind_cv_ct &ic2 = mf2.convex_to_basic_dof(idof2);
174  bool lk = false;
175  for (size_type i = 0; i < ic1.size(); ++i) aux_dof_cv.add(ic1[i]);
176  for (size_type i = 0; i < ic2.size(); ++i)
177  if (aux_dof_cv.is_in(ic2[i])) { lk = true; break; }
178  for (size_type i = 0; i < ic1.size(); ++i) aux_dof_cv.sup(ic1[i]);
179  return lk;
180  }
181 
182  bool multi_contact_frame::is_dof_linked(size_type ib1, size_type idof1,
183  size_type ib2, size_type cv) {
184  const mesh_fem &mf1 = mfdisp_of_boundary(ib1);
185  const mesh_fem &mf2 = mfdisp_of_boundary(ib2);
186  if ( &(mf1.linked_mesh()) != &(mf2.linked_mesh())) return false;
187  GMM_ASSERT1(!(mf1.is_reduced()) && !(mf2.is_reduced()),
188  "Nodal strategy can only be applied for non reduced fems");
189  const mesh::ind_cv_ct &ic1 = mf1.convex_to_basic_dof(idof1);
190  for (size_type i = 0; i < ic1.size(); ++i)
191  if (cv == ic1[i]) return true;
192  return false;
193  }
194 
195  void multi_contact_frame::add_potential_contact_face
196  (size_type ip, size_type ib, size_type ie, short_type iff) {
197  bool found = false;
198  std::vector<face_info> &sfi = potential_pairs[ip];
199  for (size_type k = 0; k < sfi.size(); ++k)
200  if (sfi[k].ind_boundary == ib &&
201  sfi[k].ind_element == ie &&
202  sfi[k].ind_face == iff) found = true;
203 
204  if (!found) sfi.push_back(face_info(ib, ie, iff));
205  }
206 
207  void multi_contact_frame::clear_aux_info() {
208  boundary_points = std::vector<base_node>();
209  boundary_points_info = std::vector<boundary_point>();
210  element_boxes.clear();
211  element_boxes_info = std::vector<influence_box>();
212  potential_pairs = std::vector<std::vector<face_info> >();
213  }
214 
215  multi_contact_frame::multi_contact_frame(size_type NN, scalar_type r_dist,
216  bool dela, bool selfc,
217  scalar_type cut_a,
218  bool rayt, int nmode, bool refc)
219  : N(NN), self_contact(selfc), ref_conf(refc), use_delaunay(dela),
220  nodes_mode(nmode), raytrace(rayt), release_distance(r_dist),
221  cut_angle(cut_a), EPS(1E-8), md(0), coordinates(N), pt(N) {
222  if (N > 0) coordinates[0] = "x";
223  if (N > 1) coordinates[1] = "y";
224  if (N > 2) coordinates[2] = "z";
225  if (N > 3) coordinates[3] = "w";
226  GMM_ASSERT1(N <= 4, "Complete the definition for contact in "
227  "dimension greater than 4");
228  }
229 
230  multi_contact_frame::multi_contact_frame(const model &mdd, size_type NN,
231  scalar_type r_dist,
232  bool dela, bool selfc,
233  scalar_type cut_a,
234  bool rayt, int nmode, bool refc)
235  : N(NN), self_contact(selfc), ref_conf(refc),
236  use_delaunay(dela), nodes_mode(nmode), raytrace(rayt),
237  release_distance(r_dist), cut_angle(cut_a), EPS(1E-8), md(&mdd),
238  coordinates(N), pt(N) {
239  if (N > 0) coordinates[0] = "x";
240  if (N > 1) coordinates[1] = "y";
241  if (N > 2) coordinates[2] = "z";
242  if (N > 3) coordinates[3] = "w";
243  GMM_ASSERT1(N <= 4, "Complete the definition for contact in "
244  "dimension greater than 4");
245  }
246 
247  size_type multi_contact_frame::add_obstacle(const std::string &obs) {
248  size_type ind = obstacles.size();
249  obstacles.push_back(obs);
250  obstacles_velocities.push_back("");
251  obstacles_gw.push_back(ga_workspace());
252  pt.resize(N); ptx.resize(1); pty.resize(1); ptz.resize(1); ptw.resize(1);
253  obstacles_gw.back().add_fixed_size_constant("X", pt);
254  if (N >= 4) obstacles_gw.back().add_fixed_size_constant("w", ptw);
255  if (N >= 3) obstacles_gw.back().add_fixed_size_constant("z", ptz);
256  if (N >= 2) obstacles_gw.back().add_fixed_size_constant("y", pty);
257  if (N >= 1) obstacles_gw.back().add_fixed_size_constant("x", ptx);
258  obstacles_f.push_back(ga_function(obstacles_gw.back(), obs));
259  obstacles_f.back().compile();
260  return ind;
261  }
262 
263 
264 
265  size_type multi_contact_frame::add_master_boundary
266  (const mesh_im &mim, const mesh_fem *mfu,
267  const model_real_plain_vector *U, size_type reg,
268  const mesh_fem *mflambda, const model_real_plain_vector *lambda,
269  const model_real_plain_vector *w,
270  const std::string &vvarname,
271  const std::string &mmultname, const std::string &wname) {
272  GMM_ASSERT1(mfu->linked_mesh().dim() == N,
273  "Mesh dimension is " << mfu->linked_mesh().dim()
274  << "should be " << N << ".");
275  GMM_ASSERT1(&(mfu->linked_mesh()) == &(mim.linked_mesh()),
276  "Integration and finite element are not on the same mesh !");
277  if (mflambda)
278  GMM_ASSERT1(&(mflambda->linked_mesh()) == &(mim.linked_mesh()),
279  "Integration and finite element are not on the same mesh !");
280  contact_boundary cb(reg, mfu, mim, add_U(U, vvarname, w, wname),
281  mflambda, add_lambda(lambda, mmultname));
282  contact_boundaries.push_back(cb);
283  return size_type(contact_boundaries.size() - 1);
284  }
285 
286  size_type multi_contact_frame::add_slave_boundary
287  (const mesh_im &mim, const mesh_fem *mfu,
288  const model_real_plain_vector *U, size_type reg,
289  const mesh_fem *mflambda, const model_real_plain_vector *lambda,
290  const model_real_plain_vector *w,
291  const std::string &vvarname,
292  const std::string &mmultname, const std::string &wname) {
293  size_type ind
294  = add_master_boundary(mim, mfu, U, reg, mflambda, lambda, w,
295  vvarname, mmultname, wname);
296  contact_boundaries[ind].slave = true;
297  return ind;
298  }
299 
300 
301  size_type multi_contact_frame::add_master_boundary
302  (const mesh_im &mim, size_type reg, const std::string &vvarname,
303  const std::string &mmultname, const std::string &wname) {
304  GMM_ASSERT1(md, "This multi contact frame object is not linked "
305  "to a model");
306  const mesh_fem *mfl(0);
307  const model_real_plain_vector *l(0);
308  if (mmultname.size()) {
309  mfl = &(md->mesh_fem_of_variable(mmultname));
310  l = &(md->real_variable(mmultname));
311  }
312  const model_real_plain_vector *w(0);
313  if (wname.compare(vvarname) == 0) {
314  GMM_ASSERT1(md->n_iter_of_variable(vvarname) > 1, "More than one "
315  "versions of the displacement variable were expected here");
316  w = &(md->real_variable(vvarname,1));
317  }
318  else if (wname.size()) {
319  GMM_ASSERT1(&(md->mesh_fem_of_variable(wname))
320  == &(md->mesh_fem_of_variable(vvarname)), "The previous "
321  "displacement should be defined on the same mesh_fem as the "
322  "current one");
323  w = &(md->real_variable(wname));
324  }
325  return add_master_boundary(mim, &(md->mesh_fem_of_variable(vvarname)),
326  &(md->real_variable(vvarname)), reg, mfl, l, w,
327  vvarname, mmultname, wname);
328  }
329 
330  size_type multi_contact_frame::add_slave_boundary
331  (const mesh_im &mim, size_type reg, const std::string &vvarname,
332  const std::string &mmultname, const std::string &wname) {
333  GMM_ASSERT1(md, "This multi contact frame object is not linked "
334  "to a model");
335  const mesh_fem *mfl(0);
336  const model_real_plain_vector *l(0);
337  if (mmultname.size()) {
338  mfl = &(md->mesh_fem_of_variable(mmultname));
339  l = &(md->real_variable(mmultname));
340  }
341  const model_real_plain_vector *w(0);
342  if (wname.compare(vvarname) == 0) {
343  GMM_ASSERT1(md->n_iter_of_variable(vvarname) > 1, "More than one "
344  "versions of the displacement variable were expected here");
345  w = &(md->real_variable(vvarname,1));
346  }
347  else if (wname.size()) {
348  GMM_ASSERT1(&(md->mesh_fem_of_variable(wname))
349  == &(md->mesh_fem_of_variable(vvarname)), "The previous "
350  "displacement should be defined on the same mesh_fem as the "
351  "current one");
352  w = &(md->real_variable(wname));
353  }
354  return add_slave_boundary(mim, &(md->mesh_fem_of_variable(vvarname)),
355  &(md->real_variable(vvarname)), reg, mfl, l, w,
356  vvarname, mmultname, wname);
357  }
358 
359 
360  void multi_contact_frame::compute_boundary_points(bool slave_only) {
361  fem_precomp_pool fppool;
362  base_matrix G;
363  model_real_plain_vector coeff;
364 
365  for (size_type i = 0; i < contact_boundaries.size(); ++i)
366  if (!slave_only || is_slave_boundary(i)) {
367  size_type bnum = region_of_boundary(i);
368  const mesh_fem &mfu = mfdisp_of_boundary(i);
369  const mesh_im &mim = mim_of_boundary(i);
370  const model_real_plain_vector &U = disp_of_boundary(i);
371  const mesh &m = mfu.linked_mesh();
372  bool on_fem_nodes =
373  boundary_has_fem_nodes(is_slave_boundary(i), nodes_mode);
374 
375  base_node val(N), bmin(N), bmax(N);
376  base_small_vector n0(N), n(N), n_mean(N);
377  base_matrix grad(N,N);
378  mesh_region region = m.region(bnum);
379  GMM_ASSERT1(mfu.get_qdim() == N, "Wrong mesh_fem qdim");
380 
381 
382  dal::bit_vector dof_already_interpolated;
383  std::vector<size_type> dof_ind(mfu.nb_basic_dof());
384  for (getfem::mr_visitor v(region,m); !v.finished(); ++v) {
385  size_type cv = v.cv();
386  bgeot::pgeometric_trans pgt = m.trans_of_convex(cv);
387  pfem pf_s = mfu.fem_of_element(cv);
388 
389  if (!ref_conf)
390  slice_vector_on_basic_dof_of_element(mfu, U, cv, coeff);
391  mfu.linked_mesh().points_of_convex(cv, G);
392 
393  pfem_precomp pfp(0);
394  size_type nbptf(0);
395  std::vector<size_type> indpt, indpfp;
396  if (on_fem_nodes) {
397  dim_type qqdim = mfu.get_qdim() / pf_s->target_dim();
398  pfp = fppool(pf_s, pf_s->node_tab(cv));
399  nbptf = pf_s->node_convex(cv).structure()->nb_points_of_face(v.f());
400  indpt.resize(nbptf); indpfp.resize(nbptf);
401  for (short_type ip = 0; ip < nbptf; ++ip) {
402  indpt[ip] =
403  mfu.ind_basic_dof_of_face_of_element(cv,v.f())[ip*qqdim];
404  indpfp[ip] =
405  pf_s->node_convex(cv).structure()->ind_points_of_face(v.f())[ip];
406  }
407  }
408  else {
409  pintegration_method pim = mim.int_method_of_element(cv);
410  GMM_ASSERT1(pim, "Integration method should be defined");
411  pfp = fppool(pf_s, pim->approx_method()->pintegration_points());
412  nbptf = pim->approx_method()->nb_points_on_face(v.f());
413  indpt.resize(nbptf); indpfp.resize(nbptf);
414  for (short_type ip = 0; ip < nbptf; ++ip)
415  indpt[ip] = indpfp[ip] =
416  pim->approx_method()->ind_first_point_on_face(v.f())+ip;
417  }
418  fem_interpolation_context ctx(pgt,pfp,size_type(-1),G,cv,v.f());
419 
420  for (short_type ip = 0; ip < nbptf; ++ip) {
421  ctx.set_ii(indpfp[ip]);
422 
423  size_type ind = indpt[ip];
424  if (!(on_fem_nodes && dof_already_interpolated[ind])) {
425  if (!ref_conf) {
426  pf_s->interpolation(ctx, coeff, val, dim_type(N));
427  val += ctx.xreal();
428  } else {
429  val = ctx.xreal();
430  }
431  if (on_fem_nodes) dof_ind[ind] = boundary_points.size();
432 
433  }
434 
435  // unit normal vector computation
436  compute_normal(ctx, v.f(), ref_conf, coeff, n0, n, grad);
437  n /= gmm::vect_norm2(n);
438 
439  if (on_fem_nodes && dof_already_interpolated[ind]) {
440  boundary_points_info[dof_ind[ind]].normals.add_normal(n);
441  } else {
442  boundary_points.push_back(val);
443  boundary_points_info.push_back(boundary_point(ctx.xreal(), i, cv,
444  v.f(), ind, n));
445  }
446 
447  if (on_fem_nodes) dof_already_interpolated.add(ind);
448  }
449  }
450  }
451  }
452 
453  void multi_contact_frame::compute_potential_contact_pairs_delaunay() {
454 
455  compute_boundary_points();
456  normal_cone_simplification();
457  potential_pairs = std::vector<std::vector<face_info> >();
458  potential_pairs.resize(boundary_points.size());
459 
460  gmm::dense_matrix<size_type> simplexes;
461  base_small_vector rr(N);
462  // Necessary ?
463  // for (size_type i = 0; i < boundary_points.size(); ++i) {
464  // gmm::fill_random(rr);
465  // boundary_points[i] += 1E-9*rr;
466  // }
467  bgeot::qhull_delaunay(boundary_points, simplexes);
468 
469  // connectivity analysis
470  for (size_type is = 0; is < gmm::mat_ncols(simplexes); ++is) {
471 
472  for (size_type i = 1; i <= N; ++i)
473  for (size_type j = 0; j < i; ++j) {
474  size_type ipt1 = simplexes(i, is), ipt2 = simplexes(j, is);
475  boundary_point *pt_info1 = &(boundary_points_info[ipt1]);
476  boundary_point *pt_info2 = &(boundary_points_info[ipt2]);
477  size_type ib1 = pt_info1->ind_boundary;
478  size_type ib2 = pt_info2->ind_boundary;
479  bool sl1 = is_slave_boundary(ib1);
480  bool sl2 = is_slave_boundary(ib2);
481  if (!sl1 && sl2) { // The slave in first if any
482  std::swap(ipt1, ipt2);
483  std::swap(pt_info1, pt_info2);
484  std::swap(ib1, ib2);
485  std::swap(sl1, sl2);
486  }
487  size_type ir1 = region_of_boundary(ib1);
488  size_type ir2 = region_of_boundary(ib2);
489  const mesh_fem &mf1 = mfdisp_of_boundary(ib1);
490  const mesh_fem &mf2 = mfdisp_of_boundary(ib2);
491 
492  // CRITERION 1 : The unit normal cone / vector are compatible
493  // and the two points are not in the same element.
494  if (
495  // slave-master case
496  ((sl1 && !sl2)
497  // master-master self-contact case
498  || (self_contact && !sl1 && !sl2))
499  // test of unit normal vectors or cones
500  && test_normal_cones_compatibility(pt_info1->normals,
501  pt_info2->normals)
502  // In case of self-contact, test if the two points share the
503  // same element.
504  && (sl1
505  || ((nodes_mode < 2)
506  && (( &(mf1.linked_mesh()) != &(mf2.linked_mesh()))
507  || (pt_info1->ind_element != pt_info2->ind_element)))
508  || ((nodes_mode == 2)
509  && !(are_dof_linked(ib1, pt_info1->ind_pt,
510  ib2, pt_info2->ind_pt)))
511  )
512  ) {
513 
514  // Store the potential contact pairs
515 
516  if (boundary_has_fem_nodes(sl2, nodes_mode)) {
517  const mesh::ind_cv_ct &ic2
518  = mf2.convex_to_basic_dof(pt_info2->ind_pt);
519  for (size_type k = 0; k < ic2.size(); ++k) {
520  mesh_region::face_bitset fbs
521  = mf2.linked_mesh().region(ir2).faces_of_convex(ic2[k]);
522  short_type nbf = mf2.linked_mesh().nb_faces_of_convex(ic2[k]);
523  for (short_type f = 0; f < nbf; ++f)
524  if (fbs.test(f))
525  add_potential_contact_face(ipt1,
526  pt_info2->ind_boundary,
527  ic2[k], f);
528  }
529  } else
530  add_potential_contact_face(ipt1, pt_info2->ind_boundary,
531  pt_info2->ind_element,
532  pt_info2->ind_face);
533 
534  if (self_contact && !sl1 && !sl2) {
535  if (boundary_has_fem_nodes(sl2, nodes_mode)) {
536  const mesh::ind_cv_ct &ic1
537  = mf1.convex_to_basic_dof(pt_info1->ind_pt);
538  for (size_type k = 0; k < ic1.size(); ++k) {
539  mesh_region::face_bitset fbs
540  = mf1.linked_mesh().region(ir1).faces_of_convex(ic1[k]);
541  short_type nbf = mf1.linked_mesh().nb_faces_of_convex(ic1[k]);
542  for (short_type f = 0; f < nbf; ++f)
543  if (fbs.test(f))
544  add_potential_contact_face(ipt2,
545  pt_info1->ind_boundary,
546  ic1[k], f);
547  }
548  } else
549  add_potential_contact_face(ipt2, pt_info1->ind_boundary,
550  pt_info1->ind_element,
551  pt_info1->ind_face);
552  }
553 
554  }
555 
556  }
557  }
558  }
559 
560 
561  void multi_contact_frame::compute_influence_boxes() {
562  fem_precomp_pool fppool;
563  bool avert = false;
564  base_matrix G;
565  model_real_plain_vector coeff;
566 
567  for (size_type i = 0; i < contact_boundaries.size(); ++i)
568  if (!is_slave_boundary(i)) {
569  size_type bnum = region_of_boundary(i);
570  const mesh_fem &mfu = mfdisp_of_boundary(i);
571  const model_real_plain_vector &U = disp_of_boundary(i);
572  const mesh &m = mfu.linked_mesh();
573 
574  base_node val(N), bmin(N), bmax(N);
575  base_small_vector n0(N), n(N), n_mean(N);
576  base_matrix grad(N,N);
577  mesh_region region = m.region(bnum);
578  GMM_ASSERT1(mfu.get_qdim() == N, "Wrong mesh_fem qdim");
579 
580  dal::bit_vector points_already_interpolated;
581  std::vector<base_node> transformed_points(m.nb_max_points());
582  for (getfem::mr_visitor v(region,m); !v.finished(); ++v) {
583  size_type cv = v.cv();
584  bgeot::pgeometric_trans pgt = m.trans_of_convex(cv);
585  pfem pf_s = mfu.fem_of_element(cv);
586  pfem_precomp pfp = fppool(pf_s, pgt->pgeometric_nodes());
587  if (!ref_conf)
588  slice_vector_on_basic_dof_of_element(mfu, U, cv, coeff);
589  mfu.linked_mesh().points_of_convex(cv, G);
590  fem_interpolation_context ctx(pgt,pfp,size_type(-1), G, cv);
591 
592  size_type nb_pt_on_face = 0;
593  dal::bit_vector points_on_face;
594  bgeot::pconvex_structure cvs = pgt->structure();
595  for (size_type k = 0; k < cvs->nb_points_of_face(v.f()); ++k)
596  points_on_face.add(cvs->ind_points_of_face(v.f())[k]);
597 
598  gmm::clear(n_mean);
599  size_type nbd_t = pgt->nb_points();
600  for (short_type ip = 0; ip < nbd_t; ++ip) {
601  size_type ind = m.ind_points_of_convex(cv)[ip];
602 
603  // computation of transformed vertex
604  ctx.set_ii(ip);
605  if (!(points_already_interpolated.is_in(ind))) {
606  if (!ref_conf) {
607  pf_s->interpolation(ctx, coeff, val, dim_type(N));
608  val += ctx.xreal();
609  transformed_points[ind] = val;
610  } else {
611  transformed_points[ind] = ctx.xreal();
612  }
613  points_already_interpolated.add(ind);
614  } else {
615  val = transformed_points[ind];
616  }
617  // computation of unit normal vector if the vertex is on the face
618  if (points_on_face[ip]) {
619  compute_normal(ctx, v.f(), ref_conf, coeff, n0, n, grad);
620  n /= gmm::vect_norm2(n);
621  n_mean += n;
622  ++nb_pt_on_face;
623  }
624 
625  if (ip == 0) // computation of bounding box
626  bmin = bmax = val;
627  else {
628  for (size_type k = 0; k < N; ++k) {
629  bmin[k] = std::min(bmin[k], val[k]);
630  bmax[k] = std::max(bmax[k], val[k]);
631  }
632  }
633 
634  }
635 
636  // is nb_pt_on_face really necessary, is this possible to occur?
637  GMM_ASSERT1(nb_pt_on_face,
638  "This element has no vertex on considered face !");
639 
640  // Computation of influence box :
641  // offset of the bounding box relatively to the release distance
642  scalar_type h = bmax[0] - bmin[0];
643  for (size_type k = 1; k < N; ++k) h = std::max(h, bmax[k]-bmin[k]);
644  if (h < release_distance/scalar_type(40) && !avert) {
645  GMM_WARNING1("Found an element whose size is smaller than 1/40 "
646  "of the release distance. You should probably "
647  "adapt the release distance.");
648  avert = true;
649  }
650  for (size_type k = 0; k < N; ++k)
651  { bmin[k] -= release_distance; bmax[k] += release_distance; }
652 
653  // Store the influence box and additional information.
654  element_boxes.add_box(bmin, bmax, element_boxes_info.size());
655  n_mean /= gmm::vect_norm2(n_mean);
656  element_boxes_info.push_back(influence_box(i, cv, v.f(), n_mean));
657  }
658  }
659  element_boxes.build_tree();
660  }
661 
662  void multi_contact_frame::compute_potential_contact_pairs_influence_boxes() {
663  compute_influence_boxes();
664  compute_boundary_points(!self_contact); // vraiment necessaire ?
665  normal_cone_simplification();
666  potential_pairs = std::vector<std::vector<face_info> >();
667  potential_pairs.resize(boundary_points.size());
668 
669  for (size_type ip = 0; ip < boundary_points.size(); ++ip) {
670 
671  bgeot::rtree::pbox_set bset;
672  element_boxes.find_boxes_at_point(boundary_points[ip], bset);
673  boundary_point *pt_info = &(boundary_points_info[ip]);
674  const mesh_fem &mf1 = mfdisp_of_boundary(pt_info->ind_boundary);
675  size_type ib1 = pt_info->ind_boundary;
676 
677  bgeot::rtree::pbox_set::iterator it = bset.begin();
678  for (; it != bset.end(); ++it) {
679  influence_box &ibx = element_boxes_info[(*it)->id];
680  size_type ib2 = ibx.ind_boundary;
681  const mesh_fem &mf2 = mfdisp_of_boundary(ib2);
682 
683  // CRITERION 1 : The unit normal cone / vector are compatible
684  // and the two points are not in the same element.
685  if (
686  test_normal_cones_compatibility(ibx.mean_normal,
687  pt_info->normals)
688  // In case of self-contact, test if the points and the face
689  // share the same element.
690  && (((nodes_mode < 2)
691  && (( &(mf1.linked_mesh()) != &(mf2.linked_mesh()))
692  || (pt_info->ind_element != ibx.ind_element)))
693  || ((nodes_mode == 2)
694  && !(is_dof_linked(ib1, pt_info->ind_pt,
695  ibx.ind_boundary, ibx.ind_element)))
696  )
697  ) {
698 
699  add_potential_contact_face(ip, ibx.ind_boundary, ibx.ind_element,
700  ibx.ind_face);
701  }
702  }
703 
704  }
705  }
706 
707  struct proj_pt_surf_cost_function_object {
708  size_type N;
709  scalar_type EPS;
710  const base_node &x0, &x;
711  fem_interpolation_context &ctx;
712  const model_real_plain_vector &coeff;
713  const std::vector<base_small_vector> &ti;
714  bool ref_conf;
715  mutable base_node dxy;
716  mutable base_matrix grad, gradtot;
717 
718  scalar_type operator()(const base_small_vector& a) const {
719  base_node xx = x0;
720  for (size_type i= 0; i < N-1; ++i) xx += a[i] * ti[i];
721  ctx.set_xref(xx);
722  if (!ref_conf) {
723  ctx.pf()->interpolation(ctx, coeff, dxy, dim_type(N));
724  dxy += ctx.xreal() - x;
725  } else
726  dxy = ctx.xreal() - x;
727  return gmm::vect_norm2(dxy)/scalar_type(2);
728  }
729 
730  scalar_type operator()(const base_small_vector& a,
731  base_small_vector &grada) const {
732  base_node xx = x0;
733  for (size_type i = 0; i < N-1; ++i) xx += a[i] * ti[i];
734  ctx.set_xref(xx);
735  // N x P, with P = N-1 for an element of a curve in 2D or a surface
736  // in 3D (a shell)
737  gmm::resize(gradtot, N, gmm::mat_ncols(ctx.K()));
738  if (!ref_conf) {
739  ctx.pf()->interpolation(ctx, coeff, dxy, dim_type(N));
740  dxy += ctx.xreal() - x;
741  ctx.pf()->interpolation_grad(ctx, coeff, grad, dim_type(N));
742  gmm::add(gmm::identity_matrix(), grad);
743  gmm::mult(grad, ctx.K(), gradtot);
744  } else {
745  dxy = ctx.xreal() - x;
746  gmm::copy(ctx.K(), gradtot);
747  }
748  for (size_type i = 0; i < N-1; ++i)
749  grada[i] = gmm::vect_sp(gradtot, ti[i], dxy);
750  return gmm::vect_norm2(dxy)/scalar_type(2);
751  }
752  void operator()(const base_small_vector& a,
753  base_matrix &hessa) const {
754  base_small_vector b = a;
755  base_small_vector grada(N-1), gradb(N-1);
756  (*this)(b, grada);
757  for (size_type i = 0; i < N-1; ++i) {
758  b[i] += EPS;
759  (*this)(b, gradb);
760  for (size_type j = 0; j < N-1; ++j)
761  hessa(j, i) = (gradb[j] - grada[j])/EPS;
762  b[i] -= EPS;
763  }
764  }
765 
766  proj_pt_surf_cost_function_object
767  (const base_node &x00, const base_node &xx,
768  fem_interpolation_context &ctxx,
769  const model_real_plain_vector &coefff,
770  const std::vector<base_small_vector> &tii,
771  scalar_type EPSS, bool rc)
772  : N(gmm::vect_size(xx)), EPS(EPSS), x0(x00), x(xx),
773  ctx(ctxx), coeff(coefff), ti(tii), ref_conf(rc),
774  dxy(N), grad(N,N), gradtot(N,N) {}
775 
776  };
777 
778  struct raytrace_pt_surf_cost_function_object {
779  size_type N;
780  const base_node &x0, &x;
781  fem_interpolation_context &ctx;
782  const model_real_plain_vector &coeff;
783  const std::vector<base_small_vector> &ti;
784  const std::vector<base_small_vector> &Ti;
785  bool ref_conf;
786  mutable base_node dxy;
787  mutable base_matrix grad, gradtot;
788 
789  void operator()(const base_small_vector& a,
790  base_small_vector &res) const {
791  base_node xx = x0;
792  for (size_type i = 0; i < N-1; ++i) xx += a[i] * ti[i];
793  ctx.set_xref(xx);
794  if (!ref_conf) {
795  ctx.pf()->interpolation(ctx, coeff, dxy, dim_type(N));
796  dxy += ctx.xreal() - x;
797  } else
798  dxy = ctx.xreal() - x;
799  for (size_type i = 0; i < N-1; ++i)
800  res[i] = gmm::vect_sp(dxy, Ti[i]);
801  }
802 
803  void operator()(const base_small_vector& a,
804  base_matrix &hessa) const {
805  base_node xx = x0;
806  for (size_type i = 0; i < N-1; ++i) xx += a[i] * ti[i];
807  ctx.set_xref(xx);
808  // N x P, with P = N-1 for an element of a curve in 2D or a surface
809  // in 3D (a shell)
810  gmm::resize(gradtot, N, gmm::mat_ncols(ctx.K()));
811  if (!ref_conf) {
812  ctx.pf()->interpolation_grad(ctx, coeff, grad, dim_type(N));
813  gmm::add(gmm::identity_matrix(), grad);
814  gmm::mult(grad, ctx.K(), gradtot);
815  } else {
816  gmm::copy(ctx.K(), gradtot);
817  }
818  for (size_type i = 0; i < N-1; ++i)
819  for (size_type j = 0; j < N-1; ++j)
820  hessa(j, i) = gmm::vect_sp(gradtot, ti[i], Ti[j]);
821  }
822 
823 
824  raytrace_pt_surf_cost_function_object
825  (const base_node &x00, const base_node &xx,
826  fem_interpolation_context &ctxx,
827  const model_real_plain_vector &coefff,
828  const std::vector<base_small_vector> &tii,
829  const std::vector<base_small_vector> &Tii,
830  bool rc)
831  : N(gmm::vect_size(xx)), x0(x00), x(xx),
832  ctx(ctxx), coeff(coefff), ti(tii), Ti(Tii), ref_conf(rc),
833  dxy(N), grad(N,N), gradtot(N,N) {}
834 
835  };
836 
837  // Ideas to improve efficiency :
838  // - From an iteration to another, is it possible to simplify the
839  // computation ? For instance in testing the old contact pairs ...
840  // But how to detect new contact situations ?
841  // - A pre-test before projection (for Delaunay) : if the distance to a
842  // node is greater than the release distance + h then give up.
843  // - Case J3 of valid/invalid contact situations is not really taken into
844  // account. How to take it into account in a cheap way ?
845 
846  void multi_contact_frame::compute_contact_pairs() {
847  base_matrix G, grad(N,N);
848  model_real_plain_vector coeff;
849  base_small_vector a(N-1), ny(N);
850  base_node y(N);
851  std::vector<base_small_vector> ti(N-1), Ti(N-1);
852  size_type nbwarn(0);
853 
854  // double time = dal::uclock_sec();
855 
856  clear_aux_info();
857  contact_pairs = std::vector<contact_pair>();
858 
859  if (!ref_conf) extend_vectors();
860 
861  bool only_slave(true), only_master(true);
862  for (size_type i = 0; i < contact_boundaries.size(); ++i)
863  if (is_slave_boundary(i)) only_master = false;
864  else only_slave = false;
865 
866  if (only_master && !self_contact) {
867  GMM_WARNING1("There is only master boundary and no self-contact to detect. Exiting");
868  return;
869  }
870 
871  if (only_slave) {
872  compute_boundary_points();
873  potential_pairs.resize(boundary_points.size());
874  }
875  else if (use_delaunay)
876  compute_potential_contact_pairs_delaunay();
877  else
878  compute_potential_contact_pairs_influence_boxes();
879 
880  // cout << "Time for computing potential pairs: " << dal::uclock_sec() - time << endl; time = dal::uclock_sec();
881 
882 
883  // Scan of potential pairs
884  for (size_type ip = 0; ip < potential_pairs.size(); ++ip) {
885  bool first_pair_found = false;
886  const base_node &x = boundary_points[ip];
887  boundary_point &bpinfo = boundary_points_info[ip];
888  size_type ibx = bpinfo.ind_boundary;
889  bool slx = is_slave_boundary(ibx);
890  scalar_type d0 = 1E300, d1, d2;
891 
892  base_small_vector nx = bpinfo.normals[0];
893  if (raytrace) {
894  if (bpinfo.normals.size() > 1) { // take the mean normal vector
895  for (size_type i = 1; i < bpinfo.normals.size(); ++i)
896  gmm::add(bpinfo.normals[i], nx);
897  scalar_type nnx = gmm::vect_norm2(nx);
898  GMM_ASSERT1(nnx != scalar_type(0), "Invalid normal cone");
899  gmm::scale(nx, scalar_type(1)/nnx);
900  }
901  }
902 
903  if (self_contact || slx) {
904  // Detect here the nearest rigid obstacle (taking into account
905  // the release distance)
906  size_type irigid_obstacle(-1);
907  gmm::copy(x, pt);
908  if (N >= 4) ptw[0] = pt[3];
909  if (N >= 3) ptz[0] = pt[2];
910  if (N >= 2) pty[0] = pt[1];
911  if (N >= 1) ptx[0] = pt[0];
912  for (size_type i = 0; i < obstacles.size(); ++i) {
913  d1 = (obstacles_f[i].eval())[0];
914  if (gmm::abs(d1) < release_distance && d1 < d0) {
915 
916  for (size_type j=0; j < bpinfo.normals.size(); ++j) {
917  gmm::add(gmm::scaled(bpinfo.normals[j], EPS), pt);
918  if (N >= 4) ptw[0] = pt[3];
919  if (N >= 3) ptz[0] = pt[2];
920  if (N >= 2) pty[0] = pt[1];
921  if (N >= 1) ptx[0] = pt[0];
922  d2 = (obstacles_f[i].eval())[0];
923  if (d2 < d1) { d0 = d1; irigid_obstacle = i; break; }
924  gmm::copy(x, pt);
925  if (N >= 4) ptw[0] = pt[3];
926  if (N >= 3) ptz[0] = pt[2];
927  if (N >= 2) pty[0] = pt[1];
928  if (N >= 1) ptx[0] = pt[0];
929  }
930  }
931  }
932 
933  if (irigid_obstacle != size_type(-1)) {
934 
935  gmm::copy(x, pt);
936  if (N >= 4) ptw[0] = pt[3];
937  if (N >= 3) ptz[0] = pt[2];
938  if (N >= 2) pty[0] = pt[1];
939  if (N >= 1) ptx[0] = pt[0];
940  gmm::copy(x, y);
941  size_type nit = 0, nb_fail = 0;
942  scalar_type alpha(0), beta(0);
943  d1 = d0;
944 
945  while (++nit < 50 && nb_fail < 3) {
946  for (size_type k = 0; k < N; ++k) {
947  pt[k] += EPS;
948  switch(N) {
949  case 4: ptw[0] += EPS; break;
950  case 3: ptz[0] += EPS; break;
951  case 2: pty[0] += EPS; break;
952  case 1: ptx[0] += EPS; break;
953  }
954  d2 = (obstacles_f[irigid_obstacle].eval())[0];
955  ny[k] = (d2 - d1) / EPS;
956  pt[k] -= EPS;
957  switch(N) {
958  case 4: ptw[0] -= EPS; break;
959  case 3: ptz[0] -= EPS; break;
960  case 2: pty[0] -= EPS; break;
961  case 1: ptx[0] -= EPS; break;
962  }
963  }
964 
965  if (gmm::abs(d1) < 1E-13)
966  break; // point already lies on the rigid obstacle surface
967 
968  // ajouter un test de divergence ...
969  for (scalar_type lambda(1); lambda >= 1E-3; lambda /= scalar_type(2)) {
970  if (raytrace) {
971  alpha = beta - lambda * d1 / gmm::vect_sp(ny, nx);
972  gmm::add(x, gmm::scaled(nx, alpha), pt);
973  } else {
974  gmm::add(gmm::scaled(ny, -d1/gmm::vect_norm2_sqr(ny)), y, pt);
975  }
976  if (N >= 4) ptw[0] = pt[3];
977  if (N >= 3) ptz[0] = pt[2];
978  if (N >= 2) pty[0] = pt[1];
979  if (N >= 1) ptx[0] = pt[0];
980  d2 = (obstacles_f[irigid_obstacle].eval())[0];
981 // if (nit > 10)
982 // cout << "nit = " << nit << " lambda = " << lambda
983 // << " alpha = " << alpha << " d2 = " << d2
984 // << " d1 = " << d1 << endl;
985  if (gmm::abs(d2) < gmm::abs(d1)) break;
986  }
987  if (raytrace &&
988  gmm::abs(beta - d1 / gmm::vect_sp(ny, nx)) > scalar_type(500))
989  nb_fail++;
990  gmm::copy(pt, y); beta = alpha; d1 = d2;
991  }
992 
993  if (gmm::abs(d1) > 1E-8) {
994  GMM_WARNING1("Projection/raytrace on rigid obstacle failed");
995  continue;
996  }
997 
998  // CRITERION 4 for rigid bodies : Apply the release distance
999  if (gmm::vect_dist2(y, x) > release_distance)
1000  continue;
1001 
1002  gmm::copy(pt, y);
1003  ny /= gmm::vect_norm2(ny);
1004 
1005  d0 = gmm::vect_dist2(y, x) * gmm::sgn(d0);
1006  contact_pair ct(x, nx, bpinfo, y, ny, irigid_obstacle, d0);
1007 
1008  contact_pairs.push_back(ct);
1009  first_pair_found = true;
1010  }
1011  }
1012 
1013  // if (potential_pairs[ip].size())
1014  // cout << "number of potential pairs for point " << ip << " : " << potential_pairs[ip].size() << endl;
1015  for (size_type ipf = 0; ipf < potential_pairs[ip].size(); ++ipf) {
1016  // Point to surface projection. Principle :
1017  // - One parametrizes first the face on the reference element by
1018  // obtaining a point x_0 on that face and t_i, i=1..d-1 some
1019  // orthonormals tangent vectors to the face.
1020  // - Let y_0 be the point to be projected and y the searched
1021  // projected point. Then one searches for the minimum of
1022  // J = (1/2)|| y - x ||
1023  // with
1024  // y = \phi(x0 + a_i t_i)
1025  // (with a summation on i), where \phi = I+u(\tau(x)), and \tau
1026  // the geometric transformation between reference and real
1027  // elements.
1028  // - The gradient of J with respect to a_i is
1029  // \partial_{a_j} J = (\phi(x0 + a_i t_i) - x)
1030  // . (\nabla \phi(x0 + a_i t_i) t_j
1031  // - A Newton algorithm is applied.
1032  // - If it fails, a BFGS is called.
1033 
1034  const face_info &fi = potential_pairs[ip][ipf];
1035  size_type ib = fi.ind_boundary;
1036  size_type cv = fi.ind_element;
1037  short_type iff = fi.ind_face;
1038 
1039  const mesh_fem &mfu = mfdisp_of_boundary(ib);
1040  const mesh &m = mfu.linked_mesh();
1041  pfem pf_s = mfu.fem_of_element(cv);
1042  bgeot::pgeometric_trans pgt = m.trans_of_convex(cv);
1043 
1044  if (!ref_conf)
1045  slice_vector_on_basic_dof_of_element(mfu, disp_of_boundary(ib),
1046  cv, coeff);
1047  m.points_of_convex(cv, G);
1048  // face_pts is of type bgeot::convex<...>::ref_convex_pt_ct
1049  const auto face_pts = pf_s->ref_convex(cv)->points_of_face(iff);
1050  // Newton start: the face centre, nearest to any hit inside the face
1051  const base_node x0 = gmm::mean_value(face_pts);
1052  fem_interpolation_context ctx(pgt, pf_s, x0, G, cv, iff);
1053 
1054  const base_small_vector &n0 = pf_s->ref_convex(cv)->normals()[iff];
1055  for (size_type k = 0; k < N-1; ++k) { // A basis for the face
1056  gmm::resize(ti[k], N);
1057  scalar_type norm(0);
1058  while(norm < 1E-5) {
1059  gmm::fill_random(ti[k]);
1060  ti[k] -= gmm::vect_sp(ti[k], n0) * n0;
1061  for (size_type l = 0; l < k; ++l)
1062  ti[k] -= gmm::vect_sp(ti[k], ti[l]) * ti[l];
1063  norm = gmm::vect_norm2(ti[k]);
1064  }
1065  ti[k] /= norm;
1066  }
1067 
1068  scalar_type h(0); // estimate of element face size
1069  for (size_type k = 0; k < N-1; ++k) {
1070  base_small_vector Kti(N);
1071  gmm::mult(ctx.K(), ti[k], Kti);
1072  h += gmm::vect_norm2_sqr(Kti);
1073  }
1074  h = gmm::sqrt(h / scalar_type(N-1));
1075 
1076  bool converged = false;
1077  scalar_type residual(0);
1078 
1079 
1080  if (raytrace) { // Raytrace search for y by a Newton algorithm
1081 
1082  base_small_vector res(N-1), res2(N-1), dir(N-1), b(N-1);
1083 
1084  base_matrix hessa(N-1, N-1);
1085  gmm::clear(a);
1086 
1087  for (size_type k = 0; k < N-1; ++k) {
1088  gmm::resize(Ti[k], N);
1089  scalar_type norm(0);
1090  while (norm < 1E-5) {
1091  gmm::fill_random(Ti[k]);
1092  Ti[k] -= gmm::vect_sp(Ti[k], nx) * nx;
1093  for (size_type l = 0; l < k; ++l)
1094  Ti[k] -= gmm::vect_sp(Ti[k], Ti[l]) * Ti[l];
1095  norm = gmm::vect_norm2(Ti[k]);
1096  }
1097  Ti[k] /= norm;
1098  }
1099 
1100  raytrace_pt_surf_cost_function_object pps(x0, x, ctx, coeff, ti, Ti,
1101  ref_conf);
1102 
1103  pps(a, res);
1104  residual = gmm::vect_norm2(res);
1105  scalar_type residual2(0), det(0);
1106  bool exited = false;
1107  size_type nbfail = 0, niter = 0;
1108  scalar_type eps_res = 2E-12*h,
1109  eps_det = 1E-15*pow(h, scalar_type(N-1));
1110  for (;residual > eps_res && niter <= 30; ++niter) {
1111 
1112  for (size_type subiter(0);;) {
1113  pps(a, hessa);
1114  det = gmm::abs(bgeot::lu_inverse(&(*(hessa.begin())),N-1, false));
1115  if (det > eps_det) break;
1116  for (size_type i = 0; i < N-1; ++i)
1117  a[i] += gmm::random() * 1E-7;
1118  if (++subiter > 4) break;
1119  }
1120  if (det <= eps_det) break;
1121  // Computation of the descent direction
1122  gmm::mult(hessa, gmm::scaled(res, scalar_type(-1)), dir);
1123 
1124  if (gmm::vect_norm2(dir) > scalar_type(10)) nbfail++;
1125  if (nbfail >= 4) break;
1126 
1127  // Line search
1128  scalar_type lambda(1);
1129  for (size_type j = 0; j < 5; ++j) {
1130  gmm::add(a, gmm::scaled(dir, lambda), b);
1131  pps(b, res2);
1132  residual2 = gmm::vect_norm2(res2);
1133  if (residual2 < residual) break;
1134  lambda /= ((j < 3) ? scalar_type(2) : scalar_type(5));
1135  }
1136 
1137  residual = residual2;
1138  gmm::copy(res2, res);
1139  gmm::copy(b, a);
1140  scalar_type dist_ref = gmm::vect_norm2(a);
1141 // if (niter == 15)
1142 // cout << "more than 15 iterations " << a
1143 // << " dir " << dir << " nbfail : " << nbfail << endl;
1144  if (niter > 1 && dist_ref > 15) break;
1145  if (niter > 5 && dist_ref > 8) break;
1146  if ((niter > 1 && dist_ref > 7) || nbfail == 3) exited = true;
1147  }
1148  converged = (gmm::vect_norm2(res) < 2E-6*h); // relaxed tolerance
1149  GMM_ASSERT1(!((exited && converged &&
1150  pf_s->ref_convex(cv)->is_in(ctx.xref()) < 1E-6)),
1151  "A non conformal case !! " << gmm::vect_norm2(res)
1152  << " : " << nbfail << " : " << niter);
1153 
1154  } else { // Classical projection for y
1155 
1156  proj_pt_surf_cost_function_object pps(x0, x, ctx, coeff, ti,
1157  EPS, ref_conf);
1158 
1159  // Projection could be ameliorated by finding a starting point near
1160  // x (with respect to the integration method, for instance).
1161 
1162  // A specific (Quasi) Newton algorithm for computing the projection
1163  base_small_vector grada(N-1), dir(N-1), b(N-1);
1164  gmm::clear(a);
1165  base_matrix hessa(N-1, N-1);
1166  scalar_type det(0);
1167 
1168  scalar_type dist = pps(a, grada);
1169  scalar_type eps_grad = 1E-12*h*h,
1170  eps_det = 1E-15*pow(h, scalar_type(2*N-2));
1171  for (size_type niter = 0;
1172  gmm::vect_norm2(grada) > eps_grad && niter <= 50; ++niter) {
1173 
1174  for (size_type subiter(0);;) {
1175  pps(a, hessa);
1176  det = gmm::abs(bgeot::lu_inverse(&(*(hessa.begin())),N-1, false));
1177  if (det > eps_det) break;
1178  for (size_type i = 0; i < N-1; ++i)
1179  a[i] += gmm::random() * 1E-7;
1180  if (++subiter > 4) break;
1181  }
1182  if (det <= eps_det) break;
1183  // Computation of the descent direction
1184  gmm::mult(hessa, gmm::scaled(grada, scalar_type(-1)), dir);
1185 
1186  // Line search
1187  for (scalar_type lambda(1);
1188  lambda >= 1E-3; lambda /= scalar_type(2)) {
1189  gmm::add(a, gmm::scaled(dir, lambda), b);
1190  if (pps(b) < dist) break;
1191  gmm::add(a, gmm::scaled(dir, -lambda), b);
1192  if (pps(b) < dist) break;
1193  }
1194  gmm::copy(b, a);
1195  dist = pps(a, grada);
1196  }
1197 
1198  converged = (gmm::vect_norm2(grada) < 2E-6*h*h); // relaxed tolerance
1199 
1200  if (!converged) { // Try with BFGS
1201  gmm::iteration iter(eps_grad, 0 /* noisy*/, 100 /*maxiter*/);
1202  gmm::clear(a);
1203  gmm::bfgs(pps, pps, a, 10, iter, 0, 0.5);
1204  residual = gmm::abs(iter.get_res());
1205  converged = (residual < 2E-5*h*h); // relaxed tolerance
1206  }
1207  }
1208 
1209  bool is_in = (pf_s->ref_convex(cv)->is_in(ctx.xref()) < 1E-6);
1210 
1211  if (is_in || (!converged && !raytrace)) {
1212  if (!ref_conf) {
1213  ctx.pf()->interpolation(ctx, coeff, y, dim_type(N));
1214  y += ctx.xreal();
1215  } else {
1216  y = ctx.xreal();
1217  }
1218  }
1219 
1220  // CRITERION 2 : The contact pair is eliminated when
1221  // projection/raytrace do not converge.
1222  if (!converged) {
1223  if (!raytrace && nbwarn < 4) {
1224  GMM_WARNING3("Projection or raytrace algorithm did not converge "
1225  "for point " << x << " residual " << residual
1226  << " projection computed " << y);
1227  ++nbwarn;
1228  }
1229  continue;
1230  }
1231 
1232  // CRITERION 3 : The projected point is inside the element
1233  // The test should be completed: If the point is outside
1234  // the element, a rapid reprojection on the face
1235  // (on the reference element, with a linear algorithm)
1236  // can be applied and a test with a neigbhour element
1237  // to decide if the point is in fact ok ...
1238  // (to be done only if there is no projection on other
1239  // element which coincides and with a test on the
1240  // distance ... ?) To be specified (in this case,
1241  // change xref).
1242  if (!is_in) continue;
1243 
1244  // CRITERION 4 : Apply the release distance
1245  scalar_type signed_dist = gmm::vect_dist2(y, x);
1246  if (signed_dist > release_distance) continue;
1247 
1248  // compute the unit normal vector at y and the signed distance.
1249  base_small_vector ny0(N);
1250  compute_normal(ctx, iff, ref_conf, coeff, ny0, ny, grad);
1251  // ny /= gmm::vect_norm2(ny); // Useful only if the unit normal is kept
1252  ny0 /= gmm::vect_norm2(ny0);
1253  signed_dist *= gmm::sgn(gmm::vect_sp(x - y, ny));
1254 
1255  // CRITERION 5 : comparison with rigid obstacles
1256  // CRITERION 7 : smallest signed distance on contact pairs
1257  if (first_pair_found && contact_pairs.back().signed_dist < signed_dist)
1258  continue;
1259 
1260  // CRITERION 1 : again on found unit normal vector
1261  if (!(test_normal_cones_compatibility(ny, bpinfo.normals)))
1262  continue;
1263 
1264  // CRITERION 6 : for self-contact only : apply a test on
1265  // unit normals in reference configuration.
1266  if (&m == &(mfdisp_of_boundary(ibx).linked_mesh())) {
1267 
1268  base_small_vector diff = bpinfo.ref_point - ctx.xreal();
1269  scalar_type ref_dist = gmm::vect_norm2(diff);
1270 
1271  if ( (ref_dist < scalar_type(4) * release_distance)
1272  && (gmm::vect_sp(diff, ny0) < - 0.01 * ref_dist) )
1273  continue;
1274  }
1275 
1276  contact_pair ct(x, nx, bpinfo, ctx.xref(), y, ny, fi, signed_dist);
1277  if (first_pair_found) {
1278  contact_pairs.back() = ct;
1279  } else {
1280  contact_pairs.push_back(ct);
1281  first_pair_found = true;
1282  }
1283 
1284  }
1285  }
1286 
1287  // cout << "Time for computing pairs: " << dal::uclock_sec() - time << endl; time = dal::uclock_sec();
1288 
1289  clear_aux_info();
1290  }
1291 
1292  //=========================================================================
1293  //
1294  // Raytracing interpolate transformation for generic assembly
1295  //
1296  //=========================================================================
1297 
1298  class raytracing_interpolate_transformation
1299  : public virtual_interpolate_transformation {
1300  protected:
1301  // Structure describing a contact boundary
1302  struct contact_boundary {
1303  size_type region; // Boundary number
1304  const getfem::mesh_fem *mfu; // F.e.m. for the displacement.
1305  std::string dispname; // Variable name for the displacement
1306  mutable const model_real_plain_vector *U; // Displacement
1307  mutable model_real_plain_vector U_unred; // Unreduced displacement
1308  bool slave;
1309 
1310  contact_boundary()
1311  : region(-1), mfu(0), dispname(""), U(0), U_unred(0), slave(false) {}
1312  contact_boundary(size_type r, const mesh_fem *mf, const std::string &dn,
1313  bool sl)
1314  : region(r), mfu(mf), dispname(dn), slave(sl) {}
1315  };
1316 
1317  struct face_box_info { // Additional information for a face box
1318  size_type ind_boundary; // Boundary number
1319  size_type ind_element; // Element number
1320  short_type ind_face; // Face number in element
1321  base_small_vector mean_normal; // Mean outward normal unit vector
1322  face_box_info()
1323  : ind_boundary(-1), ind_element(-1), ind_face(-1), mean_normal(0) {}
1324  face_box_info(size_type ib, size_type ie,
1325  short_type iff, const base_small_vector &n)
1326  : ind_boundary(ib), ind_element(ie), ind_face(iff), mean_normal(n) {}
1327  };
1328 
1329  scalar_type release_distance; // Limit distance beyond which the contact
1330  // will not be considered.
1331 
1332  std::vector<contact_boundary> contact_boundaries;
1333  typedef std::map<const mesh *, std::vector<size_type> > mesh_boundary_cor;
1334  mesh_boundary_cor boundary_for_mesh;
1335 
1336  class obstacle {
1337  const model *md;
1338  const ga_workspace *parent_workspace;
1339  std::string expr;
1340 
1341  mutable base_vector X;
1342  mutable ga_function f, der_f;
1343  mutable bool compiled;
1344 
1345  void compile() const {
1346  if (md)
1347  f = ga_function(*md, expr);
1348  else if (parent_workspace)
1349  f = ga_function(*parent_workspace, expr);
1350  else
1351  f = ga_function(expr);
1352  size_type N = gmm::vect_size(X);
1353  f.workspace().add_fixed_size_variable("X", gmm::sub_interval(0, N), X);
1354  if (N >= 1) f.workspace().add_macro("x", "X(1)");
1355  if (N >= 2) f.workspace().add_macro("y", "X(2)");
1356  if (N >= 3) f.workspace().add_macro("z", "X(3)");
1357  if (N >= 4) f.workspace().add_macro("w", "X(4)");
1358  f.compile();
1359  der_f = f;
1360  der_f.derivative("X");
1361  compiled = true;
1362  }
1363 
1364  public:
1365 
1366  base_vector &point() const { return X; }
1367 
1368  const base_tensor &eval() const {
1369  if (!compiled) compile();
1370  return f.eval();
1371  }
1372  const base_tensor &eval_derivative() const {
1373  if (!compiled) compile();
1374  return der_f.eval();
1375  }
1376 
1377  obstacle()
1378  : md(0), parent_workspace(0), expr(""), X(0), f(), der_f() {}
1379  obstacle(const model &md_, const std::string &expr_, size_type N)
1380  : md(&md_), parent_workspace(0), expr(expr_), X(N),
1381  f(), der_f(), compiled(false) {}
1382  obstacle(const ga_workspace &parent_workspace_,
1383  const std::string &expr_, size_type N)
1384  : md(0), parent_workspace(&parent_workspace_), expr(expr_), X(N),
1385  f(), der_f(), compiled(false) {}
1386  obstacle(const obstacle &obs)
1387  : md(obs.md), parent_workspace(obs.parent_workspace), expr(obs.expr),
1388  X(obs.X), f(), der_f(), compiled(false) {}
1389  obstacle &operator =(const obstacle& obs) {
1390  md = obs.md;
1391  parent_workspace = obs.parent_workspace;
1392  expr = obs.expr;
1393  X = obs.X;
1394  f = ga_function();
1395  der_f = ga_function();
1396  compiled = false;
1397  return *this;
1398  }
1399  ~obstacle() {}
1400  };
1401 
1402  std::vector<obstacle> obstacles;
1403 
1404  mutable bgeot::rtree face_boxes;
1405  mutable std::vector<face_box_info> face_boxes_info;
1406 
1407 
1408  void compute_face_boxes() const { // called by init
1409  fem_precomp_pool fppool;
1410  base_matrix G;
1411  model_real_plain_vector coeff;
1412  face_boxes.clear();
1413  face_boxes_info.resize(0);
1414 
1415  for (size_type i = 0; i < contact_boundaries.size(); ++i) {
1416  const contact_boundary &cb = contact_boundaries[i];
1417  if (! cb.slave) {
1418  size_type bnum = cb.region;
1419  const mesh_fem &mfu = *(cb.mfu);
1420  const model_real_plain_vector &U = *(cb.U);
1421  const mesh &m = mfu.linked_mesh();
1422  size_type N = m.dim();
1423 
1424  base_node val(N), bmin(N), bmax(N);
1425  base_small_vector n0_x(N), n_x(N), n0_y(N), n_y(N), n_mean(N);
1426  base_matrix grad(N,N);
1427  mesh_region region = m.region(bnum);
1428  GMM_ASSERT1(mfu.get_qdim() == N, "Wrong mesh_fem qdim");
1429 
1430  dal::bit_vector points_already_interpolated;
1431  std::vector<base_node> transformed_points(m.nb_max_points());
1432  for (getfem::mr_visitor v(region,m); !v.finished(); ++v) {
1433  size_type cv = v.cv();
1434  bgeot::pgeometric_trans pgt = m.trans_of_convex(cv);
1435  pfem pf_s = mfu.fem_of_element(cv);
1436  pfem_precomp pfp = fppool(pf_s, pgt->pgeometric_nodes());
1437  slice_vector_on_basic_dof_of_element(mfu, U, cv, coeff);
1438  mfu.linked_mesh().points_of_convex(cv, G);
1439  fem_interpolation_context ctx(pgt, pfp, size_type(-1), G, cv);
1440 
1441  bgeot::pconvex_structure cvs = pgt->structure();
1442  // v.f() == -1: an element of a curve in 2D or a surface in 3D
1443  // (a shell, two-sided)
1444  bool elt = (v.f() == short_type(-1));
1445  GMM_ASSERT1(!elt || (size_type(pgt->dim()+1) == N &&
1446  (N == 2 || N == 3)),
1447  "Contact boundaries are faces of elements, or "
1448  "elements of curves in 2D and surfaces in 3D");
1449  size_type nb_pt_on_face = elt ? cvs->nb_points()
1450  : cvs->nb_points_of_face(v.f());
1451  GMM_ASSERT1(nb_pt_on_face >= 2, "This element has less than two "
1452  "vertices on considered face !");
1453  gmm::clear(n_mean);
1454 
1455  for (size_type k = 0; k < nb_pt_on_face; ++k) {
1456  size_type ip = elt ? k : cvs->ind_points_of_face(v.f())[k];
1457  size_type ind = m.ind_points_of_convex(cv)[ip];
1458 
1459  // computation of transformed vertex
1460  ctx.set_ii(ip);
1461  if (!(points_already_interpolated.is_in(ind))) {
1462  pf_s->interpolation(ctx, coeff, val, dim_type(N));
1463  val += ctx.xreal();
1464  transformed_points[ind] = val;
1465  points_already_interpolated.add(ind);
1466  } else {
1467  val = transformed_points[ind];
1468  }
1469  // computation of unit normal vector if the vertex is on the face
1470  compute_normal(ctx, v.f(), false, coeff, n0_x, n_x, grad);
1471  n_x /= gmm::vect_norm2(n_x);
1472  n_mean += n_x;
1473 
1474  if (k == 0) // computation of bounding box
1475  bmin = bmax = val;
1476  else {
1477  for (size_type l = 0; l < N; ++l) {
1478  bmin[l] = std::min(bmin[l], val[l]);
1479  bmax[l] = std::max(bmax[l], val[l]);
1480  }
1481  }
1482  }
1483 
1484  // Security coefficient of 1.3 (for nonlinear transformations)
1485  scalar_type h = bmax[0] - bmin[0];
1486  for (size_type k = 1; k < N; ++k) h = std::max(h, bmax[k]-bmin[k]);
1487  for (size_type k = 0; k < N; ++k)
1488  { bmin[k] -= h * 0.15; bmax[k] += h * 0.15; }
1489 
1490  // Store the bounding box and additional information.
1491  face_boxes.add_box(bmin, bmax, face_boxes_info.size());
1492  n_mean /= gmm::vect_norm2(n_mean);
1493  face_boxes_info.push_back(face_box_info(i, cv, v.f(), n_mean));
1494  }
1495  }
1496  }
1497  face_boxes.build_tree();
1498  }
1499 
1500  public:
1501 
1502  void add_rigid_obstacle(const model &md, const std::string &expr,
1503  size_type N) {
1504  obstacles.push_back(obstacle(md, expr, N));
1505  }
1506 
1507  void add_rigid_obstacle(const ga_workspace &parent_workspace,
1508  const std::string &expr, size_type N) {
1509  obstacles.push_back(obstacle(parent_workspace, expr, N));
1510  }
1511 
1512  void add_contact_boundary(const model &md, const mesh &m,
1513  const std::string dispname,
1514  size_type region, bool slave) {
1515  const mesh_fem *mf = 0;
1516  if (md.variable_group_exists(dispname)) {
1517  for (const std::string &t : md.variable_group(dispname)) {
1518  const mesh_fem *mf2 = md.pmesh_fem_of_variable(t);
1519  if (mf2 && &(mf2->linked_mesh()) == &m)
1520  { mf = mf2; break; }
1521  }
1522  } else
1523  mf = md.pmesh_fem_of_variable(dispname);
1524 
1525  GMM_ASSERT1(mf, "Displacement should be a fem variable");
1526  contact_boundary cb(region, mf, dispname, slave);
1527  boundary_for_mesh[&(mf->linked_mesh())]
1528  .push_back(contact_boundaries.size());
1529  contact_boundaries.push_back(cb);
1530  }
1531 
1532  void add_contact_boundary(const ga_workspace &workspace, const mesh &m,
1533  const std::string dispname,
1534  size_type region, bool slave) {
1535  const mesh_fem *mf = 0;
1536  if (workspace.variable_group_exists(dispname)) {
1537  for (const std::string &t : workspace.variable_group(dispname)) {
1538  const mesh_fem *mf2 = workspace.associated_mf(t);
1539  if (mf2 && &(mf2->linked_mesh()) == &m)
1540  { mf = mf2; break; }
1541  }
1542  } else
1543  mf = workspace.associated_mf(dispname);
1544 
1545  GMM_ASSERT1(mf, "Displacement should be a fem variable");
1546  contact_boundary cb(region, mf, dispname, slave);
1547  boundary_for_mesh[&(mf->linked_mesh())]
1548  .push_back(contact_boundaries.size());
1549  contact_boundaries.push_back(cb);
1550  }
1551 
1552  void extract_variables(const ga_workspace &workspace,
1553  std::set<var_trans_pair> &vars,
1554  bool ignore_data, const mesh &m_x,
1555  const std::string &interpolate_name) const {
1556 
1557  bool expand_groups = !ignore_data;
1558  // const mesh_fem *mf = workspace.associated_mf(name);
1559  // GMM_ASSERT1(mf, "Internal error");
1560  // const mesh &m_x = mf->linked_mesh();
1561 
1562  mesh_boundary_cor::const_iterator it = boundary_for_mesh.find(&m_x);
1563  GMM_ASSERT1(it != boundary_for_mesh.end(), "Raytracing interpolate "
1564  "transformation: Mesh with no declared contact boundary");
1565  for (const size_type &boundary_ind : it->second) {
1566  const contact_boundary &cb = contact_boundaries[boundary_ind];
1567  const std::string &dispname_x
1568  = workspace.variable_in_group(cb.dispname, m_x);
1569  if (!ignore_data || !(workspace.is_constant(dispname_x)))
1570  vars.insert(var_trans_pair(dispname_x, ""));
1571  }
1572 
1573  for (const contact_boundary &cb : contact_boundaries) {
1574  if (!(cb.slave)) {
1575  if (expand_groups && workspace.variable_group_exists(cb.dispname)
1576  && (!ignore_data || !(workspace.is_constant(cb.dispname)))) {
1577  for (const std::string &t : workspace.variable_group(cb.dispname))
1578  vars.insert(var_trans_pair(t, interpolate_name));
1579  } else {
1580  if (!ignore_data || !(workspace.is_constant(cb.dispname)))
1581  vars.insert(var_trans_pair(cb.dispname, interpolate_name));
1582  }
1583  }
1584  }
1585  }
1586 
1587  void init(const ga_workspace &workspace) const {
1588  for (const contact_boundary &cb : contact_boundaries) {
1589  const mesh_fem &mfu = *(cb.mfu);
1590  const std::string dispname_x
1591  = workspace.variable_in_group(cb.dispname, mfu.linked_mesh());
1592 
1593  if (mfu.is_reduced()) {
1594  gmm::resize(cb.U_unred, mfu.nb_basic_dof());
1595  mfu.extend_vector(workspace.value(dispname_x), cb.U_unred);
1596  cb.U = &(cb.U_unred);
1597  } else {
1598  cb.U = &(workspace.value(dispname_x));
1599  }
1600  }
1601  compute_face_boxes();
1602  };
1603 
1604  void finalize() const {
1605  face_boxes.clear();
1606  face_boxes_info = std::vector<face_box_info>();
1607  for (const contact_boundary &cb : contact_boundaries)
1608  cb.U_unred = model_real_plain_vector();
1609  }
1610 
1611  int transform(const ga_workspace &workspace, const mesh &m_x,
1612  fem_interpolation_context &ctx_x,
1613  const base_small_vector &/*Normal*/,
1614  const mesh **m_t,
1615  size_type &cv, short_type &face_num, base_node &P_ref,
1616  base_small_vector &N_y,
1617  std::map<var_trans_pair, base_tensor> &derivatives,
1618  bool compute_derivatives) const {
1619  size_type cv_x = ctx_x.convex_num();
1620  short_type face_x = ctx_x.face_num();
1621  // face_x == -1: inside an element of a curve in 2D or a surface in 3D
1622  // (a shell), the ray along its deformed normal (oriented as Normal)
1623 
1624  //
1625  // Find the right (slave) contact boundary
1626  //
1627  mesh_boundary_cor::const_iterator it = boundary_for_mesh.find(&m_x);
1628  GMM_ASSERT1(it != boundary_for_mesh.end(),
1629  "Mesh with no declared contact boundary");
1630  size_type ib_x = size_type(-1);
1631  for (const size_type &boundary_ind : it->second) {
1632  const contact_boundary &cb = contact_boundaries[boundary_ind];
1633  if (m_x.region(cb.region).is_in(cv_x, face_x))
1634  { ib_x = boundary_ind; break; }
1635  }
1636  GMM_ASSERT1(ib_x != size_type(-1),
1637  "No contact region found for this point");
1638  const contact_boundary &cb_x = contact_boundaries[ib_x];
1639  const mesh_fem &mfu_x = *(cb_x.mfu);
1640  pfem pfu_x = mfu_x.fem_of_element(cv_x);
1641  size_type N = mfu_x.linked_mesh().dim();
1642  GMM_ASSERT1(mfu_x.get_qdim() == N,
1643  "Displacment field with wrong dimension");
1644 
1645  model_real_plain_vector coeff_x, coeff_y, stored_coeff_y;
1646  base_small_vector a(N-1), b(N-1), pt_x(N), pt_y(N), n_x(N);
1647  base_small_vector stored_pt_y(N), stored_n_y(N), stored_pt_y_ref(N);
1648  base_small_vector n0_x, n_y(N), n0_y, res(N-1), res2(N-1), dir(N-1);
1649  base_matrix G_x, G_y, grad(N,N), hessa(N-1, N-1);
1650  std::vector<base_small_vector> ti(N-1), Ti(N-1);
1651  scalar_type stored_signed_distance(0);
1652  std::string stored_dispname;
1653  scalar_type d0 = 1E300, d1, d2;
1654  const mesh *stored_m_y(0);
1655  size_type stored_cv_y(-1);
1656  short_type stored_face_y(-1);
1657  fem_interpolation_context stored_ctx_y;
1658 
1659  //
1660  // Computation of the deformed point and unit normal vectors
1661  //
1662  slice_vector_on_basic_dof_of_element(mfu_x, *(cb_x.U), cv_x, coeff_x);
1663  m_x.points_of_convex(cv_x, G_x);
1664  ctx_x.set_pf(pfu_x);
1665  pfu_x->interpolation(ctx_x, coeff_x, pt_x, dim_type(N));
1666  pt_x += ctx_x.xreal();
1667  compute_normal(ctx_x, face_x, false, coeff_x, n0_x, n_x, grad);
1668  n_x /= gmm::vect_norm2(n_x);
1669 
1670  //
1671  // Determine the nearest rigid obstacle, taking into account
1672  // the release distance.
1673  //
1674 
1675  bool first_pair_found = false;
1676  size_type irigid_obstacle(-1);
1677  for (size_type i = 0; i < obstacles.size(); ++i) {
1678  const obstacle &obs = obstacles[i];
1679  gmm::copy(pt_x, obs.point());
1680  const base_tensor &t = obs.eval();
1681 
1682  GMM_ASSERT1(t.size() == 1, "Obstacle level set function as to be "
1683  "a scalar valued one");
1684  d1 = t[0];
1685  // cout << "d1 = " << d1 << endl;
1686  if (gmm::abs(d1) < release_distance && d1 < d0) {
1687  const base_tensor &t_der = obs.eval_derivative();
1688  GMM_ASSERT1(t_der.size() == n_x.size(), "Bad derivative size");
1689  if (gmm::vect_sp(t_der.as_vector(), n_x) < scalar_type(0)) {
1690  d0 = d1;
1691  irigid_obstacle = i;
1692  gmm::copy(t_der.as_vector(), n_y);
1693  }
1694  }
1695  }
1696 
1697  if (irigid_obstacle != size_type(-1)) {
1698  // cout << "Testing obstacle " << irigid_obstacle << endl;
1699  const obstacle &obs = obstacles[irigid_obstacle];
1700  gmm::copy(pt_x, obs.point());
1701  gmm::copy(pt_x, pt_y);
1702  size_type nit = 0, nb_fail = 0;
1703  scalar_type alpha(0), beta(0);
1704  d1 = d0;
1705 
1706  while (gmm::abs(d1) > 1E-13 && ++nit < 50 && nb_fail < 3) {
1707  if (nit != 1) gmm::copy(obs.eval_derivative().as_vector(), n_y);
1708 
1709  for (scalar_type lambda(1); lambda >= 1E-3; lambda/=scalar_type(2)) {
1710  alpha = beta - lambda * d1 / gmm::vect_sp(n_y, n_x);
1711  gmm::add(pt_x, gmm::scaled(n_x, alpha), obs.point());
1712  d2 = obs.eval()[0];
1713  if (gmm::abs(d2) < gmm::abs(d1)) break;
1714  }
1715  if (gmm::abs(beta - d1 / gmm::vect_sp(n_y, n_x)) > scalar_type(500))
1716  nb_fail++;
1717  beta = alpha; d1 = d2;
1718  }
1719  gmm::copy(obs.point(), pt_y);
1720 
1721  if (gmm::abs(d1) > 1E-8) {
1722  GMM_WARNING1("Raytrace on rigid obstacle failed");
1723  } // CRITERION 4 for rigid bodies : Apply the release distance
1724  else if (gmm::vect_dist2(pt_y, pt_x) <= release_distance) {
1725  n_y /= gmm::vect_norm2(n_y);
1726  d0 = gmm::vect_dist2(pt_y, pt_x) * gmm::sgn(d0);
1727  stored_pt_y = stored_pt_y_ref = pt_y;
1728  stored_n_y = n_y;
1729  stored_signed_distance = d0;
1730  first_pair_found = true;
1731  } else
1732  irigid_obstacle = size_type(-1);
1733  }
1734 
1735  //
1736  // Determine the potential contact pairs with deformable bodies
1737  //
1738  bgeot::rtree::pbox_set bset;
1739  base_node bmin(pt_x), bmax(pt_x);
1740  for (size_type i = 0; i < N; ++i)
1741  { bmin[i] -= release_distance; bmax[i] += release_distance; }
1742 
1743  face_boxes.find_line_intersecting_boxes(pt_x, n_x, bmin, bmax, bset);
1744 
1745  //
1746  // Iteration on potential contact pairs and application
1747  // of selection criteria
1748  //
1749  for (const auto &pbox : bset) {
1750  face_box_info &fbox_y = face_boxes_info[pbox->id];
1751  size_type ib_y = fbox_y.ind_boundary;
1752  const contact_boundary &cb_y = contact_boundaries[ib_y];
1753  const mesh_fem &mfu_y = *(cb_y.mfu);
1754  const mesh &m_y = mfu_y.linked_mesh();
1755  size_type cv_y = fbox_y.ind_element;
1756  pfem pfu_y = mfu_y.fem_of_element(cv_y);
1757  short_type face_y = fbox_y.ind_face;
1758  bgeot::pgeometric_trans pgt_y= m_y.trans_of_convex(cv_y);
1759  // An element of a curve in 2D or a surface in 3D: a two-sided shell
1760  bool two_sided = (face_y == short_type(-1));
1761 
1762  // CRITERION 1 : The unit normal vector are compatible (not for
1763  // two-sided shells) and the two points are not in
1764  // the same element.
1765  if ((!two_sided &&
1766  gmm::vect_sp(fbox_y.mean_normal, n_x) >= scalar_type(0)) ||
1767  (cv_x == cv_y && &m_x == &m_y))
1768  continue;
1769 
1770  //
1771  // Raytrace search for y by Newton's algorithm
1772  //
1773 
1774  m_y.points_of_convex(cv_y, G_y);
1775  bgeot::pconvex_ref cvr_y = pfu_y->ref_convex(cv_y);
1776  // Newton start: the face centre, nearest to any hit inside the face
1777  // (the element centre for a shell)
1778  const base_node Y0 = two_sided
1779  ? gmm::mean_value(cvr_y->points())
1780  : gmm::mean_value(cvr_y->points_of_face(face_y));
1781  fem_interpolation_context ctx_y(pgt_y, pfu_y, Y0, G_y, cv_y, face_y);
1782 
1783  if (two_sided) { // the N-1 reference axes of the element
1784  for (size_type k = 0; k < N-1; ++k) {
1785  gmm::resize(ti[k], N-1); gmm::clear(ti[k]);
1786  ti[k][k] = scalar_type(1);
1787  }
1788  } else {
1789  const base_small_vector &NY0 = cvr_y->normals()[face_y];
1790  for (size_type k = 0; k < N-1; ++k) { // A basis for the face
1791  gmm::resize(ti[k], N);
1792  scalar_type norm(0);
1793  while(norm < 1E-5) {
1794  gmm::fill_random(ti[k]);
1795  ti[k] -= gmm::vect_sp(ti[k], NY0) * NY0;
1796  for (size_type l = 0; l < k; ++l)
1797  ti[k] -= gmm::vect_sp(ti[k], ti[l]) * ti[l];
1798  norm = gmm::vect_norm2(ti[k]);
1799  }
1800  ti[k] /= norm;
1801  }
1802  }
1803 
1804  scalar_type h(0); // estimate of element face size
1805  for (size_type k = 0; k < N-1; ++k) {
1806  base_small_vector Kti(N);
1807  gmm::mult(ctx_y.K(), ti[k], Kti);
1808  h += gmm::vect_norm2_sqr(Kti);
1809  }
1810  h = gmm::sqrt(h / scalar_type(N-1));
1811 
1812  gmm::clear(a);
1813 
1814  for (size_type k = 0; k < N-1; ++k) {
1815  gmm::resize(Ti[k], N);
1816  scalar_type norm(0);
1817  while (norm < 1E-5) {
1818  gmm::fill_random(Ti[k]);
1819  Ti[k] -= gmm::vect_sp(Ti[k], n_x) * n_x;
1820  for (size_type l = 0; l < k; ++l)
1821  Ti[k] -= gmm::vect_sp(Ti[k], Ti[l]) * Ti[l];
1822  norm = gmm::vect_norm2(Ti[k]);
1823  }
1824  Ti[k] /= norm;
1825  }
1826 
1827  slice_vector_on_basic_dof_of_element(mfu_y, *(cb_y.U), cv_y, coeff_y);
1828 
1829  raytrace_pt_surf_cost_function_object pps(Y0, pt_x, ctx_y, coeff_y,
1830  ti, Ti, false);
1831  pps(a, res);
1832  scalar_type residual = gmm::vect_norm2(res);
1833  scalar_type residual2(0), det(0);
1834  bool exited = false;
1835  size_type nbfail = 0, niter = 0;
1836  scalar_type eps_res = 2E-12*h,
1837  eps_det = 1E-15*pow(h, scalar_type(N-1));
1838  for (;residual > eps_res && niter <= 30; ++niter) {
1839 
1840  for (size_type subiter(0); subiter <= 4; ++subiter) {
1841  pps(a, hessa);
1842  det = gmm::abs(bgeot::lu_inverse(&(*(hessa.begin())), N-1, false));
1843  if (det > eps_det) break;
1844  for (size_type i = 0; i < N-1; ++i)
1845  a[i] += gmm::random() * 1E-7;
1846  }
1847  if (det <= eps_det) break;
1848  // Computation of the descent direction
1849  gmm::mult(hessa, gmm::scaled(res, scalar_type(-1)), dir);
1850 
1851  if (gmm::vect_norm2(dir) > scalar_type(10)) nbfail++;
1852  if (nbfail >= 4) break;
1853 
1854  // Line search
1855  scalar_type lambda(1);
1856  for (size_type j = 0; j < 5; ++j) {
1857  gmm::add(a, gmm::scaled(dir, lambda), b);
1858  pps(b, res2);
1859  residual2 = gmm::vect_norm2(res2);
1860  if (residual2 < residual) break;
1861  lambda /= ((j < 3) ? scalar_type(2) : scalar_type(5));
1862  }
1863 
1864  residual = residual2;
1865  gmm::copy(res2, res);
1866  gmm::copy(b, a);
1867  scalar_type dist_ref = gmm::vect_norm2(a);
1868 
1869  if (niter > 1 && dist_ref > 15) break;
1870  if (niter > 5 && dist_ref > 8) break;
1871  if (/*(niter > 1 && dist_ref > 7) ||*/ nbfail == 3) exited = true;
1872  }
1873  bool converged = (gmm::vect_norm2(res) < 2E-6*h); // relaxed tolerance
1874  bool is_in = (cvr_y->is_in(ctx_y.xref()) < 1E-6);
1875  // GMM_ASSERT1(!(exited && converged && is_in),
1876  // "A non conformal case !! " << gmm::vect_norm2(res)
1877  // << " : " << nbfail << " : " << niter);
1878  if (is_in) {
1879  ctx_y.pf()->interpolation(ctx_y, coeff_y, pt_y, dim_type(N));
1880  pt_y += ctx_y.xreal();
1881  }
1882 
1883  // CRITERION 2 : The contact pair is eliminated when
1884  // raytrace do not converge.
1885  if (!converged) continue;
1886 
1887  // CRITERION 3 : The raytraced point is inside the element
1888  if (!is_in) continue;
1889 
1890  // CRITERION 4 : Apply the release distance
1891  scalar_type signed_dist = gmm::vect_dist2(pt_y, pt_x);
1892  if (signed_dist > release_distance) continue;
1893 
1894  // compute the unit normal vector at y and the signed distance.
1895  compute_normal(ctx_y, face_y, false, coeff_y, n0_y, n_y, grad);
1896  n_y /= gmm::vect_norm2(n_y);
1897  n0_y /= gmm::vect_norm2(n0_y);
1898  // a two-sided shell faces the ray
1899  if (two_sided && gmm::vect_sp(n_y, n_x) > scalar_type(0))
1900  gmm::scale(n_y, scalar_type(-1));
1901  signed_dist *= gmm::sgn(gmm::vect_sp(pt_x - pt_y, n_y));
1902 
1903  // CRITERION 5 : comparison with rigid obstacles
1904  // CRITERION 7 : smallest signed distance on contact pairs
1905  if (first_pair_found && stored_signed_distance < signed_dist)
1906  continue;
1907 
1908  // CRITERION 1 : again on found unit normal vector
1909  if (gmm::vect_sp(n_y, n_x) >= scalar_type(0)) continue;
1910 
1911  // CRITERION 6 : for self-contact only : apply a test on
1912  // unit normals in reference configuration.
1913  if (&m_x == &m_y) {
1914  base_small_vector diff = ctx_x.xreal() - ctx_y.xreal();
1915  scalar_type ref_dist = gmm::vect_norm2(diff);
1916  if ( (ref_dist < scalar_type(4) * release_distance)
1917  && (gmm::vect_sp(diff, n0_y) < - 0.01 * ref_dist) )
1918  continue;
1919  }
1920 
1921  stored_pt_y = pt_y; stored_pt_y_ref = ctx_y.xref();
1922  stored_m_y = &m_y; stored_cv_y = cv_y; stored_face_y = face_y;
1923  stored_n_y = n_y;
1924  stored_ctx_y = ctx_y;
1925  stored_coeff_y = coeff_y;
1926  stored_signed_distance = signed_dist;
1927  stored_dispname = cb_y.dispname;
1928  first_pair_found = true;
1929  irigid_obstacle = size_type(-1);
1930  }
1931 
1932  int ret_type = 0;
1933  *m_t = 0;
1934  cv = size_type(-1);
1935  face_num = short_type(-1);
1936  if (irigid_obstacle != size_type(-1)) {
1937  P_ref = stored_pt_y; N_y = stored_n_y;
1938  ret_type = 2;
1939  } else if (first_pair_found) {
1940  *m_t = stored_m_y; cv = stored_cv_y; face_num = stored_face_y;
1941  P_ref = stored_pt_y_ref; N_y = stored_n_y;
1942  ret_type = 1;
1943  }
1944 
1945  // Note on derivatives of the transformation : for efficiency and
1946  // simplicity reasons, the derivative should be computed with
1947  // the value of corresponding test functions. This means that
1948  // for a transformation F(u) the conputed derivative is F'(u).Test_u
1949  // including the Test_u.
1950  if (compute_derivatives) {
1951  if (ret_type >= 1) {
1952  fem_interpolation_context &ctx_y = stored_ctx_y;
1953  size_type cv_y = 0;
1954  if (ret_type == 1) cv_y = ctx_y.convex_num();
1955 
1956  base_matrix I_nxny(N,N); // I - nx@ny/nx.ny
1957  gmm::copy(gmm::identity_matrix(), I_nxny);
1958  gmm::rank_one_update(I_nxny, n_x,
1959  gmm::scaled(stored_n_y,scalar_type(-1)
1960  / gmm::vect_sp(n_x, stored_n_y)));
1961 
1962  // Computation of F_y
1963  base_matrix F_y(N,N), F_y_inv(N,N), M1(N, N), M2(N, N);
1964  pfem pfu_y = 0;
1965  if (ret_type == 1) {
1966  pfu_y = ctx_y.pf();
1967  pfu_y->interpolation_grad(ctx_y, stored_coeff_y, F_y, dim_type(N));
1968  gmm::add(gmm::identity_matrix(), F_y);
1969  gmm::copy(F_y, F_y_inv);
1970  bgeot::lu_inverse(&(*(F_y_inv.begin())), N);
1971  } else {
1972  gmm::copy(gmm::identity_matrix(), F_y);
1973  gmm::copy(gmm::identity_matrix(), F_y_inv);
1974  }
1975 
1976  // Computation of F_x
1977  base_matrix F_x(N,N), F_x_inv(N,N);
1978  pfu_x->interpolation_grad(ctx_x, coeff_x, F_x, dim_type(N));
1979  gmm::add(gmm::identity_matrix(), F_x);
1980  gmm::copy(F_x, F_x_inv);
1981  bgeot::lu_inverse(&(*(F_x_inv.begin())), N);
1982 
1983 
1984  base_tensor base_ux;
1985  base_matrix vbase_ux;
1986  ctx_x.base_value(base_ux);
1987  size_type qdim_ux = pfu_x->target_dim();
1988  size_type ndof_ux = pfu_x->nb_dof(cv_x) * N / qdim_ux;
1989  vectorize_base_tensor(base_ux, vbase_ux, ndof_ux, qdim_ux, N);
1990 
1991  base_tensor base_uy;
1992  base_matrix vbase_uy;
1993  size_type ndof_uy = 0;
1994  if (ret_type == 1) {
1995  ctx_y.base_value(base_uy);
1996  size_type qdim_uy = pfu_y->target_dim();
1997  ndof_uy = pfu_y->nb_dof(cv_y) * N / qdim_uy;
1998  vectorize_base_tensor(base_uy, vbase_uy, ndof_uy, qdim_uy, N);
1999  }
2000 
2001  base_tensor grad_base_ux, vgrad_base_ux;
2002  ctx_x.grad_base_value(grad_base_ux);
2003  vectorize_grad_base_tensor(grad_base_ux, vgrad_base_ux, ndof_ux,
2004  qdim_ux, N);
2005 
2006  // Derivative : F_y^{-1}*I_nxny*(Test_u(X)-Test_u(Y)+gDn_x[Test_u])
2007  // with Dn_x[Test_u] =-(I-nx@nx)*F_x^{-T}*Grad_Test_u^{T}*n_x
2008  // and I_nxny*(I - nx@nx) = I_nxny
2009 
2010  // F_y^{-1}*I_nxny*Test_u(X)
2011  gmm::mult(F_y_inv, I_nxny, M1);
2012  base_matrix der_x(ndof_ux, N);
2013  gmm::mult(vbase_ux, gmm::transposed(M1), der_x);
2014 
2015  // -F_y^{-1}*I_nxny*Test_u(Y)
2016  base_matrix der_y(ndof_uy, N);
2017  if (ret_type == 1) {
2018  gmm::mult(vbase_uy, gmm::transposed(M1), der_y);
2019  gmm::scale(der_y, scalar_type(-1));
2020  }
2021 
2022  // F_y^{-1}*I_nxny*gDn_x[Test_u]
2023  gmm::mult(M1, gmm::transposed(F_x_inv), M2);
2024  for (size_type i = 0; i < ndof_ux; ++i)
2025  for (size_type j = 0; j < N; ++j)
2026  for (size_type k = 0; k < N; ++k)
2027  for (size_type l = 0; l < N; ++l)
2028  der_x(i, j) -= M2(j, k) * vgrad_base_ux(i, l, k)
2029  * n_x[l] * stored_signed_distance;
2030 
2031  const std::string &dispname_x
2032  = workspace.variable_in_group(cb_x.dispname, m_x);
2033 
2034  for (auto&& d : derivatives) {
2035  if (dispname_x.compare(d.first.varname) == 0 &&
2036  d.first.transname.size() == 0) {
2037  d.second.adjust_sizes(ndof_ux, N);
2038  gmm::copy(der_x.as_vector(), d.second.as_vector());
2039  } else if (ret_type == 1 &&
2040  stored_dispname.compare(d.first.varname) == 0 &&
2041  d.first.transname.size() != 0) {
2042  d.second.adjust_sizes(ndof_uy, N);
2043  gmm::copy(der_y.as_vector(), d.second.as_vector());
2044  } else
2045  d.second.adjust_sizes(0, 0);
2046  }
2047  } else {
2048  for (auto&& d : derivatives)
2049  d.second.adjust_sizes(0, 0);
2050  }
2051  }
2052  return ret_type;
2053  }
2054 
2055  raytracing_interpolate_transformation(scalar_type d)
2056  : release_distance(d) {}
2057  };
2058 
2059 
2060  //=========================================================================
2061  //
2062  // Projection interpolate transformation for generic assembly
2063  //
2064  //=========================================================================
2065 
2066  class projection_interpolate_transformation
2067  : public raytracing_interpolate_transformation {
2068 
2069  scalar_type release_distance; // Limit distance beyond which the contact
2070  // will not be considered.
2071  public:
2072  int transform(const ga_workspace &workspace, const mesh &m_x,
2073  fem_interpolation_context &ctx_x,
2074  const base_small_vector &/*Normal*/,
2075  const mesh **m_t,
2076  size_type &cv, short_type &face_num, base_node &P_ref,
2077  base_small_vector &N_y,
2078  std::map<var_trans_pair, base_tensor> &derivatives,
2079  bool compute_derivatives) const {
2080  size_type cv_x = ctx_x.convex_num();
2081  short_type face_x = ctx_x.face_num();
2082  // face_x == -1: inside an element of a curve in 2D or a surface in 3D
2083  // (a shell), n_x its deformed normal (oriented as Normal)
2084 
2085  //
2086  // Find the right (slave) contact boundary
2087  //
2088  mesh_boundary_cor::const_iterator it = boundary_for_mesh.find(&m_x);
2089  GMM_ASSERT1(it != boundary_for_mesh.end(),
2090  "Mesh with no declared contact boundary");
2091  size_type ib_x = size_type(-1);
2092  for (const auto &boundary_ind : it->second) {
2093  const contact_boundary &cb = contact_boundaries[boundary_ind];
2094  if (m_x.region(cb.region).is_in(cv_x, face_x))
2095  { ib_x = boundary_ind; break; }
2096  }
2097  GMM_ASSERT1(ib_x != size_type(-1),
2098  "No contact region found for this point");
2099  const contact_boundary &cb_x = contact_boundaries[ib_x];
2100  const mesh_fem &mfu_x = *(cb_x.mfu);
2101  pfem pfu_x = mfu_x.fem_of_element(cv_x);
2102  size_type N = mfu_x.linked_mesh().dim();
2103  GMM_ASSERT1(mfu_x.get_qdim() == N,
2104  "Displacment field with wrong dimension");
2105 
2106  model_real_plain_vector coeff_x, coeff_y, stored_coeff_y;
2107  base_small_vector a(N-1), b(N-1), pt_x(N), pt_y(N), n_x(N);
2108  base_small_vector stored_pt_y(N), stored_n_y(N), stored_pt_y_ref(N);
2109  base_small_vector n0_x, n_y(N), n0_y, res(N-1), res2(N-1), dir(N-1);
2110  base_matrix G_x, G_y, grad(N,N), hessa(N-1, N-1);
2111  std::vector<base_small_vector> ti(N-1);
2112  scalar_type stored_signed_distance(0);
2113  std::string stored_dispname;
2114  scalar_type d0 = 1E300, d1, d2(0);
2115  const mesh *stored_m_y(0);
2116  size_type stored_cv_y(-1);
2117  short_type stored_face_y(-1);
2118  fem_interpolation_context stored_ctx_y;
2119  size_type nbwarn(0);
2120 
2121 
2122  //
2123  // Computation of the deformed point and unit normal vectors
2124  //
2125  slice_vector_on_basic_dof_of_element(mfu_x, *(cb_x.U), cv_x, coeff_x);
2126  bgeot::vectors_to_base_matrix(G_x, m_x.points_of_convex(cv_x));
2127  ctx_x.set_pf(pfu_x);
2128  pfu_x->interpolation(ctx_x, coeff_x, pt_x, dim_type(N));
2129  pt_x += ctx_x.xreal();
2130  compute_normal(ctx_x, face_x, false, coeff_x, n0_x, n_x, grad);
2131  n_x /= gmm::vect_norm2(n_x);
2132 
2133  //
2134  // Determine the nearest rigid obstacle, taking into account
2135  // the release distance.
2136  //
2137 
2138  bool first_pair_found = false;
2139  size_type irigid_obstacle(-1);
2140  for (size_type i = 0; i < obstacles.size(); ++i) {
2141  const obstacle &obs = obstacles[i];
2142  gmm::copy(pt_x, obs.point());
2143  const base_tensor &t = obs.eval();
2144 
2145  GMM_ASSERT1(t.size() == 1, "Obstacle level set function as to be "
2146  "a scalar valued one");
2147  d1 = t[0];
2148  // cout << "d1 = " << d1 << endl;
2149  if (gmm::abs(d1) < release_distance && d1 < d0) {
2150  const base_tensor &t_der = obs.eval_derivative();
2151  GMM_ASSERT1(t_der.size() == n_x.size(), "Bad derivative size");
2152  if (gmm::vect_sp(t_der.as_vector(), n_x) < scalar_type(0))
2153  { d0 = d1; irigid_obstacle = i; gmm::copy(t_der.as_vector(),n_y); }
2154  }
2155  }
2156 
2157  if (irigid_obstacle != size_type(-1)) {
2158  // cout << "Testing obstacle " << irigid_obstacle << endl;
2159  const obstacle &obs = obstacles[irigid_obstacle];
2160  gmm::copy(pt_x, obs.point());
2161  gmm::copy(pt_x, pt_y);
2162  size_type nit = 0;
2163  d1 = d0;
2164 
2165  while (gmm::abs(d1) > 1E-13 && ++nit < 50) {
2166  if (nit != 1) gmm::copy(obs.eval_derivative().as_vector(), n_y);
2167 
2168  for (scalar_type lambda(1); lambda >= 1E-3; lambda/=scalar_type(2)) {
2169  gmm::add(pt_y, gmm::scaled(n_y, -lambda*d1/gmm::vect_norm2_sqr(n_y)),
2170  obs.point());
2171  d2 = obs.eval()[0];
2172  if (gmm::abs(d2) < gmm::abs(d1)) break;
2173  }
2174  gmm::copy(obs.point(), pt_y);
2175  d1 = d2;
2176  }
2177 
2178  if (gmm::abs(d1) > 1E-8) {
2179  GMM_WARNING1("Raytrace on rigid obstacle failed");
2180  } // CRITERION 4 for rigid bodies : Apply the release distance
2181  else if (gmm::vect_dist2(pt_y, pt_x) <= release_distance) {
2182  n_y /= gmm::vect_norm2(n_y);
2183  d0 = gmm::vect_dist2(pt_y, pt_x) * gmm::sgn(d0);
2184  stored_pt_y = stored_pt_y_ref = pt_y; stored_n_y = n_y,
2185  stored_signed_distance = d0;
2186  first_pair_found = true;
2187  } else
2188  irigid_obstacle = size_type(-1);
2189  }
2190 
2191  //
2192  // Determine the potential contact pairs with deformable bodies
2193  //
2194  bgeot::rtree::pbox_set bset;
2195  base_node bmin(pt_x), bmax(pt_x);
2196  for (size_type i = 0; i < N; ++i)
2197  { bmin[i] -= release_distance; bmax[i] += release_distance; }
2198 
2199  face_boxes.find_line_intersecting_boxes(pt_x, n_x, bmin, bmax, bset);
2200  //
2201  // Iteration on potential contact pairs and application
2202  // of selection criteria
2203  //
2204  for (const auto &pbox : bset) {
2205  face_box_info &fbox_y = face_boxes_info[pbox->id];
2206  size_type ib_y = fbox_y.ind_boundary;
2207  const contact_boundary &cb_y = contact_boundaries[ib_y];
2208  const mesh_fem &mfu_y = *(cb_y.mfu);
2209  const mesh &m_y = mfu_y.linked_mesh();
2210  bool ref_conf=false;
2211  size_type cv_y = fbox_y.ind_element;
2212  pfem pfu_y = mfu_y.fem_of_element(cv_y);
2213  short_type face_y = fbox_y.ind_face;
2214  bgeot::pgeometric_trans pgt_y= m_y.trans_of_convex(cv_y);
2215  // An element of a curve in 2D or a surface in 3D: a two-sided shell
2216  bool two_sided = (face_y == short_type(-1));
2217 
2218  // CRITERION 1 : The unit normal vectors are compatible (not for
2219  // two-sided shells) and the two points are not in
2220  // the same element.
2221  if ((!two_sided &&
2222  gmm::vect_sp(fbox_y.mean_normal, n_x) >= scalar_type(0)) ||
2223  (cv_x == cv_y && &m_x == &m_y))
2224  continue;
2225 
2226  //
2227  // Classical projection for y by quasi Newton algorithm
2228  //
2229  bgeot::vectors_to_base_matrix(G_y, m_y.points_of_convex(cv_y));
2230  bgeot::pconvex_ref cvr_y = pfu_y->ref_convex(cv_y);
2231  // Newton start: the face centre, nearest to any hit inside the face
2232  // (the element centre for a shell)
2233  const base_node Y0 = two_sided
2234  ? gmm::mean_value(cvr_y->points())
2235  : gmm::mean_value(cvr_y->points_of_face(face_y));
2236  fem_interpolation_context ctx_y(pgt_y, pfu_y, Y0, G_y, cv_y, face_y);
2237 
2238  gmm::clear(a);
2239 
2240  if (two_sided) { // the N-1 reference axes of the element
2241  for (size_type k = 0; k < N-1; ++k) {
2242  gmm::resize(ti[k], N-1); gmm::clear(ti[k]);
2243  ti[k][k] = scalar_type(1);
2244  }
2245  } else {
2246  const base_small_vector &NY0 = cvr_y->normals()[face_y];
2247  for (size_type k = 0; k < N-1; ++k) { // A basis for the face
2248  gmm::resize(ti[k], N);
2249  scalar_type norm(0);
2250  while(norm < 1E-5) {
2251  gmm::fill_random(ti[k]);
2252  ti[k] -= gmm::vect_sp(ti[k], NY0) * NY0;
2253  for (size_type l = 0; l < k; ++l)
2254  ti[k] -= gmm::vect_sp(ti[k], ti[l]) * ti[l];
2255  norm = gmm::vect_norm2(ti[k]);
2256  }
2257  ti[k] /= norm;
2258  }
2259  }
2260 
2261  scalar_type h(0); // estimate of element face size
2262  for (size_type k = 0; k < N-1; ++k) {
2263  base_small_vector Kti(N);
2264  gmm::mult(ctx_y.K(), ti[k], Kti);
2265  h += gmm::vect_norm2_sqr(Kti);
2266  }
2267  h = gmm::sqrt(h / scalar_type(N-1));
2268 
2269  slice_vector_on_basic_dof_of_element(mfu_y, *(cb_y.U), cv_y, coeff_y);
2270  proj_pt_surf_cost_function_object pps(Y0, pt_x, ctx_y, coeff_y, ti,
2271  1E-10, ref_conf);
2272  base_small_vector grada(N-1);
2273  scalar_type det(0);
2274  scalar_type residual = gmm::vect_norm2(res);
2275  scalar_type dist = pps(a, grada);
2276  pps(a, res);
2277  scalar_type eps_grad = 1E-7*h*h,
2278  eps_det = 1E-15*pow(h, scalar_type(2*N-2));
2279  for (size_type niter = 0;
2280  gmm::vect_norm2(grada) > eps_grad && niter <= 50; ++niter) {
2281 
2282  for (size_type subiter(0);;) {
2283  pps(a, hessa);
2284  det = gmm::abs(gmm::lu_inverse(hessa, false));
2285  if (det > eps_det) break;
2286  for (size_type i = 0; i < N-1; ++i)
2287  a[i] += gmm::random() * 1E-7;
2288  if (++subiter > 4) break;
2289  }
2290  if (det <= eps_det) break;
2291  // Computation of the descent direction
2292  gmm::mult(hessa, gmm::scaled(grada, scalar_type(-1)), dir);
2293 
2294  // Line search
2295  for (scalar_type lambda(1);
2296  lambda >= 1E-3; lambda /= scalar_type(2)) {
2297  gmm::add(a, gmm::scaled(dir, lambda), b);
2298  if (pps(b) < dist) break;
2299  gmm::add(a, gmm::scaled(dir, -lambda), b);
2300  if (pps(b) < dist) break;
2301  }
2302  //cout<< "b =" << b <<endl;
2303  gmm::copy(b, a);
2304  dist = pps(a, grada);
2305  }
2306 
2307  bool converged = (gmm::vect_norm2(grada) < 2E-6*h*h); // relaxed tolerance
2308  if (!converged) { // Try with BFGS
2309  gmm::iteration iter(1E-10*h*h, 0 /* noisy*/, 100 /*maxiter*/);
2310  gmm::clear(a);
2311  gmm::bfgs(pps, pps, a, 10, iter, 0, 0.5);
2312  residual = gmm::abs(iter.get_res());
2313  converged = (residual < 2E-5*h*h); // relaxed tolerance
2314  }
2315 
2316  bool is_in = (cvr_y->is_in(ctx_y.xref()) < 1E-6);
2317 
2318  // cout<< "y_ref =" << ctx_y.xref() <<endl;
2319  // cout<< "x_ref =" << ctx_x.xref() <<endl;
2320  // cout<< "y =" << ctx_y.xreal() <<endl;
2321  // cout<< "x =" << ctx_x.xreal() <<endl;
2322  // cout<< "is_in =" << is_in <<endl;
2323 
2324  if (is_in || (!converged )) {
2325  if (!ref_conf) {
2326  ctx_y.pf()->interpolation(ctx_y, coeff_y, pt_y, dim_type(N));
2327  pt_y += ctx_y.xreal();
2328  } else {
2329  pt_y = ctx_y.xreal();
2330  }
2331  }
2332  // CRITERION 2 : The contact pair is eliminated when
2333  // projection/raytrace do not converge.
2334  if (!converged) {
2335  if ( nbwarn < 4) {
2336  GMM_WARNING3("Projection algorithm did not converge "
2337  "for point " << pt_x << " residual " << residual
2338  << " projection computed " << pt_y);
2339  ++nbwarn;
2340  }
2341  continue;
2342  }
2343 
2344  // CRITERION 3 : The projected point is inside the element
2345  // The test should be completed: If the point is outside
2346  // the element, a rapid reprojection on the face
2347  // (on the reference element, with a linear algorithm)
2348  // can be applied and a test with a neigbhour element
2349  // to decide if the point is in fact ok ...
2350  // (to be done only if there is no projection on other
2351  // element which coincides and with a test on the
2352  // distance ... ?) To be specified (in this case,
2353  // change xref).
2354  if (!is_in) continue;
2355 
2356  // CRITERION 4 : Apply the release distance
2357 
2358  scalar_type signed_dist = gmm::vect_dist2(pt_y, pt_x);
2359  //cout<< "signd_dist="<< signed_dist << "relaese_dist="<< release_distance <<endl;
2360  if (signed_dist > release_distance) continue;
2361 
2362  // compute the unit normal vector at y and the signed distance.
2363  base_small_vector ny0(N);
2364  compute_normal(ctx_y, face_y, ref_conf, coeff_y, ny0, n_y, grad);
2365  n_y /= gmm::vect_norm2(n_y);
2366  ny0 /= gmm::vect_norm2(ny0);
2367  // a two-sided shell faces the slave point
2368  if (two_sided && gmm::vect_sp(n_y, n_x) > scalar_type(0))
2369  gmm::scale(n_y, scalar_type(-1));
2370  signed_dist *= gmm::sgn(gmm::vect_sp(pt_x - pt_y, n_y));
2371 
2372  // CRITERION 5 : comparison with rigid obstacles
2373  // CRITERION 7 : smallest signed distance on contact pairs
2374  if (first_pair_found && stored_signed_distance < signed_dist)
2375  continue;
2376 
2377  // CRITERION 1 : again on found unit normal vector
2378  if (gmm::vect_sp(n_y, n_x) >= scalar_type(0)) continue;
2379 
2380  // CRITERION 6 : for self-contact only : apply a test on
2381  // unit normals in reference configuration.
2382  if (&m_x == &m_y) {
2383 
2384  base_small_vector diff = ctx_x.xreal() - ctx_y.xreal();
2385  scalar_type ref_dist = gmm::vect_norm2(diff);
2386 
2387  if ( (ref_dist < scalar_type(4) * release_distance)
2388  && (gmm::vect_sp(diff, ny0) < - 0.01 * ref_dist) )
2389  continue;
2390  }
2391 
2392  stored_pt_y = pt_y; stored_pt_y_ref = ctx_y.xref();
2393  stored_m_y = &m_y; stored_cv_y = cv_y; stored_face_y = face_y;
2394  stored_n_y = n_y;
2395  stored_ctx_y = ctx_y;
2396  stored_coeff_y = coeff_y;
2397  stored_signed_distance = signed_dist;
2398  stored_dispname = cb_y.dispname;
2399  first_pair_found = true;
2400  irigid_obstacle = size_type(-1);
2401 
2402  // Projection could be ameliorated by finding a starting point near
2403  // x (with respect to the integration method, for instance).
2404 
2405  // A specific (Quasi) Newton algorithm for computing the projection
2406  }
2407 
2408  int ret_type = 0;
2409  *m_t = 0; cv = size_type(-1); face_num = short_type(-1);
2410  if (irigid_obstacle != size_type(-1)) {
2411  P_ref = stored_pt_y; N_y = stored_n_y;
2412  ret_type = 2;
2413  } else if (first_pair_found) {
2414  *m_t = stored_m_y; cv = stored_cv_y; face_num = stored_face_y;
2415  P_ref = stored_pt_y_ref;
2416  ret_type = 1;
2417  }
2418  // Note on derivatives of the transformation : for efficiency and
2419  // simplicity reasons, the derivative should be computed with
2420  // the value of corresponding test functions. This means that
2421  // for a transformation F(u) the conputed derivative is F'(u).Test_u
2422  // including the Test_u.
2423 
2424  if (compute_derivatives) {
2425  if (ret_type >= 1) {
2426  fem_interpolation_context &ctx_y = stored_ctx_y;
2427  size_type cv_y = 0;
2428  if (ret_type == 1) cv_y = ctx_y.convex_num();
2429 
2430 
2431  base_matrix I_nyny(N,N); // I - ny@ny
2432  gmm::copy(gmm::identity_matrix(), I_nyny);
2433  gmm::rank_one_update(I_nyny, stored_n_y,
2434  gmm::scaled(stored_n_y,scalar_type(-1)));
2435 
2436  // Computation of F_y
2437  base_matrix F_y(N,N), F_y_inv(N,N), M1(N, N), M2(N, N);
2438  pfem pfu_y = 0;
2439  if (ret_type == 1) {
2440  pfu_y = ctx_y.pf();
2441  pfu_y->interpolation_grad(ctx_y, stored_coeff_y, F_y, dim_type(N));
2442  gmm::add(gmm::identity_matrix(), F_y);
2443  gmm::copy(F_y, F_y_inv);
2444  gmm::lu_inverse(F_y_inv);
2445  } else {
2446  gmm::copy(gmm::identity_matrix(), F_y);
2447  gmm::copy(gmm::identity_matrix(), F_y_inv);
2448  }
2449 
2450 
2451  base_tensor base_ux;
2452  base_matrix vbase_ux;
2453  ctx_x.base_value(base_ux);
2454  size_type qdim_ux = pfu_x->target_dim();
2455  size_type ndof_ux = pfu_x->nb_dof(cv_x) * N / qdim_ux;
2456  vectorize_base_tensor(base_ux, vbase_ux, ndof_ux, qdim_ux, N);
2457 
2458  base_tensor base_uy;
2459  base_matrix vbase_uy;
2460  size_type ndof_uy = 0;
2461  if (ret_type == 1) {
2462  ctx_y.base_value(base_uy);
2463  size_type qdim_uy = pfu_y->target_dim();
2464  ndof_uy = pfu_y->nb_dof(cv_y) * N / qdim_uy;
2465  vectorize_base_tensor(base_uy, vbase_uy, ndof_uy, qdim_uy, N);
2466  }
2467 
2468  base_tensor grad_base_ux, vgrad_base_ux;
2469  ctx_x.grad_base_value(grad_base_ux);
2470  vectorize_grad_base_tensor(grad_base_ux, vgrad_base_ux, ndof_ux,
2471  qdim_ux, N);
2472 
2473  // Derivative : F_y^{-1}*I_nyny*(Test_u(X)-Test_u(Y))
2474  // and I_nyny*(I - ny@ny) = I_nyny
2475 
2476  // F_y^{-1}*I_nyny*Test_u(X)
2477  gmm::mult(F_y_inv, I_nyny, M1);
2478  base_matrix der_x(ndof_ux, N);
2479  gmm::mult(vbase_ux, gmm::transposed(M1), der_x);
2480 
2481  // -F_y^{-1}*I_nyny*Test_u(Y)
2482  base_matrix der_y(ndof_uy, N);
2483  if (ret_type == 1) {
2484  gmm::mult(vbase_uy, gmm::transposed(M1), der_y);
2485  gmm::scale(der_y, scalar_type(-1));
2486  }
2487 
2488  const std::string &dispname_x
2489  = workspace.variable_in_group(cb_x.dispname, m_x);
2490 
2491  for (auto&& d : derivatives) {
2492  if (dispname_x.compare(d.first.varname) == 0 &&
2493  d.first.transname.size() == 0) {
2494  d.second.adjust_sizes(ndof_ux, N);
2495  gmm::copy(der_x.as_vector(), d.second.as_vector());
2496  } else if (ret_type == 1 &&
2497  stored_dispname.compare(d.first.varname) == 0 &&
2498  d.first.transname.size() != 0) {
2499  d.second.adjust_sizes(ndof_uy, N);
2500  gmm::copy(der_y.as_vector(), d.second.as_vector());
2501  } else
2502  d.second.adjust_sizes(0, 0);
2503  }
2504  } else {
2505  for (auto&& d : derivatives)
2506  d.second.adjust_sizes(0, 0);
2507  }
2508  }
2509  return ret_type;
2510  }
2511  projection_interpolate_transformation(const scalar_type &d)
2512  :raytracing_interpolate_transformation(d), release_distance(d) {}
2513  };
2515  (model &md, const std::string &transname, scalar_type d) {
2516  pinterpolate_transformation
2517  p = std::make_shared<raytracing_interpolate_transformation>(d);
2518  md.add_interpolate_transformation(transname, p);
2519  }
2520 
2522  (ga_workspace &workspace, const std::string &transname, scalar_type d) {
2523  pinterpolate_transformation
2524  p = std::make_shared<raytracing_interpolate_transformation>(d);
2525  workspace.add_interpolate_transformation(transname, p);
2526  }
2527 
2529  (model &md, const std::string &transname, const mesh &m,
2530  const std::string &dispname, size_type region) {
2531  raytracing_interpolate_transformation *p
2532  = dynamic_cast<raytracing_interpolate_transformation *>
2533  (const_cast<virtual_interpolate_transformation *>
2534  (&(*(md.interpolate_transformation(transname)))));
2535  p->add_contact_boundary(md, m, dispname, region, false);
2536  }
2537 
2539  (model &md, const std::string &transname, const mesh &m,
2540  const std::string &dispname, size_type region) {
2541  raytracing_interpolate_transformation *p
2542  = dynamic_cast<raytracing_interpolate_transformation *>
2543  (const_cast<virtual_interpolate_transformation *>
2544  (&(*(md.interpolate_transformation(transname)))));
2545  p->add_contact_boundary(md, m, dispname, region, true);
2546  }
2547 
2549  (ga_workspace &workspace, const std::string &transname, const mesh &m,
2550  const std::string &dispname, size_type region) {
2551  raytracing_interpolate_transformation *p
2552  = dynamic_cast<raytracing_interpolate_transformation *>
2553  (const_cast<virtual_interpolate_transformation *>
2554  (&(*(workspace.interpolate_transformation(transname)))));
2555  p->add_contact_boundary(workspace, m, dispname, region, false);
2556  }
2557 
2559  (ga_workspace &workspace, const std::string &transname, const mesh &m,
2560  const std::string &dispname, size_type region) {
2561  raytracing_interpolate_transformation *p
2562  = dynamic_cast<raytracing_interpolate_transformation *>
2563  (const_cast<virtual_interpolate_transformation *>
2564  (&(*(workspace.interpolate_transformation(transname)))));
2565  p->add_contact_boundary(workspace, m, dispname, region, true);
2566  }
2567 
2569  (model &md, const std::string &transname,
2570  const std::string &expr, size_type N) {
2571  raytracing_interpolate_transformation *p
2572  = dynamic_cast<raytracing_interpolate_transformation *>
2573  (const_cast<virtual_interpolate_transformation *>
2574  (&(*(md.interpolate_transformation(transname)))));
2575  p->add_rigid_obstacle(md, expr, N);
2576  }
2577 
2579  (ga_workspace &workspace, const std::string &transname,
2580  const std::string &expr, size_type N) {
2581  raytracing_interpolate_transformation *p
2582  = dynamic_cast<raytracing_interpolate_transformation *>
2583  (const_cast<virtual_interpolate_transformation *>
2584  (&(*(workspace.interpolate_transformation(transname)))));
2585  p->add_rigid_obstacle(workspace, expr, N);
2586  }
2587 
2589  (model &md, const std::string &transname, scalar_type d) {
2590  pinterpolate_transformation
2591  p = std::make_shared<projection_interpolate_transformation>(d);
2592  md.add_interpolate_transformation(transname, p);
2593  }
2594 
2596  (ga_workspace &workspace, const std::string &transname, scalar_type d) {
2597  pinterpolate_transformation
2598  p = std::make_shared<projection_interpolate_transformation>(d);
2599  workspace.add_interpolate_transformation(transname, p);
2600  }
2601 
2603  (model &md, const std::string &transname, const mesh &m,
2604  const std::string &dispname, size_type region) {
2605  projection_interpolate_transformation *p
2606  = dynamic_cast<projection_interpolate_transformation *>
2607  (const_cast<virtual_interpolate_transformation *>
2608  (&(*(md.interpolate_transformation(transname)))));
2609  p->add_contact_boundary(md, m, dispname, region, false);
2610  }
2611 
2613  (model &md, const std::string &transname, const mesh &m,
2614  const std::string &dispname, size_type region) {
2615  projection_interpolate_transformation *p
2616  = dynamic_cast<projection_interpolate_transformation *>
2617  (const_cast<virtual_interpolate_transformation *>
2618  (&(*(md.interpolate_transformation(transname)))));
2619  p->add_contact_boundary(md, m, dispname, region, true);
2620  }
2621 
2623  (ga_workspace &workspace, const std::string &transname, const mesh &m,
2624  const std::string &dispname, size_type region) {
2625  projection_interpolate_transformation *p
2626  = dynamic_cast<projection_interpolate_transformation *>
2627  (const_cast<virtual_interpolate_transformation *>
2628  (&(*(workspace.interpolate_transformation(transname)))));
2629  p->add_contact_boundary(workspace, m, dispname, region, false);
2630  }
2631 
2633  (ga_workspace &workspace, const std::string &transname, const mesh &m,
2634  const std::string &dispname, size_type region) {
2635  projection_interpolate_transformation *p
2636  = dynamic_cast<projection_interpolate_transformation *>
2637  (const_cast<virtual_interpolate_transformation *>
2638  (&(*(workspace.interpolate_transformation(transname)))));
2639  p->add_contact_boundary(workspace, m, dispname, region, true);
2640  }
2641 
2643  (model &md, const std::string &transname,
2644  const std::string &expr, size_type N) {
2645  projection_interpolate_transformation *p
2646  = dynamic_cast<projection_interpolate_transformation *>
2647  (const_cast<virtual_interpolate_transformation *>
2648  (&(*(md.interpolate_transformation(transname)))));
2649  p->add_rigid_obstacle(md, expr, N);
2650  }
2651 
2653  (ga_workspace &workspace, const std::string &transname,
2654  const std::string &expr, size_type N) {
2655  projection_interpolate_transformation *p
2656  = dynamic_cast<projection_interpolate_transformation *>
2657  (const_cast<virtual_interpolate_transformation *>
2658  (&(*(workspace.interpolate_transformation(transname)))));
2659  p->add_rigid_obstacle(workspace, expr, N);
2660  }
2661 
2662 
2663 
2664  //=========================================================================
2665  //
2666  // Specific nonlinear operator of the high-level generic assembly language
2667  // dedicated to contact/friction
2668  //
2669  //=========================================================================
2670 
2671  // static void ga_init_scalar(bgeot::multi_index &mi) { mi.resize(0); }
2672  static void ga_init_vector(bgeot::multi_index &mi, size_type N)
2673  { mi.resize(1); mi[0] = N; }
2674  // static void ga_init_square_matrix(bgeot::multi_index &mi, size_type N)
2675  // { mi.resize(2); mi[0] = mi[1] = N; }
2676 
2677 
2678  // Transformed_unit_vector(Grad_u, n) = (I+Grad_u)^{-T}n / ||(I+Grad_u)^{-T}n||
2679  struct Transformed_unit_vector : public ga_nonlinear_operator {
2680  bool result_size(const arg_list &args, bgeot::multi_index &sizes) const {
2681  if (args.size() != 2 || args[0]->sizes().size() != 2
2682  || args[1]->size() != args[0]->sizes()[0]
2683  || args[0]->sizes()[0] != args[0]->sizes()[1]) return false;
2684  ga_init_vector(sizes, args[0]->sizes()[0]);
2685  return true;
2686  }
2687 
2688  // Value : (I+Grad_u)^{-T}n / ||(I+Grad_u)^{-T}n||
2689  void value(const arg_list &args, base_tensor &result) const {
2690  size_type N = args[0]->sizes()[0];
2691  base_matrix F(N, N);
2692  gmm::copy(args[0]->as_vector(), F.as_vector());
2693  gmm::add(gmm::identity_matrix(), F);
2694  bgeot::lu_inverse(&(*(F.begin())), N);
2695  gmm::mult(gmm::transposed(F), args[1]->as_vector(), result.as_vector());
2696  gmm::scale(result.as_vector(),
2697  scalar_type(1)/gmm::vect_norm2(result.as_vector()));
2698  }
2699 
2700  // Derivative / Grad_u: -(I - ndef@ndef)(I+Grad_u)^{-T}Test_Grad_u^T ndef
2701  // Implementation: A{ijk} = -G{ik}ndef{j}
2702  // with G = (I - ndef@ndef)(I+Grad_u)^{-T}
2703  // and ndef the transformed normal
2704  // Derivative / n: (I - ndef@ndef)(I+Grad_u)^{-T}Test_n
2705  // / ||(I+Grad_u)^{-T}n||
2706  // Implementation: A{ij} = G{ij}/norm_ndef
2707  // with norm_ndef = ||(I+Grad_u)^{-T}n||
2708  void derivative(const arg_list &args, size_type nder,
2709  base_tensor &result) const {
2710  size_type N = args[0]->sizes()[0];
2711  base_matrix F(N, N), G(N, N);
2712  base_small_vector ndef(N), aux(N);
2713  gmm::copy(args[0]->as_vector(), F.as_vector());
2714  gmm::add(gmm::identity_matrix(), F);
2715  bgeot::lu_inverse(&(*(F.begin())), N);
2716  gmm::mult(gmm::transposed(F), args[1]->as_vector(), ndef);
2717  scalar_type norm_ndef = gmm::vect_norm2(ndef);
2718  gmm::scale(ndef, scalar_type(1)/norm_ndef);
2719  gmm::copy(gmm::transposed(F), G);
2720  gmm::mult(F, ndef, aux);
2721  gmm::rank_one_update(G, gmm::scaled(ndef, scalar_type(-1)), aux);
2722  base_tensor::iterator it = result.begin();
2723  switch (nder) {
2724  case 1:
2725  for (size_type k = 0; k < N; ++k)
2726  for (size_type j = 0; j < N; ++j)
2727  for (size_type i = 0; i < N; ++i, ++it)
2728  *it = -G(i, k) * ndef[j];
2729  break;
2730  case 2:
2731  for (size_type j = 0; j < N; ++j)
2732  for (size_type i = 0; i < N; ++i, ++it)
2733  *it = G(i, j)/norm_ndef;
2734  break;
2735  default: GMM_ASSERT1(false, "Internal error");
2736  }
2737  GMM_ASSERT1(it == result.end(), "Internal error");
2738  }
2739 
2740  // Second derivative : not implemented
2741  void second_derivative(const arg_list &, size_type, size_type,
2742  base_tensor &) const {
2743  GMM_ASSERT1(false, "Sorry, second derivative not implemented");
2744  }
2745  };
2746 
2747 
2748  // Coulomb_friction_coupled_projection(lambda, n, Vs, g, f, r)
2749  struct Coulomb_friction_coupled_projection : public ga_nonlinear_operator {
2750  bool result_size(const arg_list &args, bgeot::multi_index &sizes) const {
2751  if (args.size() != 6) return false;
2752  size_type N = args[0]->size();
2753  if (N == 0 || args[1]->size() != N || args[2]->size() != N
2754  || args[3]->size() != 1 || args[4]->size() > 3
2755  || args[4]->size() == 0 || args[5]->size() != 1 ) return false;
2756  ga_init_vector(sizes, N);
2757  return true;
2758  }
2759 
2760  // Value : (lambda.n+rg)_- n - P_B(n, f(lambda.n+rg)_-)(lambda-r Vs)
2761  void value(const arg_list &args, base_tensor &result) const {
2762  const base_vector &lambda = *(args[0]);
2763  const base_vector &n = *(args[1]);
2764  const base_vector &Vs = *(args[2]);
2765  base_vector &F = result;
2766  scalar_type g = (*(args[3]))[0];
2767  const base_vector &f = *(args[4]);
2768  scalar_type r = (*(args[5]))[0];
2769 
2770 
2771  scalar_type nn = gmm::vect_norm2(n);
2772  scalar_type lambdan = gmm::vect_sp(lambda, n)/nn;
2773  scalar_type lambdan_aug = gmm::neg(lambdan + r * g);
2774  size_type s_f = gmm::vect_size(f);
2775  scalar_type tau = ((s_f >= 3) ? f[2] : scalar_type(0)) + f[0]*lambdan_aug;
2776  if (s_f >= 2) tau = std::min(tau, f[1]);
2777 
2778  if (tau > scalar_type(0)) {
2779  gmm::add(lambda, gmm::scaled(Vs, -r), F);
2780  scalar_type mu = gmm::vect_sp(F, n)/nn;
2781  gmm::add(gmm::scaled(n, -mu/nn), F);
2782  scalar_type norm = gmm::vect_norm2(F);
2783  if (norm > tau) gmm::scale(F, tau / norm);
2784  } else { gmm::clear(F); }
2785 
2786  gmm::add(gmm::scaled(n, -lambdan_aug/nn), F);
2787  }
2788 
2789  // Derivative / Grad_u: -(I - n@n)(I+Grad_u)^{-T}Test_Grad_u n
2790  // Implementation: A{ijk} = -G{kj}ndef{i}
2791  // with G = (I - n@n)(I+Grad_u)^{-T}
2792  // and ndef the transformed normal
2793  // Derivative / n: ((I+Grad_u)^{-T}Test_n
2794  // - ndef(ndef.Test_n))/||(I+Grad_u)^{-T}n||
2795  // Implementation: A{ij} = (F{ij} - ndef{i}ndef{j})/norm_ndef
2796  // with F = (I+Grad_u)^{-1}
2797  void derivative(const arg_list &args, size_type nder,
2798  base_tensor &result) const { // Can be optimized ?
2799  size_type N = args[0]->size();
2800  const base_vector &lambda = *(args[0]);
2801  const base_vector &n = *(args[1]);
2802  const base_vector &Vs = *(args[2]);
2803  base_vector F(N), dg(N);
2804  base_matrix dVs(N,N), dn(N,N);
2805  scalar_type g = (*(args[3]))[0];
2806  const base_vector &f = *(args[4]);
2807  scalar_type r = (*(args[5]))[0];
2808 
2809  scalar_type nn = gmm::vect_norm2(n);
2810  scalar_type lambdan = gmm::vect_sp(lambda, n)/nn;
2811  scalar_type lambdan_aug = gmm::neg(lambdan + r * g);
2812  size_type s_f = gmm::vect_size(f);
2813  scalar_type tau = ((s_f >= 3) ? f[2] : scalar_type(0))+f[0]*lambdan_aug;
2814  if (s_f >= 2) tau = std::min(tau, f[1]);
2815  scalar_type norm(0);
2816 
2817  if (tau > scalar_type(0)) {
2818  gmm::add(lambda, gmm::scaled(Vs, -r), F); // F <-- lambda -r*Vs
2819  scalar_type mu = gmm::vect_sp(F, n)/nn; // mu <-- (lambda -r*Vs).n/|n|
2820  gmm::add(gmm::scaled(n, -mu/nn), F); // F <-- (lambda -r*Vs)*(I-n x n / |n|²)
2821  norm = gmm::vect_norm2(F);
2822  gmm::copy(gmm::identity_matrix(), dn); // dn <-- I
2823  gmm::scale(dn, -mu/nn); // dn <-- -(lambda -r*Vs).n/|n|² I
2824  gmm::rank_one_update(dn, gmm::scaled(n, mu/(nn*nn*nn)), n); // dn <-- -(lambda -r*Vs).n/|n|² (I - n x n/|n|²)
2825  gmm::rank_one_update(dn, gmm::scaled(n, scalar_type(-1)/(nn*nn)), F); // dn <-- -(lambda -r*Vs).n/|n|² (I - n x n/|n|²) + n x ((lambda -r*Vs)*(I-n x n / |n|²)) /|n|²
2826  gmm::copy(gmm::identity_matrix(), dVs); // dVs <-- I
2827  gmm::rank_one_update(dVs, n, gmm::scaled(n, scalar_type(-1)/(nn*nn))); // dVs <-- I - n x n/|n|²
2828 
2829  if (norm > tau) { // slip
2830  gmm::rank_one_update(dVs, F,
2831  gmm::scaled(F, scalar_type(-1)/(norm*norm)));
2832  gmm::scale(dVs, tau / norm);
2833  gmm::copy(gmm::scaled(F, scalar_type(1)/norm), dg); // dg <-- Normalized((lambda -r*Vs)*(I-n x n / |n|²))
2834  gmm::rank_one_update(dn, gmm::scaled(F, mu/(norm*norm*nn)), F);
2835  gmm::scale(dn, tau / norm);
2836  gmm::scale(F, tau / norm);
2837  } // else gmm::clear(dg);
2838 
2839  } // else { gmm::clear(dg); gmm::clear(dVs); gmm::clear(F); gmm::clear(dn); }
2840  // At this stage, F = P_{B_T}, dVs = d_q P_{B_T}, dn = d_n P_{B_T}
2841  // and dg = d_tau P_{B_T}.
2842 
2843 
2844  base_tensor::iterator it = result.begin();
2845  switch (nder) {
2846  case 1: // Derivative with respect to lambda
2847  if (norm > tau && ((s_f <= 1) || tau < f[1]) &&
2848  ((s_f <= 2) || tau > f[2]))
2849  gmm::rank_one_update(dVs, dg, gmm::scaled(n, -f[0]/nn));
2850  if (lambdan_aug > scalar_type(0))
2851  gmm::rank_one_update(dVs, n, gmm::scaled(n, scalar_type(1)/(nn*nn)));
2852  for (size_type j = 0; j < N; ++j)
2853  for (size_type i = 0; i < N; ++i, ++it)
2854  *it = dVs(i, j);
2855  break;
2856  case 2: // Derivative with respect to n
2857  if (norm > tau && ((s_f <= 1) || tau < f[1])
2858  && ((s_f <= 2) || tau > f[2])) {
2859  gmm::rank_one_update(dn, dg, gmm::scaled(lambda, -f[0]/nn));
2860  gmm::rank_one_update(dn, dg, gmm::scaled(n, f[0]*lambdan/(nn*nn)));
2861  }
2862  if (lambdan_aug > scalar_type(0)) {
2863  gmm::rank_one_update(dn, gmm::scaled(n, scalar_type(1)/(nn*nn)),
2864  lambda);
2865  gmm::rank_one_update(dn,
2866  gmm::scaled(n,(lambdan_aug-lambdan)/(nn*nn*nn)), n);
2867  for (size_type j = 0; j < N; ++j) dn(j,j) -= lambdan_aug/nn;
2868  }
2869  for (size_type j = 0; j < N; ++j)
2870  for (size_type i = 0; i < N; ++i, ++it)
2871  *it = dn(i, j);
2872  break;
2873  case 3:
2874  gmm::scale(dVs, -r);
2875  for (size_type j = 0; j < N; ++j)
2876  for (size_type i = 0; i < N; ++i, ++it)
2877  *it = dVs(i, j);
2878  break;
2879  case 4:
2880  if (norm > tau && ((s_f <= 1) || tau < f[1])
2881  && ((s_f <= 2) || tau > f[2]))
2882  gmm::scale(dg, -f[0]*r);
2883  else
2884  gmm::clear(dg);
2885  if (lambdan_aug > scalar_type(0))
2886  gmm::add(gmm::scaled(n, r/nn), dg);
2887  for (size_type i = 0; i < N; ++i, ++it)
2888  *it = dg[i];
2889  break;
2890  case 5:
2891  if (norm > tau && ((s_f <= 1) || tau < f[1])
2892  && ((s_f <= 2) || tau > f[2]))
2893  gmm::scale(dg, -f[0]*g);
2894  else
2895  gmm::clear(dg);
2896  gmm::mult_add(dVs, gmm::scaled(Vs, scalar_type(-1)), dg);
2897  if (lambdan_aug > scalar_type(0))
2898  gmm::add(gmm::scaled(n, g/nn), dg);
2899  for (size_type i = 0; i < N; ++i, ++it)
2900  *it = dg[i];
2901  it = result.end();
2902  break;
2903  case 6:
2904  base_small_vector dtau_df(s_f);
2905  if ((s_f <= 1) || tau < f[1]) dtau_df[0] = lambdan_aug;
2906  if (s_f >= 2 && tau == f[1]) dtau_df[1] = 1;
2907  if (s_f >= 3 && tau < f[1]) dtau_df[2] = 1;
2908  for (size_type j = 0; j < s_f; ++j)
2909  for (size_type i = 0; i < N; ++i, ++it)
2910  *it = dg[i] * dtau_df[j];
2911  break;
2912  }
2913  GMM_ASSERT1(it == result.end(), "Internal error");
2914  }
2915 
2916  // Second derivative : not implemented
2917  void second_derivative(const arg_list &, size_type, size_type,
2918  base_tensor &) const {
2919  GMM_ASSERT1(false, "Sorry, second derivative not implemented");
2920  }
2921  };
2922 
2923  static bool init_predef_operators() {
2924 
2925  ga_predef_operator_tab &PREDEF_OPERATORS
2927 
2928  PREDEF_OPERATORS.add_method("Transformed_unit_vector",
2929  std::make_shared<Transformed_unit_vector>());
2930  PREDEF_OPERATORS.add_method("Coulomb_friction_coupled_projection",
2931  std::make_shared<Coulomb_friction_coupled_projection>());
2932 
2933  return true;
2934  }
2935 
2936  // declared in getfem_generic_assembly.cc
2937  bool predef_operators_contact_initialized
2938  = init_predef_operators();
2939 
2940 } /* end of namespace getfem. */
Balanced tree of n-dimensional rectangles.
Definition: bgeot_rtree.h:97
static T & instance()
Instance from the current thread.
Describe a finite element method linked to a mesh.
"iterator" class for regions.
Describe a mesh (collection of convexes (elements) and points).
Definition: getfem_mesh.h:98
`‘Model’' variables store the variables, the data and the description of a model.
void add_interpolate_transformation(const std::string &name, pinterpolate_transformation ptrans)
Add an interpolate transformation to the model to be used with the generic assembly.
pinterpolate_transformation interpolate_transformation(const std::string &name) const
Get a pointer to the interpolate transformation name.
The Iteration object calculates whether the solution has reached the desired accuracy,...
Definition: gmm_iter.h:52
Comomon tools for unilateral contact and Coulomb friction bricks.
A language for generic assembly of pde boundary value problems.
void mult_add(const L1 &l1, const L2 &l2, L3 &l3)
*‍/
Definition: gmm_blas.h:1790
void copy(const L1 &l1, L2 &l2)
*‍/
Definition: gmm_blas.h:976
number_traits< typename linalg_traits< V >::value_type >::magnitude_type vect_norm2(const V &v)
Euclidean norm of a vector.
Definition: gmm_blas.h:556
void fill_random(L &l)
fill a vector or matrix with random value (uniform [-1,1]).
Definition: gmm_blas.h:129
number_traits< typename linalg_traits< V >::value_type >::magnitude_type vect_norm2_sqr(const V &v)
squared Euclidean norm of a vector.
Definition: gmm_blas.h:543
void clear(L &l)
clear (fill with zeros) a vector or matrix.
Definition: gmm_blas.h:58
number_traits< typename linalg_traits< V1 >::value_type >::magnitude_type vect_dist2(const V1 &v1, const V2 &v2)
Euclidean distance between two vectors.
Definition: gmm_blas.h:596
void resize(V &v, size_type n)
*‍/
Definition: gmm_blas.h:209
void mult(const L1 &l1, const L2 &l2, L3 &l3)
*‍/
Definition: gmm_blas.h:1663
strongest_value_type< V1, V2 >::value_type vect_sp(const V1 &v1, const V2 &v2)
*‍/
Definition: gmm_blas.h:263
void add(const L1 &l1, L2 &l2)
*‍/
Definition: gmm_blas.h:1275
void lu_inverse(const DenseMatrixLU &LU, const Pvector &pvector, const DenseMatrix &AInv_)
Given an LU factored matrix, build the inverse of the matrix.
Definition: gmm_dense_lu.h:211
std::shared_ptr< const getfem::virtual_fem > pfem
type of pointer on a fem description
Definition: getfem_fem.h:243
gmm::uint16_type short_type
used as the common short type integer in the library
Definition: bgeot_config.h:72
std::shared_ptr< const convex_structure > pconvex_structure
Pointer on a convex structure description.
base_small_vector compute_unit_element_normal(const geotrans_interpolation_context &c)
Unit normal vector to an element of dimension N-1 in dimension N (a curve in 2D or a surface in 3D),...
base_small_vector compute_normal(const geotrans_interpolation_context &c, size_type face)
norm of returned vector is the ratio between the face surface on the real element and the face surfac...
size_t size_type
used as the common size type in the library
Definition: bgeot_poly.h:48
std::shared_ptr< const bgeot::geometric_trans > pgeometric_trans
pointer type for a geometric transformation
size_type alpha(short_type n, short_type d)
Return the value of which is the number of monomials of a polynomial of variables and degree .
Definition: bgeot_poly.cc:46
GEneric Tool for Finite Element Methods.
void add_rigid_obstacle_to_raytracing_transformation(model &md, const std::string &transname, const std::string &expr, size_type N)
Add a rigid obstacle whose geometry corresponds to the zero level-set of the high-level generic assem...
void add_master_contact_boundary_to_projection_transformation(model &md, const std::string &transname, const mesh &m, const std::string &dispname, size_type region)
Add a master boundary with corresponding displacement variable 'dispname' on a specific boundary 'reg...
void add_raytracing_transformation(model &md, const std::string &transname, scalar_type release_distance)
Add a raytracing interpolate transformation called 'transname' to a model to be used by the generic a...
void add_rigid_obstacle_to_projection_transformation(model &md, const std::string &transname, const std::string &expr, size_type N)
Add a rigid obstacle whose geometry corresponds to the zero level-set of the high-level generic assem...
void add_master_contact_boundary_to_raytracing_transformation(model &md, const std::string &transname, const mesh &m, const std::string &dispname, size_type region)
Add a master boundary with corresponding displacement variable 'dispname' on a specific boundary 'reg...
void slice_vector_on_basic_dof_of_element(const mesh_fem &mf, const VEC1 &vec, size_type cv, VEC2 &coeff, size_type qmult1=size_type(-1), size_type qmult2=size_type(-1))
Given a mesh_fem.
void add_projection_transformation(model &md, const std::string &transname, scalar_type release_distance)
Add a projection interpolate transformation called 'transname' to a model to be used by the generic a...
void add_slave_contact_boundary_to_projection_transformation(model &md, const std::string &transname, const mesh &m, const std::string &dispname, size_type region)
Add a slave boundary with corresponding displacement variable 'dispname' on a specific boundary 'regi...
void add_slave_contact_boundary_to_raytracing_transformation(model &md, const std::string &transname, const mesh &m, const std::string &dispname, size_type region)
Add a slave boundary with corresponding displacement variable 'dispname' on a specific boundary 'regi...