Debian Codegraph @

include/deal.II/differentiation/ad/ad_helpers.h

raw
1 // ------------------------------------------------------------------------
2 //
3 // SPDX-License-Identifier: LGPL-2.1-or-later
4 // Copyright (C) 2018 - 2025 by the deal.II authors
5 //
6 // This file is part of the deal.II library.
7 //
8 // Part of the source code is dual licensed under Apache-2.0 WITH
9 // LLVM-exception OR LGPL-2.1-or-later. Detailed license information
10 // governing the source code and code contributions can be found in
11 // LICENSE.md and CONTRIBUTING.md at the top level directory of deal.II.
12 //
13 // ------------------------------------------------------------------------
14
15 #ifndef dealii_differentiation_ad_ad_helpers_h
16 #define dealii_differentiation_ad_ad_helpers_h
17
18 #include <deal.II/base/config.h>
19
20 #if defined(DEAL_II_WITH_ADOLC) || defined(DEAL_II_TRILINOS_WITH_SACADO)
21
22 # include <deal.II/base/numbers.h>
23 # include <deal.II/base/symmetric_tensor.h>
24 # include <deal.II/base/tensor.h>
25
26 # include <deal.II/differentiation/ad/ad_drivers.h>
27 # include <deal.II/differentiation/ad/ad_number_traits.h>
28 # include <deal.II/differentiation/ad/adolc_number_types.h>
29 # include <deal.II/differentiation/ad/adolc_product_types.h>
30 # include <deal.II/differentiation/ad/sacado_number_types.h>
31 # include <deal.II/differentiation/ad/sacado_product_types.h>
32
33 # include <deal.II/fe/fe_values_extractors.h>
34
35 # include <deal.II/lac/full_matrix.h>
36 # include <deal.II/lac/vector.h>
37
38 # include <algorithm>
39 # include <iostream>
40 # include <iterator>
41 # include <numeric>
42
43 DEAL_II_NAMESPACE_OPEN
44
45 namespace Differentiation
46 {
47 namespace AD
48 {
49 /**
50 * A base helper class that facilitates the evaluation of the derivative(s)
51 * of a number of user-defined dependent variables $\mathbf{f}(\mathbf{X})$
52 * with respect to a set of independent variables $\mathbf{X}$, that is
53 * $\dfrac{d^{i} \mathbf{f}(\mathbf{X})}{d \mathbf{X}^{i}}$.
54 *
55 * This class is templated on the floating point type @p scalar_type of the
56 * number that we'd like to differentiate, as well as an enumeration
57 * indicating the @p ADNumberTypeCode . The @p ADNumberTypeCode dictates
58 * which auto-differentiation library is to be used, and what the nature of
59 * the underlying auto-differentiable number is. Refer to the
60 * @ref auto_symb_diff topic for more details in this regard.
61 *
62 * For all of the classes derived from this base class, there are two
63 * possible ways that the code in which they are used can be structured.
64 * The one approach is effectively a subset of the other, and which might
65 * be necessary to use depends on the nature of the chosen
66 * auto-differentiable number.
67 *
68 * When "tapeless" numbers are employed, the most simple code structure
69 * would be of the following form:
70 *
71 * @code
72 * // Initialize AD helper
73 * ADHelperType<tapeless_AD_typecode> ad_helper (...);
74 *
75 * // Register independent variables
76 * ad_helper.register_independent_variable(...);
77 *
78 * // Extract the sensitive equivalent of the independent variables.
79 * // They are the auto-differentiable counterparts to the values
80 * // used as arguments to the register_independent_variable() function.
81 * // The operations conducted with these AD numbers will be tracked.
82 * const auto ad_independent_variables
83 * = ad_helper.get_sensitive_variables(...);
84 *
85 * // Use the sensitive variables to compute the dependent variables.
86 * const auto ad_dependent_variables = func(sensitive_variables);
87 *
88 * // Register the dependent variables with the helper class
89 * ad_helper.register_dependent_variables(ad_dependent_variables);
90 *
91 * // Compute derivatives of the dependent variables
92 * const auto derivatives = ad_helper.compute_gradients();
93 * @endcode
94 *
95 * Note that since the specialized classes interpret the independent
96 * variables in different ways, above represents only an outline of the
97 * steps taken to compute derivatives. More specific examples are outlined
98 * in the individual classes that specialize this base class.
99 *
100 * When "taped" numbers are to be used, the above code should be wrapped by
101 * a few more lines of code to manage the taping procedure:
102 *
103 * @code
104 * // Initialize AD helper
105 * ADHelperType<taped_or_tapeless_AD_typecode> ad_helper (...);
106 *
107 * // An optional call to set the amount of memory to be allocated to
108 * // storing taped data
109 * ad_helper.set_tape_buffer_sizes();
110 *
111 * // Select a tape number to record to
112 * const typename Types<ad_type>::tape_index tape_index = ...;
113 *
114 * // Indicate that we are about to start tracing the operations for
115 * // function evaluation on the tape. If this tape has already been used
116 * // (i.e. the operations are already recorded) then we (optionally)
117 * // load the tape and reuse this data.
118 * const bool is_recording
119 * = ad_helper.start_recording_operations(tape_index);
120 * if (is_recording == true)
121 * {
122 * // This is the "recording" phase of the operations.
123 * // In this block one places the majority of the operations described
124 * // in the previous code block. The set of operations that are
125 * // conducted here therefore includes the following steps:
126 * // - Register independent variables
127 * // - Extract the sensitive equivalent of the independent variables
128 * // - Use the sensitive variables to compute the dependent variables
129 * // - Register the dependent variables with the helper class
130 *
131 * // Indicate that have completed tracing the operations onto the tape.
132 * ad_helper.stop_recording_operations(false); // write_tapes_to_file
133 * }
134 * else
135 * {
136 * // This is the "tape reuse" phase of the operations.
137 * // Here we will leverage the already traced operations that reside
138 * // on a tape, and simply revaluate the tape at a different point
139 * // to get the function values and their derivatives.
140 *
141 * // Load the existing tape to be reused
142 * ad_helper.activate_recorded_tape(tape_no);
143 *
144 * // Set the new values of the independent variables where the recorded
145 * // dependent functions are to be evaluated (and differentiated
146 * // around).
147 * ad_helper.set_independent_variable(...);
148 * }
149 *
150 * // Compute derivatives of the dependent variables
151 * const auto derivatives = ad_helper.compute_gradients();
152 * @endcode
153 *
154 * The second approach outlined here is more general than the first, and
155 * will work equally well for both taped and tapeless auto-differentiable
156 * numbers.
157 *
158 * @warning ADOL-C does not support the standard threading models used by
159 * deal.II, so this class should @b not be embedded within a multithreaded
160 * function when using ADOL-C number types. It is, however, suitable for use
161 * in both serial and MPI routines.
162 *
163 * @todo Make this class thread safe for Sacado number and ADOL-C tapeless
164 * numbers (if supported).
165 */
166 template <enum AD::NumberTypes ADNumberTypeCode,
167 typename ScalarType = double>
168 class HelperBase
169 {
170 public:
171 /**
172 * Type definition for the floating point number type that is used in,
173 * and results from, all computations.
174 */
175 using scalar_type =
176 typename AD::NumberTraits<ScalarType, ADNumberTypeCode>::scalar_type;
177
178 /**
179 * Type definition for the auto-differentiation number type that is used
180 * in all computations.
181 */
182 using ad_type =
183 typename AD::NumberTraits<ScalarType, ADNumberTypeCode>::ad_type;
184
185 /**
186 * @name Constructor / destructor
187 * @{
188 */
189
190 /**
191 * The constructor for the class.
192 *
193 * @param[in] n_independent_variables The number of independent variables
194 * that will be used in the definition of the functions that it is
195 * desired to compute the sensitivities of. In the computation of
196 * $\mathbf{f}(\mathbf{X})$, this will be the number of inputs
197 * $\mathbf{X}$, i.e., the dimension of the domain space.
198 * @param[in] n_dependent_variables The number of scalar functions to be
199 * defined that will have a sensitivity to the given independent
200 * variables. In the computation of $\mathbf{f}(\mathbf{X})$, this will
201 * be the number of outputs $\mathbf{f}$, i.e., the dimension of the
202 * image space.
203 */
204 HelperBase(const unsigned int n_independent_variables,
205 const unsigned int n_dependent_variables);
206
207 /**
208 * Destructor
209 */
210 virtual ~HelperBase() = default;
211
212 /** @} */
213
214 /**
215 * @name Interrogation of internal information
216 * @{
217 */
218
219 /**
220 * Return the number of independent variables that this object expects to
221 * work with. This is the dimension of the domain space.
222 */
223 std::size_t
224 n_independent_variables() const;
225
226 /**
227 * Return the number of dependent variables that this object expects to
228 * operate on. This is the dimension of the image space.
229 */
230 std::size_t
231 n_dependent_variables() const;
232
233 /**
234 * Print the status of all queryable data. Exactly what is printed and
235 * its format depends on the @p ad_type, as is determined by the
236 * @p ADNumberTypeCode template parameter.
237 *
238 * @param[in] stream The output stream to which the values are to be
239 * written.
240 */
241 void
242 print(std::ostream &stream) const;
243
244 /**
245 * Print the values currently assigned to the independent variables.
246 *
247 * @param[in] stream The output stream to which the values are to be
248 * written.
249 */
250 void
251 print_values(std::ostream &stream) const;
252
253 /**
254 * Print the statistics regarding the usage of the tapes.
255 *
256 * @param[in] tape_index The index of the tape to get the statistics of.
257 * @param[out] stream The output stream to which the values are to be
258 * written.
259 *
260 * @note This function only produces meaningful output when @p ad_type
261 * is a taped auto-differentiable number.
262 */
263 void
264 print_tape_stats(const typename Types<ad_type>::tape_index tape_index,
265 std::ostream &stream) const;
266
267 /** @} */
268
269 /**
270 * @name Operations specific to tapeless mode
271 * @{
272 */
273
274 /**
275 * Pre-specify the number of @p independent_variables to be used in
276 * tapeless mode.
277 *
278 * Although this function is called internally in the HelperBase
279 * constructor, there may be occasions when ADOL-C tapeless numbers
280 * (<tt>adtl::adoubles</tt>) are created before an instance of this class
281 * is created. This function therefore allows one to declare at the
282 * earliest possible instance how many directional derivatives will be
283 * considered in tapeless mode.
284 *
285 * @warning With @p ensure_persistent_setting set to <tt>true</tt> when
286 * the @p ad_type is an ADOL-C tapeless number, calling this function
287 * leaves the set number of directional derivatives in a persistent state.
288 * It will therefore not be possible to further modify the number of
289 * directional derivatives to be tracked by <tt>adtl::adoubles</tt>'s
290 * during course of the program's execution.
291 */
292 static void
293 configure_tapeless_mode(const unsigned int n_independent_variables,
294 const bool ensure_persistent_setting = true);
295
296 /** @} */
297
298 /**
299 * @name Operations specific to taped mode: Recording tapes
300 * @{
301 */
302
303 /**
304 * Reset the state of the helper class.
305 *
306 * When an instance of an HelperBase is stored as a class member object
307 * with the intention to reuse its instance, it may be necessary to reset
308 * the state of the object before use. This is because, internally, there
309 * is error checking performed to ensure that the correct
310 * auto-differentiable data is being tracked and used only when
311 * appropriate. This function clears all member data and, therefore,
312 * allows the state of all internal flags to be safely reset to their
313 * initial state.
314 *
315 * In the rare case that the number of independent or dependent variables
316 * has changed, this can also reconfigured by passing in the appropriate
317 * arguments to the function.
318 *
319 * @param[in] n_independent_variables The number of independent variables
320 * that will be used in the definition of the functions that it is
321 * desired to compute the sensitivities of. In the computation of
322 * $\mathbf{f}(\mathbf{X})$, this will be the number of inputs
323 * $\mathbf{X}$, i.e., the dimension of the domain space.
324 * @param[in] n_dependent_variables The number of scalar functions to be
325 * defined that will have a sensitivity to the given independent
326 * variables. In the computation of $\mathbf{f}(\mathbf{X})$, this will
327 * be the number of outputs $\mathbf{f}$, i.e., the dimension of the
328 * image space.
329 * @param[in] clear_registered_tapes A flag that indicates the that
330 * list of @p registered_tapes must be cleared.
331 * If set to <tt>true</tt> then the data structure that tracks which
332 * tapes have been recorded is cleared as well. It is then expected that
333 * any preexisting tapes be re-recorded.
334 *
335 * @note This also resets the active tape number to an invalid number, and
336 * deactivates the recording mode for taped variables.
337 */
338 virtual void
339 reset(const unsigned int n_independent_variables =
340 dealii::numbers::invalid_unsigned_int,
341 const unsigned int n_dependent_variables =
342 dealii::numbers::invalid_unsigned_int,
343 const bool clear_registered_tapes = true);
344
345 /**
346 * Return whether or not this class is tracking calculations performed
347 * with its marked independent variables.
348 */
349 bool
350 is_recording() const;
351
352 /**
353 * Return the tape index which is currently activated for recording or
354 * reading.
355 */
356 typename Types<ad_type>::tape_index
357 active_tape_index() const;
358
359 /**
360 * Return whether or not a tape number has already been used
361 * or registered.
362 */
363 bool
364 is_registered_tape(
365 const typename Types<ad_type>::tape_index tape_index) const;
366
367 /**
368 * Set the buffer sizes for the next active tape.
369 *
370 * This function must be called before start_recording_operations() for
371 * it to have any influence on the memory allocated to the next recorded
372 * tape.
373 *
374 * @note This function only has an effect when using ADOL-C numbers. As
375 * stated by the ADOL-C manual, it may be desirable to create a file
376 * ".adolcrc" in the program run directory and set the buffer size
377 * therein.
378 * Alternatively, this function can be used to override the settings for
379 * any given tape, or can be used in the event that no ".adolcrc" file
380 * exists.
381 * The default value for each buffer is set at 64 megabytes, a
382 * heuristically chosen value thought to be appropriate for use within
383 * the context of finite element analysis when considering coupled
384 * problems with multiple vector-valued fields discretised by higher
385 * order shape functions, as well as complex constitutive laws.
386 *
387 * @param[in] obufsize ADOL-C operations buffer size
388 * @param[in] lbufsize ADOL-C locations buffer size
389 * @param[in] vbufsize ADOL-C value buffer size
390 * @param[in] tbufsize ADOL-C Taylor buffer size
391 */
392 void
393 set_tape_buffer_sizes(
394 const typename Types<ad_type>::tape_buffer_sizes obufsize = 64 * 1024 *
395 1024,
396 const typename Types<ad_type>::tape_buffer_sizes lbufsize = 64 * 1024 *
397 1024,
398 const typename Types<ad_type>::tape_buffer_sizes vbufsize = 64 * 1024 *
399 1024,
400 const typename Types<ad_type>::tape_buffer_sizes tbufsize = 64 * 1024 *
401 1024);
402
403 /**
404 * Enable recording mode for a given tape. The use of this function is
405 * mandatory if the auto-differentiable number is a taped type. However,
406 * for the purpose of developing generic code, it can also be safely
407 * called for tapeless auto-differentiable numbers.
408 *
409 * The operations that take place between this function call and that
410 * of stop_recording_operations() are recorded to the tape and can
411 * be replayed and reevaluated as necessary.
412 *
413 * The typical set of operations to be performed during this "recording"
414 * phase (between the calls to start_recording_operations() and
415 * stop_recording_operations() ) are:
416 * - Definition of some independent variables via
417 * register_independent_variable() or
418 * register_independent_variables(). These define the branch of
419 * operations tracked by the tape. If the @p keep flag is set to
420 * <tt>true</tt> then these represent precisely the point about which
421 * the function derivatives are to be computed. If the @p keep flag is
422 * set to <tt>false</tt> then these only represent dummy values, and
423 * the point at which the function derivatives are to be computed must
424 * be set by calling set_independent_variables() again.
425 * - Extraction of a set of independent variables of auto-differentiable
426 * type using get_sensitive_variables(). These are then tracked during
427 * later computations.
428 * - Defining the dependent variables via register_dependent_variable()
429 * or register_dependent_variables(). These are the functions that
430 * will be differentiated with respect to the independent variables.
431 *
432 * @param[in] tape_index The index of the tape to be written
433 * @param[in] overwrite_tape Express whether tapes are allowed to be
434 * overwritten. If <tt>true</tt> then any existing tape with a given
435 * @p tape_index will be destroyed and a new tape traced over it.
436 * @param[in] keep_independent_values Determines whether the numerical
437 * values of all independent variables are recorded in the tape buffer.
438 * If true, then the tape can be immediately used to perform computations
439 * after recording is complete.
440 *
441 * @note During the recording phase, no value(), gradient(), hessian(),
442 * or jacobian() operations can be performed.
443 *
444 * @note The chosen tape index must be greater than
445 * Numbers<ad_type>::invalid_tape_index and less than
446 * Numbers<ad_type>::max_tape_index.
447 */
448 bool
449 start_recording_operations(
450 const typename Types<ad_type>::tape_index tape_index,
451 const bool overwrite_tape = false,
452 const bool keep_independent_values = true);
453
454 /**
455 * Disable recording mode for a given tape. The use of this function is
456 * mandatory if the auto-differentiable number is a taped type. However,
457 * for the purpose of developing generic code, it can also be safely
458 * called for tapeless auto-differentiable numbers.
459 *
460 * @note After this function call, the tape is considered ready for use and
461 * operations such as value(), gradient() or hessian() can be executed.
462 *
463 * @note For taped AD numbers, this operation is only valid in recording mode.
464 */
465 void
466 stop_recording_operations(const bool write_tapes_to_file = false);
467
468 /**
469 * Select a pre-recorded tape to read from.
470 *
471 * @param[in] tape_index The index of the tape to be read from.
472 *
473 * @note The chosen tape index must be greater than
474 * Numbers<ad_type>::invalid_tape_index and less than
475 * Numbers<ad_type>::max_tape_index.
476 */
477 void
478 activate_recorded_tape(
479 const typename Types<ad_type>::tape_index tape_index);
480
481 /**
482 * Return a flag that, when <code>true</code>, indicates that the
483 * retaping of the dependent function is necessary for a reliable
484 * computation to be performed on a tape with the given @p tape_index.
485 * This may be necessary if a sign comparison within branched operations
486 * yields different results to those computed at the original tape
487 * evaluation point.
488 *
489 * This issue, known as "branch switching", can be clarified by means of
490 * a trivial, contrived example:
491 * @code
492 * ADNumberType func (ADNumberType x, ADNumberType y, ADNumberType z)
493 * {
494 * if (x < y)
495 * return y;
496 * else
497 * return x*z;
498 * }
499 * @endcode
500 * During taping, the conditional statement may be either <tt>true</tt> or
501 * <tt>false</tt>, and the result (with its sensitivities) returned by
502 * this function.
503 * The AD library doesn't just record the parse tree of the operations
504 * applied on the branch chosen at the time to taping, but also checks
505 * that the condition continues to be satisfied. For some other evaluation
506 * of the tape (i.e. for some different inputs @p x and @p y), the other
507 * branch of the conditional check may be chosen. The result of following
508 * this code path has not been recorded on the tape, and therefore cannot
509 * be evaluated. In such a case, the underlying AD library will be able to
510 * tell you that it is necessary to re-record the tape at the new
511 * evaluation point in order to resolve the new code branch. This function
512 * can be used to find out whether this is so.
513 *
514 * For the output of this function to be meaningful, it must be called
515 * after activate_recorded_tape() is called and the new evaluation
516 * point for the tape (i.e. values of the independent variables) have
517 * been set and subsequently used (i.e. in the determination of the values
518 * or derivatives of the dependent variables).
519 */
520 bool
521 recorded_tape_requires_retaping(
522 const typename Types<ad_type>::tape_index tape_index) const;
523
524 /**
525 * Return a flag that, when <code>true</code>, indicates that the
526 * retaping of the dependent function is necessary for a reliable
527 * computation to be performed on the currently active tape.
528 * This may be necessary if a sign comparison within branched operations
529 * yields different results to those computed at the original tape
530 * evaluation point.
531 *
532 * This issue, known as "branch switching", can be clarified by means of
533 * a trivial, contrived example:
534 * @code
535 * ADNumberType func (ADNumberType x, ADNumberType y, ADNumberType z)
536 * {
537 * if (x < y)
538 * return y;
539 * else
540 * return x*z;
541 * }
542 * @endcode
543 * During taping, the conditional statement may be either <tt>true</tt> or
544 * <tt>false</tt>, and the result (with its sensitivities) returned by
545 * this function.
546 * The AD library doesn't just record the parse tree of the operations
547 * applied on the branch chosen at the time to taping, but also checks
548 * that the condition continues to be satisfied. For some other evaluation
549 * of the tape (i.e. for some different inputs @p x and @p y), the other
550 * branch of the conditional check may be chosen. The result of following
551 * this code path has not been recorded on the tape, and therefore cannot
552 * be evaluated. In such a case, the underlying AD library will be able to
553 * tell you that it is necessary to re-record the tape at the new
554 * evaluation point in order to resolve the new code branch. This function
555 * can be used to find out whether this is so.
556 *
557 * For the output of this function to be meaningful, it must be called
558 * after activate_recorded_tape() is called and the new evaluation
559 * point for the tape (i.e. values of the independent variables) have
560 * been set and subsequently used (i.e. in the determination of the values
561 * or derivatives of the dependent variables).
562 */
563 bool
564 active_tape_requires_retaping() const;
565
566 /**
567 * Clears and removes the currently active tape.
568 *
569 * This is typically only necessary when branch switching is detected on
570 * the original tape at evaluation point. This state can be checked using
571 * the active_tape_requires_retaping() function.
572 */
573 void
574 clear_active_tape();
575
576 /** @} */
577
578 protected:
579 /**
580 * @name Drivers and taping
581 * @{
582 */
583
584 /**
585 * An object used to help manage stored tapes.
586 *
587 * In the event that the @p ad_type is a tapeless AD type, then the object
588 * constructed here is, effectively, a dummy one.
589 */
590 TapedDrivers<ad_type, scalar_type> taped_driver;
591
592 /**
593 * An object used to help manage tapeless data structures.
594 *
595 * In the event that the @p ad_type is a taped AD type, then the object
596 * constructed here is, effectively, a dummy one.
597 */
598 TapelessDrivers<ad_type, scalar_type> tapeless_driver;
599
600 /**
601 * Select a tape to record to or read from.
602 *
603 * This function activates a tape, but depending on whether @p read_mode
604 * is set, the tape is either taken as previously written to (and put
605 * into read-only mode), or cleared for (re-)taping.
606 *
607 * @param[in] tape_index The index of the tape to be written to/read
608 * from.
609 * @param[in] read_mode A flag that marks whether or not we expect to
610 * read data from a preexisting tape.
611 *
612 * @note The chosen tape index must be greater than
613 * Numbers<ad_type>::invalid_tape_index and less than
614 * Numbers<ad_type>::max_tape_index.
615 */
616 void
617 activate_tape(const typename Types<ad_type>::tape_index tape_index,
618 const bool read_mode);
619
620 /** @} */
621
622 /**
623 * @name Independent variables
624 * @{
625 */
626
627 /**
628 * A set of independent variables $\mathbf{X}$ that differentiation will
629 * be performed with respect to.
630 *
631 * The gradients and Hessians of dependent variables will be computed
632 * at these finite values.
633 */
634 mutable std::vector<scalar_type> independent_variable_values;
635
636 /**
637 * A set of sensitive independent variables $\mathbf{X}$ that
638 * differentiation will be performed with respect to.
639 *
640 * The gradients and Hessians of dependent variables will be computed
641 * using these configured AD numbers. Note that only reverse-mode AD
642 * requires that the sensitive independent variables be stored.
643 */
644 mutable std::vector<ad_type> independent_variables;
645
646 /**
647 * A list of registered independent variables that have been manipulated
648 * for a given set of operations.
649 */
650 std::vector<bool> registered_independent_variable_values;
651
652 /**
653 * A list of registered independent variables that have been extracted and
654 * their sensitivities marked.
655 */
656 mutable std::vector<bool> registered_marked_independent_variables;
657
658 /**
659 * Reset the boolean vector @p registered_independent_variable_values that
660 * indicates which independent variables we've been manipulating for
661 * the current set of operations.
662 */
663 void
664 reset_registered_independent_variables();
665
666 /**
667 * Set the actual value of the independent variable $X_{i}$.
668 *
669 * @param[in] index The index in the vector of independent variables.
670 * @param[in] value The value to set the index'd independent variable to.
671 */
672 void
673 set_sensitivity_value(const unsigned int index, const scalar_type &value);
674
675 /**
676 * Initialize an independent variable $X_{i}$ such that subsequent
677 * operations performed with it are tracked.
678 *
679 * @note Care must be taken to mark each independent variable only once.
680 *
681 * @note The order in which the independent variables are marked defines the
682 * order of all future internal operations. They must be manipulated in
683 * the same order as that in which they are first marked. If not then,
684 * for example, ADOL-C won't throw an error, but rather it might complain
685 * nonsensically during later computations or produce garbage results.
686 *
687 * @param[in] index The index in the vector of independent variables.
688 * @param[out] out An auto-differentiable number that is ready for use in
689 * computations. The operations that are performed with it are recorded on
690 * the tape and will be considered in the computation of dependent
691 * variable values.
692 */
693 void
694 mark_independent_variable(const unsigned int index, ad_type &out) const;
695
696 /**
697 * Finalize the state of the independent variables before use.
698 *
699 * This step and the storage of the independent variables is done
700 * separately because some derived classes may offer the capability
701 * to add independent variables in a staggered manner. This function
702 * is to be triggered when these values are considered finalized
703 * and we can safely initialize the sensitive equivalents of those
704 * values.
705 */
706 void
707 finalize_sensitive_independent_variables() const;
708
709 /**
710 * Initialize an independent variable $X_{i}$.
711 *
712 * @param[out] out An auto-differentiable number that is ready for use in
713 * standard computations. The operations that are performed with it are
714 * not recorded on the tape, and so should only be used when not in
715 * recording mode.
716 * @param[in] index The index in the vector of independent variables.
717 */
718 void
719 initialize_non_sensitive_independent_variable(const unsigned int index,
720 ad_type &out) const;
721
722 /**
723 * The number of independent variables that have been manipulated within a
724 * set of operations.
725 */
726 unsigned int
727 n_registered_independent_variables() const;
728
729 /** @} */
730
731 /**
732 * @name Dependent variables
733 * @{
734 */
735
736 /**
737 * The set of dependent variables $\mathbf{f}(\mathbf{X})$ of which the
738 * derivatives with respect to $\mathbf{X}$ will be computed.
739 *
740 * The gradients and Hessians of these dependent variables will be
741 * computed at the values $\mathbf{X}$ set with the
742 * set_sensitivity_value() function.
743 *
744 * @note These are stored as an @p ad_type so that we can use them to
745 * compute function values and directional derivatives in the case that
746 * tapeless numbers are used
747 */
748 std::vector<ad_type> dependent_variables;
749
750 /**
751 * A list of registered dependent variables.
752 */
753 std::vector<bool> registered_marked_dependent_variables;
754
755 /**
756 * Reset the boolean vector @p registered_marked_dependent_variables that
757 * indicates which independent variables have been manipulated by the
758 * current set of operations. All entries in the vector are set to the
759 * value of the @p flag.
760 */
761 void
762 reset_registered_dependent_variables(const bool flag = false);
763
764 /**
765 * The number of dependent variables that have been registered.
766 */
767 unsigned int
768 n_registered_dependent_variables() const;
769
770 /**
771 * Register the definition of the index'th dependent variable
772 * $f(\mathbf{X})$.
773 *
774 * @param[in] index The index of the entry in the global list of dependent
775 * variables that this function belongs to.
776 * @param[in] func The recorded function that defines a dependent
777 * variable.
778 *
779 * @note Each dependent variable must only be registered once.
780 */
781 void
782 register_dependent_variable(const unsigned int index,
783 const ad_type &func);
784
785 /** @} */
786
787 }; // class HelperBase
788
789
790
791 /**
792 * A general helper class that facilitates the evaluation of a vector of
793 * functions, as well as its first derivatives (their Jacobian).
794 * This class would typically be used to compute the linearization of a
795 * set of local nonlinear equations, but can also be used as the basis of
796 * the linearization of the residual vector defined on the level of a finite
797 * element (for example, in order to compute the Jacobian matrix necessary
798 * in Newton-type solvers for nonlinear problems).
799 *
800 * @note When using the cell-level taped AD methods in 3d and/or with higher
801 * order elements, it is incredibly easy to exceed the tape buffer size.
802 * The reason for this is two-fold:
803 * 1. there are many independent variables (the local
804 * degrees-of-freedom) to take the derivatives with respect to, and
805 * 2. the expressions for the dependent variables (each being a component
806 * of the residual vector) in terms of all of the independent variables
807 * are lengthy, especially when non-trivial constitutive laws are
808 * considered.
809 * These buffer variables dictate the amount of memory allocated to a tape
810 * before it is written to file (at a significant performance loss).
811 * Therefore for ADOL-C taped AD numbers, it may be desirable to
812 * create a file ".adolcrc" in the program run directory and set the buffer
813 * size therein (as is suggested by the ADOL-C manual). For example, the
814 * following settings increase the default buffer size by 128 times:
815 * @code
816 * "OBUFSIZE" "67108864"
817 * "LBUFSIZE" "67108864"
818 * "VBUFSIZE" "67108864"
819 * "TBUFSIZE" "67108864"
820 * @endcode
821 * Note that the quotation marks are mandatory.
822 * An alternative approach that allows for run-time decision making is to
823 * use the HelperBase::set_tape_buffer_sizes() function before starting
824 * taping (as done via the HelperBase::start_recording_operations()
825 * function).
826 *
827 * @warning ADOL-C does not support the standard threading models used by
828 * deal.II, so this class should @b not be embedded within a multithreaded
829 * function when using ADOL-C number types. It is, however, suitable for use
830 * in both serial and MPI routines.
831 */
832 template <enum AD::NumberTypes ADNumberTypeCode,
833 typename ScalarType = double>
834 class CellLevelBase : public HelperBase<ADNumberTypeCode, ScalarType>
835 {
836 public:
837 /**
838 * Type definition for the floating point number type that is used in,
839 * and results from, all computations.
840 */
841 using scalar_type =
842 typename HelperBase<ADNumberTypeCode, ScalarType>::scalar_type;
843
844 /**
845 * Type definition for the auto-differentiation number type that is used
846 * in all computations.
847 */
848 using ad_type =
849 typename HelperBase<ADNumberTypeCode, ScalarType>::ad_type;
850
851 /**
852 * @name Constructor / destructor
853 */
854 /** @{ */
855
856 /**
857 * The constructor for the class.
858 *
859 * @param[in] n_independent_variables The number of independent variables
860 * that will be used in the definition of the functions that it is
861 * desired to compute the sensitivities of. In the computation of
862 * $\mathbf{f}(\mathbf{X})$, this will be the number of inputs
863 * $\mathbf{X}$, i.e., the dimension of the domain space.
864 * @param[in] n_dependent_variables The number of scalar functions to be
865 * defined that will have a sensitivity to the given independent
866 * variables. In the computation of $\mathbf{f}(\mathbf{X})$, this will
867 * be the number of outputs $\mathbf{f}$, i.e., the dimension of the
868 * image space.
869 */
870 CellLevelBase(const unsigned int n_independent_variables,
871 const unsigned int n_dependent_variables);
872
873 /**
874 * Destructor
875 */
876 virtual ~CellLevelBase() = default;
877
878 /** @} */
879
880 /**
881 * @name Independent variables
882 */
883 /** @{ */
884
885 /**
886 * Register the complete set of independent variables $\mathbf{X}$ that
887 * represent the local degree of freedom values.
888 *
889 * @param[in] dof_values A vector field associated with local
890 * degree of freedom values on the current finite element. These define
891 * the values of all independent variables. When considering taped AD
892 * numbers with branching functions, to avoid potential issues with branch
893 * switching it may be a good idea to choose these values close or equal
894 * to those that will be later evaluated and linearized around.
895 *
896 * @note The input value type must correspond to this class's @p scalar_type.
897 * Depending on the selected @p ADNumberTypeCode, this may or may not
898 * correspond with the @p ScalarType prescribed as a template argument.
899 *
900 * @note For taped AD numbers, this operation is only valid in recording mode.
901 */
902 void
903 register_dof_values(const std::vector<scalar_type> &dof_values);
904
905 /**
906 * Register the complete set of independent variables $\mathbf{X}$ that
907 * represent the local degree of freedom values.
908 *
909 * @param[in] values A global field from which the values of all
910 * independent variables will be extracted. This typically will be the
911 * solution vector around which point a residual vector is to be
912 * computed and around which linearization is to occur.
913 * When considering taped AD numbers with branching functions, to avoid
914 * potential issues with branch switching it may be a good idea to choose
915 * these values close or equal to those that will be later evaluated and
916 * linearized around.
917 * @param[in] local_dof_indices A vector of degree of freedom indices from
918 * which to extract the local degree of freedom values. This would
919 * typically obtained by calling <code>cell->get_dof_indices()</code>.
920 *
921 * @note For taped AD numbers, this operation is only valid in recording mode.
922 */
923 template <typename VectorType>
924 void
925 register_dof_values(
926 const VectorType &values,
927 const std::vector<dealii::types::global_dof_index> &local_dof_indices);
928
929 /**
930 * Return the complete set of degree of freedom values as represented by
931 * auto-differentiable numbers. These are the independent
932 * variables $\mathbf{X}$ about which the solution is linearized.
933 *
934 * This function indicates to the AD library that implements the
935 * auto-differentiable number type that operations performed on these
936 * numbers are to be tracked so they are considered "sensitive"
937 * variables. This is, therefore, the set of variables with which one
938 * would then perform computations, and based on which one can then
939 * extract both the value of the function and its derivatives with the
940 * member functions below. The values of the components of the returned
941 * object are initialized to the values set with
942 * register_independent_variable().
943 *
944 * @return An array of auto-differentiable type numbers representing the
945 * local degree of freedom values.
946 *
947 * @note For taped AD numbers, this operation is only valid in recording mode.
948 */
949 const std::vector<ad_type> &
950 get_sensitive_dof_values() const;
951
952 /** @} */
953
954 /**
955 * @name Operations specific to taped mode: Reusing tapes
956 */
957 /** @{ */
958
959 /**
960 * Set the values for the independent variables $\mathbf{X}$, i.e., the
961 * linearization point.
962 *
963 * @param[in] dof_values A vector field associated with local
964 * degree of freedom values on the current finite element. These define
965 * the values of all independent variables.
966 *
967 * @note The input value type must correspond to this class's @p scalar_type.
968 * Depending on the selected @p ADNumberTypeCode, this may or may not
969 * correspond with the @p ScalarType prescribed as a template argument.
970 *
971 * @note If the @p keep_independent_values flag has been set when
972 * HelperBase::start_recording_operations() is called then the tape is
973 * immediately usable after creation, and the values of the independent
974 * variables set by register_dof_values() are those at which the function
975 * is to be evaluated. In this case, a separate call to this function is
976 * not strictly necessary.
977 */
978 void
979 set_dof_values(const std::vector<scalar_type> &dof_values);
980
981 /**
982 * Set the values for the independent variables $\mathbf{X}$, i.e., the
983 * linearization point.
984 *
985 * @param[in] values A vector field from which the values of all
986 * independent variables is to be extracted.
987 * @param[in] local_dof_indices A vector of degree of freedom indices from
988 * which to extract the local degree of freedom values. This would
989 * typically obtained by calling <code>cell->get_dof_indices()</code>.
990 *
991 * @note If the @p keep_independent_values flag has been set when
992 * HelperBase::start_recording_operations() is called then the tape is
993 * immediately usable after creation, and the values of the independent
994 * variables set by register_dof_values() are those at which the function
995 * is to be evaluated. In this case, a separate call to this function is
996 * not strictly necessary.
997 */
998 template <typename VectorType>
999 void
1000 set_dof_values(
1001 const VectorType &values,
1002 const std::vector<dealii::types::global_dof_index> &local_dof_indices);
1003
1004 /** @} */
1005
1006 /**
1007 * @name Dependent variables
1008 */
1009 /** @{ */
1010
1011 /**
1012 * Compute the value of the residual vector field
1013 * $\mathbf{r}(\mathbf{X})$.
1014 *
1015 * @param[out] residual A Vector object with the value for each component
1016 * of the vector field evaluated at the point defined by the independent
1017 * variable values.
1018 *
1019 * @note The size of the @p residual vector is determined by the derived
1020 * classes, as it depends on the order of the dependent variable(s)
1021 * derivative(s) that it represents. Code examples that show how to use
1022 * this interface will be provided in the documentation of the derived
1023 * classes.
1024 */
1025 virtual void
1026 compute_residual(Vector<scalar_type> &residual) const = 0;
1027
1028 /**
1029 * Compute the gradient (first derivative) of the residual vector field
1030 * with respect to all independent variables, i.e.
1031 * @f[
1032 * \frac{\partial\mathbf{r}(\mathbf{X})}{\partial\mathbf{X}}
1033 * @f]
1034 *
1035 * @param[out] linearization A FullMatrix with the gradient of each
1036 * component of the vector field evaluated at the point defined by the
1037 * independent variable values.
1038 *
1039 * @note The dimensions of the @p linearization matrix is determined by
1040 * the derived classes, as it depends on the order of the dependent
1041 * variable(s) derivative(s) that it represents. Code examples that show
1042 * how to use this interface will be provided in the documentation of
1043 * the derived classes.
1044 */
1045 virtual void
1046 compute_linearization(FullMatrix<scalar_type> &linearization) const = 0;
1047
1048 /** @} */
1049
1050 }; // class CellLevelBase
1051
1052
1053
1054 /**
1055 * A helper class that facilitates the implementation of a generic
1056 * (incremental) variational formulation from which the computation of the
1057 * residual vector, as well as its linearization, is automated. This class
1058 * would typically be used to derive the residual vector and tangent matrix
1059 * (defined on the level of a cell), or a linearized system of
1060 * equations, starting from a scalar energy functional.
1061 *
1062 * An example of its usage in the case of a residual and tangent
1063 * computations might be as follows (in this case we'll compute the
1064 * linearization of a finite-strain hyperelastic solid from a stored/strain
1065 * energy density function):
1066 *
1067 * @code
1068 * // Existing data structures:
1069 * Vector<double> solution (...); // Or another vector type
1070 * std::vector<types::global_dof_index> local_dof_indices (...);
1071 * const FEValuesExtractors::Vector u_fe (...);
1072 * FEValues<dim> fe_values (...);
1073 * const unsigned int n_q_points (...);
1074 * FullMatrix<double> cell_matrix (...);
1075 * Vector<double> cell_rhs (...);
1076 *
1077 * // Assembly loop:
1078 * for (auto &cell : ...)
1079 * {
1080 * cell->get_dof_indices(local_dof_indices);
1081 * const unsigned int n_independent_variables =
1082 * local_dof_indices.size();
1083 *
1084 * // Create some aliases for the AD helper.
1085 * // In the example, the AD_typecode used for the template argument can
1086 * // be refer to either a taped or tapeless type.
1087 * using ADHelper = AD::EnergyFunctional<...>;
1088 * using ADNumberType = typename ADHelper::ad_type;
1089 *
1090 * // Create and initialize an instance of the helper class.
1091 * ADHelper ad_helper(n_independent_variables);
1092 *
1093 * // Initialize the local data structures for assembly.
1094 * // This is also taken care of by the ADHelper, so this step could
1095 * // be skipped.
1096 * cell_rhs.reinit(n_independent_variables);
1097 * cell_matrix.reinit(n_independent_variables,n_independent_variables);
1098 *
1099 * // An optional call to set the amount of memory to be allocated to
1100 * // storing taped data.
1101 * // If using a taped AD number then we would likely want to increase
1102 * // the buffer size from the default values as the expression for each
1103 * // residual component will likely be lengthy, and therefore memory
1104 * // intensive.
1105 * ad_helper.set_tape_buffer_sizes(...);
1106 *
1107 * // If using a taped AD number, then at this point we would initiate
1108 * // taping of the expression for the energy for this FE type and
1109 * // material combination:
1110 *
1111 * // Select a tape number to record to
1112 * const typename Types<ad_type>::tape_index tape_index = ...;
1113 *
1114 * // Indicate that we are about to start tracing the operations for
1115 * // function evaluation on the tape. If this tape has already been
1116 * // used (i.e. the operations are already recorded) then we
1117 * // (optionally) load the tape and reuse this data.
1118 * const bool is_recording
1119 * = ad_helper.start_recording_operations(tape_index);
1120 *
1121 * // The steps that follow in the recording phase are required for
1122 * // tapeless methods as well.
1123 * if (is_recording == true)
1124 * {
1125 * // This is the "recording" phase of the operations.
1126 * // First, we set the values for all DoFs.
1127 * ad_helper.register_dof_values(solution, local_dof_indices);
1128 *
1129 * // Then we get the complete set of degree of freedom values as
1130 * // represented by auto-differentiable numbers. The operations
1131 * // performed with these variables are tracked by the AD library
1132 * // from this point until stop_recording_operations() is called.
1133 * const std::vector<ADNumberType> dof_values_ad
1134 * = ad_helper.get_sensitive_dof_values();
1135 *
1136 * // Then we do some problem specific tasks, the first being to
1137 * // compute all values, gradients, etc. based on sensitive AD DoF
1138 * // values. Here we are fetching the displacement gradients at each
1139 * // quadrature point.
1140 * std::vector<Tensor<2, dim, ADNumberType>> Grad_u(
1141 * n_q_points, Tensor<2, dim, ADNumberType>());
1142 * fe_values[u_fe].get_function_gradients_from_local_dof_values(
1143 * dof_values_ad, Grad_u);
1144 *
1145 * // This variable stores the cell total energy.
1146 * // IMPORTANT: Note that it is hand-initialized with a value of
1147 * // zero. This is a highly recommended practise, as some AD numbers
1148 * // appear not to safely initialize their internal data structures.
1149 * ADNumberType energy_ad = ADNumberType(0.0);
1150 *
1151 * // Compute the cell total energy = (internal + external) energies
1152 * for (unsigned int q_point = 0; q_point < n_q_points; ++q_point)
1153 * {
1154 * // Calculate the deformation gradient at this quadrature point
1155 * const Tensor<2, dim, ADNumberType> F =
1156 * unit_symmetric_tensor<dim>() + Grad_u[q_point];
1157 * Assert(numbers::value_is_greater_than(determinant(F), 0.0),
1158 * ExcMessage("Negative determinant of the deformation "
1159 * "gradient detected!"));
1160 *
1161 * // Add contribution of the internal energy:
1162 * // Integrate the stored energy density function with the current
1163 * // solution.
1164 * energy_ad += get_Psi(F) * fe_values.JxW(q_point);
1165 * }
1166 *
1167 * // Add contribution from external energy:
1168 * // Loop over faces and accumulate external energy into cell
1169 * // total energy.
1170 * for (const unsigned int face : ...)
1171 * if (cell->face(face)->at_boundary())
1172 * energy_ad += ...
1173 *
1174 * // Register the definition of the total cell energy
1175 * ad_helper.register_energy_functional(energy_ad);
1176 *
1177 * // Indicate that we have completed tracing the operations onto
1178 * // the tape.
1179 * ad_helper.stop_recording_operations(false); // write_tapes_to_file
1180 * }
1181 * else
1182 * {
1183 * // This is the "tape reuse" phase of the operations.
1184 * // Here we will leverage the already traced operations that reside
1185 * // on a tape, and simply re-evaluate the tape at a different point
1186 * // to get the function values and their derivatives.
1187 *
1188 * // Load the existing tape to be reused
1189 * ad_helper.activate_recorded_tape(tape_index);
1190 *
1191 * // Set the new values of the independent variables where the
1192 * // recorded dependent functions are to be evaluated (and
1193 * // differentiated around).
1194 * ad_helper.set_dof_values(solution, local_dof_indices);
1195 * }
1196 *
1197 * // Compute the residual values and their Jacobian at the
1198 * // evaluation point
1199 * ad_helper.compute_residual(cell_rhs);
1200 * cell_rhs *= -1.0; // RHS = - residual
1201 * ad_helper.compute_linearization(cell_matrix);
1202 * }
1203 * @endcode
1204 *
1205 * In most use cases, and in particular in the code example shown above,
1206 * the number of independent variables equals the number of
1207 * <code>dofs_per_cell</code> for the used finite element.
1208 *
1209 * @warning ADOL-C does not support the standard threading models used by
1210 * deal.II, so this class should @b not be embedded within a multithreaded
1211 * function when using ADOL-C number types. It is, however, suitable for use
1212 * in both serial and MPI routines.
1213 */
1214 template <enum AD::NumberTypes ADNumberTypeCode,
1215 typename ScalarType = double>
1216 class EnergyFunctional : public CellLevelBase<ADNumberTypeCode, ScalarType>
1217 {
1218 public:
1219 /**
1220 * Type definition for the floating point number type that is used in,
1221 * and results from, all computations.
1222 */
1223 using scalar_type =
1224 typename HelperBase<ADNumberTypeCode, ScalarType>::scalar_type;
1225
1226 /**
1227 * Type definition for the auto-differentiation number type that is used
1228 * in all computations.
1229 */
1230 using ad_type =
1231 typename HelperBase<ADNumberTypeCode, ScalarType>::ad_type;
1232
1233 /**
1234 * @name Constructor / destructor
1235 */
1236 /** @{ */
1237
1238 /**
1239 * The constructor for the class.
1240 *
1241 * @param[in] n_independent_variables The number of independent variables
1242 * that will be used in the definition of the functions that it is
1243 * desired to compute the sensitivities of. In the computation of
1244 * $\Psi(\mathbf{X})$, this will be the number of inputs
1245 * $\mathbf{X}$, i.e., the dimension of the domain space.
1246 *
1247 * @note There is only one dependent variable associated with the total
1248 * energy attributed to the local finite element. That is to say, this
1249 * class assumes that the (local) right hand side and matrix contribution
1250 * is computed from the first and second derivatives of a scalar
1251 * function $\Psi(\mathbf{X})$.
1252 */
1253 EnergyFunctional(const unsigned int n_independent_variables);
1254
1255 /**
1256 * Destructor
1257 */
1258 virtual ~EnergyFunctional() = default;
1259
1260 /** @} */
1261
1262 /**
1263 * @name Dependent variables
1264 */
1265 /** @{ */
1266
1267 /**
1268 * Register the definition of the total cell energy
1269 * $\Psi(\mathbf{X})$.
1270 *
1271 * @param[in] energy A recorded function that defines the total cell
1272 * energy. This represents the single dependent variable from which both
1273 * the residual and its linearization are to be computed.
1274 *
1275 * @note For this class that expects only a single scalar dependent
1276 * variable, this function must only be called once per tape.
1277 *
1278 * @note For taped AD numbers, this operation is only valid in recording mode.
1279 */
1280 void
1281 register_energy_functional(const ad_type &energy);
1282
1283 /**
1284 * Evaluation of the total scalar energy functional for a chosen set of
1285 * degree of freedom values, i.e.
1286 * @f[
1287 * \Psi(\mathbf{X}) \vert_{\mathbf{X}}
1288 * @f]
1289 *
1290 * The values at the evaluation point $\mathbf{X}$ are obtained by calling
1291 * CellLevelBase::set_dof_values().
1292 *
1293 * @return The value of the energy functional at the evaluation point
1294 * corresponding to a chosen set of local degree of freedom values.
1295 */
1296 scalar_type
1297 compute_energy() const;
1298
1299 /**
1300 * Evaluation of the residual for a chosen set of degree of freedom
1301 * values. Underlying this is the computation of the gradient (first
1302 * derivative) of the scalar function $\Psi$ with respect to all
1303 * independent variables, i.e.
1304 * @f[
1305 * \mathbf{r}(\mathbf{X}) =
1306 * \frac{\partial\Psi(\mathbf{X})}{\partial\mathbf{X}}
1307 * \Big\vert_{\mathbf{X}}
1308 * @f]
1309 *
1310 * The values at the evaluation point $\mathbf{X}$ are obtained by calling
1311 * CellLevelBase::set_dof_values().
1312 *
1313 * @param[out] residual A Vector object, for which the value for each
1314 * entry represents the residual value for the corresponding local
1315 * degree of freedom. The output @p residual vector has a length
1316 * corresponding to @p n_independent_variables.
1317 */
1318 void
1319 compute_residual(Vector<scalar_type> &residual) const override;
1320
1321 /**
1322 * Compute the linearization of the residual vector around a chosen set
1323 * of degree of freedom values. Underlying this is the computation of the
1324 * Hessian (second derivative) of the scalar function $\Psi$ with respect
1325 * to all independent variables, i.e.
1326 * @f[
1327 * \frac{\partial\mathbf{r}(\mathbf{X})}{\partial\mathbf{X}}
1328 * =
1329 * \frac{\partial^{2}\Psi(\mathbf{X})}{\partial\mathbf{X}
1330 * \otimes \partial\mathbf{X}} \Big\vert_{\mathbf{X}}
1331 * @f]
1332 *
1333 * The values at the evaluation point $\mathbf{X}$ are obtained by calling
1334 * CellLevelBase::set_dof_values().
1335 *
1336 * @param[out] linearization A FullMatrix representing the linearization
1337 * of the residual vector. The output @p linearization matrix has
1338 * dimensions corresponding to
1339 * <code>n_independent_variables</code>$\times$<code>n_independent_variables</code>.
1340 */
1341 virtual void
1342 compute_linearization(
1343 FullMatrix<scalar_type> &linearization) const override;
1344
1345 /** @} */
1346
1347 }; // class EnergyFunctional
1348
1349
1350
1351 /**
1352 * A helper class that facilitates the evaluation and automated
1353 * linearization of a vector of functions that represents a residual vector
1354 * (as computed from some corresponding local degree of freedom values).
1355 * This class would typically be used to compute the linearization of a
1356 * residual vector defined on the level of a cell, or for local
1357 * nonlinear equations.
1358 *
1359 * An example of its usage in the case of a residual linearization
1360 * might be as follows (in this case we'll compute the
1361 * linearization of a finite-strain magneto-elastic solid from the residual,
1362 * as constructed from the Piola-Kirchoff stress and magnetic induction
1363 * assuming the magnetic scalar potential formulation):
1364 *
1365 * @code
1366 * // Existing data structures:
1367 * Vector<double> solution (...); // Or another vector type
1368 * std::vector<types::global_dof_index> local_dof_indices (...);
1369 * const FEValuesExtractors::Vector u_fe (...);
1370 * const FEValuesExtractors::Scalar msp_fe (...);
1371 * const unsigned int u_block (...);
1372 * const unsigned int msp_block (...);
1373 * FEValues<dim> fe_values (...);
1374 * const unsigned int n_q_points (...);
1375 * FullMatrix<double> cell_matrix (...);
1376 * Vector<double> cell_rhs (...);
1377 *
1378 * // Assembly loop:
1379 * for (auto &cell : ...)
1380 * {
1381 * cell->get_dof_indices(local_dof_indices);
1382 * const unsigned int n_independent_variables
1383 * = local_dof_indices.size();
1384 * const unsigned int n_dependent_variables
1385 * = local_dof_indices.size();
1386 *
1387 * // Create some aliases for the AD helper.
1388 * // In this example, we strictly assume that we're using tapeless
1389 * // AD types, and so the AD_typecode used in the template argument
1390 * // must refer to one of these types. See the example for the
1391 * // EnergyFunctional for details on how to extend
1392 * // support to taped AD numbers.
1393 * using ADHelper = AD::ResidualLinearization<...>;
1394 * using ADNumberType = typename ADHelper::ad_type;
1395 *
1396 * // Create and initialize an instance of the helper class.
1397 * ADHelper ad_helper(n_independent_variables,n_dependent_variables);
1398 *
1399 * // Initialize the local data structures for assembly.
1400 * // This is also taken care of by the ADHelper, so this step could
1401 * // be skipped.
1402 * cell_rhs.reinit(n_dependent_variables);
1403 * cell_matrix.reinit(n_independent_variables,n_dependent_variables);
1404 *
1405 * // This next code block corresponds to the "recording" phase, where
1406 * // the operations performed with the AD numbers are tracked and
1407 * // differentiation is performed.
1408 * {
1409 * // First, we set the values for all DoFs.
1410 * ad_helper.register_dof_values(solution, local_dof_indices);
1411 *
1412 * // Then we get the complete set of degree of freedom values as
1413 * // represented by auto-differentiable numbers.
1414 * const std::vector<ADNumberType> dof_values_ad
1415 * = ad_helper.get_sensitive_dof_values();
1416 *
1417 * // Then we do some problem specific tasks, the first being to
1418 * // compute all values, gradients, etc. based on sensitive AD DoF
1419 * // values. Here we are fetching the displacement gradients at each
1420 * // quadrature point, as well as the gradients of the magnetic
1421 * // scalar potential field.
1422 * std::vector<Tensor<2, dim, ADNumberType>> Grad_u(
1423 * n_q_points, Tensor<2, dim, ADNumberType>());
1424 * std::vector<Tensor<1, dim, ADNumberType>> Grad_msp(
1425 * n_q_points, Tensor<1, dim, ADNumberType>());
1426 * fe_values[u_fe].get_function_gradients_from_local_dof_values(
1427 * dof_values_ad, Grad_u);
1428 * fe_values[msp_fe].get_function_gradients_from_local_dof_values(
1429 * dof_values_ad, Grad_msp);
1430 *
1431 * // This variable stores the cell residual vector contributions.
1432 * // IMPORTANT: Note that each entry is hand-initialized with a value
1433 * // of zero. This is a highly recommended practise, as some AD
1434 * // numbers appear not to safely initialize their internal data
1435 * // structures.
1436 * std::vector<ADNumberType> residual_ad (
1437 * n_dependent_variables, ADNumberType(0.0));
1438 *
1439 * // Compute the cell total residual
1440 * // = (internal + external) contributions
1441 * for (unsigned int q_point = 0; q_point < n_q_points; ++q_point)
1442 * {
1443 * // Calculate the deformation gradient and magnetic field at this
1444 * // quadrature point
1445 * const Tensor<2, dim, ADNumberType> F =
1446 * unit_symmetric_tensor<dim>() + Grad_u[q_point];
1447 * const Tensor<1, dim, ADNumberType> H = -Grad_msp[q_point];
1448 * Assert(numbers::value_is_greater_than(determinant(F), 0.0),
1449 * ExcMessage("Negative determinant of the deformation "
1450 * "gradient detected!"));
1451 *
1452 * // Extract some configuration dependent variables from our
1453 * // nonlinear constitutive law for the current quadrature point.
1454 * // In this way they only have to be computed once per quadrature
1455 * // point.
1456 * const SymmetricTensor<2,dim,ad_type> S = get_S(F,H);
1457 * const Tensor<1,dim,ad_type> B = get_B(F,H);
1458 *
1459 * // Define some position-dependent aliases, to make the assembly
1460 * // process easier to follow.
1461 * const double JxW = fe_values.JxW(q_point);
1462 *
1463 * // Add contribution of the internal forces:
1464 * // Note that we assemble the residual contribution directly
1465 * // as it is this vector that is to be automatically linearized.
1466 * for (unsigned int I = 0; I < n_dofs_per_cell; ++I)
1467 * {
1468 * // Determine the component and block associated with
1469 * // the I'th local degree of freedom.
1470 * const unsigned int block_I =
1471 * fe.system_to_base_index(I).first.first;
1472 *
1473 * if (block_I == u_block) // u-terms
1474 * {
1475 * // Variation of the Green-Lagrange strain tensor
1476 * // associated with the I'th vector-valued basis function.
1477 * const SymmetricTensor<2,dim,double> dE_I
1478 * = symmetrize(transpose(F)
1479 * * fe_values[u_fe].gradient(I,q_point));
1480 *
1481 * residual_ad[I] += (dE_I*S) * JxW;
1482 * }
1483 * else if (block_I == msp_block)
1484 * {
1485 * // Variation of the magnetic field vector associated with
1486 * // the I'th scalar-valued basis function
1487 * const Tensor<1,dim,double> dH_I
1488 * = -fe_values[msp_fe].gradient(I, q_point);
1489 *
1490 * residual_ad[I] -= (dH_I*B) * JxW;
1491 * }
1492 * }
1493 * }
1494 *
1495 * // Add contribution from external sources. If these contributions
1496 * // are also solution dependent then they will also be consistently
1497 * // linearized.
1498 * // Loop over faces and accumulate external contributions into the
1499 * // cell total residual.
1500 * for (const unsigned int face : ...)
1501 * if (cell->face(face)->at_boundary())
1502 * residual_ad[I] += ...
1503 *
1504 * // Register the definition of the cell residual
1505 * ad_helper.register_residual_vector(residual_ad);
1506 * }
1507 *
1508 * // Compute the residual values and their Jacobian at the
1509 * // evaluation point
1510 * ad_helper.compute_residual(cell_rhs);
1511 * cell_rhs *= -1.0; // RHS = - residual
1512 * ad_helper.compute_linearization(cell_matrix);
1513 * }
1514 * @endcode
1515 *
1516 * In most use cases, and in particular in the code example shown above,
1517 * both the number of independent and dependent variables equals the
1518 * number of <code>dofs_per_cell</code> for the used finite element.
1519 *
1520 * @warning ADOL-C does not support the standard threading models used by
1521 * deal.II, so this class should @b not be embedded within a multithreaded
1522 * function when using ADOL-C number types. It is, however, suitable for use
1523 * in both serial and MPI routines.
1524 */
1525 template <enum AD::NumberTypes ADNumberTypeCode,
1526 typename ScalarType = double>
1527 class ResidualLinearization
1528 : public CellLevelBase<ADNumberTypeCode, ScalarType>
1529 {
1530 public:
1531 /**
1532 * Type definition for the floating point number type that is used in,
1533 * and results from, all computations.
1534 */
1535 using scalar_type =
1536 typename HelperBase<ADNumberTypeCode, ScalarType>::scalar_type;
1537
1538 /**
1539 * Type definition for the auto-differentiation number type that is used
1540 * in all computations.
1541 */
1542 using ad_type =
1543 typename HelperBase<ADNumberTypeCode, ScalarType>::ad_type;
1544
1545 /**
1546 * @name Constructor / destructor
1547 */
1548 /** @{ */
1549
1550 /**
1551 * The constructor for the class.
1552 *
1553 * @param[in] n_independent_variables The number of independent variables
1554 * that will be used in the definition of the functions that it is
1555 * desired to compute the sensitivities of. In the computation of
1556 * $\mathbf{r}(\mathbf{X})$, this will be the number of inputs
1557 * $\mathbf{X}$, i.e., the dimension of the domain space.
1558 * @param[in] n_dependent_variables The number of scalar functions to be
1559 * defined that will have a sensitivity to the given independent
1560 * variables. In the computation of $\mathbf{r}(\mathbf{X})$, this will
1561 * be the number of outputs $\mathbf{r}$, i.e., the dimension of the
1562 * image space.
1563 */
1564 ResidualLinearization(const unsigned int n_independent_variables,
1565 const unsigned int n_dependent_variables);
1566
1567 /**
1568 * Destructor
1569 */
1570 virtual ~ResidualLinearization() = default;
1571
1572 /** @} */
1573
1574 /**
1575 * @name Dependent variables
1576 */
1577 /** @{ */
1578
1579 /**
1580 * Register the definition of the cell residual vector
1581 * $\mathbf{r}(\mathbf{X})$.
1582 *
1583 * @param[in] residual A vector of recorded functions that defines the
1584 * residual. The components of this vector represents the dependent
1585 * variables.
1586 *
1587 * @note For this class that expects only vector fields of dependent
1588 * variables, this function must only be called once per tape.
1589 *
1590 * @note For taped AD numbers, this operation is only valid in recording mode.
1591 */
1592 void
1593 register_residual_vector(const std::vector<ad_type> &residual);
1594
1595 /**
1596 * Evaluation of the residual for a chosen set of degree of freedom
1597 * values. This corresponds to the computation of the residual vector,
1598 * i.e.
1599 * @f[
1600 * \mathbf{r}(\mathbf{X}) \vert_{\mathbf{X}}
1601 * @f]
1602 *
1603 * The values at the evaluation point $\mathbf{X}$ are obtained by calling
1604 * CellLevelBase::set_dof_values().
1605 *
1606 * @param[out] residual A Vector object, for which the value for each
1607 * entry represents the residual value for the corresponding local
1608 * degree of freedom. The output @p residual vector has a length
1609 * corresponding to @p n_dependent_variables.
1610 */
1611 virtual void
1612 compute_residual(Vector<scalar_type> &residual) const override;
1613
1614 /**
1615 * Compute the linearization of the residual vector around a chosen set
1616 * of degree of freedom values. Underlying this is the computation of the
1617 * gradient (first derivative) of the residual vector $\mathbf{r}$ with
1618 * respect to all independent variables, i.e.
1619 * @f[
1620 * \frac{\partial\mathbf{r}(\mathbf{X})}{\partial\mathbf{X}}
1621 * @f]
1622 *
1623 * The values at the evaluation point $\mathbf{X}$ are obtained by calling
1624 * CellLevelBase::set_dof_values().
1625 *
1626 * @param[out] linearization A FullMatrix representing the linearization
1627 * of the residual vector. The output @p linearization matrix has
1628 * dimensions corresponding to
1629 * <code>n_dependent_variables</code>$\times$<code>n_independent_variables</code>.
1630 */
1631 virtual void
1632 compute_linearization(
1633 FullMatrix<scalar_type> &linearization) const override;
1634
1635 /** @} */
1636
1637 }; // class ResidualLinearization
1638
1639
1640
1641 namespace internal
1642 {
1643 /**
1644 * A helper struct that assists with the extraction of data associated
1645 * with fields that are defined by FEExtractors.
1646 */
1647 template <int dim, typename ExtractorType>
1648 struct Extractor;
1649
1650
1651 /**
1652 * A helper struct that assists with the extraction of data associated
1653 * with fields that are defined by FEExtractors.
1654 * This particular specialization is for scalar fields.
1655 */
1656 template <int dim>
1657 struct Extractor<dim, FEValuesExtractors::Scalar>
1658 {
1659 /**
1660 * The number of components of the field.
1661 */
1662 static const unsigned int n_components = 1;
1663
1664 /**
1665 * The tensor rank of the field.
1666 */
1667 static const unsigned int rank = 0;
1668
1669 /**
1670 * The tensor type associated with this field.
1671 */
1672 template <typename NumberType>
1673 using tensor_type = Tensor<rank, dim, NumberType>;
1674
1675 static_assert(
1676 n_components == tensor_type<double>::n_independent_components,
1677 "The number of components doesn't match that of the corresponding tensor type.");
1678 static_assert(
1679 rank == tensor_type<double>::rank,
1680 "The rank doesn't match that of the corresponding tensor type.");
1681
1682 /**
1683 * The value type associated with this field.
1684 */
1685 // Note: FEValuesViews::Scalar::tensor_type is double, so we can't
1686 // use it (FEValuesViews) in this context.
1687 // In fact, sadly, all FEValuesViews objects expect doubles as value
1688 // types.
1689 template <typename NumberType>
1690 using value_type = NumberType;
1691
1692 /**
1693 * The gradient type associated with this field.
1694 */
1695 template <typename NumberType>
1696 using gradient_type = Tensor<rank + 1, dim, NumberType>; // NumberType;
1697
1698 /**
1699 * Return the first global component of this field.
1700 */
1701 static inline unsigned int
1702 first_component(const FEValuesExtractors::Scalar &extractor)
1703 {
1704 return extractor.component;
1705 }
1706
1707 /**
1708 * Return a flag that indicates if the input @p unrolled_index
1709 * corresponds to a symmetric component of the field.
1710 *
1711 * For a scalar field, the single component is defined
1712 * to not have a symmetric counterpart.
1713 */
1714 static bool
1715 symmetric_component(const unsigned int unrolled_index)
1716 {
1717 (void)unrolled_index;
1718 return false;
1719 }
1720
1721 /**
1722 * Return the local unrolled component corresponding to
1723 * @p column_offset entry of the @p table_indices.
1724 *
1725 * For a scalar field, the local component is always
1726 * equal to zero.
1727 */
1728 template <typename IndexType = unsigned int, int rank_in>
1729 static IndexType
1730 local_component(const TableIndices<rank_in> &table_indices,
1731 const unsigned int column_offset)
1732 {
1733 Assert(column_offset <= rank_in, ExcInternalError());
1734 (void)table_indices;
1735 (void)column_offset;
1736 return 0;
1737 }
1738 };
1739
1740
1741 /**
1742 * A helper struct that assists with the extraction of data associated
1743 * with fields that are defined by FEExtractors.
1744 * This particular specialization is for vector fields.
1745 */
1746 template <int dim>
1747 struct Extractor<dim, FEValuesExtractors::Vector>
1748 {
1749 /**
1750 * The number of components of the field.
1751 */
1752 static const unsigned int n_components = dim;
1753
1754 /**
1755 * The tensor rank of the field.
1756 */
1757 static const unsigned int rank = 1;
1758
1759 /**
1760 * The tensor type associated with this field.
1761 */
1762 template <typename NumberType>
1763 using tensor_type = Tensor<rank, dim, NumberType>;
1764
1765 static_assert(
1766 n_components == tensor_type<double>::n_independent_components,
1767 "The number of components doesn't match that of the corresponding tensor type.");
1768 static_assert(
1769 rank == tensor_type<double>::rank,
1770 "The rank doesn't match that of the corresponding tensor type.");
1771
1772 /**
1773 * The value type associated with this field.
1774 */
1775 template <typename NumberType>
1776 using value_type = tensor_type<NumberType>;
1777
1778 /**
1779 * The gradient type associated with this field.
1780 */
1781 template <typename NumberType>
1782 using gradient_type = Tensor<rank + 1, dim, NumberType>;
1783
1784 /**
1785 * Return the first global component of this field.
1786 */
1787 static inline unsigned int
1788 first_component(const FEValuesExtractors::Vector &extractor)
1789 {
1790 return extractor.first_vector_component;
1791 }
1792
1793 /**
1794 *
1795 * Return a flag that indicates if the input @p unrolled_index
1796 * corresponds to a symmetric component of the field.
1797 *
1798 * For a vector field, the none of the vector components
1799 * have a symmetric counterpart.
1800 */
1801 static bool
1802 symmetric_component(const unsigned int unrolled_index)
1803 {
1804 (void)unrolled_index;
1805 return false;
1806 }
1807
1808 /**
1809 * Return the table index corresponding to
1810 * @p column_offset entry of the input @p table_indices.
1811 */
1812 template <int rank_in>
1813 static TableIndices<rank>
1814 table_index_view(const TableIndices<rank_in> &table_indices,
1815 const unsigned int column_offset)
1816 {
1817 Assert(0 + column_offset < rank_in, ExcInternalError());
1818 return TableIndices<rank>(table_indices[column_offset]);
1819 }
1820
1821 /**
1822 * Return the local unrolled component corresponding to
1823 * @p column_offset entry of the @p table_indices.
1824 *
1825 * This function computes and returns a local component
1826 * associated with the extractor's @p tensor_type from a
1827 * set of @p table_indices that are generally associated
1828 * with a tensor of equal or greater order. In effect, it
1829 * creates a view of a selected number of indices of the
1830 * input table, and interprets that subtable's indices as
1831 * the local index to be returned. Since the @p table_indices
1832 * may be of size greater than the extractor's @p rank,
1833 * the @p column_offset specifies the first index of the
1834 * input table to create the view from.
1835 */
1836 template <typename IndexType = unsigned int, int rank_in>
1837 static IndexType
1838 local_component(const TableIndices<rank_in> &table_indices,
1839 const unsigned int column_offset)
1840 {
1841 static_assert(
1842 rank_in >= rank,
1843 "Cannot extract more table indices than the input table has!");
1844 using TensorType = tensor_type<double>;
1845 return TensorType::component_to_unrolled_index(
1846 table_index_view(table_indices, column_offset));
1847 }
1848 };
1849
1850
1851 /**
1852 * A helper struct that assists with the extraction of data associated
1853 * with fields that are defined by FEExtractors.
1854 * This particular specialization is for rank-1 tensor fields.
1855 */
1856 template <int dim>
1857 struct Extractor<dim, FEValuesExtractors::Tensor<1>>
1858 {
1859 /**
1860 * The number of components of the field.
1861 */
1862 static const unsigned int n_components =
1863 Tensor<1, dim>::n_independent_components;
1864
1865 /**
1866 * The tensor rank of the field.
1867 */
1868 static const unsigned int rank = 1;
1869
1870 /**
1871 * The tensor type associated with this field.
1872 */
1873 template <typename NumberType>
1874 using tensor_type = Tensor<rank, dim, NumberType>;
1875
1876 /**
1877 * The value type associated with this field.
1878 */
1879 template <typename NumberType>
1880 using value_type = tensor_type<NumberType>;
1881
1882 /**
1883 * The gradient type associated with this field.
1884 */
1885 template <typename NumberType>
1886 using gradient_type = Tensor<rank + 1, dim, NumberType>;
1887
1888 /**
1889 * Return the first global component of this field.
1890 */
1891 static inline unsigned int
1892 first_component(const FEValuesExtractors::Tensor<1> &extractor)
1893 {
1894 return extractor.first_tensor_component;
1895 }
1896
1897 /**
1898 * Return a flag that indicates if the input @p unrolled_index
1899 * corresponds to a symmetric component of the field.
1900 *
1901 * For a vector field, the none of the vector components
1902 * have a symmetric counterpart.
1903 */
1904 static bool
1905 symmetric_component(const unsigned int unrolled_index)
1906 {
1907 (void)unrolled_index;
1908 return false;
1909 }
1910
1911 /**
1912 * Return the table index corresponding to
1913 * @p column_offset entry of the input @p table_indices.
1914 */
1915 template <int rank_in>
1916 static TableIndices<rank>
1917 table_index_view(const TableIndices<rank_in> &table_indices,
1918 const unsigned int column_offset)
1919 {
1920 Assert(column_offset < rank_in, ExcInternalError());
1921 return TableIndices<rank>(table_indices[column_offset]);
1922 }
1923
1924 /**
1925 * Return the local unrolled component corresponding to
1926 * a subset of table indices from the input @p table_indices.
1927 *
1928 * This function computes and returns a local component
1929 * associated with the extractor's @p tensor_type from a
1930 * set of @p table_indices that are generally associated
1931 * with a tensor of equal or greater order. In effect, it
1932 * creates a view of a selected number of indices of the
1933 * input table, and interprets that subtable's indices as
1934 * the local index to be returned. Since the @p table_indices
1935 * may be of size greater than the extractor's @p rank,
1936 * the @p column_offset specifies the first index of the
1937 * input table to create the view from.
1938 */
1939 template <typename IndexType = unsigned int, int rank_in>
1940 static IndexType
1941 local_component(const TableIndices<rank_in> &table_indices,
1942 const unsigned int column_offset)
1943 {
1944 static_assert(
1945 rank_in >= rank,
1946 "Cannot extract more table indices than the input table has!");
1947 using TensorType = tensor_type<double>;
1948 return TensorType::component_to_unrolled_index(
1949 table_index_view(table_indices, column_offset));
1950 }
1951 };
1952
1953
1954 /**
1955 * A helper struct that assists with the extraction of data associated
1956 * with fields that are defined by FEExtractors.
1957 * This particular specialization is for rank-2 tensor fields.
1958 */
1959 template <int dim>
1960 struct Extractor<dim, FEValuesExtractors::Tensor<2>>
1961 {
1962 /**
1963 * The number of components of the field.
1964 */
1965 static const unsigned int n_components =
1966 Tensor<2, dim>::n_independent_components;
1967
1968 /**
1969 * The tensor rank of the field.
1970 */
1971 static const unsigned int rank = Tensor<2, dim>::rank;
1972
1973 /**
1974 * The tensor type associated with this field.
1975 */
1976 template <typename NumberType>
1977 using tensor_type = Tensor<rank, dim, NumberType>;
1978
1979 /**
1980 * The value type associated with this field.
1981 */
1982 template <typename NumberType>
1983 using value_type = tensor_type<NumberType>;
1984
1985 /**
1986 * The gradient type associated with this field.
1987 */
1988 template <typename NumberType>
1989 using gradient_type = Tensor<rank + 1, dim, NumberType>;
1990
1991 /**
1992 * Return the first global component of this field.
1993 */
1994 static inline unsigned int
1995 first_component(const FEValuesExtractors::Tensor<2> &extractor)
1996 {
1997 return extractor.first_tensor_component;
1998 }
1999
2000 /**
2001 * Return a flag that indicates if the input @p unrolled_index
2002 * corresponds to a symmetric component of the field.
2003 *
2004 * For a rank-2 tensor field, the none of the tensor
2005 * components have a symmetric counterpart.
2006 */
2007 static bool
2008 symmetric_component(const unsigned int unrolled_index)
2009 {
2010 (void)unrolled_index;
2011 return false;
2012 }
2013
2014 /**
2015 * Return the table indices corresponding to
2016 * @p column_offset entry of the input @p table_indices.
2017 */
2018 template <int rank_in>
2019 static TableIndices<rank>
2020 table_index_view(const TableIndices<rank_in> &table_indices,
2021 const unsigned int column_offset)
2022 {
2023 Assert(column_offset < rank_in, ExcInternalError());
2024 Assert(column_offset + 1 < rank_in, ExcInternalError());
2025 return TableIndices<rank>(table_indices[column_offset],
2026 table_indices[column_offset + 1]);
2027 }
2028
2029 /**
2030 * Return the local unrolled component corresponding to
2031 * @p column_offset entry of the @p table_indices.
2032 *
2033 * This function computes and returns a local component
2034 * associated with the extractor's @p tensor_type from a
2035 * set of @p table_indices that are generally associated
2036 * with a tensor of equal or greater order. In effect, it
2037 * creates a view of a selected number of indices of the
2038 * input table, and interprets that subtable's indices as
2039 * the local index to be returned. Since the @p table_indices
2040 * may be of size greater than the extractor's @p rank,
2041 * the @p column_offset specifies the first index of the
2042 * input table to create the view from.
2043 */
2044 template <typename IndexType = unsigned int, int rank_in>
2045 static IndexType
2046 local_component(const TableIndices<rank_in> &table_indices,
2047 const unsigned int column_offset)
2048 {
2049 static_assert(
2050 rank_in >= rank,
2051 "Cannot extract more table indices than the input table has!");
2052 using TensorType = tensor_type<double>;
2053 return TensorType::component_to_unrolled_index(
2054 table_index_view(table_indices, column_offset));
2055 }
2056 };
2057
2058
2059 /**
2060 * A helper struct that assists with the extraction of data associated
2061 * with fields that are defined by FEExtractors.
2062 * This particular specialization is for rank-2 symmetric tensor fields.
2063 */
2064 template <int dim>
2065 struct Extractor<dim, FEValuesExtractors::SymmetricTensor<2>>
2066 {
2067 /**
2068 * The number of components of the field.
2069 */
2070 static const unsigned int n_components =
2071 SymmetricTensor<2, dim>::n_independent_components;
2072
2073 /**
2074 * The tensor rank of the field.
2075 */
2076 static const unsigned int rank = SymmetricTensor<2, dim>::rank;
2077
2078 /**
2079 * The tensor type associated with this field.
2080 */
2081 template <typename NumberType>
2082 using tensor_type = SymmetricTensor<rank, dim, NumberType>;
2083
2084 /**
2085 * The value type associated with this field.
2086 */
2087 template <typename NumberType>
2088 using value_type = tensor_type<NumberType>;
2089
2090 /**
2091 * The gradient type associated with this field.
2092 */
2093 template <typename NumberType>
2094 using gradient_type = Tensor<rank + 1, dim, NumberType>;
2095
2096 /**
2097 * Return the first global component of this field.
2098 */
2099 static inline unsigned int
2100 first_component(const FEValuesExtractors::SymmetricTensor<2> &extractor)
2101 {
2102 return extractor.first_tensor_component;
2103 }
2104
2105 /**
2106 * Return a flag that indicates if the input @p unrolled_index
2107 * corresponds to a symmetric component of the field.
2108 *
2109 * For a rank-2 symmetric tensor field, each of the
2110 * off-diagonal components have a symmetric counterpart,
2111 * while the diagonal components do not.
2112 */
2113 static bool
2114 symmetric_component(const unsigned int unrolled_index)
2115 {
2116 const TableIndices<2> table_indices =
2117 tensor_type<double>::unrolled_to_component_indices(unrolled_index);
2118 return table_indices[0] != table_indices[1];
2119 }
2120
2121 /**
2122 * Return the table indices corresponding to
2123 * @p column_offset entry of the input @p table_indices.
2124 */
2125 template <int rank_in>
2126 static TableIndices<rank>
2127 table_index_view(const TableIndices<rank_in> &table_indices,
2128 const unsigned int column_offset)
2129 {
2130 Assert(column_offset < rank_in, ExcInternalError());
2131 Assert(column_offset + 1 < rank_in, ExcInternalError());
2132 return TableIndices<rank>(table_indices[column_offset],
2133 table_indices[column_offset + 1]);
2134 }
2135
2136 /**
2137 * Return the local unrolled component corresponding to
2138 * @p column_offset entry of the @p table_indices.
2139 *
2140 * This function computes and returns a local component
2141 * associated with the extractor's @p tensor_type from a
2142 * set of @p table_indices that are generally associated
2143 * with a tensor of equal or greater order. In effect, it
2144 * creates a view of a selected number of indices of the
2145 * input table, and interprets that subtable's indices as
2146 * the local index to be returned. Since the @p table_indices
2147 * may be of size greater than the extractor's @p rank,
2148 * the @p column_offset specifies the first index of the
2149 * input table to create the view from.
2150 */
2151 template <typename IndexType = unsigned int, int rank_in>
2152 static IndexType
2153 local_component(const TableIndices<rank_in> &table_indices,
2154 const unsigned int column_offset)
2155 {
2156 static_assert(
2157 rank_in >= rank,
2158 "Cannot extract more table indices than the input table has!");
2159 using TensorType = tensor_type<double>;
2160 return TensorType::component_to_unrolled_index(
2161 table_index_view(table_indices, column_offset));
2162 }
2163 };
2164
2165
2166 /**
2167 * A helper struct that defines the return type of gradient (first
2168 * derivative) calculations of scalar fields with respect to a field
2169 * defined by the @p ExtractorType template parameter.
2170 */
2171 template <int dim, typename NumberType, typename ExtractorType>
2172 struct ScalarFieldGradient
2173 {
2174 /**
2175 * The type associated with computing the gradient of a scalar
2176 * field with respect to the given @p ExtractorType.
2177 */
2178 using type =
2179 typename Extractor<dim,
2180 ExtractorType>::template tensor_type<NumberType>;
2181 };
2182
2183
2184 /**
2185 * An intermediate helper struct that defines the return type of Hessian
2186 * (second derivative) calculations of scalar fields with respect to
2187 * fields defined by the two extractor-type template parameters.
2188 * The first, @p ExtractorType_Row, defines the field that the first
2189 * derivatives are taken with respect to while the second,
2190 * @p ExtractorType_Col, defines the field that the second derivatives
2191 * are taken with respect to.
2192 */
2193 template <typename ExtractorType_Row, typename ExtractorType_Col>
2194 struct HessianType
2195 {
2196 /**
2197 * The type associated with computing the gradient of a scalar
2198 * field with respect to the given @p ExtractorType_Row
2199 * followed by the @p ExtractorType_Col.
2200 *
2201 * @note We set the return type for
2202 * HessianType<FEExtractor::Vector,FEExtractor::Vector>
2203 * as a normal Tensor. This is because if one has two vector components,
2204 * the coupling tensor (i.e. Hessian component<FE::V_1,FE::V_2>) is in
2205 * general not symmetric.
2206 */
2207 template <int rank, int dim, typename NumberType>
2208 using type = Tensor<rank, dim, NumberType>;
2209 };
2210
2211
2212 /**
2213 * An intermediate helper struct that defines the return type of Hessian
2214 * (second derivative) calculations of scalar fields with respect to
2215 * fields defined by the two extractor-type template parameters. This
2216 * particular specialization is for taking the first derivative with
2217 * respect to a symmetric tensor field, and the second with respect to a
2218 * scalar field.
2219 */
2220 template <>
2221 struct HessianType<FEValuesExtractors::SymmetricTensor<2>,
2222 FEValuesExtractors::Scalar>
2223 {
2224 /**
2225 * The type associated with computing the gradient of a scalar
2226 * field with respect to the given
2227 * <code>ExtractorType_Row =
2228 * FEValuesExtractors::SymmetricTensor<2></code> followed by the
2229 * <code>ExtractorType_Col = FEValuesExtractors::Scalar</code>.
2230 */
2231 template <int /*rank*/, int dim, typename NumberType>
2232 using type = SymmetricTensor<2 /*rank*/, dim, NumberType>;
2233 };
2234
2235
2236 /**
2237 * An intermediate helper struct that defines the return type of Hessian
2238 * (second derivative) calculations of scalar fields with respect to
2239 * fields defined by the two extractor-type template parameters. This
2240 * particular specialization is for taking the first derivative with
2241 * respect to a scalar field, and the second with respect to a symmetric
2242 * tensor field.
2243 */
2244 template <>
2245 struct HessianType<FEValuesExtractors::Scalar,
2246 FEValuesExtractors::SymmetricTensor<2>>
2247 {
2248 /**
2249 * The type associated with computing the gradient of a scalar
2250 * field with respect to the given
2251 * <code>ExtractorType_Row = FEValuesExtractors::Scalar</code>
2252 * followed by the
2253 * <code>ExtractorType_Col =
2254 * FEValuesExtractors::SymmetricTensor<2></code>.
2255 */
2256 template <int /*rank*/, int dim, typename NumberType>
2257 using type = SymmetricTensor<2 /*rank*/, dim, NumberType>;
2258 };
2259
2260
2261 /**
2262 * An intermediate helper struct that defines the return type of Hessian
2263 * (second derivative) calculations of scalar fields with respect to
2264 * fields defined by the two extractor-type template parameters. This
2265 * particular specialization is for taking both the first and second
2266 * derivatives with respect to symmetric tensor fields.
2267 */
2268 template <>
2269 struct HessianType<FEValuesExtractors::SymmetricTensor<2>,
2270 FEValuesExtractors::SymmetricTensor<2>>
2271 {
2272 /**
2273 * The type associated with computing the gradient of a scalar
2274 * field with respect to the given
2275 * <code>ExtractorType_Row =
2276 * FEValuesExtractors::SymmetricTensor<2></code> followed by the
2277 * <code>ExtractorType_Col =
2278 * FEValuesExtractors::SymmetricTensor<2></code>.
2279 */
2280 template <int /*rank*/, int dim, typename NumberType>
2281 using type = SymmetricTensor<4 /*rank*/, dim, NumberType>;
2282 };
2283
2284
2285 /**
2286 * A helper struct that defines the final return type of Hessian
2287 * (second derivative) calculations of scalar fields with respect to
2288 * fields defined by the two extractor-type
2289 * template parameters. The first, @p ExtractorType_Row, defines the field
2290 * that the first derivatives are taken with respect to while the second,
2291 * @p ExtractorType_Col, defines the field that the second derivatives
2292 * are taken with respect to.
2293 */
2294 template <int dim,
2295 typename NumberType,
2296 typename ExtractorType_Row,
2297 typename ExtractorType_Col>
2298 struct ScalarFieldHessian
2299 {
2300 /**
2301 * The tensor rank of the resulting derivative computation.
2302 */
2303 static const int rank = Extractor<dim, ExtractorType_Row>::rank +
2304 Extractor<dim, ExtractorType_Col>::rank;
2305
2306 /**
2307 * The type associated with computing the Hessian of a scalar
2308 * field with first respect to the field defined by the
2309 * @p ExtractorType_Row and then with respect to the field defined by
2310 * the @p ExtractorType_Col.
2311 */
2312 using type =
2313 typename HessianType<ExtractorType_Row, ExtractorType_Col>::
2314 template type<rank, dim, NumberType>;
2315 };
2316
2317
2318 /**
2319 * A helper struct that defines the return type of value computations
2320 * of vector fields the @p ExtractorType_Field template parameter.
2321 */
2322 template <int dim, typename NumberType, typename ExtractorType_Field>
2323 using VectorFieldValue =
2324 ScalarFieldGradient<dim, NumberType, ExtractorType_Field>;
2325
2326
2327 /**
2328 * A helper struct that defines the final return type of Jacobian
2329 * (first derivative) calculations of vector fields with respect to
2330 * fields as defined by the two extractor-type template parameters.
2331 * The first, @p ExtractorType_Field, defines the field from which
2332 * the initial field values are computed while the second,
2333 * @p ExtractorType_Derivative, defines the field that the derivatives
2334 * are taken with respect to.
2335 */
2336 template <int dim,
2337 typename NumberType,
2338 typename ExtractorType_Field,
2339 typename ExtractorType_Derivative>
2340 using VectorFieldJacobian = ScalarFieldHessian<dim,
2341 NumberType,
2342 ExtractorType_Field,
2343 ExtractorType_Derivative>;
2344
2345
2346 /**
2347 * Return a global view of the field component indices that correspond to
2348 * the input @p extractor. For this general function the
2349 * @p ignore_symmetries flag has no effect.
2350 */
2351 template <int dim,
2352 typename IndexType = unsigned int,
2353 typename ExtractorType>
2354 std::vector<IndexType>
2355 extract_field_component_indices(const ExtractorType &extractor,
2356 const bool ignore_symmetries = true)
2357 {
2358 (void)ignore_symmetries;
2359 const IndexType n_components =
2360 internal::Extractor<dim, ExtractorType>::n_components;
2361 const IndexType comp_first =
2362 internal::Extractor<dim, ExtractorType>::first_component(extractor);
2363 std::vector<IndexType> indices(n_components);
2364 std::iota(indices.begin(), indices.end(), comp_first);
2365 return indices;
2366 }
2367
2368
2369 /**
2370 * Return a global view of the field component indices that correspond to
2371 * the input FEValuesExtractors::SymmetricTensor @p extractor_symm_tensor.
2372 * If the @p ignore_symmetries is set <code>true</code>, then all
2373 * component of the tensor are considered to be independent. If set to
2374 * <code>false</code>, then the set of returned indices will contain
2375 * duplicate entries for components that are symmetric.
2376 */
2377 template <int dim, typename IndexType = unsigned int>
2378 std::vector<IndexType>
2379 extract_field_component_indices(
2380 const FEValuesExtractors::SymmetricTensor<2> &extractor_symm_tensor,
2381 const bool ignore_symmetries = true)
2382 {
2383 using ExtractorType = FEValuesExtractors::SymmetricTensor<2>;
2384 const IndexType n_components =
2385 internal::Extractor<dim, ExtractorType>::n_components;
2386 const IndexType comp_first =
2387 internal::Extractor<dim, ExtractorType>::first_component(
2388 extractor_symm_tensor);
2389
2390 if (ignore_symmetries == true)
2391 {
2392 std::vector<IndexType> indices(n_components);
2393 std::iota(indices.begin(), indices.end(), comp_first);
2394 return indices;
2395 }
2396 else
2397 {
2398 // First get all of the indices of the non-symmetric tensor
2399 const FEValuesExtractors::Tensor<2> extractor_tensor(
2400 extractor_symm_tensor.first_tensor_component);
2401 std::vector<IndexType> indices =
2402 extract_field_component_indices<dim>(extractor_tensor, true);
2403
2404 // Then we overwrite any illegal entries with the equivalent indices
2405 // from the symmetric tensor
2406 for (unsigned int i = 0; i < indices.size(); ++i)
2407 {
2408 // The indices stored in the vector start with the extractor's
2409 // first_component_index. We need to account for this when
2410 // retrieving the tensor (local) index.
2411 const IndexType local_index_i = indices[i] - comp_first;
2412 if (local_index_i >= n_components)
2413 {
2414 const TableIndices<2> ti_tensor =
2415 Tensor<2, dim>::unrolled_to_component_indices(
2416 local_index_i);
2417 const IndexType sti_new_index =
2418 SymmetricTensor<2, dim>::component_to_unrolled_index(
2419 ti_tensor);
2420 indices[i] = comp_first + sti_new_index;
2421 }
2422 }
2423
2424 return indices;
2425 }
2426 }
2427
2428
2429 /**
2430 * Set the unrolled component given by @p index in the generic tensor
2431 * @p t to the given @p value.
2432 */
2433 template <typename TensorType, typename NumberType>
2434 inline void
2435 set_tensor_entry(TensorType &t,
2436 const unsigned int unrolled_index,
2437 const NumberType &value)
2438 {
2439 // Where possible, set values using TableIndices
2440 AssertIndexRange(unrolled_index, t.n_independent_components);
2441 t[TensorType::unrolled_to_component_indices(unrolled_index)] = value;
2442 }
2443
2444
2445 /**
2446 * Set the unrolled component given by @p index in the rank-0 tensor
2447 * @p t to the given @p value.
2448 */
2449 template <int dim, typename NumberType>
2450 inline void
2451 set_tensor_entry(Tensor<0, dim, NumberType> &t,
2452 const unsigned int unrolled_index,
2453 const NumberType &value)
2454 {
2455 AssertIndexRange(unrolled_index, 1);
2456 (void)unrolled_index;
2457 t = value;
2458 }
2459
2460
2461 /**
2462 * Set the value of @p t to the given @p value.
2463 * This function exists to provide compatibility with similar functions
2464 * that exist for use with the tensor classes.
2465 */
2466 template <typename NumberType>
2467 inline void
2468 set_tensor_entry(NumberType &t,
2469 const unsigned int unrolled_index,
2470 const NumberType &value)
2471 {
2472 AssertIndexRange(unrolled_index, 1);
2473 (void)unrolled_index;
2474 t = value;
2475 }
2476
2477
2478 /**
2479 * Set the unrolled component given by the @p index_row and
2480 * the @p index_col in the fourth-order symmetric tensor
2481 * @p t to the given @p value.
2482 */
2483 template <int dim, typename NumberType>
2484 inline void
2485 set_tensor_entry(SymmetricTensor<4, dim, NumberType> &t,
2486 const unsigned int unrolled_index_row,
2487 const unsigned int unrolled_index_col,
2488 const NumberType &value)
2489 {
2490 // Fourth order symmetric tensors require a specialized interface
2491 // to extract values.
2492 using SubTensorType = SymmetricTensor<2, dim, NumberType>;
2493 AssertIndexRange(unrolled_index_row,
2494 SubTensorType::n_independent_components);
2495 AssertIndexRange(unrolled_index_col,
2496 SubTensorType::n_independent_components);
2497 const TableIndices<2> indices_row =
2498 SubTensorType::unrolled_to_component_indices(unrolled_index_row);
2499 const TableIndices<2> indices_col =
2500 SubTensorType::unrolled_to_component_indices(unrolled_index_col);
2501 t[indices_row[0]][indices_row[1]][indices_col[0]][indices_col[1]] =
2502 value;
2503 }
2504
2505
2506 /**
2507 * Return the value of the @p index'th unrolled component of the
2508 * generic tensor @p t.
2509 */
2510 template <int rank,
2511 int dim,
2512 typename NumberType,
2513 template <int, int, typename>
2514 class TensorType>
2515 inline NumberType
2516 get_tensor_entry(const TensorType<rank, dim, NumberType> &t,
2517 const unsigned int unrolled_index)
2518 {
2519 // Where possible, get values using TableIndices
2520 AssertIndexRange(unrolled_index, t.n_independent_components);
2521 return t[TensorType<rank, dim, NumberType>::
2522 unrolled_to_component_indices(unrolled_index)];
2523 }
2524
2525
2526 /**
2527 * Return the value of the @p index'th unrolled component of the
2528 * rank-0 tensor @p t.
2529 */
2530 template <int dim,
2531 typename NumberType,
2532 template <int, int, typename>
2533 class TensorType>
2534 inline NumberType
2535 get_tensor_entry(const TensorType<0, dim, NumberType> &t,
2536 const unsigned int unrolled_index)
2537 {
2538 AssertIndexRange(unrolled_index, 1);
2539 (void)unrolled_index;
2540 return t;
2541 }
2542
2543
2544 /**
2545 * Return the value of @p t.
2546 * This function exists to provide compatibility with similar functions
2547 * that exist for use with the tensor classes.
2548 */
2549 template <typename NumberType>
2550 inline const NumberType &
2551 get_tensor_entry(const NumberType &t, const unsigned int unrolled_index)
2552 {
2553 AssertIndexRange(unrolled_index, 1);
2554 (void)unrolled_index;
2555 return t;
2556 }
2557
2558
2559 /**
2560 * Return a reference to the entry stored in the @p index'th unrolled
2561 * component of the generic tensor @p t.
2562 */
2563 template <int rank,
2564 int dim,
2565 typename NumberType,
2566 template <int, int, typename>
2567 class TensorType>
2568 inline NumberType &
2569 get_tensor_entry(TensorType<rank, dim, NumberType> &t,
2570 const unsigned int unrolled_index)
2571 {
2572 // Where possible, get values using TableIndices
2573 AssertIndexRange(unrolled_index, t.n_independent_components);
2574 return t[TensorType<rank, dim, NumberType>::
2575 unrolled_to_component_indices(unrolled_index)];
2576 }
2577
2578
2579 /**
2580 * Return a reference to the entry stored in the @p index'th unrolled
2581 * component of the rank-0 tensor @p t.
2582 */
2583 template <int dim,
2584 typename NumberType,
2585 template <int, int, typename>
2586 class TensorType>
2587 NumberType &
2588 get_tensor_entry(TensorType<0, dim, NumberType> &t,
2589 const unsigned int index)
2590 {
2591 AssertIndexRange(index, 1);
2592 (void)index;
2593 return t;
2594 }
2595
2596
2597 /**
2598 * Return a reference to @p t.
2599 * This function exists to provide compatibility with similar functions
2600 * that exist for use with the tensor classes.
2601 */
2602 template <typename NumberType>
2603 inline NumberType &
2604 get_tensor_entry(NumberType &t, const unsigned int index)
2605 {
2606 AssertIndexRange(index, 1);
2607 (void)index;
2608 return t;
2609 }
2610
2611 } // namespace internal
2612
2613
2614
2615 /**
2616 * A base helper class that facilitates the evaluation of point-wise defined
2617 * functions. This is the point-wise counterpart of the
2618 * CellLevelBase class, and was conceived for computations at a
2619 * continuum point, or quadrature point, rather than for finite-element
2620 * level calculations. That being said, the interface to this and the
2621 * derived classes are sufficiently generic that the dependent function(s)
2622 * and their argument(s), that are the independent variables, can be
2623 * interpreted in any manner that the user may choose.
2624 *
2625 * As it offers a field-based interface, this class would
2626 * typically be used to compute the derivatives of a constitutive law
2627 * defined at a quadrature point; however, it may also be used in other
2628 * contexts, such as to compute the linearization of a set of local
2629 * nonlinear equations.
2630 *
2631 * @warning ADOL-C does not support the standard threading models used by
2632 * deal.II, so this class should @b not be embedded within a multithreaded
2633 * function when using ADOL-C number types. It is, however, suitable for use
2634 * in both serial and MPI routines.
2635 */
2636 template <int dim,
2637 enum AD::NumberTypes ADNumberTypeCode,
2638 typename ScalarType = double>
2639 class PointLevelFunctionsBase
2640 : public HelperBase<ADNumberTypeCode, ScalarType>
2641 {
2642 public:
2643 /**
2644 * Type definition for the dimension of the associated input and output
2645 * tensor types.
2646 */
2647 static constexpr unsigned int dimension = dim;
2648
2649 /**
2650 * Type definition for the floating point number type that is used in,
2651 * and results from, all computations.
2652 */
2653 using scalar_type =
2654 typename HelperBase<ADNumberTypeCode, ScalarType>::scalar_type;
2655
2656 /**
2657 * Type definition for the auto-differentiation number type that is used
2658 * in all computations.
2659 */
2660 using ad_type =
2661 typename HelperBase<ADNumberTypeCode, ScalarType>::ad_type;
2662
2663 /**
2664 * @name Constructor / destructor
2665 */
2666 /** @{ */
2667
2668 /**
2669 * The constructor for the class.
2670 *
2671 * @param[in] n_independent_variables The number of independent variables
2672 * that will be used in the definition of the functions that it is
2673 * desired to compute the sensitivities of. In the computation of
2674 * $\mathbf{f}(\mathbf{X})$, this will be the number of inputs
2675 * $\mathbf{X}$, i.e., the dimension of the domain space.
2676 * @param[in] n_dependent_variables The number of scalar functions to be
2677 * defined that will have a sensitivity to the given independent
2678 * variables. In the computation of $\mathbf{f}(\mathbf{X})$, this will
2679 * be the number of outputs $\mathbf{f}$, i.e., the dimension of the
2680 * image space.
2681 */
2682 PointLevelFunctionsBase(const unsigned int n_independent_variables,
2683 const unsigned int n_dependent_variables);
2684
2685 /**
2686 * Destructor
2687 */
2688 virtual ~PointLevelFunctionsBase() = default;
2689
2690 /** @} */
2691
2692 /**
2693 * @name Independent variables
2694 */
2695 /** @{ */
2696
2697 /**
2698 * Reset the state of the class.
2699 *
2700 * When an instance of the class is stored as a class member object
2701 * with the intention to reuse its instance, it may be necessary to reset
2702 * the state of the object before use. This is because, internally, there
2703 * is error checking performed to ensure that the correct
2704 * auto-differentiable data is being tracked and used only when
2705 * appropriate. This function clears all member data and, therefore,
2706 * allows the state of all internal flags to be safely reset to their
2707 * initial state.
2708 *
2709 * In the rare case that the number of independent or dependent variables
2710 * has changed, this can also be reconfigured by passing in the
2711 * appropriate arguments to the function.
2712 *
2713 * @param[in] n_independent_variables The number of independent variables
2714 * that will be used in the definition of the functions that it is
2715 * desired to compute the sensitivities of. In the computation of
2716 * $\mathbf{f}(\mathbf{X})$, this will be the number of inputs
2717 * $\mathbf{X}$, i.e., the dimension of the domain space.
2718 * @param[in] n_dependent_variables The number of scalar functions to be
2719 * defined that will have a sensitivity to the given independent
2720 * variables. In the computation of $\mathbf{f}(\mathbf{X})$, this will
2721 * be the number of outputs $\mathbf{f}$, i.e., the dimension of the
2722 * image space.
2723 * @param[in] clear_registered_tapes A flag that indicates the that
2724 * list of @p registered_tapes must be cleared.
2725 * If set to <tt>true</tt> then the data structure that tracks which
2726 * tapes have been recorded is cleared as well. It is then expected that
2727 * any preexisting tapes be re-recorded.
2728 *
2729 * @note This also resets the active tape number to an invalid number, and
2730 * deactivates the recording mode for taped variables.
2731 */
2732 virtual void
2733 reset(const unsigned int n_independent_variables =
2734 dealii::numbers::invalid_unsigned_int,
2735 const unsigned int n_dependent_variables =
2736 dealii::numbers::invalid_unsigned_int,
2737 const bool clear_registered_tapes = true) override;
2738
2739 /**
2740 * Register the complete set of independent variables $\mathbf{X}$.
2741 *
2742 * @param[in] values A field that defines the values of all independent
2743 * variables. When considering taped AD numbers with branching functions,
2744 * to avoid potential issues with branch switching it may be a good idea
2745 * to choose these values close or equal to those that will be later
2746 * evaluated and differentiated around.
2747 *
2748 * @note The input value type must correspond to this class's @p scalar_type.
2749 * Depending on the selected @p ADNumberTypeCode, this may or may not
2750 * correspond with the @p ScalarType prescribed as a template argument.
2751 *
2752 * @note For taped AD numbers, this operation is only valid in recording mode.
2753 */
2754 void
2755 register_independent_variables(const std::vector<scalar_type> &values);
2756
2757 /**
2758 * Register the subset of independent variables
2759 * $\mathbf{A} \subset \mathbf{X}$.
2760 *
2761 * @param[in] value A field that defines a number of independent
2762 * variables. When considering taped AD numbers with branching functions,
2763 * to avoid potential issues with branch switching it may be a good idea
2764 * to choose these values close or equal to those that will be later
2765 * evaluated and differentiated around.
2766 * @param[in] extractor An extractor associated with the input field
2767 * variables. This effectively defines which components of the global set
2768 * of independent variables this field is associated with.
2769 *
2770 * @note The input value type must correspond to this class's @p scalar_type.
2771 * Depending on the selected @p ADNumberTypeCode, this may or may not
2772 * correspond with the @p ScalarType prescribed as a template argument.
2773 *
2774 * @note The input extractor must correspond to the input @p ValueType.
2775 * So, for example, if a value is a rank-1 tensor
2776 * (i.e. of type Tensor<1,dim,scalar_type>), then the extractor must
2777 * be an FEValuesExtractors::Vector or FEValuesExtractors::Tensor<1>.
2778 *
2779 * @note This function may be repeatedly used until a call to
2780 * finalize_sensitive_independent_variables() or
2781 * get_sensitive_variables() is made.
2782 *
2783 * @note For taped AD numbers, this operation is only valid in recording mode.
2784 */
2785 template <typename ValueType, typename ExtractorType>
2786 void
2787 register_independent_variable(const ValueType &value,
2788 const ExtractorType &extractor);
2789
2790 /**
2791 * Return the complete set of independent variables as represented by
2792 * auto-differentiable numbers. These are the independent
2793 * variables $\mathbf{X}$ at which the dependent values are evaluated
2794 * and differentiated.
2795 *
2796 * This function indicates to the AD library that implements the
2797 * auto-differentiable number type that operations performed on these
2798 * numbers are to be tracked so they are considered "sensitive"
2799 * variables. This is, therefore, the set of variables with which one
2800 * would then perform computations, and based on which one can then
2801 * extract both the value of the function and its derivatives with the
2802 * member functions below. The values of the components of the returned
2803 * object are initialized to the values set with
2804 * register_independent_variable().
2805 *
2806 * @return An array of auto-differentiable type numbers.
2807 *
2808 * @note For taped AD numbers, this operation is only valid in recording mode.
2809 */
2810 const std::vector<ad_type> &
2811 get_sensitive_variables() const;
2812
2813 /*
2814 * Extract a subset of the independent variables as represented by
2815 * auto-differentiable numbers. These are the independent
2816 * variables $\mathbf{A} \subset \mathbf{X}$ at which the dependent values
2817 * are evaluated and differentiated.
2818 *
2819 * This function indicates to the AD library that implements the
2820 * auto-differentiable number type that operations performed on these
2821 * numbers are to be tracked so they are considered "sensitive"
2822 * variables. This is, therefore, the set of variables with which one
2823 * would then perform computations, and based on which one can then
2824 * extract both the value of the function and its derivatives with the
2825 * member functions below. The values of the components of the returned
2826 * object are initialized to the values set with
2827 * register_independent_variable().
2828 *
2829 * @param[in] extractor An extractor associated with the input field
2830 * variables. This effectively defines which components of the global set
2831 * of independent variables this field is associated with.
2832 * @return An object of auto-differentiable type numbers. The return type is
2833 * based on the input extractor, and will be either a scalar,
2834 * Tensor<1,dim>, Tensor<2,dim>, or SymmetricTensor<2,dim>.
2835 *
2836 * @note For taped AD numbers, this operation is only valid in recording mode.
2837 */
2838 template <typename ExtractorType>
2839 typename internal::Extractor<dim, ExtractorType>::template tensor_type<
2840 typename HelperBase<ADNumberTypeCode, ScalarType>::ad_type>
2841 get_sensitive_variables(const ExtractorType &extractor) const;
2842
2843 /** @} */
2844
2845 /**
2846 * @name Operations specific to taped mode: Reusing tapes
2847 */
2848 /** @{ */
2849
2850 /**
2851 * Set the values for the independent variables $\mathbf{X}$.
2852 *
2853 * @param[in] values A vector that defines the values of all
2854 * independent variables.
2855 *
2856 * @note The input value type must correspond to this class's @p scalar_type.
2857 * Depending on the selected @p ADNumberTypeCode, this may or may not
2858 * correspond with the @p ScalarType prescribed as a template argument.
2859 *
2860 * @note If the @p keep_independent_values flag has been set when
2861 * HelperBase::start_recording_operations() is called then the tape is
2862 * immediately usable after creation, and the values of the independent
2863 * variables set by register_independent_variables() are those at which
2864 * the function is to be evaluated. In this case, a separate call to this
2865 * function is not strictly necessary.
2866 */
2867 void
2868 set_independent_variables(const std::vector<scalar_type> &values);
2869
2870 /**
2871 * Set the values for a subset of independent variables
2872 * $\mathbf{A} \subset \mathbf{X}$.
2873 *
2874 * @param[in] value A field that defines the values of a number of
2875 * independent variables.
2876 * @param[in] extractor An extractor associated with the input field
2877 * variables. This effectively defines which components of the global set
2878 * of independent variables this field is associated with.
2879 *
2880 * @note The input value type must correspond to this class's @p scalar_type.
2881 * Depending on the selected @p ADNumberTypeCode, this may or may not
2882 * correspond with the @p ScalarType prescribed as a template argument.
2883 *
2884 * @note The input extractor must correspond to the input @p ValueType.
2885 * So, for example, if a value is a rank-1 tensor
2886 * (i.e. of type Tensor<1,dim,scalar_type>), then the extractor must
2887 * be an FEValuesExtractors::Vector or FEValuesExtractors::Tensor<1>.
2888 *
2889 * @note If the @p keep_independent_values flag has been set when
2890 * HelperBase::start_recording_operations() is called then the tape is
2891 * immediately usable after creation, and the values of the independent
2892 * variables set by register_independent_variable() are those at which the
2893 * function is to be evaluated. In this case, a separate call to this
2894 * function is not strictly necessary.
2895 */
2896 template <typename ValueType, typename ExtractorType>
2897 void
2898 set_independent_variable(const ValueType &value,
2899 const ExtractorType &extractor);
2900
2901 /** @} */
2902
2903 protected:
2904 /**
2905 * @name Independent variables
2906 */
2907 /** @{ */
2908
2909 /**
2910 * Set the actual value of the independent variable $X_{i}$.
2911 *
2912 * @param[in] index The index in the vector of independent variables.
2913 * @param[in] symmetric_component Mark whether this index relates to a
2914 * component of a field that has a symmetric counterpart
2915 * (e.g. if @p index represents an off-diagonal entry in a symmetric
2916 * tensor).
2917 * @param[in] value The value to set the index'd independent variable to.
2918 */
2919 void
2920 set_sensitivity_value(const unsigned int index,
2921 const bool symmetric_component,
2922 const scalar_type &value);
2923
2924 /**
2925 * Return whether the @p index'th independent variables is one for which
2926 * we must take into account symmetry when extracting their gradient or
2927 * Hessian values.
2928 */
2929 bool
2930 is_symmetric_independent_variable(const unsigned int index) const;
2931
2932 /**
2933 * Return the number of independent variables that have been marked as
2934 * being components of a symmetric field.
2935 */
2936 unsigned int
2937 n_symmetric_independent_variables() const;
2938
2939 /** @} */
2940
2941 private:
2942 /**
2943 * @name Independent variables
2944 */
2945 /** @{ */
2946
2947 /**
2948 * The independent variables for which we must take into account symmetry
2949 * when extracting their gradient or Hessian values.
2950 */
2951 std::vector<bool> symmetric_independent_variables;
2952
2953 /** @} */
2954
2955 }; // class PointLevelFunctionsBase
2956
2957
2958
2959 /**
2960 * A helper class that facilitates the evaluation of a scalar function,
2961 * its first derivatives (gradient), and its second derivatives (Hessian).
2962 * This class would typically be used to compute the first and second
2963 * derivatives of a <b>stored energy function</b> defined at a quadrature
2964 * point. It can also be used to compute derivatives of any other scalar
2965 * field so long as all its dependencies on the independent variables are
2966 * explicit (that is to say, no independent variables may have some implicit
2967 * dependence on one another).
2968 *
2969 * An example of its usage in the case of a multi-field constitutive law
2970 * might be as follows:
2971 * @code
2972 * // Define some extractors that will help us set independent variables
2973 * // and later get the computed values related to the dependent
2974 * // variables. Each of these extractors is related to the gradient of a
2975 * // component of the solution field (in this case, displacement and
2976 * // magnetic scalar potential). Here "C" is the right Cauchy-Green
2977 * // tensor and "H" is the magnetic field.
2978 * const FEValuesExtractors::SymmetricTensor<2> C_dofs (0);
2979 * const FEValuesExtractors::Vector H_dofs
2980 * (dealii::SymmetricTensor<2,dim>::n_independent_components);
2981 * const unsigned int n_independent_variables =
2982 * SymmetricTensor<2,dim>::n_independent_components +
2983 * Tensor<1,dim>::n_independent_components;
2984 *
2985 * // Define the helper that we will use in the AD computations for our
2986 * // scalar energy function. Note that we expect it to return values of
2987 * // type double.
2988 * ScalarFunction<dim,...> ad_helper (n_independent_variables);
2989 * using ADNumberType = typename ADHelper::ad_type;
2990 *
2991 * // Compute the fields that provide the independent values.
2992 * // When the tape is being replayed, these should be set to something
2993 * // meaningful.
2994 * const Tensor<1,dim> H = ...;
2995 * const SymmetricTensor<2,dim> C = ...;
2996 *
2997 * // If using a taped AD number, then at this point we would initiate
2998 * // taping of the expression for the material stored energy function
2999 * // for this particular set of material parameters:
3000 *
3001 * // Select a tape number to record to
3002 * const typename Types<ADNumberType>::tape_index tape_index = ...;
3003 *
3004 * // Indicate that we are about to start tracing the operations for
3005 * // function evaluation on the tape. If this tape has already been
3006 * // used (i.e. the operations are already recorded) then we
3007 * // (optionally) load the tape and reuse this data.
3008 * const bool is_recording
3009 * = ad_helper.start_recording_operations(tape_index);
3010 *
3011 * // The steps that follow in the recording phase are required for
3012 * // tapeless methods as well.
3013 * if (is_recording == true)
3014 * {
3015 * // This is the "recording" phase of the operations.
3016 *
3017 * // First, we set the values for all fields.
3018 * // These could happily be set to anything, unless the function will
3019 * // be evaluated along a branch not otherwise traversed during later
3020 * // use. For this reason, in this example instead of using some dummy
3021 * // values, we'll actually map out the function at the same point
3022 * // around which we'll later linearize it.
3023 * ad_helper.register_independent_variable(H, H_dofs);
3024 * ad_helper.register_independent_variable(C, C_dofs);
3025 *
3026 * // NOTE: We have to extract the sensitivities in the order we wish to
3027 * // introduce them. So this means we have to do it by logical order
3028 * // of the extractors that we've created.
3029 * const SymmetricTensor<2,dim,ADNumberType> C_AD =
3030 * ad_helper.get_sensitive_variables(C_dofs);
3031 * const Tensor<1,dim,ADNumberType> H_AD =
3032 * ad_helper.get_sensitive_variables(H_dofs);
3033 *
3034 * // Here we define the material stored energy function.
3035 * // This example is sufficiently complex to warrant the use of AD to,
3036 * // at the very least, verify an unassisted implementation.
3037 * const double mu_e = 10; // Shear modulus
3038 * const double lambda_e = 15; // Lam&eacute; parameter
3039 * const double mu_0 = 4*M_PI*1e-7; // Magnetic permeability constant
3040 * const double mu_r = 5; // Relative magnetic permeability
3041 *
3042 * const ADNumberType J = std::sqrt(determinant(C_AD));
3043 * const SymmetricTensor<2,dim,ADNumberType> C_inv_AD = invert(C_AD);
3044 * const ADNumberType psi =
3045 * 0.5*mu_e*(1.0+std::tanh((H_AD*H_AD)/100.0))*
3046 * (trace(C_AD) - dim - 2*std::log(J)) +
3047 * lambda_e*std::log(J)*std::log(J) -
3048 * 0.5*mu_0*mu_r*J*H_AD*C_inv_AD*H_AD;
3049 *
3050 * // Register the definition of the total stored energy
3051 * ad_helper.register_dependent_variable(psi);
3052 *
3053 * // Indicate that we have completed tracing the operations onto
3054 * // the tape.
3055 * ad_helper.stop_recording_operations(false); // write_tapes_to_file
3056 * }
3057 * else
3058 * {
3059 * // This is the "tape reuse" phase of the operations.
3060 * // Here we will leverage the already traced operations that reside
3061 * // on a tape, and simply re-evaluate the tape at a different point
3062 * // to get the function values and their derivatives.
3063 *
3064 * // Load the existing tape to be reused
3065 * ad_helper.activate_recorded_tape(tape_index);
3066 *
3067 * // Set the new values of the independent variables where the
3068 * // recorded dependent functions are to be evaluated (and
3069 * // differentiated around).
3070 * ad_helper.set_independent_variable(C, C_dofs);
3071 * ad_helper.set_independent_variable(H, H_dofs);
3072 * }
3073 *
3074 * // Play the tape and store the output function value, its gradient and
3075 * // linearization. These are expensive to compute, so we'll do this once
3076 * // and extract the desired values from these intermediate outputs.
3077 * Vector<double> Dpsi (ad_helper.n_dependent_variables());
3078 * FullMatrix<double> D2psi (ad_helper.n_dependent_variables(),
3079 * ad_helper.n_independent_variables());
3080 * const double psi = ad_helper.compute_value();
3081 * ad_helper.compute_gradient(Dpsi);
3082 * ad_helper.compute_hessian(D2psi);
3083 *
3084 * // Extract the desired components of the gradient vector and Hessian
3085 * // matrix. In this example, we use them to compute the Piola-Kirchhoff
3086 * // stress tensor and its associated tangent, defined by thermodynamic
3087 * // arguments as S = 2*dpsi/dC and HH = 2*dS/dC...
3088 * const SymmetricTensor<2,dim> S =
3089 * 2.0*ad_helper.extract_gradient_component(Dpsi,C_dofs);
3090 * const SymmetricTensor<4,dim> HH =
3091 * 4.0*ad_helper.extract_hessian_component(D2psi,C_dofs,C_dofs);
3092 *
3093 * // ... the magnetic induction and its associated tangent defined
3094 * // as B = -dpsi/dH and BB = dB/dH...
3095 * const Tensor<1,dim> B =
3096 * -ad_helper.extract_gradient_component(Dpsi,H_dofs);
3097 * const SymmetricTensor<2,dim> BB =
3098 * -symmetrize(ad_helper.extract_hessian_component(D2psi,H_dofs,H_dofs));
3099 *
3100 * // ... and finally the magnetoelastic coupling tangent, defined
3101 * // as PP = -dS/dH = -d/dH(2*dpsi/dC). Here the order of the extractor
3102 * // arguments is especially important, as it dictates the order in which
3103 * // the directional derivatives are taken.
3104 * const Tensor<3,dim,double> PP =
3105 * -2.0*ad_helper.extract_hessian_component(D2psi,C_dofs,H_dofs)
3106 * @endcode
3107 *
3108 * @warning ADOL-C does not support the standard threading models used by
3109 * deal.II, so this class should @b not be embedded within a multithreaded
3110 * function when using ADOL-C number types. It is, however, suitable for use
3111 * in both serial and MPI routines.
3112 */
3113 template <int dim,
3114 enum AD::NumberTypes ADNumberTypeCode,
3115 typename ScalarType = double>
3116 class ScalarFunction
3117 : public PointLevelFunctionsBase<dim, ADNumberTypeCode, ScalarType>
3118 {
3119 public:
3120 /**
3121 * Type definition for the floating point number type that is used in,
3122 * and results from, all computations.
3123 */
3124 using scalar_type =
3125 typename HelperBase<ADNumberTypeCode, ScalarType>::scalar_type;
3126
3127 /**
3128 * Type definition for the auto-differentiation number type that is used
3129 * in all computations.
3130 */
3131 using ad_type =
3132 typename HelperBase<ADNumberTypeCode, ScalarType>::ad_type;
3133
3134 /**
3135 * @name Constructor / destructor
3136 */
3137 /** @{ */
3138
3139 /**
3140 * The constructor for the class.
3141 *
3142 * @param[in] n_independent_variables The number of independent variables
3143 * that will be used in the definition of the functions that it is
3144 * desired to compute the sensitivities of. In the computation of
3145 * $\mathbf{f}(\mathbf{X})$, this will be the number of inputs
3146 * $\mathbf{X}$, i.e., the dimension of the domain space.
3147 */
3148 ScalarFunction(const unsigned int n_independent_variables);
3149
3150 /**
3151 * Destructor.
3152 */
3153 virtual ~ScalarFunction() = default;
3154
3155 /** @} */
3156
3157 /**
3158 * @name Dependent variables
3159 */
3160 /** @{ */
3161
3162 /**
3163 * Register the definition of the scalar field $\Psi(\mathbf{X})$.
3164 *
3165 * @param[in] func The recorded function that defines a dependent
3166 * variable.
3167 *
3168 * @note For this class that expects only one dependent variable, this
3169 * function must only be called once per tape.
3170 *
3171 * @note For taped AD numbers, this operation is only valid in recording mode.
3172 */
3173 void
3174 register_dependent_variable(const ad_type &func);
3175
3176 /**
3177 * Compute the value of the scalar field $\Psi(\mathbf{X})$ using the
3178 * tape as opposed to executing the source code.
3179 *
3180 * @return A scalar object with the value for the scalar field evaluated
3181 * at the point defined by the independent variable values.
3182 */
3183 scalar_type
3184 compute_value() const;
3185
3186 /**
3187 * Compute the gradient (first derivative) of the scalar field with
3188 * respect to all independent variables, i.e.
3189 * @f[
3190 * \frac{\partial\Psi(\mathbf{X})}{\partial\mathbf{X}}
3191 * @f]
3192 *
3193 * @param[out] gradient A Vector with the values for the scalar field
3194 * gradient (first derivatives) evaluated at the point defined by the
3195 * independent variable values. The output @p gradient vector has a length
3196 * corresponding to @p n_independent_variables.
3197 */
3198 void
3199 compute_gradient(Vector<scalar_type> &gradient) const;
3200
3201 /**
3202 * Compute the Hessian (second derivative) of the scalar field with
3203 * respect to all independent variables, i.e.
3204 * @f[
3205 * \frac{\partial^{2}\Psi(\mathbf{X})}{\partial\mathbf{X} \otimes
3206 * \partial\mathbf{X}}
3207 * @f]
3208 *
3209 * @param[out] hessian A FullMatrix with the values for the scalar field
3210 * Hessian (second derivatives) evaluated at the point defined by the
3211 * independent variable values. The output @p hessian matrix has
3212 * dimensions corresponding to
3213 * <code>n_independent_variables</code>$\times$<code>n_independent_variables</code>.
3214 */
3215 void
3216 compute_hessian(FullMatrix<scalar_type> &hessian) const;
3217
3218 /**
3219 * Extract the function gradient for a subset of independent variables
3220 * $\mathbf{A} \subset \mathbf{X}$, i.e.
3221 * @f[
3222 * \frac{\partial\Psi(\mathbf{X})}{\partial\mathbf{A}}
3223 * @f]
3224 *
3225 * @param[in] gradient The gradient of the scalar function with respect to
3226 * all independent variables, i.e., that returned by compute_gradient().
3227 * @param[in] extractor_row An extractor associated with the input field
3228 * variables. This effectively defines which components of the global set
3229 * of independent variables this field is associated with.
3230 *
3231 * @return A Tensor or SymmetricTensor with its rank and symmetries
3232 * determined by the @p extractor_row.
3233 * This corresponds to subsetting a whole set of rows of the
3234 * gradient vector, scaling those entries to take account of tensor
3235 * symmetries, and then reshaping the (sub-)vector so obtained into a
3236 * tensor, the final result.
3237 * For example, if
3238 * @p extractor_row is a FEValuesExtractors::Vector and
3239 * @p extractor_col is a FEValuesExtractors::Tensor,
3240 * then the returned object is a Tensor of rank 3, with its first
3241 * index associated with the field corresponding to the row extractor and
3242 * the second and third indices associated with the field corresponding to
3243 * the column extractor.
3244 * Similarly, if
3245 * @p extractor_row is a FEValuesExtractors::SymmetricTensor and
3246 * @p extractor_col is a FEValuesExtractors::SymmetricTensor,
3247 * then the returned object is a SymmetricTensor of rank 4, with its first
3248 * two indices associated with the field corresponding to the row
3249 * extractor and the last two indices associated with the field
3250 * corresponding to the column extractor.
3251 */
3252 template <typename ExtractorType_Row>
3253 static typename internal::
3254 ScalarFieldGradient<dim, scalar_type, ExtractorType_Row>::type
3255 extract_gradient_component(const Vector<scalar_type> &gradient,
3256 const ExtractorType_Row &extractor_row);
3257
3258 /**
3259 * Extract the function Hessian for a subset of independent variables
3260 * $\mathbf{A},\mathbf{B} \subset \mathbf{X}$, i.e.
3261 * @f[
3262 * \frac{}{\partial\mathbf{B}} \left[
3263 * \frac{\partial\Psi(\mathbf{X})}{\partial\mathbf{A}} \right] =
3264 * \frac{\partial^{2}\Psi(\mathbf{X})}{\partial\mathbf{B} \otimes
3265 * \partial\mathbf{A}}
3266 * @f]
3267 *
3268 * @param[in] hessian The Hessian of the scalar function with respect to
3269 * all independent variables, i.e., that returned by compute_hessian().
3270 * @param[in] extractor_row An extractor associated with the input field
3271 * variables for which the first index of the Hessian is extracted.
3272 * @param[in] extractor_col An extractor associated with the input field
3273 * variables for which the second index of the Hessian is extracted.
3274 *
3275 * @return A Tensor or SymmetricTensor with its rank and symmetries
3276 * determined by the @p extractor_row and @p extractor_col .
3277 * This corresponds to subsetting a whole set of rows and columns of the
3278 * Hessian matrix, scaling those entries to take account of tensor
3279 * symmetries, and then reshaping the (sub-)matrix so obtained into a
3280 * tensor, the final result.
3281 * For example, if
3282 * @p extractor_row is a FEValuesExtractors::Vector and
3283 * @p extractor_col is a FEValuesExtractors::Tensor,
3284 * then the returned object is a Tensor of rank 3, with its first
3285 * index associated with the field corresponding to the row extractor and
3286 * the second and third indices associated with the field corresponding to
3287 * the column extractor.
3288 * Similarly, if
3289 * @p extractor_row is a FEValuesExtractors::SymmetricTensor and
3290 * @p extractor_col is a FEValuesExtractors::SymmetricTensor,
3291 * then the returned object is a SymmetricTensor of rank 4, with its first
3292 * two indices associated with the field corresponding to the row
3293 * extractor and the last two indices associated with the field
3294 * corresponding to the column extractor.
3295 */
3296 template <typename ExtractorType_Row, typename ExtractorType_Col>
3297 static typename internal::ScalarFieldHessian<dim,
3298 scalar_type,
3299 ExtractorType_Row,
3300 ExtractorType_Col>::type
3301 extract_hessian_component(const FullMatrix<scalar_type> &hessian,
3302 const ExtractorType_Row &extractor_row,
3303 const ExtractorType_Col &extractor_col);
3304
3305 /**
3306 * Extract the function Hessian for a subset of independent variables
3307 * $\mathbf{A},\mathbf{B} \subset \mathbf{X}$, i.e.
3308 * @f[
3309 * \frac{}{\partial\mathbf{B}} \left[
3310 * \frac{\partial\Psi(\mathbf{X})}{\partial\mathbf{A}} \right]
3311 * @f]
3312 *
3313 * This function is a specialization of the above for rank-0 tensors
3314 * (scalars). This corresponds to extracting a single entry of the
3315 * Hessian matrix because both extractors imply selection of just a
3316 * single row or column of the matrix.
3317 */
3318 static Tensor<0, dim, scalar_type>
3319 extract_hessian_component(
3320 const FullMatrix<scalar_type> &hessian,
3321 const FEValuesExtractors::Scalar &extractor_row,
3322 const FEValuesExtractors::Scalar &extractor_col);
3323
3324 /**
3325 * Extract the function Hessian for a subset of independent variables
3326 * $\mathbf{A},\mathbf{B} \subset \mathbf{X}$, i.e.
3327 * @f[
3328 * \frac{}{\partial\mathbf{B}} \left[
3329 * \frac{\partial\Psi(\mathbf{X})}{\partial\mathbf{A}} \right]
3330 * @f]
3331 *
3332 * This function is a specialization of the above for rank-4 symmetric
3333 * tensors.
3334 */
3335 static SymmetricTensor<4, dim, scalar_type>
3336 extract_hessian_component(
3337 const FullMatrix<scalar_type> &hessian,
3338 const FEValuesExtractors::SymmetricTensor<2> &extractor_row,
3339 const FEValuesExtractors::SymmetricTensor<2> &extractor_col);
3340
3341 /** @} */
3342
3343 }; // class ScalarFunction
3344
3345
3346
3347 /**
3348 * A helper class that facilitates the evaluation of a vector of functions,
3349 * typically one that represents a collection of coupled, multi-dimensional
3350 * fields. This class would typically be used to compute the linearization
3351 * of a set of kinetic field variables defined at the quadrature point
3352 * level.
3353 *
3354 * An example of its usage in the case of linearizing the kinetic variables
3355 * derived from a multi-field constitutive law might be as follows:
3356 * @code
3357 * // Define some extractors that will help us set independent variables
3358 * // and later get the computed values related to the dependent
3359 * // variables. Each of these extractors is related to the gradient of a
3360 * // component of the solution field (in this case, displacement and
3361 * // magnetic scalar potential). Here "C" is the right Cauchy-Green
3362 * // tensor and "H" is the magnetic field.
3363 * const FEValuesExtractors::SymmetricTensor<2> C_dofs (0);
3364 * const FEValuesExtractors::Vector H_dofs
3365 * (dealii::SymmetricTensor<2,dim>::n_independent_components);
3366 * const unsigned int n_independent_variables =
3367 * SymmetricTensor<2,dim>::n_independent_components +
3368 * Tensor<1,dim>::n_independent_components;
3369 *
3370 * // Declare how many dependent variables we expect to compute.
3371 * // In this case, we will be computing a stress field (a symmetric
3372 * // rank-2 tensor) and the magnetic induction (a vector field).
3373 * // At the same time we define some additional extractors associated
3374 * // with these kinetic fields. In general, these need not be of the same
3375 * // layout as the independent variables.
3376 * const FEValuesExtractors::SymmetricTensor<2> S_dofs (0);
3377 * const FEValuesExtractors::Vector B_dofs
3378 * (dealii::SymmetricTensor<2,dim>::n_independent_components);
3379 * const unsigned int n_dependent_variables =
3380 * SymmetricTensor<2,dim>::n_independent_components +
3381 * Tensor<1,dim>::n_independent_components;
3382 *
3383 * // Define the helper that we will use in the AD computations for our
3384 * // scalar energy function. Note that we expect it to return values of
3385 * // type double.
3386 * VectorFunction<dim,double> ad_helper (n_independent_variables,
3387 * n_dependent_variables);
3388 * using ADNumberType = typename ADHelper::ad_type;
3389 *
3390 * // Compute the fields that provide the independent values.
3391 * // When the tape is being replayed, these should be set to something
3392 * // meaningful.
3393 * const Tensor<1,dim> H = ...;
3394 * const SymmetricTensor<2,dim> C = ...;
3395 *
3396 * // If using a taped AD number, then at this point we would initiate
3397 * // taping of the expression for the material stored energy function
3398 * // for this particular set of material parameters:
3399 *
3400 * // Select a tape number to record to
3401 * const typename Types<ADNumberType>::tape_index tape_index = ...;
3402 *
3403 * // Indicate that we are about to start tracing the operations for
3404 * // function evaluation on the tape. If this tape has already been
3405 * // used (i.e. the operations are already recorded) then we
3406 * // (optionally) load the tape and reuse this data.
3407 * const bool is_recording
3408 * = ad_helper.start_recording_operations(tape_index);
3409 *
3410 * // The steps that follow in the recording phase are required for
3411 * // tapeless methods as well.
3412 * if (is_recording == true)
3413 * {
3414 * // This is the "recording" phase of the operations.
3415 *
3416 * // First, we set the values for all fields.
3417 * // These could happily be set to anything, unless the function will
3418 * // be evaluated along a branch not otherwise traversed during later
3419 * // use. For this reason, in this example instead of using some dummy
3420 * // values, we'll actually map out the function at the same point
3421 * // around which we'll later linearize it.
3422 * ad_helper.register_independent_variable(H, H_dofs);
3423 * ad_helper.register_independent_variable(C, C_dofs);
3424 *
3425 * // NOTE: We have to extract the sensitivities in the order we wish to
3426 * // introduce them. So this means we have to do it by logical order
3427 * // of the extractors that we've created.
3428 * const SymmetricTensor<2,dim,ADNumberType> C_AD =
3429 * ad_helper.get_sensitive_variables(C_dofs);
3430 * const Tensor<1,dim,ADNumberType> H_AD =
3431 * ad_helper.get_sensitive_variables(H_dofs);
3432 *
3433 * // Here we define the stress and magnetic induction in terms
3434 * // of the independent values C_AD and H_AD.
3435 * const SymmetricTensor<2, dim, ad_type> S_AD = ...;
3436 * const Tensor<1, dim, ad_type> B_AD = ...;
3437 *
3438 * // Register the definition of the kinetic fields. The second
3439 * // argument to the function provides a non-overlapping ordering
3440 * // of the
3441 * ad_helper.register_dependent_variable(S_AD, S_dofs);
3442 * ad_helper.register_dependent_variable(B_AD, B_dofs);
3443 *
3444 * // Indicate that we have completed tracing the operations onto
3445 * // the tape.
3446 * ad_helper.stop_recording_operations(false); // write_tapes_to_file
3447 * }
3448 * else
3449 * {
3450 * // This is the "tape reuse" phase of the operations.
3451 * // Here we will leverage the already traced operations that reside
3452 * // on a tape, and simply re-evaluate the tape at a different point
3453 * // to get the function values and their derivatives.
3454 *
3455 * // Load the existing tape to be reused
3456 * ad_helper.activate_recorded_tape(tape_index);
3457 *
3458 * // Set the new values of the independent variables where the
3459 * // recorded dependent functions are to be evaluated (and
3460 * // differentiated around).
3461 * ad_helper.set_independent_variable(C, C_dofs);
3462 * ad_helper.set_independent_variable(H, H_dofs);
3463 * }
3464 *
3465 * // Play the tape and store the output function value, its gradient and
3466 * // linearization. These are expensive to compute, so we'll do this once
3467 * // and extract the desired values from these intermediate outputs.
3468 * Vector<double> values (ad_helper.n_dependent_variables());
3469 * FullMatrix<double> jacobian (ad_helper.n_dependent_variables(),
3470 * ad_helper.n_independent_variables());
3471 * ad_helper.compute_values(values);
3472 * ad_helper.compute_jacobian(jacobian);
3473 *
3474 * // Extract the desired components of the value vector and its Jacobian
3475 * // matrix. In this example, we use them to compute the Piola-Kirchhoff
3476 * // stress tensor S and its associated tangent, defined
3477 * // as HH = 2*dS/dC...
3478 * const SymmetricTensor<2,dim> S =
3479 * ad_helper.extract_value_component(values,S_dofs);
3480 * const SymmetricTensor<4,dim> HH =
3481 * 2.0*ad_helper.extract_jacobian_component(jacobian,S_dofs,C_dofs);
3482 *
3483 * // ... the magnetic induction B and its associated tangent defined
3484 * // as BB = dB/dH...
3485 * const Tensor<1,dim> B =
3486 * ad_helper.extract_value_component(values,H_dofs);
3487 * const SymmetricTensor<2,dim> BB =
3488 * symmetrize(ad_helper.extract_jacobian_component(jacobian,B_dofs,H_dofs));
3489 *
3490 * // ... and finally the magnetoelastic coupling tangent, defined
3491 * // as PP = -dS/dH. Here the order of the extractor arguments is
3492 * // especially important, as it dictates the field that is being
3493 * // differentiated, and which the directional derivatives are being
3494 * // computed.
3495 * const Tensor<3,dim,double> PP =
3496 * -ad_helper.extract_jacobian_component(jacobian,S_dofs,H_dofs)
3497 * @endcode
3498 *
3499 * @warning ADOL-C does not support the standard threading models used by
3500 * deal.II, so this class should @b not be embedded within a multithreaded
3501 * function when using ADOL-C number types. It is, however, suitable for use
3502 * in both serial and MPI routines.
3503 */
3504 template <int dim,
3505 enum AD::NumberTypes ADNumberTypeCode,
3506 typename ScalarType = double>
3507 class VectorFunction
3508 : public PointLevelFunctionsBase<dim, ADNumberTypeCode, ScalarType>
3509 {
3510 public:
3511 /**
3512 * Type definition for the floating point number type that is used in,
3513 * and results from, all computations.
3514 */
3515 using scalar_type =
3516 typename HelperBase<ADNumberTypeCode, ScalarType>::scalar_type;
3517
3518 /**
3519 * Type definition for the auto-differentiation number type that is used
3520 * in all computations.
3521 */
3522 using ad_type =
3523 typename HelperBase<ADNumberTypeCode, ScalarType>::ad_type;
3524
3525 /**
3526 * @name Constructor / destructor
3527 */
3528 /** @{ */
3529
3530 /**
3531 * The constructor for the class.
3532 *
3533 * @param[in] n_independent_variables The number of independent variables
3534 * that will be used in the definition of the functions that it is
3535 * desired to compute the sensitivities of. In the computation of
3536 * $\mathbf{f}(\mathbf{X})$, this will be the number of inputs
3537 * $\mathbf{X}$, i.e., the dimension of the domain space.
3538 * @param[in] n_dependent_variables The number of scalar functions to be
3539 * defined that will have a sensitivity to the given independent
3540 * variables. In the computation of $\mathbf{f}(\mathbf{X})$, this will
3541 * be the number of outputs $\mathbf{f}$, i.e., the dimension of the
3542 * image space.
3543 */
3544 VectorFunction(const unsigned int n_independent_variables,
3545 const unsigned int n_dependent_variables);
3546
3547 /**
3548 * Destructor.
3549 */
3550 virtual ~VectorFunction() = default;
3551
3552 /** @} */
3553
3554 /**
3555 * @name Dependent variables
3556 */
3557 /** @{ */
3558
3559 /**
3560 * Register the definition of the vector field
3561 * $\boldsymbol{\Psi}(\mathbf{X})$.
3562 *
3563 * @param[in] funcs A vector of recorded functions that defines the
3564 * dependent variables.
3565 *
3566 * @note For this class that expects only vector field of dependent
3567 * variables, this function must only be called once per tape.
3568 *
3569 * @note For taped AD numbers, this operation is only valid in recording mode.
3570 */
3571 void
3572 register_dependent_variables(const std::vector<ad_type> &funcs);
3573
3574 /**
3575 * Register the definition of the vector field
3576 * $\hat{\mathbf{g}}(\mathbf{X}) \subset \boldsymbol{\Psi}(\mathbf{X})$
3577 * that may represent a subset of the dependent variables.
3578 *
3579 * @param[in] funcs The recorded functions that define a set of dependent
3580 * variables.
3581 * @param[in] extractor An extractor associated with the input field
3582 * variables. This effectively defines which components of the global set
3583 * of dependent variables this field is associated with.
3584 *
3585 * @note The input extractor must correspond to the input @p ValueType.
3586 * So, for example, if a value is a rank-1 tensor
3587 * (i.e. of type Tensor<1,dim,scalar_type>), then the extractor must
3588 * be an FEValuesExtractors::Vector or FEValuesExtractors::Tensor<1>.
3589 *
3590 * @note For taped AD numbers, this operation is only valid in recording mode.
3591 */
3592 template <typename ValueType, typename ExtractorType>
3593 void
3594 register_dependent_variable(const ValueType &funcs,
3595 const ExtractorType &extractor);
3596
3597 /**
3598 * Compute the value of the vector field $\boldsymbol{\Psi}(\mathbf{X})$.
3599 *
3600 * @param[out] values A Vector object with the value for each component
3601 * of the vector field evaluated at the point defined by the independent
3602 * variable values. The output @p values vector has a length
3603 * corresponding to @p n_dependent_variables.
3604 */
3605 void
3606 compute_values(Vector<scalar_type> &values) const;
3607
3608 /**
3609 * Compute the Jacobian (first derivative) of the vector field with
3610 * respect to all independent variables, i.e.
3611 * @f[
3612 * \mathbf{J}(\boldsymbol{\Psi})
3613 * = \frac{\partial\boldsymbol{\Psi}(\mathbf{X})}{\partial\mathbf{X}}
3614 * @f]
3615 *
3616 * @param[out] jacobian A FullMatrix with the gradient of each component
3617 * of the vector field evaluated at the point defined by the independent
3618 * variable values. The output @p jacobian matrix has
3619 * dimensions corresponding to
3620 * <code>n_dependent_variables</code>$\times$<code>n_independent_variables</code>.
3621 */
3622 void
3623 compute_jacobian(FullMatrix<scalar_type> &jacobian) const;
3624
3625
3626 /**
3627 * Extract the set of functions' values for a subset of dependent
3628 * variables
3629 * $\mathbf{g} \subset \boldsymbol{\Psi}(\mathbf{X})$.
3630 *
3631 * @param[in] values A Vector object with the value for each component of
3632 * the vector field evaluated at the point defined by the independent
3633 * variable values.
3634 * @param[in] extractor_row An extractor associated with the input field
3635 * variables. This effectively defines which components of the global set
3636 * of dependent variables this field is associated with.
3637 */
3638 template <typename ExtractorType_Row>
3639 static typename internal::
3640 VectorFieldValue<dim, scalar_type, ExtractorType_Row>::type
3641 extract_value_component(const Vector<scalar_type> &values,
3642 const ExtractorType_Row &extractor_row);
3643
3644 /**
3645 * Extract the Jacobian of the subset of dependent functions
3646 * $\mathbf{g} \subset \boldsymbol{\Psi}(\mathbf{X})$
3647 * for a subset of independent variables
3648 * $\mathbf{A} \subset \mathbf{X}$, i.e.
3649 * @f[
3650 * \mathbf{J}(\mathbf{g})
3651 * = \frac{\partial\mathbf{g}(\mathbf{X})}{\partial\mathbf{A}}
3652 * @f]
3653 * The first index of the Jacobian matrix $\mathbf{J}(\mathbf{g})$
3654 * relates to the dependent variables, while the second index relates
3655 * to the independent variables.
3656 *
3657 * @param[in] jacobian The Jacobian of the vector function with respect to
3658 * all independent variables, i.e., that returned by compute_jacobian().
3659 * @param[in] extractor_row An extractor associated with the input field
3660 * variables for which the first index of the Jacobian is extracted.
3661 * This effectively defines the correspondence between components of the
3662 * global set of dependent variables and the field (representing a
3663 * subset of dependent functions) associated with the extractor.
3664 * @param[in] extractor_col An extractor associated with the input field
3665 * variables for which the second index of the Jacobian is extracted.
3666 * This effectively defines the correspondence between components of the
3667 * global set of independent variables and the field (representing a
3668 * subset of independent variables) associated with the extractor.
3669 *
3670 * @return A Tensor or SymmetricTensor with its rank and symmetries
3671 * determined by the @p extractor_row and @p extractor_col .
3672 * This corresponds to subsetting a whole set of rows and columns of the
3673 * Jacobian matrix, scaling those entries to take account of tensor
3674 * symmetries, and then reshaping the (sub-)matrix so obtained into a
3675 * tensor, the final result.
3676 * For example, if
3677 * @p extractor_row is a FEValuesExtractors::Vector and
3678 * @p extractor_col is a FEValuesExtractors::Tensor,
3679 * then the returned object is a Tensor of rank 3, with its first
3680 * index associated with the field corresponding to the row extractor and
3681 * the second and third indices associated with the field corresponding to
3682 * the column extractor.
3683 * Similarly, if
3684 * @p extractor_row is a FEValuesExtractors::SymmetricTensor and
3685 * @p extractor_col is a FEValuesExtractors::SymmetricTensor,
3686 * then the returned object is a SymmetricTensor of rank 4, with its first
3687 * two indices associated with the field corresponding to the row
3688 * extractor and the last two indices associated with the field
3689 * corresponding to the column extractor.
3690 */
3691 template <typename ExtractorType_Row, typename ExtractorType_Col>
3692 static typename internal::VectorFieldJacobian<dim,
3693 scalar_type,
3694 ExtractorType_Row,
3695 ExtractorType_Col>::type
3696 extract_jacobian_component(const FullMatrix<scalar_type> &jacobian,
3697 const ExtractorType_Row &extractor_row,
3698 const ExtractorType_Col &extractor_col);
3699
3700 /**
3701 * Extract the Jacobian of the subset of dependent functions
3702 * $\mathbf{g} \subset \boldsymbol{\Psi}(\mathbf{X})$
3703 * for a subset of independent variables
3704 * $\mathbf{A} \subset \mathbf{X}$, i.e.
3705 * @f[
3706 * \mathbf{J}(\mathbf{g})
3707 * = \frac{\partial\mathbf{g}(\mathbf{X})}{\partial\mathbf{A}}
3708 * @f]
3709 *
3710 * This function is a specialization of the above for rank-0 tensors
3711 * (scalars). This corresponds to extracting a single entry of the
3712 * Jacobian matrix because both extractors imply selection of just a
3713 * single row or column of the matrix.
3714 */
3715 static Tensor<0, dim, scalar_type>
3716 extract_jacobian_component(
3717 const FullMatrix<scalar_type> &jacobian,
3718 const FEValuesExtractors::Scalar &extractor_row,
3719 const FEValuesExtractors::Scalar &extractor_col);
3720
3721 /**
3722 * Extract the Jacobian of the subset of dependent functions
3723 * $\mathbf{g} \subset \boldsymbol{\Psi}(\mathbf{X})$
3724 * for a subset of independent variables
3725 * $\mathbf{A} \subset \mathbf{X}$, i.e.
3726 * @f[
3727 * \mathbf{J}(\mathbf{g})
3728 * = \frac{\partial\mathbf{g}(\mathbf{X})}{\partial\mathbf{A}}
3729 * @f]
3730 *
3731 * This function is a specialization of the above for rank-4 symmetric
3732 * tensors.
3733 */
3734 static SymmetricTensor<4, dim, scalar_type>
3735 extract_jacobian_component(
3736 const FullMatrix<scalar_type> &jacobian,
3737 const FEValuesExtractors::SymmetricTensor<2> &extractor_row,
3738 const FEValuesExtractors::SymmetricTensor<2> &extractor_col);
3739
3740 /** @} */
3741
3742 }; // class VectorFunction
3743
3744
3745 } // namespace AD
3746 } // namespace Differentiation
3747
3748
3749 /* ----------------- inline and template functions ----------------- */
3750
3751
3752 # ifndef DOXYGEN
3753
3754 namespace Differentiation
3755 {
3756 namespace AD
3757 {
3758 /* ----------------- CellLevelBase ----------------- */
3759
3760
3761
3762 template <enum AD::NumberTypes ADNumberTypeCode, typename ScalarType>
3763 template <typename VectorType>
3764 void
3765 CellLevelBase<ADNumberTypeCode, ScalarType>::register_dof_values(
3766 const VectorType &values,
3767 const std::vector<dealii::types::global_dof_index> &local_dof_indices)
3768 {
3769 // This is actually the same thing the set_dof_values() function,
3770 // in the sense that we simply populate our array of independent values
3771 // with a meaningful number. However, in this case we need to double check
3772 // that we're not registering these variables twice
3773 Assert(
3774 local_dof_indices.size() == this->n_independent_variables(),
3775 ExcMessage(
3776 "Degree of freedom index vector size does not match number of independent variables"));
3777 for (unsigned int i = 0; i < this->n_independent_variables(); ++i)
3778 {
3779 Assert(this->registered_independent_variable_values[i] == false,
3780 ExcMessage("Independent variables already registered."));
3781 }
3782 set_dof_values(values, local_dof_indices);
3783 }
3784
3785
3786
3787 template <enum AD::NumberTypes ADNumberTypeCode, typename ScalarType>
3788 template <typename VectorType>
3789 void
3790 CellLevelBase<ADNumberTypeCode, ScalarType>::set_dof_values(
3791 const VectorType &values,
3792 const std::vector<dealii::types::global_dof_index> &local_dof_indices)
3793 {
3794 Assert(local_dof_indices.size() == this->n_independent_variables(),
3795 ExcMessage(
3796 "Vector size does not match number of independent variables"));
3797 for (unsigned int i = 0; i < this->n_independent_variables(); ++i)
3798 HelperBase<ADNumberTypeCode, ScalarType>::set_sensitivity_value(
3799 i, values[local_dof_indices[i]]);
3800 }
3801
3802
3803
3804 /* ----------------- PointLevelFunctionsBase ----------------- */
3805
3806
3807
3808 template <int dim,
3809 enum AD::NumberTypes ADNumberTypeCode,
3810 typename ScalarType>
3811 template <typename ValueType, typename ExtractorType>
3812 void
3813 PointLevelFunctionsBase<dim, ADNumberTypeCode, ScalarType>::
3814 register_independent_variable(const ValueType &value,
3815 const ExtractorType &extractor)
3816 {
3817 // This is actually the same thing as the set_independent_variable
3818 // function, in the sense that we simply populate our array of independent
3819 // values with a meaningful number. However, in this case we need to
3820 // double check that we're not registering these variables twice
3821 if constexpr (running_in_debug_mode())
3822 {
3823 const std::vector<unsigned int> index_set(
3824 internal::extract_field_component_indices<dim>(extractor));
3825 for (const unsigned int index : index_set)
3826 {
3827 Assert(
3828 this->registered_independent_variable_values[index] == false,
3829 ExcMessage(
3830 "Overlapping indices for independent variables. "
3831 "One or more indices associated with the field that "
3832 "is being registered as an independent variable have "
3833 "already been associated with another field. This suggests "
3834 "that the component offsets used to construct their counterpart "
3835 "extractors are incompatible with one another. Make sure that "
3836 "the first component for each extractor properly takes into "
3837 "account the dimensionality of the preceding fields."));
3838 }
3839 }
3840 set_independent_variable(value, extractor);
3841 }
3842
3843
3844
3845 template <int dim,
3846 enum AD::NumberTypes ADNumberTypeCode,
3847 typename ScalarType>
3848 template <typename ValueType, typename ExtractorType>
3849 void
3850 PointLevelFunctionsBase<dim, ADNumberTypeCode, ScalarType>::
3851 set_independent_variable(const ValueType &value,
3852 const ExtractorType &extractor)
3853 {
3854 const std::vector<unsigned int> index_set(
3855 internal::extract_field_component_indices<dim>(extractor));
3856 for (unsigned int i = 0; i < index_set.size(); ++i)
3857 {
3858 set_sensitivity_value(
3859 index_set[i],
3860 internal::Extractor<dim, ExtractorType>::symmetric_component(i),
3861 internal::get_tensor_entry(value, i));
3862 }
3863 }
3864
3865
3866
3867 template <int dim,
3868 enum AD::NumberTypes ADNumberTypeCode,
3869 typename ScalarType>
3870 template <typename ExtractorType>
3871 typename internal::Extractor<dim, ExtractorType>::template tensor_type<
3872 typename HelperBase<ADNumberTypeCode, ScalarType>::ad_type>
3873 PointLevelFunctionsBase<dim, ADNumberTypeCode, ScalarType>::
3874 get_sensitive_variables(const ExtractorType &extractor) const
3875 {
3876 if (ADNumberTraits<ad_type>::is_taped == true)
3877 {
3878 Assert(this->active_tape_index() !=
3879 Numbers<ad_type>::invalid_tape_index,
3880 ExcMessage("Invalid tape index"));
3881 }
3882
3883 // If necessary, finalize the internally stored vector of
3884 // AD numbers that represents the independent variables
3885 this->finalize_sensitive_independent_variables();
3886 Assert(this->independent_variables.size() ==
3887 this->n_independent_variables(),
3888 ExcDimensionMismatch(this->independent_variables.size(),
3889 this->n_independent_variables()));
3890
3891 const std::vector<unsigned int> index_set(
3892 internal::extract_field_component_indices<dim>(extractor));
3893 typename internal::Extractor<dim,
3894 ExtractorType>::template tensor_type<ad_type>
3895 out;
3896
3897 for (unsigned int i = 0; i < index_set.size(); ++i)
3898 {
3899 const unsigned int index = index_set[i];
3900 Assert(index < this->n_independent_variables(), ExcInternalError());
3901 Assert(this->registered_independent_variable_values[index] == true,
3902 ExcInternalError());
3903 internal::get_tensor_entry(out, i) =
3904 this->independent_variables[index];
3905 }
3906
3907 return out;
3908 }
3909
3910
3911
3912 /* ----------------- ScalarFunction ----------------- */
3913
3914
3915
3916 template <int dim,
3917 enum AD::NumberTypes ADNumberTypeCode,
3918 typename ScalarType>
3919 template <typename ExtractorType_Row>
3920 typename internal::ScalarFieldGradient<
3921 dim,
3922 typename ScalarFunction<dim, ADNumberTypeCode, ScalarType>::scalar_type,
3923 ExtractorType_Row>::type
3924 ScalarFunction<dim, ADNumberTypeCode, ScalarType>::
3925 extract_gradient_component(const Vector<scalar_type> &gradient,
3926 const ExtractorType_Row &extractor_row)
3927 {
3928 // NOTE: The order of components must be consistently defined throughout
3929 // this class.
3930 typename internal::
3931 ScalarFieldGradient<dim, scalar_type, ExtractorType_Row>::type out;
3932
3933 // Get indexsets for the subblock from which we wish to extract the
3934 // gradient values
3935 const std::vector<unsigned int> row_index_set(
3936 internal::extract_field_component_indices<dim>(extractor_row));
3937 Assert(out.n_independent_components == row_index_set.size(),
3938 ExcMessage("Not all tensor components have been extracted!"));
3939 for (unsigned int r = 0; r < row_index_set.size(); ++r)
3940 internal::set_tensor_entry(out, r, gradient[row_index_set[r]]);
3941
3942 return out;
3943 }
3944
3945
3946
3947 template <int dim,
3948 enum AD::NumberTypes ADNumberTypeCode,
3949 typename ScalarType>
3950 template <typename ExtractorType_Row, typename ExtractorType_Col>
3951 typename internal::ScalarFieldHessian<
3952 dim,
3953 typename ScalarFunction<dim, ADNumberTypeCode, ScalarType>::scalar_type,
3954 ExtractorType_Row,
3955 ExtractorType_Col>::type
3956 ScalarFunction<dim, ADNumberTypeCode, ScalarType>::
3957 extract_hessian_component(const FullMatrix<scalar_type> &hessian,
3958 const ExtractorType_Row &extractor_row,
3959 const ExtractorType_Col &extractor_col)
3960 {
3961 using InternalHessian = internal::ScalarFieldHessian<dim,
3962 scalar_type,
3963 ExtractorType_Row,
3964 ExtractorType_Col>;
3965 using InternalExtractorRow = internal::Extractor<dim, ExtractorType_Row>;
3966 using InternalExtractorCol = internal::Extractor<dim, ExtractorType_Col>;
3967 using HessianType = typename InternalHessian::type;
3968
3969 // NOTE: The order of components must be consistently defined throughout
3970 // this class.
3971 HessianType out;
3972
3973 // Get indexsets for the subblocks from which we wish to extract the
3974 // Hessian values
3975 // NOTE: Here we have to do some clever accounting when the
3976 // one extractor is a symmetric Tensor and the other is not, e.g.
3977 // <SymmTensor,Vector>. In this scenario the return type is a
3978 // non-symmetric Tensor<3,dim> but we have to fetch information from a
3979 // SymmTensor row/column that has too few entries to fill the output
3980 // tensor. So we must duplicate the relevant entries in the row/column
3981 // indexset to fetch off-diagonal components that are otherwise
3982 // non-existent in a SymmTensor.
3983 const std::vector<unsigned int> row_index_set(
3984 internal::extract_field_component_indices<dim>(
3985 extractor_row, false /*ignore_symmetries*/));
3986 const std::vector<unsigned int> col_index_set(
3987 internal::extract_field_component_indices<dim>(
3988 extractor_col, false /*ignore_symmetries*/));
3989
3990 for (unsigned int index = 0;
3991 index < HessianType::n_independent_components;
3992 ++index)
3993 {
3994 const TableIndices<HessianType::rank> ti_out =
3995 HessianType::unrolled_to_component_indices(index);
3996 const unsigned int r =
3997 InternalExtractorRow::local_component(ti_out, 0);
3998 const unsigned int c =
3999 InternalExtractorCol::local_component(ti_out,
4000 InternalExtractorRow::rank);
4001
4002 internal::set_tensor_entry(
4003 out, index, hessian[row_index_set[r]][col_index_set[c]]);
4004 }
4005
4006 return out;
4007 }
4008
4009
4010
4011 /* ----------------- VectorFunction ----------------- */
4012
4013
4014
4015 template <int dim,
4016 enum AD::NumberTypes ADNumberTypeCode,
4017 typename ScalarType>
4018 template <typename ValueType, typename ExtractorType>
4019 void
4020 VectorFunction<dim, ADNumberTypeCode, ScalarType>::
4021 register_dependent_variable(const ValueType &funcs,
4022 const ExtractorType &extractor)
4023 {
4024 const std::vector<unsigned int> index_set(
4025 internal::extract_field_component_indices<dim>(extractor));
4026 for (unsigned int i = 0; i < index_set.size(); ++i)
4027 {
4028 Assert(this->registered_marked_dependent_variables[index_set[i]] ==
4029 false,
4030 ExcMessage("Overlapping indices for dependent variables."));
4031 HelperBase<ADNumberTypeCode, ScalarType>::register_dependent_variable(
4032 index_set[i], internal::get_tensor_entry(funcs, i));
4033 }
4034 }
4035
4036
4037
4038 template <int dim,
4039 enum AD::NumberTypes ADNumberTypeCode,
4040 typename ScalarType>
4041 template <typename ExtractorType_Row>
4042 typename internal::VectorFieldValue<
4043 dim,
4044 typename VectorFunction<dim, ADNumberTypeCode, ScalarType>::scalar_type,
4045 ExtractorType_Row>::type
4046 VectorFunction<dim, ADNumberTypeCode, ScalarType>::extract_value_component(
4047 const Vector<scalar_type> &values,
4048 const ExtractorType_Row &extractor_row)
4049 {
4050 // NOTE: The order of components must be consistently defined throughout
4051 // this class.
4052 typename internal::VectorFieldValue<dim, scalar_type, ExtractorType_Row>::
4053 type out;
4054
4055 // Get indexsets for the subblock from which we wish to extract the
4056 // gradient values
4057 const std::vector<unsigned int> row_index_set(
4058 internal::extract_field_component_indices<dim>(extractor_row));
4059 Assert(out.n_independent_components == row_index_set.size(),
4060 ExcMessage("Not all tensor components have been extracted!"));
4061 for (unsigned int r = 0; r < row_index_set.size(); ++r)
4062 internal::set_tensor_entry(out, r, values[row_index_set[r]]);
4063
4064 return out;
4065 }
4066
4067
4068
4069 template <int dim,
4070 enum AD::NumberTypes ADNumberTypeCode,
4071 typename ScalarType>
4072 template <typename ExtractorType_Row, typename ExtractorType_Col>
4073 typename internal::VectorFieldJacobian<
4074 dim,
4075 typename VectorFunction<dim, ADNumberTypeCode, ScalarType>::scalar_type,
4076 ExtractorType_Row,
4077 ExtractorType_Col>::type
4078 VectorFunction<dim, ADNumberTypeCode, ScalarType>::
4079 extract_jacobian_component(const FullMatrix<scalar_type> &jacobian,
4080 const ExtractorType_Row &extractor_row,
4081 const ExtractorType_Col &extractor_col)
4082 {
4083 using InternalJacobian = internal::VectorFieldJacobian<dim,
4084 scalar_type,
4085 ExtractorType_Row,
4086 ExtractorType_Col>;
4087 using InternalExtractorRow = internal::Extractor<dim, ExtractorType_Row>;
4088 using InternalExtractorCol = internal::Extractor<dim, ExtractorType_Col>;
4089 using JacobianType = typename InternalJacobian::type;
4090
4091 // NOTE: The order of components must be consistently defined throughout
4092 // this class.
4093 JacobianType out;
4094
4095 // Get indexsets for the subblocks from which we wish to extract the
4096 // Hessian values.
4097 // NOTE: Here we have to do some clever accounting when the
4098 // one extractor is a symmetric Tensor and the other is not, e.g.
4099 // <SymmTensor,Vector>. In this scenario the return type is a
4100 // non-symmetric Tensor<3,dim> but we have to fetch information from a
4101 // SymmTensor row/column that has too few entries to fill the output
4102 // tensor. So we must duplicate the relevant entries in the row/column
4103 // indexset to fetch off-diagonal components that are otherwise
4104 // non-existent in a SymmTensor.
4105 const std::vector<unsigned int> row_index_set(
4106 internal::extract_field_component_indices<dim>(
4107 extractor_row, false /*ignore_symmetries*/));
4108 const std::vector<unsigned int> col_index_set(
4109 internal::extract_field_component_indices<dim>(
4110 extractor_col, false /*ignore_symmetries*/));
4111
4112 for (unsigned int index = 0;
4113 index < JacobianType::n_independent_components;
4114 ++index)
4115 {
4116 const TableIndices<JacobianType::rank> ti_out =
4117 JacobianType::unrolled_to_component_indices(index);
4118 const unsigned int r =
4119 InternalExtractorRow::local_component(ti_out, 0);
4120 const unsigned int c =
4121 InternalExtractorCol::local_component(ti_out,
4122 InternalExtractorRow::rank);
4123
4124 internal::set_tensor_entry(
4125 out, index, jacobian[row_index_set[r]][col_index_set[c]]);
4126 }
4127
4128 return out;
4129 }
4130
4131
4132 } // namespace AD
4133 } // namespace Differentiation
4134
4135
4136 # endif // DOXYGEN
4137
4138
4139 DEAL_II_NAMESPACE_CLOSE
4140
4141 #else
4142
4143 // Make sure the scripts that create the C++20 module input files have
4144 // something to latch on if the preprocessor #ifdef above would
4145 // otherwise lead to an empty content of the file.
4146 DEAL_II_NAMESPACE_OPEN
4147 DEAL_II_NAMESPACE_CLOSE
4148
4149 #endif // defined(DEAL_II_WITH_ADOLC) || defined(DEAL_II_TRILINOS_WITH_SACADO)
4150
4151 #endif // dealii_differentiation_ad_ad_helpers_h