xref: /libCEED/rust/libceed-sys/c-src/interface/ceed-vector.c (revision 311fcb10b55cb48c3b64adc7e4913ca9b48b57b6)
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 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 HasValidArray");
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 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 HasBorrowedArrayOfType");
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 where the CeedVector will be created
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 `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 `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 memtype, 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 memtype.
290 
291   This function is used to force synchronization of arrays set with @ref CeedVectorSetArray().
292   If the requested memtype is already synchronized, this function results in a no-op.
293 
294   @param[in,out] vec      CeedVector
295   @param[in]     mem_type Memtype 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 CeedVectorGetArray* and CeedVectorRestoreArray* functions provide access to array pointers in the desired memory space.
366         Pairing get/restore allows the Vector 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. If the backend uses a different memory type, this will perform a copy (possibly
399 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 GetArrayWrite");
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
495 duplicated or hanging nodes.
496 
497   @param[in]  vec       CeedVector to retrieve maximum value
498   @param[in]  norm_type Norm type @ref CEED_NORM_1, @ref CEED_NORM_2, or @ref CEED_NORM_MAX
499   @param[out] norm      Variable to store norm value
500 
501   @return An error code: 0 - success, otherwise - failure
502 
503   @ref User
504 **/
505 int CeedVectorNorm(CeedVector vec, CeedNormType norm_type, CeedScalar *norm) {
506   bool has_valid_array = true;
507   CeedCall(CeedVectorHasValidArray(vec, &has_valid_array));
508   CeedCheck(has_valid_array, vec->ceed, CEED_ERROR_BACKEND,
509             "CeedVector has no valid data to compute norm, must set data with CeedVectorSetValue or CeedVectorSetArray");
510 
511   if (vec->length == 0) {
512     *norm = 0;
513     return CEED_ERROR_SUCCESS;
514   }
515 
516   // Backend impl for GPU, if added
517   if (vec->Norm) {
518     CeedCall(vec->Norm(vec, norm_type, norm));
519     return CEED_ERROR_SUCCESS;
520   }
521 
522   const CeedScalar *array;
523   CeedCall(CeedVectorGetArrayRead(vec, CEED_MEM_HOST, &array));
524   assert(array);
525 
526   *norm = 0.;
527   switch (norm_type) {
528     case CEED_NORM_1:
529       for (CeedSize i = 0; i < vec->length; i++) {
530         *norm += fabs(array[i]);
531       }
532       break;
533     case CEED_NORM_2:
534       for (CeedSize i = 0; i < vec->length; i++) {
535         *norm += fabs(array[i]) * fabs(array[i]);
536       }
537       break;
538     case CEED_NORM_MAX:
539       for (CeedSize i = 0; i < vec->length; i++) {
540         const CeedScalar abs_v_i = fabs(array[i]);
541         *norm                    = *norm > abs_v_i ? *norm : abs_v_i;
542       }
543   }
544   if (norm_type == CEED_NORM_2) *norm = sqrt(*norm);
545 
546   CeedCall(CeedVectorRestoreArrayRead(vec, &array));
547   return CEED_ERROR_SUCCESS;
548 }
549 
550 /**
551   @brief Compute x = alpha x
552 
553   @param[in,out] x     vector for scaling
554   @param[in]     alpha scaling factor
555 
556   @return An error code: 0 - success, otherwise - failure
557 
558   @ref User
559 **/
560 int CeedVectorScale(CeedVector x, CeedScalar alpha) {
561   CeedScalar *x_array = NULL;
562   CeedSize    n_x;
563   bool        has_valid_array = true;
564 
565   CeedCall(CeedVectorHasValidArray(x, &has_valid_array));
566   CeedCheck(has_valid_array, x->ceed, CEED_ERROR_BACKEND,
567             "CeedVector has no valid data to scale, must set data with CeedVectorSetValue or CeedVectorSetArray");
568 
569   CeedCall(CeedVectorGetLength(x, &n_x));
570 
571   // Return early for empty vector
572   if (n_x == 0) return CEED_ERROR_SUCCESS;
573 
574   // Backend implementation
575   if (x->Scale) return x->Scale(x, alpha);
576 
577   // Default implementation
578   CeedCall(CeedVectorGetArray(x, CEED_MEM_HOST, &x_array));
579   assert(x_array);
580   for (CeedSize i = 0; i < n_x; i++) x_array[i] *= alpha;
581   CeedCall(CeedVectorRestoreArray(x, &x_array));
582   return CEED_ERROR_SUCCESS;
583 }
584 
585 /**
586   @brief Compute y = alpha x + y
587 
588   @param[in,out] y     target vector for sum
589   @param[in]     alpha scaling factor
590   @param[in]     x     second vector, must be different than y
591 
592   @return An error code: 0 - success, otherwise - failure
593 
594   @ref User
595 **/
596 int CeedVectorAXPY(CeedVector y, CeedScalar alpha, CeedVector x) {
597   Ceed              ceed_parent_x, ceed_parent_y;
598   CeedScalar       *y_array = NULL;
599   CeedScalar const *x_array = NULL;
600   CeedSize          n_x, n_y;
601   bool              has_valid_array_x = true, has_valid_array_y = true;
602 
603   CeedCall(CeedVectorGetLength(y, &n_y));
604   CeedCall(CeedVectorGetLength(x, &n_x));
605   CeedCheck(n_x == n_y, y->ceed, CEED_ERROR_UNSUPPORTED, "Cannot add vector of different lengths");
606   CeedCheck(x != y, y->ceed, CEED_ERROR_UNSUPPORTED, "Cannot use same vector for x and y in CeedVectorAXPY");
607 
608   CeedCall(CeedVectorHasValidArray(x, &has_valid_array_x));
609   CeedCheck(has_valid_array_x, x->ceed, CEED_ERROR_BACKEND,
610             "CeedVector x has no valid data, must set data with CeedVectorSetValue or CeedVectorSetArray");
611   CeedCall(CeedVectorHasValidArray(y, &has_valid_array_y));
612   CeedCheck(has_valid_array_y, y->ceed, CEED_ERROR_BACKEND,
613             "CeedVector y has no valid data, must set data with CeedVectorSetValue or CeedVectorSetArray");
614 
615   CeedCall(CeedGetParent(x->ceed, &ceed_parent_x));
616   CeedCall(CeedGetParent(y->ceed, &ceed_parent_y));
617   CeedCheck(ceed_parent_x == ceed_parent_y, y->ceed, CEED_ERROR_INCOMPATIBLE, "Vectors x and y must be created by the same Ceed context");
618 
619   // Return early for empty vectors
620   if (n_y == 0) return CEED_ERROR_SUCCESS;
621 
622   // Backend implementation
623   if (y->AXPY) {
624     CeedCall(y->AXPY(y, alpha, x));
625     return CEED_ERROR_SUCCESS;
626   }
627 
628   // Default implementation
629   CeedCall(CeedVectorGetArray(y, CEED_MEM_HOST, &y_array));
630   CeedCall(CeedVectorGetArrayRead(x, CEED_MEM_HOST, &x_array));
631 
632   assert(x_array);
633   assert(y_array);
634 
635   for (CeedSize i = 0; i < n_y; i++) y_array[i] += alpha * x_array[i];
636 
637   CeedCall(CeedVectorRestoreArray(y, &y_array));
638   CeedCall(CeedVectorRestoreArrayRead(x, &x_array));
639   return CEED_ERROR_SUCCESS;
640 }
641 
642 /**
643   @brief Compute y = alpha x + beta y
644 
645   @param[in,out] y     target vector for sum
646   @param[in]     alpha first scaling factor
647   @param[in]     beta  second scaling factor
648   @param[in]     x     second vector, must be different than y
649 
650   @return An error code: 0 - success, otherwise - failure
651 
652   @ref User
653 **/
654 int CeedVectorAXPBY(CeedVector y, CeedScalar alpha, CeedScalar beta, CeedVector x) {
655   Ceed              ceed_parent_x, ceed_parent_y;
656   CeedScalar       *y_array = NULL;
657   CeedScalar const *x_array = NULL;
658   CeedSize          n_x, n_y;
659   bool              has_valid_array_x = true, has_valid_array_y = true;
660 
661   CeedCall(CeedVectorGetLength(y, &n_y));
662   CeedCall(CeedVectorGetLength(x, &n_x));
663   CeedCheck(n_x == n_y, y->ceed, CEED_ERROR_UNSUPPORTED, "Cannot add vector of different lengths");
664   CeedCheck(x != y, y->ceed, CEED_ERROR_UNSUPPORTED, "Cannot use same vector for x and y in CeedVectorAXPBY");
665 
666   CeedCall(CeedVectorHasValidArray(x, &has_valid_array_x));
667   CeedCheck(has_valid_array_x, x->ceed, CEED_ERROR_BACKEND,
668             "CeedVector x has no valid data, must set data with CeedVectorSetValue or CeedVectorSetArray");
669   CeedCall(CeedVectorHasValidArray(y, &has_valid_array_y));
670   CeedCheck(has_valid_array_y, y->ceed, CEED_ERROR_BACKEND,
671             "CeedVector y has no valid data, must set data with CeedVectorSetValue or CeedVectorSetArray");
672 
673   CeedCall(CeedGetParent(x->ceed, &ceed_parent_x));
674   CeedCall(CeedGetParent(y->ceed, &ceed_parent_y));
675   CeedCheck(ceed_parent_x == ceed_parent_y, y->ceed, CEED_ERROR_INCOMPATIBLE, "Vectors x and y must be created by the same Ceed context");
676 
677   // Return early for empty vectors
678   if (n_y == 0) return CEED_ERROR_SUCCESS;
679 
680   // Backend implementation
681   if (y->AXPBY) {
682     CeedCall(y->AXPBY(y, alpha, beta, x));
683     return CEED_ERROR_SUCCESS;
684   }
685 
686   // Default implementation
687   CeedCall(CeedVectorGetArray(y, CEED_MEM_HOST, &y_array));
688   CeedCall(CeedVectorGetArrayRead(x, CEED_MEM_HOST, &x_array));
689 
690   assert(x_array);
691   assert(y_array);
692 
693   for (CeedSize i = 0; i < n_y; i++) y_array[i] += alpha * x_array[i] + beta * y_array[i];
694 
695   CeedCall(CeedVectorRestoreArray(y, &y_array));
696   CeedCall(CeedVectorRestoreArrayRead(x, &x_array));
697   return CEED_ERROR_SUCCESS;
698 }
699 
700 /**
701   @brief Compute the pointwise multiplication w = x .* y.
702 
703   Any subset of x, y, and w may be the same vector.
704 
705   @param[out] w target vector for the product
706   @param[in]  x first vector for product
707   @param[in]  y second vector for the product
708 
709   @return An error code: 0 - success, otherwise - failure
710 
711   @ref User
712 **/
713 int CeedVectorPointwiseMult(CeedVector w, CeedVector x, CeedVector y) {
714   Ceed              ceed_parent_w, ceed_parent_x, ceed_parent_y;
715   CeedScalar       *w_array = NULL;
716   CeedScalar const *x_array = NULL, *y_array = NULL;
717   CeedSize          n_w, n_x, n_y;
718   bool              has_valid_array_x = true, has_valid_array_y = true;
719 
720   CeedCall(CeedVectorGetLength(w, &n_w));
721   CeedCall(CeedVectorGetLength(x, &n_x));
722   CeedCall(CeedVectorGetLength(y, &n_y));
723   CeedCheck(n_w == n_x && n_w == n_y, w->ceed, CEED_ERROR_UNSUPPORTED, "Cannot multiply vectors of different lengths");
724 
725   CeedCall(CeedGetParent(w->ceed, &ceed_parent_w));
726   CeedCall(CeedGetParent(x->ceed, &ceed_parent_x));
727   CeedCall(CeedGetParent(y->ceed, &ceed_parent_y));
728   CeedCheck(ceed_parent_w == ceed_parent_x && ceed_parent_w == ceed_parent_y, w->ceed, CEED_ERROR_INCOMPATIBLE,
729             "Vectors w, x, and y must be created by the same Ceed context");
730 
731   CeedCall(CeedVectorHasValidArray(x, &has_valid_array_x));
732   CeedCheck(has_valid_array_x, x->ceed, CEED_ERROR_BACKEND,
733             "CeedVector x has no valid data, must set data with CeedVectorSetValue or CeedVectorSetArray");
734   CeedCall(CeedVectorHasValidArray(y, &has_valid_array_y));
735   CeedCheck(has_valid_array_y, y->ceed, CEED_ERROR_BACKEND,
736             "CeedVector y has no valid data, must set data with CeedVectorSetValue or CeedVectorSetArray");
737 
738   // Return early for empty vectors
739   if (n_w == 0) return CEED_ERROR_SUCCESS;
740 
741   // Backend implementation
742   if (w->PointwiseMult) {
743     CeedCall(w->PointwiseMult(w, x, y));
744     return CEED_ERROR_SUCCESS;
745   }
746 
747   // Default implementation
748   if (x == w || y == w) {
749     CeedCall(CeedVectorGetArray(w, CEED_MEM_HOST, &w_array));
750   } else {
751     CeedCall(CeedVectorGetArrayWrite(w, CEED_MEM_HOST, &w_array));
752   }
753   if (x != w) {
754     CeedCall(CeedVectorGetArrayRead(x, CEED_MEM_HOST, &x_array));
755   } else {
756     x_array = w_array;
757   }
758   if (y != w && y != x) {
759     CeedCall(CeedVectorGetArrayRead(y, CEED_MEM_HOST, &y_array));
760   } else if (y == x) {
761     y_array = x_array;
762   } else if (y == w) {
763     y_array = w_array;
764   }
765 
766   assert(w_array);
767   assert(x_array);
768   assert(y_array);
769 
770   for (CeedSize i = 0; i < n_w; i++) w_array[i] = x_array[i] * y_array[i];
771 
772   if (y != w && y != x) CeedCall(CeedVectorRestoreArrayRead(y, &y_array));
773   if (x != w) CeedCall(CeedVectorRestoreArrayRead(x, &x_array));
774   CeedCall(CeedVectorRestoreArray(w, &w_array));
775   return CEED_ERROR_SUCCESS;
776 }
777 
778 /**
779   @brief Take the reciprocal of a CeedVector.
780 
781   @param[in,out] vec CeedVector to take reciprocal
782 
783   @return An error code: 0 - success, otherwise - failure
784 
785   @ref User
786 **/
787 int CeedVectorReciprocal(CeedVector vec) {
788   CeedSize    len;
789   CeedScalar *array;
790   bool        has_valid_array = true;
791 
792   CeedCall(CeedVectorHasValidArray(vec, &has_valid_array));
793   CeedCheck(has_valid_array, vec->ceed, CEED_ERROR_BACKEND,
794             "CeedVector has no valid data to compute reciprocal, must set data with CeedVectorSetValue or CeedVectorSetArray");
795 
796   // Check if vector data set
797   CeedCheck(vec->state > 0, vec->ceed, CEED_ERROR_INCOMPLETE, "CeedVector must have data set to take reciprocal");
798 
799   // Return early for empty vector
800   if (vec->length == 0) return CEED_ERROR_SUCCESS;
801 
802   // Backend impl for GPU, if added
803   if (vec->Reciprocal) {
804     CeedCall(vec->Reciprocal(vec));
805     return CEED_ERROR_SUCCESS;
806   }
807 
808   CeedCall(CeedVectorGetLength(vec, &len));
809   CeedCall(CeedVectorGetArray(vec, CEED_MEM_HOST, &array));
810   for (CeedSize i = 0; i < len; i++) {
811     if (fabs(array[i]) > CEED_EPSILON) array[i] = 1. / array[i];
812   }
813 
814   CeedCall(CeedVectorRestoreArray(vec, &array));
815   return CEED_ERROR_SUCCESS;
816 }
817 
818 /**
819   @brief View a CeedVector
820 
821   Note: It is safe to use any unsigned values for `start` or `stop` and any nonzero integer for `step`.
822         Any portion of the provided range that is outside the range of valid indices for the CeedVector will be ignored.
823 
824   @param[in] vec    CeedVector to view
825   @param[in] start  Index of first CeedVector entry to view
826   @param[in] stop   Index of last CeedVector entry to view
827   @param[in] step   Step between CeedVector entries to view
828   @param[in] fp_fmt Printing format
829   @param[in] stream Filestream to write to
830 
831   @return An error code: 0 - success, otherwise - failure
832 
833   @ref User
834 **/
835 int CeedVectorViewRange(CeedVector vec, CeedSize start, CeedSize stop, CeedInt step, const char *fp_fmt, FILE *stream) {
836   const CeedScalar *x;
837   char              fmt[1024];
838 
839   CeedCheck(step != 0, vec->ceed, CEED_ERROR_MINOR, "View range 'step' must be nonzero");
840 
841   fprintf(stream, "CeedVector length %ld\n", (long)vec->length);
842   if (start != 0 || stop != vec->length || step != 1) {
843     fprintf(stream, "  start: %ld\n  stop:  %ld\n  step:  %" CeedInt_FMT "\n", (long)start, (long)stop, step);
844   }
845   if (start > vec->length) start = vec->length;
846   if (stop > vec->length) stop = vec->length;
847 
848   snprintf(fmt, sizeof fmt, "  %s\n", fp_fmt ? fp_fmt : "%g");
849   CeedCall(CeedVectorGetArrayRead(vec, CEED_MEM_HOST, &x));
850   for (CeedSize i = start; step > 0 ? (i < stop) : (i > stop); i += step) fprintf(stream, fmt, x[i]);
851   CeedCall(CeedVectorRestoreArrayRead(vec, &x));
852   if (stop != vec->length) fprintf(stream, "  ...\n");
853   return CEED_ERROR_SUCCESS;
854 }
855 
856 /**
857   @brief View a CeedVector
858 
859   @param[in] vec    CeedVector to view
860   @param[in] fp_fmt Printing format
861   @param[in] stream Filestream to write to
862 
863   @return An error code: 0 - success, otherwise - failure
864 
865   @ref User
866 **/
867 int CeedVectorView(CeedVector vec, const char *fp_fmt, FILE *stream) {
868   CeedCall(CeedVectorViewRange(vec, 0, vec->length, 1, fp_fmt, stream));
869   return CEED_ERROR_SUCCESS;
870 }
871 
872 /**
873   @brief Get the Ceed associated with a CeedVector
874 
875   @param[in]  vec  CeedVector to retrieve state
876   @param[out] ceed Variable to store ceed
877 
878   @return An error code: 0 - success, otherwise - failure
879 
880   @ref Advanced
881 **/
882 int CeedVectorGetCeed(CeedVector vec, Ceed *ceed) {
883   *ceed = vec->ceed;
884   return CEED_ERROR_SUCCESS;
885 }
886 
887 /**
888   @brief Get the length of a CeedVector
889 
890   @param[in]  vec    CeedVector to retrieve length
891   @param[out] length Variable to store length
892 
893   @return An error code: 0 - success, otherwise - failure
894 
895   @ref User
896 **/
897 int CeedVectorGetLength(CeedVector vec, CeedSize *length) {
898   *length = vec->length;
899   return CEED_ERROR_SUCCESS;
900 }
901 
902 /**
903   @brief Destroy a CeedVector
904 
905   @param[in,out] vec CeedVector to destroy
906 
907   @return An error code: 0 - success, otherwise - failure
908 
909   @ref User
910 **/
911 int CeedVectorDestroy(CeedVector *vec) {
912   if (!*vec || *vec == CEED_VECTOR_ACTIVE || *vec == CEED_VECTOR_NONE || --(*vec)->ref_count > 0) {
913     *vec = NULL;
914     return CEED_ERROR_SUCCESS;
915   }
916   CeedCheck((*vec)->state % 2 == 0, (*vec)->ceed, CEED_ERROR_ACCESS, "Cannot destroy CeedVector, the writable access lock is in use");
917   CeedCheck((*vec)->num_readers == 0, (*vec)->ceed, CEED_ERROR_ACCESS, "Cannot destroy CeedVector, a process has read access");
918 
919   if ((*vec)->Destroy) CeedCall((*vec)->Destroy(*vec));
920 
921   CeedCall(CeedDestroy(&(*vec)->ceed));
922   CeedCall(CeedFree(vec));
923   return CEED_ERROR_SUCCESS;
924 }
925 
926 /// @}
927