xref: /libCEED/interface/ceed-vector.c (revision aa67b84255fd38cedae0f40d1566f643808af2e9)
1 // Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and other CEED contributors.
2 // All Rights Reserved. See the top-level LICENSE and NOTICE files for details.
3 //
4 // SPDX-License-Identifier: BSD-2-Clause
5 //
6 // This file is part of CEED:  http://github.com/ceed
7 
8 #include <ceed-impl.h>
9 #include <ceed.h>
10 #include <ceed/backend.h>
11 #include <assert.h>
12 #include <math.h>
13 #include <stdbool.h>
14 #include <stdint.h>
15 #include <stdio.h>
16 
17 /// @file
18 /// Implementation of public CeedVector interfaces
19 
20 /// @cond DOXYGEN_SKIP
21 static struct CeedVector_private ceed_vector_active;
22 static struct CeedVector_private ceed_vector_none;
23 /// @endcond
24 
25 /// @addtogroup CeedVectorUser
26 /// @{
27 
28 /// Indicate that vector will be provided as an explicit argument to @ref CeedOperatorApply().
29 const CeedVector CEED_VECTOR_ACTIVE = &ceed_vector_active;
30 
31 /// Indicate that no vector is applicable (i.e., for @ref CEED_EVAL_WEIGHT).
32 const CeedVector CEED_VECTOR_NONE = &ceed_vector_none;
33 
34 /// @}
35 
36 /// ----------------------------------------------------------------------------
37 /// CeedVector Backend API
38 /// ----------------------------------------------------------------------------
39 /// @addtogroup CeedVectorBackend
40 /// @{
41 
42 /**
43   @brief Check for valid data in a `CeedVector`
44 
45   @param[in]  vec             `CeedVector` to check validity
46   @param[out] has_valid_array Variable to store validity
47 
48   @return An error code: 0 - success, otherwise - failure
49 
50   @ref Backend
51 **/
52 int CeedVectorHasValidArray(CeedVector vec, bool *has_valid_array) {
53   CeedCheck(vec->HasValidArray, vec->ceed, CEED_ERROR_UNSUPPORTED, "Backend does not support CeedVectorHasValidArray");
54   if (vec->length == 0) {
55     *has_valid_array = true;
56     return CEED_ERROR_SUCCESS;
57   }
58   CeedCall(vec->HasValidArray(vec, has_valid_array));
59   return CEED_ERROR_SUCCESS;
60 }
61 
62 /**
63   @brief Check for borrowed array of a specific @ref CeedMemType in a `CeedVector`
64 
65   @param[in]  vec                        `CeedVector` to check
66   @param[in]  mem_type                   Memory type to check
67   @param[out] has_borrowed_array_of_type Variable to store result
68 
69   @return An error code: 0 - success, otherwise - failure
70 
71   @ref Backend
72 **/
73 int CeedVectorHasBorrowedArrayOfType(CeedVector vec, CeedMemType mem_type, bool *has_borrowed_array_of_type) {
74   CeedCheck(vec->HasBorrowedArrayOfType, vec->ceed, CEED_ERROR_UNSUPPORTED, "Backend does not support CeedVectorHasBorrowedArrayOfType");
75   CeedCall(vec->HasBorrowedArrayOfType(vec, mem_type, has_borrowed_array_of_type));
76   return CEED_ERROR_SUCCESS;
77 }
78 
79 /**
80   @brief Get the state of a `CeedVector`
81 
82   @param[in]  vec    `CeedVector` to retrieve state
83   @param[out] state  Variable to store state
84 
85   @return An error code: 0 - success, otherwise - failure
86 
87   @ref Backend
88 **/
89 int CeedVectorGetState(CeedVector vec, uint64_t *state) {
90   *state = vec->state;
91   return CEED_ERROR_SUCCESS;
92 }
93 
94 /**
95   @brief Get the backend data of a `CeedVector`
96 
97   @param[in]  vec  `CeedVector` to retrieve state
98   @param[out] data Variable to store data
99 
100   @return An error code: 0 - success, otherwise - failure
101 
102   @ref Backend
103 **/
104 int CeedVectorGetData(CeedVector vec, void *data) {
105   *(void **)data = vec->data;
106   return CEED_ERROR_SUCCESS;
107 }
108 
109 /**
110   @brief Set the backend data of a `CeedVector`
111 
112   @param[in,out] vec  `CeedVector` to retrieve state
113   @param[in]     data Data to set
114 
115   @return An error code: 0 - success, otherwise - failure
116 
117   @ref Backend
118 **/
119 int CeedVectorSetData(CeedVector vec, void *data) {
120   vec->data = data;
121   return CEED_ERROR_SUCCESS;
122 }
123 
124 /**
125   @brief Increment the reference counter for a `CeedVector`
126 
127   @param[in,out] vec `CeedVector` to increment the reference counter
128 
129   @return An error code: 0 - success, otherwise - failure
130 
131   @ref Backend
132 **/
133 int CeedVectorReference(CeedVector vec) {
134   vec->ref_count++;
135   return CEED_ERROR_SUCCESS;
136 }
137 
138 /// @}
139 
140 /// ----------------------------------------------------------------------------
141 /// CeedVector Public API
142 /// ----------------------------------------------------------------------------
143 /// @addtogroup CeedVectorUser
144 /// @{
145 
146 /**
147   @brief Create a `CeedVector` of the specified length (does not allocate memory)
148 
149   @param[in]  ceed   `Ceed` object used to create the `CeedVector`
150   @param[in]  length Length of vector
151   @param[out] vec    Address of the variable where the newly created `CeedVector` will be stored
152 
153   @return An error code: 0 - success, otherwise - failure
154 
155   @ref User
156 **/
157 int CeedVectorCreate(Ceed ceed, CeedSize length, CeedVector *vec) {
158   if (!ceed->VectorCreate) {
159     Ceed delegate;
160 
161     CeedCall(CeedGetObjectDelegate(ceed, &delegate, "Vector"));
162     CeedCheck(delegate, ceed, CEED_ERROR_UNSUPPORTED, "Backend does not support VectorCreate");
163     CeedCall(CeedVectorCreate(delegate, length, vec));
164     return CEED_ERROR_SUCCESS;
165   }
166 
167   CeedCall(CeedCalloc(1, vec));
168   CeedCall(CeedReferenceCopy(ceed, &(*vec)->ceed));
169   (*vec)->ref_count = 1;
170   (*vec)->length    = length;
171   (*vec)->state     = 0;
172   CeedCall(ceed->VectorCreate(length, *vec));
173   return CEED_ERROR_SUCCESS;
174 }
175 
176 /**
177   @brief Copy the pointer to a `CeedVector`.
178 
179   Both pointers should be destroyed with @ref CeedVectorDestroy().
180 
181   Note: If the value of `*vec_copy` passed to this function is non-`NULL`, then it is assumed that `*vec_copy` is a pointer to a `CeedVector`.
182         This `CeedVector` will be destroyed if `*vec_copy` is the only reference to this `CeedVector`.
183 
184   @param[in]     vec      `CeedVector` to copy reference to
185   @param[in,out] vec_copy Variable to store copied reference
186 
187   @return An error code: 0 - success, otherwise - failure
188 
189   @ref User
190 **/
191 int CeedVectorReferenceCopy(CeedVector vec, CeedVector *vec_copy) {
192   if (vec != CEED_VECTOR_ACTIVE && vec != CEED_VECTOR_NONE) CeedCall(CeedVectorReference(vec));
193   CeedCall(CeedVectorDestroy(vec_copy));
194   *vec_copy = vec;
195   return CEED_ERROR_SUCCESS;
196 }
197 
198 /**
199   @brief Copy a `CeedVector` into a different `CeedVector`.
200 
201   Both pointers should be destroyed with @ref CeedVectorDestroy().
202 
203   Note: If `*vec_copy` is non-`NULL`, then it is assumed that `*vec_copy` is a pointer to a `CeedVector`.
204         This `CeedVector` will be destroyed if `*vec_copy` is the only reference to this `CeedVector`.
205 
206   @param[in]     vec      `CeedVector` to copy
207   @param[in,out] vec_copy Variable to store copied `CeedVector` to
208 
209   @return An error code: 0 - success, otherwise - failure
210 
211   @ref User
212 **/
213 int CeedVectorCopy(CeedVector vec, CeedVector vec_copy) {
214   Ceed        ceed;
215   CeedMemType mem_type, mem_type_copy;
216   CeedScalar *array;
217 
218   // Get the preferred memory type
219   CeedVectorGetCeed(vec, &ceed);
220   CeedGetPreferredMemType(ceed, &mem_type);
221 
222   // Get the preferred memory type
223   CeedVectorGetCeed(vec_copy, &ceed);
224   CeedGetPreferredMemType(ceed, &mem_type_copy);
225 
226   // Check that both have same memory type
227   if (mem_type != mem_type_copy) mem_type = CEED_MEM_HOST;
228 
229   // Copy the values from vec to vec_copy
230   CeedCall(CeedVectorGetArray(vec, mem_type, &array));
231   CeedCall(CeedVectorSetArray(vec_copy, mem_type, CEED_COPY_VALUES, array));
232 
233   CeedCall(CeedVectorRestoreArray(vec, &array));
234   return CEED_ERROR_SUCCESS;
235 }
236 
237 /**
238   @brief Set the array used by a `CeedVector`, freeing any previously allocated array if applicable.
239 
240   The backend may copy values to a different @ref CeedMemType, such as during @ref CeedOperatorApply().
241   See also @ref CeedVectorSyncArray() and @ref CeedVectorTakeArray().
242 
243   @param[in,out] vec       `CeedVector`
244   @param[in]     mem_type  Memory type of the array being passed
245   @param[in]     copy_mode Copy mode for the array
246   @param[in]     array     Array to be used, or `NULL` with @ref CEED_COPY_VALUES to have the library allocate
247 
248   @return An error code: 0 - success, otherwise - failure
249 
250   @ref User
251 **/
252 int CeedVectorSetArray(CeedVector vec, CeedMemType mem_type, CeedCopyMode copy_mode, CeedScalar *array) {
253   CeedCheck(vec->SetArray, vec->ceed, CEED_ERROR_UNSUPPORTED, "Backend does not support VectorSetArray");
254   CeedCheck(vec->state % 2 == 0, vec->ceed, CEED_ERROR_ACCESS, "Cannot grant CeedVector array access, the access lock is already in use");
255   CeedCheck(vec->num_readers == 0, vec->ceed, CEED_ERROR_ACCESS, "Cannot grant CeedVector array access, a process has read access");
256 
257   if (vec->length > 0) CeedCall(vec->SetArray(vec, mem_type, copy_mode, array));
258   vec->state += 2;
259   return CEED_ERROR_SUCCESS;
260 }
261 
262 /**
263   @brief Set the `CeedVector` to a constant value
264 
265   @param[in,out] vec   `CeedVector`
266   @param[in]     value Value to be used
267 
268   @return An error code: 0 - success, otherwise - failure
269 
270   @ref User
271 **/
272 int CeedVectorSetValue(CeedVector vec, CeedScalar value) {
273   CeedCheck(vec->state % 2 == 0, vec->ceed, CEED_ERROR_ACCESS, "Cannot grant CeedVector array access, the access lock is already in use");
274   CeedCheck(vec->num_readers == 0, vec->ceed, CEED_ERROR_ACCESS, "Cannot grant CeedVector array access, a process has read access");
275 
276   if (vec->SetValue) {
277     CeedCall(vec->SetValue(vec, value));
278   } else {
279     CeedScalar *array;
280     CeedCall(CeedVectorGetArrayWrite(vec, CEED_MEM_HOST, &array));
281     for (CeedSize i = 0; i < vec->length; i++) array[i] = value;
282     CeedCall(CeedVectorRestoreArray(vec, &array));
283   }
284   vec->state += 2;
285   return CEED_ERROR_SUCCESS;
286 }
287 
288 /**
289   @brief Sync the `CeedVector` to a specified `mem_type`.
290 
291   This function is used to force synchronization of arrays set with @ref CeedVectorSetArray().
292   If the requested `mem_type` is already synchronized, this function results in a no-op.
293 
294   @param[in,out] vec      `CeedVector`
295   @param[in]     mem_type @ref CeedMemType to be synced
296 
297   @return An error code: 0 - success, otherwise - failure
298 
299   @ref User
300 **/
301 int CeedVectorSyncArray(CeedVector vec, CeedMemType mem_type) {
302   CeedCheck(vec->state % 2 == 0, vec->ceed, CEED_ERROR_ACCESS, "Cannot sync CeedVector, the access lock is already in use");
303 
304   // Don't sync empty array
305   if (vec->length == 0) return CEED_ERROR_SUCCESS;
306 
307   if (vec->SyncArray) {
308     CeedCall(vec->SyncArray(vec, mem_type));
309   } else {
310     const CeedScalar *array;
311     CeedCall(CeedVectorGetArrayRead(vec, mem_type, &array));
312     CeedCall(CeedVectorRestoreArrayRead(vec, &array));
313   }
314   return CEED_ERROR_SUCCESS;
315 }
316 
317 /**
318   @brief Take ownership of the `CeedVector` array set by @ref CeedVectorSetArray() with @ref CEED_USE_POINTER and remove the array from the `CeedVector`.
319 
320   The caller is responsible for managing and freeing the array.
321   This function will error if @ref CeedVectorSetArray() was not previously called with @ref CEED_USE_POINTER for the corresponding mem_type.
322 
323   @param[in,out] vec      `CeedVector`
324   @param[in]     mem_type Memory type on which to take the array.
325                             If the backend uses a different memory type, this will perform a copy.
326   @param[out]    array    Array on memory type `mem_type`, or `NULL` if array pointer is not required
327 
328   @return An error code: 0 - success, otherwise - failure
329 
330   @ref User
331 **/
332 int CeedVectorTakeArray(CeedVector vec, CeedMemType mem_type, CeedScalar **array) {
333   CeedScalar *temp_array = NULL;
334 
335   CeedCheck(vec->state % 2 == 0, vec->ceed, CEED_ERROR_ACCESS, "Cannot take CeedVector array, the access lock is already in use");
336   CeedCheck(vec->num_readers == 0, vec->ceed, CEED_ERROR_ACCESS, "Cannot take CeedVector array, a process has read access");
337 
338   if (vec->length > 0) {
339     bool has_borrowed_array_of_type = true;
340     CeedCall(CeedVectorHasBorrowedArrayOfType(vec, mem_type, &has_borrowed_array_of_type));
341     CeedCheck(has_borrowed_array_of_type, vec->ceed, CEED_ERROR_BACKEND,
342               "CeedVector has no borrowed %s array, must set array with CeedVectorSetArray", CeedMemTypes[mem_type]);
343 
344     bool has_valid_array = true;
345     CeedCall(CeedVectorHasValidArray(vec, &has_valid_array));
346     CeedCheck(has_valid_array, vec->ceed, CEED_ERROR_BACKEND,
347               "CeedVector has no valid data to take, must set data with CeedVectorSetValue or CeedVectorSetArray");
348 
349     CeedCall(vec->TakeArray(vec, mem_type, &temp_array));
350   }
351   if (array) (*array) = temp_array;
352   return CEED_ERROR_SUCCESS;
353 }
354 
355 /**
356   @brief Get read/write access to a `CeedVector` via the specified memory type.
357 
358   Restore access with @ref CeedVectorRestoreArray().
359 
360   @param[in,out] vec      `CeedVector` to access
361   @param[in]     mem_type Memory type on which to access the array.
362                             If the backend uses a different memory type, this will perform a copy.
363   @param[out]    array    Array on memory type `mem_type`
364 
365   @note The @ref CeedVectorGetArray() and @ref CeedVectorRestoreArray() functions provide access to array pointers in the desired memory space.
366         Pairing get/restore allows the `CeedVector` to track access, thus knowing if norms or other operations may need to be recomputed.
367 
368   @return An error code: 0 - success, otherwise - failure
369 
370   @ref User
371 **/
372 int CeedVectorGetArray(CeedVector vec, CeedMemType mem_type, CeedScalar **array) {
373   CeedCheck(vec->GetArray, vec->ceed, CEED_ERROR_UNSUPPORTED, "Backend does not support GetArray");
374   CeedCheck(vec->state % 2 == 0, vec->ceed, CEED_ERROR_ACCESS, "Cannot grant CeedVector array access, the access lock is already in use");
375   CeedCheck(vec->num_readers == 0, vec->ceed, CEED_ERROR_ACCESS, "Cannot grant CeedVector array access, a process has read access");
376 
377   if (vec->length > 0) {
378     bool has_valid_array = true;
379 
380     CeedCall(CeedVectorHasValidArray(vec, &has_valid_array));
381     CeedCheck(has_valid_array, vec->ceed, CEED_ERROR_BACKEND,
382               "CeedVector has no valid data to read, must set data with CeedVectorSetValue or CeedVectorSetArray");
383 
384     CeedCall(vec->GetArray(vec, mem_type, array));
385   } else {
386     *array = NULL;
387   }
388   vec->state++;
389   return CEED_ERROR_SUCCESS;
390 }
391 
392 /**
393   @brief Get read-only access to a `CeedVector` via the specified memory type.
394 
395   Restore access with @ref CeedVectorRestoreArrayRead().
396 
397   @param[in]  vec      `CeedVector` to access
398   @param[in]  mem_type Memory type on which to access the array.
399                          If the backend uses a different memory type, this will perform a copy (possibly cached).
400   @param[out] array    Array on memory type `mem_type`
401 
402   @return An error code: 0 - success, otherwise - failure
403 
404   @ref User
405 **/
406 int CeedVectorGetArrayRead(CeedVector vec, CeedMemType mem_type, const CeedScalar **array) {
407   CeedCheck(vec->GetArrayRead, vec->ceed, CEED_ERROR_UNSUPPORTED, "Backend does not support GetArrayRead");
408   CeedCheck(vec->state % 2 == 0, vec->ceed, CEED_ERROR_ACCESS, "Cannot grant CeedVector read-only array access, the access lock is already in use");
409 
410   if (vec->length > 0) {
411     bool has_valid_array = true;
412 
413     CeedCall(CeedVectorHasValidArray(vec, &has_valid_array));
414     CeedCheck(has_valid_array, vec->ceed, CEED_ERROR_BACKEND,
415               "CeedVector has no valid data to read, must set data with CeedVectorSetValue or CeedVectorSetArray");
416 
417     CeedCall(vec->GetArrayRead(vec, mem_type, array));
418   } else {
419     *array = NULL;
420   }
421   vec->num_readers++;
422   return CEED_ERROR_SUCCESS;
423 }
424 
425 /**
426   @brief Get write access to a `CeedVector` via the specified memory type.
427 
428   Restore access with @ref CeedVectorRestoreArray().
429   All old values should be assumed to be invalid.
430 
431   @param[in,out] vec      `CeedVector` to access
432   @param[in]     mem_type Memory type on which to access the array.
433   @param[out]    array    Array on memory type `mem_type`
434 
435   @return An error code: 0 - success, otherwise - failure
436 
437   @ref User
438 **/
439 int CeedVectorGetArrayWrite(CeedVector vec, CeedMemType mem_type, CeedScalar **array) {
440   CeedCheck(vec->GetArrayWrite, vec->ceed, CEED_ERROR_UNSUPPORTED, "Backend does not support CeedVectorGetArrayWrite");
441   CeedCheck(vec->state % 2 == 0, vec->ceed, CEED_ERROR_ACCESS, "Cannot grant CeedVector array access, the access lock is already in use");
442   CeedCheck(vec->num_readers == 0, vec->ceed, CEED_ERROR_ACCESS, "Cannot grant CeedVector array access, a process has read access");
443 
444   if (vec->length > 0) {
445     CeedCall(vec->GetArrayWrite(vec, mem_type, array));
446   } else {
447     *array = NULL;
448   }
449   vec->state++;
450   return CEED_ERROR_SUCCESS;
451 }
452 
453 /**
454   @brief Restore an array obtained using @ref CeedVectorGetArray() or @ref CeedVectorGetArrayWrite()
455 
456   @param[in,out] vec   `CeedVector` to restore
457   @param[in,out] array Array of vector data
458 
459   @return An error code: 0 - success, otherwise - failure
460 
461   @ref User
462 **/
463 int CeedVectorRestoreArray(CeedVector vec, CeedScalar **array) {
464   CeedCheck(vec->state % 2 == 1, vec->ceed, CEED_ERROR_ACCESS, "Cannot restore CeedVector array access, access was not granted");
465   if (vec->length > 0 && vec->RestoreArray) CeedCall(vec->RestoreArray(vec));
466   *array = NULL;
467   vec->state++;
468   return CEED_ERROR_SUCCESS;
469 }
470 
471 /**
472   @brief Restore an array obtained using @ref CeedVectorGetArrayRead()
473 
474   @param[in]     vec   `CeedVector` to restore
475   @param[in,out] array Array of vector data
476 
477   @return An error code: 0 - success, otherwise - failure
478 
479   @ref User
480 **/
481 int CeedVectorRestoreArrayRead(CeedVector vec, const CeedScalar **array) {
482   CeedCheck(vec->num_readers > 0, vec->ceed, CEED_ERROR_ACCESS, "Cannot restore CeedVector array read access, access was not granted");
483 
484   vec->num_readers--;
485   if (vec->length > 0 && vec->num_readers == 0 && vec->RestoreArrayRead) CeedCall(vec->RestoreArrayRead(vec));
486   *array = NULL;
487   return CEED_ERROR_SUCCESS;
488 }
489 
490 /**
491   @brief Get the norm of a `CeedVector`.
492 
493   Note: This operation is local to the `CeedVector`.
494         This function will likely not provide the desired results for the norm of the libCEED portion of a parallel vector or a `CeedVector` with duplicated or hanging nodes.
495 
496   @param[in]  vec       `CeedVector` to retrieve maximum value
497   @param[in]  norm_type Norm type @ref CEED_NORM_1, @ref CEED_NORM_2, or @ref CEED_NORM_MAX
498   @param[out] norm      Variable to store norm value
499 
500   @return An error code: 0 - success, otherwise - failure
501 
502   @ref User
503 **/
504 int CeedVectorNorm(CeedVector vec, CeedNormType norm_type, CeedScalar *norm) {
505   bool has_valid_array = true;
506   CeedCall(CeedVectorHasValidArray(vec, &has_valid_array));
507   CeedCheck(has_valid_array, vec->ceed, CEED_ERROR_BACKEND,
508             "CeedVector has no valid data to compute norm, must set data with CeedVectorSetValue or CeedVectorSetArray");
509 
510   if (vec->length == 0) {
511     *norm = 0;
512     return CEED_ERROR_SUCCESS;
513   }
514 
515   // Backend impl for GPU, if added
516   if (vec->Norm) {
517     CeedCall(vec->Norm(vec, norm_type, norm));
518     return CEED_ERROR_SUCCESS;
519   }
520 
521   const CeedScalar *array;
522   CeedCall(CeedVectorGetArrayRead(vec, CEED_MEM_HOST, &array));
523   assert(array);
524 
525   *norm = 0.;
526   switch (norm_type) {
527     case CEED_NORM_1:
528       for (CeedSize i = 0; i < vec->length; i++) {
529         *norm += fabs(array[i]);
530       }
531       break;
532     case CEED_NORM_2:
533       for (CeedSize i = 0; i < vec->length; i++) {
534         *norm += fabs(array[i]) * fabs(array[i]);
535       }
536       break;
537     case CEED_NORM_MAX:
538       for (CeedSize i = 0; i < vec->length; i++) {
539         const CeedScalar abs_v_i = fabs(array[i]);
540         *norm                    = *norm > abs_v_i ? *norm : abs_v_i;
541       }
542   }
543   if (norm_type == CEED_NORM_2) *norm = sqrt(*norm);
544 
545   CeedCall(CeedVectorRestoreArrayRead(vec, &array));
546   return CEED_ERROR_SUCCESS;
547 }
548 
549 /**
550   @brief Compute `x = alpha x`
551 
552   @param[in,out] x     `CeedVector` for scaling
553   @param[in]     alpha scaling factor
554 
555   @return An error code: 0 - success, otherwise - failure
556 
557   @ref User
558 **/
559 int CeedVectorScale(CeedVector x, CeedScalar alpha) {
560   CeedScalar *x_array = NULL;
561   CeedSize    n_x;
562   bool        has_valid_array = true;
563 
564   CeedCall(CeedVectorHasValidArray(x, &has_valid_array));
565   CeedCheck(has_valid_array, x->ceed, CEED_ERROR_BACKEND,
566             "CeedVector has no valid data to scale, must set data with CeedVectorSetValue or CeedVectorSetArray");
567 
568   CeedCall(CeedVectorGetLength(x, &n_x));
569 
570   // Return early for empty vector
571   if (n_x == 0) return CEED_ERROR_SUCCESS;
572 
573   // Backend implementation
574   if (x->Scale) return x->Scale(x, alpha);
575 
576   // Default implementation
577   CeedCall(CeedVectorGetArray(x, CEED_MEM_HOST, &x_array));
578   assert(x_array);
579   for (CeedSize i = 0; i < n_x; i++) x_array[i] *= alpha;
580   CeedCall(CeedVectorRestoreArray(x, &x_array));
581   return CEED_ERROR_SUCCESS;
582 }
583 
584 /**
585   @brief Compute `y = alpha x + y`
586 
587   @param[in,out] y     target `CeedVector` for sum
588   @param[in]     alpha scaling factor
589   @param[in]     x     second `CeedVector`, must be different than ``y`
590 
591   @return An error code: 0 - success, otherwise - failure
592 
593   @ref User
594 **/
595 int CeedVectorAXPY(CeedVector y, CeedScalar alpha, CeedVector x) {
596   Ceed              ceed_parent_x, ceed_parent_y;
597   CeedScalar       *y_array = NULL;
598   CeedScalar const *x_array = NULL;
599   CeedSize          n_x, n_y;
600   bool              has_valid_array_x = true, has_valid_array_y = true;
601 
602   CeedCall(CeedVectorGetLength(y, &n_y));
603   CeedCall(CeedVectorGetLength(x, &n_x));
604   CeedCheck(n_x == n_y, y->ceed, CEED_ERROR_UNSUPPORTED, "Cannot add vector of different lengths");
605   CeedCheck(x != y, y->ceed, CEED_ERROR_UNSUPPORTED, "Cannot use same vector for x and y in CeedVectorAXPY");
606 
607   CeedCall(CeedVectorHasValidArray(x, &has_valid_array_x));
608   CeedCheck(has_valid_array_x, x->ceed, CEED_ERROR_BACKEND,
609             "CeedVector x has no valid data, must set data with CeedVectorSetValue or CeedVectorSetArray");
610   CeedCall(CeedVectorHasValidArray(y, &has_valid_array_y));
611   CeedCheck(has_valid_array_y, y->ceed, CEED_ERROR_BACKEND,
612             "CeedVector y has no valid data, must set data with CeedVectorSetValue or CeedVectorSetArray");
613 
614   CeedCall(CeedGetParent(x->ceed, &ceed_parent_x));
615   CeedCall(CeedGetParent(y->ceed, &ceed_parent_y));
616   CeedCheck(ceed_parent_x == ceed_parent_y, y->ceed, CEED_ERROR_INCOMPATIBLE, "Vectors x and y must be created by the same Ceed context");
617 
618   // Return early for empty vectors
619   if (n_y == 0) return CEED_ERROR_SUCCESS;
620 
621   // Backend implementation
622   if (y->AXPY) {
623     CeedCall(y->AXPY(y, alpha, x));
624     return CEED_ERROR_SUCCESS;
625   }
626 
627   // Default implementation
628   CeedCall(CeedVectorGetArray(y, CEED_MEM_HOST, &y_array));
629   CeedCall(CeedVectorGetArrayRead(x, CEED_MEM_HOST, &x_array));
630 
631   assert(x_array);
632   assert(y_array);
633 
634   for (CeedSize i = 0; i < n_y; i++) y_array[i] += alpha * x_array[i];
635 
636   CeedCall(CeedVectorRestoreArray(y, &y_array));
637   CeedCall(CeedVectorRestoreArrayRead(x, &x_array));
638   return CEED_ERROR_SUCCESS;
639 }
640 
641 /**
642   @brief Compute `y = alpha x + beta y`
643 
644   @param[in,out] y     target `CeedVector` for sum
645   @param[in]     alpha first scaling factor
646   @param[in]     beta  second scaling factor
647   @param[in]     x     second `CeedVector`, must be different than `y`
648 
649   @return An error code: 0 - success, otherwise - failure
650 
651   @ref User
652 **/
653 int CeedVectorAXPBY(CeedVector y, CeedScalar alpha, CeedScalar beta, CeedVector x) {
654   Ceed              ceed_parent_x, ceed_parent_y;
655   CeedScalar       *y_array = NULL;
656   CeedScalar const *x_array = NULL;
657   CeedSize          n_x, n_y;
658   bool              has_valid_array_x = true, has_valid_array_y = true;
659 
660   CeedCall(CeedVectorGetLength(y, &n_y));
661   CeedCall(CeedVectorGetLength(x, &n_x));
662   CeedCheck(n_x == n_y, y->ceed, CEED_ERROR_UNSUPPORTED, "Cannot add vector of different lengths");
663   CeedCheck(x != y, y->ceed, CEED_ERROR_UNSUPPORTED, "Cannot use same vector for x and y in CeedVectorAXPBY");
664 
665   CeedCall(CeedVectorHasValidArray(x, &has_valid_array_x));
666   CeedCheck(has_valid_array_x, x->ceed, CEED_ERROR_BACKEND,
667             "CeedVector x has no valid data, must set data with CeedVectorSetValue or CeedVectorSetArray");
668   CeedCall(CeedVectorHasValidArray(y, &has_valid_array_y));
669   CeedCheck(has_valid_array_y, y->ceed, CEED_ERROR_BACKEND,
670             "CeedVector y has no valid data, must set data with CeedVectorSetValue or CeedVectorSetArray");
671 
672   CeedCall(CeedGetParent(x->ceed, &ceed_parent_x));
673   CeedCall(CeedGetParent(y->ceed, &ceed_parent_y));
674   CeedCheck(ceed_parent_x == ceed_parent_y, y->ceed, CEED_ERROR_INCOMPATIBLE, "Vectors x and y must be created by the same Ceed context");
675 
676   // Return early for empty vectors
677   if (n_y == 0) return CEED_ERROR_SUCCESS;
678 
679   // Backend implementation
680   if (y->AXPBY) {
681     CeedCall(y->AXPBY(y, alpha, beta, x));
682     return CEED_ERROR_SUCCESS;
683   }
684 
685   // Default implementation
686   CeedCall(CeedVectorGetArray(y, CEED_MEM_HOST, &y_array));
687   CeedCall(CeedVectorGetArrayRead(x, CEED_MEM_HOST, &x_array));
688 
689   assert(x_array);
690   assert(y_array);
691 
692   for (CeedSize i = 0; i < n_y; i++) y_array[i] = alpha * x_array[i] + beta * y_array[i];
693 
694   CeedCall(CeedVectorRestoreArray(y, &y_array));
695   CeedCall(CeedVectorRestoreArrayRead(x, &x_array));
696   return CEED_ERROR_SUCCESS;
697 }
698 
699 /**
700   @brief Compute the pointwise multiplication \f$w = x .* y\f$.
701 
702   Any subset of `x`, `y`, and `w` may be the same `CeedVector`.
703 
704   @param[out] w target `CeedVector` for the product
705   @param[in]  x first `CeedVector` for product
706   @param[in]  y second `CeedVector` for the product
707 
708   @return An error code: 0 - success, otherwise - failure
709 
710   @ref User
711 **/
712 int CeedVectorPointwiseMult(CeedVector w, CeedVector x, CeedVector y) {
713   Ceed              ceed_parent_w, ceed_parent_x, ceed_parent_y;
714   CeedScalar       *w_array = NULL;
715   CeedScalar const *x_array = NULL, *y_array = NULL;
716   CeedSize          n_w, n_x, n_y;
717   bool              has_valid_array_x = true, has_valid_array_y = true;
718 
719   CeedCall(CeedVectorGetLength(w, &n_w));
720   CeedCall(CeedVectorGetLength(x, &n_x));
721   CeedCall(CeedVectorGetLength(y, &n_y));
722   CeedCheck(n_w == n_x && n_w == n_y, w->ceed, CEED_ERROR_UNSUPPORTED, "Cannot multiply vectors of different lengths");
723 
724   CeedCall(CeedGetParent(w->ceed, &ceed_parent_w));
725   CeedCall(CeedGetParent(x->ceed, &ceed_parent_x));
726   CeedCall(CeedGetParent(y->ceed, &ceed_parent_y));
727   CeedCheck(ceed_parent_w == ceed_parent_x && ceed_parent_w == ceed_parent_y, w->ceed, CEED_ERROR_INCOMPATIBLE,
728             "Vectors w, x, and y must be created by the same Ceed context");
729 
730   CeedCall(CeedVectorHasValidArray(x, &has_valid_array_x));
731   CeedCheck(has_valid_array_x, x->ceed, CEED_ERROR_BACKEND,
732             "CeedVector x has no valid data, must set data with CeedVectorSetValue or CeedVectorSetArray");
733   CeedCall(CeedVectorHasValidArray(y, &has_valid_array_y));
734   CeedCheck(has_valid_array_y, y->ceed, CEED_ERROR_BACKEND,
735             "CeedVector y has no valid data, must set data with CeedVectorSetValue or CeedVectorSetArray");
736 
737   // Return early for empty vectors
738   if (n_w == 0) return CEED_ERROR_SUCCESS;
739 
740   // Backend implementation
741   if (w->PointwiseMult) {
742     CeedCall(w->PointwiseMult(w, x, y));
743     return CEED_ERROR_SUCCESS;
744   }
745 
746   // Default implementation
747   if (x == w || y == w) {
748     CeedCall(CeedVectorGetArray(w, CEED_MEM_HOST, &w_array));
749   } else {
750     CeedCall(CeedVectorGetArrayWrite(w, CEED_MEM_HOST, &w_array));
751   }
752   if (x != w) {
753     CeedCall(CeedVectorGetArrayRead(x, CEED_MEM_HOST, &x_array));
754   } else {
755     x_array = w_array;
756   }
757   if (y != w && y != x) {
758     CeedCall(CeedVectorGetArrayRead(y, CEED_MEM_HOST, &y_array));
759   } else if (y == x) {
760     y_array = x_array;
761   } else if (y == w) {
762     y_array = w_array;
763   }
764 
765   assert(w_array);
766   assert(x_array);
767   assert(y_array);
768 
769   for (CeedSize i = 0; i < n_w; i++) w_array[i] = x_array[i] * y_array[i];
770 
771   if (y != w && y != x) CeedCall(CeedVectorRestoreArrayRead(y, &y_array));
772   if (x != w) CeedCall(CeedVectorRestoreArrayRead(x, &x_array));
773   CeedCall(CeedVectorRestoreArray(w, &w_array));
774   return CEED_ERROR_SUCCESS;
775 }
776 
777 /**
778   @brief Take the reciprocal of a `CeedVector`.
779 
780   @param[in,out] vec `CeedVector` to take reciprocal
781 
782   @return An error code: 0 - success, otherwise - failure
783 
784   @ref User
785 **/
786 int CeedVectorReciprocal(CeedVector vec) {
787   CeedSize    len;
788   CeedScalar *array;
789   bool        has_valid_array = true;
790 
791   CeedCall(CeedVectorHasValidArray(vec, &has_valid_array));
792   CeedCheck(has_valid_array, vec->ceed, CEED_ERROR_BACKEND,
793             "CeedVector has no valid data to compute reciprocal, must set data with CeedVectorSetValue or CeedVectorSetArray");
794 
795   // Check if vector data set
796   CeedCheck(vec->state > 0, vec->ceed, CEED_ERROR_INCOMPLETE, "CeedVector must have data set to take reciprocal");
797 
798   // Return early for empty vector
799   if (vec->length == 0) return CEED_ERROR_SUCCESS;
800 
801   // Backend impl for GPU, if added
802   if (vec->Reciprocal) {
803     CeedCall(vec->Reciprocal(vec));
804     return CEED_ERROR_SUCCESS;
805   }
806 
807   CeedCall(CeedVectorGetLength(vec, &len));
808   CeedCall(CeedVectorGetArray(vec, CEED_MEM_HOST, &array));
809   for (CeedSize i = 0; i < len; i++) {
810     if (fabs(array[i]) > CEED_EPSILON) array[i] = 1. / array[i];
811   }
812 
813   CeedCall(CeedVectorRestoreArray(vec, &array));
814   return CEED_ERROR_SUCCESS;
815 }
816 
817 /**
818   @brief View a `CeedVector`
819 
820   Note: It is safe to use any unsigned values for `start` or `stop` and any nonzero integer for `step`.
821         Any portion of the provided range that is outside the range of valid indices for the `CeedVector` will be ignored.
822 
823   @param[in] vec    `CeedVector` to view
824   @param[in] start  Index of first `CeedVector` entry to view
825   @param[in] stop   Index of last `CeedVector` entry to view
826   @param[in] step   Step between `CeedVector` entries to view
827   @param[in] fp_fmt Printing format
828   @param[in] stream Filestream to write to
829 
830   @return An error code: 0 - success, otherwise - failure
831 
832   @ref User
833 **/
834 int CeedVectorViewRange(CeedVector vec, CeedSize start, CeedSize stop, CeedInt step, const char *fp_fmt, FILE *stream) {
835   const CeedScalar *x;
836   char              fmt[1024];
837 
838   CeedCheck(step != 0, vec->ceed, CEED_ERROR_MINOR, "View range 'step' must be nonzero");
839 
840   fprintf(stream, "CeedVector length %ld\n", (long)vec->length);
841   if (start != 0 || stop != vec->length || step != 1) {
842     fprintf(stream, "  start: %ld\n  stop:  %ld\n  step:  %" CeedInt_FMT "\n", (long)start, (long)stop, step);
843   }
844   if (start > vec->length) start = vec->length;
845   if (stop > vec->length) stop = vec->length;
846 
847   snprintf(fmt, sizeof fmt, "  %s\n", fp_fmt ? fp_fmt : "%g");
848   CeedCall(CeedVectorGetArrayRead(vec, CEED_MEM_HOST, &x));
849   for (CeedSize i = start; step > 0 ? (i < stop) : (i > stop); i += step) fprintf(stream, fmt, x[i]);
850   CeedCall(CeedVectorRestoreArrayRead(vec, &x));
851   if (stop != vec->length) fprintf(stream, "  ...\n");
852   return CEED_ERROR_SUCCESS;
853 }
854 
855 /**
856   @brief View a `CeedVector`
857 
858   @param[in] vec    `CeedVector` to view
859   @param[in] fp_fmt Printing format
860   @param[in] stream Filestream to write to
861 
862   @return An error code: 0 - success, otherwise - failure
863 
864   @ref User
865 **/
866 int CeedVectorView(CeedVector vec, const char *fp_fmt, FILE *stream) {
867   CeedCall(CeedVectorViewRange(vec, 0, vec->length, 1, fp_fmt, stream));
868   return CEED_ERROR_SUCCESS;
869 }
870 
871 /**
872   @brief Get the `Ceed` associated with a `CeedVector`
873 
874   @param[in]  vec  `CeedVector` to retrieve state
875   @param[out] ceed Variable to store `Ceed`
876 
877   @return An error code: 0 - success, otherwise - failure
878 
879   @ref Advanced
880 **/
881 int CeedVectorGetCeed(CeedVector vec, Ceed *ceed) {
882   *ceed = vec->ceed;
883   return CEED_ERROR_SUCCESS;
884 }
885 
886 /**
887   @brief Get the length of a `CeedVector`
888 
889   @param[in]  vec    `CeedVector` to retrieve length
890   @param[out] length Variable to store length
891 
892   @return An error code: 0 - success, otherwise - failure
893 
894   @ref User
895 **/
896 int CeedVectorGetLength(CeedVector vec, CeedSize *length) {
897   *length = vec->length;
898   return CEED_ERROR_SUCCESS;
899 }
900 
901 /**
902   @brief Destroy a `CeedVector`
903 
904   @param[in,out] vec `CeedVector` to destroy
905 
906   @return An error code: 0 - success, otherwise - failure
907 
908   @ref User
909 **/
910 int CeedVectorDestroy(CeedVector *vec) {
911   if (!*vec || *vec == CEED_VECTOR_ACTIVE || *vec == CEED_VECTOR_NONE || --(*vec)->ref_count > 0) {
912     *vec = NULL;
913     return CEED_ERROR_SUCCESS;
914   }
915   CeedCheck((*vec)->state % 2 == 0, (*vec)->ceed, CEED_ERROR_ACCESS, "Cannot destroy CeedVector, the writable access lock is in use");
916   CeedCheck((*vec)->num_readers == 0, (*vec)->ceed, CEED_ERROR_ACCESS, "Cannot destroy CeedVector, a process has read access");
917 
918   if ((*vec)->Destroy) CeedCall((*vec)->Destroy(*vec));
919 
920   CeedCall(CeedDestroy(&(*vec)->ceed));
921   CeedCall(CeedFree(vec));
922   return CEED_ERROR_SUCCESS;
923 }
924 
925 /// @}
926