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